From 05756094ac7918c599c15e360f45de8fc232c31d Mon Sep 17 00:00:00 2001 From: SoraKatadzuma Date: Mon, 26 Oct 2026 10:14:11 -0500 Subject: [PATCH] Initial Commit --- .editorconfig | 9 + .gitignore | 1 + CHANGELOG.md | 236 ++ LICENSE | 18 + README.md | 1207 +++++++ analyzer/README.md | 143 + analyzer/builtin.sakura | 98 + analyzer/checker.sakura | 464 +++ analyzer/checker/access.sakura | 918 +++++ analyzer/checker/attributes.sakura | 292 ++ analyzer/checker/bodies.sakura | 363 ++ analyzer/checker/calls.sakura | 1833 ++++++++++ analyzer/checker/composite.sakura | 587 ++++ analyzer/checker/constants.sakura | 341 ++ analyzer/checker/convert.sakura | 829 +++++ analyzer/checker/declare.sakura | 627 ++++ analyzer/checker/decls.sakura | 579 +++ analyzer/checker/describe.sakura | 198 ++ analyzer/checker/evaluator.sakura | 594 ++++ analyzer/checker/expressions.sakura | 847 +++++ analyzer/checker/generics.sakura | 738 ++++ analyzer/checker/incremental.sakura | 671 ++++ analyzer/checker/knowns.sakura | 1372 ++++++++ analyzer/checker/lifetimes.sakura | 491 +++ analyzer/checker/link.sakura | 297 ++ analyzer/checker/lookup.sakura | 453 +++ analyzer/checker/nodes.sakura | 186 + analyzer/checker/notes.sakura | 242 ++ analyzer/checker/operators.sakura | 1491 ++++++++ analyzer/checker/ownership.sakura | 184 + analyzer/checker/patterns.sakura | 509 +++ analyzer/checker/reflection.sakura | 523 +++ analyzer/checker/resolve.sakura | 1353 +++++++ analyzer/checker/results.sakura | 376 ++ analyzer/checker/scopes.sakura | 67 + analyzer/checker/statements.sakura | 1445 ++++++++ analyzer/checker/traits.sakura | 895 +++++ analyzer/checker/types.sakura | 581 +++ analyzer/column.sakura | 127 + analyzer/errors.sakura | 56 + analyzer/idindex.sakura | 126 + analyzer/keymap.sakura | 226 ++ analyzer/lexer.sakura | 668 ++++ analyzer/libraries.sakura | 756 ++++ analyzer/lines.sakura | 44 + analyzer/names.sakura | 412 +++ analyzer/node.sakura | 136 + analyzer/note.sakura | 113 + analyzer/parser.sakura | 125 + analyzer/parser/attribute.sakura | 44 + analyzer/parser/declarations.sakura | 889 +++++ analyzer/parser/expressions.sakura | 347 ++ analyzer/parser/fields.sakura | 63 + analyzer/parser/helpers.sakura | 633 ++++ analyzer/parser/primary.sakura | 200 ++ analyzer/parser/reparse.sakura | 229 ++ analyzer/parser/statements.sakura | 352 ++ analyzer/parser/tables.sakura | 119 + analyzer/parser/types.sakura | 382 ++ analyzer/parser/when.sakura | 133 + analyzer/printer.sakura | 161 + analyzer/queries/calling.sakura | 270 ++ analyzer/queries/completion.sakura | 1223 +++++++ analyzer/queries/highlights.sakura | 81 + analyzer/queries/hover.sakura | 226 ++ analyzer/queries/names.sakura | 540 +++ analyzer/queries/programs.sakura | 80 + analyzer/queries/signatures.sakura | 829 +++++ analyzer/queries/symbols.sakura | 628 ++++ analyzer/reading.sakura | 170 + analyzer/shapes.sakura | 455 +++ analyzer/source.sakura | 227 ++ analyzer/syntax.sakura | 365 ++ analyzer/token.sakura | 274 ++ analyzer/walker.sakura | 86 + blossomfile | 173 + compiler/README.md | 136 + compiler/atomics.sakura | 71 + compiler/bytecode.sakura | 1592 +++++++++ compiler/compiler.sakura | 475 +++ compiler/constants.sakura | 358 ++ compiler/conventions.sakura | 31 + compiler/dispatch.sakura | 427 +++ compiler/emitter.sakura | 699 ++++ compiler/emitter/bodies.sakura | 253 ++ compiler/emitter/builtins.sakura | 310 ++ compiler/emitter/calls.sakura | 702 ++++ compiler/emitter/closures.sakura | 303 ++ compiler/emitter/composite.sakura | 553 +++ compiler/emitter/formatting.sakura | 238 ++ compiler/emitter/intrinsics.sakura | 546 +++ compiler/emitter/loops.sakura | 410 +++ compiler/emitter/match.sakura | 238 ++ compiler/emitter/operators.sakura | 1163 ++++++ compiler/emitter/ownership.sakura | 146 + compiler/emitter/places.sakura | 617 ++++ compiler/emitter/reflection.sakura | 253 ++ compiler/emitter/statements.sakura | 653 ++++ compiler/emitter/storage.sakura | 246 ++ compiler/emitter/values.sakura | 487 +++ compiler/escapes.sakura | 1949 +++++++++++ compiler/flows.sakura | 357 ++ compiler/globals.sakura | 158 + compiler/intermediate/builder.sakura | 581 +++ compiler/intermediate/cells.sakura | 205 ++ compiler/intermediate/code.sakura | 677 ++++ compiler/intermediate/compact.sakura | 250 ++ compiler/intermediate/ids.sakura | 160 + compiler/intermediate/liveness.sakura | 133 + compiler/intermediate/moves.sakura | 82 + compiler/intermediate/numbers.sakura | 152 + compiler/intermediate/orders.sakura | 123 + compiler/intermediate/printer.sakura | 322 ++ compiler/intermediate/verifier.sakura | 383 ++ compiler/intermediate/walks.sakura | 246 ++ compiler/keeps.sakura | 410 +++ compiler/lanes.sakura | 381 ++ compiler/layouts.sakura | 503 +++ compiler/nodes.sakura | 64 + compiler/optimizer/alias.sakura | 393 +++ compiler/optimizer/control.sakura | 1224 +++++++ compiler/optimizer/dead.sakura | 224 ++ compiler/optimizer/edit.sakura | 592 ++++ compiler/optimizer/inline.sakura | 1136 ++++++ compiler/optimizer/loops.sakura | 985 ++++++ compiler/optimizer/memory.sakura | 500 +++ compiler/optimizer/merge.sakura | 186 + compiler/optimizer/numbering.sakura | 689 ++++ compiler/optimizer/optimizer.sakura | 575 +++ compiler/optimizer/promote.sakura | 887 +++++ compiler/optimizer/simplify.sakura | 925 +++++ compiler/optimizer/sink.sakura | 271 ++ compiler/optimizer/unused.sakura | 79 + compiler/optimizer/versions.sakura | 158 + compiler/program.sakura | 199 ++ compiler/report.sakura | 113 + compiler/scratch.sakura | 145 + compiler/tracking.sakura | 211 ++ compiler/workers.sakura | 145 + core/allocators/allocator.sakura | 170 + core/atomic.sakura | 291 ++ core/attribute.sakura | 104 + core/bits.sakura | 74 + core/bool.ext.sakura | 14 + core/containers/decimal.sakura | 349 ++ core/containers/pair.sakura | 18 + core/containers/slice.sakura | 249 ++ core/containers/sort.sakura | 199 ++ core/containers/span.sakura | 373 ++ core/containers/string.sakura | 416 +++ core/containers/strview.sakura | 301 ++ core/containers/vector.sakura | 688 ++++ core/fault.sakura | 70 + core/ffi.sakura | 19 + core/flags.sakura | 73 + core/functions/function.sakura | 163 + core/intrinsics.sakura | 46 + core/iterators/adapters.sakura | 547 +++ core/iterators/range.sakura | 165 + core/iterators/text.sakura | 201 ++ core/mem.sakura | 422 +++ core/owners/box.sakura | 87 + core/reflect.sakura | 120 + core/results/maybe.sakura | 286 ++ core/results/result.sakura | 357 ++ core/simd.sakura | 1251 +++++++ core/site.sakura | 57 + core/swar.sakura | 287 ++ core/target.sakura | 25 + core/traits/addable.sakura | 25 + core/traits/additive.sakura | 22 + core/traits/closeable.sakura | 19 + core/traits/copyable.sakura | 48 + core/traits/divisible.sakura | 25 + core/traits/equatable.sakura | 37 + core/traits/extendable.sakura | 20 + core/traits/hashable.sakura | 93 + core/traits/indexable.sakura | 53 + core/traits/integer.sakura | 67 + core/traits/invokable.sakura | 45 + core/traits/iterable.sakura | 41 + core/traits/iterator.sakura | 529 +++ core/traits/modular.sakura | 24 + core/traits/moveable.sakura | 76 + core/traits/multipliable.sakura | 25 + core/traits/multiplicative.sakura | 18 + core/traits/negatable.sakura | 21 + core/traits/numeric.sakura | 29 + core/traits/ordered.sakura | 26 + core/traits/ordinal.sakura | 19 + core/traits/owning.sakura | 49 + core/traits/pointer.sakura | 23 + core/traits/real.sakura | 94 + core/traits/signature.sakura | 32 + core/traits/sliceable.sakura | 21 + core/traits/subtractable.sakura | 25 + core/traits/viewable.sakura | 23 + core/traits/zeroable.sakura | 21 + core/u8.ext.sakura | 149 + docs/algorithms.md | 663 ++++ docs/benchmarks.md | 626 ++++ docs/freestanding.md | 607 ++++ docs/inconsistencies.md | 71 + docs/later.md | 582 +++ docs/linear.md | 595 ++++ docs/logging.md | 428 +++ docs/performance.md | 395 +++ docs/random.md | 469 +++ docs/roadmap.md | 741 ++++ docs/tui.md | 843 +++++ entry.sakura | 864 +++++ machine/README.md | 241 ++ machine/atomics.sakura | 65 + machine/evaluation.sakura | 548 +++ machine/foreign.sakura | 846 +++++ machine/format.sakura | 336 ++ machine/heap.sakura | 800 +++++ machine/interpreter.sakura | 1297 +++++++ machine/jit.sakura | 2523 +++++++++++++ machine/machine.sakura | 840 +++++ machine/system.sakura | 138 + machine/threads.sakura | 399 +++ machine/x86.sakura | 496 +++ native/README.md | 171 + native/abi.sakura | 881 +++++ native/atomics.sakura | 188 + native/calls.sakura | 1192 +++++++ native/check.sakura | 181 + native/codeview.sakura | 753 ++++ native/dwarf.sakura | 1159 ++++++ native/evex.sakura | 370 ++ native/lanes.sakura | 1250 +++++++ native/native.sakura | 1909 ++++++++++ native/operations.sakura | 1127 ++++++ native/output.sakura | 52 + native/registers.sakura | 1673 +++++++++ native/relax.sakura | 337 ++ native/reshape.sakura | 268 ++ native/select.sakura | 759 ++++ native/singles.sakura | 392 +++ native/variables.sakura | 466 +++ native/windows.sakura | 1011 ++++++ runtime/abi.sakura | 224 ++ runtime/float.sakura | 592 ++++ runtime/format.sakura | 415 +++ runtime/linux_x86_64.sakura | 20 + runtime/memory.sakura | 809 +++++ runtime/start.sakura | 318 ++ runtime/threads.sakura | 281 ++ runtime/values.sakura | 127 + runtime/windows.sakura | 213 ++ server/README.md | 103 + server/answers.sakura | 861 +++++ server/jobs.sakura | 704 ++++ server/program.sakura | 532 +++ server/requests.sakura | 525 +++ server/server.sakura | 654 ++++ server/system.sakura | 715 ++++ server/text.sakura | 329 ++ system/clock.sakura | 20 + system/files.sakura | 99 + system/io_error.sakura | 39 + system/linux/linux.sakura | 26 + system/linux/x86_64.sakura | 71 + system/on_linux.sakura | 1016 ++++++ system/on_linux_x86_64.sakura | 52 + system/on_windows.sakura | 2449 +++++++++++++ system/on_windows_x86_64.sakura | 58 + system/system.sakura | 262 ++ system/windows/waits.sakura | 18 + system/windows/windows.sakura | 268 ++ tests/analyzer/checker.sakura | 3116 +++++++++++++++++ tests/analyzer/keymap.sakura | 94 + tests/analyzer/lexer.sakura | 204 ++ tests/analyzer/names.sakura | 19 + tests/analyzer/parser.sakura | 285 ++ tests/analyzer/queries.sakura | 477 +++ tests/analyzer/reading.sakura | 146 + tests/analyzer/recovery.sakura | 141 + tests/analyzer/reparse.sakura | 128 + tests/analyzer/support.sakura | 611 ++++ tests/analyzer/syntax.sakura | 92 + .../an_index_outside_a_view_is_a_fault_1.out | 4 + ...n_index_outside_a_view_is_a_fault_1.sakura | 6 + tests/checked/enums_and_match_values_3.out | 5 + tests/checked/enums_and_match_values_3.sakura | 8 + ...red_out_of_order_check_their_members_1.out | 6 + ..._out_of_order_check_their_members_1.sakura | 16 + tests/checked/faults_1.out | 5 + tests/checked/faults_1.sakura | 6 + tests/checked/fixed_arrays_are_bounded_1.out | 4 + .../checked/fixed_arrays_are_bounded_1.sakura | 6 + tests/checked/functions_as_values_2.out | 6 + tests/checked/functions_as_values_2.sakura | 8 + ...ameters_convert_to_and_from_integers_2.out | 5 + ...ters_convert_to_and_from_integers_2.sakura | 4 + .../checked/refined_functions_as_values_2.out | 4 + .../refined_functions_as_values_2.sakura | 7 + .../text_constants_are_indexed_as_views_2.out | 5 + ...xt_constants_are_indexed_as_views_2.sakura | 3 + ...s_implementing_indexable_are_indexed_3.out | 6 + ...mplementing_indexable_are_indexed_3.sakura | 9 + tests/checked/unions_2.out | 5 + tests/checked/unions_2.sakura | 7 + ...xed_arrays_write_where_the_array_can_2.out | 5 + ..._arrays_write_where_the_array_can_2.sakura | 8 + tests/compiler/compiler.sakura | 510 +++ tests/compiler/intermediate.sakura | 298 ++ tests/compiler/optimizer.sakura | 697 ++++ tests/compiler/workers.sakura | 137 + tests/core/allocators.sakura | 16 + tests/core/atomics.sakura | 195 ++ tests/core/containers.sakura | 111 + tests/core/function.sakura | 235 ++ tests/core/generics.sakura | 244 ++ tests/core/iterators.sakura | 440 +++ tests/core/main.sakura | 111 + tests/core/mem.sakura | 91 + tests/core/operators.sakura | 188 + tests/core/owners.sakura | 74 + tests/core/owning.sakura | 209 ++ tests/core/references.sakura | 372 ++ tests/core/results.sakura | 168 + tests/core/scanning.sakura | 76 + tests/core/signals.sakura | 541 +++ tests/core/simd.sakura | 431 +++ tests/core/swar.sakura | 315 ++ tests/core/text.sakura | 35 + tests/libraries.sakura | 309 ++ tests/machine/machine.sakura | 902 +++++ tests/main.sakura | 32 + ...ock_released_twice_stops_the_program_1.out | 5 + ..._released_twice_stops_the_program_1.sakura | 8 + ..._after_its_release_stops_the_program_1.out | 5 + ...ter_its_release_stops_the_program_1.sakura | 8 + ...hat_exits_holds_what_its_frames_hold_1.out | 3 + ..._exits_holds_what_its_frames_hold_1.sakura | 12 + ...utliving_its_frame_stops_the_program_1.out | 5 + ...iving_its_frame_stops_the_program_1.sakura | 12 + ...e_reported_where_they_were_allocated_1.out | 9 + ...eported_where_they_were_allocated_1.sakura | 26 + ...s_close_the_fields_of_what_they_hold_1.out | 1 + ...lose_the_fields_of_what_they_hold_1.sakura | 10 + ...ctions_give_back_the_boxes_they_hold_1.out | 1 + ...ons_give_back_the_boxes_they_hold_1.sakura | 23 + ...om_the_system_is_held_until_unmapped_1.out | 6 + ...the_system_is_held_until_unmapped_1.sakura | 33 + ..._before_writing_it_stops_the_program_1.out | 6 + ...fore_writing_it_stops_the_program_1.sakura | 19 + ...what_was_allocated_stops_the_program_1.out | 5 + ...t_was_allocated_stops_the_program_1.sakura | 8 + ..._before_writing_it_stops_the_program_1.out | 5 + ...fore_writing_it_stops_the_program_1.sakura | 12 + ...ram_ends_hold_what_their_frames_hold_1.out | 1 + ..._ends_hold_what_their_frames_hold_1.sakura | 23 + .../unnamed_values_stay_in_their_union_1.out | 3 + ...nnamed_values_stay_in_their_union_1.sakura | 30 + ..._program_still_holds_is_not_reported_1.out | 1 + ...ogram_still_holds_is_not_reported_1.sakura | 22 + tests/native/native.sakura | 1292 +++++++ ...ile_may_begin_with_a_byte_order_mark_1.out | 1 + ..._may_begin_with_a_byte_order_mark_1.sakura | 2 + ...function_owns_the_values_it_is_given_1.out | 1 + ...ction_owns_the_values_it_is_given_1.sakura | 21 + ...a_test_names_the_value_a_union_holds_1.out | 4 + ...est_names_the_value_a_union_holds_1.sakura | 35 + .../aliases_satisfy_what_they_alias_1.out | 1 + .../aliases_satisfy_what_they_alias_1.sakura | 16 + .../allocations_give_aligned_memory_1.out | 2 + .../allocations_give_aligned_memory_1.sakura | 27 + .../an_abort_reports_where_it_was_1.out | 5 + .../an_abort_reports_where_it_was_1.sakura | 4 + .../programs/arguments_are_referred_to_1.out | 2 + .../arguments_are_referred_to_1.sakura | 19 + ...als_are_views_where_spans_are_wanted_1.out | 3 + ..._are_views_where_spans_are_wanted_1.sakura | 16 + ...rals_viewed_by_a_call_close_after_it_1.out | 4 + ...s_viewed_by_a_call_close_after_it_1.sakura | 8 + tests/programs/atomics_1.out | 21 + tests/programs/atomics_1.sakura | 171 + .../attributes_leave_the_program_alone_1.out | 1 + ...ttributes_leave_the_program_alone_1.sakura | 11 + .../bitwise_operators_call_methods_1.out | 6 + .../bitwise_operators_call_methods_1.sakura | 36 + .../programs/booleans_numbers_and_loops_1.out | 1 + .../booleans_numbers_and_loops_1.sakura | 26 + ...d_tests_narrow_the_branch_they_guard_1.out | 2 + ...ests_narrow_the_branch_they_guard_1.sakura | 35 + ...es_and_containers_close_whole_values_1.out | 9 + ...and_containers_close_whole_values_1.sakura | 22 + ..._in_types_are_equatable_and_hashable_1.out | 1 + ..._types_are_equatable_and_hashable_1.sakura | 16 + ...ers_close_where_the_function_returns_1.out | 11 + ..._close_where_the_function_returns_1.sakura | 20 + ..._values_close_where_their_scope_ends_1.out | 17 + ...lues_close_where_their_scope_ends_1.sakura | 40 + .../compile_error_in_a_generic_property_1.out | 4 + ...mpile_error_in_a_generic_property_1.sakura | 23 + ...says_text_worked_out_while_compiling_1.out | 3 + ...s_text_worked_out_while_compiling_1.sakura | 8 + ...says_text_worked_out_while_compiling_2.out | 4 + ...s_text_worked_out_while_compiling_2.sakura | 19 + ..._for_evaluating_to_choose_its_branch_1.out | 6 + ...r_evaluating_to_choose_its_branch_1.sakura | 37 + ..._for_evaluating_to_choose_its_branch_2.out | 4 + ...r_evaluating_to_choose_its_branch_2.sakura | 27 + ...nts_change_in_place_where_a_type_can_1.out | 6 + ..._change_in_place_where_a_type_can_1.sakura | 47 + tests/programs/const_declarations_1.out | 5 + tests/programs/const_declarations_1.sakura | 53 + tests/programs/const_pointers_1.out | 1 + tests/programs/const_pointers_1.sakura | 40 + ...nts_are_made_by_operators_of_methods_1.out | 1 + ..._are_made_by_operators_of_methods_1.sakura | 13 + tests/programs/constants_hold_functions_1.out | 1 + .../constants_hold_functions_1.sakura | 20 + ...ants_keep_the_memory_they_point_into_3.out | 1 + ...s_keep_the_memory_they_point_into_3.sakura | 4 + .../constants_view_other_constants_1.out | 7 + .../constants_view_other_constants_1.sakura | 60 + tests/programs/contracts_1.out | 6 + tests/programs/contracts_1.sakura | 14 + tests/programs/contracts_2.out | 7 + tests/programs/contracts_2.sakura | 21 + tests/programs/contracts_3.out | 6 + tests/programs/contracts_3.sakura | 55 + tests/programs/contracts_4.out | 6 + tests/programs/contracts_4.sakura | 24 + tests/programs/contracts_5.out | 4 + tests/programs/contracts_5.sakura | 43 + tests/programs/contracts_6.out | 6 + tests/programs/contracts_6.sakura | 13 + tests/programs/control_flow_1.out | 3 + tests/programs/control_flow_1.sakura | 30 + tests/programs/core_alone_1.out | 7 + tests/programs/core_alone_1.sakura | 62 + ..._of_takes_a_type_a_declaration_makes_1.out | 3 + ..._takes_a_type_a_declaration_makes_1.sakura | 7 + tests/programs/default_trait_methods_1.out | 2 + tests/programs/default_trait_methods_1.sakura | 32 + ...ng_to_the_declaration_a_call_reaches_1.out | 2 + ...to_the_declaration_a_call_reaches_1.sakura | 10 + tests/programs/dereferences_2.out | 5 + tests/programs/dereferences_2.sakura | 6 + tests/programs/enums_and_match_values_1.out | 5 + .../programs/enums_and_match_values_1.sakura | 39 + tests/programs/enums_and_match_values_2.out | 2 + .../programs/enums_and_match_values_2.sakura | 8 + ...lity_calls_what_a_type_says_it_means_1.out | 3 + ...y_calls_what_a_type_says_it_means_1.sakura | 8 + .../equality_is_what_equals_says_1.out | 1 + .../equality_is_what_equals_says_1.sakura | 37 + ...rors_are_handled_where_they_are_made_1.out | 1 + ...s_are_handled_where_they_are_made_1.sakura | 32 + tests/programs/faults_2.out | 6 + tests/programs/faults_2.sakura | 6 + tests/programs/faults_3.out | 4 + tests/programs/faults_3.sakura | 6 + .../fixed_arrays_hold_their_elements_1.out | 5 + .../fixed_arrays_hold_their_elements_1.sakura | 34 + .../for_const_counts_through_ranges_1.out | 8 + .../for_const_counts_through_ranges_1.sakura | 42 + ..._a_pack_are_what_each_instance_gives_1.out | 3 + ...pack_are_what_each_instance_gives_1.sakura | 81 + tests/programs/functions_as_values_1.out | 1 + tests/programs/functions_as_values_1.sakura | 60 + .../functions_hold_any_callable_1.out | 13 + .../functions_hold_any_callable_1.sakura | 99 + tests/programs/generic_traits_1.out | 3 + tests/programs/generic_traits_1.sakura | 40 + tests/programs/generics_1.out | 1 + tests/programs/generics_1.sakura | 60 + tests/programs/generics_2.out | 6 + tests/programs/generics_2.sakura | 6 + tests/programs/globals_1.out | 1 + tests/programs/globals_1.sakura | 18 + ..._const_calls_through_type_parameters_1.out | 2 + ...nst_calls_through_type_parameters_1.sakura | 24 + ...t_compares_what_reflection_describes_1.out | 4 + ...ompares_what_reflection_describes_1.sakura | 27 + ..._const_names_the_type_a_parameter_is_1.out | 4 + ...nst_names_the_type_a_parameter_is_1.sakura | 35 + .../indexes_read_through_references_1.out | 1 + .../indexes_read_through_references_1.sakura | 32 + ...ndexing_gives_the_reference_at_gives_1.out | 6 + ...xing_gives_the_reference_at_gives_1.sakura | 56 + .../inline_functions_run_as_called_1.out | 6 + .../inline_functions_run_as_called_1.sakura | 28 + .../inlined_calls_behave_like_calls_1.out | 3 + .../inlined_calls_behave_like_calls_1.sakura | 22 + tests/programs/integers_1.out | 6 + tests/programs/integers_1.sakura | 23 + tests/programs/invokable_values_1.out | 6 + tests/programs/invokable_values_1.sakura | 50 + .../is_tests_what_a_type_satisfies_1.out | 1 + .../is_tests_what_a_type_satisfies_1.sakura | 21 + tests/programs/iterator_adapters_1.out | 1 + tests/programs/iterator_adapters_1.sakura | 44 + tests/programs/jumps_take_a_condition_1.out | 3 + .../programs/jumps_take_a_condition_1.sakura | 31 + ...das_give_type_parameters_their_types_1.out | 4 + ..._give_type_parameters_their_types_1.sakura | 13 + .../literals_of_text_are_walked_1.out | 1 + .../literals_of_text_are_walked_1.sakura | 10 + tests/programs/local_functions_1.out | 2 + tests/programs/local_functions_1.sakura | 25 + tests/programs/logic_short_circuits_1.out | 1 + tests/programs/logic_short_circuits_1.sakura | 8 + tests/programs/loops_walk_iterators_1.out | 2 + tests/programs/loops_walk_iterators_1.sakura | 32 + ..._constants_go_straight_to_their_case_1.out | 4 + ...nstants_go_straight_to_their_case_1.sakura | 45 + .../math_functions_agree_everywhere_1.out | 53 + .../math_functions_agree_everywhere_1.sakura | 204 ++ .../maybe_references_are_one_word_1.out | 1 + .../maybe_references_are_one_word_1.sakura | 39 + .../programs/methods_on_built_in_types_1.out | 2 + .../methods_on_built_in_types_1.sakura | 22 + ...n_numbers_stand_beside_the_compilers_1.out | 3 + ...umbers_stand_beside_the_compilers_1.sakura | 19 + .../methods_shadow_the_types_aliased_1.out | 1 + .../methods_shadow_the_types_aliased_1.sakura | 11 + tests/programs/module_exports_1.out | 1 + tests/programs/module_exports_1.sakura | 18 + .../modules_see_nothing_of_the_program_1.out | 1 + ...odules_see_nothing_of_the_program_1.sakura | 12 + ...unctions_are_called_as_the_type_asks_1.out | 6 + ...tions_are_called_as_the_type_asks_1.sakura | 68 + tests/programs/names_of_core_give_way_1.out | 2 + .../programs/names_of_core_give_way_1.sakura | 39 + ...row_scalars_are_referred_to_in_place_1.out | 2 + ..._scalars_are_referred_to_in_place_1.sakura | 26 + tests/programs/nested_traits_run_1.out | 1 + tests/programs/nested_traits_run_1.sakura | 27 + tests/programs/nested_types_run_1.out | 1 + tests/programs/nested_types_run_1.sakura | 30 + ...l_the_methods_of_ordered_and_numeric_1.out | 3 + ...he_methods_of_ordered_and_numeric_1.sakura | 34 + ...l_the_methods_of_ordered_and_numeric_2.out | 2 + ...he_methods_of_ordered_and_numeric_2.sakura | 24 + ...tors_call_the_methods_that_give_them_1.out | 3 + ...s_call_the_methods_that_give_them_1.sakura | 48 + ...constants_as_their_methods_take_them_1.out | 8 + ...stants_as_their_methods_take_them_1.sakura | 47 + ...rs_reach_generic_code_through_bounds_1.out | 5 + ...reach_generic_code_through_bounds_1.sakura | 38 + ...ameters_convert_to_and_from_integers_1.out | 2 + ...ters_convert_to_and_from_integers_1.sakura | 15 + tests/programs/overloads_1.out | 2 + tests/programs/overloads_1.sakura | 38 + tests/programs/packs_in_function_types_1.out | 5 + .../programs/packs_in_function_types_1.sakura | 19 + .../programs/packs_of_types_and_traits_1.out | 6 + .../packs_of_types_and_traits_1.sakura | 59 + .../packs_of_types_have_lengths_1.out | 1 + .../packs_of_types_have_lengths_1.sakura | 8 + .../packs_spread_move_their_values_1.out | 5 + .../packs_spread_move_their_values_1.sakura | 12 + .../parameters_take_default_values_1.out | 10 + .../parameters_take_default_values_1.sakura | 36 + .../path_of_names_the_modules_of_types_1.out | 5 + ...ath_of_names_the_modules_of_types_1.sakura | 12 + tests/programs/pattern_parameters_1.out | 10 + tests/programs/pattern_parameters_1.sakura | 77 + tests/programs/pattern_parameters_2.out | 4 + tests/programs/pattern_parameters_2.sakura | 56 + .../programs/pointers_and_manual_memory_2.out | 5 + .../pointers_and_manual_memory_2.sakura | 6 + tests/programs/properties_1.out | 4 + tests/programs/properties_1.sakura | 29 + tests/programs/properties_2.out | 2 + tests/programs/properties_2.sakura | 27 + ...rties_and_generic_methods_are_values_1.out | 4 + ...es_and_generic_methods_are_values_1.sakura | 43 + tests/programs/property_accessors_1.out | 2 + tests/programs/property_accessors_1.sakura | 23 + tests/programs/ranges_are_values_1.out | 1 + tests/programs/ranges_are_values_1.sakura | 38 + .../programs/ranges_count_through_enums_1.out | 4 + .../ranges_count_through_enums_1.sakura | 53 + tests/programs/references_1.out | 1 + tests/programs/references_1.sakura | 31 + ...ces_are_kept_only_where_they_must_be_1.out | 4 + ..._are_kept_only_where_they_must_be_1.sakura | 35 + ...references_are_lent_and_values_given_1.out | 7 + ...erences_are_lent_and_values_given_1.sakura | 68 + ...erences_reach_the_types_holding_them_1.out | 1 + ...nces_reach_the_types_holding_them_1.sakura | 33 + ...ences_stay_where_they_cannot_be_kept_1.out | 1 + ...es_stay_where_they_cannot_be_kept_1.sakura | 40 + tests/programs/references_to_new_values_1.out | 4 + .../references_to_new_values_1.sakura | 25 + .../refined_functions_as_values_1.out | 1 + .../refined_functions_as_values_1.sakura | 47 + ...lection_reaches_declarations_by_name_1.out | 5 + ...tion_reaches_declarations_by_name_1.sakura | 59 + ...eflection_spells_types_and_instances_1.out | 3 + ...ection_spells_types_and_instances_1.sakura | 23 + ...wherever_their_parameter_is_declared_1.out | 3 + ...rever_their_parameter_is_declared_1.sakura | 31 + tests/programs/signatures_1.out | 8 + tests/programs/signatures_1.sakura | 45 + .../simd_lanes_agree_everywhere_1.out | 1205 +++++++ .../simd_lanes_agree_everywhere_1.sakura | 177 + .../simd_lanes_agree_everywhere_2.out | 481 +++ .../simd_lanes_agree_everywhere_2.sakura | 165 + tests/programs/simd_values_in_registers_1.out | 7 + .../simd_values_in_registers_1.sakura | 134 + tests/programs/static_trait_methods_1.out | 3 + tests/programs/static_trait_methods_1.sakura | 35 + ...rings_unions_shadowing_and_ternaries_1.out | 1 + ...gs_unions_shadowing_and_ternaries_1.sakura | 27 + tests/programs/structs_1.out | 4 + tests/programs/structs_1.sakura | 30 + .../structs_of_no_fields_are_returned_1.out | 3 + ...structs_of_no_fields_are_returned_1.sakura | 25 + .../swar_words_agree_everywhere_1.out | 96 + .../swar_words_agree_everywhere_1.sakura | 56 + ...ternaries_name_what_their_tests_give_1.out | 1 + ...naries_name_what_their_tests_give_1.sakura | 8 + .../ternary_branches_take_fallbacks_1.out | 10 + .../ternary_branches_take_fallbacks_1.sakura | 73 + .../text_constants_are_indexed_as_views_1.out | 1 + ...xt_constants_are_indexed_as_views_1.sakura | 6 + ...t_is_a_view_of_the_program_own_bytes_1.out | 5 + ...s_a_view_of_the_program_own_bytes_1.sakura | 17 + tests/programs/text_is_split_lazily_1.out | 1 + tests/programs/text_is_split_lazily_1.sakura | 27 + tests/programs/text_spanning_lines_1.out | 6 + tests/programs/text_spanning_lines_1.sakura | 14 + tests/programs/text_spanning_lines_2.out | 4 + tests/programs/text_spanning_lines_2.sakura | 12 + tests/programs/text_spanning_lines_3.out | 3 + tests/programs/text_spanning_lines_3.sakura | 11 + ...e_compiler_gives_a_call_its_own_site_1.out | 4 + ...ompiler_gives_a_call_its_own_site_1.sakura | 18 + .../the_receiver_chooses_the_overload_1.out | 1 + ...the_receiver_chooses_the_overload_1.sakura | 34 + tests/programs/threads_1.out | 7 + tests/programs/threads_1.sakura | 97 + tests/programs/trait_composition_1.out | 4 + tests/programs/trait_composition_1.sakura | 31 + tests/programs/trait_composition_2.out | 1 + tests/programs/trait_composition_2.sakura | 20 + tests/programs/trait_composition_3.out | 1 + tests/programs/trait_composition_3.sakura | 25 + tests/programs/trait_defaults_per_type_1.out | 1 + .../programs/trait_defaults_per_type_1.sakura | 60 + tests/programs/traits_1.out | 1 + tests/programs/traits_1.sakura | 21 + tests/programs/traits_ask_for_types_1.out | 1 + tests/programs/traits_ask_for_types_1.sakura | 31 + .../traits_have_functions_of_their_own_1.out | 5 + ...raits_have_functions_of_their_own_1.sakura | 37 + .../programs/traits_see_through_aliases_1.out | 1 + .../traits_see_through_aliases_1.sakura | 11 + ...arameters_given_references_pass_them_1.out | 2 + ...meters_given_references_pass_them_1.sakura | 45 + ...s_implementing_indexable_are_indexed_1.out | 3 + ...mplementing_indexable_are_indexed_1.sakura | 19 + ...s_implementing_indexable_are_indexed_2.out | 1 + ...mplementing_indexable_are_indexed_2.sakura | 10 + .../types_name_their_own_without_them_1.out | 3 + ...types_name_their_own_without_them_1.sakura | 60 + .../union_fields_are_named_by_reference_1.out | 5 + ...ion_fields_are_named_by_reference_1.sakura | 18 + .../programs/unions_hold_what_is_given_1.out | 2 + .../unions_hold_what_is_given_1.sakura | 25 + tests/programs/unsigned_literals_1.out | 1 + tests/programs/unsigned_literals_1.sakura | 7 + .../values_are_called_through_invoke_1.out | 11 + .../values_are_called_through_invoke_1.sakura | 56 + ...by_branches_not_taken_are_not_closed_1.out | 8 + ...branches_not_taken_are_not_closed_1.sakura | 16 + ...guments_are_closed_where_they_belong_1.out | 6 + ...ents_are_closed_where_they_belong_1.sakura | 9 + tests/programs/variadic_function_values_1.out | 6 + .../variadic_function_values_1.sakura | 30 + ...tions_take_a_view_of_their_arguments_1.out | 4 + ...ns_take_a_view_of_their_arguments_1.sakura | 22 + ...dic_generics_unroll_over_their_packs_1.out | 2 + ..._generics_unroll_over_their_packs_1.sakura | 37 + .../views_are_indexed_and_walked_1.out | 5 + .../views_are_indexed_and_walked_1.sakura | 17 + ...xed_arrays_write_where_the_array_can_1.out | 3 + ..._arrays_write_where_the_array_can_1.sakura | 16 + .../programs/void_is_a_value_of_its_own_1.out | 16 + .../void_is_a_value_of_its_own_1.sakura | 71 + .../when_runs_what_the_target_takes_1.out | 1 + .../when_runs_what_the_target_takes_1.sakura | 22 + .../programs/writing_through_references_1.out | 1 + .../writing_through_references_1.sakura | 24 + tests/server/server.sakura | 127 + tools/corpus.sakura | 204 ++ tools/function.sakura | 96 + tools/iterators.sakura | 121 + tools/memory.sakura | 148 + .../__pycache__/inlined.cpython-314.pyc | Bin 0 -> 2642 bytes tools/profile/annotate.py | 32 + tools/profile/costs.py | 145 + tools/profile/count.c | 78 + tools/profile/inlined.py | 40 + tools/profile/kinds.py | 52 + tools/profile/measure.py | 110 + tools/profile/sampler.c | 69 + tools/profile/samples.py | 87 + 706 files changed, 135430 insertions(+) create mode 100644 .editorconfig create mode 100644 .gitignore create mode 100644 CHANGELOG.md create mode 100644 LICENSE create mode 100644 README.md create mode 100644 analyzer/README.md create mode 100644 analyzer/builtin.sakura create mode 100644 analyzer/checker.sakura create mode 100644 analyzer/checker/access.sakura create mode 100644 analyzer/checker/attributes.sakura create mode 100644 analyzer/checker/bodies.sakura create mode 100644 analyzer/checker/calls.sakura create mode 100644 analyzer/checker/composite.sakura create mode 100644 analyzer/checker/constants.sakura create mode 100644 analyzer/checker/convert.sakura create mode 100644 analyzer/checker/declare.sakura create mode 100644 analyzer/checker/decls.sakura create mode 100644 analyzer/checker/describe.sakura create mode 100644 analyzer/checker/evaluator.sakura create mode 100644 analyzer/checker/expressions.sakura create mode 100644 analyzer/checker/generics.sakura create mode 100644 analyzer/checker/incremental.sakura create mode 100644 analyzer/checker/knowns.sakura create mode 100644 analyzer/checker/lifetimes.sakura create mode 100644 analyzer/checker/link.sakura create mode 100644 analyzer/checker/lookup.sakura create mode 100644 analyzer/checker/nodes.sakura create mode 100644 analyzer/checker/notes.sakura create mode 100644 analyzer/checker/operators.sakura create mode 100644 analyzer/checker/ownership.sakura create mode 100644 analyzer/checker/patterns.sakura create mode 100644 analyzer/checker/reflection.sakura create mode 100644 analyzer/checker/resolve.sakura create mode 100644 analyzer/checker/results.sakura create mode 100644 analyzer/checker/scopes.sakura create mode 100644 analyzer/checker/statements.sakura create mode 100644 analyzer/checker/traits.sakura create mode 100644 analyzer/checker/types.sakura create mode 100644 analyzer/column.sakura create mode 100644 analyzer/errors.sakura create mode 100644 analyzer/idindex.sakura create mode 100644 analyzer/keymap.sakura create mode 100644 analyzer/lexer.sakura create mode 100644 analyzer/libraries.sakura create mode 100644 analyzer/lines.sakura create mode 100644 analyzer/names.sakura create mode 100644 analyzer/node.sakura create mode 100644 analyzer/note.sakura create mode 100644 analyzer/parser.sakura create mode 100644 analyzer/parser/attribute.sakura create mode 100644 analyzer/parser/declarations.sakura create mode 100644 analyzer/parser/expressions.sakura create mode 100644 analyzer/parser/fields.sakura create mode 100644 analyzer/parser/helpers.sakura create mode 100644 analyzer/parser/primary.sakura create mode 100644 analyzer/parser/reparse.sakura create mode 100644 analyzer/parser/statements.sakura create mode 100644 analyzer/parser/tables.sakura create mode 100644 analyzer/parser/types.sakura create mode 100644 analyzer/parser/when.sakura create mode 100644 analyzer/printer.sakura create mode 100644 analyzer/queries/calling.sakura create mode 100644 analyzer/queries/completion.sakura create mode 100644 analyzer/queries/highlights.sakura create mode 100644 analyzer/queries/hover.sakura create mode 100644 analyzer/queries/names.sakura create mode 100644 analyzer/queries/programs.sakura create mode 100644 analyzer/queries/signatures.sakura create mode 100644 analyzer/queries/symbols.sakura create mode 100644 analyzer/reading.sakura create mode 100644 analyzer/shapes.sakura create mode 100644 analyzer/source.sakura create mode 100644 analyzer/syntax.sakura create mode 100644 analyzer/token.sakura create mode 100644 analyzer/walker.sakura create mode 100644 blossomfile create mode 100644 compiler/README.md create mode 100644 compiler/atomics.sakura create mode 100644 compiler/bytecode.sakura create mode 100644 compiler/compiler.sakura create mode 100644 compiler/constants.sakura create mode 100644 compiler/conventions.sakura create mode 100644 compiler/dispatch.sakura create mode 100644 compiler/emitter.sakura create mode 100644 compiler/emitter/bodies.sakura create mode 100644 compiler/emitter/builtins.sakura create mode 100644 compiler/emitter/calls.sakura create mode 100644 compiler/emitter/closures.sakura create mode 100644 compiler/emitter/composite.sakura create mode 100644 compiler/emitter/formatting.sakura create mode 100644 compiler/emitter/intrinsics.sakura create mode 100644 compiler/emitter/loops.sakura create mode 100644 compiler/emitter/match.sakura create mode 100644 compiler/emitter/operators.sakura create mode 100644 compiler/emitter/ownership.sakura create mode 100644 compiler/emitter/places.sakura create mode 100644 compiler/emitter/reflection.sakura create mode 100644 compiler/emitter/statements.sakura create mode 100644 compiler/emitter/storage.sakura create mode 100644 compiler/emitter/values.sakura create mode 100644 compiler/escapes.sakura create mode 100644 compiler/flows.sakura create mode 100644 compiler/globals.sakura create mode 100644 compiler/intermediate/builder.sakura create mode 100644 compiler/intermediate/cells.sakura create mode 100644 compiler/intermediate/code.sakura create mode 100644 compiler/intermediate/compact.sakura create mode 100644 compiler/intermediate/ids.sakura create mode 100644 compiler/intermediate/liveness.sakura create mode 100644 compiler/intermediate/moves.sakura create mode 100644 compiler/intermediate/numbers.sakura create mode 100644 compiler/intermediate/orders.sakura create mode 100644 compiler/intermediate/printer.sakura create mode 100644 compiler/intermediate/verifier.sakura create mode 100644 compiler/intermediate/walks.sakura create mode 100644 compiler/keeps.sakura create mode 100644 compiler/lanes.sakura create mode 100644 compiler/layouts.sakura create mode 100644 compiler/nodes.sakura create mode 100644 compiler/optimizer/alias.sakura create mode 100644 compiler/optimizer/control.sakura create mode 100644 compiler/optimizer/dead.sakura create mode 100644 compiler/optimizer/edit.sakura create mode 100644 compiler/optimizer/inline.sakura create mode 100644 compiler/optimizer/loops.sakura create mode 100644 compiler/optimizer/memory.sakura create mode 100644 compiler/optimizer/merge.sakura create mode 100644 compiler/optimizer/numbering.sakura create mode 100644 compiler/optimizer/optimizer.sakura create mode 100644 compiler/optimizer/promote.sakura create mode 100644 compiler/optimizer/simplify.sakura create mode 100644 compiler/optimizer/sink.sakura create mode 100644 compiler/optimizer/unused.sakura create mode 100644 compiler/optimizer/versions.sakura create mode 100644 compiler/program.sakura create mode 100644 compiler/report.sakura create mode 100644 compiler/scratch.sakura create mode 100644 compiler/tracking.sakura create mode 100644 compiler/workers.sakura create mode 100644 core/allocators/allocator.sakura create mode 100644 core/atomic.sakura create mode 100644 core/attribute.sakura create mode 100644 core/bits.sakura create mode 100644 core/bool.ext.sakura create mode 100644 core/containers/decimal.sakura create mode 100644 core/containers/pair.sakura create mode 100644 core/containers/slice.sakura create mode 100644 core/containers/sort.sakura create mode 100644 core/containers/span.sakura create mode 100644 core/containers/string.sakura create mode 100644 core/containers/strview.sakura create mode 100644 core/containers/vector.sakura create mode 100644 core/fault.sakura create mode 100644 core/ffi.sakura create mode 100644 core/flags.sakura create mode 100644 core/functions/function.sakura create mode 100644 core/intrinsics.sakura create mode 100644 core/iterators/adapters.sakura create mode 100644 core/iterators/range.sakura create mode 100644 core/iterators/text.sakura create mode 100644 core/mem.sakura create mode 100644 core/owners/box.sakura create mode 100644 core/reflect.sakura create mode 100644 core/results/maybe.sakura create mode 100644 core/results/result.sakura create mode 100644 core/simd.sakura create mode 100644 core/site.sakura create mode 100644 core/swar.sakura create mode 100644 core/target.sakura create mode 100644 core/traits/addable.sakura create mode 100644 core/traits/additive.sakura create mode 100644 core/traits/closeable.sakura create mode 100644 core/traits/copyable.sakura create mode 100644 core/traits/divisible.sakura create mode 100644 core/traits/equatable.sakura create mode 100644 core/traits/extendable.sakura create mode 100644 core/traits/hashable.sakura create mode 100644 core/traits/indexable.sakura create mode 100644 core/traits/integer.sakura create mode 100644 core/traits/invokable.sakura create mode 100644 core/traits/iterable.sakura create mode 100644 core/traits/iterator.sakura create mode 100644 core/traits/modular.sakura create mode 100644 core/traits/moveable.sakura create mode 100644 core/traits/multipliable.sakura create mode 100644 core/traits/multiplicative.sakura create mode 100644 core/traits/negatable.sakura create mode 100644 core/traits/numeric.sakura create mode 100644 core/traits/ordered.sakura create mode 100644 core/traits/ordinal.sakura create mode 100644 core/traits/owning.sakura create mode 100644 core/traits/pointer.sakura create mode 100644 core/traits/real.sakura create mode 100644 core/traits/signature.sakura create mode 100644 core/traits/sliceable.sakura create mode 100644 core/traits/subtractable.sakura create mode 100644 core/traits/viewable.sakura create mode 100644 core/traits/zeroable.sakura create mode 100644 core/u8.ext.sakura create mode 100644 docs/algorithms.md create mode 100644 docs/benchmarks.md create mode 100644 docs/freestanding.md create mode 100644 docs/inconsistencies.md create mode 100644 docs/later.md create mode 100644 docs/linear.md create mode 100644 docs/logging.md create mode 100644 docs/performance.md create mode 100644 docs/random.md create mode 100644 docs/roadmap.md create mode 100644 docs/tui.md create mode 100644 entry.sakura create mode 100644 machine/README.md create mode 100644 machine/atomics.sakura create mode 100644 machine/evaluation.sakura create mode 100644 machine/foreign.sakura create mode 100644 machine/format.sakura create mode 100644 machine/heap.sakura create mode 100644 machine/interpreter.sakura create mode 100644 machine/jit.sakura create mode 100644 machine/machine.sakura create mode 100644 machine/system.sakura create mode 100644 machine/threads.sakura create mode 100644 machine/x86.sakura create mode 100644 native/README.md create mode 100644 native/abi.sakura create mode 100644 native/atomics.sakura create mode 100644 native/calls.sakura create mode 100644 native/check.sakura create mode 100644 native/codeview.sakura create mode 100644 native/dwarf.sakura create mode 100644 native/evex.sakura create mode 100644 native/lanes.sakura create mode 100644 native/native.sakura create mode 100644 native/operations.sakura create mode 100644 native/output.sakura create mode 100644 native/registers.sakura create mode 100644 native/relax.sakura create mode 100644 native/reshape.sakura create mode 100644 native/select.sakura create mode 100644 native/singles.sakura create mode 100644 native/variables.sakura create mode 100644 native/windows.sakura create mode 100644 runtime/abi.sakura create mode 100644 runtime/float.sakura create mode 100644 runtime/format.sakura create mode 100644 runtime/linux_x86_64.sakura create mode 100644 runtime/memory.sakura create mode 100644 runtime/start.sakura create mode 100644 runtime/threads.sakura create mode 100644 runtime/values.sakura create mode 100644 runtime/windows.sakura create mode 100644 server/README.md create mode 100644 server/answers.sakura create mode 100644 server/jobs.sakura create mode 100644 server/program.sakura create mode 100644 server/requests.sakura create mode 100644 server/server.sakura create mode 100644 server/system.sakura create mode 100644 server/text.sakura create mode 100644 system/clock.sakura create mode 100644 system/files.sakura create mode 100644 system/io_error.sakura create mode 100644 system/linux/linux.sakura create mode 100644 system/linux/x86_64.sakura create mode 100644 system/on_linux.sakura create mode 100644 system/on_linux_x86_64.sakura create mode 100644 system/on_windows.sakura create mode 100644 system/on_windows_x86_64.sakura create mode 100644 system/system.sakura create mode 100644 system/windows/waits.sakura create mode 100644 system/windows/windows.sakura create mode 100644 tests/analyzer/checker.sakura create mode 100644 tests/analyzer/keymap.sakura create mode 100644 tests/analyzer/lexer.sakura create mode 100644 tests/analyzer/names.sakura create mode 100644 tests/analyzer/parser.sakura create mode 100644 tests/analyzer/queries.sakura create mode 100644 tests/analyzer/reading.sakura create mode 100644 tests/analyzer/recovery.sakura create mode 100644 tests/analyzer/reparse.sakura create mode 100644 tests/analyzer/support.sakura create mode 100644 tests/analyzer/syntax.sakura create mode 100644 tests/checked/an_index_outside_a_view_is_a_fault_1.out create mode 100644 tests/checked/an_index_outside_a_view_is_a_fault_1.sakura create mode 100644 tests/checked/enums_and_match_values_3.out create mode 100644 tests/checked/enums_and_match_values_3.sakura create mode 100644 tests/checked/enums_declared_out_of_order_check_their_members_1.out create mode 100644 tests/checked/enums_declared_out_of_order_check_their_members_1.sakura create mode 100644 tests/checked/faults_1.out create mode 100644 tests/checked/faults_1.sakura create mode 100644 tests/checked/fixed_arrays_are_bounded_1.out create mode 100644 tests/checked/fixed_arrays_are_bounded_1.sakura create mode 100644 tests/checked/functions_as_values_2.out create mode 100644 tests/checked/functions_as_values_2.sakura create mode 100644 tests/checked/ordinal_parameters_convert_to_and_from_integers_2.out create mode 100644 tests/checked/ordinal_parameters_convert_to_and_from_integers_2.sakura create mode 100644 tests/checked/refined_functions_as_values_2.out create mode 100644 tests/checked/refined_functions_as_values_2.sakura create mode 100644 tests/checked/text_constants_are_indexed_as_views_2.out create mode 100644 tests/checked/text_constants_are_indexed_as_views_2.sakura create mode 100644 tests/checked/types_implementing_indexable_are_indexed_3.out create mode 100644 tests/checked/types_implementing_indexable_are_indexed_3.sakura create mode 100644 tests/checked/unions_2.out create mode 100644 tests/checked/unions_2.sakura create mode 100644 tests/checked/views_of_fixed_arrays_write_where_the_array_can_2.out create mode 100644 tests/checked/views_of_fixed_arrays_write_where_the_array_can_2.sakura create mode 100644 tests/compiler/compiler.sakura create mode 100644 tests/compiler/intermediate.sakura create mode 100644 tests/compiler/optimizer.sakura create mode 100644 tests/compiler/workers.sakura create mode 100644 tests/core/allocators.sakura create mode 100644 tests/core/atomics.sakura create mode 100644 tests/core/containers.sakura create mode 100644 tests/core/function.sakura create mode 100644 tests/core/generics.sakura create mode 100644 tests/core/iterators.sakura create mode 100644 tests/core/main.sakura create mode 100644 tests/core/mem.sakura create mode 100644 tests/core/operators.sakura create mode 100644 tests/core/owners.sakura create mode 100644 tests/core/owning.sakura create mode 100644 tests/core/references.sakura create mode 100644 tests/core/results.sakura create mode 100644 tests/core/scanning.sakura create mode 100644 tests/core/signals.sakura create mode 100644 tests/core/simd.sakura create mode 100644 tests/core/swar.sakura create mode 100644 tests/core/text.sakura create mode 100644 tests/libraries.sakura create mode 100644 tests/machine/machine.sakura create mode 100644 tests/main.sakura create mode 100644 tests/memory/a_block_released_twice_stops_the_program_1.out create mode 100644 tests/memory/a_block_released_twice_stops_the_program_1.sakura create mode 100644 tests/memory/a_block_used_after_its_release_stops_the_program_1.out create mode 100644 tests/memory/a_block_used_after_its_release_stops_the_program_1.sakura create mode 100644 tests/memory/a_program_that_exits_holds_what_its_frames_hold_1.out create mode 100644 tests/memory/a_program_that_exits_holds_what_its_frames_hold_1.sakura create mode 100644 tests/memory/a_reference_outliving_its_frame_stops_the_program_1.out create mode 100644 tests/memory/a_reference_outliving_its_frame_stops_the_program_1.sakura create mode 100644 tests/memory/blocks_nothing_reaches_are_reported_where_they_were_allocated_1.out create mode 100644 tests/memory/blocks_nothing_reaches_are_reported_where_they_were_allocated_1.sakura create mode 100644 tests/memory/boxes_close_the_fields_of_what_they_hold_1.out create mode 100644 tests/memory/boxes_close_the_fields_of_what_they_hold_1.sakura create mode 100644 tests/memory/functions_give_back_the_boxes_they_hold_1.out create mode 100644 tests/memory/functions_give_back_the_boxes_they_hold_1.sakura create mode 100644 tests/memory/memory_mapped_from_the_system_is_held_until_unmapped_1.out create mode 100644 tests/memory/memory_mapped_from_the_system_is_held_until_unmapped_1.sakura create mode 100644 tests/memory/reading_an_undefined_variable_before_writing_it_stops_the_program_1.out create mode 100644 tests/memory/reading_an_undefined_variable_before_writing_it_stops_the_program_1.sakura create mode 100644 tests/memory/reading_past_what_was_allocated_stops_the_program_1.out create mode 100644 tests/memory/reading_past_what_was_allocated_stops_the_program_1.sakura create mode 100644 tests/memory/reading_what_raw_allocate_gave_before_writing_it_stops_the_program_1.out create mode 100644 tests/memory/reading_what_raw_allocate_gave_before_writing_it_stops_the_program_1.sakura create mode 100644 tests/memory/threads_running_as_the_program_ends_hold_what_their_frames_hold_1.out create mode 100644 tests/memory/threads_running_as_the_program_ends_hold_what_their_frames_hold_1.sakura create mode 100644 tests/memory/unnamed_values_stay_in_their_union_1.out create mode 100644 tests/memory/unnamed_values_stay_in_their_union_1.sakura create mode 100644 tests/memory/what_the_program_still_holds_is_not_reported_1.out create mode 100644 tests/memory/what_the_program_still_holds_is_not_reported_1.sakura create mode 100644 tests/native/native.sakura create mode 100644 tests/programs/a_file_may_begin_with_a_byte_order_mark_1.out create mode 100644 tests/programs/a_file_may_begin_with_a_byte_order_mark_1.sakura create mode 100644 tests/programs/a_function_owns_the_values_it_is_given_1.out create mode 100644 tests/programs/a_function_owns_the_values_it_is_given_1.sakura create mode 100644 tests/programs/a_test_names_the_value_a_union_holds_1.out create mode 100644 tests/programs/a_test_names_the_value_a_union_holds_1.sakura create mode 100644 tests/programs/aliases_satisfy_what_they_alias_1.out create mode 100644 tests/programs/aliases_satisfy_what_they_alias_1.sakura create mode 100644 tests/programs/allocations_give_aligned_memory_1.out create mode 100644 tests/programs/allocations_give_aligned_memory_1.sakura create mode 100644 tests/programs/an_abort_reports_where_it_was_1.out create mode 100644 tests/programs/an_abort_reports_where_it_was_1.sakura create mode 100644 tests/programs/arguments_are_referred_to_1.out create mode 100644 tests/programs/arguments_are_referred_to_1.sakura create mode 100644 tests/programs/array_literals_are_views_where_spans_are_wanted_1.out create mode 100644 tests/programs/array_literals_are_views_where_spans_are_wanted_1.sakura create mode 100644 tests/programs/array_literals_viewed_by_a_call_close_after_it_1.out create mode 100644 tests/programs/array_literals_viewed_by_a_call_close_after_it_1.sakura create mode 100644 tests/programs/atomics_1.out create mode 100644 tests/programs/atomics_1.sakura create mode 100644 tests/programs/attributes_leave_the_program_alone_1.out create mode 100644 tests/programs/attributes_leave_the_program_alone_1.sakura create mode 100644 tests/programs/bitwise_operators_call_methods_1.out create mode 100644 tests/programs/bitwise_operators_call_methods_1.sakura create mode 100644 tests/programs/booleans_numbers_and_loops_1.out create mode 100644 tests/programs/booleans_numbers_and_loops_1.sakura create mode 100644 tests/programs/bound_tests_narrow_the_branch_they_guard_1.out create mode 100644 tests/programs/bound_tests_narrow_the_branch_they_guard_1.sakura create mode 100644 tests/programs/boxes_and_containers_close_whole_values_1.out create mode 100644 tests/programs/boxes_and_containers_close_whole_values_1.sakura create mode 100644 tests/programs/built_in_types_are_equatable_and_hashable_1.out create mode 100644 tests/programs/built_in_types_are_equatable_and_hashable_1.sakura create mode 100644 tests/programs/closeable_parameters_close_where_the_function_returns_1.out create mode 100644 tests/programs/closeable_parameters_close_where_the_function_returns_1.sakura create mode 100644 tests/programs/closeable_values_close_where_their_scope_ends_1.out create mode 100644 tests/programs/closeable_values_close_where_their_scope_ends_1.sakura create mode 100644 tests/programs/compile_error_in_a_generic_property_1.out create mode 100644 tests/programs/compile_error_in_a_generic_property_1.sakura create mode 100644 tests/programs/compile_error_says_text_worked_out_while_compiling_1.out create mode 100644 tests/programs/compile_error_says_text_worked_out_while_compiling_1.sakura create mode 100644 tests/programs/compile_error_says_text_worked_out_while_compiling_2.out create mode 100644 tests/programs/compile_error_says_text_worked_out_while_compiling_2.sakura create mode 100644 tests/programs/compile_error_waits_for_evaluating_to_choose_its_branch_1.out create mode 100644 tests/programs/compile_error_waits_for_evaluating_to_choose_its_branch_1.sakura create mode 100644 tests/programs/compile_error_waits_for_evaluating_to_choose_its_branch_2.out create mode 100644 tests/programs/compile_error_waits_for_evaluating_to_choose_its_branch_2.sakura create mode 100644 tests/programs/compound_assignments_change_in_place_where_a_type_can_1.out create mode 100644 tests/programs/compound_assignments_change_in_place_where_a_type_can_1.sakura create mode 100644 tests/programs/const_declarations_1.out create mode 100644 tests/programs/const_declarations_1.sakura create mode 100644 tests/programs/const_pointers_1.out create mode 100644 tests/programs/const_pointers_1.sakura create mode 100644 tests/programs/constants_are_made_by_operators_of_methods_1.out create mode 100644 tests/programs/constants_are_made_by_operators_of_methods_1.sakura create mode 100644 tests/programs/constants_hold_functions_1.out create mode 100644 tests/programs/constants_hold_functions_1.sakura create mode 100644 tests/programs/constants_keep_the_memory_they_point_into_3.out create mode 100644 tests/programs/constants_keep_the_memory_they_point_into_3.sakura create mode 100644 tests/programs/constants_view_other_constants_1.out create mode 100644 tests/programs/constants_view_other_constants_1.sakura create mode 100644 tests/programs/contracts_1.out create mode 100644 tests/programs/contracts_1.sakura create mode 100644 tests/programs/contracts_2.out create mode 100644 tests/programs/contracts_2.sakura create mode 100644 tests/programs/contracts_3.out create mode 100644 tests/programs/contracts_3.sakura create mode 100644 tests/programs/contracts_4.out create mode 100644 tests/programs/contracts_4.sakura create mode 100644 tests/programs/contracts_5.out create mode 100644 tests/programs/contracts_5.sakura create mode 100644 tests/programs/contracts_6.out create mode 100644 tests/programs/contracts_6.sakura create mode 100644 tests/programs/control_flow_1.out create mode 100644 tests/programs/control_flow_1.sakura create mode 100644 tests/programs/core_alone_1.out create mode 100644 tests/programs/core_alone_1.sakura create mode 100644 tests/programs/decl_of_takes_a_type_a_declaration_makes_1.out create mode 100644 tests/programs/decl_of_takes_a_type_a_declaration_makes_1.sakura create mode 100644 tests/programs/default_trait_methods_1.out create mode 100644 tests/programs/default_trait_methods_1.sakura create mode 100644 tests/programs/default_values_belong_to_the_declaration_a_call_reaches_1.out create mode 100644 tests/programs/default_values_belong_to_the_declaration_a_call_reaches_1.sakura create mode 100644 tests/programs/dereferences_2.out create mode 100644 tests/programs/dereferences_2.sakura create mode 100644 tests/programs/enums_and_match_values_1.out create mode 100644 tests/programs/enums_and_match_values_1.sakura create mode 100644 tests/programs/enums_and_match_values_2.out create mode 100644 tests/programs/enums_and_match_values_2.sakura create mode 100644 tests/programs/equality_calls_what_a_type_says_it_means_1.out create mode 100644 tests/programs/equality_calls_what_a_type_says_it_means_1.sakura create mode 100644 tests/programs/equality_is_what_equals_says_1.out create mode 100644 tests/programs/equality_is_what_equals_says_1.sakura create mode 100644 tests/programs/errors_are_handled_where_they_are_made_1.out create mode 100644 tests/programs/errors_are_handled_where_they_are_made_1.sakura create mode 100644 tests/programs/faults_2.out create mode 100644 tests/programs/faults_2.sakura create mode 100644 tests/programs/faults_3.out create mode 100644 tests/programs/faults_3.sakura create mode 100644 tests/programs/fixed_arrays_hold_their_elements_1.out create mode 100644 tests/programs/fixed_arrays_hold_their_elements_1.sakura create mode 100644 tests/programs/for_const_counts_through_ranges_1.out create mode 100644 tests/programs/for_const_counts_through_ranges_1.sakura create mode 100644 tests/programs/function_types_naming_a_pack_are_what_each_instance_gives_1.out create mode 100644 tests/programs/function_types_naming_a_pack_are_what_each_instance_gives_1.sakura create mode 100644 tests/programs/functions_as_values_1.out create mode 100644 tests/programs/functions_as_values_1.sakura create mode 100644 tests/programs/functions_hold_any_callable_1.out create mode 100644 tests/programs/functions_hold_any_callable_1.sakura create mode 100644 tests/programs/generic_traits_1.out create mode 100644 tests/programs/generic_traits_1.sakura create mode 100644 tests/programs/generics_1.out create mode 100644 tests/programs/generics_1.sakura create mode 100644 tests/programs/generics_2.out create mode 100644 tests/programs/generics_2.sakura create mode 100644 tests/programs/globals_1.out create mode 100644 tests/programs/globals_1.sakura create mode 100644 tests/programs/if_const_calls_through_type_parameters_1.out create mode 100644 tests/programs/if_const_calls_through_type_parameters_1.sakura create mode 100644 tests/programs/if_const_compares_what_reflection_describes_1.out create mode 100644 tests/programs/if_const_compares_what_reflection_describes_1.sakura create mode 100644 tests/programs/if_const_names_the_type_a_parameter_is_1.out create mode 100644 tests/programs/if_const_names_the_type_a_parameter_is_1.sakura create mode 100644 tests/programs/indexes_read_through_references_1.out create mode 100644 tests/programs/indexes_read_through_references_1.sakura create mode 100644 tests/programs/indexing_gives_the_reference_at_gives_1.out create mode 100644 tests/programs/indexing_gives_the_reference_at_gives_1.sakura create mode 100644 tests/programs/inline_functions_run_as_called_1.out create mode 100644 tests/programs/inline_functions_run_as_called_1.sakura create mode 100644 tests/programs/inlined_calls_behave_like_calls_1.out create mode 100644 tests/programs/inlined_calls_behave_like_calls_1.sakura create mode 100644 tests/programs/integers_1.out create mode 100644 tests/programs/integers_1.sakura create mode 100644 tests/programs/invokable_values_1.out create mode 100644 tests/programs/invokable_values_1.sakura create mode 100644 tests/programs/is_tests_what_a_type_satisfies_1.out create mode 100644 tests/programs/is_tests_what_a_type_satisfies_1.sakura create mode 100644 tests/programs/iterator_adapters_1.out create mode 100644 tests/programs/iterator_adapters_1.sakura create mode 100644 tests/programs/jumps_take_a_condition_1.out create mode 100644 tests/programs/jumps_take_a_condition_1.sakura create mode 100644 tests/programs/lambdas_give_type_parameters_their_types_1.out create mode 100644 tests/programs/lambdas_give_type_parameters_their_types_1.sakura create mode 100644 tests/programs/literals_of_text_are_walked_1.out create mode 100644 tests/programs/literals_of_text_are_walked_1.sakura create mode 100644 tests/programs/local_functions_1.out create mode 100644 tests/programs/local_functions_1.sakura create mode 100644 tests/programs/logic_short_circuits_1.out create mode 100644 tests/programs/logic_short_circuits_1.sakura create mode 100644 tests/programs/loops_walk_iterators_1.out create mode 100644 tests/programs/loops_walk_iterators_1.sakura create mode 100644 tests/programs/matches_of_many_constants_go_straight_to_their_case_1.out create mode 100644 tests/programs/matches_of_many_constants_go_straight_to_their_case_1.sakura create mode 100644 tests/programs/math_functions_agree_everywhere_1.out create mode 100644 tests/programs/math_functions_agree_everywhere_1.sakura create mode 100644 tests/programs/maybe_references_are_one_word_1.out create mode 100644 tests/programs/maybe_references_are_one_word_1.sakura create mode 100644 tests/programs/methods_on_built_in_types_1.out create mode 100644 tests/programs/methods_on_built_in_types_1.sakura create mode 100644 tests/programs/methods_on_numbers_stand_beside_the_compilers_1.out create mode 100644 tests/programs/methods_on_numbers_stand_beside_the_compilers_1.sakura create mode 100644 tests/programs/methods_shadow_the_types_aliased_1.out create mode 100644 tests/programs/methods_shadow_the_types_aliased_1.sakura create mode 100644 tests/programs/module_exports_1.out create mode 100644 tests/programs/module_exports_1.sakura create mode 100644 tests/programs/modules_see_nothing_of_the_program_1.out create mode 100644 tests/programs/modules_see_nothing_of_the_program_1.sakura create mode 100644 tests/programs/named_functions_are_called_as_the_type_asks_1.out create mode 100644 tests/programs/named_functions_are_called_as_the_type_asks_1.sakura create mode 100644 tests/programs/names_of_core_give_way_1.out create mode 100644 tests/programs/names_of_core_give_way_1.sakura create mode 100644 tests/programs/narrow_scalars_are_referred_to_in_place_1.out create mode 100644 tests/programs/narrow_scalars_are_referred_to_in_place_1.sakura create mode 100644 tests/programs/nested_traits_run_1.out create mode 100644 tests/programs/nested_traits_run_1.sakura create mode 100644 tests/programs/nested_types_run_1.out create mode 100644 tests/programs/nested_types_run_1.sakura create mode 100644 tests/programs/operators_call_the_methods_of_ordered_and_numeric_1.out create mode 100644 tests/programs/operators_call_the_methods_of_ordered_and_numeric_1.sakura create mode 100644 tests/programs/operators_call_the_methods_of_ordered_and_numeric_2.out create mode 100644 tests/programs/operators_call_the_methods_of_ordered_and_numeric_2.sakura create mode 100644 tests/programs/operators_call_the_methods_that_give_them_1.out create mode 100644 tests/programs/operators_call_the_methods_that_give_them_1.sakura create mode 100644 tests/programs/operators_lend_constants_as_their_methods_take_them_1.out create mode 100644 tests/programs/operators_lend_constants_as_their_methods_take_them_1.sakura create mode 100644 tests/programs/operators_reach_generic_code_through_bounds_1.out create mode 100644 tests/programs/operators_reach_generic_code_through_bounds_1.sakura create mode 100644 tests/programs/ordinal_parameters_convert_to_and_from_integers_1.out create mode 100644 tests/programs/ordinal_parameters_convert_to_and_from_integers_1.sakura create mode 100644 tests/programs/overloads_1.out create mode 100644 tests/programs/overloads_1.sakura create mode 100644 tests/programs/packs_in_function_types_1.out create mode 100644 tests/programs/packs_in_function_types_1.sakura create mode 100644 tests/programs/packs_of_types_and_traits_1.out create mode 100644 tests/programs/packs_of_types_and_traits_1.sakura create mode 100644 tests/programs/packs_of_types_have_lengths_1.out create mode 100644 tests/programs/packs_of_types_have_lengths_1.sakura create mode 100644 tests/programs/packs_spread_move_their_values_1.out create mode 100644 tests/programs/packs_spread_move_their_values_1.sakura create mode 100644 tests/programs/parameters_take_default_values_1.out create mode 100644 tests/programs/parameters_take_default_values_1.sakura create mode 100644 tests/programs/path_of_names_the_modules_of_types_1.out create mode 100644 tests/programs/path_of_names_the_modules_of_types_1.sakura create mode 100644 tests/programs/pattern_parameters_1.out create mode 100644 tests/programs/pattern_parameters_1.sakura create mode 100644 tests/programs/pattern_parameters_2.out create mode 100644 tests/programs/pattern_parameters_2.sakura create mode 100644 tests/programs/pointers_and_manual_memory_2.out create mode 100644 tests/programs/pointers_and_manual_memory_2.sakura create mode 100644 tests/programs/properties_1.out create mode 100644 tests/programs/properties_1.sakura create mode 100644 tests/programs/properties_2.out create mode 100644 tests/programs/properties_2.sakura create mode 100644 tests/programs/properties_and_generic_methods_are_values_1.out create mode 100644 tests/programs/properties_and_generic_methods_are_values_1.sakura create mode 100644 tests/programs/property_accessors_1.out create mode 100644 tests/programs/property_accessors_1.sakura create mode 100644 tests/programs/ranges_are_values_1.out create mode 100644 tests/programs/ranges_are_values_1.sakura create mode 100644 tests/programs/ranges_count_through_enums_1.out create mode 100644 tests/programs/ranges_count_through_enums_1.sakura create mode 100644 tests/programs/references_1.out create mode 100644 tests/programs/references_1.sakura create mode 100644 tests/programs/references_are_kept_only_where_they_must_be_1.out create mode 100644 tests/programs/references_are_kept_only_where_they_must_be_1.sakura create mode 100644 tests/programs/references_are_lent_and_values_given_1.out create mode 100644 tests/programs/references_are_lent_and_values_given_1.sakura create mode 100644 tests/programs/references_reach_the_types_holding_them_1.out create mode 100644 tests/programs/references_reach_the_types_holding_them_1.sakura create mode 100644 tests/programs/references_stay_where_they_cannot_be_kept_1.out create mode 100644 tests/programs/references_stay_where_they_cannot_be_kept_1.sakura create mode 100644 tests/programs/references_to_new_values_1.out create mode 100644 tests/programs/references_to_new_values_1.sakura create mode 100644 tests/programs/refined_functions_as_values_1.out create mode 100644 tests/programs/refined_functions_as_values_1.sakura create mode 100644 tests/programs/reflection_reaches_declarations_by_name_1.out create mode 100644 tests/programs/reflection_reaches_declarations_by_name_1.sakura create mode 100644 tests/programs/reflection_spells_types_and_instances_1.out create mode 100644 tests/programs/reflection_spells_types_and_instances_1.sakura create mode 100644 tests/programs/signature_bounds_hold_wherever_their_parameter_is_declared_1.out create mode 100644 tests/programs/signature_bounds_hold_wherever_their_parameter_is_declared_1.sakura create mode 100644 tests/programs/signatures_1.out create mode 100644 tests/programs/signatures_1.sakura create mode 100644 tests/programs/simd_lanes_agree_everywhere_1.out create mode 100644 tests/programs/simd_lanes_agree_everywhere_1.sakura create mode 100644 tests/programs/simd_lanes_agree_everywhere_2.out create mode 100644 tests/programs/simd_lanes_agree_everywhere_2.sakura create mode 100644 tests/programs/simd_values_in_registers_1.out create mode 100644 tests/programs/simd_values_in_registers_1.sakura create mode 100644 tests/programs/static_trait_methods_1.out create mode 100644 tests/programs/static_trait_methods_1.sakura create mode 100644 tests/programs/strings_unions_shadowing_and_ternaries_1.out create mode 100644 tests/programs/strings_unions_shadowing_and_ternaries_1.sakura create mode 100644 tests/programs/structs_1.out create mode 100644 tests/programs/structs_1.sakura create mode 100644 tests/programs/structs_of_no_fields_are_returned_1.out create mode 100644 tests/programs/structs_of_no_fields_are_returned_1.sakura create mode 100644 tests/programs/swar_words_agree_everywhere_1.out create mode 100644 tests/programs/swar_words_agree_everywhere_1.sakura create mode 100644 tests/programs/ternaries_name_what_their_tests_give_1.out create mode 100644 tests/programs/ternaries_name_what_their_tests_give_1.sakura create mode 100644 tests/programs/ternary_branches_take_fallbacks_1.out create mode 100644 tests/programs/ternary_branches_take_fallbacks_1.sakura create mode 100644 tests/programs/text_constants_are_indexed_as_views_1.out create mode 100644 tests/programs/text_constants_are_indexed_as_views_1.sakura create mode 100644 tests/programs/text_is_a_view_of_the_program_own_bytes_1.out create mode 100644 tests/programs/text_is_a_view_of_the_program_own_bytes_1.sakura create mode 100644 tests/programs/text_is_split_lazily_1.out create mode 100644 tests/programs/text_is_split_lazily_1.sakura create mode 100644 tests/programs/text_spanning_lines_1.out create mode 100644 tests/programs/text_spanning_lines_1.sakura create mode 100644 tests/programs/text_spanning_lines_2.out create mode 100644 tests/programs/text_spanning_lines_2.sakura create mode 100644 tests/programs/text_spanning_lines_3.out create mode 100644 tests/programs/text_spanning_lines_3.sakura create mode 100644 tests/programs/the_compiler_gives_a_call_its_own_site_1.out create mode 100644 tests/programs/the_compiler_gives_a_call_its_own_site_1.sakura create mode 100644 tests/programs/the_receiver_chooses_the_overload_1.out create mode 100644 tests/programs/the_receiver_chooses_the_overload_1.sakura create mode 100644 tests/programs/threads_1.out create mode 100644 tests/programs/threads_1.sakura create mode 100644 tests/programs/trait_composition_1.out create mode 100644 tests/programs/trait_composition_1.sakura create mode 100644 tests/programs/trait_composition_2.out create mode 100644 tests/programs/trait_composition_2.sakura create mode 100644 tests/programs/trait_composition_3.out create mode 100644 tests/programs/trait_composition_3.sakura create mode 100644 tests/programs/trait_defaults_per_type_1.out create mode 100644 tests/programs/trait_defaults_per_type_1.sakura create mode 100644 tests/programs/traits_1.out create mode 100644 tests/programs/traits_1.sakura create mode 100644 tests/programs/traits_ask_for_types_1.out create mode 100644 tests/programs/traits_ask_for_types_1.sakura create mode 100644 tests/programs/traits_have_functions_of_their_own_1.out create mode 100644 tests/programs/traits_have_functions_of_their_own_1.sakura create mode 100644 tests/programs/traits_see_through_aliases_1.out create mode 100644 tests/programs/traits_see_through_aliases_1.sakura create mode 100644 tests/programs/type_parameters_given_references_pass_them_1.out create mode 100644 tests/programs/type_parameters_given_references_pass_them_1.sakura create mode 100644 tests/programs/types_implementing_indexable_are_indexed_1.out create mode 100644 tests/programs/types_implementing_indexable_are_indexed_1.sakura create mode 100644 tests/programs/types_implementing_indexable_are_indexed_2.out create mode 100644 tests/programs/types_implementing_indexable_are_indexed_2.sakura create mode 100644 tests/programs/types_name_their_own_without_them_1.out create mode 100644 tests/programs/types_name_their_own_without_them_1.sakura create mode 100644 tests/programs/union_fields_are_named_by_reference_1.out create mode 100644 tests/programs/union_fields_are_named_by_reference_1.sakura create mode 100644 tests/programs/unions_hold_what_is_given_1.out create mode 100644 tests/programs/unions_hold_what_is_given_1.sakura create mode 100644 tests/programs/unsigned_literals_1.out create mode 100644 tests/programs/unsigned_literals_1.sakura create mode 100644 tests/programs/values_are_called_through_invoke_1.out create mode 100644 tests/programs/values_are_called_through_invoke_1.sakura create mode 100644 tests/programs/values_kept_by_branches_not_taken_are_not_closed_1.out create mode 100644 tests/programs/values_kept_by_branches_not_taken_are_not_closed_1.sakura create mode 100644 tests/programs/variadic_arguments_are_closed_where_they_belong_1.out create mode 100644 tests/programs/variadic_arguments_are_closed_where_they_belong_1.sakura create mode 100644 tests/programs/variadic_function_values_1.out create mode 100644 tests/programs/variadic_function_values_1.sakura create mode 100644 tests/programs/variadic_functions_take_a_view_of_their_arguments_1.out create mode 100644 tests/programs/variadic_functions_take_a_view_of_their_arguments_1.sakura create mode 100644 tests/programs/variadic_generics_unroll_over_their_packs_1.out create mode 100644 tests/programs/variadic_generics_unroll_over_their_packs_1.sakura create mode 100644 tests/programs/views_are_indexed_and_walked_1.out create mode 100644 tests/programs/views_are_indexed_and_walked_1.sakura create mode 100644 tests/programs/views_of_fixed_arrays_write_where_the_array_can_1.out create mode 100644 tests/programs/views_of_fixed_arrays_write_where_the_array_can_1.sakura create mode 100644 tests/programs/void_is_a_value_of_its_own_1.out create mode 100644 tests/programs/void_is_a_value_of_its_own_1.sakura create mode 100644 tests/programs/when_runs_what_the_target_takes_1.out create mode 100644 tests/programs/when_runs_what_the_target_takes_1.sakura create mode 100644 tests/programs/writing_through_references_1.out create mode 100644 tests/programs/writing_through_references_1.sakura create mode 100644 tests/server/server.sakura create mode 100644 tools/corpus.sakura create mode 100644 tools/function.sakura create mode 100644 tools/iterators.sakura create mode 100644 tools/memory.sakura create mode 100644 tools/profile/__pycache__/inlined.cpython-314.pyc create mode 100644 tools/profile/annotate.py create mode 100644 tools/profile/costs.py create mode 100644 tools/profile/count.c create mode 100644 tools/profile/inlined.py create mode 100644 tools/profile/kinds.py create mode 100644 tools/profile/measure.py create mode 100644 tools/profile/sampler.c create mode 100644 tools/profile/samples.py diff --git a/.editorconfig b/.editorconfig new file mode 100644 index 00000000..53b061a8 --- /dev/null +++ b/.editorconfig @@ -0,0 +1,9 @@ +root = true + +[*] +indent_style = space +indent_size = 2 +end_of_line = lf +charset = utf-8 +trim_trailing_whitespace = true +insert_final_newline = true \ No newline at end of file diff --git a/.gitignore b/.gitignore new file mode 100644 index 00000000..cfecb95e --- /dev/null +++ b/.gitignore @@ -0,0 +1 @@ +.blossom diff --git a/CHANGELOG.md b/CHANGELOG.md new file mode 100644 index 00000000..5131505c --- /dev/null +++ b/CHANGELOG.md @@ -0,0 +1,236 @@ +# Changelog + +Each version's changes, newest first. Versions follow [semantic +versioning](https://semver.org). + +## Unreleased + +- Checking holds less and does less: of the compiler's own sources, the + analyzer's tables take 28 MB where they took 49, and checking them runs + 1,440 million instructions where it ran 1,900, with a fifth fewer cycles. + - A token keeps its kind, where it begins, and its name. How many bytes it + covers is its kind's, or its name's, and only a literal's is kept. A node + keeps where it ends in a byte, as how many tokens past its own. + - The token and node vectors are trimmed to fit once a file is read. + - A node's result flags take two bytes. The type it converts to and the + constant it is, which few nodes have, are kept by row in maps rather than + in columns mostly of zeros, and each constant is kept once. + - The checker's maps hold a key and a value, twelve bytes a slot, where a + `dict` took forty, and types, constants, and known values are found by + their hash in an index of IDs, eight bytes a slot. + - The resolver looks each path up by the IDs of its names, once for the + program, where it made the path's text again in each file, a tenth of + checking. + - The lifetime warnings walk each body on one stack, noting where its locals + are in a column by node, where they made a vector for each node and two + maps for each function, an eighth of checking. +- A frame zeroes a cell whose address a call is given, or an edge, only where + a word of it may not be written yet, and the copy of a function inlined + clears only the cells its own frame would zero, where it cleared every one: + the checker's `expr` cleared 1.9 KB on each call. Checking the compiler runs + 5% fewer instructions. +- `values_of` in a default argument evaluates the locals of the call where it + was written, rather than a parameter of the function whose default it is + with the same node in another file, which gave a wrong value, or none, as + `std::testing`'s `expects` did of a loop's variable, stopping the virtual + machine. +- `sakura::analyzer`'s interface changed: + - `source::open` takes the path alone, and `names::new` and `syntax::new` + take no allocator. + - `parser::new`, `syntax::reparse`, `syntax::print`, and `syntax::token` + take the names the tokens were lexed with, and `syntax::token_length` + gives a token's length, for `token_lengths`. + - `syntax::node_end` and `syntax::set_node_end` read and write where a node + ends, for `node_ends`. + - A `note` holds its `detail`, `instance`, and `related` as `string`s, so it + is moved rather than copied: `note_sink::give` and what hears notes take + `&mut note`, `checker::keep` is gone, and `report_text` and `warn_text` + take `&string`. + - The kinds of type are `ty`, for `tkind`, and the words the checker knows + are `word`'s members, constants, for `checker.words`. + - `resolver::refer` is given the program's one table of names for each file. + - `id_index` takes the place of `chains`, and `core`'s `trailing_zeros` of + `lowest_bit`. + +- Executables work `f32` arithmetic in single precision, `addss` and the rest, + where every reader rounds it to an `f32` anyway, which gives the same bits, and + hold `f32`s as `f32`s where every reader takes one, rather than converting + each way around every operation. +- The register allocator keeps a value a loop reads in every arm in one register + through the loop: one living across a call takes a register a call keeps from + a value read later, and none takes a register from a value read more often. + The virtual machine's loop does about half the work it did for each operation. +- A function calling one whose x86-64-v3 version is small enough to be inlined + gets a version too, so `simd`'s `fma` in a loop is one instruction there. +- `simd`'s `fma` is `vfmadd231ps` or `vfmadd231pd` alone. It also took the + product where it was NaN, five instructions more, to give the NaN std's `fma` + gave without FMA3, which gives the instruction's now. +- Splatting `f32`, `f64`, and 32-bit lanes shuffles within the register, and an + `f32` only splats read is held as an `f32` too, rather than converted to an + `f64` and back. +- A function returning memory copies it 16 bytes at a time, as callers read it + back, so the processor forwards the stores. +- Each function begins at a multiple of 16 bytes. +- The virtual machine works an `f32` arithmetic and its rounding as one + operation, and each arithmetic of reals as a case of its own. +- The virtual machine's loop keeps why it stops in a register: each check of + its steps gives the reason, rather than writing it where the loop read it + back every operation. +- A loop whose head jumps through a table, as the virtual machine's loop over + its operations does, begins that head at a multiple of 64 bytes, so it never + lies across two lines of the cache. The machine's loop ran 16% slower where + it did, as code before it grew or shrank. +- `@inline` copies a function, method, or property wherever it's called, at + every level, `-O0` too, whatever its size, and `core`'s word and byte tests + are `@inline`, so `-O0` searches of text no longer call a function for each + word. +- Debugging information keeps a variable whose value is a constant the + optimizer made where it's read, so gdb shows a parameter given a constant, as + `scale (by=2)`, at `-O2` too. +- A `compile_error` in a branch of `if const` that only running the condition + decides, as `if const size_of::() != size_of::()`, is reported once the + condition chooses that branch, by `check`, `run`, and `build` alike, rather + than stopping the program as it runs; one in a branch not chosen never is. +- `compile_error` says text it is given that isn't written, a constant's or text + worked out while compiling, as `$"{f.name} is not read"`, rather than "The + program reports an error here." +- The accessors of a generic type's property are checked for each instance a + value reaches, as a method called is, so a `compile_error` in one is reported + while checking, rather than stopping lowering without the note. +- `simd`'s `bits` refuses a vector of another size while compiling, rather than + stopping the program as it runs. +- `lanes_have` and `lanes_apply` take one real alone, worked with the + instruction of one number: `roundss` and `roundsd`, `sqrtss` and `sqrtsd`, and + `vfmadd231ss` and `vfmadd231sd`. +- Counting a word's ones, leading zeros, and trailing zeros is `popcnt`, + `lzcnt`, and `tzcnt` in a function's x86-64-v3 version, which asks for them. + `SAKURA_CPU` names `popcnt`, `lzcnt`, `bmi1`, `avx512`, and `x86-64-v4` too. +- `simd`'s lanes are worked with instructions where they were a lane at a time: + `*` of every width of integer, the least and greatest of 64-bit lanes, `abs` + and `>>` of `i64`, shifts of bytes, `round`, `sum`, the `product` of reals, + the `smallest` and `largest` of integers, `shuffle`, by `pshufb` and across 32 + bytes `vpermd`, `convert`, and gathering. A constant vector, as a splat of a + constant, is read from constants written after the function. +- `simd` has `low` and `high`, the halves of 32 bytes, `join`, of two of 16, + `widened` and `widened_high`, each lane twice as wide, `narrowed`, half as + wide and saturated, `gather`, and `scatter`. +- Vectors of 64 bytes, of 16 bits a lane or more: `f32x16`, `f64x8`, `i16x32`, + `u16x32`, `i32x16`, `u32x16`, `i64x8`, and `u64x8`. Executables work them with + AVX-512 where the processor has it, which an x86-64-v3 version still asks, + and a half or a quarter at a time where it doesn't. +- The stores filling 16 bytes of a struct, four `f32`s or two words, are merged + into one store of a vector, so a struct returned in memory is copied out + without waiting on each field: `linear`'s `cross` takes 12 cycles where it + took 30, and `quat * quat` 18 where it took 35. +- A narrow integer held as a value is wrapped once, where it was wrapped again + as each field read and through each loop's parameter, so a loop of + `vec3` arithmetic takes 11 ms where it took 17. +- The register allocator weighs values by how often they're read only where they + live in a loop. Elsewhere it spills the value read furthest ahead, rather than + each value as it's made, which it read straight back, as `linear`'s + `mat4::inverse` did with nearly every product. + +## 1.0.0 - Unreleased + +- The first version of `sakurac`, the Sakura compiler, written in Sakura and + built by itself. It holds: + - the command line: `check`; `run`, on the virtual machine; `build`, of + standalone x86-64 executables for Linux and Windows, with no assembler, + linker, or C library; and `lsp`, the language server; + - the language as the README describes it; + - `core`, `system`, and the runtime, in `runtime`, found beside the compiler, and + the standard library; + - checked programs, with `run --checks` checking memory too, and contracts, + which `--contracts off` leaves out; + - debugging information, as DWARF, and for Windows as a PDB file too; + - the tests, run with `blossom test`. +- Its parts are libraries of this repository, each in the folder of its name + with its tests in `tests/`, and exported for other projects to read: + - `sakura::analyzer`: the lexer and parser, with reparsing after an edit; the + checker, with checking again after an edit and the evaluation of constants; + the resolver finding a program's library files; and the queries the language + server answers with; + - `sakura::compiler`: lowering a checked program to intermediate code, + verifying and optimizing it, and assembling each function into the + machine's code, on threads, with the same result however many there are; + - `sakura::machine`: the virtual machine `run` runs programs on, with its + heap, its threads, and its calls to the system and to C; the memory checks + `run --checks` asks for; and the evaluation of constants while compiling; + - `sakura::native`: x86-64 executables for Linux as ELF and for Windows as PE; + the selection of instructions, with SSE and AVX for a `simd`'s lanes; the + register allocator, and the checker replaying what it chose; calls to C and + from it; and the debugging information, as DWARF and as a PDB file; + - `sakura::server`: the language server `lsp` serves, with diagnostics, + hovering, completion, signature help, colouring, going to a declaration, + finding references, and renaming, each job in a process of its own; and + `toolchain_folder`, which finds `core`, `system`, and `runtime`. +- Each was a package of its own, at version 1.0.0, from 2026-10-25 or 2026-10-26 + until it came back on 2026-10-26. +- The standard library is a repository of its own, `sakura/std`, each module + a library of its own, which it requires, naming the modules each of its + libraries reads. Its tests went with it, but for those of `core` and + `system`, which ship with the compiler, as `tests/core`. +- `core` holds only what the compiler names, or what that, `system`, and the + runtime are built from: + - `dict`, `hashset`, `rc`, `arc`, and `arena` are std's, as are the streams' + traits, `readable`, `writable`, and `flushable`, with `string`'s `write` + and `strview`'s `read`, so the built-in `string` names no `writable`; + - `io_error` is `system`'s; + - `core::intrinsics` holds `square_root`, `lanes_have`, and `lanes_apply`, + which `std::math` declared, and `system` holds `start`, which + `std::thread` did, so std declares no intrinsic. +- The standard library is the folder `--lib std=DIR` names, else a `std` + folder beside the compiler or above it, else its libraries in the + `share/sakura` folder above it, where `blossom install` puts them. `--std` + and `SAKURA_STD` are gone, and `sakurac lsp` finds it the same way. +- `install` puts `system` beside `core` and `runtime`. +- It requires packages for the standard library, `std::args` and `std::json` + among it, and for the back end's libraries, in `binary`. +- Fixed, from what building `hearth` met: + - `close(x)`, which a `box` and the containers close what they hold with, + closed a value's own `close` but not its fields after, as a scope ending + does, so what the fields held leaked; and generic code closing a type of + another module whose `close` isn't `pub` was refused. It's the compiler's + own closing now, `close_where_it_is`. + - `f(...xs)` copied a pack's values that close to the function given them, + so both closed them; it moves them. + - An anonymous function whose parameters' types are written gives its type + to a type parameter where overloads are chosen between, and to the type + parameters a function type leaves unknown, as `T` of `def(&T): bool`, + where before neither was given and the call was refused. + - `? :` names what its condition's `is` tests give, as `if` does. + - `for` walks a literal of text, as the `strview` it settles as. + - A pack of types has a `length`, as `Ts.length`. + - A folder holding a module's file and the one file of a module within it, + as `nest/nest.sakura` and `nest/deeper.sakura`, was taken for the deeper + module's alone, by its first file, which hid the folder's own module. + - A file beginning with UTF-8's byte order mark is read past it. + - `decl_of` of a type no declaration makes, as a reference, is refused where + it's checked, rather than failing as it's lowered. + - The checker's columns are given back as a checker closes, which the + language server leaked a checker's worth of with each check. + - Notes: a property called, as `m.is_none()`, says it's a property; and a + copy an `is` test names, written, says `&mut` names the reference. + - `is some(_)`, `is not some(_)`, and an arm's `some(_)` took a field that + closes out of the union and closed it, through a reference too, so the + union's owner lost it; `_` names nothing, and takes nothing. + - The condition of an `if const` within a pass of `for const` over + reflection, where only evaluating decides it, as `d.name == "x"`, couldn't + read the pass's description, which evaluating's function never declared. +- `path_of::()` spells a type with the module of each type it names, as + `&mut game::position`, which no two types share, as `name_of` doesn't. +- `sakura::machine` is embeddable, as `hearth::scripting` runs scripts: + - `begin` gives a program's globals their values without calling `main`, and + `call` and `call_value` call a function, or a function value, given the + words of its parameters, `result` giving the words it returned; + - `provide` gives a foreign declaration's name a function of the host's, as + a `cfn`, found before any library's, which may call back into the program, + a fault there stopping the calls under way as the host returns to them; + - `interpreting::steps` stops a call taking more steps than that, with the + new `halt::step_limit`; + - `interpreting::capture`, `stack`, and `steps` are `pub`, and `take_output` + gives what was kept; on Windows it keeps what `WriteFile` and + `WriteConsoleW` write to the output and error, as it kept Linux's `write` + alone before; + - a fault in a function C called back keeps the trace of where each function + was, which the program's call of C ending forgot. diff --git a/LICENSE b/LICENSE new file mode 100644 index 00000000..b8bae395 --- /dev/null +++ b/LICENSE @@ -0,0 +1,18 @@ +MIT License + +Copyright (c) 2026 Malunal Studios, LLC. + +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/README.md b/README.md new file mode 100644 index 00000000..e757c2ca --- /dev/null +++ b/README.md @@ -0,0 +1,1207 @@ +# 🌸 Sakura +Sakura is a statically typed, compiled programming language. Values are immutable unless declared `var`, traits are satisfied by shape rather than by name, and errors are values. Programs run on a virtual machine, or as standalone x86-64 executables for Linux and Windows that behave identically. Source files use the `.sakura` extension. + +This repository is `sakurac`, the compiler, written in Sakura, with the libraries every program reads. + +```sakura +import std::io; + +# A union holds one of its fields at a time, and knows which. +union shape { + var circle: f64; # radius + var rect: f64[2]; # width and height +} + +def shape::area(&this): f64 { + return match this { + circle(r) => 3.14159 * r * r, + rect(s) => s[0] * s[1], + }; +} + +# Traits are satisfied by shape: anything with an `area` method is `sized`. +trait sized { + def area(&this): f64; +} + +# Generics are bounded by traits, and each use is compiled for its type. +def largest(items: span): f64 where T: sized { + var best := 0.0; + for item in items { + best = item.area() > best ? item.area() : best; + } + return best; +} + +def main(args: span): void { + val shapes: shape[3] = [ + shape{ circle = 1 }, + shape{ rect = [2, 3] }, + shape{ circle = 0.5 }, + ]; + + for i, s in shapes { + println($"shape {i}: area {s.area()}"); + } + println($"largest: {largest(shapes[:])}"); +} +``` +``` +shape 0: area 3.14159 +shape 1: area 6 +shape 2: area 0.7853975 +largest: 6 +``` + +## Contents +1. [Getting started](#getting-started) +2. The language: [modules](#programs-and-modules), [types](#variables-and-types), [structs, unions, and enums](#structs-unions-and-enums), [control flow](#control-flow), [errors](#errors), [faults](#faults), [contracts](#contracts), and [checks](#checks), [functions](#functions), [methods](#methods-and-properties), [traits](#traits), [generics](#generics), [ownership](#closing-copying-and-moving), [compile time](#compile-time), [pointers](#pointers-and-memory), and [C](#calling-c) +3. [The standard library](#the-standard-library) +4. [Executables, debugging, and editors](#executables-debugging-and-editors) +5. [This repository](#this-repository) +6. [Grammar](#grammar) +7. [License](#license) + +--- + +## Getting started +> **Note:** the language, toolchain, and standard library are still changing. + +`sakurac` is built and tested with [blossom](https://git.malunal.studio/sakura/blossom), which clones the packages it reads (see [This repository](#this-repository)). Building it takes a `sakurac` already: the one blossom's config names, or else the first on `PATH`. The corpus, the tests of finding libraries, and the native backend's read the standard library's [repository](https://git.malunal.studio/sakura/std) checked out beside this one, as `../std`. +```sh +blossom build # writes .blossom//bin/sakurac +blossom test # builds it, then runs the tests, the corpus by the sakurac just built +blossom install --prefix ~/.local # sakurac in ~/.local/bin, with core, system, and runtime in ~/.local +``` +The standard library is installed from its repository the same way, into `~/.local/share/sakura`, where `sakurac` finds it. + +```sh +sakurac run main.sakura util.sakura -- one two # check, then run `main` on the VM with the arguments after `--` +sakurac run --checks main.sakura # run with its memory checked too (see Pointers and memory) +sakurac run --fast main.sakura # run without checks, as a build is (see Checks) +sakurac check main.sakura # check only +sakurac check --checks-report main.sakura # list the checks left in the program's own code, by line +sakurac build -o hello main.sakura util.sakura # check, then write a standalone executable, hello.exe on Windows +sakurac build -O0 -g -o hello main.sakura # unoptimized, with debugging information in hello.petal, or hello.pdb and hello.exe +sakurac build --checks -o app main.sakura # an executable that checks indexes and the rest, as `run` does +sakurac build --contracts off -o app main.sakura # with every `expects`, `asserts`, and `ensures` left out +sakurac build --lib geometry=../geometry -o app app.sakura # with a library of its own name: `import geometry;` reads ../geometry +sakurac run --lib sakura::analyzer=analyzer app.sakura # one within another module: `import sakura::analyzer;` +sakurac run --lib std=../std app.sakura # the standard library in the folder named, rather than the one found +sakurac check --deps app.deps app.sakura # also writes the path of each file the program read +sakurac lsp # a language server, over standard input and output +``` +`sakurac --help`, and `--help` after each command, list every option. + +**Libraries**: every program reads `core`, the language's own: the types the syntax makes, the traits the compiler reads, and what those, `system`, and the runtime are built from, as `vector` and `box`. Every file sees its names with no import. A program reads the rest only where its files refer to it, by an import or a path, and what that refers to in turn: one printing a line reads `core`, `std::io`, and `system`, and none of JSON. See [The standard library](#the-standard-library). +- **`core/`, `system/`, and `runtime/`** are the compiler's own, found beside the `sakurac` executable or in the nearest folder above it that holds them. Nothing names them. `runtime/` holds the module `runtime`, which is read only for an executable, and needs nothing of std, so a program importing nothing of std builds without it. +- **The standard library**, a [repository of its own](https://git.malunal.studio/sakura/std), is the folder `--lib std=DIR` names, or else a `std` folder beside the executable or in the nearest folder above it, as `core` is found, or else its libraries in the `share/sakura` folder nearest above it, where `blossom install` puts them, as `share/sakura/std.io` for `std::io`. No other option or variable names it. blossom gives each of its modules a target lists with `--lib`, as `--lib std::io=DIR`. +- **Other libraries** are named by `--lib NAME=DIR`, once for each, and imported by their names. `NAME` is the module the directory is, which may be within another, as `std::json` or `sakura::analyzer`. A module is found in the library whose name is the most of its path, so `--lib std::json=DIR` holds `std::json` and the standard library the rest of `std`, and two libraries may be within one module that is in none, as `sakura::analyzer` and `sakura::machine`. `sakurac lsp` takes them too. +- **`--deps FILE`** writes the path of each file the program read, one to a line. + +**Statuses**: `check`, `run`, and `build` end with 2 where the program has notes, or the command is wrong, and `check` with 0 otherwise. `run` ends with the program's own status, and `build` with 0 once the executable is written. + +--- + +## Programs and modules +A program is one or more files with one `main`, `def main(): void` or `def main(args: span): void`. Comments start with `#`, and documentation comments with `#!`. `::` reaches into a module or type (`std::io`, `color::red`), and `.` into a value (`p.x`, `p.length()`). + +```sakura +import std::io; # imports come first, +import std::math; + +module geometry; # then a module, which holds the rest of the file + +pub struct rect { + pub var width := 0f; # a field other modules reach, as they do a `pub` method + pub var height := 0f; +} + +pub def rect::area(&this): f32 { return this.width * this.height; } +``` +- **Modules** have no braces, and may span several files. `geometry::shapes` is a module within `geometry`. Files without a `module` declaration are the program itself, which nothing imports. +- **Visibility**: a module sees what it declares, and what the modules holding it declare, with no import. Where no file of a module holding it is read, as a library's root left out, a name it would see is not declared, and the note says which module has no file. Everything else must be `pub`. A field takes its own `pub`, as does what is declared outside a type, as `pub def rect::area`, so a struct's fields are private to its module unless marked. A literal may leave a private field out, which then takes its default or zero value. Enum members are as visible as their enum, and a type parameter reaches what its bounds ask for, `pub` or not. +- **Imports** bring a module's names into one file, without its submodules. The nearest name wins: a local's, then what the types around it give (see [Methods and properties](#methods-and-properties)), then the current module's, then those of the modules holding it, then imports, then the built-in types and the names of `core`'s root, which every file sees. A name both a type around it and its module give, or two imports give, is told apart by path, as `token::kind` or `io::println`. Anything a program declares or imports hides a name of `core`'s, which `core::vector` still names. +- **Paths**: a full path needs no import, as `system::exit(0)`, and reads the module it names. A path's first name is a module's, where a module of that name is seen, before a type's, so a module isn't named as a type it declares: `std::net` holds `uri`, and `uri::parse` reaches the type. +- **Methods declared on another's type**, as `std::math` declares `sqrt` on a `simd`, or a module on `u8`, are seen within that module and where a file imports it, and `core`'s everywhere. So `std::io` declares `write` on a `string`, which is `writable` only where it's imported. What a file means doesn't hang on what another file of the program imports. +- **A member declared on `core`'s type** with a name `core` gives that type too, method or property, is chosen over `core`'s wherever it is seen, and `core`'s only where none of its overloads takes the call's arguments. So `core` adding a member never refuses a program or takes its calls, and `core`'s own code keeps calling its own. A type declared through `core`'s, as `type bool::storage = bit;` for a trait asking for one, is kept apart the same way. +- **A library's modules are found by their paths**: in the library `std`, `std::a::b` is the folder `a/b`, or the one file `a/b.sakura`. A file or folder within a module's folder belongs to it where its first `module` line says so, and is otherwise a module of its own, as `std/testing.sakura` is `std::testing`. + +--- + +## Variables and types +```sakura +val x := 10; # immutable, type inferred +var y: f32 = 2.5; # mutable, type written +var count: u64; # starts at its zero value +var buffer: u8[4096] = undefined; # left as its memory happens to be +const page: u64 = 4096; # worked out while compiling +_ = io::write_file(at, "text"); # `_` lets go of what nothing reads +``` +A block declares each name once: a second `val x` in the same block is refused, as is one after an `is not` test names `x` for the rest of the block. A parameter, a block within, a loop's body, or a function within may declare a name again, hiding the one around it. + +The **zero value** of numbers is `0`, of pointers `null`, of enums the member whose value is `0`, and of unions their first field's. Arrays and structs are zeroed element by element and field by field, and struct fields take their defaults. References and functions have none, so they are always given a value. + +**`= undefined`** leaves a `var` as its memory happens to be, for a buffer the program fills before it reads it, which then costs nothing to declare. Only a local `var` with its type written takes it, of a type that has a zero value and closes nothing. Reading one before writing it is the program's mistake, which `run --checks` stops at. Elsewhere `undefined` is a name. + +**`void`** is a type of one value, `void {}`, which holds nothing and takes no bytes: what a function giving nothing gives. It is a type argument, a field, a local, or an element as any type is, so generic code serves it as any other, and `result` says only whether something failed. + +| Built-in type | | +|---|---| +| `i8` `i16` `i32` `i64`, `u8` `u16` `u32` `u64` | Integers. `int` is `i64`, and `uint` is `u64` | +| `f32` `f64` | Floats. `float` is `f64` | +| `bool`, `void` | `void`'s one value is `void {}` | +| `T[n]` | A fixed array of `n` elements | +| `&T`, `&mut T` | A reference that reads, or also writes | +| `*T`, `*mut T` | A raw pointer that reads, or also writes. It may be `null` | +| `def(T, U): R` | A function. `def(T, U...): R` takes any number of `U`s last | +| `cfn` | The address of a C function. It may be `null` | + +Text and dynamic arrays come from `core`, and the other containers from `std::containers`, imported: + +| Type | | +|---|---| +| `span`, `slice` | A view of elements that reads, or also writes | +| `strview` | Read-only text, the alias of `span` with text's methods. Literals are `strview`s | +| `string` | Text it owns, and can grow | +| `vector` | A dynamic array, `core`'s | +| `dict`, `hashset` | Values by key, and values held once, found by their hashes | +| `list`, `stack`, `queue`, `deque`, `chain` | Lists, stacks, queues, and the rest | +| `interner` | Gives each distinct value an ID, counted from 0 in the order values are first given, and reads it back by ID | +| `heap` | Keeps its least value first, for `peek` and `pop` | +| `runs`, `groups` | Many short lists in one block: named by an ID as each is added, or gathered by a key in two passes | +| `byte_writer` | `std::io`'s: bytes laid out one after another, words least significant byte first, alignment, and lengths written once known | +| `maybe`, `result` | A value that may be missing, or have failed (see [Errors](#errors)) | + +- **Conversions**: a number widens to a larger type of its kind, and an unsigned integer to a larger signed one. Anything else needs `as`: `3.9 as i32` is `3`. A reference converts as the value it refers to, so `(&x) as u64`, which would be `x` rather than its address, is refused: the address is `&x as *u8 as u64`. A reference written as one, `&x` or `&mut x`, is a pointer where one at its type is expected (see [Pointers and memory](#pointers-and-memory)). +- **Mixed operands**: integers of different signs compare exactly. An integer and a float operate as the float. Signed and unsigned arithmetic needs `as`. +- **`%`** on floats takes the dividend's sign, as C's `fmod` does. +- **Booleans** are not numbers: write `if count != 0`. `flag as u8` is `0` or `1`. +- **Aliases**: `type meters = f32;` converts to and from `f32` implicitly, and takes methods of its own. Arithmetic, bitwise operators, and shifts keep an alias their operands are written with, the right operand's where it is the number they operate as: `a | b` of two `mask8`s is a `mask8`, with its methods, while `mask | u64` is a `u64`. + +| Literal | Type | +|---|---| +| `42`, `0xFF`, `0o17`, `0b101` | `i64`, or the integer type expected | +| `0u`, `0xFFu` | `uint`, or the unsigned type expected. It cannot be negated | +| `3.14`, `6.02e23`, `2.5f` | `f64`, or `f32` with `f` | +| `'a'`, `'\n'`, `'é'` | Its code point, a `u32` | +| `"text"` | `strview`, or `string` where one is expected | +| `$"x = {x}"` | An interpolated `string` | +| `[1, 2, 3]` | A `T[3]`, or a `span` of itself where one is expected | +| `null` | Any pointer | + +Escapes are `\n` `\t` `\r` `\0` `\\` `\'` `\"`, `\{` and `\}` in interpolation, and `\xHH`. Text between `"""` lines spans lines, with the indentation of the closing `"""` removed from each. + +### Arrays, references, and views +```sakura +var bytes: u8[64]; # 64 zeroed bytes, held inline +const table: i64[4] = [10, 20, 30, 40]; +val middle := table[1:2]; # a span of 20 and 30 + +def grow(xs: &mut vector): void { xs.append(9); } +var numbers := vector::::new(); +grow(numbers); # referred to as though `&mut` were written +``` +- **Fixed arrays** have a length known while compiling, and are values: assigning one copies it. Indexing outside one stops a checked program, and one that isn't reads or writes past it, as C does (see [Checks](#checks)). `a[start:count]` is a view, a `slice` of a `var` array and a `span` of a `val` one, and either end may be left out, as `a[:]`. A view is narrowed the same way, as `text[2:]`, into a view of the same kind, and a range past its end stops a checked program. +- **References** are never `null`, and are read through, however deep, to what they refer to. They never stack: `&` of a reference is that reference, wherever it is held, and `&mut` of one writes where it does, as `&mut held` of a `held` an `is some(&mut held)` names. Assigning to one writes what it refers to, a reference's too, while a `var` given a reference written as one, `r = &mut y`, refers elsewhere. +- **Where a value goes says what happens to it**: a reference type lends it, and any other type gives it. Only `&` or `&mut` written, or a reference parameter at a call, makes a reference, so a binding, a pattern, and `for` take the value a reference reaches, copied where it closes nothing, as are a variable's and a field's: `val x := v[i]` and `for x in v` copy, while `val x := &v[i]`, `for &x in v`, and `is some(&x)` refer. What closes is refused rather than copied (see [Closing, copying, and moving](#closing-copying-and-moving)). A reference to a trait is taken as it is, since no value is of a trait. +- **Validity**: a reference or view into memory that moves or is released, as a vector's elements do when it grows, or into a local whose function has returned, no longer refers to anything, as in C++. The checker warns where it is sure, and `run --checks` stops where one is used (see [Pointers and memory](#pointers-and-memory)). +- **Views** come from slicing, from containers (`v.view()`, `s.view()`), and from `span::::over(data, length)`. A `slice` converts to a `span`, and `==` compares their elements. +- **`get(i)`** gives a `maybe` of the element at an index, or `none` past the end, on every view and container that is indexed, for an index that may be past the end in a program that is right. + +### Text +```sakura +val plain := "hello"; # a strview of the program's own bytes +val owned: string = "hello"; # a copy, which `owned` owns +val built := $"{plain}, world"; # interpolation makes a string +println(built); # a string lends a view wherever one is wanted +``` +A literal's bytes last as long as the program, followed by a zero byte, so they can be given to C. `==` compares two strings or two views. Comparing a string with a view needs `.view()`. + +### Equality and order +`==` works on numbers, `bool`, enums, pointers, and fixed arrays of them, and on any type implementing `equatable`, as views, strings, and containers do. Floats compare by value, so `0.0 == -0.0`. A reference compares what it refers to, and a pointer its address. `<` works on numbers, enums, pointers, and what implements `ordered` (see [Operators](#operators)). + +--- + +## Structs, unions, and enums +```sakura +struct vec2 { + var x := 0f; # a default, type inferred + var y := 0f; +} + +val a := vec2{}; # defaults and zero values +val b := vec2{1, 2}; # positional +val c := vec2{y = 8, x = 5}; # named, in any order +val vec2::zero := vec2{}; # an associated variable, read as `vec2::zero` +``` +A `val` field cannot change once made. A generic type has no associated variables, since each instance would need its own: an alias of one instance has them, as `val vec3f::zero`. `var pos: ...point { x as left };` spreads the fields of `point` into the struct, here renaming `x`. + +A **union** holds one of its fields at a time, and knows which: +```sakura +union reply { + var error: i32; + var data: T; +} + +var r: reply = 5; # holds `error`, the only field 5 fits +r = "fine"; # now holds `data` +if r is data(text) { println(text); } # names the field's value where the test holds +val held := r.data; # stops the program if `r` holds another field +``` +- **Making one**: a value becomes the field it fits. Where it fits several, name the field: `reply::{ error = 5 }`. +- **Testing**: `r is data` and `r is not data`. `is data(x)` names the value wherever the test holds, as in its branch, on the right of `&&`, and in the first branch of `? :`, as `m is some(v) ? v : 0`. `is not data(x)` names it wherever the test failed, such as after an `if` that leaves, or in the second branch of `? :`. `&x` or `&mut x` refers to the field in place, and `_` names nothing, so `is data(_)` and an arm's `data(_)` take nothing out, as `is data` doesn't. `is` with a type asks the value's own type, so `m is nothing` of a `maybe`, never true, is refused: write the field, `m is none`. +- **Referring**: `&r.data` refers to a field only where what it refers to closes nothing, and `&mut r.data`, or `&mut` of anything within a field, never, since the union could hold another field before the reference is used. A test names it where it is held, as `if r is data(&mut x)`. +- **Changing**: assigning a field switches to it. A field cannot be changed in place. +- **Size**: a union of an empty field and a reference, a reference to a trait, or a function value, as `maybe<&T>`, is no larger than the reference: it holds `null` for the empty field. + +An **enum** is a set of named integers: +```sakura +enum color: u8 { red, green = 4, blue } # 0, 4, 5 +enum level { low = -1, mid, high } # held as an i32 where no type is given +``` +An enum converts to its integer implicitly, and an integer to an enum with `as`, which stops the program unless the integer is some member's value. Enums print as their member's name, and their zero value is the member whose value is `0`. + +Structs, unions, and enums all take methods, associated variables, and nested types. + +--- + +## Control flow +```sakura +if n < 0 { ... } else if n == 0 { ... } else { ... } +val sign := n < 0 ? -1 : 1; + +while running { ... } +for name in names { } # a reference to each element +for i, name in names { } # with its index +for &mut n in counts { n += 1; } # changing each in place +for i in 0..10 { } # 0 up to 9 +for i in 1..=10 { } # 1 up to 10 +for i in (0..10).rev().step(3) { } # 9, 6, 3, 0 +for c in color::red..=color::blue { } # each member of `color` from red to blue + +return "negative" if n < 0; # guards keep early exits flat +continue if name.length == 0; +break if i > limit; +``` +- Assignments are expressions. `x++` and `x--` give the value from before. +- `for` walks fixed arrays, views, and anything `iterable`, as `core`'s containers are: `iter()` lends an `iterator`, whose `next()` gives a `maybe` of each element. It also walks any iterator, from where it is, so a loop that stops early leaves the rest for the next. `for x` takes a copy of each element, `for &x` refers to it, and `for &mut x` writes it in place. What a loop's iterator gives by value, as each `string` of `for line in input.lines()`, is the pass's own, closed where that pass ends. +- **Ranges** are values: `a..b` and `a..=b` are `core`'s `range` of the integers their ends are, or of the type expected, as `val r: range = 0..9;` or a `range` given for an `iterator`. A loop counts through one written in place without making it. Members of one enum make a range of its members, given in the order of their values, each value once and those no member has passed over, so `color::red..=color::blue` gives `red`, `green` and `blue` of `enum color: u8 { red, green = 4, blue }`. Within a generic, the ends may be any `ordinal` type parameter, which one bounded by `integer` is. + +**Iterators** take adapters, which make an iterator of another, and consumers, which walk one to its end. Each is compiled for the iterator it is called on, so a chain of them over a view runs as fast as the loop written out: +```sakura +val total := v.iter().copied().filter(def(x) => x % 2 == 0).map(def(x) => x * x).sum(); +val parts := line.split(',').to_vector(); # text is split as it is walked +for p in names.iter().zip(scores.iter()) { println($"{p.first}: {p.second}"); } +val longest := words.iter().max_by_key(def(w) => w.length) else { return; }; +``` +The adapters are `map`, `filter`, `filter_map`, `enumerate`, `zip`, `chain`, `take`, `skip`, `take_while`, `skip_while`, `step`, `rev`, `peekable`, `flat_map`, `copied`, and `inspect`; the consumers `count`, `sum`, `product`, `fold`, `reduce`, `any`, `all`, `find`, `position`, `min`, `max`, `min_by`, `max_by`, `min_by_key`, `max_by_key`, `last`, `nth`, `for_each`, `to_vector`, `to_string(between)`, and `into(&mut target)`, which appends to anything `extendable`. An adapter moves what it is called on into what it makes. `rev` is there for what walks from its far end, a `backward_iterator`, and `sum` for numbers. + +**`match`** runs the first arm that fits. A union's arms name fields, an enum's name members, and anything else's list values. Matching a union or enum must cover every case, or end with `else`: +```sakura +match held { + number(&mut n) => n += 1; + text(t) => println(t); + else => return; +} + +val label := match c { red => "stop", green, blue => "go" }; +``` + +--- + +## Errors +A mistake in the program stops it, as indexing past the end does. What can go wrong in a correct program, such as a missing file, is a value: a `result` holding its `value` or its `error`, or a `maybe` holding `some` or `none`. +```sakura +enum parse_error { empty, not_a_number } +def parse(text: strview): result { ... } + +val port := parse(arg) else 8080; # a value in its place +val n := parse(text) else (e) { return e; }; # a block that leaves, naming the error +if parse(text) is not value(v) { return; } # `v` is named from here on +val wide := big ? parse(text) else 0 : 1; # `else` within the branch `:` ends +val doubled := parse(text).map(def(n) => n * 2); # a result of what `map` makes of the value +``` +`result` is `@nodiscard`, so dropping one is an error, and `_ = parse(text);` drops it on purpose. `@nodiscard` marks any function or type this way. + +A `result` says only whether something failed. `return;` gives its value, and a block after `else` may end rather than leave, since there's no value to stand in for: `io::write_file(at, text) else (e) { warn(e); };`. + +A value that closes has one owner, so `else` takes over what a call made, but not what a variable holds, nor a union's field, whose union still closes it: name it in place with `is value(&v)`, then copy or move it by name. + +Both have methods for what `else` and `is` don't say as briefly: +- **Asking**: `is_some` and `is_none` of a `maybe`, and `is_ok` and `is_err` of a `result`, are properties. `is_some_and(test)`, `is_ok_and(test)` and `is_err_and(test)` test what it holds too. +- **Reading**: `unwrap()`, `expect(why)` and `unwrap_or(fallback)` give the value, and a `result`'s `unwrap_err()` and `expect_err(why)` its error, stopping the program where it holds none. From what can be written they move it out, as `move` does, so one holding what closes is left empty. From what is only read they copy it, which a value that closes refuses. `unwrap_or_else(make)` calls a function only where there's no value. +- **Making others**: a `maybe`'s `map`, `and_then`, `filter`, `or`, `or_else` and `ok_or(error)`, and a `result`'s `map`, `map_err`, `and_then`, `or_else`, `to_maybe` and `err_to_maybe`, move what it holds into what they make, as an iterator's adapters do. `as_ref()` and `as_mut()` lend what it holds to them instead. `take()` empties a `maybe`, and `replace(value)` puts another value in, each giving what it held. +- **Comparing**: both compare with `==`, hash, and copy where what they hold does. A `result` whose value and error are of one type tells them apart. + +### Faults +A fault stops the program with a trace and exit status `1`: every program's at `null` reached through and dividing by zero, and a checked program's at an index out of bounds and the like, as `run`'s is (see [Checks](#checks)): +``` +sakura: runtime error: Index or slice is out of bounds. + at pick (trap.sakura:5:12) + at main (trap.sakura:11:18) +``` +A program stops itself the same way with `fault(why)`, whose text the report gives, as the containers do where they're asked for what they don't hold: `sakura: runtime error: The deque is empty.` + +### Contracts +`expects`, `asserts`, and `ensures` are what a program promises itself: what a function needs of what it's given, what holds as the work goes on, and what holds where a block is left. +```sakura +def withdraw(from: &mut wallet, amount: u64): u64 { + expects(amount <= from.balance, "A wallet gives no more than it holds."); + ensures(left: left == old(from.balance) - amount); + from.balance -= amount; + return from.balance; +} +``` +- **A contract that fails is a fault**, with the trace and status `1`: `sakura: runtime error: A pre-condition failed: b != 0, with b = 0.` A second argument, a `strview`, says what failed in place of the condition. Only a contract that fails makes its report, so one that holds costs its condition and a branch. +- **`ensures` is checked on every way out of its block** once it's been reached: each `return`, a `break` or `continue` leaving the block, and the block's end, the last written first. In a function's own block, `ensures(r: ...)` names what the function returns, and within any `ensures`, `old(e)` is what `e` was where it was reached, of a type that closes nothing. +- **`--contracts off`**, for `run`, `build`, and `check`, leaves every contract out, conditions and all: the executable is byte for byte the one built from the source without them. So a condition changes nothing it names, by `=`, `+=`, `++`, or the like. `contracts()` is a constant, true where they're checked, so `if const contracts()` keeps work only they read. +- **In a constant,** a contract that fails is reported where the constant is: `Evaluating `h` stopped: An assertion failed: n % 2 == 0, with n % 2 = 1.` +- **The words are names elsewhere:** `t.expects(x)` calls a method, and a field may be named `ensures`. Only at a statement's start, before `(`, is one a contract. + +Contracts are apart from the checks a checked program makes: `--contracts off` leaves them out, and nothing else does. + +### Checks +A program is checked or it isn't, as a debug and a release build: `run` checks unless `--fast`, and `build` doesn't unless `--checks`. +- **A checked program** stops at an index or a range past the end, of a fixed array, a view, or a container; at a union's field read where it holds another; at an integer converted to an enum none of whose members has its value; and at a `match` finding no arm. Each is a fault, saying what went wrong and where. std's containers check what they're asked for alike, as the front of one that's empty, or a key a `dict` doesn't hold. +- **One that isn't** does none of that, and reads and writes where the program said, as C does. An index that may be past the end in a program that is right is asked of `get(i)`. +- **Every program** stops at `null` reached through, at a division by zero, and as its stack runs out. The processor faults at the first two itself, and the runtime reports them as a check would, so they cost nothing where they hold. Only a checked program compares a pointer with `null` where it reaches past the first page of memory. +- **`checking()`** is a constant, true where the program checks, so `if const checking() { ... }` checks only there, as std's containers do. In a constant, the checks are always made. +- **`sakurac check --checks-report`** lowers the program checked and optimized, and lists the checks the optimizer couldn't leave out, in the program's own functions, a line of the source each, with how many of each kind: where an unchecked build trusts the program. A check inlined from std, as a `vector`'s index, is listed at the line calling it. + +--- + +## Functions +```sakura +def add(a: f32, b: f32): f32 { return a + b; } + +def greet(name: strview = "world", mark: strview = "!"): void { # defaults run at each call + println($"Hello, {name}{mark}"); +} + +def sum(xs: i64...): i64 { # variadic: `xs` is a span of the arguments + var total: i64 = 0; + for x in xs { total += x; } + return total; +} + +sum(1, 2, 3); # 6 +sum(...numbers); # a view or fixed array given as all of them +``` +- **Parameters** belong to the function, which may change them. One that closes is closed where the function returns, unless it is returned. +- **Overloads** differ in their parameters. The best fit wins: an exact type, then a constant converting, then any other conversion, then becoming a union. A function that isn't generic wins a tie against one that is. +- **No body**: a function ending at its signature is given by the compiler, `@intrinsic`, or by C, in an `extern module` (see [Calling C](#calling-c)). +- **Returning what gives nothing**: a function giving nothing may `return` a call that gives nothing, so generic code returns what a call gives, `return f(x);`, whatever that is. + +**Functions are values**: named functions, static methods, and methods and properties taken through their type, as `vec2::length`, or `rect::area`, whose value is its `get`, a `def(&rect): f32`. A generic function, or a member of a generic type, named without its type arguments takes them from the function type expected, or from a parameter's `invokable` bound, as `val empty: def(&vector): bool = vector::is_empty;` takes `vector`'s. Where those don't give them all, they're written, as `integer::parse::`. A named function given where a function type it doesn't match is expected, as a type or a bound, is called as that type asks by a function made for it, which the optimizer inlines: each parameter is given to it as a call gives an argument, lent where it takes a reference and read through where it takes what one reaches, the parameters left over take their defaults, and among overloads the one such a call chooses is called. So `words.iter().map(path::parse)` gives each `&strview` to a `parse(text: strview, alloc: maybe<&mut allocator> = nothing {})`, and a method taking `&mut this`, given where each value is given away, as `map` gives them, is lent each one, which is closed after. Anonymous functions may leave out types where a function type is expected, or where they are given for a parameter bounded by `invokable`, as `xs.iter().map(def(x) => x * 2)`, and `=> value` returns the value. One whose parameters' types are all written has a type of its own, which gives the type parameters of what it's given for, where an overload is chosen among others too, as `T` of `test: def(&T): bool`. They refer to the locals they use where those are, so they see and change them, and must not outlive them: +```sakura +var total := 0; +items.iter().for_each(def(x) { total += x; }); # changes `total` itself + +val doubled := def(x: int) => x * 2; +``` +A function value is the code and what it refers to, and owns nothing. One holding state past the function making it, as a counter returned, is a struct implementing `invokable`, as below. A function is never `null`. Functions can also be declared inside a block. A variadic function's value is of a type written with `...`, as `def(i64...): i64`, and is called as the function is, `f(1, 2, 3)` or `f(...xs)`. + +**Calling values**: a value whose type is no function is called through its `invoke`, so `f(1, 2)` is `f.invoke(1, 2)`, by the rules of a method's call: the overloads are chosen between, and one taking `&mut this` is called on what can be written. A function value and the address of a C function have an `invoke` the compiler gives them, so generic code bounded by `invokable` takes them and callable values alike: +```sakura +struct counter : invokable { var total: i64; } +def counter::invoke(&mut this, by: i64): i64 { this.total += by; return this.total; } + +def twice(f: &mut F, x: i64): i64 where F: invokable { return f(f(x)); } + +var c := counter{}; +c(5); # counter::invoke(&mut c, 5) +twice(&mut c, 1); +var g := def(x: i64): i64 => x * 2; +twice(&mut g, 1); # 4 +``` + +**Holding any callable**: `function`, of `core`, holds one callable of a signature, whatever its type, and owns it: a functor, a named function, a lambda, or a method taken through its type. A list holds callables of different types so, and a functor is kept without naming its type: +```sakura +struct tally : invokable { var seen: u64; } +def tally::invoke(&mut this, e: &event): void { this.seen++; } + +var handlers := vector::>::new(); +handlers.append(function::new(tally{})); +handlers.append(function::new(def(e: &event) { println(e.name); })); +for &h in handlers { h(&e); } +``` +- A callable of up to 24 bytes is held in the `function` itself, and a larger one in a `box`. A call goes through one table of what the held type does. +- It's moved, never copied. Its zero value holds nothing, which `holds()` says, and calling it then stops the program. `get::()` lends what it holds where that is an `F`. +- Holding a lambda, it refers to what the lambda refers to, so it must not outlive those locals. What must outlive them is a functor. +- It is no constant: a constant would keep the words of what it holds, but not the function a function value among them is. + +--- + +## Methods and properties +Methods are declared outside their type, in any module, for any type, the built-in ones included. One taking `&this` or `&mut this` is called on a value, and any other is static: +```sakura +def vec2::length(&this): f32 { ... } +def vec2::of(x: f32, y: f32): vec2 { ... } # called as vec2::of(1, 2) +def u8::is_upper(&this): bool { return this >= 'A' && this <= 'Z'; } + +val rect::area: f32 { # a property, read like a field + get => this.width * this.height; +} + +var rect::size: vec2 { # one written too + get => vec2{ this.width, this.height }; + set { this.width = value.x; this.height = value.y; } +} +``` +- **Generic types** name their parameters, as `def stack::push`. A method can't be declared for one instance, which is why text's methods are on `strview`. +- **`&this` and `&mut this`** may overload each other. A writable receiver calls the second. +- **Bounds of their own**: a method of a generic type may bound the type's parameters, as `def bag::sum(&this): T where T: numeric`, and belongs only to the instances meeting them, which then satisfy the traits asking for it. +- **Properties** are `val` with a `get`, or `var` with a `set` too, of any type but `void`. An accessor's parameters are implied: a `get` has `this`, as `&this`, and a `set` has `this`, as `&mut this`, and `value`, of the property's type. Its body is a block, or `=> expression;`, which a `get` returns and a `set` does, as `set => this.w = value;`. A trait asks for a property with `{ get; }` or `{ get; set; }`. `pub get` or `pub set` gives one accessor visibility of its own. `value` is a name only within a `set`. +- **Nested types** are declared and named through another type, as `list::cursor`. A field may share its name with one, since the field is reached through a value and the type through its type: `struct token { var kind: token::kind; }`. +- **Names within a type**: within a type, and what is declared through it, its nested types and associated variables, and an enum's members, are named without the type, as `cursor` within `list` is `list::cursor`, given the same `T`. In a type, only its types are meant, so an enum's member `u8` leaves `u8` the type. A type's functions are still named through it, since they are often named for the free functions they implement, as `vector::decode` calls `decode::`. +- **Indexing**: a type implementing `indexable`, by `at(&this, key): &V` and optionally `at(&mut this, key): &mut V`, supports `x[key]`, which is `x.at(key)`: the reference it gives, read, written, and bound as any reference is. + +--- + +## Traits +A trait lists methods, and **any type with them satisfies it**, whether or not it names the trait. A trait bounds a generic, which is compiled for each type, or is the type of a reference, which calls through a table at run time: +```sakura +trait clickable { + def clicked(&mut this): void; +} + +struct button : clickable { var label: strview; } # naming the trait is optional, but checked +def button::clicked(&mut this): void { println($"clicked {this.label}"); } + +def press(target: &mut clickable): void { target.clicked(); } +``` +- **Default methods** have a body, which types naming the trait take as their own. `@optional` methods may be left out. In a trait that is only a bound, each default is compiled for each type implementing the trait, with `self` that type, so it calls the type's methods directly and may be generic, as `def map(&mut this, f: F): mapped where F: invokable`. In any other, a default is compiled once and calls through the table. +- **Bounds of a method**: a method of a trait may bound the trait's parameters or `self` beyond what the trait does, as `def sum(&mut this): T where T: numeric` or `def rev(&mut this): reversed where self: backward_iterator`. Only the types meeting them have it, and the bounds hold within its body. +- **Composition**: `trait shape : named, sized { ... }` asks for what both ask for. +- **Generic traits**, as `trait into`, are a trait for each type argument. +- **Static methods and constants** describe the type, and are reached through a bounded parameter, as `T::top()`. +- **Functions of its own** are declared through it, outside it, as `def real::parse(text: strview): result`, and named through it, as `real::parse::(text)`. The trait doesn't ask for them and what implements it doesn't take them, so they take no `this` and may be generic. +- **`self`** is the type implementing the trait, as `def copy_of(other: &self): self;`. +- **Types a trait asks for**, as `type cursor: iterator<&T>;`, are given by each implementer and named through a bound, as `C::cursor`. A trait naming `self`, asking for types, or with generic methods or methods bounding its parameters or `self`, as `iterator`, is only a bound. +- **References** satisfy the traits of what they refer to, except `owning`, and those whose methods make or take a `self` by value: `numeric` and the traits it composes, `copyable`, `moveable`, `integer`, `real`, `ordinal`, and `zeroable`. +- **Pointers** satisfy `equatable`, `ordered`, and `hashable` by address, `zeroable`, and `pointer`. +- **Built-in types** are `equatable` and `hashable`, numbers, enums, and pointers `ordered`, and numbers `numeric`, with every trait it composes. Function types and `cfn` are `signature`, and `invokable` of their own type. +- **Receivers**: a method taking `&this` meets one a trait asks for taking `&mut this`, since what can be written can be read. +- **Calling**: `invokable` asks for `invoke(&mut this, args: Ts...): R`, which a call of the value calls (see [Functions](#functions)). `signature` is every function type, naming `F::result` and the pack of its parameter types, `F::params`. + +### Operators +**A struct or union has each arithmetic and bitwise operator by the method that gives it**, as it has `==` by `equals`: + +| Operator | Method | +|---|---| +| `a + b`, `a - b`, `a * b`, `a / b`, `a % b` | `add`, `sub`, `mul`, `div`, `rem` | +| `-a` | `negate` | +| `a & b`, `a \| b`, `a ^ b`, `~a` | `bit_and`, `bit_or`, `bit_xor`, `bit_not` | +| `a << b`, `a >> b` | `shift_left`, `shift_right` | +| `a += b` and the others | `add_assign` and the others, changing `a` in place, where `a`'s type has one taking `b`; otherwise the operator's method, whose result is written over `a` | +| `a == b`, `a != b` | `equals`, by implementing `equatable` | +| `a < b`, `a <= b`, `a > b`, `a >= b` | `compare`, giving a negative number, zero, or a positive one, by implementing `ordered` | + +An arithmetic operator is a call of its method on the left operand, given the right one by reference, so the method says what the operands are and what the operator gives: +```sakura +struct duration { var ns: i64; } +def duration::add(&this, other: &duration): duration { return duration { ns = this.ns + other.ns }; } +def duration::mul(&this, by: &i64): duration { return duration { ns = this.ns * by }; } + +struct instant { var ns: i64; } +def instant::add(&this, by: &duration): instant { return instant { ns = this.ns + by.ns }; } +def instant::sub(&this, since: &instant): duration { return duration { ns = this.ns - since.ns }; } + +val waited := now - started; # a duration +var due := started + waited * 2; # `2` is taken as the `i64` the method asks for +due += waited; # `add` gives an instant, written over `due` +``` +- **Each operator alone**: a type with only `add` has `+` and nothing else. Keeping its operators consistent is the type's own job. +- **Overloads** are chosen by the right operand, as a call chooses, so a type may add a `duration` and subtract either a `duration` or an `instant`. +- **The method's shape** is `def T::add(&this, other: &B): R`, and `def T::negate(&this): R` and `def T::bit_not(&this): R`, with no type parameters of its own. +- **A number on the left** asks its own type, so `2.0 * v` calls a program's `def f64::mul(&this, v: &vec2): vec2`. A method a program declares on a number stands beside those the compiler gives it. +- **Compound assignment** calls `add_assign`, `sub_assign`, and the rest, as `def T::add_assign(&mut this, other: &B): void`, where the type has one taking the value, so a type owning memory grows in place. Otherwise it is `a = a + b`, so what the method gives is `a`'s own type. +- **Comparisons** stay between two values of one type. Integers give `bit_and` and the rest as methods too, a shift taking how far as a `&u32`, so a bound asking for them is met by integers as well as by a program's types. +- **Numbers** operate as the language does, and never call a method. + +`core` names the methods as traits, for generic code to ask for, each satisfied by any type with the method: + +| Trait | Asks for | Gives a type parameter | +|---|---|---| +| `addable`, `subtractable`, `multipliable`, `divisible`, `modular`, `negatable` | `add`, `sub`, `mul`, `div`, `rem`, `negate`, each between values of one type | `+`, `-`, `*`, `/`, `%`, `-x` | +| `additive` | `addable`, `subtractable`, `negatable`, and `equatable` | `+`, `-`, `-x`, `==` | +| `multiplicative` | `multipliable` and `equatable` | `*`, `==` | +| `numeric` | `additive`, `multiplicative`, `divisible`, and `modular` | All of arithmetic, and constants | + +A program composes its own, and **any bound asking for an operator's method gives the operator**: +```sakura +trait scales : additive { def mul(&this, by: &S): self; } + +def lerp(a: V, b: V, t: S): V where V: scales { return a + (b - a) * t; } + +lerp(1.0, 3.0, 0.5); # f64 scales by an f64 +lerp(vec2 { x = 0, y = 0 }, vec2 { x = 2, y = 4 }, 0.5); # vec2::mul(&this, by: &f64) +``` + +**Asking**: `x is shown` and `T is integer` are decided while compiling, and a branch they guard gets the bounds they proved: +```sakura +def tell(x: &T): string { + return "?" if const x is not shown; + return x.show(); +} +``` + +--- + +## Generics +Functions, structs, unions, aliases, traits, and methods take type parameters. Each use compiles an **instance** for its types, which is only made where the program uses it: +```sakura +struct stack { var items: vector; } +def stack::push(&mut this, value: T): void { this.items.append(value); } + +def largest(a: T, b: T): T where T: ordered { return a > b ? a : b; } + +var s := stack::{ items = vector::::new() }; +val big := largest(3, 7); # T is inferred +``` +- **Type arguments** are written `<>` in types and `::<>` in expressions, so a lone `<` is a comparison. +- **Inference** reads the arguments, the result type expected, struct literals' fields, bounds, and the lengths of fixed arrays, and for a function named as a value, the function type expected of it. A parameter of a type parameter's own type takes the value an argument is, so `largest(v[0], v[1])` gives an `i64` rather than a reference into `v`, and `math::sqrt(xs[i])` takes a `f64`, while `f(&x)` gives `T` the reference. +- **Checking**: a generic is checked against its bounds. Errors only an instance has, such as `x + 300` where `T` is `u8`, name the instance. +- **Bounds** are written one `where` for each parameter: `where T: shown where U: shown, equatable`. + +| Bound | Allows | +|---|---| +| a trait | Its methods, and `&T` as a reference to it | +| `equatable`, `ordered` | Their operators | +| `numeric` | Arithmetic, with constants and `as` between numbers | +| `additive`, `multiplicative`, `addable` and the rest | The operators their methods give (see [Operators](#operators)) | +| `integer` | Bitwise operators, shifts, and indexing, with what `numeric`, `ordered`, `ordinal`, and `zeroable` allow | +| `real` | What `numeric`, `ordered`, and `zeroable` allow, with float constants. `f32` and `f64` are real, and the functions of `std::math` ask for it | +| `ordinal` | Comparing, `as` to and from integers, and ranges. Integers and enums are ordinal, as is a type parameter bounded by `integer` | +| `zeroable` | A zero value, as `var made: T;` | +| `pointer` | Moving and subtracting by elements | +| `closeable` | Nothing more. Generic code asks it, as `if const T is closeable`: whether values are closed | +| `signature` | `F::result`, the pack `F::params`, and calling a value of it, as `f(...args)` where `args: F::params...` | + +The compiler decides `integer`, `real`, `ordinal`, `zeroable`, `pointer`, `closeable`, and `signature`, and no other type implements them. + +**Constant parameters** stand for values each instance is given while compiling: +```sakura +struct buffer where T: zeroable { var items: T[N]; } +def buffer::capacity(&this): u64 { return N; } + +def grown(xs: &T[N], last: T): T[N + 1] where T: zeroable { + var out: T[N + 1]; + for i, x in xs { out[i] = x; } + out[N] = last; + return out; +} + +val ys := grown(&xs, 4); # N is the length of xs +``` +Their type is any that closes nothing. They are given literals, constants, enum members, functions, and literals and arithmetic of those, and equal values are one instance. + +**Packs** take a type for each argument of a function's variadic parameter: +```sakura +def show_all(args: Ts...): string where Ts...: shown { + var out: string = ""; + for const x in args { out.append(x.show()); } # the body, once for each argument + return out; +} +``` +A pack is used by `for const`, `args.length`, `args[i]` with `i` known while compiling, and `f(...args)`, which moves the values that close to the function given them, leaving the pack empty, as `move` would. The pack of types has a length too, `Ts.length`. A function type takes one too, as `def(Ts...): R`. Structs, unions, and traits take a pack last, which the type arguments after those before it fill, and `Ts...` passes one on whole: +```sakura +trait sink { def put(&mut this, args: Ts...): void; } +struct log : sink where Ts...: shown { var lines: vector; } + +var l := log::{ lines = vector::::new() }; +l.put(1, true); +``` +A pack is only the type of a variadic parameter, never of a field or variable, and a type alias takes none. + +**Pattern parameters** take a function type or a fixed array and name its parts, on a struct, union, or trait. `trait invokable` is written `invokable`, which gives `Ts` the pack `(i64, bool)` and `R` the type `u8`: +```sakura +struct functor : invokable where R: zeroable { var hits: i64; } +def functor::invoke(&mut this, args: Ts...): R { + this.hits++; + var out: R; + return out; +} + +var f := functor::{}; +_ = f(1, true); +``` +- Names before a pack take a parameter type each, as `A` of `def(A, Rest...): R`, and a pattern without a pack takes exactly as many. +- A variadic function's pack ends in what its last parameter takes, so `invokable` asks for a variadic `invoke`, and within a function given one, the pack's last value is a view of the rest. +- A type parameter bounded by `signature` is given whole, as `invokable`, naming `F::params` and `F::result`. Only a pattern `def(Ts...): R` takes it, since its parameters are not known. +- **`L[N]`** takes a fixed array, naming its element's type `L` and its length `N`, a constant `u64`, as `struct simd` is written `simd`. A method names it in its receiver, as `def simd::sum(&this): L`, and a function takes the parts, as `def first(v: &simd): L`, which inference gives them. + +--- + +## Closing, copying, and moving +A type naming `owning` is **closed** where its value's scope ends, so what it holds is released without a call written by hand: +```sakura +pub struct buffer : owning { + var data: *mut u8; + var size: u64; +} + +pub def buffer::close(&mut this): void { + raw_release(this.data); + this.data = null; +} + +def work(): void { + var b := buffer::new(64); + fill(b); +} # b.close() runs here +``` +- **When**: on every way out of the scope, in reverse order of declaration. A temporary closes where its statement ends, and a value written over closes after the new one is made. Fields close after their value's own `close`. +- **Which**: a type is `owning` only by naming it. A type whose values are closed, by being `owning` or holding what is, is `closeable`. +- **Returning** hands a local to the caller instead of closing it. +- **One owner**: a value that closes is never copied implicitly. Wherever one goes that isn't a reference, as `val b := a;`, `take(a)`, a field, `a = b`, `for x in v`, or `is some(x)`, a place holding it is refused, so it is referred to, returned, or copied or moved by name. A new value, as a call gives, is moved where it goes. +- **References and pointers** own nothing, so they never close what they reach. + +**Copying and moving** are explicit, through `copyable` and `moveable`: +```sakura +var a := string::from("hello", nothing{}); +var b := string::copy_of(&a); # a second string, with memory of its own +var c := string::move_of(&mut b); # b's memory, leaving b empty but valid +val d := copy(a); # the same, through `core`'s generic helpers, which a call lends `a` +val e := move(c); +``` +`copy` copies anything that closes nothing byte for byte. `close(x)` closes a value where it stands, as its scope ending would: its own `close`, then its fields, and leaves it empty, so a `box` and a container close what they hold whole. A value moved from is left empty, and closed as usual where its scope ends. + +--- + +## Compile time +### Constants +**Any function can run while compiling** where a constant calls it, unless it reads a global variable, calls C, or turns an address into a number: +```sakura +def crc_table(): u32[256] { + var table: u32[256]; + for i in 0..256 { + var c := i as u32; + for _ in 0..8 { c = (c & 1) != 0 ? 0xEDB88320 ^ (c >> 1) : c >> 1; } + table[i] = c; + } + return table; +} + +const crc: u32[256] = crc_table(); +``` +- Constants hold numbers, `bool`, enums, functions, read-only pointers and references, and arrays, structs, and unions of those, so a `span` works and a `string` doesn't. They may use each other in any order. +- Memory built while compiling is kept where a constant still points into it, as read-only data. A constant may also point into another constant, as `const odd: span = primes[1:4];` or `&primes[4]`, which shares that constant's memory rather than copying it. +- A fault while evaluating is reported at the constant, with a trace. `const def` promises a function can run while compiling. + +### Choosing code +`if const` keeps only the branch its condition chooses while compiling, and that branch gets the bounds the condition proved. Where the condition says a type parameter is a type, as `T is strview`, the branch takes the parameter as that type: each instance taking it checks it so, and what it says of `T` is noted there: +```sakura +def describe(x: T): string { + if const T is integer { + return $"{x + 1} is {size_of::() * 8} bits"; + } + if const T is strview { + val text: strview = x; + return $"{text.length} bytes of text"; + } + return "something else"; +} +``` +`T is X` is exact: an alias is a type of its own, so `strview` isn't `span`. +`for const i in 0..n` counts through a range whose ends are known while checking, a copy of its body for each number, or each member of an enum, in which `i` is a constant, so `if const` decides by it and a fixed array may take its length from it. It unrolls at most 1024 numbers, and within a generic waits for each instance where an end depends on it: +```sakura +def lanes(): void { + for const i in 0..N { + if const i % 2 == 0 { even(i); } else { odd(i); } + } +} +``` +`if const` and `for const` read constants, and `if const` also what functions give of them, as `if const twice(count) == 6`. A condition the checker can't work out itself, as one calling a function given text, as `if const named(name_of::())`, is worked out by running it once checking is done, so both its branches are checked, and only the one it chooses is compiled, which reports any `compile_error` it holds. + +`when` keeps declarations or statements only for some targets. Its keys are `os` (`linux`, `macos`, `windows`, `freebsd`), `arch` (`x86_64`, `aarch64`), and `backend` (`vm`, `native`), and an unknown key or value is an error. `run` and `check` target the system running `sakurac`, with the `vm` backend, and `build` and `check --target` an executable's, `linux-x86_64` or `windows-x86_64`, with the `native` backend. `module system when os == linux;` limits a section of a file the same way: +```sakura +when os == linux { + def config_dir(): strview { return ".config"; } +} +else when os == macos { + def config_dir(): strview { return "Library/Application Support"; } +} +``` + +### Attributes +An attribute is a struct literal after `@`, worked out as a constant, of a struct implementing `attribute`. `@usage` says what it may be written on: +```sakura +@usage{ on = target::functions | target::constants, many = false } +struct check : attribute { val skip: bool = false; } + +@check def adds(): bool { return 1 + 1 == 2; } +@check{ skip = true } def later(): bool { return false; } +``` +The compiler itself reads only `@usage`, `@optional`, `@nodiscard`, `@allow`, `@intrinsic`, and `@inline`. + +`@inline` copies a function's body wherever it's called, at every level, `-O0` too, whatever its size against `--inline N`: a small function a loop calls costs no call even in a build for debugging, where the copy's locals keep cells of their own and debuggers show it as a frame of its own. On a property, it marks both accessors. A call it can't copy stays a call: one through a trait reference, or through a function value the optimizer can't follow, and the call closing a loop of calls, as a function calling itself. A function C or the compiler gives has no body to copy, so it's never `@inline`, and neither is a trait's method, which each type gives its own of. `run --checks` copies nothing, so each function's locals end where its frame does. `core`'s word tests, as `bytes8::zero`, and byte tests, as `u8::is_space`, are `@inline`: +```sakura +@inline def is_blank(byte: u8): bool { return byte == ' ' || byte == '\t'; } + +def indent(line: strview): u64 { + var at := 0u; + while at < line.length && is_blank(line[at]) { at++; } # no call, at -O0 too + return at; +} +``` + +`call_site()`, `source_of(cond)`, and `values_of(cond)` describe the code calling them. As defaults, they describe the caller, which is how `t.expects(b != 0)` reports `b != 0` and its values. + +### Reflection +A program reads its own declarations while compiling. `for const` checks its body once for each, and `value_of(d)` and `x.(d)` reach what `d` declares: +```sakura +def run_checks(): void { + for const d in declarations() { + if const attached::(d).length == 0 { continue; } + if attached::(d)[0].skip { continue; } + println($"{d.name}: {value_of(d)()}"); + } +} + +def show(x: &T): void { + print(name_of::()); + for const f in members_of(decl_of::()) { + if const f.kind == target::fields { print($" {f.name}={x.(f)}"); } + } + println(""); +} +``` +The intrinsics are `declarations()`, `decl_of::()`, `members_of(d)`, `owner_of(d)`, `params_of(d)`, `attributes_of(d)`, `attached::(d)`, `name_of::()`, `path_of::()`, `value_of(d)`, `type_of(d)`, and `compile_error(text, at)`. `name_of` spells a type as notes do, as `&mut position`, and `path_of` with the module of each type it names, as `&mut game::position`, which no two types share. `decl_of` takes a type a declaration makes, so not a reference or a number. A module reaches what it could name, and declarations carrying its own attributes, so writing `@check` on a private function lets the module owning `check` call it. `x.(f)` reaches any field of the value it is given, `pub` or not, as reflection reaches what it was given. `compile_error`'s text may be worked out while compiling, as `$"{f.name} is not read"`, and `at` places the error, as `f.at` places it at the field. + +--- + +## Pointers and memory +Memory is owned as C++ owns it, by values the program can see: what a value holds is released where its owner closes it (see [Closing, copying, and moving](#closing-copying-and-moving)). References, views, pointers, and function values own nothing, and keep nothing alive. `&x` is `x`'s address, wherever `x` is, and a local lives as long as its scope; a temporary referred to lives to the end of its statement, or as long as the name it is bound to, as `val p := &point{ x = 1 };`. + +The heap's owners are `box`, `core`'s, `rc` and `arc`, `std::containers`', the containers and `string`, arenas and pools, and raw blocks: +```sakura +struct node { var value: u64; var next: maybe>; } +var front: maybe> = nothing {}; +for i in 0..3u { front = box::new(node { value = i, next = move(&mut front) }); } + +var settings := rc::new(config{ depth = 2 }); +var also := copy(&settings); # counted: the last copy to close closes it +val watching := settings.weak(); # lock() gives an owner while one is left +``` +- **`box`** owns one value alone, as C++'s `unique_ptr` and Rust's `Box`. It is one word that is never null, so `maybe>` is one word too. `get` lends the value, and `take` moves it out. +- **`rc`** owns one value with every copy of it, counting them plainly, for one thread; **`arc`** counts them atomically, for values shared between threads. `rc_weak` and `arc_weak` refer to the value without keeping it. + +Raw pointers are for memory a program manages itself, such as arenas and tables. They aren't checked, except that reaching through `null` stops the program: +```sakura +struct node { + var name: strview; + var next: *node; +} + +val nodes := raw_allocate_zeroed(16 * size_of::()) as *mut node; +nodes[0].name = "first"; +nodes[1] = node{ name = "second", next = nodes }; +val second := nodes + 1; # moves by whole elements +println((*second).next[0].name); # first +raw_release(nodes as *mut u8); +``` +- `p[i]` is the element `i` along, `*p` is `p[0]`, and `through(p)` is a reference to it. A pointer is an address, so nothing is reached through `p.` itself. +- `p + n` and `p - n` move by elements, and `p - q` counts them. `p[start:count]` is a view. +- **Taking an address** is always written. A reference written as one is a pointer where one is expected, `&x` a `*T` and `&mut x` a `*mut T` or a `*T`, as `val p: *mut node = &mut n;` or `look(&x)` for a `*T` parameter, and `address(x)` gives one, `*mut T` for what can be written and `*T` otherwise, as `through(p)` gives a reference. A pointer keeps nothing alive, so one at a value that ends with its statement, as `val p: *i64 = &10;`, is refused, though an argument lives as long as its call. A pointer becomes a reference only through `through`. +- `*mut T` converts to `*T`, never the reverse. `as` converts pointers to and from integers and other pointer types, and `&x as *T` takes an address as a pointer of any type. + +| Function | Does | +|---|---| +| `raw_allocate(size)` | Memory that isn't zeroed, holding anything at first, as C's `malloc` | +| `raw_allocate_zeroed(size)` | Zeroed memory, as C's `calloc`: memory the system gives fresh is zero already, and isn't cleared again | +| `raw_resize(p, size)`, `raw_release(p)` | Resizes or releases a block | +| `size_of()`, `align_of()` | The size and alignment of a type | + +**Allocators**: each container takes an optional `allocator`, and uses the program's heap where it is given none. An `arena`, `std::allocators`', hands out memory from large chunks, and takes it back all at once, or back to a `mark()`: +```sakura +var scratch := arena::new(); +val alloc: maybe<&mut allocator> = &mut scratch; +val point := scratch.mark(); +var seen := vector::::new(alloc); # its memory is the arena's +seen.append(4); +seen.close(); +scratch.rewind(point); +``` +A `pool`, also `std::allocators`', hands out blocks of one size, taking each back to hand out again, for values made and released often: `pool::of::()`, then `make(value)` gives a `*mut node` and `unmake(p)` closes it and takes it back. A list or other container given one holds a node in each block. + +**Lifetimes**: a reference used after what it refers to ends is the program's mistake, as in C++. The checker warns where it is sure one outlives its referent: a function returning a reference to its own locals, or a function value, literal, or alias holding one; a reference to a local written into a global, through a parameter, or into a local of an outer scope; and a temporary kept past its statement. Warnings never stop a check, run, or build, and `@allow` on a function quiets them, where it is right for reasons the checker can't see. + +**Checked runs**: `sakurac run --checks` checks every read and write through a reference or pointer, and stops where the program holds no memory there: a dangling reference, a block used after its release or past its end, or a block released twice. Released blocks are held back for a while, so a late use still finds them released. As the program ends, it lists the blocks it allocated that nothing it keeps reaches, by where each was allocated. Memory the program was given rather than allocated, as what it maps from the system, its arguments, and its variables, is held too, what it maps until it gives it back. Where code of its own calls C, memory the machine doesn't know is taken as C's from then on, but for what it mapped and gave back; `system`'s own calls of C, which it's made of on Windows, don't count. Its code is optimized no more than `-O1` would, since inlining may leave out the frames a dangling reference refers to. + +It stops at a read of memory nothing wrote, too: of a block `raw_allocate` gave, the bytes `raw_resize` added, or a variable `undefined`, until each byte is written. Copying such bytes, as moving a block does, isn't reading them, and memory the system or C is given the address of counts as written. An executable can't check memory: `build --checks` makes the checks of [Checks](#checks) alone. + +--- + +## Calling C +C's functions, structs, and unions are declared in an `extern module`, a section of a module that says which systems it's for, and `extern import` names the library they're found in: +```sakura +extern import "libc.so.6" when os == linux; +extern import "ucrtbase.dll" when os == windows; + +extern module clib when os == linux || os == windows; + +pub struct quotient { pub var quot: i32; pub var rem: i32; } # laid out as C's +pub def strlen(text: *u8): u64; # C's: it has no body +pub def div(a: i32, b: i32): quotient; +pub def qsort(base: *mut u8, count: u64, size: u64, compare: cfn): void; + +pub def length_of(text: strview): u64 { return strlen(text.data); } # ordinary Sakura of `clib` +``` +```sakura +import clib; + +def compare(a: *u8, b: *u8): i32 { return (a as *i32)[0] - (b as *i32)[0]; } + +def main(): void { + var xs: i32[3] = [3, 1, 2]; + qsort((&mut xs) as *mut u8, 3, 4, compare); # C calls `compare` back + val length := length_of("hello"); # 5: literals are followed by a zero byte +} +``` +- **A section's `when` is required**, and names `os`, `arch`, or both, since a library is one system's, and so is C's calling convention. A section for `arch` alone suits only libraries whose types are the same size on every system: C's `long` is 64 bits on Linux and 32 on Windows. +- **In a section**, a function with no body is C's, by its own name, and never generic, overloaded, or a method. A struct is laid out as C's, of fields that cross, and never generic. A union is C's: every field begins where it does, and nothing says which it holds, so `is` and `match` can't ask. Everything else, functions with a body included, is ordinary Sakura of the module. Outside a section, a function with no body is `@intrinsic`. +- **Libraries**: a C function is found in the libraries its file's `extern import`s name for the target, and an `extern import` may have a `when` of its own, so one file names a library as each system does. An executable for Linux needs every one. One for Windows lists each function under its library, so a file names one there. A file naming none finds its functions in the running process, which only the VM has: on Windows, `sakurac.exe` itself, then every DLL loaded into it but `ntdll.dll`. +- **Calling back**: a function of the program given where a `cfn` is expected is the address of an entry C calls it back through. It's never generic or a method, and a lambda can't be one, since C gives it no way to reach what the lambda refers to. The entry stops the program unless it's called while the program is in a call of C. +- The VM calls C on Windows, which its `system` is made of there. On Linux it reaches the system through system calls, and calls no C, so a program calling C is built instead. +- C functions can't run while compiling. Only types C lays out alike cross: numbers, `bool`, enums, pointers, `cfn<...>`, and structs and C's unions of them, with `&T` as a C function's parameter. + +--- + +## The standard library +The libraries are the best reference for idiomatic code. Three ship with the compiler, found beside it: [core](core), [system](system), and [runtime](runtime), compiled into executables, which programs don't import. The standard library is [a repository of its own](https://git.malunal.studio/sakura/std), whose README says what each of its modules holds. + +| Module | Holds | +|---|---| +| `core` | The language's own, which every file sees with no import: the types the syntax makes (`string`, `strview`, `span`, `slice`, `range`, `maybe`, `result`, `nothing`, whose declarations the compiler holds), the traits above, `copy`, `move`, `close`, and `fault`; `vector`, `pair`, `box`, and `function`; iterators and their adapters, sorting, the allocator trait and memory, counting bits, atomics, vectors of lanes, attributes, and reflection. It needs no system, and holds only what the compiler names, or what that, `system`, and the runtime are built from | +| `core::swar` | Words of bytes: eight bytes of text in a `u64`, tested at once | +| `core::intrinsics` | The square root and the operations on lanes the compiler gives, which `std::math` builds on | +| `system` | The layer beneath `std::io` that talks to the operating system, signals, clocks, and threads included, the same on every system, with what files are, who may use them, and `io_error`, why an operation failed. Beneath it, `system::linux` gives Linux's system calls, and `system::windows` the functions of `kernel32.dll`, each declared once | +| `std::containers`, `std::allocators` | The other containers, `dict`, `hashset`, `deque`, `list`, `chain`, `heap`, `queue`, `stack`, `groups`, `runs`, and `interner`, and the owners `rc` and `arc`; and the allocators `arena` and `pool` | +| `std::io`, `std::process`, `std::thread`, `std::time` | Files, streams and their traits, the console, and globs, in `std::io::glob`; running other programs; threads; and time | +| `std::math`, `std::serial`, `std::testing` | The functions of real numbers; typed values by their marks; and tests | +| `std::text`, `std::net`, `std::semver` | Regular expressions, URIs, and semantic versions | +| `std::json`, `std::yaml`, `std::args` | JSON and YAML, read and written, and a program's arguments, read into a struct | + +**Vectors**: `simd` is 16 or 32 bytes of numbers that one instruction works on lane by lane, as SSE and AVX do, or 64 bytes of lanes of 16 bits or more, as AVX-512 does: `L` the type of each lane, and `N` how many. Aliases name each, as `f32x4`, `f32x8`, `f64x2`, `f64x4`, and `i8x16` through `u64x4` for each type of integer, and of 64 bytes `f32x16`, `f64x8`, and `i16x32` through `u64x8`: +```sakura +val a := f32x4::of([1.0, 2.0, 3.0, 4.0]); +val c := a * f32x4::splat(0.5) + f32x4::splat(1.0); # [1.5, 2, 2.5, 3] +val big := c.greater(&f32x4::splat(2.0)); # a mask of lanes 2 and 3 +val d := select(big, c, f32x4::splat(0.0)); # [0, 0, 2.5, 3] +println($"{d.sum()} {big.count()}"); # 5.5 2 + +# Finds a byte sixteen at a time. +def index_of(text: strview, wanted: u8): maybe { + val needle := u8x16::splat(wanted); + var at := 0u; + while at + 16 <= text.length { + if u8x16::load(text.view(), at).equal(&needle).first() is some(lane) { return at + lane as u64; } + at += 16; + } + for i in at..text.length { return i if text[i] == wanted; } + return nothing {}; +} +``` +- **Making and reading**: `of(array)`, `splat(value)`, `load(view, at)` and `store(slice, at)`, which stop the program past the view's end, `lanes()`, `v[i]` reading and writing a lane, `shuffle(order)`, `convert::()`, lane by lane as `as` converts, and `bits::()`, the same bytes as other lanes, which refuses `K` lanes of `M` that aren't as many bytes while compiling. +- **Halves and widths**: `low()` and `high()`, the halves of a vector as vectors of half as many lanes, and `f32x4::join(low, high)` the vector of both; `widened::()` and `widened_high::()`, the first or second half of the lanes, each as a lane of `M` twice as wide; and `narrowed::(&other)`, this vector's lanes then the other's, each as a lane of `M` half as wide, held at `M`'s limits. +- **Gathering**: `f64x4::gather(from, at)` reads the lanes of a view at the places a `simd` names, and `v.scatter(into, at)` writes them there. A place below zero or past the view's end stops the program, `gather`'s only where it's checked. +- **Operators**: `+`, `-`, `*`, `/`, `%`, and `-x`, lane by lane, and of integers `&`, `|`, `^`, `~`, `<<`, and `>>`, a shift by a `u32` count. Integer lanes wrap, and dividing one by zero stops the program, as the numbers do. `==` is every lane equal. +- **Comparing**: `equal`, `not_equal`, `less`, `less_equal`, `greater`, and `greater_equal` give a `mask`, whose `any`, `all`, `none`, `count`, `first`, `has(i)`, and `bits()` say which lanes hold, and whose `&`, `|`, `^`, and `~` combine them. `select(mask, then, otherwise)` takes each lane from one or the other. +- **Functions of lanes**: `min`, `max`, and `abs`, and across the lanes `sum`, `product`, `smallest`, and `largest`, lane 0 first. `std::math` declares the functions of reals on vectors too, seen where it's imported: `fma`, and of real lanes `sqrt`, `floor`, `ceil`, `trunc`, `round`, and `round_even`, each as it gives it of the lane. +- **The same bits everywhere**: each operation is written in `core` lane by lane, which the VM and constants run. An executable asks its processor which vector instructions it has as it starts, with `cpuid`, and works the lanes with them where it has those an operation needs: SSE2, which every x86-64 processor has, for most of 16 bytes, SSSE3, SSE4.1, and SSE4.2 for some, AVX and AVX2 for 32 bytes, AVX-512 for 64, and FMA3 for `fma`. Where it lacks them, a vector is worked a half or a quarter at a time, or the lanes as `core` writes them. Whichever runs, the bits are the same. Integer division and `%`, `scatter`, the `product` of integers, and the `smallest` and `largest` of reals have no instructions, and are always worked a lane at a time. +- **`SAKURA_CPU`** names the instruction sets an executable may use, joined by `+`: `sse2`, `ssse3`, `sse4.1`, `sse4.2`, `avx`, `avx2`, `fma`, `popcnt`, `lzcnt`, `bmi1`, and `avx512`, or a level of x86-64, `x86-64`, `x86-64-v2`, `x86-64-v3`, or `x86-64-v4`. `SAKURA_CPU=x86-64 ./program` runs a program as on a processor with SSE2 alone. +- **In registers**: executables built with `-O2` hold vectors of 16 and 32 bytes in vector registers between operations, as numbers are, and those of 64 in memory. A function using instructions some processors lack, as any working `f32x8` does, or counting a word's bits, has a second version for processors with x86-64-v3's, which it goes to as it begins, and which still asks for AVX-512. +- **`lanes_held()`** says whether vectors are held in registers, as such an executable holds them, and is known while compiling. The virtual machine and constants work lanes one at a time, where code for one number is faster, so code with a way for each chooses by it. + +**Words**: std searches text eight bytes at a time, as words, and sixteen at a time where vectors are held in registers. `core::swar` gives the words themselves, for reading text a program's own way: +```sakura +import core::swar; + +val lines := text.count_of(&'\n'); +val day := swar::load("20261016", 0).digits() else { return; }; # 20261016 + +# Where a string's plain run ends: at a quote, a backslash, or a control byte. +def plain_end(text: strview, from: u64): u64 { + var at := from; + while at + 8 <= text.length { + val word := swar::load(text, at); + val stops := word.equal('"') | word.equal('\\') | word.below(0x20); + return at + stops.first() if stops.any(); + at += 8; + } + for i in at..text.length { return i if text[i] == '"' || text[i] == '\\' || text[i] < 0x20; } + return text.length; +} +``` +- **Words**: a `bytes8` is eight bytes in a `u64`, the first in its lowest byte. `swar::load(text, at)` reads one, stopping the program past the view's end, and `load_last` reads the last one to seven bytes without passing it, with zeros after them. `repeat(byte)` is one byte eight times. +- **Tests**: `equal`, `zero`, `below`, `above`, `within`, and `ascii` each give a `mask8` of the bytes they choose, exact in every byte. A mask's `any`, `first`, `last`, `count`, and `rest` read it, and `&`, `|`, `^`, and `~` combine masks. +- **Changes**: `upper` and `lower` change ASCII letters, `digits` reads eight ASCII digits as a number, or `nothing`, and `choose(mask, then, otherwise)` takes each byte from one word or the other. +- **The same everywhere**: words are `u64` arithmetic, so they give the same results in the VM, in executables, and in constants. + +**Atomics**: `atomic` is a value that threads, or a program and its signal handlers, read and write without a lock, each operation in one step. `T` is an integer, `bool`, enum, or pointer, which every processor reads and writes whole: +```sakura +var hits := atomic::::new(0); +_ = hits.fetch_add(1); # from wherever `&mut hits` is held + +var ready := atomic::::new(false); +data = 42; +ready.store(true, order::release); # publishes `data` +if ready.load(order::acquire) { use(data); } # sees 42 + +match slot.compare_exchange(seen, seen + 1) { + value(_) => {} # it held `seen`, and now holds one more + error(found) => seen = found; # another wrote first, so try again with what it found +} +``` +- **Operations**: `load`, `store`, `exchange`, `compare_exchange`, and `compare_exchange_weak`, and of integers `fetch_add`, `fetch_sub`, `fetch_and`, `fetch_or`, `fetch_xor`, `fetch_min`, and `fetch_max`, each giving what it held. Adding and subtracting wrap, and the least and greatest are compared as `T` is, signed or unsigned. Another `T` given to these stops the compile. +- **Orders** are C11's, as C, C++, Rust, and Zig have them: `order::relaxed`, `acquire`, `release`, `acq_rel`, and `seq_cst`, which is what each operation takes where none is written. A `release` store that an `acquire` load reads makes everything written before the store seen after the load. `fence(how)` orders the reads and writes around it. An order that makes no sense, as a `release` load, stops the program with a fault saying so. +- **Never copied by accident**: an atomic is `owning`, closing nothing, so `val b := a;` is refused, as a copy would read it without a load. Threads share one through `&mut atomic`. +- **The same everywhere**: an executable works them with x86-64's locked instructions, and the VM with C's or `core`'s own atomics, so they're atomic between processes sharing memory there too. While compiling, one thread runs, and an atomic is what it reads and writes. + +**Signals**: `system::handle` runs a function, a lambda, or a functor once a signal comes, at the program's next safe point rather than in the middle of what it was doing, so a handler may allocate, print, or set a flag. It keeps the handler in a `function` until another handles the signal, so a functor may hold what it needs: +```sakura +var stopping := false; +_ = system::handle(system::signal::interrupt, def(s: system::signal) { stopping = true; }); +while !stopping { work(); } +``` +A program that never calls `system::handle` has no safe points, and pays nothing. One that would rather ask has the signal noted with `system::watch(which)`, which runs no handler and so adds no safe points, and asks with `system::watched()`, which gives the signals that came since it last asked, one bit each by the system's number, and `system::signal_of(number)` names them. `system::exit(code)` stops with a status, and `system::abort()` with a fault report. + +Windows has no signals of its own, so the console's events stand for them: Ctrl-C is `interrupt`, Ctrl-Break `quit`, closing the console `hangup`, and logging off or shutting down `terminate`. `system::raise`, `system::handle`, and `system::watch` work within the program as on Linux, but that raising `stop` or `suspend` gives `unsupported`. `system::kill` can only stop another process, with `kill` or `terminate`, which stop it at once with 128 more than the signal's number as its status. + +--- + +## Executables, debugging, and editors +**`sakurac build`** writes a standalone x86-64 executable, with no assembler, linker, or C library, for the system running `sakurac` unless `--target` names another: `linux-x86_64` or `windows-x86_64`. One for Linux is static unless it calls C. One for Windows is a console program that calls the system through its DLLs, as `kernel32.dll`, and an output named without an extension gets `.exe`. A build replaces whatever file its output names, as a C compiler does, even one a program is running from: that one is moved aside to its name with `.old` added and removed from there, which Windows only allows once the program ends, so there it stays until a build next replaces it. The runtime is written in Sakura, in [runtime](runtime), found beside the compiler as `core` is. It behaves as the VM does: the same output, the same fault reports, and the same exit status, but that an executable is unchecked unless built with `--checks` (see [Checks](#checks)). + +| Level | Does | +|---|---| +| `-O0` | Compiles the code as written, but for calls of `@inline` functions, which builds fastest and is what a debugger reads best | +| `-O1` | Optimizes each function on its own: folds and combines what it computes, reuses what it already computed or loaded, threads jumps through what a branch already knows, makes small branches choose a value instead, and moves what a loop doesn't change out of it | +| `-O2` | The default. Also inlines small functions, those called once, and the tests other functions return early on | + +**Compiling on threads**: `-j N`, or `--threads N`, says how many threads `check`, `run`, and `build` compile on: one for each processor, up to eight, unless it says otherwise, and `-j 1` starts none. What they make is the same, byte for byte, however many there are, and notes are printed in the order one thread would make them. + +**Debugging**: `-g` also writes DWARF 5. For Linux, it goes to the executable's path with `.petal` added, which gdb and valgrind find through the executable. For Windows, it goes into sections of the `.exe` itself, named as `gcc -g` names them, which gdb and lldb read, and a PDB file is written beside the executable, its path with `.pdb` in place of `.exe`, which Visual Studio and WinDbg read. The executable names that file by its path and the GUID it is named by, which is made from what the file holds, so the same build writes the same file. It changes nothing in the executable's code. Fault traces and debuggers show inlined functions as frames of their own. Every executable for Windows, debugged or not, also says how each of its functions unwinds, in its `.pdata` and `.xdata`, as the system and its debuggers read to unwind a thread's stack. + +**Editors**: `sakurac lsp`, the language server, checks the workspace as you type, unsaved text included. It gives hover documentation, completion, signature help, semantic highlighting, going to declarations, finding references, and renaming. Where several files declare `main`, each is a program of its own, together with the files that declare none. It checks for the system it runs on, or with `--target` for an executable's. Each job is worked out in a process of its own, so a fault while checking can't stop the server. Windows can't copy a process, so there those are this program started again, as `sakurac lsp --base` and `sakurac lsp --worker`. + +--- + +## This repository +`sakurac` is `entry.sakura`, the command line, over the compiler's own libraries, with the libraries every program reads beside it: + +| Path | Holds | +|---|---| +| `entry.sakura` | The command line: `check`, `run`, `build`, and `lsp` | +| `analyzer/`, `compiler/`, `machine/`, `native/`, `server/` | The compiler's parts, each a library of its own, with a README of its own | +| `core/`, `system/`, `runtime/` | The language's own library, the layer over the operating system, and the runtime compiled into executables | +| `tests/` | Each part's tests, in the folder of its name; the corpus, in `programs/`, `checked/`, and `memory/`, each program beside the `.out` file of what it writes; the tests of `core` and `system`, in `core/`; and the tests of finding libraries | +| `tools/corpus.sakura` | Runs each program of the corpus with a command given, and compares what it writes with its `.out` | +| `docs/` | The roadmap, the plans not built yet, and what's left for later | + +**The compiler's parts** are libraries the blossomfile declares and exports, so another project requiring this repository may read them: +- [`sakura::analyzer`](analyzer/README.md) lexes, parses, and checks, and answers the language server's queries. +- [`sakura::compiler`](compiler/README.md) lowers a checked program to intermediate code, optimizes it, and assembles the virtual machine's code. +- [`sakura::machine`](machine/README.md) is the virtual machine, which also evaluates constants while compiling. +- [`sakura::native`](native/README.md) is the native backend, which chooses the instructions of an executable, places its values, and lays out its file and its debugging information. +- [`sakura::server`](server/README.md) is the language server `sakurac lsp` serves, which also finds `core`, `system`, and the runtime beside the compiler. + +**Packages** it requires, each a repository at `https://git.malunal.studio/sakura/NAME`: +- `std`, the standard library, of which the compiler reads `std::args` for its command line and `std::json` for the language server, besides containers, files, and threads. +- `binary` holds the back end's libraries, `binary::amd64`, `binary::elf`, `binary::dwarf`, `binary::pe`, and `binary::pdb`: they encode instructions, write Linux's and Windows' executables, and write their debugging information. + +**Tests**: `blossom test` builds `sakurac`, then runs: +- `sakurac.tests`, of finding libraries, on the machine; +- `sakura.analyzer.tests`, `sakura.compiler.tests`, `sakura.machine.tests`, `sakura.native.tests`, and `sakura.server.tests`, each part's, on the machine; +- `sakurac.core`, the tests of `core` and `system`, built and run as an executable; +- `sakurac.corpus`, `sakurac.checked`, and `sakurac.memory`, the corpus, each program run by the `sakurac` just built over `../std`, the last with `run --checks`. + +--- + +## Grammar +The syntax as the parser reads it, in EBNF: `{ x }` is zero or more, `[ x ]` is optional, `|` separates choices, and quoted text is written as it is. What the parser accepts and the checker then refuses, such as `break` outside a loop, is left to the sections above. + +### Words and literals +```ebnf +ident = ( letter | "_" ) { letter | digit | "_" } ; (* not a keyword *) +keyword = "true" | "false" | "null" | "import" | "module" | "pub" | "var" | "val" + | "const" | "def" | "mut" | "type" | "struct" | "union" | "enum" | "trait" + | "where" | "return" | "if" | "else" | "for" | "in" | "while" | "break" + | "continue" | "match" | "when" | "as" | "is" | "not" | "extern" ; + +int = ( digit { digit } + | "0x" hex { hex } | "0o" octal { octal } | "0b" bit { bit } ) [ "u" ] ; +float = digit { digit } [ "." digit { digit } ] exponent [ "f" ] + | digit { digit } "." digit { digit } [ "f" ] + | digit { digit } "f" ; +exponent = ( "e" | "E" ) [ "+" | "-" ] digit { digit } ; +char = "'" { char_item } "'" ; +string = '"' { char_item } '"' + | '"""' newline { any } '"""' ; (* spans lines *) +istring = "$" '"' { char_item | hole } '"' + | "$" '"""' newline { any | hole } '"""' ; +hole = "{" expression "}" ; +char_item = any character but the closing quote, a line break, "\" or, in an istring, "{" + | escape ; +escape = "\" ( "n" | "t" | "r" | "0" | "\" | "'" | '"' | "{" | "}" ) + | "\x" hex hex ; +comment = "#" { any but a line break } ; (* "#!" is documentation *) +``` +`this`, `self`, `_`, `get`, `set`, `type_of`, `expects`, `asserts`, `ensures`, `old`, `undefined`, and the `when` keys `os`, `arch`, and `backend` are identifiers the grammar gives a meaning in one place each. + +### Files and declarations +```ebnf +file = { declaration } ; +declaration = import | extern_import | module | extern_module | top_when + | { attribute } [ "pub" ] declared ; +attribute = "@" type_name [ field_list ] ; +declared = function | variable | property | struct | union | trait | enum | alias ; + +import = "import" path ";" ; +module = "module" path [ "when" condition ] ";" ; +extern_import = "extern" "import" string [ "when" condition ] ";" ; (* C's library *) +extern_module = "extern" "module" path [ "when" condition ] ";" ; (* C's declarations; the checker asks for a `when` *) +path = ident { "::" ident } ; + +top_when = "when" condition "{" { declaration } "}" (* no import or module *) + [ "else" ( top_when | "{" { declaration } "}" ) ] ; +condition = cond_and { "||" cond_and } ; +cond_and = cond_item { "&&" cond_item } ; +cond_item = "!" cond_item | "(" condition ")" | ident ( "==" | "!=" ) ident ; + +decl_name = ident [ type_params ] { "::" ident [ type_params ] } ; (* receiver::name *) +type_params = "<" type_param { "," type_param } ">" ; +type_param = ident [ "..." ] + | "const" ident ":" type + | "def" "(" [ ident { "," ident } [ "..." ] ] ")" ":" ident (* a pattern *) + | ident "[" ident "]" ; (* an array's pattern *) +where = "where" bound_list { "where" bound_list } ; +bound_list = ident [ "..." ] ":" type_name { "," type_name } ; (* a trait's method may name its trait's parameters and `self` *) + +function = [ "const" ] "def" decl_name params ":" type [ where ] ( block | ";" ) ; +params = "(" [ this_param [ "," ] ] [ param { "," param } [ "," ] ] ")" ; +this_param = "&" [ "mut" ] "this" ; +param = ident ":" type [ "..." ] [ "=" expression ] ; + +variable = ( "val" | "var" | "const" ) decl_name ":" [ type ] [ "=" expression ] ";" ; +property = ( "val" | "var" ) decl_name ":" type "{" accessor [ accessor ] "}" ; +accessor = [ "pub" ] ( "get" | "set" ) ( block | "=>" expression ";" | ";" ) ; + +struct = "struct" decl_name [ ":" type_name { "," type_name } ] [ where ] + "{" { { attribute } field } "}" ; +union = "union" decl_name [ ":" type_name { "," type_name } ] [ where ] + "{" { { attribute } field } "}" ; +field = [ "pub" ] ( "val" | "var" ) ident ":" ( type | spread ) [ "=" expression ] ";" ; +spread = "..." type_name [ "{" [ ident "as" ident { "," ident "as" ident } ] "}" ] ; + +trait = "trait" decl_name [ ":" type_name { "," type_name } ] [ where ] + "{" { { attribute } trait_member } "}" ; +trait_member = function (* ";" leaves it to the implementer *) + | "const" ident ":" [ type ] [ "=" expression ] ";" + | property + | "type" ident [ "..." ] [ ":" type_name { "," type_name } ] [ "=" type ] ";" ; + +enum = "enum" decl_name [ ":" type ] + "{" [ member { "," member } [ "," ] ] "}" ; +member = { attribute } ident [ "=" expression ] ; + +alias = "type" decl_name "=" type [ where ] ";" ; +``` + +### Types +```ebnf +type = "*" [ "mut" ] type (* pointer *) + | "&" [ "mut" ] type (* reference *) + | type_primary { "[" expression "]" } ; (* fixed array *) +type_primary = "def" "(" [ type { "," type } [ "..." ] ] ")" ":" type (* function *) + | "(" type ")" + | "type_of" "(" expression ")" + | type_name ; +type_name = segment { "::" segment } ; +segment = ident [ "<" type_arg { "," type_arg } ">" ] ; +type_arg = type [ "..." ] | expression ; (* "..." passes a pack on *) +``` + +### Statements +```ebnf +block = "{" { statement } "}" ; +statement = local | local_def | if | when | while | for | match + | jump | contract | block | expression ";" ; + +local = ( "val" | "var" | "const" ) ident ":" [ type ] [ "=" ( expression | "undefined" ) ] ";" ; +local_def = "def" ident params ":" type block ; + +if = "if" [ "const" ] condition_expr block [ "else" ( if | block ) ] ; +when = "when" condition block [ "else" ( when | block ) ] ; +while = "while" condition_expr block ; +for = "for" [ "const" ] [ ident "," ] [ "&" [ "mut" ] ] ident "in" + condition_expr block ; (* a range here is counted in place *) +match = "match" condition_expr "{" { arm } "}" ; +arm = ( "else" | expression { "," expression } ) "=>" ( block | statement ) ; + +jump = ( "return" [ expression ] | "break" | "continue" ) + [ "if" [ "const" ] condition_expr ] ";" ; +contract = ( "expects" | "asserts" ) "(" expression [ "," expression ] ")" ";" + | "ensures" "(" [ ident ":" ] expression [ "," expression ] ")" ";" ; +``` +`condition_expr` is an `expression` that cannot be a struct literal outside parentheses, so `if x {` opens the block. + +### Expressions +Lowest precedence first. Binary operators and ranges group to the left, and assignment, `?:`, and `else` to the right. +```ebnf +expression = fallback [ assign_op expression ] ; +assign_op = "=" | "+=" | "-=" | "*=" | "/=" | "%=" | "&=" | "|=" | "^=" | "<<=" | ">>=" ; +fallback = ternary [ "else" ( "(" ident ")" block | block | expression ) ] ; +ternary = range [ "?" fallback ":" ternary ] ; +range = binary { ( ".." | "..=" ) binary } ; (* core's range *) + +binary = cast { binary_op cast } ; +binary_op = "||" (* 1, lowest *) + | "&&" (* 2 *) + | "|" (* 3 *) + | "^" (* 4 *) + | "&" (* 5 *) + | "==" | "!=" (* 6 *) + | "<" | "<=" | ">" | ">=" (* 7 *) + | "<<" | ">>" (* 8 *) + | "+" | "-" (* 9 *) + | "*" | "/" | "%" ; (* 10, highest *) + +cast = unary { "as" type_operand | "is" [ "not" ] is_target } ; +is_target = "(" expression ")" (* a field a declaration names *) + | type_operand [ "(" [ "&" [ "mut" ] ] ident ")" ] ; +type_operand = type ; (* where "<" always opens type arguments *) + +unary = ( "-" | "!" | "~" | "++" | "--" | "*" | "&" [ "mut" ] ) unary + | postfix ; +postfix = primary { call | index | member | type_args | "++" | "--" } ; +call = "(" [ argument { "," argument } [ "," ] ] ")" ; +argument = [ "..." ] expression ; +index = "[" expression "]" + | "[" [ expression ] ":" [ expression ] "]" ; (* slice *) +member = "." ident [ "::<" type { "," type } ">" ] + | "." "(" expression ")" ; (* a member a declaration names *) +type_args = "::<" type { "," type } ">" ; (* after a call, as value_of(d):: *) + +primary = literal | name [ field_list ] | "(" expression ")" + | lambda | array | "match" condition_expr "{" [ value_arm { "," value_arm } [ "," ] ] "}" + | "type_of" "(" expression ")" (* a type, tested with `is` *) + | "old" "(" expression ")" ; (* within an `ensures` *) +literal = int | float | char | string | istring | "true" | "false" | "null" ; +name = name_segment { "::" name_segment } ; +name_segment = ident [ "::<" type { "," type } ">" ] ; +field_list = "{" [ field_init { "," field_init } [ "," ] ] "}" ; +field_init = ident "=" expression | expression ; +array = "[" [ expression { "," expression } [ "," ] ] "]" ; +lambda = "def" "(" [ lambda_param { "," lambda_param } [ "," ] ] ")" [ ":" type ] + ( "=>" expression | block ) ; +lambda_param = ident [ ":" type ] [ "=" expression ] ; +value_arm = ( "else" | expression { "," expression } ) "=>" expression ; +``` + +--- + +## License +Sakura is released under the MIT License: see [LICENSE](LICENSE). What changed in each version is in [CHANGELOG.md](CHANGELOG.md). diff --git a/analyzer/README.md b/analyzer/README.md new file mode 100644 index 00000000..f349f12c --- /dev/null +++ b/analyzer/README.md @@ -0,0 +1,143 @@ +# sakura::analyzer + +`sakura::analyzer` is the front end of the compiler and of its language server. +It holds the lexer, the parser, and the checker, which keep what they work out +in tables of numbers, a column for each field, so a pass reads only what it +needs and little memory is spent on each token and node. The checker works out what each +name refers to and the type of each expression, and notes what is wrong. After +an edit, it checks again only what the edit touched. It also answers what an +editor asks of a checked program. `sakura::compiler` lowers what it checks to +code. + +## Using it + +Require this repository, which exports each of the compiler's libraries, and name this +one among a target's `deps`: + +```yaml +requires: +- https://git.malunal.studio/sakura/std@v1.0.0 +- https://git.malunal.studio/sakura/sakurac@v1.0.0 + +targets: +- name: app + type: program + deps: [sakura.analyzer, std.io] +``` + +Every program is checked with two things: `core`, the folder beside the +`sakura` executable, read whole; and the types the syntax makes, which the +analyzer holds as `builtin_text`: + +```sakura +import std::io; +import sakura::analyzer; + +# Checks a file importing nothing, with `core`, whose folder is given, and +# prints each note as `sakura check` does. Gives how many there were. +def check(path: strview, core: strview): u64 { + var paths := vector::::new(); + paths.append(string::from(path, nothing {})); + paths.append(string::from(builtin_path, nothing {})); # The types the syntax makes. + every_file(core, &mut paths); + + var names := names::new(); + var notes := vector::::new(); + var sources := vector::::new(); + var syntaxes := vector::::new(); + var roots := vector::::new(); + # The checker refers to each source and syntax, so none moves once made. + sources.reserve(paths.length); + syntaxes.reserve(paths.length); + for i in 0..paths.length { + val at := paths[i].view(); + sources.append(at == builtin_path ? source::from(at, builtin_text) : source::open(at)); + syntaxes.append(syntax::new()); + var lexing := lexer::new(sources.at(i), &mut names, &mut notes, i as u32); + lexing.tokenize_all(syntaxes.at(i)); + var parsing := parser::new(syntaxes.at(i), &names, &mut notes, i as u32); + roots.append(parsing.parse()); + } + + var checker := checker::new(&mut names, &mut notes); + for i in 0..paths.length { + checker.add(sources.at(i), syntaxes.at(i), roots.at(i)); + } + checker.check(); + for &each in notes { + val held := &sources.at(each.file); + val at := held.lines.place_of(each.offset); + println($"{held.path}:{at.line}:{at.column}: {each.code}: {each.message(held)}"); + } + return notes.length; +} +``` + +Given a file whose `main` holds `val x: i32 = true;` and `val y: u8 = 300;`, it +prints: + +``` +wrong.sakura:2:16: mismatch: Expected `i32`, but the value is `bool`. +wrong.sakura:3:15: overflow: The constant is outside the range of `u8`. +``` + +A program that imports modules is read a round at a time by a `resolver`. It +is given the libraries: `whole` for `core`, and `add_library` for `system`, +`std` and the rest. After each round, `refer` adds the files of the modules +that round's files refer to, until a round refers to nothing new. +`sakura::machine`'s README does that. Every file it is given is read with the +program's one table of names, which it looks each path up by. + +## What it holds + +- **Sources**: + - `source` is a file's text and where its lines begin (`lines`, `place_of`), + opened from a path or made from text. + - `names` gives each word an ID, the keywords first, then the words the + parser and the checker know by ID (`word`), and keeps each word's text in + blocks that never move. +- **Lexing and parsing**: + - `lexer` reads a source into a `syntax`'s tokens, and `parser` builds its + tree. Each node has a kind (`nk`), a token, and two slots, whose meaning + its `shape` gives, and where it ends, as how many tokens past its own. + - A token keeps its kind, where it begins, and its name. How many bytes it + covers is its kind's, for a keyword or a punctuator, or its name's, and + only a literal's is kept, which `token_length` reads. + - `walker` finds the nodes a node holds, and `printer` writes a tree as text. + - `syntax::reparse` parses again only the declarations an edit touched. + - `read_files` reads files on threads, giving each word the ID it would have + if the files were read one after another. +- **Checking**: `checker` declares each file's names, then checks every body. + - Each part of the language has its own file in `checker/`: lookup, types, + conversions, calls and overloads, generics and their instances, traits, + operators, patterns, properties, ownership, lifetimes, contracts and + checks, attributes, and reflection. + - It folds constants. Where a value must be known but folding can't give it, + such as an array's length, it runs the code that gives it. + - `update` takes a file parsed again and checks again only what changed and + what depends on it. + - Its tables keep each field in a `column` of its own. What few rows have, + as the type a node converts to, is in a `keymap` by row rather than a + column mostly of zeros, and what is interned, as types and constants, is + found by its hash in an `id_index`. +- **Notes**: a `note` says what is wrong and where, with its code (`ec`), its + message, and any place it relates to, and holds its text, so it is moved + rather than copied. The lexer, parser and checker put notes in a + `note_sink`, which keeps them or hands each on as it is made. +- **Libraries**: `resolver` finds the files of the modules a program's files + refer to, in the libraries it is given. Each library is a folder named by a + module, such as `std` or `sakura::analyzer`. +- **Queries**: what an editor asks of a checked program, which the language + server answers with: `hover`, `complete`, `calls_at` for signature help, + `name_at` and `references`, `highlights`, and which program a file belongs to. + +## Testing + +From the repository's root, `blossom test` runs them as `sakura.analyzer.tests`, or: + +```sh +sakurac run --lib sakura::analyzer=analyzer tests/main.sakura tests/analyzer/*.sakura +``` + +The tests are declared within the module, so they can reach its private names. +Add `-- --only TEXT` to run only the tests whose name contains the text. diff --git a/analyzer/builtin.sakura b/analyzer/builtin.sakura new file mode 100644 index 00000000..0ead06cf --- /dev/null +++ b/analyzer/builtin.sakura @@ -0,0 +1,98 @@ +#! @file builtin.sakura +#! @author John Christman (sorakatadzuma@gmail.com) +#! @copyright Malunal Studios, LLC. +#! @license MIT +#! +#! Contains the types the syntax makes, which the compiler holds itself rather +#! than finding them in a library: `string`, which interpolation makes, the +#! views `span`, `slice`, and `strview`, which `a[:]` and literals make, `range`, +#! which `a..b` makes, and `maybe`, `result`, and `nothing`, which `else`, `for`, +#! and `?` read. They are found where `i64` is, from every file. +#! +#! Their declarations are text read as the first file of `core`'s root, before +#! `core`'s own, so what the compiler relies on of them is written here, beside +#! the code relying on it: `string`'s fields in their order, `maybe`'s `none` +#! first, `span`'s two words, and `range`'s three fields. They name `core`'s +#! traits and `allocator`, so they are read only with `core`. Their methods are +#! `core`'s, declared through them as `u8`'s are. + +module sakura::analyzer; + + +#! The path the text is read as, which notes and traces into it name. +pub const builtin_path: strview = ""; + +#! The declarations of the types the syntax makes, as `core`'s root. +pub const builtin_text: strview = """ + #! The types the syntax makes, which the compiler holds. Their methods are + #! `core`'s. + module core; + + #! What a `maybe` holds where its value is missing, which `nothing {}` makes + #! the empty one of any `maybe`. It is apart from `void`, the value of what + #! gives nothing. + pub struct nothing {} + + #! A value that may be missing: either a `T`, as `some`, or `nothing`, as + #! `none`, which comes first, so a `maybe` left without a value holds nothing. + #! A value converts to a `maybe` of its type wherever one is wanted. + #! @tparam T The type of the value it may hold. + pub union maybe { + pub var none: nothing; #! Holds nothing: the value is missing. + pub var some: T; #! Holds the value. + } + + #! The outcome of something that may fail: either the value it gave, as + #! `value`, or the error that stopped it, as `error`, which must be handled + #! where it is made. + #! @tparam T The type of the value it gives where it succeeds. + #! @tparam E The type of the error it gives where it fails. + @nodiscard + pub union result { + pub var value: T; #! The value, where it succeeded. + pub var error: E; #! The error, where it failed. + } + + #! A view over a run of elements that something else holds: where they begin, + #! and how many there are. It owns nothing, and writes nothing. + #! @tparam T The type of the elements it views. + pub struct span : hashable, equatable, indexable, viewable, iterable { + var _dat: *T; + var _len: u64; + } + + #! A writable view over a run of elements that something else holds, which + #! converts to a `span` wherever a reader is wanted. + #! @tparam T The type of the elements it views. + pub struct slice : hashable, equatable, indexable, viewable, sliceable, iterable { + var _dat: *mut T; + var _len: u64; + } + + #! Text that is only read, as a literal is: a view of bytes. + pub type strview = span; + + #! Text that owns the memory its bytes are written in, which interpolation + #! makes. Its memory is its allocator's, or `raw_allocate`'s where it has + #! none, and goes back where its scope ends. + pub struct string + : owning, hashable, indexable, viewable, sliceable, iterable, + extendable, equatable, ordered, copyable, moveable + { + var _alc: maybe<&mut allocator>; + var _dat: *mut u8; + var _len: u64; + var _cap: u64; + } + + #! The integers from `start` up to, but not including, `end`, as `a..b` + #! makes, or through `end`, as `a..=b` makes, or the members of an enum + #! between them, in the order of their values. The compiler makes one from + #! its fields in the order they are declared. + #! @tparam T The type of the integers, or the enum. + pub struct range : sized_iterator, backward_iterator where T: ordinal { + pub var start: T; #! The first value it gives, while it gives any. + pub var end: T; #! Where it ends: just past its last, or its last where it was made by `..=`. + var _last: bool; #! Whether `end` is still to be given, as `a..=b` gives it. + } + """; diff --git a/analyzer/checker.sakura b/analyzer/checker.sakura new file mode 100644 index 00000000..ff51ab57 --- /dev/null +++ b/analyzer/checker.sakura @@ -0,0 +1,464 @@ +#! @file checker.sakura +#! @author John Christman (sorakatadzuma@gmail.com) +#! @copyright Malunal Studios, LLC. +#! @license MIT +#! +#! Contains the checker, which works out what the parsed files of a program +#! mean: what each name refers to, the type of each expression, and whether +#! the program is valid, and `check`, where it begins. What it checks is split +#! across the files of the `checker` directory, one for each part of the +#! language, as the parser's are. +#! +#! The checker never changes a syntax. What it works out is kept in tables of +#! its own: the types and declarations of the type table and declaration +#! table, and the results of each node, which a result table holds for the +#! node's file, or for the instance of a generic the node is checked in. An +#! instance is checked over its template's nodes with a result table of its +#! own, so nothing of the template is ever copied. + +import std::containers; +module sakura::analyzer; + + +#! A file the checker is given: its source, its syntax, and what the checker +#! keeps of it. +pub struct unit { + pub var source: &source; #! The file's source, which its notes are placed in. + pub val syntax: &syntax; #! What the file parsed into. + var root: u32; #! The `document` node. + var imports: u32; #! The run of the modules it imports, in the lists of the declarations. + pub var table: u32; #! The result table of its nodes. + var parses: u32; #! How many times its syntax had been parsed whole again when it was last checked. +} + +#! The results of a run of nodes of a file: those of the whole file, or of the +#! nodes of a template, checked for one of its instances. A node's results are +#! at `offset + node - base` of the result vectors. +pub struct rtable { + pub var file: u32; #! The file whose nodes it holds the results of. + pub var base: u32; #! The first node it holds. + pub var count: u32; #! How many nodes it holds. + var offset: u32; #! Where its results begin in the result vectors. + var instance: u32; #! One more than the instance it is of, or 0 for a file's. + pub var parent: u32; #! One more than the table it was made within, which holds the nodes it does not, or 0. +} + +#! A value known while compiling: an integer, as its magnitude and sign, a +#! float, or a `bool`, as a magnitude of 0 or 1. An integer's magnitude and a +#! float's bits share one word, which `magnitude` and `real` read as the kind +#! of constant says, so it takes sixteen bytes rather than thirty-two. +pub struct constant { + var word: u64; #! An integer's magnitude, a `bool` as 0 or 1, or a float's bits. + pub var negative: bool; #! Whether an integer is below zero. + pub var floating: bool; #! Whether it is a float, whose bits `word` holds. +} + +#! An instance of a generic function: its template, given type arguments, whose +#! body is checked with a result table of its own once something uses it. +pub struct instance { + var decl: u32; #! The template. + pub var args: u32; #! The pack of its type arguments, its owner's first. + pub var table: u32; #! One more than its result table, once its body is checked. + pub var kind: u32; #! Its function type. +} + +#! Where checking is: what a name resolves within, and what a body's +#! statements are checked against. It is saved and put back as a whole where +#! checking moves to another declaration, so nothing of one leaks into another. +pub struct checker::frame { + pub var file: u32; #! The file being checked. + pub var table: u32; #! The result table being written. + var base: u32; #! Of that table, kept here so reaching a node's results is quick. + var offset: u32; #! Of that table, where its results begin. + var count: u32; #! Of that table, how many nodes it holds. + var decl: u32; #! The declaration whose signature or body is checked. + var scope: u32; #! The type whose own names are named without it there, or 0. + var home: u32; #! The module names resolve in. + var result: u32; #! What `return` gives, in a function's body. + var loops: u32; #! How many loops are around what is checked. + var block: u32; #! The block whose statements are checked. + var opened: u32; #! Where the bindings of that block begin, past which a local of the same name is declared twice. + var body: u32; #! The block of the function whose body is checked, which every `return` leaves, so its `ensures` may name what it returns. + pub var instance: u32; #! One more than the instance being checked, which notes name. + var marks: u32; #! Where the bindings of the body begin. + + # The fields of the nodes and tokens of the file being checked, which never + # change while it is checked, so each is read where it is without a call. + var kinds: *nk; #! The kind of each node. + var tokens: *u32; #! The token each node says what it is by. + var lefts: *u32; #! The first slot of each node. + var rights: *u32; #! The second slot of each node. + var extras: *u32; #! The records and runs the slots begin at. + var names: *u32; #! The name of each token that is a word, or 0. + var tkinds: *tk; #! The kind of each token. +} + +#! The target a program is checked for, which `when` decides by, each value +#! the ID of its name. +pub struct target { + pub var os: u32; #! The operating system's name, as `linux`. + pub var arch: u32; #! The processor's name, as `x86_64`. + pub var backend: u32; #! How the program runs, as `vm`. +} + +#! A type parameter standing for a type a bound asks of another, as `C::cursor` +#! where `C: walk`, which becomes the type the type given for `C` gives. +pub struct checker::stand_in { + var base: u32; #! The type parameter's type it is asked of. + var asked: u32; #! The declaration of the type the bound asks for. + var param: u32; #! The declaration of the parameter standing for it. + var bound: u32; #! The bound asking for it. +} + +#! A branch of an `if const` whose condition only evaluating decides, around +#! what is checked. +pub struct checker::branch { + pub var table: u32; #! The result table the `if const` was checked in. + pub var node: u32; #! The `if_const` node. + pub var holds: bool; #! Whether it is the branch taken where the condition holds. +} + +#! A `compile_error` checking leaves to evaluating: one within branches of +#! `if const` only evaluating decides, reported where each is the one taken, or +#! one given text that is not written, which evaluating works out. +pub struct checker::held_error { + pub var table: u32; #! The result table it was checked in. + pub var node: u32; #! The `call` node. + var file: u32; #! The file it is reported in. + var place: u32; #! The node it is reported at: the call, or the declaration whose `at` it was given. + var decl: u32; #! The declaration whose body it is in. + var instance: u32; #! One more than the instance it was checked in, which its note names, or 0. + var detail: string; #! What it says, where checking knew it. + pub var first: u32; #! The first of the branches around it, in `held_branches`. + pub var count: u32; #! How many branches are around it. + pub var computed: bool; #! Whether evaluating works out what it says. +} + +#! The checker. +pub struct checker { + pub var names: &mut names; #! The names the files were lexed with, which the checker interns more into. + pub var sink: note_sink; #! Where what the checker finds is noted, kept or heard as it is made, which `max_notes` bounds. + pub var units: vector; #! The files it is given, by their index. + pub var types: type_table; #! Every type, by its ID. + pub var decls: decl_table; #! Every declaration, by its ID. + pub var modules: module_table; #! Every module, by its ID. + pub var target: target; #! The target the program is checked for. + pub var contracts_off: bool; #! Whether contracts are left out, conditions and all, as `--contracts off` asks. + pub var checks_off: bool; #! Whether the checks a checked build makes are left out, as a build without `--checks` and `run --fast` ask. + pub var at: checker::frame; #! Where checking is. + + # Results: a table for each file and each instance, whose nodes' types, + # what they refer to, and flags are runs of these columns, a row for each + # node. The few nodes that convert, or whose values are known, are found by + # their rows in maps of their own, rather than in columns mostly of zeros. + pub var tables: column; #! The result tables, of each file and each instance. + var r_types: column; #! The type of each node, by table. + var r_refs: column; #! What each node refers to, by table. + var r_flags: column; #! The flags of each node, by table. + var r_converts: keymap; #! The type each node converts to, where it is not its own, by its row. + var r_values: keymap; #! The constant each node is, by index in `constants`, by its row, where it is known. + var converts: keymap; #! The type a node no table holds converts to: `table << 32 | node`. + var values: keymap; #! The constant a node no table holds is, by index in `constants`: `table << 32 | node`. + var constants: column; #! The constants nodes and declarations are, each once, the first a zero constant standing for none. + var constant_index: id_index; #! The constants of each hash, which interning finds them by. + + # Bindings: the locals, parameters, and type parameters names refer to, a + # stack cut back where each scope ends. `innermost` holds one more than the + # binding of each name nearest the top. + var bind_names: vector; #! The name of each binding, from the bottom of the stack. + var bind_values: vector; #! What each binding refers to. + var bind_prev: vector; #! The binding of the same name each hides, plus one, or 0. + var innermost: vector; #! One more than the binding of each name nearest the top, by its name. + + # Declarations: those every program has, those declared through a type that + # wait for their type to resolve, and those of std the checker gives meaning. + var builtins: dict; #! The declaration of each built-in type, by its name. + pub var shelves: vector; #! The libraries the program's modules are found in, which completion lists the modules of by their folders. + var builtin_of: vector; #! The declaration of each built-in type, by its type. + var pending: vector; #! Declarations through a type, waiting for it to resolve. + var pending_imports: vector; #! Each import, as `file << 32 | node`, resolved once every module is declared. + pub var libraries: vector; #! Each `extern import` the target takes, as `file << 32 | node`, which names the library of its file's C functions. + var external: bool; #! Whether what is being declared is in an `extern module`, where functions without a body, structs, and unions are C's. + var cores_own: u32; #! How deeply what a trait of `core`'s asks for is being met, where `core`'s types meet it by `core`'s own members. + var known: dict; #! The declarations of std the checker knows, by name. + var selves: dict; #! The declaration `self` is within each trait. + var decl_values: column; #! One more than the constant each constant and enum member holds, by index in `constants`, or 0, by its declaration. + + # Generics. + pub var instances: vector; #! The instances of generic functions. + var instanced: keymap; #! One more than the instance of each template and arguments: `decl << 32 | args`. + var wants: vector; #! Instances used whose bodies are not yet checked. + var wants_checked: u64; #! How many of `wants` have been checked, which checking goes on from. + var satisfied: keymap; #! Whether a type satisfies a trait: `type << 32 | trait`. + var composed: column; #! One more than the run of the traits a struct, union, or trait names, once worked out, or 0, by its declaration. + var decl_bases: column; #! The first node of each generic declaration, whose nodes an instance's table holds, once worked out, or 0, by its declaration. + pub var called: keymap; #! One more than the instance a call uses: `table << 32 | node`. + var mirrors: column; #! The type's parameter each parameter a receiver names stands for, or 0, by the parameter. + var shapes: dict; #! The written shape of each declaration with a pattern among its type parameters, as `record_shape` makes it. + var only_bounds: dict; #! Whether each trait is only a bound, once worked out. + var outers: dict; #! The bounds each trait's method puts on the trait's type parameters and `self`, once worked out. + var locks: vector; #! What the loops around what is checked iterate. + var undecided: u32; #! How many `if const` and `for const` around what is checked are not decided. + pub var to_evaluate: vector; #! What only evaluating can work out, once checking is done: local constants, conditions of `if const`, and the text of `compile_error`, each as its table and node. + var branches: vector; #! The branches of `if const` only evaluating decides around what is checked, the outermost first. + pub var held_errors: vector; #! The `compile_error`s left to evaluating, in the order checking reached them. + pub var held_branches: vector; #! The branches around each held `compile_error`, a run of each. + + # Reflection: the descriptions of declarations, and what each expression of + # reflection gives, as `kind, descriptions...` runs of `reflected`. + pub var descs: vector; #! The descriptions of declarations reflection gives. + var desc_ids: keymap; #! Each description by `decl << 32 | param`. + var reflected: runs; #! What expressions of reflection give, as runs of `kind, descriptions...`. + var reflections: keymap; #! The run of `reflected` each node gives: `table << 32 | node`. + var lengths: keymap; #! How many values a view of reflection holds: `table << 32 | node`. + var consent: u32; #! A declaration reflection reaches, which its attribute consents to. + var attr_decls: keymap; #! The declaration each attribute is as `attributes_of` gives it: `file << 32 | node`. + + # Dependencies, recorded as declarations are checked, for checking again + # only what an edit affects: from each top-level declaration to what it + # resolved, or to a name with `named_dependency` set. + pub var tracks: bool; #! Whether dependencies are recorded, which a program checked only once has no use for. + var dep_from: vector; #! Of each dependency, the declaration that resolved something. + var dep_to: vector; #! Of each dependency, what it resolved. + var dep_seen: keymap; #! Which dependencies are recorded, each as 1: `from << 32 | to`. + var depended: vector; #! Whether any declaration resolved each declaration, whether or not dependencies are recorded. + + # What walks each function's body to warn of what it keeps past what it + # refers to, made once and walking each in turn. + var lifetimes: lifetime_walk; #! The walk. + + # The evaluator: the frames of the calls it runs, each the values of its + # locals by the node declaring them, the elements of the arrays it holds, + # and the arrays constants hold. + var ev_frames: vector>; #! The locals of each call being evaluated, by the node declaring them. + var ev_heap: vector; #! The elements of the arrays being evaluated. + var ev_arrays: dict; #! The arrays constants hold, by the node declaring them. + var ev_result: ev; #! What the call being evaluated gives. + var ev_steps: u64; #! How many steps evaluation has taken, which a limit stops. + var ev_depth: u32; #! How deeply evaluation's calls nest. + var ev_site: u32; #! The node evaluation was asked at, which its failure is noted at. + var ev_file: u32; #! The file of that node. + var ev_failed: bool; #! Whether evaluation failed. + var projections: keymap; #! The parameter standing for a type a bound asks for: `param << 32 | asked`. + var stand_ins: vector; #! Each parameter standing for a type a bound asks for, which substituting its type parameter resolves. + + # Constants: the values constant type arguments are, each interned once. + var knowns: column; #! The values worked out while checking, by ID, the first standing for none. + var known_parts: runs; #! The parts of each, a run each. + var known_texts: vector; #! The bytes text values hold. + var known_index: id_index; #! The values of each hash, which interning finds them by. + + # Bounds an `if const` proved of type parameters, for the branch it guards. + var proved_params: vector; #! The type parameters an `if const` proved bounds of. + var proved_bounds: vector; #! The bound proved of each. + + # Notes. + var failed: bool; #! Whether the program is not valid. + var errors: u64; #! How many errors were reported, which a function's body must add none of to be warned of. + pub var skipped: u32; #! What was met that the checker does not check yet, and let through. + # Notes dropped while an argument is tried quietly, and how many of them were + # type arguments nothing gave, which tells one that needs another argument's + # type first from one that is wrong. + var mute: u32; #! Whether notes are dropped, where more than 0. + var dropped: u32; #! How many notes were dropped. + var uninferred: u32; #! How many of those were type arguments nothing gave. + var free_result: bool; #! Whether the next lambda takes its result from its body, or the next generic function named as a value from its parameters, whatever the type expected says. + var generic_names: vector; #! Whether a generic function is declared of each name, by its ID. + var owned_names: bool; #! Whether types declared through others are described with them, as `token::kind`, as an editor shows them. + var qualified_names: bool; #! Whether types are described with the modules they're declared in, as `path_of` spells them. +} + +#! The most notes the checker makes. +pub const checker::max_notes: u32 = 200; + +#! How many notes the checker has made, whether kept in its notes or heard as +#! they were made. +#! @param this The checker. +#! @returns How many, at most `max_notes`. +pub val checker::notes_made: u32 { get => this.sink.count; } + +#! How deeply type arguments may nest, which a generic instantiating itself +#! with ever larger types soon passes. +pub const checker::max_nesting: u32 = 32; + +#! The most instances the checker makes. +pub const checker::max_instances: u32 = 65536; + +#! Makes a checker of the names the files were lexed with, which notes what it +#! finds in `notes`. +#! @param names The names the files were lexed with. +#! @param notes Where what the checker finds is noted. +#! @returns The checker, which knows the built-in types and the names it looks +#! for. +pub def checker::new(names: &mut names, notes: &mut vector): checker { + var made := checker { + names = names, + sink = note_sink::new(notes, checker::max_notes), + units = vector::::new(), + types = type_table::new(), + decls = decl_table::new(), + modules = module_table::new(), + tables = column::::new(), + r_types = column::::new(), + r_refs = column::::new(), + r_flags = column::::new(), + r_converts = keymap::new(), + r_values = keymap::new(), + converts = keymap::new(), + values = keymap::new(), + constants = column::::new(), + constant_index = id_index::new(), + bind_names = vector::::new(), + bind_values = vector::::new(), + bind_prev = vector::::new(), + innermost = vector::::new(), + builtins = dict::::new(), + shelves = vector::::new(), + builtin_of = vector::::new(), + pending = vector::::new(), + pending_imports = vector::::new(), + libraries = vector::::new(), + known = dict::::new(), + selves = dict::::new(), + decl_values = column::::new(), + instances = vector::::new(), + instanced = keymap::new(), + wants = vector::::new(), + satisfied = keymap::new(), + composed = column::::new(), + decl_bases = column::::new(), + called = keymap::new(), + mirrors = column::::new(), + shapes = dict::::new(), + only_bounds = dict::::new(), + outers = dict::::new(), + locks = vector::::new(), + descs = vector::::new(), + desc_ids = keymap::new(), + reflected = runs::::new(), + reflections = keymap::new(), + lengths = keymap::new(), + attr_decls = keymap::new(), + tracks = true, + dep_from = vector::::new(), + dep_to = vector::::new(), + dep_seen = keymap::new(), + lifetimes = lifetime_walk::new(), + depended = vector::::new(), + ev_frames = vector::>::new(), + ev_heap = vector::::new(), + ev_arrays = dict::::new(), + projections = keymap::new(), + stand_ins = vector::::new(), + knowns = column::::new(), + known_parts = runs::::new(), + known_texts = vector::::new(), + known_index = id_index::new(), + generic_names = vector::::new(), + proved_params = vector::::new(), + proved_bounds = vector::::new(), + to_evaluate = vector::::new(), + branches = vector::::new(), + held_errors = vector::::new(), + held_branches = vector::::new() + }; + + # Constant 0 stands for none, and is the integer 0 too. + _ = made.intern_constant(constant {}); + made.declare_builtins(); + made.target = target { + os = made.names.intern(&"linux"), + arch = made.names.intern(&"x86_64"), + backend = made.names.intern(&"vm") + }; + # Known value 0 stands for none. + made.knowns.append(known {}); + return made; +} + +#! Gives the checker a file to check, lexed with its names and parsed. +#! @param this The checker. +#! @param source The file's source. +#! @param syntax What it parsed into. +#! @param root Its `document` node. +#! @returns The index of the file, which its notes give. +pub def checker::add(&mut this, source: &source, syntax: &syntax, root: u32): u32 { + val file := this.units.length as u32; + val table := this.add_table(file, 0, syntax.node_count as u32, 0); + this.units.append(unit { + source = source, + syntax = syntax, + root = root, + table = table, + parses = syntax.parses + }); + return file; +} + +#! Checks the files given: declares what each declares, resolves what each +#! declaration is, then checks the bodies of functions and the values of +#! variables, and then the bodies of the instances of generics they use. +#! @param this The checker. +#! @returns Whether the program is valid. +pub def checker::check(&mut this): bool { + for file in 0..this.units.length { + this.declare_unit(file as u32); + } + + this.link(); + this.name_types(); + for id in 1..this.decls.count { + this.resolve(id as u32); + } + + for id in 1..this.decls.count { + this.check_decl(id as u32); + } + + this.check_wanted(); + return !this.failed; +} + +#! A built-in type and the names it goes by. +struct checker::builtin_name { + val text: strview; + val kind: bt; +} + +const _builtin_names: checker::builtin_name[15] = [ + checker::builtin_name { text = "void", kind = bt::void_type }, + checker::builtin_name { text = "bool", kind = bt::boolean }, + checker::builtin_name { text = "i8", kind = bt::int8 }, + checker::builtin_name { text = "i16", kind = bt::int16 }, + checker::builtin_name { text = "i32", kind = bt::int32 }, + checker::builtin_name { text = "i64", kind = bt::int64 }, + checker::builtin_name { text = "u8", kind = bt::uint8 }, + checker::builtin_name { text = "u16", kind = bt::uint16 }, + checker::builtin_name { text = "u32", kind = bt::uint32 }, + checker::builtin_name { text = "u64", kind = bt::uint64 }, + checker::builtin_name { text = "f32", kind = bt::float32 }, + checker::builtin_name { text = "f64", kind = bt::float64 }, + checker::builtin_name { text = "int", kind = bt::int64 }, + checker::builtin_name { text = "uint", kind = bt::uint64 }, + checker::builtin_name { text = "float", kind = bt::float64 }, +]; + +#! Declares the built-in types, one declaration for each type, which every +#! name it goes by finds, so `int::f` and `i64::f` are methods of one type. +#! @param this The checker. +def checker::declare_builtins(&mut this): void { + this.builtin_of.resize(bt::count as u64); + + for &each in _builtin_names { + val name := this.names.intern(&each.text); + var decl: u32 = this.builtin_of[each.kind as u64]; + if decl == 0 { + decl = this.decls.add(dk::builtin, name, 0, 0, 0); + this.decls.types.p[decl as u32] = each.kind; + this.decls.states.p[decl as u32] = ds::resolved; + this.decls.mark(decl, df::exported); + this.builtin_of[each.kind as u64] = decl; + } + this.builtins.set(name, decl); + } +} diff --git a/analyzer/checker/access.sakura b/analyzer/checker/access.sakura new file mode 100644 index 00000000..dc523432 --- /dev/null +++ b/analyzer/checker/access.sakura @@ -0,0 +1,918 @@ +#! @file access.sakura +#! @author John Christman (sorakatadzuma@gmail.com) +#! @copyright Malunal Studios, LLC. +#! @license MIT +#! +#! Contains the checking of what reaches into a value: its members, as a field +#! or a property, and its elements, by an index or a slice. Each reaches +#! through references and pointers, so `p.field` and `r[i]` work where `p` and +#! `r` point at what has them. + +module sakura::analyzer; + + +#! What a value of the type is once read through its references, however many +#! there are. A pointer is an address, so nothing is reached through it. +#! @param this The checker. +#! @param kind The type. +#! @returns What it reaches, or the type itself where it is no reference. +pub def checker::reached(&mut this, kind: u32): u32 { + var at := kind; + var steps := 0; + while this.types.kind_of(this.unalias(at)) == ty::reference && steps < 8 { + at = this.types.first_of(this.unalias(at)); + steps++; + } + return at; +} + +#! Whether what a value of the type reaches through can be written: a `&mut` +#! reference or a `*mut` pointer, where it reaches through one. +#! @param this The checker. +#! @param kind The type. +#! @param object The node of the value, which says whether it can be written +#! where it is no reference. +#! @returns Whether it can be. +def checker::reaches_writable(&mut this, kind: u32, object: u32): bool { + var at := this.unalias(kind); + var steps := 0; + while this.types.kind_of(at) == ty::reference && steps < 8 { + val inner := this.unalias(this.types.first_of(at)); + if this.types.kind_of(inner) != ty::reference { + return this.types.second_of(at) != 0; + } + at = inner; + steps++; + } + return this.types.second_of(at) != 0 if this.types.kind_of(at) == ty::pointer; + return this.is_writable(object); +} + +#! What a member of a type is: the declaration, and the struct a spread field +#! is reached through. +pub struct checker::found { + pub var decl: u32; #! The member, or 0. + var owner: u32; #! The type it is a member of, given its arguments. +} + +#! The member of the name of a value of the type: a field, a property, or a +#! method, found on an alias before what it stands for, on a struct's spread +#! fields after its own, and on a type parameter among its bounds. +#! @param this The checker. +#! @param kind The type. +#! @param name The ID of the name. +#! @returns The member and the type it is of, or no member. +pub def checker::find_member(&mut this, kind: u32, name: u32): checker::found { + return this.find_member_of(kind, name, false); +} + +#! The member of the name of the type `::` reaches, as `token::kind`: a type +#! declared through it before a field of the same name, which only a value +#! reaches, and otherwise as `find_member` finds it. +#! @param this The checker. +#! @param kind The type. +#! @param name The ID of the name. +#! @returns The member and the type it is of, or no member. +pub def checker::find_path_member(&mut this, kind: u32, name: u32): checker::found { + return this.find_member_of(kind, name, true); +} + +#! The member of the name of the type, with a type declared through it before a +#! field of the same name where `types` says. +#! @param this The checker. +#! @param kind The type. +#! @param name The ID of the name. +#! @param types Whether a type declared through it comes first. +#! @returns The member and the type it is of, or no member. +def checker::find_member_of(&mut this, kind: u32, name: u32, types: bool): checker::found { + this.depend(this.type_decl(this.unalias(kind))); + var at := kind; + var steps := 0; + while steps < 16 { + steps++; + val decl := this.type_decl(at); + if decl != 0 { + val member := this.member_here(decl, name, types); + return checker::found { decl = member, owner = at } if member != 0; + } + + match this.types.kind_of(at) { + ty::named => { + val kind_of: dk = this.decls.kinds.p[this.types.first_of(at)]; + if kind_of == dk::alias_type { + at = this.alias_target(at); + continue; + } + if kind_of == dk::struct_type { + val spread := this.find_spread(at, name); + return spread if spread.decl != 0; + } + if kind_of == dk::struct_type || kind_of == dk::union_type { + return this.find_default(this.types.first_of(at), name, 0); + } + # A trait has the members of the traits it composes. + if kind_of == dk::trait_type { + val member := this.trait_member(this.types.first_of(at), name); + return checker::found { decl = member, owner = this.declaring_bound(at, member) } if member != 0; + } + return checker::found {}; + } + ty::param => return this.find_in_bounds(at, name); + else => return checker::found {}; + } + } + return checker::found {}; +} + +#! The default of the name a trait a struct or union names gives it, or one of +#! those a trait composes gives that trait: a method the trait writes a body +#! for, which the type has as its own where it does not write one itself. +#! @param this The checker. +#! @param decl The struct's, union's, or trait's declaration. +#! @param name The ID of the name. +#! @param depth How deeply composition has been followed. +#! @returns The default and the trait it is of, or no member. +def checker::find_default(&mut this, decl: u32, name: u32, depth: u32): checker::found { + return checker::found {} if depth > 16; + + val run := this.composed_of(decl); + for i in 0..this.decls.list_length(run) { + val trait_kind := this.decls.list_at(run, i as u32); + val holder := this.types.first_of(trait_kind); + val member := this.decls.member(holder, name); + if member != 0 && this.decls.kinds.p[member] == dk::function && this.has_body(member) + && this.trait_asks(member) { + return checker::found { decl = member, owner = trait_kind }; + } + val inner := this.find_default(holder, name, depth + 1); + return inner if inner.decl != 0; + } + return checker::found {}; +} + +#! The field of the name among the fields a struct's spread fields bring in. +#! @param this The checker. +#! @param kind The struct's type. +#! @param name The ID of the name. +#! @returns The field and the struct it is of, or no member. +def checker::find_spread(&mut this, kind: u32, name: u32): checker::found { + val decl := this.types.first_of(kind); + val run: u32 = this.decls.children.p[decl]; + for i in 0..this.decls.list_length(run) { + val field := this.decls.list_at(run, i as u32); + continue if this.decls.kinds.p[field] != dk::field || !this.is_spread(field); + + this.resolve(field); + val spread := this.instantiated(this.decls.types.p[field], decl, kind); + val inner := this.renamed(field, name); + val found := this.find_member(spread, inner); + if found.decl != 0 && this.decls.kinds.p[found.decl] == dk::field { + return found; + } + } + return checker::found {}; +} + +#! Whether a member is seen where checking is. One a module declares on a type +#! of another module, or on a built-in type, is seen within that module and +#! where a file imports it, as `std::math`'s `sqrt` of a `simd` is, and `core`'s +#! everywhere; so what a file means never hangs on what another file of the +#! program imports. A type's own members are seen wherever it is. +#! @param this The checker. +#! @param id The member. +#! @returns Whether it is. +pub def checker::member_seen(&this, id: u32): bool { + var at := id; + var owner: u32 = this.decls.owners.p[id]; + # An accessor is seen as its property is. + if owner != 0 && this.decls.kinds.p[owner] == dk::property { + at = owner; + owner = this.decls.owners.p[owner]; + } + return true if owner == 0; + val home: u32 = this.decls.modules.p[at]; + return true if this.decls.kinds.p[owner] != dk::builtin && this.decls.modules.p[owner] == home; + return true if this.modules.within(this.at.home, home) || this.in_core(home); + val imports: u32 = this.units[this.at.file].imports; + for &imported in this.decls.list_view(imports) { + return true if imported == home; + } + return false; +} + +#! Whether a module is `core` or one within it. +#! @param this The checker. +#! @param id The module. +#! @returns Whether it is. +pub def checker::in_core(&this, id: u32): bool { + var at := id; + var steps := 0; + while at != 0 && this.modules.parents[at] != 0 && steps < 64 { + at = this.modules.parents[at]; + steps++; + } + return at != 0 && this.modules.names[at] == word::core; +} + +#! The first of a member's overloads seen where checking is, or 0. +#! @param this The checker. +#! @param first The first of them, or 0. +#! @returns The overload, or 0. +pub def checker::first_seen(&this, first: u32): u32 { + return first if first == 0 || this.member_seen(first); + var walk := this.decls.walk_overloads(first); + while true { + val at := walk.next(); + return 0 if at == 0; + return at if this.member_seen(at); + } + return 0; +} + +#! The first of the type's members of the name seen where checking is, with a +#! type declared through it before a field of the same name where `types` says, +#! or 0. One declared outside `core` on `core`'s type is chosen over `core`'s +#! member or type of its name, where it is seen, and never within `core` or for +#! a trait of `core`'s. +#! @param this The checker. +#! @param decl The type's declaration. +#! @param name The ID of the name. +#! @param types Whether a type declared through it comes first. +#! @returns The member, whose overloads follow it, or 0. +pub def checker::member_here(&this, decl: u32, name: u32, types: bool): u32 { + if !this.in_core(this.at.home) && this.cores_own == 0 { + val added := this.first_seen(this.decls.added_member(decl, name)); + return added if added != 0; + } + return this.first_seen(types ? this.decls.path_member(decl, name) : this.decls.member(decl, name)); +} + +#! The overloads a call chooses from: those beginning with `first`, or `core`'s +#! of their name where they were declared outside `core` on `core`'s type and +#! none of them takes the arguments, so a program's overload of `core`'s +#! method is chosen where it fits, and `core`'s elsewhere. +#! @param this The checker. +#! @param first The first of the overloads `member_here` gave. +#! @param object The value a method is called on, or 0. +#! @param owner The type the method is of, given its arguments. +#! @param through The type it is reached through. +#! @param args The arguments' nodes. +#! @returns The first of the overloads chosen from. +pub def checker::overloads_for(&mut this, first: u32, object: u32, owner: u32, through: u32, args: span): u32 { + val behind := this.core_behind(first); + return first if behind == 0 || this.fits_overload(first, object, owner, through, args); + return behind; +} + +#! The first of the overloads a member of a type is among: those declared +#! outside `core` on `core`'s type are kept apart from `core`'s of their name. +#! @param this The checker. +#! @param id The member. +#! @returns The first of them, or 0 where it is no type's member. +pub def checker::first_member(&this, id: u32): u32 { + val owner: u32 = this.decls.owners.p[id]; + return 0 if owner == 0; + val name: u32 = this.decls.names.p[id]; + val added := this.decls.added_member(owner, name); + return added if added != 0 && !this.in_core(this.decls.modules.p[id]); + return this.decls.member(owner, name); +} + +#! `core`'s members of the name seen where checking is, behind those a module +#! outside `core` declared on `core`'s type, or 0 where these are not those. +#! @param this The checker. +#! @param first The first of the members `member_here` gave. +#! @returns The first of `core`'s, or 0. +pub def checker::core_behind(&this, first: u32): u32 { + val holder: u32 = this.decls.owners.p[first]; + return 0 if first == 0 || holder == 0 || this.in_core(this.decls.modules.p[first]); + val name: u32 = this.decls.names.p[first]; + return 0 if this.decls.added_member(holder, name) == 0; + return this.first_seen(this.decls.member_in(holder, name, false)); +} + +#! Reports a member named where it is not visible. A field a spread brings in +#! is as visible as the spread field and its own. +#! @param this The checker. +#! @param node The node naming it. +#! @param kind The type it is a member of. +#! @param member The member. +pub def checker::check_reaches(&mut this, node: u32, kind: u32, member: u32): void { + if !this.visible(member) { + this.report_hidden(node, member); + return; + } + return if this.decls.kinds.p[member] != dk::field; + val spread := this.spread_of(kind, this.decls.names.p[member]); + if spread != 0 && !this.visible(spread) { + this.report_hidden(node, spread); + } +} + +#! The spread field of a struct a field of the name is brought in by, or 0 +#! where the struct declares it itself or has none of the name. +#! @param this The checker. +#! @param kind The struct's type. +#! @param name The ID of the name. +#! @returns The spread field, or 0. +def checker::spread_of(&mut this, kind: u32, name: u32): u32 { + val plain := this.unalias(kind); + return 0 if this.named_kind(plain) != dk::struct_type; + val decl := this.types.first_of(plain); + return 0 if this.decls.member(decl, name) != 0; + + val run: u32 = this.decls.children.p[decl]; + for i in 0..this.decls.list_length(run) { + val field := this.decls.list_at(run, i as u32); + continue if this.decls.kinds.p[field] != dk::field || !this.is_spread(field); + this.resolve(field); + val spread := this.instantiated(this.decls.types.p[field], decl, plain); + val found := this.find_member(spread, this.renamed(field, name)); + return field if found.decl != 0 && this.decls.kinds.p[found.decl] == dk::field; + } + return 0; +} + +#! Whether a field spreads another struct's fields into its own. +#! @param this The checker. +#! @param field The field's declaration. +#! @returns Whether it does. +pub def checker::is_spread(&this, field: u32): bool { + val syntax := &this.units[this.decls.files.p[field]].syntax; + val record := syntax.node_lefts[this.decls.nodes.p[field]]; + val written := syntax.extras[record as u64 + variable_slot::type_expr as u64]; + return written != 0 && syntax.node_kinds[written] == nk::spread; +} + +#! The name a spread field's struct gives the field a rename calls `name`, as +#! `x` where `x as left` renames it `left`, or `name` itself. +#! @param this The checker. +#! @param field The spread field's declaration. +#! @param name The ID of the name it is reached by. +#! @returns The ID of the name its struct gives it. +def checker::renamed(&this, field: u32, name: u32): u32 { + val syntax := &this.units[this.decls.files.p[field]].syntax; + val record := syntax.node_lefts[this.decls.nodes.p[field]]; + val written := syntax.extras[record as u64 + variable_slot::type_expr as u64]; + for &rename in syntax.run_view(syntax.node_rights[written]) { + val target := syntax.node_lefts[rename]; + if syntax.token_names[syntax.node_tokens[target]] == name { + return syntax.token_names[syntax.node_tokens[rename]]; + } + } + return name; +} + +#! The member of the name a type parameter has through the traits bounding it. +#! @param this The checker. +#! @param kind The type parameter's type. +#! @param name The ID of the name. +#! @returns The member and the trait it is of, or no member. +def checker::find_in_bounds(&mut this, kind: u32, name: u32): checker::found { + val param := this.types.first_of(kind); + this.resolve(param); + val run: u32 = this.decls.children.p[param]; + for i in 0..this.decls.list_length(run) { + val bound := this.decls.list_at(run, i as u32); + val member := this.trait_member(this.types.first_of(bound), name); + return checker::found { decl = member, owner = this.declaring_bound(bound, member) } if member != 0; + } + + # What an `if const` proved of it, in the branch it guards. + for i in 0..this.proved_params.length { + continue if this.proved_params[i] != param; + val bound: u32 = this.proved_bounds[i]; + val member := this.trait_member(this.types.first_of(bound), name); + return checker::found { decl = member, owner = this.declaring_bound(bound, member) } if member != 0; + } + + # Within a trait, `self` has the trait's members. + if this.decls.names.p[param] == names::self_id && this.decls.owners.p[param] != 0 { + val holder: u32 = this.decls.owners.p[param]; + val member := this.trait_member(holder, name); + return checker::found { decl = member, owner = this.declaring_bound(this.decls.types.p[holder], member) } if member != 0; + } + return checker::found {}; +} + +#! The trait, given its arguments, that declares a member a bound has: the +#! bound itself, or a trait it composes, in terms of the bound's arguments, as +#! `into` of `pair: into`. +#! @param this The checker. +#! @param bound The bound's type. +#! @param member The member. +#! @returns The trait's type. +def checker::declaring_bound(&mut this, bound: u32, member: u32): u32 { + val declarer := this.enclosing_trait(member); + return bound if declarer == 0 || this.types.kind_of(this.unalias(bound)) != ty::named; + return this.bound_for(this.unalias(bound), declarer); +} + +#! The member of the name a trait has, its own or a trait's it composes. +#! @param this The checker. +#! @param trait_decl The trait's declaration. +#! @param name The ID of the name. +#! @returns The member, or 0. +pub def checker::trait_member(&mut this, trait_decl: u32, name: u32): u32 { + val own := this.decls.member(trait_decl, name); + return own if own != 0 && this.trait_asks(own); + + this.resolve_composed(trait_decl); + val held := this.composed.at_or_zero(trait_decl); + val run: u32 = held != 0 ? held - 1 : 0; + for i in 0..this.decls.list_length(run) { + val inner := this.decls.list_at(run, i as u32); + val found := this.trait_member(this.types.first_of(inner), name); + return found if found != 0; + } + return 0; +} + +#! Whether a value of the type has a method of the name: its own, through a +#! bound, or one the compiler gives a built-in type. +#! @param this The checker. +#! @param kind The type. +#! @param name The ID of the name. +#! @returns Whether it has. +pub def checker::has_method(&mut this, kind: u32, name: u32): bool { + val found := this.find_member(kind, name); + if found.decl != 0 { + return this.decls.kinds.p[found.decl] == dk::function; + } + return this.builtin_method(kind, name) != 0; +} + +#! The type of the method the compiler gives a built-in type, as `equals` of a +#! number, or 0: every number has `equals`, `hash`, `compare`, and the methods +#! of `numeric`, and `bool`, enums, and pointers have `equals` and `hash`, and +#! enums and pointers `compare`. A fixed array has `equals` and `hash` where +#! its elements do. +#! @param this The checker. +#! @param kind The built-in type. +#! @param name The ID of the method's name. +#! @returns The method's type, or 0. +pub def checker::builtin_method(&mut this, kind: u32, name: u32): u32 { + val plain := this.unalias(kind); + # A function, and the address of a C function, are called by an `invoke` + # taking what they take, which makes each `invokable` of its own type. + if name == word::invoke { + val function := this.signature_function(plain); + return 0 if function == 0; + var taken := vector::::new(); + taken.append(this.types.reference(kind, false)); + taken.extend(this.types.parts_view(function)); + return this.types.function(taken.view(), this.types.first_of(function), this.types.second_of(function) != 0); + } + # A fixed array has `equals` and `hash` where its elements do. + if this.types.kind_of(plain) == ty::fixed { + return 0 if this.types.part_count(plain) != 0 || (name != word::equals && name != word::hash); + return 0 if !this.has_method(this.types.first_of(plain), name); + var taken := vector::::new(); + taken.append(this.types.reference(kind, false)); + if name == word::equals { + taken.append(this.types.reference(kind, false)); + return this.types.function(taken.view(), bt::boolean, false); + } + return this.types.function(taken.view(), bt::uint64, false); + } + val number := this.types.is_numeric(plain) && !this.types.is_untyped(plain); + val ordered := number || this.named_kind(plain) == dk::enum_type || this.types.kind_of(plain) == ty::pointer; + val equal := ordered || this.types.kind_of(plain) == ty::boolean; + val this_ref := this.types.reference(kind, false); + + var params := vector::::new(); + params.append(this_ref); + if name == word::equals && equal { + params.append(this_ref); + return this.types.function(params.view(), bt::boolean, false); + } + if name == word::hash && equal { + return this.types.function(params.view(), bt::uint64, false); + } + if name == word::compare && ordered { + params.append(this_ref); + return this.types.function(params.view(), bt::int64, false); + } + if number && (name == word::add || name == word::sub || name == word::mul + || name == word::div || name == word::rem) { + params.append(this_ref); + return this.types.function(params.view(), kind, false); + } + if number && name == word::negate { + return this.types.function(params.view(), kind, false); + } + # Integers give their bitwise operators and shifts as methods too, a shift + # taking how far as a `u32`. + val integer := number && this.types.is_integer(plain); + if integer && (name == word::bit_and || name == word::bit_or || name == word::bit_xor) { + params.append(this_ref); + return this.types.function(params.view(), kind, false); + } + if integer && (name == word::shift_left || name == word::shift_right) { + params.append(this.types.reference(bt::uint32, false)); + return this.types.function(params.view(), kind, false); + } + if integer && name == word::bit_not { + return this.types.function(params.view(), kind, false); + } + return 0; +} + +#! `x.name`: a field, a property, or the length of a fixed array. +#! @param this The checker. +#! @param node The `member` node. +#! @returns The member's type, or the error type where the value has none of the +#! name. +def checker::member(&mut this, node: u32): u32 { + val object := this.left_of(node); + val name := this.name_of(node); + # A pack of types has a length as a pack of values does, as `Ts.length` of + # `def f()`, known in each instance. + if name == word::length && this.kind_of(object) == nk::name { + val named := this.tested_type(object); + if named != 0 && named != bt::error && this.types.kind_of(this.unalias(named)) == ty::pack { + if !this.types.is_open_pack(this.unalias(named)) { + this.set_value(node, constant::integer(this.types.part_count(this.unalias(named)) as u64, false)); + } + return bt::uint64; + } + } + # A constant settles as it would alone, so `"text".length` is a `strview`'s. + var kind := this.infer_expr(object); + return bt::error if kind == bt::error; + if this.types.is_untyped(kind) { + kind = this.settle_expr(object); + } + + val through := this.reached(kind); + val plain := this.unalias(through); + # Within a template, a length only each instance knows is no constant there. + if this.types.kind_of(plain) == ty::fixed && name == word::length { + if this.types.part_count(plain) == 0 { + this.set_value(node, constant::integer(this.types.second_of(plain) as u64, false)); + } + return bt::uint64; + } + + # A pack's length is how many types it has, known in each instance. + if this.types.kind_of(plain) == ty::pack { + if name != word::length { + this.report(node, ec::member, "A pack has only `length`; each of its values is reached with `for const` or `args[i]`."); + return bt::error; + } + if !this.types.is_open_pack(plain) { + this.set_value(node, constant::integer(this.types.part_count(plain) as u64, false)); + } + return bt::uint64; + } + + val found := this.find_member(through, name); + if found.decl == 0 { + this.report_no_member(node, through, name); + return bt::error; + } + this.check_reaches(node, through, found.decl); + + # What reflection gives says some of itself while checking. + val one := this.reflected_one(object); + if one != checker::no_reflection { + this.reflected_field(node, one, name); + } + if name == word::length { + val key := this.result_key(object); + if this.lengths.get(&key) is some(got) { + this.set_value(node, constant::integer(got as u64, false)); + } else { + val list := this.reflected_at(object); + if list != checker::no_reflection && this.reflected_kind(list) == rk::list as u32 { + this.set_value(node, constant::integer(this.reflected_count(list) as u64, false)); + } + } + } + + this.set_ref(node, found.decl); + match this.decls.kinds.p[found.decl] { + dk::field => { + this.resolve(found.decl); + val owner := this.types.first_of(found.owner); + val held := this.instantiated(this.decls.types.p[found.decl], owner, found.owner); + val writes := this.reaches_writable(kind, object) && this.decls.has(found.decl, df::mutable); + this.mark_place(node, writes || (this.named_kind(found.owner) == dk::union_type && this.reaches_writable(kind, object))); + if this.types.kind_of(this.unalias(kind)) != ty::reference && this.types.kind_of(this.unalias(kind)) != ty::pointer + && !this.is_place(object) { + this.clear_flag(node, rf::place); + this.clear_flag(node, rf::writable); + } + return held; + } + dk::property => { + # A property's type names the parameters its receiver did. + this.resolve(found.decl); + val property: u32 = this.decls.types.p[found.decl]; + val named := this.types.kind_of(found.owner) == ty::named; + val held := named ? this.instantiated(property, found.decl, found.owner) : property; + if this.property_setter(found.decl) != 0 && this.reaches_writable(kind, object) { + this.set_flag(node, rf::writable); + } + this.want_accessor(this.property_getter(found.decl), found.owner, node); + return held; + } + dk::function => { + this.report(node, ec::not_value, "A method is called, as `x.name()`; take it through its type, as `T::name`, for its value."); + return bt::error; + } + else => { + this.report(node, ec::member, "Only fields, properties, and methods are reached with `.`; reach this through its type with `::`."); + return bt::error; + } + } + return bt::error; +} + +#! The getter of a property, or 0 where it has none. +#! @param this The checker. +#! @param property The property's declaration. +#! @returns The getter's declaration, or 0. +pub def checker::property_getter(&this, property: u32): u32 { + val run: u32 = this.decls.children.p[property]; + for &accessor in this.decls.list_view(run) { + return accessor if !this.decls.has(accessor, df::setter); + } + return 0; +} + +#! The setter of a property, or 0 where it has none. +#! @param this The checker. +#! @param property The property's declaration. +#! @returns The setter's declaration, or 0. +pub def checker::property_setter(&this, property: u32): u32 { + val run: u32 = this.decls.children.p[property]; + for &accessor in this.decls.list_view(run) { + return accessor if this.decls.has(accessor, df::setter); + } + return 0; +} + +#! Asks for the instance of a generic type's property accessor that a value of +#! the type given its arguments reaches, so its body is checked, as a method's +#! called is, rather than only once lowering asks for it. +#! @param this The checker. +#! @param accessor The accessor's declaration, or 0. +#! @param owner The type the property was found on. +#! @param node The node a note is placed at, where too many instances +#! are made. +pub def checker::want_accessor(&mut this, accessor: u32, owner: u32, node: u32): void { + return if accessor == 0; + this.resolve(accessor); + val plain := this.unalias(owner); + return if !this.decls.has(accessor, df::generic) || this.trait_asks(accessor) || this.types.kind_of(plain) != ty::named; + val args := this.types.parts_of(plain); + this.instance_of(accessor, args.view(), node); +} + +#! Reports a member a type does not have. +#! @param this The checker. +#! @param node The `member` node. +#! @param kind The type. +#! @param name The ID of the name. +def checker::report_no_member(&mut this, node: u32, kind: u32, name: u32): void { + if this.types.kind_of(this.unalias(kind)) == ty::pointer { + var said := string::from("A pointer is an address, whose only members are `equals`, `compare`, and `hash`. Reach what it points at with `(*p).", nothing {}); + val member := this.names.text(name); + said.append(member); + said.append("`, `p[0]."); + said.append(member); + said.append("`, or `through(p)."); + said.append(member); + said.append("`."); + this.report_text(node, ec::member, &said); + return; + } + var text := string::from("`", nothing {}); + val named := this.describe(kind); + text.append(named.view()); + # A module may declare one on the type that this file does not see. + val decl := this.type_decl(this.unalias(kind)); + val unseen := decl == 0 ? 0 : this.decls.member(decl, name); + if unseen != 0 && !this.member_seen(unseen) { + var holder := string::new(nothing {}); + this.module_text(this.decls.modules.p[unseen], &mut holder); + text.append("` has `"); + text.append(this.names.text(name)); + text.append("` where `"); + text.append(holder.view()); + text.append("` is imported, as `import "); + text.append(holder.view()); + text.append(";`, since that module declares it."); + this.report_text(node, ec::member, &text); + return; + } + text.append("` has no field, property, or method `"); + text.append(this.names.text(name)); + text.append("`."); + this.report_text(node, ec::member, &text); +} + +#! `x[i]`: an element of a fixed array, of what a pointer points at, or of what +#! implements `indexable` through its `at`, which is the reference `at` gives. +#! @param this The checker. +#! @param node The `index` node. +#! @returns The element's type, the reference to it `at` gives, or the error +#! type where the value cannot be indexed. +def checker::index(&mut this, node: u32): u32 { + val object := this.left_of(node); + val at := this.right_of(node); + # A constant settles as it would alone, so `"text"[0]` is a `strview`'s. + var kind := this.infer_expr(object); + if kind == bt::error { + this.infer_expr(at); + return bt::error; + } + if this.types.is_untyped(kind) { + kind = this.settle_expr(object); + } + + # A reference is indexed through, but a pointer is indexed itself. + val through := this.reached_value(kind); + val plain := this.unalias(through); + match this.types.kind_of(plain) { + ty::fixed => { + this.check_index(at); + # Within a template, a length only each instance knows is theirs to check. + if this.is_known(at) && this.types.part_count(plain) == 0 + && this.value_at(at).magnitude >= this.types.second_of(plain) as u64 { + this.report(at, ec::overflow, "The index is past the end of the array."); + } + this.mark_place(node, this.reaches_writable(kind, object)); + + # An element of a constant array, at an index known, is known. + val held := this.ref_at(object); + if held != 0 && (held & (ref_local | ref_type)) == 0 && this.ev_arrays.contains(&held) && this.is_known(at) { + val array: ev = this.ev_arrays[held]; + val index := this.value_at(at).magnitude; + if index < array.count as u64 { + this.set_value(node, this.ev_heap[array.start as u64 + index]); + } + } + return this.types.first_of(plain); + } + ty::pointer => { + this.check_index(at); + this.mark_place(node, this.types.second_of(plain) != 0); + return this.types.first_of(plain); + } + ty::pack => { + # `args[i]` is one of a pack's values, at an index known while compiling, + # of a type known in each instance. + this.check_index(at); + this.mark_place(node, this.reaches_writable(kind, object)); + if this.types.is_open_pack(plain) { + return this.types.param(this.types.first_of(plain)); + } + if !this.is_known(at) { + this.report(at, ec::constant, "A pack's values are reached at an index known while compiling."); + return bt::error; + } + val index := this.value_at(at).magnitude; + if index >= this.types.part_count(plain) as u64 { + this.report(at, ec::overflow, "The index is past the last of the pack's values."); + return bt::error; + } + return this.pack_value_type(plain, index as u32); + } + else => {} + } + + # What implements `indexable` gives the place its `at` refers to, and the one + # taking `&mut this` where the value can be written. A slice writes what it + # views however it is held, as a `*mut` pointer does. + val writes := this.reaches_writable(kind, object) || this.is_std(this.unalias(through), word::slice); + val method := this.pick_at(through, writes); + if method == 0 { + var text := string::from("`", nothing {}); + val named := this.describe(kind); + text.append(named.view()); + text.append("` is not indexed: a type is by implementing `indexable`."); + this.report_text(node, ec::member, &text); + this.infer_expr(at); + return bt::error; + } + + val signature := this.method_type(method, through); + if this.types.part_count(signature) >= 2 { + this.check_expr(at, this.types.part_at(signature, 1)); + } + this.set_ref(node, method); + + # An element of a list of reflection, at an index known, describes one. + val list := this.reflected_at(object); + if list != checker::no_reflection && this.reflected_kind(list) == rk::list as u32 && this.is_known(at) { + val index := this.value_at(at).magnitude; + if index < this.reflected_count(list) as u64 { + var items := vector::::new(); + items.append(this.reflected_item(list, index as u32)); + this.set_reflected(node, rk::one, items.view()); + } + } + + # `x[k]` is `x.at(k)`: the reference it gives, `&V` or `&mut V`, which is + # read, written, and bound as any reference is, so it copies nothing. + return this.types.first_of(signature); +} + +#! Checks an index of an array or a pointer, which is an integer. +#! @param this The checker. +#! @param node The index's node. +def checker::check_index(&mut this, node: u32): void { + val kind := this.infer_expr(node); + return if kind == bt::error; + if this.types.is_untyped(kind) { + this.check_expr(node, bt::uint64); + } else if !this.types.is_integer(this.read_type(kind)) { + this.report_operand(node, kind, "An index is an integer."); + } +} + +#! The `at` of a type indexing it: the one taking `&mut this` where `writes` +#! says and there is one, or else the one taking `&this`, or 0. +#! @param this The checker. +#! @param kind The type. +#! @param writes Whether the element is written. +#! @returns The method's declaration, or 0. +pub def checker::pick_at(&mut this, kind: u32, writes: bool): u32 { + val found := this.find_member(kind, word::at); + return 0 if found.decl == 0 || this.decls.kinds.p[found.decl] != dk::function; + + # Through a type parameter's bound, the accessor that writes is `@optional`, and + # no bound promises it. + val bounded := this.types.kind_of(this.unalias(kind)) == ty::param; + var reads: u32 = 0; + var walk := this.decls.walk_overloads(found.decl); + while true { + val at := walk.next(); + break if at == 0; + if this.decls.has(at, df::method) && !(bounded && this.decls.has(at, df::optional)) && this.member_seen(at) { + if this.decls.has(at, df::mut_this) { + return at if writes; + } else if reads == 0 { + reads = at; + } + } + } + return reads != 0 ? reads : (writes ? 0 : found.decl); +} + +#! The type of a method of a value of the type, given the type's arguments. +#! @param this The checker. +#! @param method The method's declaration. +#! @param kind The type of the value. +#! @returns The method's type. +pub def checker::method_type(&mut this, method: u32, kind: u32): u32 { + this.resolve(method); + if this.trait_asks(method) { + return this.trait_method_type(method, kind); + } + val plain := this.unalias(kind); + return this.member_function_type(method, this.types.kind_of(plain) == ty::named ? plain : kind); +} + +#! `x[start:count]`: a view of the elements of a fixed array, of what a pointer +#! points at, or of another view, which writes where they can be written. +#! @param this The checker. +#! @param node The `slice` node. +#! @returns The view's type, or the error type where the value cannot be sliced. +def checker::slice(&mut this, node: u32): u32 { + val object := this.left_of(node); + val kind := this.infer_expr(object); + val start := this.record(node, slice_slot::start); + val count := this.record(node, slice_slot::count); + if start != 0 { this.check_index(start); } + if count != 0 { this.check_index(count); } + return bt::error if kind == bt::error; + + val through := this.reached_value(kind); + val plain := this.unalias(through); + var element: u32 = bt::error; + var writes := false; + match this.types.kind_of(plain) { + ty::fixed => { + element = this.types.first_of(plain); + writes = this.reaches_writable(kind, object); + } + ty::pointer => { + element = this.types.first_of(plain); + writes = this.types.second_of(plain) != 0; + } + else => { + if this.is_std(plain, word::span) || this.is_std(plain, word::slice) { + return plain; + } + this.report_operand(node, kind, "A slice is taken of a fixed array, a pointer, or a view."); + return bt::error; + } + } + + var args := vector::::new(); + args.append(element); + return this.std_type(writes ? word::slice : word::span, args.view()); +} diff --git a/analyzer/checker/attributes.sakura b/analyzer/checker/attributes.sakura new file mode 100644 index 00000000..5b26d224 --- /dev/null +++ b/analyzer/checker/attributes.sakura @@ -0,0 +1,292 @@ +#! @file attributes.sakura +#! @author John Christman (sorakatadzuma@gmail.com) +#! @copyright Malunal Studios, LLC. +#! @license MIT +#! +#! Contains the checking of attributes. An attribute is a struct literal of a +#! struct declaring `attribute`, written before a declaration with `@`, whose +#! fields are checked as any literal's are. A struct's `@usage` says what kinds +#! of declaration its attributes may describe, and whether one may have more +#! than one of them. + +module sakura::analyzer; + + +#! What a struct's `@usage` allows of its attributes. +pub struct checker::usage { + var on: u64; #! The bits of `core::target` it may be written on. + var many: bool; #! Whether a declaration may have more than one. +} + +#! Checks the attributes written before the declaration. +#! @param this The checker. +#! @param id The declaration. +pub def checker::check_attributes(&mut this, id: u32): void { + val node: u32 = this.decls.nodes.p[id]; + val attrs := this.attributes_of(node); + return if this.run_length(attrs) == 0; + + val attribute := this.std_decl(word::attribute); + var seen := vector::::new(); + for &attr in this.run_view(attrs) { + continue if this.kind_of(attr) != nk::attribute; + + # What C gives was written with attributes before `extern` sections were. + val named := this.left_of(attr); + val name := this.segment_name(named, this.segment_count(named) - 1); + if (name == word::foreign || name == word::link) && this.segment_count(named) == 1 + && this.lookup_named(name, attr, true).decl == 0 { + this.report(attr, ec::invalid, + "`@foreign` and `@link` are gone: C's functions, structs, and unions are declared in an `extern module`, and `extern import` names their library."); + continue; + } + + val kind := this.resolve_type(this.left_of(attr)); + continue if kind == bt::error; + if this.named_kind(kind) != dk::struct_type || (attribute != 0 && !this.names_trait(kind, attribute)) { + var text := string::from("`", nothing {}); + val named := this.describe(kind); + text.append(named.view()); + text.append("` is not an attribute: an attribute's type is a struct declaring `attribute`."); + this.report_text(attr, ec::invalid, &text); + continue; + } + + this.construct_struct(attr, kind, this.right_of(attr)); + val decl := this.types.first_of(kind); + val usage := this.usage_of(decl); + val bit := this.target_bit(id); + if bit != 0 && (usage.on & bit) == 0 { + var text := string::from("`", nothing {}); + text.append(this.decl_text(decl)); + text.append("` is not written on "); + text.append(this.target_word(id)); + text.append(", as its `@usage` says."); + this.report_text(attr, ec::invalid, &text); + } + + # What is copied where it is called has a body to copy. + val written := this.decls.kinds.p[id]; + if name == word::inline && (written == dk::function || written == dk::property) + && (this.decls.has(id, df::intrinsic) || this.decls.has(id, df::foreign)) { + this.report(attr, ec::invalid, + "`@inline` copies a function's body where it is called, and a function C or the compiler gives has none."); + } + + if seen.view().contains(&decl) && !usage.many { + var text := string::from("`", nothing {}); + text.append(this.decl_text(decl)); + text.append("` is written once on a declaration, unless its `@usage` says `many = true`."); + this.report_text(attr, ec::duplicate, &text); + } + seen.append(decl); + } +} + +#! What a struct's `@usage` allows of its attributes, or anything, once each, +#! where it has none. +#! @param this The checker. +#! @param decl The attribute struct's declaration. +#! @returns What it may be written on, and whether more than once. +pub def checker::usage_of(&mut this, decl: u32): checker::usage { + var made := checker::usage { on = 0xFFFF, many = false }; + val usage := this.std_decl(word::usage); + return made if usage == 0; + + val saved := this.at; + this.enter_decl(decl, 0); + val attrs := this.attributes_of(this.decls.nodes.p[decl]); + for &attr in this.run_view(attrs) { + continue if this.kind_of(attr) != nk::attribute; + val named := this.left_of(attr); + continue if this.segment_name(named, this.segment_count(named) - 1) != word::usage; + + val inits := this.right_of(attr); + for &init in this.run_view(inits) { + val value := this.left_of(init); + this.infer_expr(value); + continue if !this.is_known(value); + val name := this.name_of(init); + if name == this.names.intern(&"on") { + made.on = this.value_at(value).magnitude; + } else if name == this.names.intern(&"many") { + made.many = this.value_at(value).magnitude != 0; + } + } + } + this.leave(saved); + return made; +} + +#! The bit of `core::target` the kind of declaration is, or 0 where std has none. +#! @param this The checker. +#! @param id The declaration. +#! @returns The bit, or 0. +pub def checker::target_bit(&mut this, id: u32): u64 { + val holder := this.std_decl(this.names.intern(&"target")); + return 0 if holder == 0; + + val member := this.decls.member(holder, this.names.intern(&this.target_name(id))); + var value := constant {}; + this.resolve(holder); + return 0 if member == 0 || !this.decl_value(member, &mut value); + return value.magnitude; +} + +#! The name of the member of `core::target` the kind of declaration is. +#! @param this The checker. +#! @param id The declaration. +#! @returns The name, as `functions`. +def checker::target_name(&mut this, id: u32): strview { + val owner: u32 = this.decls.owners.p[id]; + val in_trait := owner != 0 && this.decls.kinds.p[owner] == dk::trait_type && !this.receiver_declared(id); + return "requirements" if in_trait; + return match this.decls.kinds.p[id] { + dk::function => owner != 0 ? "methods" : "functions", + dk::variable => this.decls.has(id, df::constant) ? "constants" : "variables", + dk::field => "fields", + dk::struct_type => "structs", + dk::union_type => "unions", + dk::enum_type => "enums", + dk::enum_member => "members", + dk::trait_type => "traits", + dk::alias_type => "aliases", + dk::property => "properties", + dk::attribute => "constants", + else => "all" + }; +} + +#! The kind of declaration, as a note says it. +#! @param this The checker. +#! @param id The declaration. +#! @returns The words, as `a function`. +def checker::target_word(&mut this, id: u32): strview { + val owner: u32 = this.decls.owners.p[id]; + val in_trait := owner != 0 && this.decls.kinds.p[owner] == dk::trait_type && !this.receiver_declared(id); + return "what a trait declares" if in_trait; + return match this.decls.kinds.p[id] { + dk::function => owner != 0 ? "methods" : "functions", + dk::variable => this.decls.has(id, df::constant) ? "constants" : "variables", + dk::field => "fields", + dk::struct_type => "structs", + dk::union_type => "unions", + dk::enum_type => "enums", + dk::enum_member => "enum members", + dk::trait_type => "traits", + dk::alias_type => "aliases", + dk::property => "properties", + else => "this" + }; +} + +#! Checks a function given by C: never generic, overloaded, or a method, and of +#! parameters and a result whose types C lays out the same way. +#! @param this The checker. +#! @param id The function's declaration. +pub def checker::check_foreign(&mut this, id: u32): void { + val node: u32 = this.decls.nodes.p[id]; + if this.decls.has(id, df::generic) || this.decls.has(id, df::method) || this.decls.overloads.p[id] != 0 { + this.report(node, ec::invalid, "A C function is never generic, overloaded, or a method."); + return; + } + + val kind: u32 = this.decls.types.p[id]; + for i in 0..this.types.part_count(kind) { + val param := this.types.part_at(kind, i as u32); + if !this.crosses(param, true, 0) { + this.report_crossing(node, param); + } + } + val result := this.types.first_of(kind); + if result != bt::void_type && !this.crosses(result, false, 0) { + this.report_crossing(node, result); + } +} + +def checker::report_crossing(&mut this, node: u32, kind: u32): void { + var text := string::from("`", nothing {}); + val named := this.describe(kind); + text.append(named.view()); + text.append("` does not cross to C, which lays out only numbers, `bool`, enums, pointers, function pointers, and structs and C's unions of them."); + this.report_text(node, ec::invalid, &text); +} + +#! Checks a function given where C's address of one is expected, which C calls +#! back: never generic or a method, and of parameters and a result that cross. +#! @param this The checker. +#! @param node The node naming it. +#! @param id The function's declaration. +pub def checker::check_callback(&mut this, node: u32, id: u32): void { + if this.decls.has(id, df::generic) || this.decls.has(id, df::method) || this.decls.has(id, df::intrinsic) { + this.report(node, ec::invalid, "C calls back a function of the program that is neither generic, a method, nor `@intrinsic`."); + return; + } + + val kind: u32 = this.decls.types.p[id]; + for i in 0..this.types.part_count(kind) { + val param := this.types.part_at(kind, i as u32); + if !this.crosses(param, true, 0) { + this.report_crossing(node, param); + } + } + val result := this.types.first_of(kind); + if result != bt::void_type && !this.crosses(result, false, 0) { + this.report_crossing(node, result); + } +} + +#! Checks a struct or union of an `extern module`, which C lays out: never +#! generic, and of fields whose types cross. +#! @param this The checker. +#! @param id The type's declaration. +def checker::check_c_type(&mut this, id: u32): void { + val node: u32 = this.decls.nodes.p[id]; + if this.decls.has(id, df::generic) { + this.report(node, ec::invalid, "A struct or union of an `extern module` is laid out as C's, so it is never generic."); + return; + } + + val run: u32 = this.decls.children.p[id]; + for i in 0..this.decls.list_length(run) { + val field := this.decls.list_at(run, i as u32); + continue if this.decls.kinds.p[field] != dk::field; + this.resolve(field); + val kind: u32 = this.decls.types.p[field]; + if !this.crosses(kind, false, 1) { + this.report_crossing(this.decls.nodes.p[field], kind); + } + } +} + +#! Whether C lays out a value of the type as Sakura does: a number, `bool`, an +#! enum, a pointer, a function pointer, a reference where it is a parameter, +#! and a struct, or a C union, of what crosses, with arrays within. +#! @param this The checker. +#! @param kind The type. +#! @param parameter Whether it is a parameter's, where a reference crosses as +#! a pointer. +#! @param depth How deeply the search has gone, which stops a type nesting +#! without end. +#! @returns Whether it does. +def checker::crosses(&mut this, kind: u32, parameter: bool, depth: u32): bool { + return true if depth > 8 || kind == bt::error; + val plain := this.unalias(kind); + match this.types.kind_of(plain) { + ty::boolean, ty::signed, ty::unsigned, ty::floating, ty::pointer => return true; + ty::reference => return parameter; + ty::fixed => return depth > 0 && this.crosses(this.types.first_of(plain), false, depth + 1); + ty::named => { + val named := this.named_kind(plain); + return true if named == dk::enum_type || this.is_std(plain, word::cfn); + return false if named != dk::struct_type && !(named == dk::union_type && this.decls.has(this.types.first_of(plain), df::foreign)); + val fields := this.field_types(plain); + for &each in fields { + return false if !this.crosses(each, false, depth + 1); + } + return true; + } + else => return false; + } + return false; +} diff --git a/analyzer/checker/bodies.sakura b/analyzer/checker/bodies.sakura new file mode 100644 index 00000000..41f32bfa --- /dev/null +++ b/analyzer/checker/bodies.sakura @@ -0,0 +1,363 @@ +#! @file bodies.sakura +#! @author John Christman (sorakatadzuma@gmail.com) +#! @copyright Malunal Studios, LLC. +#! @license MIT +#! +#! Contains the checking of what each declaration holds beyond its signature: +#! the body of a function, checked once against the bounds of its type +#! parameters where it is generic, the values of variables and fields, and +#! that a struct or union implements the traits it names. + +module sakura::analyzer; + + +#! Checks what the declaration holds. +#! @param this The checker. +#! @param id The declaration. +pub def checker::check_decl(&mut this, id: u32): void { + return if this.decls.has(id, df::checked) || this.decls.has(id, df::failed); + this.decls.mark(id, df::checked); + + # The attributes written before it, in its own file and scope. + if this.decls.kinds.p[id] != dk::type_param && this.decls.kinds.p[id] != dk::builtin + && !this.decls.has(id, df::accessor) && this.decls.nodes.p[id] != 0 { + val saved := this.at; + this.enter_decl(id, 0); + this.check_attributes(id); + this.leave(saved); + } + + match this.decls.kinds.p[id] { + dk::function => { + this.resolve(id); + this.check_overloads(id); + this.check_main(id); + if this.decls.has(id, df::foreign) { + val saved := this.at; + this.use_table(this.units[this.decls.files.p[id]].table); + this.check_foreign(id); + this.at = saved; + } + return if this.decls.has(id, df::intrinsic) || this.decls.has(id, df::foreign) && !this.has_body(id); + val saved := this.at; + this.enter_decl(id, 0); + this.check_asked(id); + # Its lifetimes are warned of only where its body checks. + val errors := this.errors; + this.check_function_body(id, this.decls.types.p[id]); + if this.errors == errors { + this.check_lifetimes(id); + } + this.leave(saved); + } + dk::variable, dk::field => this.check_value(id); + dk::struct_type, dk::union_type => { + this.check_implements(id); + this.check_contains(id); + if this.decls.has(id, df::foreign) { + val saved := this.at; + this.use_table(this.units[this.decls.files.p[id]].table); + this.check_c_type(id); + this.at = saved; + } + } + dk::trait_type => { + this.resolve_composed(id); + } + else => this.resolve(id); + } +} + +#! Checks a function a trait asks for, which each type implementing the trait +#! gives: one with type parameters of its own gives a default, which each type +#! takes as its own, since no table holds a generic, and one taking no `this` +#! has no default, since nothing within the trait names the type implementing +#! it. +#! @param this The checker. +#! @param id The function's declaration, whose file is the one checked. +def checker::check_asked(&mut this, id: u32): void { + return if !this.trait_asks(id) || this.decls.has(id, df::accessor); + + val node: u32 = this.decls.nodes.p[id]; + val params := this.record(node, function_slot::type_params); + if this.run_length(params) != 0 && !this.has_body(id) { + this.report(this.run_at(params, 0), ec::generic, + "A trait's generic method gives a default, which each type implementing the trait takes as its own, since no table holds a generic."); + } + if !this.decls.has(id, df::method) && this.has_body(id) { + this.report(node, ec::invalid, + "Static methods of a trait have no default, since nothing within the trait names the type implementing them."); + } +} + +#! Whether a function has a body, rather than ending at its signature. +#! @param this The checker. +#! @param id The function's declaration. +#! @returns Whether it has. +pub def checker::has_body(&this, id: u32): bool { + val syntax := &this.units[this.decls.files.p[id]].syntax; + val node := this.decls.nodes.p[id]; + if this.decls.has(id, df::accessor) { + return syntax.extras[syntax.node_rights[node]] != 0; + } + return syntax.extras[syntax.node_lefts[node] as u64 + function_slot::body as u64] != 0; +} + +#! Checks a function's body against its type: its parameters are locals of +#! their types, its default values are checked where its parameters are, and +#! it returns a value on every path where its result is not `void`. +#! @param this The checker. +#! @param id The function's declaration. +#! @param kind Its function type, given the type arguments it is checked with. +pub def checker::check_function_body(&mut this, id: u32, kind: u32): void { + val node: u32 = this.decls.nodes.p[id]; + val accessor := this.decls.has(id, df::accessor); + val body := accessor ? this.record(node, accessor_slot::body) : this.record(node, function_slot::body); + val params := accessor ? this.left_of(node) : this.record(node, function_slot::params); + if body == 0 { + if !this.decls.has(id, df::intrinsic) && !this.decls.has(id, df::foreign) + && this.enclosing_trait(id) == 0 { + this.report(node, ec::invalid, "A function has a body, unless it is `@intrinsic`, given by the compiler, or C's: a function with no body is C's only in an `extern module`."); + } + return; + } + + this.at.result = this.types.first_of(kind); + val count := this.types.part_count(kind); + # A trait's method's own body has the bounds it puts on the trait's parameters + # and `self`, which an instance's arguments meet. + val proved := this.proved_params.length; + if this.at.instance == 0 { + this.prove_outer(id); + } + + # A pack parameter is a local holding the pack: in the generic's own body, + # a pack of types not known, and in an instance, the types the parameters + # from it on were given. + val written: u32 = this.decls.types.p[id]; + val wcount := this.types.part_count(written); + val packed := this.decls.has(id, df::variadic) && wcount != 0 + && this.types.is_open_pack(this.types.part_at(written, wcount - 1)); + for i in 0..this.run_length(params) { + val param := this.run_at(params, i as u32); + var held: u32 = i < count ? this.types.part_at(kind, i as u32) : bt::error; + if packed && i as u32 + 1 == wcount { + var rest := vector::::new(); + for j in i..count { + rest.append(this.types.part_at(kind, j as u32)); + } + # Given a variadic function's parameters, as a pattern's pack may be, the + # pack ends in a view of the rest, which its type says as a variadic pack. + val open := i < count && this.types.is_open_pack(this.types.part_at(kind, i as u32)); + held = open ? this.types.part_at(kind, i as u32) + : this.types.second_of(kind) != 0 && rest.length != 0 ? this.types.variadic_pack(rest.view()) + : this.types.pack(rest.view(), 0); + } else if this.types.second_of(kind) != 0 && i as u32 + 1 == count { + held = this.variadic_type(held); + } + + # A default value is checked where its parameter is, with the parameters + # before it named, and runs at each call that leaves it out. + val value := accessor ? 0 : this.record(param, parameter_slot::value); + if value != 0 { + this.check_expr(value, held); + } + this.declare_local(param, this.param_name(param), held); + this.set_flag(param, rf::mutable); + } + + this.at.body = body; + val how := this.check_block(body); + this.unprove_to(proved); + val result := this.at.result; + if how == flow::goes_on && result != bt::void_type && result != bt::error { + this.report(node, ec::control, "The function can end without returning a value."); + } +} + +#! The type a variadic parameter is within its function: a view of its +#! arguments, or with a pack, the pack itself. +#! @param this The checker. +#! @param element The type of the parameter as written: of each argument. +#! @returns The type. +def checker::variadic_type(&mut this, element: u32) : u32 { + return element if this.types.kind_of(element) == ty::pack; + return this.span_of(element); +} + +#! Checks the value a variable or field is declared with, against the type +#! written for it. +#! @param this The checker. +#! @param id The variable's or field's declaration. +def checker::check_value(&mut this, id: u32): void { + this.resolve(id); + val node: u32 = this.decls.nodes.p[id]; + val saved := this.at; + this.enter_decl(id, 0); + val value := this.record(node, variable_slot::value); + if value != 0 && !this.has_flag(value, rf::checked) { + this.check_expr(value, this.decls.types.p[id]); + } else if value == 0 && this.decls.kinds.p[id] == dk::variable && !this.has_zero(this.decls.types.p[id], 0) { + var text := string::from("`", nothing {}); + val named := this.describe(this.decls.types.p[id]); + text.append(named.view()); + text.append("` has no zero value, so the variable is given a value where it is declared."); + this.report_text(node, ec::zero_value, &text); + } + this.leave(saved); +} + +#! Checks that a struct or union implements each trait it names. +#! @param this The checker. +#! @param id The struct's or union's declaration. +def checker::check_implements(&mut this, id: u32): void { + val run := this.composed_of(id); + val kind: u32 = this.decls.types.p[id]; + for i in 0..this.decls.list_length(run) { + val wanted := this.decls.list_at(run, i as u32); + continue if this.satisfies(kind, wanted); + + var text := string::from("`", nothing {}); + text.append(this.decl_text(id)); + text.append("` names `"); + val named := this.describe(wanted); + text.append(named.view()); + text.append("` but does not implement all of it"); + val missing := this.missing_requirement(kind, wanted); + if missing != 0 { + text.append(": it has no `"); + text.append(this.decl_text(missing)); + text.append("` of the signature the trait asks for"); + } + text.append("."); + this.report_decl(id, ec::bound, text.view()); + } +} + +#! The first thing a trait asks for that the type does not have, or 0. +#! @param this The checker. +#! @param kind The type. +#! @param trait_kind The trait's type, given its arguments. +#! @returns The declaration of what it asks for, or 0. +def checker::missing_requirement(&mut this, kind: u32, trait_kind: u32): u32 { + val holder := this.types.first_of(trait_kind); + val run := this.decls.children.p[holder]; + for i in 0..this.decls.list_length(run) { + val wanted := this.decls.list_at(run, i as u32); + continue if this.decls.has(wanted, df::optional); + return wanted if !this.meets(kind, trait_kind, wanted); + } + return 0; +} + +#! Reports an overload taking the same parameters as one declared before it, +#! which no call could choose between. +#! @param this The checker. +#! @param id The function's declaration. +def checker::check_overloads(&mut this, id: u32): void { + val owner := this.decls.owners.p[id]; + val first: u32 = owner != 0 && this.decls.kinds.p[owner] != dk::property + ? this.first_member(id) + : this.modules.decl(this.decls.modules.p[id], this.decls.names.p[id]); + return if first == 0 || first == id || this.decls.has(id, df::accessor); + + var walk := this.decls.walk_overloads(first); + while true { + val at := walk.next(); + break if at == 0 || at == id; + this.resolve(at); + if this.decls.kinds.p[at] == dk::function && this.same_params(at, id) { + this.report_decl_related(id, ec::duplicate, + "Another overload of this name takes the same parameters, so no call could choose between them.", + at, "The other overload."); + return; + } + } +} + +#! Whether two functions take the same parameters: of the same types, an alias +#! being a type of its own, both static or both taking `this` alike. +#! @param this The checker. +#! @param a One function's declaration. +#! @param b The other's. +#! @returns Whether they do. +def checker::same_params(&mut this, a: u32, b: u32): bool { + return false if this.decls.has(a, df::method) != this.decls.has(b, df::method); + return false if this.decls.has(a, df::mut_this) != this.decls.has(b, df::mut_this); + return false if this.decls.has(a, df::generic) || this.decls.has(b, df::generic); + + val ka := this.decls.types.p[a]; + val kb := this.decls.types.p[b]; + return false if this.types.part_count(ka) != this.types.part_count(kb); + return false if (this.types.second_of(ka) != 0) != (this.types.second_of(kb) != 0); + for i in 0..this.types.part_count(ka) { + return false if this.types.part_at(ka, i as u32) != this.types.part_at(kb, i as u32); + } + return true; +} + +#! Checks `main`, of the program itself, which takes nothing or the arguments +#! as views of text, and returns nothing. +#! @param this The checker. +#! @param id The declaration of `main`. +def checker::check_main(&mut this, id: u32): void { + return if this.decls.names.p[id] != word::main || this.decls.modules.p[id] != 0 || this.decls.owners.p[id] != 0; + + val kind: u32 = this.decls.types.p[id]; + var valid := this.types.first_of(kind) == bt::void_type && this.types.part_count(kind) <= 1; + if valid && this.types.part_count(kind) == 1 { + val texts := this.span_of(this.span_of(bt::uint8)); + valid = texts == bt::error || this.strip(this.types.part_at(kind, 0), 0) == this.strip(texts, 0); + } + if this.decls.overloads.p[id] != 0 || this.modules.decl(0, word::main) != id { + valid = false; + } + return if valid; + + this.report_decl(id, ec::invalid, + "`main` is `def main(): void` or `def main(args: span): void`, and is not overloaded."); +} + +#! Reports a struct or union holding itself, other than through a pointer or a +#! reference, which no amount of memory could hold. +#! @param this The checker. +#! @param id The struct's or union's declaration. +def checker::check_contains(&mut this, id: u32): void { + var seen := vector::::new(); + if this.holds(this.decls.types.p[id], id, &mut seen, 0) { + var text := string::from("`", nothing {}); + text.append(this.decl_text(id)); + text.append("` holds itself, which only a pointer or a reference to it can."); + this.report_decl(id, ec::recursive, text.view()); + } +} + +#! Whether a value of the type holds a value of the declaration's type, in its +#! fields or elements, rather than through a pointer or reference. +#! @param this The checker. +#! @param kind The type. +#! @param target The declaration looked for. +#! @param seen The types already looked within, which are not looked within +#! again. +#! @param depth How deeply the search has gone. +#! @returns Whether it does. +def checker::holds(&mut this, kind: u32, target: u32, seen: &mut vector, depth: u32): bool { + return false if depth > 32; + val plain := this.unalias(kind); + if this.types.kind_of(plain) == ty::fixed { + return this.holds(this.types.first_of(plain), target, seen, depth + 1); + } + val named := this.named_kind(plain); + return false if named != dk::struct_type && named != dk::union_type; + + val decl := this.types.first_of(plain); + return true if decl == target && depth > 0; + return false if seen.view().contains(&plain); + seen.append(plain); + + val fields := this.field_types(plain); + for &field in fields { + return true if this.holds(field, target, seen, depth + 1); + } + return false; +} diff --git a/analyzer/checker/calls.sakura b/analyzer/checker/calls.sakura new file mode 100644 index 00000000..e0d79d16 --- /dev/null +++ b/analyzer/checker/calls.sakura @@ -0,0 +1,1833 @@ +#! @file calls.sakura +#! @author John Christman (sorakatadzuma@gmail.com) +#! @copyright Malunal Studios, LLC. +#! @license MIT +#! +#! Contains the checking of calls: of functions named or reached through a +#! type, of methods of a value, and of function values. A call of an +#! overloaded function chooses the overload the arguments fit best. Each +#! argument is checked once, before the overloads are compared, but for an +#! anonymous function or an array, which take their types from the parameter +#! they are given for, and are checked once it is chosen. + +module sakura::analyzer; + + +#! An overload a call may call, and how well the arguments fit it. +struct checker::candidate { + var decl: u32; + var kind: u32; #! Its function type, given the type arguments. + var binds: u32; #! The pack of its type arguments, where it is generic. + var worst: fit; + var total: u32; + var generic: bool; + var arity: bool; #! Whether it takes as many arguments as the call gives. + var infers: u32; #! A type parameter nothing gave a type, which the call cannot infer. + var later: bool; #! Whether it passes on a pack whose types are not known, so only each instance checks it. + var writes: u32; #! How many arguments it lends to `&mut` parameters, which what can be written is better given to. +} + +#! A call. +#! @param this The checker. +#! @param node The `call` node. +#! @param expected The type expected of what it gives, or the error type where +#! none is. +#! @returns The type it gives, or the error type where it is not valid. +def checker::call(&mut this, node: u32, expected: u32): u32 { + val callee := this.left_of(node); + val run := this.right_of(node); + # The arguments are the run's nodes where the syntax holds them, which nothing + # changes while the call is checked. + val args := this.run_view(run); + + match this.kind_of(callee) { + nk::name => { + val name := this.name_of(callee); + val ref := this.lookup(name, callee); + if ref == 0 { + this.report_undeclared(callee, name); + this.infer_args(args); + return bt::error; + } + if (ref & (ref_local | ref_type)) == 0 && this.decls.kinds.p[ref] == dk::function + && this.decls.has(ref, df::intrinsic) && name == this.names.intern(&"compile_error") { + # Recorded, since it ends the branch it is in, as `return` does. + this.set_ref(node, ref); + return this.compile_error(node, args); + } + if (ref & (ref_local | ref_type)) == 0 && this.decls.kinds.p[ref] == dk::function && this.is_reflection(ref) { + return this.reflect_call(node, callee, ref, 0, args, expected); + } + if (ref & (ref_local | ref_type)) == 0 && this.decls.kinds.p[ref] == dk::function { + if !this.visible(ref) { + this.report_hidden(callee, ref); + } + return this.call_decl(node, callee, ref, 0, bt::error, bt::error, 0, args, expected); + } + return this.call_value(node, callee, args, expected); + } + nk::path => { + val target := this.path_target(callee); + if target.decl == 0 { + this.infer_args(args); + return bt::error; + } + if this.decls.kinds.p[target.decl] == dk::function && this.is_reflection(target.decl) { + val written := this.segment_args(callee, this.segment_count(callee) - 1); + return this.reflect_call(node, callee, target.decl, written, args, expected); + } + if this.decls.kinds.p[target.decl] == dk::function { + val written := this.segment_args(callee, this.segment_count(callee) - 1); + val first := this.overloads_for(target.decl, 0, target.owner, target.owner, args); + return this.call_decl(node, callee, first, 0, target.owner, target.owner, written, args, expected); + } + return this.call_value(node, callee, args, expected); + } + nk::member => { + # A constant settles as it would alone, so `"text".trim()` is a `strview`'s. + val object := this.left_of(callee); + val name := this.name_of(callee); + var kind := this.infer_expr(object); + if kind == bt::error { + this.infer_args(args); + return bt::error; + } + if this.types.is_untyped(kind) { + kind = this.settle_expr(object); + } + + val through := this.reached(kind); + val found := this.find_member(through, name); + if found.decl != 0 && this.decls.kinds.p[found.decl] == dk::function { + # A method a program declares on a built-in type is an overload beside the + # one the compiler gives it, which is called where the arguments fit none + # of the program's. A struct, a union, or a trait is given none. + val plain := this.unalias(through); + val shaped := this.types.kind_of(plain) == ty::named && this.named_kind(plain) != dk::enum_type; + val builtin := shaped || this.types.kind_of(plain) == ty::param ? 0 : this.builtin_method(through, name); + if builtin != 0 && this.right_of(callee) == 0 && !this.fits_overload(found.decl, object, found.owner, through, args) { + return this.call_signature(node, builtin, args, 1); + } + val first := this.overloads_for(found.decl, object, found.owner, through, args); + if !this.visible(first) { + this.report_hidden(callee, first); + } + return this.call_decl(node, callee, first, object, found.owner, through, this.right_of(callee), args, expected); + } + if found.decl == 0 { + val builtin := this.builtin_method(through, name); + if builtin != 0 { + return this.call_signature(node, builtin, args, 1); + } + this.report_no_member(callee, through, name); + this.infer_args(args); + return bt::error; + } + return this.call_value(node, callee, args, expected); + } + nk::member_of => { + # `x.(d)()` calls the method a description names, as though its name + # were written there. + val object := this.left_of(callee); + val kind := this.infer_expr(object); + val found := this.described_member(callee, kind); + if found.decl == 0 { + this.infer_args(args); + return bt::error; + } + if this.decls.kinds.p[found.decl] == dk::function { + return this.call_decl(node, callee, found.decl, object, found.owner, this.reached(kind), 0, args, expected); + } + return this.call_value(node, callee, args, expected); + } + else => return this.call_value(node, callee, args, expected); + } + return bt::error; +} + +#! Checks arguments of a call that went wrong, so what is wrong within them is +#! still reported. +#! @param this The checker. +#! @param args The arguments' nodes. +def checker::infer_args(&mut this, args: span): void { + for &each in args { + this.infer_expr(each); + } +} + +#! Whether an argument takes its type from its parameter, so it is checked once +#! the overload is chosen: an anonymous function, an array, or a range. +#! @param this The checker. +#! @param node The argument's node. +#! @returns Whether it does. +def checker::deferred(&this, node: u32): bool { + val kind := this.kind_of(node); + return kind == nk::lambda || kind == nk::array || kind == nk::range; +} + +#! Whether an argument is an anonymous function whose parameters' types are +#! all written, which has a type of its own without its parameter's. +#! @param this The checker. +#! @param node The argument's node. +#! @returns Whether it is. +def checker::typed_lambda(&this, node: u32): bool { + return false if this.kind_of(node) != nk::lambda; + val params := this.left_of(node); + for i in 0..this.run_length(params) { + return false if this.left_of(this.run_at(params, i as u32)) == 0; + } + return true; +} + +#! Whether an argument is `...xs`, spreading a view into the arguments. +#! @param this The checker. +#! @param node The argument's node. +#! @returns Whether it is. +def checker::is_spread_arg(&this, node: u32): bool { + return this.kind_of(node) == nk::unary && this.token_kind(node) == tk::spread; +} + +#! A call of a function declared by name, or of one of its overloads. +#! @param this The checker. +#! @param node The `call` node. +#! @param callee The node of what is called. +#! @param first The first of the function's overloads. +#! @param object The value a method is called on, or 0. +#! @param owner The type a member is of, given its arguments, or the error +#! type. +#! @param through The type the method is reached through, for a trait's +#! method. +#! @param written The run of type arguments written, as `max::`, or 0. +#! @param args The arguments' nodes. +#! @param expected The type expected of what it gives, or the error type. +#! @returns The type the chosen overload gives, or the error type where none +#! fits. +def checker::call_decl( + &mut this, + node: u32, + callee: u32, + first: u32, + object: u32, + owner: u32, + through: u32, + written: u32, + args: span, + expected: u32 +): u32 { + # A trait's method takes no arguments of the trait's own: its type arguments + # are its own. + var given := vector::::new(); + if written != 0 { + given = this.written_args(first, this.trait_asks(first) ? bt::error : owner, written); + } + + # A generic function without overloads infers its type arguments from the + # arguments and the type expected, and checks those that need their parameter's + # type once the rest give it: anonymous functions, arrays, generic functions + # named as values, and calls that cannot infer their own without it, which are + # tried quietly first. + val alone := this.decls.overloads.p[first] == 0 && this.decls.has(first, df::generic); + val kinds := this.arg_kinds(args, true, alone); + + # Between `&this` and `&mut this`, a receiver that can be written calls the + # one taking `&mut this`, and one that cannot the one taking `&this`. + val writes := object != 0 && this.receiver_writable(object); + # An `@optional` method may be missing from whatever type a bound or a trait + # reference stands for, so a call through them never reaches one. + val reached := object != 0 ? this.unalias(this.reached(this.type_at(object))) : 0; + val bounded := reached != 0 && (this.types.kind_of(reached) == ty::param || this.named_kind(reached) == dk::trait_type); + var best := checker::candidate { worst = fit::none }; + var tied := false; + var tried: u32 = 0; + var single := checker::candidate { worst = fit::none }; + var walk := this.decls.walk_overloads(first); + while true { + val at := walk.next(); + break if at == 0; + continue if (object != 0 && !this.decls.has(at, df::method)) || (bounded && this.decls.has(at, df::optional)) + || !this.member_seen(at); + + tried++; + val made := this.try_candidate(at, object, owner, through, given.view(), args, kinds.view(), expected, alone); + if made.later { + # Passing on a pack whose types are not known is only checked in each + # instance, where they are. + for i in 0..args.length { + if kinds[i] == 0 { this.infer_expr(args[i]); } + } + return bt::error; + } + single = made; + if made.worst != fit::none && made.worst != fit::overflow { + this.keep_better(&made, &mut best, &mut tied, object != 0, writes); + } + } + + if best.decl == 0 { + return this.report_no_fit(node, callee, first, &single, tried, object, args, kinds.view()); + } + if tied { + var text := string::from("The call fits more than one overload of `", nothing {}); + text.append(this.decl_text(first)); + text.append("` as well, so convert an argument to the type of the one meant."); + this.report_text(callee, ec::ambiguous, &text); + } + + return this.apply_candidate(node, callee, &best, object, args, kinds.view()); +} + +#! The types of a call's arguments, worked out before the function is chosen: +#! of what a spread spreads, and 0 for those that need their parameter's type +#! to be checked. +#! @param this The checker. +#! @param args The arguments' nodes. +#! @param by_name Whether a generic or overloaded function named waits for its +#! parameter's type too. +#! @param alone Whether a call is tried quietly, as one that may need its +#! parameter's type to infer its own. +#! @returns Their types. +def checker::arg_kinds(&mut this, args: span, by_name: bool, alone: bool): vector { + var kinds := vector::::new(); + for &each in args { + if this.deferred(each) || (by_name && this.kind_of(each) == nk::name && (this.names_generic(each) || this.names_overloaded(each))) + || (by_name && this.kind_of(each) == nk::path && this.path_waits(each)) { + kinds.append(0); + } else if this.is_spread_arg(each) { + kinds.append(this.infer_expr(this.left_of(each))); + } else if alone && this.kind_of(each) == nk::call { + kinds.append(this.tried(each)); + } else { + kinds.append(this.infer_expr(each)); + } + } + return kinds; +} + +#! Keeps the better of an overload that fits and the best so far, noting where +#! neither is. Between `&this` and `&mut this`, a receiver that can be written +#! is better given to the one taking `&mut this`, and one that cannot to the +#! other. +#! @param this The checker. +#! @param made The overload. +#! @param best The best so far, with no declaration where there is none. +#! @param tied Whether the best so far is tied. +#! @param receiving Whether it is a method's call on a receiver. +#! @param writes Whether the receiver can be written. +def checker::keep_better(&this, made: &checker::candidate, best: &mut checker::candidate, tied: &mut bool, receiving: bool, writes: bool): void { + var better := this.better(made, best); + if better == 0 && receiving && this.decls.has(made.decl, df::mut_this) != this.decls.has(best.decl, df::mut_this) { + better = this.decls.has(made.decl, df::mut_this) == writes ? 1 : -1; + } + # So is an argument that can be written better lent to a `&mut` parameter + # than to a `&` one, as `address(x)` of a `var x` gives a `*mut`. + if better == 0 && best.decl != 0 && made.writes != best.writes { + better = made.writes > best.writes ? 1 : -1; + } + if best.decl == 0 || better > 0 { + best = made; + tied = false; + } else if better == 0 { + tied = true; + } +} + +#! Whether the arguments of a call fit an overload of a method, or of a +#! function where nothing is called on, without choosing one or reporting +#! anything. +#! @param this The checker. +#! @param first The first of the method's overloads. +#! @param object The node of the value it is called on, or 0. +#! @param owner The type the method is of, given its arguments. +#! @param through The type it is reached through. +#! @param args The arguments' nodes. +#! @returns Whether they fit one. +pub def checker::fits_overload(&mut this, first: u32, object: u32, owner: u32, through: u32, args: span): bool { + val kinds := this.arg_kinds(args, true, false); + var walk := this.decls.walk_overloads(first); + while true { + val at := walk.next(); + break if at == 0; + if (object == 0 || this.decls.has(at, df::method)) && this.member_seen(at) { + val made := this.try_candidate(at, object, owner, through, span::::empty(), args, kinds.view(), bt::error, false); + return true if made.later || (made.worst != fit::none && made.worst != fit::overflow); + } + } + return false; +} + +#! The type arguments written for a call, each given to the parameter at its +#! place after those of the owner, a constant parameter's worked out while +#! checking. +#! @param this The checker. +#! @param first The first of the function's overloads. +#! @param owner The type a member is of, given its arguments, or the error +#! type. +#! @param written The run of type arguments written. +#! @returns The type arguments. +def checker::written_args(&mut this, first: u32, owner: u32, written: u32): vector { + var given := vector::::new(); + var leading := vector::::new(); + if owner != bt::error && this.types.kind_of(owner) == ty::named { + leading.extend(this.types.parts_view(owner)); + } + for &arg in this.run_view(written) { + val made := this.type_arg_of(arg, first, leading.length as u32, leading.view()); + given.append(made); + leading.append(made); + } + return given; +} + +#! How well the call fits the overload. +#! @param this The checker. +#! @param decl The overload. +#! @param object The value a method is called on, or 0. +#! @param owner The type a member is of, given its arguments, or the error +#! type. +#! @param through The type the method is reached through, for a trait's +#! method. +#! @param given The type arguments written. +#! @param args The arguments' nodes. +#! @param kinds The arguments' types, 0 for one checked once the overload is +#! chosen. +#! @returns How well it fits, and what it fits as. +def checker::try_candidate( + &mut this, + decl: u32, + object: u32, + owner: u32, + through: u32, + given: span, + args: span, + kinds: span, + expected: u32, + alone: bool +): checker::candidate { + this.resolve(decl); + var made := checker::candidate { decl = decl, worst = fit::exact, arity = true }; + if this.decls.has(decl, df::failed) { + made.worst = fit::none; + return made; + } + + val in_trait := this.trait_asks(decl); + # A default compiled for each type infers its own type arguments, in the terms + # of the trait the value implements and the value's type. + val typed := in_trait && this.decls.has(decl, df::generic) && this.typed_default(decl); + var kind := in_trait ? this.trait_method_type(decl, through) : this.decls.types.p[decl]; + val skip: u32 = object != 0 && this.decls.has(decl, df::method) ? 1 : 0; + + # Passing on a pack whose types are not known is checked in each instance, + # where they are, whatever is called. + for i in 0..args.length { + if this.is_spread_arg(args[i]) && kinds[i] != 0 && this.types.is_open_pack(this.reached(kinds[i])) { + made.later = true; + return made; + } + } + + # A generic's type arguments are its owner's, those written, and those the + # arguments give. + if this.decls.has(decl, df::generic) && (!in_trait || typed) { + # A pack spread into the arguments gives one for each of its types. + var slots := vector::::new(); + for i in 0..args.length { + if this.is_spread_arg(args[i]) && kinds[i] != 0 && this.types.kind_of(kinds[i]) == ty::pack { + slots.extend(this.types.parts_view(kinds[i])); + continue; + } + slots.append(kinds[i]); + } + + var inferred := this.begin_inference(decl, in_trait ? bt::error : owner, given); + if typed { + this.give_outer(decl, this.reached(through), &mut inferred); + this.unify_outer(decl, &mut inferred); + } + val count := this.types.part_count(kind); + + # A pack parameter takes a type for each argument after those before it. + val last: u32 = count == 0 ? 0 : this.types.part_at(kind, count - 1); + val packed := this.types.second_of(kind) != 0 && count != 0 && this.types.is_open_pack(last); + val stop: u32 = packed ? count - 1 : count; + + # A type parameter taking an argument whole, as `T` of `x: T` or of a pack, + # takes the value it is: what a reference reaches, unless `&` is written. + if slots.length == args.length { + for i in 0..slots.length { + val p := i as u32 + skip; + continue if slots[i] == 0 || p >= count; + val whole := p >= stop || this.types.kind_of(this.types.part_at(kind, p)) == ty::param; + if whole && this.takes_value(args[i], slots[i]) { + slots[i] = this.types.first_of(this.unalias(slots[i])); + } + } + } + for i in 0..slots.length { + val p := i as u32 + skip; + break if p >= stop; + continue if slots[i] == 0; + val pattern := this.types.part_at(kind, p); + if slots.length == args.length && this.types.kind_of(pattern) == ty::reference + && this.referred_in_template(args[i]) { + this.unify(this.types.first_of(pattern), slots[i], &mut inferred, 0); + continue; + } + this.unify(pattern, slots[i], &mut inferred, 0); + } + if packed { + this.bind_pack(last, slots.view(), (stop - skip) as u64, &mut inferred); + } + # An array literal given where an overload is chosen gives its elements' + # type, settled, as `[1, 2]` gives `T[2]` its `int`. So does an anonymous + # function whose parameters' types are written give a type parameter it's + # given for its own type, as `F` of `f: F` bounded by `invokable<...>`. + if !alone { + for i in 0..slots.length { + val p := i as u32 + skip; + break if p >= stop; + continue if slots[i] != 0; + val pattern := this.types.part_at(kind, p); + if this.kind_of(args[i]) == nk::array { + val quiet := this.tried(args[i]); + if quiet != 0 && quiet != bt::error { + this.unify(pattern, this.settle(quiet), &mut inferred, 0); + } + } else if this.typed_lambda(args[i]) && this.types.kind_of(this.unalias(pattern)) == ty::param { + val quiet := this.tried(args[i]); + if quiet != 0 && quiet != bt::error { + this.unify(pattern, quiet, &mut inferred, 0); + } + } + } + } + if skip == 1 && count != 0 { + this.unify(this.types.part_at(kind, 0), this.types.reference(this.unalias(through), false), &mut inferred, 0); + } + + # What the arguments leave, the type expected of the result gives, and then the + # bounds of what is known. + if expected != bt::error { + this.unify(this.types.first_of(kind), expected, &mut inferred, 0); + } + this.unify_bounds(&mut inferred, 0); + + # The arguments checked once their parameter's type is known, in the order + # they are written, each giving what it can to the next. + if alone && slots.length == args.length { + for i in 0..slots.length { + val p := i as u32 + skip; + break if p >= stop; + continue if slots[i] != 0; + val pattern := this.types.part_at(kind, p); + this.infer_later(args[i], pattern, &mut inferred); + this.unify_bounds(&mut inferred, 0); + } + } + + # A function named for a type parameter bounded by `invokable`, which a + # call as `S` asks would take though its type is not `S`, gives the + # parameter `S`, and is called as `S` asks by a function made for it. + if slots.length == args.length { + for i in 0..slots.length { + val p := i as u32 + skip; + break if p >= stop; + continue if slots[i] == 0; + this.adapt_bound(args[i], slots[i], this.types.part_at(kind, p), &mut inferred); + } + } + + made.infers = this.unbound(&inferred); + if made.infers != 0 { + made.worst = fit::none; + return made; + } + kind = this.apply(kind, &inferred); + made.binds = this.types.pack(inferred.binds.view(), 0); + made.generic = true; + } + made.kind = kind; + + # How many arguments it takes: those before its first default, up to all of + # its parameters, or more where its last is variadic. A pack spread with + # `...` gives an argument for each of its types. + val count := this.types.part_count(kind); + val variadic := this.types.second_of(kind) != 0; + # A variadic parameter, or a pack, takes any number of arguments, so it is + # not among those a call must give. + val takes_many: u32 = this.decls.has(decl, df::variadic) ? 1 : 0; + val written_required := this.required_params(decl); + val required: u32 = written_required >= skip + takes_many ? written_required - skip - takes_many : 0; + val most := count - skip; + val argc := this.given_count(args, kinds); + if argc < required || (!variadic && argc > most) { + made.arity = false; + made.worst = fit::none; + return made; + } + + # The receiver: `&mut this` is called on what can be written. + if skip == 1 && this.decls.has(decl, df::mut_this) && !this.receiver_writable(object) { + made.worst = fit::none; + return made; + } + + var p := skip; + for i in 0..args.length { + if this.spreads_pack(args[i], kinds[i]) { + val none := constant {}; + for j in 0..this.types.part_count(kinds[i]) { + val param := this.types.part_at(kind, p >= count ? count - 1 : p); + val how := this.spread_fits(kinds[i], j as u32, kind, p) + ? this.fits(this.types.part_at(kinds[i], j as u32), param, &none, false, 0) + : fit::none; + made.worst = (how as u8) > (made.worst as u8) ? how : made.worst; + made.total += how as u32; + p++; + } + continue; + } + + val param := this.types.part_at(kind, p >= count ? count - 1 : p); + val how := this.arg_fit(args[i], kinds[i], param, variadic && p >= count - 1); + made.worst = (how as u8) > (made.worst as u8) ? how : made.worst; + made.total += how as u32; + if this.types.kind_of(param) == ty::reference && this.types.second_of(param) != 0 { + made.writes++; + } + p++; + } + return made; +} + +#! Whether a value of a pack spread into a call goes at a parameter's place: any +#! does, but for the last of a variadic function's pack, which within it is a +#! view of the rest it was given, so only the parameter taking the rest takes it. +#! @param this The checker. +#! @param pack The pack spread. +#! @param j The value's place in the pack. +#! @param kind The function type called. +#! @param p The parameter's place. +#! @returns Whether it goes there. +def checker::spread_fits(&this, pack: u32, j: u32, kind: u32, p: u32): bool { + return true if this.types.second_of(pack) == 0 || j + 1 != this.types.part_count(pack); + return this.types.second_of(kind) != 0 && p + 1 == this.types.part_count(kind); +} + +#! Whether an argument spreads a pack whose types are known into the call. +#! @param this The checker. +#! @param node The argument's node. +#! @param kind Its type. +#! @returns Whether it does. +def checker::spreads_pack(&this, node: u32, kind: u32): bool { + return kind != 0 && this.is_spread_arg(node) && this.types.kind_of(kind) == ty::pack + && !this.types.is_open_pack(kind); +} + +#! How many arguments a call gives, each of a pack spread into it counted. +#! @param this The checker. +#! @param args The arguments' nodes. +#! @param kinds Their types. +#! @returns How many values they give. +def checker::given_count(&this, args: span, kinds: span): u32 { + var count: u32 = 0; + for i in 0..args.length { + count += this.spreads_pack(args[i], kinds[i]) ? this.types.part_count(kinds[i]) : 1; + } + return count; +} + +#! How many parameters a call must give arguments for: those before the first +#! with a default value. +#! @param this The checker. +#! @param decl The function's declaration. +#! @returns How many. +def checker::required_params(&this, decl: u32): u32 { + val syntax := &this.units[this.decls.files.p[decl]].syntax; + val node: u32 = this.decls.nodes.p[decl]; + return 1 if this.decls.has(decl, df::accessor); + + val record := syntax.node_lefts[node]; + val params := syntax.run_view(syntax.extras[record as u64 + function_slot::params as u64]); + for i in 0..params.length { + val values := syntax.node_rights[params[i]]; + if syntax.extras[values] != 0 { + return i as u32; + } + } + return params.length as u32; +} + +#! Whether a receiver can be written, for a method taking `&mut this`: what can +#! be written, a `&mut` reference, or a new value. +#! @param this The checker. +#! @param object The receiver's node. +#! @returns Whether it can be. +def checker::receiver_writable(&mut this, object: u32): bool { + val kind := this.type_at(object); + val plain := this.unalias(kind); + if this.types.kind_of(plain) == ty::reference || this.types.kind_of(plain) == ty::pointer { + return this.types.second_of(plain) != 0; + } + return this.is_writable(object) || !this.is_place(object); +} + +#! How an argument fits its parameter, taking a reference to it for a `&` +#! parameter where it is no reference itself. +#! @param this The checker. +#! @param node The argument's node. +#! @param kind Its type. +#! @param param The parameter's type. +#! @param variadic Whether the parameter takes any number of values, each of +#! its element's type. +#! @returns How it fits. +def checker::arg_fit(&mut this, node: u32, kind: u32, param: u32, variadic: bool): fit { + if kind == 0 { + val plain := this.unalias(param); + val tkd := this.types.kind_of(plain); + # An array literal is a fixed array, which it is better given as than viewed. + return fit::exact if tkd == ty::fixed && this.kind_of(node) == nk::array; + # A range is std's `range`, of the integers its ends are given as. + if this.kind_of(node) == nk::range { + return this.is_std(plain, word::range) || tkd == ty::param || param == bt::error ? fit::convert : fit::none; + } + return fit::convert if tkd == ty::function || tkd == ty::fixed || this.is_std(plain, word::span) + || tkd == ty::param || param == bt::error + || this.kind_of(node) == nk::lambda && this.is_std(plain, word::cfn); + return fit::none; + } + + if this.is_spread_arg(node) { + return variadic ? fit::convert : fit::none; + } + + val value := this.value_at(node); + val known := this.is_known(node); + if this.types.kind_of(param) == ty::reference && this.lent_whole(node, kind, param) { + # A value given for a reference to a trait is referred to where it satisfies it. + val referent := this.types.first_of(param); + if this.named_kind(this.unalias(referent)) == dk::trait_type { + return this.satisfies(this.settle(kind), this.unalias(referent)) ? fit::convert : fit::none; + } + val how := this.fits(kind, referent, &value, known, 0); + return how if how == fit::none || how == fit::overflow; + if this.types.second_of(param) != 0 && this.is_place(node) && !this.is_writable(node) { + return fit::none; + } + # A constant fits a reference to the type it is alone best, as it fits that + # type best, so `2` is given to a `&i64` before a `&f64`. + return fit::exact if this.types.is_untyped(kind) && this.settle(kind) == referent; + return how == fit::exact ? fit::exact : fit::convert; + } + + # A constant fits the type it is where nothing else is expected best. + if this.types.is_untyped(kind) && this.settle(kind) == param { + return fit::exact; + } + + # A reference is read through to its value wherever no reference is wanted, so one + # referring to the very type fits better than one whose value converts further. + if this.types.kind_of(kind) == ty::reference && this.types.kind_of(param) != ty::reference + && this.unalias(this.reached(kind)) == this.unalias(param) { + return fit::read; + } + return fit::convert if this.calls_back(node, kind, param) || this.lends_pointer(node, kind, param); + val how := this.fits(kind, param, &value, known, 0); + return how if how != fit::none; + return this.adapts(node, kind, param) ? fit::convert : fit::none; +} + +#! Whether an argument names a function of the program where C's address of one +#! of its type is expected, which it is given as the entry C calls it back +#! through. +#! @param this The checker. +#! @param node The argument's node. +#! @param kind Its type. +#! @param param The parameter's type. +#! @returns Whether it does. +def checker::calls_back(&mut this, node: u32, kind: u32, param: u32): bool { + val plain := this.unalias(param); + return false if !this.is_std(plain, word::cfn) || this.types.part_count(plain) != 1; + return false if this.kind_of(node) != nk::name && this.kind_of(node) != nk::path; + val ref := this.ref_at(node); + return false if ref == 0 || (ref & (ref_local | ref_type)) != 0; + return this.decls.kinds.p[ref] == dk::function && !this.decls.has(ref, df::foreign) + && this.unalias(kind) == this.unalias(this.types.part_at(plain, 0)); +} + +#! Below zero where `a` fits worse than `b`, zero where they fit as well, and +#! above zero where `a` fits better: by its worst argument, then all of them, +#! and then a non-generic overload before a generic one. +#! @param this The checker. +#! @param a One overload. +#! @param b Another. +#! @returns Their order. +def checker::better(&this, a: &checker::candidate, b: &checker::candidate): i32 { + return ((a.worst as u8) < (b.worst as u8)) ? 1 : -1 if a.worst != b.worst; + return (a.total < b.total) ? 1 : -1 if a.total != b.total; + return (b.generic ? 1 : -1) if a.generic != b.generic; + # One taking each argument as its own parameter is better than one gathering + # them. + val a_many := a.decl != 0 && this.decls.has(a.decl, df::variadic); + val b_many := b.decl != 0 && this.decls.has(b.decl, df::variadic); + return (b_many ? 1 : -1) if a_many != b_many; + return 0; +} + +#! Reports a call no overload takes, checking its arguments as the only +#! overload's, where there is one, so each argument that does not fit is +#! reported where it is. +#! @param this The checker. +#! @param node The `call` node. +#! @param callee The node of what is called. +#! @param first The first of the function's overloads. +#! @param single The only overload where there is one, which the arguments are +#! checked against. +#! @param tried How many overloads were tried. +#! @param object The value a method is called on, or 0. +#! @param args The arguments' nodes. +#! @param kinds Their types. +#! @returns The error type, or what the only overload gives, once its arguments +#! are checked as its own. +def checker::report_no_fit( + &mut this, + node: u32, + callee: u32, + first: u32, + single: &checker::candidate, + tried: u32, + object: u32, + args: span, + kinds: span +): u32 { + for i in 0..args.length { + if kinds[i] == 0 { + this.infer_expr(args[i]); + } + } + return bt::error if this.decls.has(first, df::failed); + + if tried != 1 { + var text := string::from("No overload of `", nothing {}); + text.append(this.decl_text(first)); + text.append("` takes these arguments."); + this.report_text(callee, ec::arguments, &text); + return bt::error; + } + + # An argument already in error gives nothing to infer from, which it was reported for. + for &each in args { + return bt::error if this.type_at(this.is_spread_arg(each) ? this.left_of(each) : each) == bt::error; + } + if single.infers != 0 { + var text := string::from(this.decls.has(single.infers, df::valued) ? "Nothing gives the value of `" : "Nothing gives the type of `", nothing {}); + text.append(this.decl_text(single.infers)); + text.append("`, so give the type arguments, as `"); + text.append(this.decl_text(first)); + text.append("::<...>`."); + this.report_text(callee, ec::generic, &text); + return bt::error; + } + + if !single.arity { + # A view spread where no variadic parameter takes it gives no arguments. + if this.reports_spread(single.kind, object != 0 && this.decls.has(single.decl, df::method) ? 1 : 0, args, kinds) { + return bt::error; + } + val skip: u32 = object != 0 && this.decls.has(single.decl, df::method) ? 1 : 0; + var text := string::from("`", nothing {}); + text.append(this.decl_text(first)); + val words := $"` takes {this.types.part_count(single.kind) - skip} arguments, but is given {args.length}."; + text.append(words.view()); + this.report_text(callee, ec::arguments, &text); + return bt::error; + } + + if object != 0 && this.decls.has(single.decl, df::mut_this) && !this.receiver_writable(object) { + this.report(object, ec::assignable, + "The method takes `&mut this`, so it is called on what can be written: a `var`, or what a `&mut` reaches."); + return bt::error; + } + + # The only overload: each argument is converted, reporting what does not fit. + return this.apply_candidate(node, callee, single, object, args, kinds); +} + +#! Converts each argument of a call to its parameter, taking references where +#! the parameter is one, and records what the call calls. +#! @param this The checker. +#! @param node The `call` node. +#! @param callee The node of what is called. +#! @param chosen The overload chosen. +#! @param object The value a method is called on, or 0. +#! @param args The arguments' nodes. +#! @param kinds Their types, 0 for one checked now. +#! @returns The type the overload gives. +def checker::apply_candidate( + &mut this, + node: u32, + callee: u32, + chosen: &checker::candidate, + object: u32, + args: span, + kinds: span +): u32 { + val kind := chosen.kind; + val count := this.types.part_count(kind); + val variadic := this.types.second_of(kind) != 0; + val skip: u32 = object != 0 && this.decls.has(chosen.decl, df::method) ? 1 : 0; + return bt::error if this.reports_spread(kind, skip, args, kinds); + this.pass_args(kind, args, kinds, skip, variadic); + + if skip == 1 && count != 0 { + this.pass_receiver(object, this.types.part_at(kind, 0)); + } + + this.set_ref(callee, chosen.decl); + this.set_ref(node, chosen.decl); + if this.decls.has(chosen.decl, df::intrinsic) { + this.know_switch(node, chosen.decl); + } + # A default compiled for each type, called on a value of a type that is known, + # is that type's instance of it. + if object != 0 && this.typed_default(chosen.decl) { + this.call_default(node, callee, chosen, object); + return this.types.first_of(kind); + } + # An instance whose arguments break its bounds is never checked, since what + # is wrong is reported here. + if chosen.generic && chosen.binds != 0 { + var binds := this.types.parts_of(chosen.binds); + if this.check_args_bounds(chosen.decl, this.decls.params.p[chosen.decl], binds.view(), callee) { + val made := this.instance_of(chosen.decl, binds.view(), node); + if made != 0 { + this.called.set(this.result_key(node), made); + } + } + } + return this.types.first_of(kind); +} + +#! Records the value of a call of `checking` or `contracts`, which the options +#! the program is checked with decide, so an `if const` of one is decided while +#! checking, and only the branch it takes is checked. +#! @param this The checker. +#! @param node The `call` node. +#! @param decl The intrinsic called. +def checker::know_switch(&mut this, node: u32, decl: u32): void { + val name := this.names.text(this.decls.names.p[decl]); + if name == "checking" { + this.set_value(node, constant::truth(!this.checks_off)); + } else if name == "contracts" { + this.set_value(node, constant::truth(!this.contracts_off)); + } +} + +#! Records the instance a call of a default compiled for each type calls: the +#! one the type of the value it is called on takes, given the type arguments +#! the call infers, where they hold no type parameter. Its own parameters' +#! bounds are checked first, in the terms of the trait the value implements. +#! @param this The checker. +#! @param node The `call` node. +#! @param callee The callee's node, where a bound it breaks is reported. +#! @param chosen The default, as the call fits it. +#! @param object The node of the value it is called on. +def checker::call_default(&mut this, node: u32, callee: u32, chosen: &checker::candidate, object: u32): void { + val decl := chosen.decl; + val holder := this.enclosing_trait(decl); + val plain := this.unalias(this.reached(this.type_at(object))); + return if this.types.is_open(plain) || this.named_kind(plain) == dk::trait_type; + val trait_kind := this.trait_reached(decl, plain); + + var own := vector::::new(); + if chosen.binds != 0 { + own = this.types.parts_of(chosen.binds); + } + # Each parameter, the trait's, `self`, and its own, is checked against its + # bounds with the others given. + var params := this.decls.list_of(this.decls.params.p[holder]); + var args := this.types.parts_of(trait_kind); + args.resize(params.length, bt::error); + params.append(this.self_decl(holder)); + args.append(plain); + params.extend(this.decls.list_view(this.decls.params.p[decl])); + args.extend(own.view()); + return if !this.check_bounds_of(decl, params.view(), args.view(), callee); + return if !this.meets_outer(decl, params.view(), args.view(), callee); + + val made := this.default_instance(decl, trait_kind, plain, own.view()); + if made != 0 { + this.called.set(this.result_key(node), made); + } +} + +#! Checks that the trait's parameters and `self` meet what a trait's method +#! asks of them, as `where self: backward_iterator`, given the arguments the +#! call gives them and its own parameters. +#! @param this The checker. +#! @param decl The method's declaration. +#! @param params The parameters the bounds may name: the trait's, `self`, and +#! the method's own. +#! @param args The type each is given. +#! @param node The node a note is placed at. +#! @returns Whether they meet them. +def checker::meets_outer(&mut this, decl: u32, params: span, args: span, node: u32): bool { + val list := this.outer_bounds(decl); + var i: u32 = 0; + while i + 1 < this.decls.list_length(list) { + val param := this.decls.list_at(list, i); + val bound := this.substitute(this.decls.list_at(list, i + 1), params, args); + i += 2; + var given: u32 = bt::error; + for k in 0..params.length { + given = params[k] == param && k < args.length ? args[k] : given; + } + continue if given == bt::error || this.satisfies(given, bound); + + var text := string::from("`", nothing {}); + val named_arg := this.describe(given); + text.append(named_arg.view()); + text.append("` does not implement `"); + val named := this.describe(bound); + text.append(named.view()); + text.append("`, which `"); + text.append(this.decl_text(decl)); + text.append("` asks of `"); + text.append(this.decl_text(param)); + text.append("`."); + this.report_text(node, ec::bound, &text); + return false; + } + return true; +} + +#! Infers a trait's default's own type parameters from what it asks of the +#! trait's parameters and `self`, as `X` of `where self: iterator<&X>` from the +#! iterator it is called on. +#! @param this The checker. +#! @param method The default's declaration. +#! @param into What is inferred, whose outer terms are given. +def checker::unify_outer(&mut this, method: u32, into: &mut checker::inferred): void { + val list := this.outer_bounds(method); + var i: u32 = 0; + while i + 1 < this.decls.list_length(list) { + val param := this.decls.list_at(list, i); + val bound := this.outer_terms(this.decls.list_at(list, i + 1), into); + i += 2; + var given: u32 = bt::error; + for k in 0..into.outer.length { + given = into.outer[k] == param ? into.given[k] : given; + } + if given != bt::error && this.types.is_open(bound) { + this.unify_trait(bound, given, into, 0); + } + } +} + +#! Reports a view spread with `...` where no variadic parameter takes it, since +#! only one takes a view of the arguments it gathers. +#! @param this The checker. +#! @param kind The function type called. +#! @param skip How many parameters come before the first argument. +#! @param args The arguments' nodes. +#! @param kinds Their types, 0 for one checked later. +#! @returns Whether one was reported. +def checker::reports_spread(&mut this, kind: u32, skip: u32, args: span, kinds: span): bool { + val count := this.types.part_count(kind); + val variadic := this.types.second_of(kind) != 0 && count != 0; + var p := skip; + for i in 0..args.length { + if this.spreads_pack(args[i], kinds[i]) { + p += this.types.part_count(kinds[i]); + continue; + } + # What follows a pack whose types are not known is at no place known yet. + return false if this.is_spread_arg(args[i]) && kinds[i] != 0 && this.types.is_open_pack(this.reached(kinds[i])); + if this.is_spread_arg(args[i]) && !(variadic && p + 1 >= count) { + this.report(args[i], ec::arguments, "`...` gives a view only for a variadic parameter, or a pack for the parameters it fills."); + return true; + } + p++; + } + return false; +} + +#! Converts an argument to its parameter. +#! @param this The checker. +#! @param node The argument's node. +#! @param kind Its type. +#! @param param The parameter's type. +#! @param variadic Whether the parameter takes any number of values. +def checker::pass_arg(&mut this, node: u32, kind: u32, param: u32, variadic: bool): void { + if kind == 0 { + this.check_expr(node, param); + return; + } + + # `...xs` gives a view or a fixed array of the variadic parameter's elements. + if this.is_spread_arg(node) { + val operand := this.left_of(node); + val plain := this.unalias(this.reached(kind)); + if this.types.kind_of(plain) == ty::fixed && this.types.first_of(plain) == param { + return; + } + this.convert(operand, this.span_of(param)); + return; + } + + if this.types.kind_of(param) == ty::reference && this.lent_whole(node, kind, param) { + val referent := this.types.first_of(param); + if this.types.second_of(param) != 0 { + this.check_unlocked(node); + } + if this.named_kind(this.unalias(referent)) == dk::trait_type { + if !this.satisfies(this.settle(kind), this.unalias(referent)) { + this.report_mismatch(node, kind, param); + } + this.set_flag(node, rf::borrowed); + this.set_convert(node, param); + return; + } + this.convert(node, referent); + if this.types.second_of(param) != 0 && this.is_place(node) && !this.is_writable(node) { + this.report(node, ec::assignable, + "The parameter is `&mut`, so it takes what can be written: a `var`, a mutable field or element, or a new value."); + } + this.set_flag(node, rf::borrowed); + return; + } + if this.calls_back(node, kind, param) { + this.clear_flag(node, rf::checked); + this.check_expr(node, param); + return; + } + # A reference written as one is a pointer for a pointer parameter, at a value + # that lasts as long as the call, whether a place or a new value. + if this.lends_pointer(node, kind, param) { + # A reference to a constant is checked again as one to the type pointed at. + if this.types.is_untyped(this.types.first_of(this.unalias(kind))) { + this.clear_flag(node, rf::checked); + this.hinted_expr(node, param); + } + this.set_convert(node, param); + return; + } + this.convert(node, param); + this.check_owned(node, param); +} + +#! Whether an argument is lent whole for a reference parameter, a reference to +#! it taken: one that is no reference, one that is a reference where the +#! parameter refers to a reference of its type, as `contains` of a +#! `vector<&mark>` takes a `&&mark`, and one whose template lent it so. +#! @param this The checker. +#! @param node The argument's node. +#! @param kind Its type. +#! @param param The parameter's type, a reference. +#! @returns Whether it is. +def checker::lent_whole(&mut this, node: u32, kind: u32, param: u32): bool { + return true if this.types.kind_of(kind) != ty::reference || this.referred_in_template(node); + return this.unalias(kind) == this.unalias(this.types.first_of(param)); +} + +#! Whether an argument checked for an instance was of a type parameter's type in +#! its template, which referred to it for a reference parameter. The instance +#! refers to it the same way, even where the type it gives is a reference, so a +#! call infers what the template's did: `move(value)` moves the reference +#! itself. Where the template's parameter was the type parameter itself, as `T` +#! of `invokable`, the template gave the value, and so does the +#! instance, though `T` is a reference there. +#! @param this The checker. +#! @param node The argument's node. +#! @returns Whether it was. +def checker::referred_in_template(&mut this, node: u32): bool { + return false if this.at.instance == 0; + + val held: rtable = this.tables.p[this.units[this.at.file].table]; + return false if node < held.base || node - held.base >= held.count; + val at := held.offset as u64 + (node - held.base) as u64; + val written: u32 = this.r_types.p[at]; + return written != 0 && this.types.kind_of(this.unalias(written)) == ty::param + && (this.r_flags.p[at] & rf::borrowed as u16) != 0; +} + +#! Whether a value whose type is a reference is taken as what it reaches, as a +#! binding, a lambda's result, and inference take one: unless `&` is written. +#! @param this The checker. +#! @param node The value's node, which notes the decision. +#! @param kind Its type. +#! @returns Whether it is. +pub def checker::takes_value(&mut this, node: u32, kind: u32): bool { + return this.decide(node, rf::valued, !this.lent(node) && this.has_value(kind)); +} + +#! Whether a type is a reference whose referent has a value to take: anything +#! but a trait, which no value is of, so a reference to one is always taken as +#! the reference it is. +#! @param this The checker. +#! @param kind The type. +#! @returns Whether it is. +pub def checker::has_value(&mut this, kind: u32): bool { + val plain := this.unalias(kind); + return this.types.kind_of(plain) == ty::reference && this.named_kind(this.unalias(this.types.first_of(plain))) != dk::trait_type; +} + +#! Decides how a node takes a reference, noting it on the node with the flag: +#! within an instance, as the template's node did, so an instance means what +#! its template does even where a type parameter is a reference there, and +#! otherwise as `holds` says. +#! @param this The checker. +#! @param node The node. +#! @param flag The flag noting it. +#! @param holds What the types say. +#! @returns What is decided. +pub def checker::decide(&mut this, node: u32, flag: rf, holds: bool): bool { + val earlier := this.template_flag(node, flag); + val made := earlier >= 0 ? earlier == 1 : holds; + if made { + this.set_flag(node, flag); + } + return made; +} + +#! Whether a node had a flag where its template was checked, within an +#! instance: 1 where it had, 0 where it had not, and -1 outside an instance. +#! @param this The checker. +#! @param node The node. +#! @param flag The flag. +#! @returns Whether it had. +def checker::template_flag(&mut this, node: u32, flag: rf): i32 { + return -1 if this.at.instance == 0; + val held: rtable = this.tables.p[this.units[this.at.file].table]; + return -1 if node < held.base || node - held.base >= held.count; + val at := held.offset as u64 + (node - held.base) as u64; + return (this.r_flags.p[at] & flag as u16) != 0 ? 1 : 0; +} + +#! Takes a reference to the value a method is called on, where it is not one. +#! @param this The checker. +#! @param object The receiver's node. +#! @param param The type of `this`. +def checker::pass_receiver(&mut this, object: u32, param: u32): void { + if this.types.second_of(param) != 0 { + this.check_unlocked(object); + } + val kind := this.type_at(object); + val plain := this.unalias(kind); + if this.types.kind_of(plain) == ty::reference || this.types.kind_of(plain) == ty::pointer { + return; + } + this.set_flag(object, rf::borrowed); +} + +#! A call of a function value: a local, a field, or anything giving a function, +#! or of a value of another type through its `invoke`, as `f(x)` is `f.invoke(x)`. +#! @param this The checker. +#! @param node The `call` node. +#! @param callee The node of the function value. +#! @param args The arguments' nodes. +#! @param expected The type expected of what it gives, or the error type. +#! @returns The type the function gives, or the error type. +def checker::call_value(&mut this, node: u32, callee: u32, args: span, expected: u32): u32 { + val kind := this.infer_expr(callee); + if kind == bt::error { + this.infer_args(args); + return bt::error; + } + + var plain := this.unalias(this.read_type(kind)); + if this.is_std(plain, word::cfn) { + plain = this.unalias(this.types.part_at(plain, 0)); + } + # A value of a type parameter that is a `signature` is called as the function + # it is in each instance, `def(F::params...): F::result`. + val sig := this.std_decl(word::signature); + if this.types.kind_of(plain) == ty::param && sig != 0 && this.satisfies(plain, this.decls.types.p[sig]) { + var parts := vector::::new(); + parts.append(this.projected(plain, this.trait_member(sig, word::params), this.decls.types.p[sig])); + plain = this.types.function(parts.view(), this.projected(plain, this.trait_member(sig, word::result), this.decls.types.p[sig]), true); + } + if this.types.kind_of(plain) != ty::function { + # A value of a type with an `invoke` is called through it, by the rules of a + # method's call, the value as `this`. The call names the method itself, since + # the callee still names the value. + val through := this.reached(kind); + val found := this.find_member(through, word::invoke); + if found.decl != 0 && this.decls.kinds.p[found.decl] == dk::function { + if !this.visible(found.decl) { + this.report_hidden(callee, found.decl); + } + this.set_flag(node, rf::invokes); + return this.call_decl(node, node, found.decl, callee, found.owner, through, 0, args, expected); + } + # A property is read as a field is, as `m.is_none`, which `()` would call. + if this.kind_of(callee) == nk::member { + val owner := this.reached(this.type_at(this.left_of(callee))); + val member := this.find_member(owner, this.name_of(callee)); + if member.decl != 0 && this.decls.kinds.p[member.decl] == dk::property { + var text := string::from("`", nothing {}); + text.append(this.names.text(this.name_of(callee))); + text.append("` is a property, read as a field is, without `()`."); + this.report_text(callee, ec::operands, &text); + this.infer_args(args); + return bt::error; + } + } + this.report_operand(callee, kind, "Only a function is called, or a value of a type with an `invoke`, as `invokable` asks for."); + this.infer_args(args); + return bt::error; + } + return this.call_signature(node, plain, args, 0); +} + +#! Checks a call's arguments against a function type, from its parameter at +#! `skip`, as a method's after `this`. A variadic last parameter takes every +#! argument after those before it, or a view `...xs` of them, and a pack spread +#! with `...args` gives an argument for each of its types. +#! @param this The checker. +#! @param node The `call` node. +#! @param kind The function type. +#! @param args The arguments' nodes. +#! @param skip How many parameters come before the first argument. +#! @returns The type the function gives, or the error type. +def checker::call_signature(&mut this, node: u32, kind: u32, args: span, skip: u32): u32 { + val count := this.types.part_count(kind); + val variadic := this.types.second_of(kind) != 0 && count != 0; + val kinds := this.arg_kinds(args, false, false); + + # Passing on a pack whose types are not known, or calling a function whose + # parameters are one, is checked in each instance, where they are known. + var later := variadic && this.types.is_open_pack(this.types.part_at(kind, count - 1)); + for i in 0..args.length { + later = later || (this.is_spread_arg(args[i]) && kinds[i] != 0 && this.types.is_open_pack(this.reached(kinds[i]))); + } + if later { + for i in 0..args.length { + if kinds[i] == 0 { this.infer_expr(args[i]); } + } + return this.types.first_of(kind); + } + + val takes := count - skip; + val given := this.given_count(args, kinds.view()); + val spread := this.reports_spread(kind, skip, args, kinds.view()); + if spread || (variadic ? given + 1 < takes : given != takes) { + if !spread { + val words := variadic + ? $"The function takes at least {takes - 1} arguments, but is given {given}." + : $"The function takes {takes} arguments, but is given {given}."; + var text := string::from(words.view(), nothing {}); + this.report_text(node, ec::arguments, &text); + } + for i in 0..args.length { + if kinds[i] == 0 { this.infer_expr(args[i]); } + } + return this.types.first_of(kind); + } + + this.pass_args(kind, args, kinds.view(), skip, variadic); + return this.types.first_of(kind); +} + +#! Checks each argument of a call against the parameter it is given for, from +#! the one at `skip`, a pack spread with `...` giving an argument for each of +#! its types. +#! @param this The checker. +#! @param kind The function type called. +#! @param args The arguments' nodes. +#! @param kinds Their types, as `arg_kinds` gives them. +#! @param skip How many parameters come before the first argument. +#! @param variadic Whether the last parameter takes the rest. +def checker::pass_args(&mut this, kind: u32, args: span, kinds: span, skip: u32, variadic: bool): void { + val count := this.types.part_count(kind); + return if count == 0; + var p := skip; + for i in 0..args.length { + if this.spreads_pack(args[i], kinds[i]) { + val none := constant {}; + for j in 0..this.types.part_count(kinds[i]) { + val param := this.types.part_at(kind, p >= count ? count - 1 : p); + val each := this.types.part_at(kinds[i], j as u32); + if !this.spread_fits(kinds[i], j as u32, kind, p) { + this.report(args[i], ec::arguments, "`...` gives the view of the rest that a variadic function's pack holds only for a variadic parameter."); + p++; + continue; + } + val how := this.fits(each, param, &none, false, 0); + if how == fit::none || how == fit::overflow { + this.report_mismatch(args[i], each, param); + } + p++; + } + continue; + } + val param := this.types.part_at(kind, p >= count ? count - 1 : p); + this.pass_arg(args[i], kinds[i], param, variadic && p + 1 >= count); + p++; + } +} + +#! `compile_error(text)`, which reports its text where checking reaches it: in +#! code that is not generic, or in each instance of what is, since a generic's +#! own body is checked before its type arguments are known. Within branches of +#! `if const` only evaluating decides, it is reported once evaluating chooses +#! each, and text that is not written, as a constant's or interpolated, is the +#! text the checker knows, or else what evaluating works out. +#! @param this The checker. +#! @param node The `call` node. +#! @param args The arguments' nodes: the text, and where the error is. +#! @returns `void`. +def checker::compile_error(&mut this, node: u32, args: span): u32 { + this.infer_args(args); + return bt::void_type if this.decls.has(this.at.decl, df::generic) && this.at.instance == 0; + # Within what is undecided that evaluating does not decide, or within a + # branch checked quietly, it never reports. + return bt::void_type if this.undecided != 0 && (this.undecided != this.branches.length || this.mute != 0); + + var text := string::new(nothing {}); + var computed := false; + if args.length != 0 && this.kind_of(args[0]) == nk::string { + this.literal_text(this.text_of(args[0]), &mut text); + } else if args.length != 0 { + val known := this.known_of(args[0], 0, 0); + val read := known == 0 ? this.runtime_local_read(args[0]) : 0; + if known != 0 && this.knowns.p[known].kind == kk::text { + text.append(this.known_text(known)); + } else if read != 0 { + this.report_runtime_read(read); + return bt::void_type; + } else { + computed = true; + } + } else { + text.append("The program reports an error here."); + } + + # Where `at` is a description's, as `d.at`, the error is where it declares. + var file := this.at.file; + var place := node; + if args.length > 1 && this.kind_of(args[1]) == nk::member { + val one := this.reflected_one(this.left_of(args[1])); + if one != checker::no_reflection { + val held: desc = this.descs[one]; + file = this.decls.files.p[held.decl]; + place = this.decls.nodes.p[held.decl]; + } + } + # What is checked quietly is only dropped, so nothing of it waits. + if (computed || this.branches.length != 0) && this.mute == 0 { + if computed { + this.to_evaluate.append(pair_key(this.at.table, node)); + } + this.held_errors.append(checker::held_error { + table = this.at.table, + node = node, + file = file, + place = place, + decl = this.at.decl, + instance = this.at.instance, + detail = move(&mut text), + first = this.held_branches.length as u32, + count = this.branches.length as u32, + computed = computed + }); + this.held_branches.extend(this.branches.view()); + return bt::void_type; + } + this.report_in(file, place, ec::invalid, text.view()); + return bt::void_type; +} + +#! Reports a `compile_error` left to evaluating, once evaluating chose each +#! branch around it, as checking would have reported it there. +#! @param this The checker. +#! @param index The held error. +#! @param text What evaluating worked out it says, where it did. +pub def checker::report_held(&mut this, index: u32, text: &mut string): void { + val held := &this.held_errors[index]; + val saved := this.at; + this.at.decl = held.decl; + this.at.instance = held.instance; + if held.computed && text.length == 0 { + text.append("The program reports an error here."); + } + val detail := held.computed ? text.view() : held.detail.view(); + this.report_in(held.file, held.place, ec::invalid, detail); + this.at = saved; +} + +#! The text a string literal writes, without its quotes, and of text spanning +#! lines, without the indentation of its closing quotes or the line breaks +#! around it. +#! @param this The checker. +#! @param written The literal as written, with its quotes. +#! @param out Where the text is written. +def checker::literal_text(&this, written: strview, out: &mut string): void { + if written.length < 6 || written[0] != '"' || written[1] != '"' || written[2] != '"' { + out.append(written.substr(1, written.length - 2)); + return; + } + + var inner := written.substr(3, written.length - 6); + var indent := 0u; + var at := inner.length; + while at > 0 && (inner[at - 1] == ' ' || inner[at - 1] == '\t') { + at--; + indent++; + } + var line_start := true; + var skipped := 0u; + var first := true; + for i in 0..at { + val c := inner[i]; + if first && c == '\n' { + first = false; + continue; + } + first = false; + if line_start && skipped < indent && (c == ' ' || c == '\t') { + skipped++; + continue; + } + line_start = c == '\n'; + skipped = 0; + if c == '\n' && i + 1 >= at { + continue; + } + out.push(c); + } +} + +#! Whether an argument names a generic function, which is a value once the type +#! of its parameter gives its type arguments. +#! @param this The checker. +#! @param node The argument's node. +#! @returns Whether it does. +def checker::names_generic(&mut this, node: u32): bool { + return false if this.kind_of(node) != nk::name; + val name := this.name_of(node); + return false if name as u64 >= this.generic_names.length || !this.generic_names[name]; + val ref := this.bound(name) != 0 ? 0 : this.lookup_global(name, 0); + return ref != 0 && this.decls.kinds.p[ref] == dk::function && this.decls.overloads.p[ref] == 0 + && this.decls.has(ref, df::generic) && this.own_param_count(ref) != 0; +} + +#! Whether a path names what is a value only once the function type expected of +#! it is known: a generic function whose type arguments it leaves out, as +#! `integer::parse`, or a method or property of a generic type named without +#! its type arguments, as `result::is_ok`. +#! @param this The checker. +#! @param node The `path` node. +#! @returns Whether it does. +def checker::path_waits(&mut this, node: u32): bool { + return false if this.segment_args(node, this.segment_count(node) - 1) != 0; + # What it names is found quietly, and again where it is checked. + val dropped := this.dropped; + val uninferred := this.uninferred; + this.mute++; + val target := this.path_target(node); + this.mute--; + this.dropped = dropped; + this.uninferred = uninferred; + var decl := target.decl; + return false if decl == 0; + + # Of a member, an owner of the error type is a generic type named without its + # arguments. + val open := this.decls.owners.p[decl] != 0 && target.owner == bt::error; + if this.decls.kinds.p[decl] == dk::property { + return false if !open; + decl = this.property_getter(decl); + return false if decl == 0; + } + return false if this.decls.kinds.p[decl] != dk::function; + # An overloaded function waits to be chosen by its parameter's type, as a name + # of one does. + return true if this.decls.overloads.p[decl] != 0; + this.resolve(decl); + return this.decls.has(decl, df::generic) && (this.own_param_count(decl) != 0 || open); +} + +#! Whether a name names an overloaded function, which is a value only where the +#! type of one overload is expected, as a parameter's. +#! @param this The checker. +#! @param node The `name` node. +#! @returns Whether it does. +def checker::names_overloaded(&mut this, node: u32): bool { + val name := this.name_of(node); + return false if this.bound(name) != 0; + val ref := this.lookup_global(name, 0); + return ref != 0 && this.decls.kinds.p[ref] == dk::function && this.decls.overloads.p[ref] != 0; +} + +#! An argument that is a call, checked quietly, or 0 where it cannot infer its own +#! type arguments without its parameter's type, so it waits for the others to give +#! it. One that is wrong for another reason is checked again where its notes are +#! made. +#! @param this The checker. +#! @param node The argument's node. +#! @returns Its type, or 0 where it waits. +def checker::tried(&mut this, node: u32): u32 { + val dropped := this.dropped; + val uninferred := this.uninferred; + this.mute++; + val kind := this.infer_expr(node); + this.mute--; + return kind if this.dropped == dropped; + + this.clear_flag(node, rf::checked); + return 0 if this.uninferred != uninferred; + return this.infer_expr(node); +} + +#! Checks an argument that waited for its parameter's type, with what is known of +#! it, giving the type arguments what it gives. +#! @param this The checker. +#! @param node The argument's node. +#! @param pattern The parameter's type, as the template writes it. +#! @param into What is inferred. +def checker::infer_later(&mut this, node: u32, pattern: u32, into: &mut checker::inferred): void { + val applied := this.apply_known(pattern, into); + val plain := this.unalias(applied); + + # An array given for a view gives the type of what it views by its elements. + if this.kind_of(node) == nk::array { + val wanted := this.unalias(pattern); + if this.is_std(wanted, word::span) && this.types.part_count(wanted) != 0 && this.types.is_open(plain) { + val run := this.left_of(node); + for &each in this.run_view(run) { + this.unify(this.types.part_at(wanted, 0), this.infer_expr(each), into, 0); + } + } + return; + } + + # An anonymous function given for a type parameter is of that parameter's type. + if this.kind_of(node) == nk::lambda && this.types.kind_of(plain) == ty::param { + this.infer_lambda(node, this.types.first_of(plain), into); + return; + } + + # So is a generic function named as a value. + val named := this.kind_of(node) == nk::name || this.kind_of(node) == nk::path; + if named && this.types.kind_of(plain) == ty::param { + this.infer_named(node, this.types.first_of(plain), into); + return; + } + + # An anonymous function, or a generic function named as a value, is given its + # parameters' types, and gives its result's. + if this.kind_of(node) == nk::lambda || named { + return if this.types.kind_of(plain) != ty::function; + var unknown := false; + for &part in this.types.parts_view(plain) { + unknown = unknown || this.unknown_in(part, into); + } + # Where the parameter's type leaves the function's parameters unknown, as + # `def(&T): bool`, one whose types are written gives them. + if unknown { + if this.typed_lambda(node) { + val own := this.infer_expr(node); + if own != bt::error { + this.unify(pattern, own, into, 0); + } + } + return; + } + this.free_result = this.unknown_in(this.types.first_of(plain), into); + val made := this.expr(node, applied); + this.free_result = false; + this.unify(pattern, made, into, 0); + return; + } + + # A range is std's `range` of the type the parameter gives its ends, or of + # what they are where it gives none. One given for a type parameter bounded by + # `iterator` counts by `E`, where that is known. + if this.kind_of(node) == nk::range { + var wanted := applied; + if this.types.kind_of(plain) == ty::param { + val element := this.iterated_bound(this.types.first_of(plain), into); + val decl := this.std_decl(word::range); + if element != 0 && decl != 0 { + val args: u32[1] = [element]; + wanted = this.types.named(decl, args[0:1]); + } + } + val made := this.types.is_open(wanted) ? this.infer_expr(node) : this.check_expr(node, wanted); + this.unify(pattern, made, into, 0); + return; + } + + # A call that waited is checked once its parameter's type is known. + if this.kind_of(node) == nk::call && !this.types.is_open(applied) { + this.check_expr(node, applied); + } +} + +#! Checks an anonymous function given for a type parameter, which is then of its +#! type. A parameter bounded by `invokable` gives the function the +#! types it leaves out, those inferred so far put in, and takes what the bound +#! names from it, as `R` from what the function gives. One bounded otherwise +#! takes a function whose types are written. +#! @param this The checker. +#! @param node The `lambda` node. +#! @param param The type parameter's declaration. +#! @param into What is inferred. +def checker::infer_lambda(&mut this, node: u32, param: u32, into: &mut checker::inferred): void { + var unbound := false; + for i in 0..into.params.length { + unbound = unbound || (into.params[i] == param && into.binds[i] == checker::unknown_type); + } + return if !unbound; + + val shape := this.invoked_bound(param, into); + var expected: u32 = bt::error; + if shape != 0 { + val known := this.apply_known(shape, into); + var closed := true; + for &part in this.types.parts_view(known) { + closed = closed && !this.unknown_in(part, into); + } + expected = closed ? known : bt::error; + } + this.free_result = expected != bt::error && this.unknown_in(this.types.first_of(expected), into); + val made := this.expr(node, expected); + this.free_result = false; + return if made == bt::error; + this.bind_param(param, made, into); + if shape != 0 { + this.unify(shape, made, into, 0); + } +} + +#! Checks a generic function named as a value given for a type parameter, which +#! is then of its type. A parameter bounded by `invokable` gives it +#! the types of its parameters, those inferred so far put in, from which it is +#! the instance they make, and takes what the bound names from it, as `R` from +#! what it gives. One bounded otherwise takes it as it is named. +#! @param this The checker. +#! @param node The `name` or `path` node. +#! @param param The type parameter's declaration. +#! @param into What is inferred. +def checker::infer_named(&mut this, node: u32, param: u32, into: &mut checker::inferred): void { + var unbound := false; + for i in 0..into.params.length { + unbound = unbound || (into.params[i] == param && into.binds[i] == checker::unknown_type); + } + return if !unbound; + + val shape := this.invoked_bound(param, into); + var expected: u32 = bt::error; + if shape != 0 { + val known := this.apply_known(shape, into); + var closed := true; + for &part in this.types.parts_view(known) { + closed = closed && !this.unknown_in(part, into); + } + expected = closed ? known : bt::error; + } + this.free_result = expected != bt::error && this.unknown_in(this.types.first_of(expected), into); + val made := this.expr(node, expected); + this.free_result = false; + return if made == bt::error; + this.bind_param(param, made, into); + if shape != 0 { + this.unify(shape, made, into, 0); + } + this.adapt_bound(node, made, this.decls.types.p[param], into); +} + +#! Gives a type parameter bounded by `invokable` the function type `S`, where +#! the argument given for it names a function of another type that a call as +#! `S` asks would take, as `filter(big)` gives `def(&&i64): bool` for a `big` +#! taking `&i64`. The argument is then made a function of `S`'s type calling it. +#! @param this The checker. +#! @param node The argument's node. +#! @param kind Its type. +#! @param pattern The parameter's type, as the template writes it. +#! @param into What is inferred. +def checker::adapt_bound(&mut this, node: u32, kind: u32, pattern: u32, into: &mut checker::inferred): void { + return if this.types.kind_of(pattern) != ty::param; + return if this.kind_of(node) != nk::name && this.kind_of(node) != nk::path; + return if this.types.kind_of(this.unalias(kind)) != ty::function; + val param := this.types.first_of(pattern); + val shape := this.invoked_bound(param, into); + return if shape == 0; + var wanted := this.apply_known(shape, into); + for &part in this.types.parts_view(wanted) { + return if this.unknown_in(part, into); + } + # What the bound leaves to what the function gives, as `U` of `map`, it gives. + if this.unknown_in(this.types.first_of(wanted), into) { + this.unify(this.types.first_of(shape), this.types.first_of(this.unalias(kind)), into, 0); + wanted = this.apply_known(shape, into); + return if this.unknown_in(this.types.first_of(wanted), into); + } + return if !this.adapts(node, kind, wanted); + for i in 0..into.params.length { + if into.params[i] == param { + into.binds[i] = wanted; + into.soft[i] = false; + } + } +} + +#! Whether a type names a type parameter the call has yet to infer. One of the +#! generic around the call is known there, as `T` is within `def f`. +#! @param this The checker. +#! @param kind The type. +#! @param into What is inferred. +#! @returns Whether it does. +def checker::unknown_in(&this, kind: u32, into: &checker::inferred): bool { + return false if !this.types.is_open(kind); + for i in 0..into.params.length { + continue if into.binds[i] != checker::unknown_type; + return true if this.mentions(kind, this.decls.types.p[into.params[i]], 0); + } + return false; +} + +#! The function type a type parameter's `invokable` bound names, as `def(&T): +#! bool` of `F: invokable`, in the terms of a trait's default +#! where it is one's, or 0 where it has no such bound. +#! @param this The checker. +#! @param param The type parameter's declaration. +#! @param into What is inferred, whose outer terms are put in. +#! @returns The function type, or 0. +def checker::invoked_bound(&mut this, param: u32, into: &checker::inferred): u32 { + this.resolve(param); + val invokable := this.std_decl(word::invokable); + return 0 if invokable == 0; + val run: u32 = this.decls.children.p[param]; + for i in 0..this.decls.list_length(run) { + val bound := this.unalias(this.outer_terms(this.decls.list_at(run, i as u32), into)); + continue if this.types.kind_of(bound) != ty::named || this.types.first_of(bound) != invokable + || this.types.part_count(bound) != 2; + val pack := this.types.part_at(bound, 0); + continue if this.types.kind_of(pack) != ty::pack || this.types.is_open_pack(pack); + return this.types.function(this.types.parts_view(pack), this.types.part_at(bound, 1), this.types.second_of(pack) != 0); + } + return 0; +} + +#! The integer type a type parameter's `iterator` bound gives its elements, +#! with the type parameters inferred so far put in. +#! @param this The checker. +#! @param param The type parameter's declaration. +#! @param into What is inferred. +#! @returns The element's type, or 0 where no such bound gives a known integer. +def checker::iterated_bound(&mut this, param: u32, into: &checker::inferred): u32 { + this.resolve(param); + val iterator := this.std_decl(word::iterator); + return 0 if iterator == 0; + val run: u32 = this.decls.children.p[param]; + for i in 0..this.decls.list_length(run) { + val bound := this.unalias(this.outer_terms(this.decls.list_at(run, i as u32), into)); + continue if this.types.kind_of(bound) != ty::named || this.types.first_of(bound) != iterator + || this.types.part_count(bound) != 1; + val element := this.apply_known(this.types.part_at(bound, 0), into); + return element if !this.types.is_open(element) && this.types.is_integer(this.unalias(element)); + } + return 0; +} diff --git a/analyzer/checker/composite.sakura b/analyzer/checker/composite.sakura new file mode 100644 index 00000000..7b48b7ba --- /dev/null +++ b/analyzer/checker/composite.sakura @@ -0,0 +1,587 @@ +#! @file composite.sakura +#! @author John Christman (sorakatadzuma@gmail.com) +#! @copyright Malunal Studios, LLC. +#! @license MIT +#! +#! Contains the checking of values built from others: struct and union +#! literals, array literals, and anonymous functions, which may take their +#! types from the type expected of them. + +module sakura::analyzer; + + +#! A struct or union literal, as `vec2{1, 2}`, `vec2{ y = 8 }`, or +#! `res::{ error = 5 }`. A generic struct written without its type +#! arguments takes them from the type expected, or from its fields' values. +#! @param this The checker. +#! @param node The `construct` node. +#! @param expected The type expected, or the error type where none is. +#! @returns The literal's type, or the error type where it is not valid. +def checker::construct(&mut this, node: u32, expected: u32): u32 { + val named := this.left_of(node); + val inits := this.right_of(node); + val decl := this.type_name_decl(named); + if decl == 0 { + this.check_inits(inits); + return bt::error; + } + + var kind: u32 = bt::error; + val wanted := this.unalias(expected); + val written_args := this.segment_args(named, this.segment_count(named) - 1); + if this.decls.has(decl, df::generic) && written_args == 0 && this.segment_count(named) == 1 + && !this.scope_gives_args(this.segment_name(named, 0), decl) { + if this.types.kind_of(wanted) == ty::named && this.types.first_of(wanted) == decl { + kind = wanted; + } else { + kind = this.infer_struct(decl, inits, named); + } + } else { + kind = this.resolve_type(named); + } + if kind == bt::error { + this.check_inits(inits); + return bt::error; + } + + # `void {}` is the one value of `void`, which holds nothing. + val plain := this.unalias(kind); + if plain == bt::void_type { + if this.run_length(inits) != 0 { + this.report(this.run_at(inits, 0), ec::invalid, "`void` holds nothing, so `void {}` is given no fields."); + this.check_inits(inits); + } + return kind; + } + match this.named_kind(plain) { + dk::struct_type => this.construct_struct(node, plain, inits); + dk::union_type => this.construct_union(node, plain, inits); + else => { + this.report(named, ec::not_type, "Only a struct or a union is made with `{}`."); + this.check_inits(inits); + return bt::error; + } + } + return kind; +} + +#! The declaration a type name names, without looking at its type arguments, +#! or 0 where it names none. +#! @param this The checker. +#! @param node The `type_name` node. +#! @returns The declaration, or 0. +def checker::type_name_decl(&mut this, node: u32): u32 { + if this.segment_count(node) == 1 { + val name := this.segment_name(node, 0); + val bound := this.bound(name); + if (bound & ref_type) != 0 { + this.set_ref(node, bound); + return this.type_decl(bound & ref_mask); + } + + val decl := this.lookup_type(name, node); + if decl == 0 || !this.is_type_decl(decl) { + var text := string::from("No struct or union `", nothing {}); + text.append(this.names.text(name)); + text.append("` is declared where it is written."); + this.report_text(node, ec::undefined, &text); + return 0; + } + this.set_ref(node, decl); + return decl; + } + + val kind := this.resolve_type(node); + return kind == bt::error ? 0 : this.type_decl(this.unalias(kind)); +} + +#! Whether a type around a name gives the arguments of the generic type it +#! names, as `list` gives `node` its `T` within it, which then takes no more. +#! @param this The checker. +#! @param name The ID of the name. +#! @param decl The type's declaration. +#! @returns Whether it does. +def checker::scope_gives_args(&mut this, name: u32, decl: u32): bool { + return false if this.bound(name) != 0 || this.own_param_count(decl) != 0; + val found := this.in_scope(name, true); + return found.decl == decl && this.types.kind_of(found.owner) == ty::named && this.types.part_count(found.owner) != 0; +} + +#! Checks the values of a literal whose type went wrong, so what is wrong +#! within them is still reported. +#! @param this The checker. +#! @param run The run of `field_init` nodes. +def checker::check_inits(&mut this, run: u32): void { + for &each in this.run_view(run) { + this.infer_expr(this.left_of(each)); + } +} + +#! The type of a generic struct whose type arguments its fields' values give. +#! @param this The checker. +#! @param decl The struct's declaration. +#! @param inits The run of `field_init` nodes. +#! @param node The node notes are placed at. +#! @returns The struct's type, or the error type where its fields do not give +#! its arguments. +def checker::infer_struct(&mut this, decl: u32, inits: u32, node: u32): u32 { + var inferred := this.begin_inference(decl, bt::error, span::::empty()); + val fields: u32 = this.decls.children.p[decl]; + for i in 0..this.run_length(inits) { + val init := this.run_at(inits, i as u32); + val field := this.init_field(decl, init, i as u32); + continue if field == 0; + + this.resolve(field); + val value := this.left_of(init); + if !this.deferred(value) { + this.unify(this.decls.types.p[field], this.infer_expr(value), &mut inferred, 0); + } + } + + val missing := this.unbound(&inferred); + if missing != 0 { + var text := string::from("Nothing gives the type of `", nothing {}); + text.append(this.decl_text(missing)); + text.append("`, so give the type arguments, as `"); + text.append(this.decl_text(decl)); + text.append("::<...>{...}`."); + this.report_text(node, ec::generic, &text); + return bt::error; + } + return this.named_of(decl, inferred.binds.view(), node, true); +} + +#! The field a value of a literal is given for: the one it names, or the one at +#! its place, or 0. +#! @param this The checker. +#! @param decl The struct's or union's declaration. +#! @param init The `field_init` node. +#! @param index Its position in the literal. +#! @returns The field's declaration, or 0. +def checker::init_field(&mut this, decl: u32, init: u32, index: u32): u32 { + if this.node_has(init, nf::named) { + val found := this.find_member(this.decls.types.p[decl], this.name_of(init)); + return found.decl != 0 && this.decls.kinds.p[found.decl] == dk::field ? found.decl : 0; + } + + val run: u32 = this.decls.children.p[decl]; + var at: u32 = 0; + for &field in this.decls.list_view(run) { + continue if this.decls.kinds.p[field] != dk::field; + return field if at == index; + at++; + } + return 0; +} + +#! The fields of a struct literal: each value given converts to its field, +#! and each field left out takes its default, or its zero value. +#! @param this The checker. +#! @param node The `construct` node. +#! @param kind The struct's type. +#! @param inits The run of `field_init` nodes. +def checker::construct_struct(&mut this, node: u32, kind: u32, inits: u32): void { + val decl := this.types.first_of(kind); + var given := vector::::new(); + for i in 0..this.run_length(inits) { + val init := this.run_at(inits, i as u32); + val value := this.left_of(init); + val field := this.init_field(decl, init, i as u32); + if field == 0 { + if this.node_has(init, nf::named) { + this.report_no_member(init, kind, this.name_of(init)); + } else { + this.report(init, ec::arguments, "The literal gives more values than the struct has fields."); + } + this.infer_expr(value); + continue; + } + + var twice := false; + for &each in given { + twice = twice || each == field; + } + if twice { + this.report(init, ec::duplicate, "The field is given a value twice."); + } + given.append(field); + this.check_reaches(init, kind, field); + + this.resolve(field); + val owner: u32 = this.decls.owners.p[field]; + val held := owner == decl + ? this.instantiated(this.decls.types.p[field], decl, kind) + : this.decls.types.p[field]; + this.check_expr(value, held); + this.check_owned(value, held); + this.set_ref(init, field); + } + + # A field left out takes its default, or its zero value, which a reference + # or a function does not have. + val run: u32 = this.decls.children.p[decl]; + for i in 0..this.decls.list_length(run) { + val field := this.decls.list_at(run, i as u32); + continue if this.decls.kinds.p[field] != dk::field; + + var was_given := false; + for &each in given { + was_given = was_given || each == field; + } + continue if was_given || this.field_default(field) != 0; + + this.resolve(field); + val held := this.instantiated(this.decls.types.p[field], decl, kind); + if !this.has_zero(held, 0) { + var text := string::from("`", nothing {}); + text.append(this.decl_text(field)); + text.append("` has no zero value, so the literal gives it a value."); + this.report_text(node, ec::zero_value, &text); + } + } +} + +#! The default value a field is declared with, or 0. +#! @param this The checker. +#! @param field The field's declaration. +#! @returns The default's node, or 0. +pub def checker::field_default(&this, field: u32): u32 { + return this.record_in(field, variable_slot::value); +} + +#! A union literal, which names the one field it holds, or none for its zero +#! value. +#! @param this The checker. +#! @param node The `construct` node. +#! @param kind The union's type. +#! @param inits The run of `field_init` nodes. +def checker::construct_union(&mut this, node: u32, kind: u32, inits: u32): void { + # Naming none, it is the union's zero value. + return if this.run_length(inits) == 0; + if this.run_length(inits) != 1 { + this.report(node, ec::arguments, "A union literal names the one field it holds, as `res{ error = 5 }`."); + this.check_inits(inits); + return; + } + + val decl := this.types.first_of(kind); + val init := this.run_at(inits, 0); + val field := this.init_field(decl, init, 0); + if field == 0 || !this.node_has(init, nf::named) { + this.report(init, ec::member, "A union literal names the field it holds, as `res{ error = 5 }`."); + this.infer_expr(this.left_of(init)); + return; + } + + this.check_reaches(init, kind, field); + this.resolve(field); + this.check_expr(this.left_of(init), this.instantiated(this.decls.types.p[field], decl, kind)); + this.set_ref(init, field); +} + +#! Whether a type has a zero value, which a variable without a value starts at: +#! numbers, `bool`, pointers, and enums with a member of value 0 do, and so do +#! arrays, structs, and unions of what does, but references and functions do +#! not, and a type parameter only where its bounds say so. +#! @param this The checker. +#! @param kind The type. +#! @param depth How deeply the search has gone, which stops a type nesting +#! without end. +#! @returns Whether it has. +pub def checker::has_zero(&mut this, kind: u32, depth: u32): bool { + return true if depth > 8 || kind == bt::error; + + val plain := this.unalias(kind); + match this.types.kind_of(plain) { + ty::reference, ty::function => return false; + ty::param, ty::pack => return this.param_zeroable(plain); + ty::fixed => return this.has_zero(this.types.first_of(plain), depth + 1); + ty::named => { + val decl := this.types.first_of(plain); + match this.decls.kinds.p[decl] { + dk::enum_type => { + this.resolve(decl); + val run: u32 = this.decls.children.p[decl]; + for &member in this.decls.list_view(run) { + var value := constant {}; + if this.decl_value(member, &mut value) && value.magnitude == 0 { + return true; + } + } + return false; + } + dk::struct_type => { + val run: u32 = this.decls.children.p[decl]; + for i in 0..this.decls.list_length(run) { + val field := this.decls.list_at(run, i as u32); + continue if this.decls.kinds.p[field] != dk::field || this.field_default(field) != 0; + this.resolve(field); + return false if !this.has_zero(this.instantiated(this.decls.types.p[field], decl, plain), depth + 1); + } + return true; + } + dk::union_type => { + val fields := this.field_types(plain); + return fields.length == 0 || this.has_zero(fields[0], depth + 1); + } + else => return true; + } + } + else => return true; + } + return true; +} + +#! Whether a type parameter's bounds give it a zero value: `zeroable` does, and +#! so do `integer`, `real`, and `pointer`, since every number and pointer has one. +#! @param this The checker. +#! @param kind The type parameter's type. +#! @returns Whether they do. +def checker::param_zeroable(&mut this, kind: u32): bool { + val zeroable := this.std_decl(word::zeroable); + val integer := this.std_decl(word::integer); + val real := this.std_decl(word::real); + val pointer := this.std_decl(word::pointer); + return (zeroable != 0 && this.param_bounded(kind, zeroable)) || (integer != 0 && this.param_bounded(kind, integer)) + || (real != 0 && this.param_bounded(kind, real)) || (pointer != 0 && this.param_bounded(kind, pointer)); +} + +#! Says why a type has no zero value, for a report that it is not `zeroable`: +#! the type itself, or the field within it that has none, followed through +#! fields and the elements of arrays as `has_zero` follows them, as "its field +#! `inner.r` holds `&i64`, which has no zero value". +#! @param this The checker. +#! @param kind The type. +#! @returns Why, as a note's detail. +pub def checker::zero_lacking(&mut this, kind: u32): string { + var fields := string::new(nothing {}); + var at := this.unalias(kind); + for _ in 0..8 { + if this.types.kind_of(at) == ty::fixed { + at = this.unalias(this.types.first_of(at)); + continue; + } + val is_union := this.named_kind(at) == dk::union_type; + break if this.named_kind(at) != dk::struct_type && !is_union; + + # A union is zeroed as its first field, and a struct as each without a + # default. + val decl := this.types.first_of(at); + val run: u32 = this.decls.children.p[decl]; + var lacking: u32 = 0; + var held: u32 = 0; + for i in 0..this.decls.list_length(run) { + val field := this.decls.list_at(run, i as u32); + continue if this.decls.kinds.p[field] != dk::field; + this.resolve(field); + val inner := this.instantiated(this.decls.types.p[field], decl, at); + if (is_union || this.field_default(field) == 0) && !this.has_zero(inner, 0) { + lacking = field; + held = inner; + } + break if lacking != 0 || is_union; + } + break if lacking == 0; + + if fields.length > 0 { + fields.append("."); + } + fields.append(this.decl_text(lacking)); + at = this.unalias(held); + } + + val described := this.describe(at); + val is_enum := this.named_kind(at) == dk::enum_type; + val is_param := this.types.kind_of(at) == ty::param; + var text := string::new(nothing {}); + if fields.length > 0 { + text.append("its field `"); + text.append(fields.view()); + text.append("` holds `"); + text.append(described.view()); + text.append(is_enum ? "`, no member of which has the value 0" + : is_param ? "`, which has a zero value only where its bounds say it is `zeroable`" + : "`, which has no zero value"); + return text; + } + if is_enum { + text.append("no member of `"); + text.append(described.view()); + text.append("` has the value 0"); + return text; + } + if is_param { + text.append("a type parameter has a zero value only where its bounds say it is `zeroable`"); + return text; + } + if this.types.kind_of(at) == ty::reference || this.types.kind_of(at) == ty::function { + text.append(this.types.kind_of(at) == ty::reference ? "a reference has no zero value" : "a function has no zero value"); + return text; + } + text.append("`"); + text.append(described.view()); + text.append("` has no zero value"); + return text; +} + +#! An array literal: a fixed array of the type its elements share, or of the +#! type expected, or where a `span` is expected, a view of itself. +#! @param this The checker. +#! @param node The `array` node. +#! @param expected The type expected, or the error type where none is. +#! @returns The array's type, or the error type where its elements share none. +def checker::array(&mut this, node: u32, expected: u32): u32 { + val run := this.left_of(node); + val count := this.run_length(run); + val wanted := this.unalias(expected); + if this.types.kind_of(wanted) == ty::fixed { + val element := this.types.first_of(wanted); + for i in 0..count { + this.check_expr(this.run_at(run, i as u32), element); + } + # Within a template, a length only each instance knows is theirs to check. + if count != this.types.second_of(wanted) && this.types.part_count(wanted) == 0 { + val words := $"The array holds {this.types.second_of(wanted)} elements, but {count} are written."; + var text := string::from(words.view(), nothing {}); + this.report_text(node, ec::mismatch, &text); + } + return expected; + } + + if this.is_std(wanted, word::span) { + val element := this.types.part_at(wanted, 0); + for i in 0..count { + this.check_expr(this.run_at(run, i as u32), element); + } + return expected; + } + + if count == 0 { + this.report(node, ec::mismatch, "An empty array takes its type from where it is written, and nothing gives it here."); + return bt::error; + } + + var shared: u32 = 0; + for i in 0..count { + val kind := this.infer_expr(this.run_at(run, i as u32)); + if kind == bt::error { + shared = bt::error; + continue; + } + if shared == 0 { + shared = kind; + continue; + } + if shared != bt::error { + val joined := this.common(shared, kind); + if joined == bt::error { + this.report_operands(this.run_at(run, i as u32), shared, kind, "are elements of one array, which share no type"); + } + shared = joined; + } + } + return bt::error if shared == bt::error; + + val element := this.settle(shared); + for i in 0..count { + this.convert(this.run_at(run, i as u32), element); + } + return this.types.fixed(element, count); +} + +#! An anonymous function, whose parameter types and result may be left out +#! where the function type expected gives them. It shares the locals of the +#! function around it, so it is checked within that function's bindings. +#! @param this The checker. +#! @param node The `lambda` node. +#! @param expected The function type expected, or the error type where none +#! is. +#! @returns The function type. +def checker::lambda(&mut this, node: u32, expected: u32): u32 { + # C calls back what it is given with nothing more, so it can't reach what a + # lambda refers to. + val c_wanted := this.unalias(expected); + if this.is_std(c_wanted, word::cfn) && this.types.part_count(c_wanted) == 1 { + this.report(node, ec::invalid, "C calls back a function of the program named where its address is expected, not a lambda, whose locals C gives it no way to reach."); + this.lambda(node, this.types.part_at(c_wanted, 0)); + return bt::error; + } + + val params := this.left_of(node); + val result := this.record(node, lambda_slot::result); + val body := this.record(node, lambda_slot::body); + val wanted := this.unalias(expected); + val gives := this.types.kind_of(wanted) == ty::function; + + var kinds := vector::::new(); + for i in 0..this.run_length(params) { + val param := this.run_at(params, i as u32); + val written := this.left_of(param); + if written != 0 { + kinds.append(this.resolve_type(written)); + } else if gives && i < this.types.part_count(wanted) { + kinds.append(this.types.part_at(wanted, i as u32)); + } else { + this.report(param, ec::mismatch, gives + ? "The function type expected here has fewer parameters, so give this one a type." + : "No function type is expected here, so give the parameter a type."); + kinds.append(bt::error); + } + } + + # A lambda whose result infers a type argument takes it from its body. + val free := this.free_result; + this.free_result = false; + var returns: u32 = 0; + if result != 0 { + returns = this.resolve_type(result); + } else if gives && !free { + returns = this.types.first_of(wanted); + } + + val saved := this.at; + this.at.result = returns != 0 ? returns : bt::void_type; + this.at.loops = 0; + this.at.body = body; + val mark := this.scope_mark(); + for i in 0..this.run_length(params) { + val param := this.run_at(params, i as u32); + this.set_type(param, kinds[i]); + this.set_flag(param, rf::local); + this.set_flag(param, rf::mutable); + this.bind(this.name_of(param), ref_local | param); + } + + if this.kind_of(body) == nk::block { + val leaves := this.check_block(body) != flow::goes_on; + if returns == 0 { + returns = bt::void_type; + } else if returns != bt::void_type && !leaves { + this.report(node, ec::control, "The function can end without returning a value."); + } + } else if returns == 0 { + # What the body gives is taken as a binding takes it: what a reference + # reaches, unless `&` is written. + returns = this.settle_expr(body); + if this.takes_value(body, returns) { + returns = this.types.first_of(this.unalias(returns)); + this.convert(body, returns); + this.check_owned(body, returns); + } + } else if returns == bt::void_type { + this.settle_expr(body); + } else { + this.check_expr(body, returns); + } + + this.unbind_to(mark); + this.at.result = saved.result; + this.at.loops = saved.loops; + this.at.body = saved.body; + # One whose parameter has no type was reported, and is nothing a call can take. + for &kind in kinds.view() { + return bt::error if kind == bt::error; + } + return this.types.function(kinds.view(), returns, false); +} diff --git a/analyzer/checker/constants.sakura b/analyzer/checker/constants.sakura new file mode 100644 index 00000000..4b0894a0 --- /dev/null +++ b/analyzer/checker/constants.sakura @@ -0,0 +1,341 @@ +#! @file constants.sakura +#! @author John Christman (sorakatadzuma@gmail.com) +#! @copyright Malunal Studios, LLC. +#! @license MIT +#! +#! Contains the constants the checker works out while checking: the values of +#! literals, and of operators applied to constants, which the length of a +#! fixed array, the value of an enum member, and whether a constant fits its +#! type need. An integer is kept as its magnitude and sign, so every value of +#! both `i64` and `u64` is one. + +module sakura::analyzer; + + +#! A constant integer of the magnitude and sign, where zero is never negative. +#! @param magnitude Its magnitude. +#! @param negative Whether it is below zero. +#! @returns The constant. +pub def constant::integer(magnitude: u64, negative: bool): constant { + return constant { word = magnitude, negative = negative && magnitude != 0 }; +} + +#! A constant float. +#! @param real Its value. +#! @returns The constant. +pub def constant::real_of(real: f64): constant { + var held := real; + return constant { word = ((&mut held) as *mut u64)[0], floating = true }; +} + +#! A constant `bool`, as a magnitude of 0 or 1. +#! @param value Its value. +#! @returns The constant. +pub def constant::truth(value: bool): constant { + return constant { word = value ? 1 : 0 }; +} + +#! An integer's magnitude, or a `bool` as 0 or 1, or 0 for a float. +#! @param this The constant. +#! @returns The magnitude. +pub val constant::magnitude: u64 { get => this.floating ? 0 : this.word; } + +#! A float's value, or 0 for an integer. +#! @param this The constant. +#! @returns The value. +pub val constant::real: f64 { + get { + return 0.0 if !this.floating; + var held := this.word; + return ((&mut held) as *mut f64)[0]; + } +} + +#! Whether two constants are the same value, a float's bits and all, as +#! interning them asks. +#! @param this The one constant. +#! @param other The other. +#! @returns Whether they are. +pub def constant::same(&this, other: &constant): bool { + return this.word == other.word && this.negative == other.negative && this.floating == other.floating; +} + +#! The constant as a float. +#! @param this The constant. +#! @returns The float, which an integer converts to. +pub def constant::as_real(&this): f64 { + return this.real if this.floating; + val magnitude := this.magnitude as f64; + return this.negative ? -magnitude : magnitude; +} + +#! The constant's 64 bits, as two's complement where it is negative. +#! @param this The constant. +#! @returns The bits. +pub def constant::bits(&this): u64 { + return this.negative ? ~this.magnitude + 1 : this.magnitude; +} + +#! The constant of the 64 bits, read as signed where `signed` says. +#! @param bits The bits. +#! @param signed Whether they are two's complement. +#! @returns The constant. +pub def constant::from_bits(bits: u64, signed: bool): constant { + if signed && (bits >> 63) != 0 { + return constant::integer(~bits + 1, true); + } + return constant::integer(bits, false); +} + +#! The integer an integer literal writes, in decimal or with `0x`, `0o`, or +#! `0b`, without its `u`, or false where it is past 64 bits. +#! @param this The checker. +#! @param text The literal as written. +#! @param out Where the integer is written. +#! @returns Whether it fits in 64 bits. +pub def checker::read_integer(&this, text: strview, out: &mut constant): bool { + var at := 0u; + var base := 10u; + var limit := text.length; + if limit > 0 && text[limit - 1] == 'u' { + limit--; + } + if limit > 2 && text[0] == '0' { + val prefix := text[1]; + if prefix == 'x' { base = 16; at = 2; } + if prefix == 'o' { base = 8; at = 2; } + if prefix == 'b' { base = 2; at = 2; } + } + + var magnitude := 0u; + while at < limit { + val c := text[at]; + var digit := 0u; + if c >= '0' && c <= '9' { + digit = (c - '0') as u64; + } else if c >= 'a' && c <= 'f' { + digit = (c - 'a') as u64 + 10; + } else if c >= 'A' && c <= 'F' { + digit = (c - 'A') as u64 + 10; + } else { + at++; + continue; + } + + if magnitude > (0xFFFFFFFFFFFFFFFFu - digit) / base { + return false; + } + magnitude = magnitude * base + digit; + at++; + } + + out.word = magnitude; + out.negative = false; + out.floating = false; + return true; +} + +#! The float a float literal writes, without its `f`. +#! @param this The checker. +#! @param text The literal as written. +#! @returns The float. +pub def checker::read_real(&this, text: strview): f64 { + var limit := text.length; + if limit > 0 && text[limit - 1] == 'f' { + limit--; + } + + return match real::parse::(text.substr(0, limit)) { + value(read) => read, + else => 0.0 + }; +} + +#! The code point a character literal writes, from its escape where it is one. +#! @param this The checker. +#! @param text The literal as written, with its quotes. +#! @returns The code point. +pub def checker::read_character(&this, text: strview): u64 { + return 0 if text.length < 3; + + val inner := text.substr(1, text.length - 2); + if inner[0] == '\\' && inner.length >= 2 { + return match inner[1] { + 'n' => 10, + 't' => 9, + 'r' => 13, + '0' => 0, + 'x' => this.read_hex(inner.substr(2, 2)), + else => inner[1] as u64 + }; + } + + # UTF-8: the lead byte's bits, then six of each byte continuing it. + val lead := inner[0]; + return lead as u64 if lead < 0x80; + + val count: u64 = lead >= 0xF0 ? 3 : lead >= 0xE0 ? 2 : 1; + var code: u64 = (lead & (0x3F >> count as u8)) as u64; + for i in 1..(count + 1) { + break if i >= inner.length; + code = (code << 6) | (inner[i] & 0x3F) as u64; + } + return code; +} + +def checker::read_hex(&this, text: strview): u64 { + var value := 0u; + for &c in text { + var digit := 0u; + if c >= '0' && c <= '9' { digit = (c - '0') as u64; } + else if c >= 'a' && c <= 'f' { digit = (c - 'a') as u64 + 10; } + else if c >= 'A' && c <= 'F' { digit = (c - 'A') as u64 + 10; } + value = value * 16 + digit; + } + return value; +} + +#! Whether the constant is within the range of the type, as a signed or +#! unsigned integer of its bits, a float, or a constant of no type. +#! @param this The checker. +#! @param kind The type. +#! @param value The constant. +#! @returns Whether it is. +pub def checker::in_range(&this, kind: u32, value: &constant): bool { + val bits := this.types.first_of(kind); + match this.types.kind_of(kind) { + ty::signed => { + return true if value.floating; + val top: u64 = 1u << (bits - 1) as u64; + return value.negative ? value.magnitude <= top : value.magnitude < top; + } + ty::unsigned => { + return true if value.floating; + return false if value.negative; + return bits == 64 || value.magnitude < (1u << bits as u64); + } + ty::untyped_uint => return !value.negative; + else => return true; + } + return true; +} + +#! The constant an operator gives of two constants, where it gives one: false +#! where it overflows 64 bits, divides by zero, or is no operator on constants. +#! @param this The checker. +#! @param operator The operator. +#! @param a The left constant. +#! @param b The right constant. +#! @param signed Whether they are signed, which division, remainder, +#! comparisons, and shifts care about. +#! @param out Where the constant given is written. +#! @returns Whether it gives one. +pub def checker::fold_binary(&this, operator: tk, a: &constant, b: &constant, signed: bool, out: &mut constant): bool { + if a.floating || b.floating { + val x := a.as_real(); + val y := b.as_real(); + match operator { + tk::plus => { out = constant::real_of(x + y); return true; } + tk::minus => { out = constant::real_of(x - y); return true; } + tk::star => { out = constant::real_of(x * y); return true; } + tk::slash => { out = constant::real_of(x / y); return true; } + tk::modulo => { out = constant::real_of(x % y); return true; } + tk::equals => { out = constant::truth(x == y); return true; } + tk::noteq => { out = constant::truth(x != y); return true; } + tk::less => { out = constant::truth(x < y); return true; } + tk::lesseq => { out = constant::truth(x <= y); return true; } + tk::more => { out = constant::truth(x > y); return true; } + tk::moreeq => { out = constant::truth(x >= y); return true; } + else => return false; + } + return false; + } + + match operator { + tk::plus => return this.fold_add(a, b.magnitude, b.negative, out); + tk::minus => return this.fold_add(a, b.magnitude, !b.negative, out); + tk::star => { + if a.magnitude != 0 && b.magnitude > 0xFFFFFFFFFFFFFFFFu / a.magnitude { + return false; + } + out = constant::integer(a.magnitude * b.magnitude, a.negative != b.negative); + return true; + } + tk::slash => { + return false if b.magnitude == 0; + out = constant::integer(a.magnitude / b.magnitude, a.negative != b.negative); + return true; + } + tk::modulo => { + return false if b.magnitude == 0; + out = constant::integer(a.magnitude % b.magnitude, a.negative); + return true; + } + tk::bitand => { out = constant::from_bits(a.bits() & b.bits(), a.negative || b.negative); return true; } + tk::bitor => { out = constant::from_bits(a.bits() | b.bits(), a.negative || b.negative); return true; } + tk::bitxor => { out = constant::from_bits(a.bits() ^ b.bits(), a.negative != b.negative); return true; } + tk::lshift => { + return false if b.negative || b.magnitude >= 64; + val shifted := a.magnitude << b.magnitude; + return false if (shifted >> b.magnitude) != a.magnitude; + out = constant::integer(shifted, a.negative); + return true; + } + tk::rshift => { + return false if b.negative; + if b.magnitude >= 64 { + out = constant::integer(a.negative ? 1 : 0, a.negative); + return true; + } + out = a.negative + ? constant::from_bits(((a.bits() as i64) >> b.magnitude as i64) as u64, true) + : constant::integer(a.magnitude >> b.magnitude, false); + return true; + } + tk::equals => { out = constant::truth(this.compare_constants(a, b) == 0); return true; } + tk::noteq => { out = constant::truth(this.compare_constants(a, b) != 0); return true; } + tk::less => { out = constant::truth(this.compare_constants(a, b) < 0); return true; } + tk::lesseq => { out = constant::truth(this.compare_constants(a, b) <= 0); return true; } + tk::more => { out = constant::truth(this.compare_constants(a, b) > 0); return true; } + tk::moreeq => { out = constant::truth(this.compare_constants(a, b) >= 0); return true; } + tk::logand => { out = constant::truth(a.magnitude != 0 && b.magnitude != 0); return true; } + tk::logor => { out = constant::truth(a.magnitude != 0 || b.magnitude != 0); return true; } + else => return false; + } + return false; +} + +def checker::fold_add(&this, a: &constant, magnitude: u64, negative: bool, out: &mut constant): bool { + if a.negative == negative { + return false if a.magnitude > 0xFFFFFFFFFFFFFFFFu - magnitude; + out = constant::integer(a.magnitude + magnitude, negative); + return true; + } + + out = a.magnitude >= magnitude + ? constant::integer(a.magnitude - magnitude, a.negative) + : constant::integer(magnitude - a.magnitude, negative); + return true; +} + +#! Below zero where `a` is less than `b`, zero where they are equal, and above +#! zero where `a` is more. +#! @param this The checker. +#! @param a One constant. +#! @param b The other. +#! @returns Their order. +pub def checker::compare_constants(&this, a: &constant, b: &constant): i32 { + if a.floating || b.floating { + val x := a.as_real(); + val y := b.as_real(); + return x < y ? -1 : x > y ? 1 : 0; + } + + return -1 if a.negative && !b.negative; + return 1 if !a.negative && b.negative; + if a.magnitude == b.magnitude { + return 0; + } + val less := a.magnitude < b.magnitude; + return (less != a.negative) ? -1 : 1; +} diff --git a/analyzer/checker/convert.sakura b/analyzer/checker/convert.sakura new file mode 100644 index 00000000..0d014fc9 --- /dev/null +++ b/analyzer/checker/convert.sakura @@ -0,0 +1,829 @@ +#! @file convert.sakura +#! @author John Christman (sorakatadzuma@gmail.com) +#! @copyright Malunal Studios, LLC. +#! @license MIT +#! +#! Contains when a value of one type is taken where another is expected, and +#! how well it fits there, which overloads are chosen by: a type exactly, then +#! a constant taking the type expected, then any other conversion, then +#! becoming a union. Also contains the type two values share, as both sides of +#! an operator or both branches of a ternary must. + +module sakura::analyzer; + + +#! How a value fits where a type is expected, best first. +pub enum fit : u8 { + exact, #! It is the type. + read, #! It is a reference, read through to what it refers to, which is the type. + constant, #! It is a constant, which takes the type. + convert, #! It converts: widening, an alias, a view lent, or reading through a reference. + unite, #! It becomes a union holding it. + none, #! It does not fit. + overflow, #! It is a constant outside the range of the type. +} + +#! The declaration of `core`'s root of the name, which the language relies on, +#! or 0 where it declares none. +#! @param this The checker. +#! @param word The ID of the name. +#! @returns The declaration, or 0. +pub def checker::std_decl(&mut this, word: u32): u32 { + if this.known.get(&word) is some(got) { + return got; + } + + val core := this.modules.find(0, word::core); + val found := core == 0 ? 0 : this.modules.decl(core, word); + this.known.set(word, found); + return found; +} + +#! The type of `core`'s root of the name given the arguments, or the error type +#! where it declares none. +#! @param this The checker. +#! @param word The ID of the name. +#! @param args The type arguments, or none. +#! @returns The type, or the error type. +pub def checker::std_type(&mut this, word: u32, args: span): u32 { + val decl := this.std_decl(word); + return bt::error if decl == 0; + + this.resolve(decl); + return this.types.named(decl, args) if args.length != 0; + return this.decls.types.p[decl]; +} + +#! A `span` of the element. +#! @param this The checker. +#! @param element The element's type. +#! @returns The span's type, or the error type where `core` declares no `span`. +pub def checker::span_of(&mut this, element: u32): u32 { + var args := vector::::new(); + args.append(element); + return this.std_type(word::span, args.view()); +} + +#! The declaration a type is of: a named type's, a built-in type's, or a type +#! parameter's, or 0. +#! @param this The checker. +#! @param kind The type. +#! @returns The declaration, or 0. +pub def checker::type_decl(&this, kind: u32): u32 { + return match this.types.kind_of(kind) { + ty::named, ty::param => this.types.first_of(kind), + else => kind < bt::count as u32 ? this.builtin_of[kind] : 0 + }; +} + +#! Whether the type is the named type of `core`'s root of the name, of any +#! arguments. +#! @param this The checker. +#! @param kind The type. +#! @param word The ID of the name. +#! @returns Whether it is. +pub def checker::is_std(&mut this, kind: u32, word: u32): bool { + return this.types.kind_of(kind) == ty::named && this.types.first_of(kind) == this.std_decl(word) + && this.std_decl(word) != 0; +} + +#! Whether a type is `core`'s vector or mask, `simd` or `mask`, which an +#! executable holds in vector registers. +#! @param this The checker. +#! @param kind The type. +#! @returns Whether it is. +pub def checker::is_lanes_type(&mut this, kind: u32): bool { + val plain := this.unalias(kind); + return this.is_std(plain, word::simd) || this.is_std(plain, word::mask); +} + +#! The type an alias stands for, given its arguments. +#! @param this The checker. +#! @param kind The alias's type. +#! @returns The type it stands for. +pub def checker::alias_target(&mut this, kind: u32): u32 { + val decl := this.types.first_of(kind); + this.resolve(decl); + return this.instantiated(this.decls.targets.p[decl], decl, kind); +} + +#! The type with the type parameters of the declaration replaced by the type +#! arguments of `kind`, a named type of it. +#! @param this The checker. +#! @param inner The type written within the declaration, as a field's. +#! @param decl The generic declaration. +#! @param kind The named type of it, whose arguments replace its parameters. +#! @returns The type with them replaced. +pub def checker::instantiated(&mut this, inner: u32, decl: u32, kind: u32): u32 { + val params: u32 = this.decls.params.p[decl]; + return inner if params == 0 || !this.types.is_open(inner); + + val from := this.decls.list_of(params); + val args := this.types.parts_of(kind); + return this.substitute(inner, from.view(), args.view()); +} + +#! Whether the type is an alias. +#! @param this The checker. +#! @param kind The type. +#! @returns Whether it is. +pub def checker::is_alias(&this, kind: u32): bool { + return this.types.kind_of(kind) == ty::named + && this.decls.kinds.p[this.types.first_of(kind)] == dk::alias_type; +} + +#! The type with every alias it is followed to what it stands for. +#! @param this The checker. +#! @param kind The type. +#! @returns The type at the end of its aliases, or the type itself where it is +#! none. +pub def checker::unalias(&mut this, kind: u32): u32 { + # Nearly every type given is no alias, which its flags say once asked, so + # that is told first, and the rest are followed apart. + return kind if (this.types.flags.p[kind] & (tf::asked as u8 | tf::alias as u8)) == tf::asked as u8; + return this.follow_aliases(kind); +} + +# The type at the end of the aliases a type is followed through, as `unalias` +# gives it, for a type not yet asked of or that is an alias. +def checker::follow_aliases(&mut this, kind: u32): u32 { + var at := kind; + var steps := 0; + while this.aliases(at) && steps < 32 { + at = this.alias_target(at); + steps++; + } + return at; +} + +#! Whether the type is an alias, as `is_alias` says, worked out once and kept in +#! its flags, as nearly every type `unalias` is given is none. +#! @param this The checker. +#! @param kind The type. +#! @returns Whether it is. +def checker::aliases(&mut this, kind: u32): bool { + val flags := this.types.flags.p[kind]; + return (flags & tf::alias as u8) != 0 if (flags & tf::asked as u8) != 0; + val alias := this.is_alias(kind); + this.types.flags.p[kind] = flags | tf::asked as u8 | (alias ? tf::alias as u8 : 0); + return alias; +} + +#! The kind of declaration a named type is of, or `none`. +#! @param this The checker. +#! @param kind The type. +#! @returns The kind of its declaration, or `none` where it is not named. +pub def checker::named_kind(&this, kind: u32): dk { + return this.types.kind_of(kind) == ty::named + ? this.decls.kinds.p[this.types.first_of(kind)] + : dk::none; +} + +#! The integer type an enum is held as. +#! @param this The checker. +#! @param kind The enum's type. +#! @returns The integer type. +pub def checker::enum_integer(&mut this, kind: u32): u32 { + # An enum's members may name earlier ones while it resolves, and its integer + # type is known before them. + val decl := this.types.first_of(kind); + if this.decls.states.p[decl] != ds::resolving { + this.resolve(decl); + } + val integer: u32 = this.decls.targets.p[decl]; + return integer == 0 ? bt::int32 : integer; +} + +#! What the values of an enum's members are flipped by to be ordered as words +#! without a sign: the sign bit where the enum is held signed, and nothing +#! otherwise. +#! @param this The checker. +#! @param kind The enum's type. +#! @returns The bits to flip. +pub def checker::member_flip(&mut this, kind: u32): u64 { + return this.types.is_signed(this.unalias(this.enum_integer(this.unalias(kind)))) ? 0x8000000000000000u : 0; +} + +#! The values of an enum's members, each once, from the least, as a range of +#! its members counts through them: each a word flipped by `member_flip`, so +#! the words order as the values do when compared without a sign. +#! @param this The checker. +#! @param kind The enum's type. +#! @returns The words. +pub def checker::member_order(&mut this, kind: u32): vector { + val plain := this.unalias(kind); + val flip := this.member_flip(plain); + val run: u32 = this.decls.children.p[this.types.first_of(plain)]; + var values := vector::::new(); + for i in 0..this.decls.list_length(run) { + val member := this.decls.list_at(run, i as u32); + var held := constant {}; + continue if this.decls.kinds.p[member] != dk::enum_member || !this.decl_value(member, &mut held); + values.append(held.bits() ^ flip); + } + values.sort(); + + # A member given an earlier one's value is another name for it. + var made := vector::::new(); + for each in values { + if made.length == 0 || made[made.length - 1] != each { + made.append(each); + } + } + return made; +} + +#! The types of the fields of a struct or union type, given its arguments. +#! @param this The checker. +#! @param kind The struct or union type. +#! @returns The type of each field, in order. +pub def checker::field_types(&mut this, kind: u32): vector { + var made := vector::::new(); + val decl := this.types.first_of(kind); + val run: u32 = this.decls.children.p[decl]; + for i in 0..this.decls.list_length(run) { + val field := this.decls.list_at(run, i as u32); + continue if this.decls.kinds.p[field] != dk::field; + this.resolve(field); + made.append(this.instantiated(this.decls.types.p[field], decl, kind)); + } + return made; +} + +#! How the value of the node fits where the type is expected. +#! @param this The checker. +#! @param node The value's node. +#! @param to The type expected. +#! @returns How it fits. +pub def checker::fits_node(&mut this, node: u32, to: u32): fit { + val value := this.value_at(node); + return this.fits(this.type_at(node), to, &value, this.is_known(node), 0); +} + +#! How a value of the type fits where `to` is expected, where `value` is its +#! value when `known`. +#! @param this The checker. +#! @param from The value's type. +#! @param to The type expected. +#! @param value The value, where it is known while compiling. +#! @param known Whether it is. +#! @param depth How deeply the search has gone, which stops a type nesting +#! without end. +#! @returns How it fits. +pub def checker::fits(&mut this, from: u32, to: u32, value: &constant, known: bool, depth: u32): fit { + return fit::exact if from == to || from == bt::error || to == bt::error; + return fit::none if depth > 8; + + val target := this.unalias(to); + val source := this.unalias(from); + val goal := this.types.kind_of(target); + match this.types.kind_of(source) { + ty::untyped_int, ty::untyped_char => { + if goal == ty::signed || goal == ty::unsigned { + return known && !this.in_range(target, value) ? fit::overflow : fit::constant; + } + if goal == ty::untyped_uint { + return known && value.negative ? fit::overflow : fit::constant; + } + return fit::constant if goal == ty::floating || goal == ty::untyped_int + || goal == ty::untyped_float || this.numeric_param(target); + return this.unites(source, target, value, known, depth); + } + ty::untyped_uint => { + if goal == ty::unsigned { + return known && !this.in_range(target, value) ? fit::overflow : fit::constant; + } + return fit::constant if this.numeric_param(target); + return this.unites(source, target, value, known, depth); + } + ty::untyped_float, ty::untyped_float32 => { + return fit::constant if goal == ty::floating || this.numeric_param(target); + return this.unites(source, target, value, known, depth); + } + ty::untyped_bool => return goal == ty::boolean ? fit::constant : this.unites(source, target, value, known, depth); + ty::untyped_text => { + return fit::constant if this.is_std(target, word::string) || this.is_text_view(target); + return this.unites(source, target, value, known, depth); + } + ty::null_type => { + return fit::constant if goal == ty::pointer || this.is_std(target, word::cfn); + return this.unites(source, target, value, known, depth); + } + ty::empty => return fit::constant; + else => {} + } + + # What only differs by aliases converts, anywhere within the types. + return fit::convert if source == target || this.strip(source, 0) == this.strip(target, 0); + + val skind := this.types.kind_of(source); + if this.types.is_numeric(source) && this.types.is_numeric(target) { + val sbits := this.types.first_of(source); + val tbits := this.types.first_of(target); + return fit::convert if skind == goal && tbits > sbits; + return fit::convert if skind == ty::unsigned && goal == ty::signed && tbits > sbits; + return fit::none; + } + + # An enum is its integer type wherever one is expected. + if this.named_kind(source) == dk::enum_type && this.types.is_integer(target) { + val integer := this.enum_integer(source); + return integer == target || this.fits(integer, target, value, false, depth + 1) == fit::convert + ? fit::convert + : fit::none; + } + + if (skind == ty::reference || skind == ty::pointer) && skind == goal { + val inner_from := this.types.first_of(source); + val inner_to := this.types.first_of(target); + val writes := this.types.second_of(source) != 0; + val wants := this.types.second_of(target) != 0; + if !wants || writes { + return fit::convert if this.unalias(inner_from) == this.unalias(inner_to); + + # A reference to a constant, as `&200`, refers to a copy of it of the type + # referred to. + if this.types.is_untyped(inner_from) { + val how := this.fits(inner_from, inner_to, value, false, depth + 1); + return how == fit::none || how == fit::overflow ? how : fit::constant; + } + + # A reference to a value converts to a reference to a trait it satisfies. + if skind == ty::reference && this.named_kind(inner_to) == dk::trait_type + && this.satisfies(inner_from, inner_to) { + return fit::convert; + } + } + + # A reference to a reference is otherwise read through to the one it holds, + # where that converts, as a generic given a reference for `T` reads a `T` + # through a `&mut T`. + if skind == ty::reference && this.types.kind_of(this.unalias(inner_from)) == ty::reference { + val read := this.fits(inner_from, target, value, false, depth + 1); + return read == fit::none || read == fit::overflow ? read : fit::convert; + } + return fit::none; + } + + # A union holds a reference as it holds anything else, before it is read. + if this.named_kind(target) == dk::union_type { + val united := this.unites(source, target, value, known, depth); + return united if united != fit::none; + } + + # A plain reference is read through where its value is expected. + if skind == ty::reference && goal != ty::reference { + val read := this.fits(this.types.first_of(source), target, value, false, depth + 1); + return read == fit::none || read == fit::overflow ? read : fit::convert; + } + + # A view lends a read-only one, and a string lends a view of its text. + if this.is_std(target, word::span) { + if this.is_std(source, word::slice) && this.types.part_at(source, 0) == this.types.part_at(target, 0) { + return fit::convert; + } + if this.is_std(source, word::string) && this.is_text_view(target) { + return fit::convert; + } + } + + # Bytes become a string by being copied into memory the string owns, so it + # outlives whatever they were read from. + if this.is_std(target, word::string) && this.is_byte_view(source) { + return fit::convert; + } + + if skind == ty::function && goal == ty::function { + return this.same_function(source, target) ? fit::convert : fit::none; + } + + return this.unites(source, target, value, known, depth); +} + +#! Whether the type is a view of bytes, read-only or writable. +#! @param this The checker. +#! @param kind The type. +#! @returns Whether it is. +pub def checker::is_byte_view(&mut this, kind: u32): bool { + val plain := this.unalias(kind); + return (this.is_std(plain, word::span) || this.is_std(plain, word::slice)) + && this.unalias(this.types.part_at(plain, 0)) == bt::uint8; +} + +#! The type with every alias within it followed to what it stands for, so +#! types differing only by aliases are the same once stripped. +#! @param this The checker. +#! @param kind The type. +#! @param depth How deeply the search has gone, which stops a type nesting +#! without end. +#! @returns The type stripped. +pub def checker::strip(&mut this, kind: u32, depth: u32): u32 { + return kind if depth > 16 || this.types.is_untyped(kind); + val plain := this.unalias(kind); + match this.types.kind_of(plain) { + ty::reference, ty::pointer, ty::fixed => { + val inner := this.strip(this.types.first_of(plain), depth + 1); + if this.types.part_count(plain) == 0 { + return this.types.intern(this.types.kind_of(plain), inner, this.types.second_of(plain), span::::empty()); + } + val length := this.types.parts_of(plain); + return this.types.intern(this.types.kind_of(plain), inner, this.types.second_of(plain), length.view()); + } + ty::named, ty::function => { + return plain if this.types.part_count(plain) == 0 && this.types.kind_of(plain) == ty::named; + var parts := vector::::new(); + for i in 0..this.types.part_count(plain) { + parts.append(this.strip(this.types.part_at(plain, i as u32), depth + 1)); + } + val first := this.types.kind_of(plain) == ty::function + ? this.strip(this.types.first_of(plain), depth + 1) + : this.types.first_of(plain); + return this.types.intern(this.types.kind_of(plain), first, this.types.second_of(plain), parts.view()); + } + else => return plain; + } + return plain; +} + +#! Whether the type is a view of bytes, which text read in place is: a +#! `span`, or a `strview`. +#! @param this The checker. +#! @param kind The type. +#! @returns Whether it is. +pub def checker::is_text_view(&mut this, kind: u32): bool { + val target := this.unalias(kind); + return this.is_std(target, word::span) && this.unalias(this.types.part_at(target, 0)) == bt::uint8; +} + +#! Whether the type is a type parameter that numbers may stand in for. +#! @param this The checker. +#! @param kind The type. +#! @returns Whether it is one. +def checker::numeric_param(&mut this, kind: u32): bool { + return this.types.kind_of(kind) == ty::param && this.param_has_numeric(this.types.first_of(kind)); +} + +#! Whether function types only differ by aliases. +#! @param this The checker. +#! @param a One function type. +#! @param b The other. +#! @returns Whether they do. +def checker::same_function(&mut this, a: u32, b: u32): bool { + return false if this.types.part_count(a) != this.types.part_count(b); + return false if this.strip(this.types.first_of(a), 0) != this.strip(this.types.first_of(b), 0); + for i in 0..this.types.part_count(a) { + # Aliases are looked through wherever they are, so `&strview` is `&span`, + # and a variadic parameter is the view it takes, so `def(i64...)` is + # `def(span)`. + val x := this.strip(this.param_taken(a, i as u32), 0); + val y := this.strip(this.param_taken(b, i as u32), 0); + return false if x != y; + } + return true; +} + +#! The type a function takes a parameter as: its own, or of a variadic one, a +#! view of what it gathers. +#! @param this The checker. +#! @param kind The function type. +#! @param index The parameter's position. +#! @returns The type. +def checker::param_taken(&mut this, kind: u32, index: u32): u32 { + val part := this.types.part_at(kind, index); + return part if this.types.second_of(kind) == 0 || index + 1 != this.types.part_count(kind); + return this.span_of(part); +} + +#! How a value fits a union: as the field of its own type, or else the one +#! field it converts to. +#! @param this The checker. +#! @param from The value's type. +#! @param to The union's type. +#! @param value The value, where it is known while compiling. +#! @param known Whether it is. +#! @param depth How deeply the search has gone. +#! @returns How it fits: `unite`, or `none`. +def checker::unites(&mut this, from: u32, to: u32, value: &constant, known: bool, depth: u32): fit { + return fit::none if this.named_kind(to) != dk::union_type; + + # A constant goes to the field of the type it would be where nothing else is + # expected, before any other it fits. + val fields := this.field_types(to); + val settled := this.types.is_untyped(from) ? this.settle(from) : from; + var exact := 0; + var fitting := 0; + for &each in fields { + if each == from || each == settled { + exact++; + continue; + } + val how := this.fits(from, each, value, known, depth + 1); + if how != fit::none && how != fit::overflow && how != fit::unite { + fitting++; + } + } + return fit::unite if exact == 1 || (exact == 0 && fitting == 1); + return fit::none; +} + +#! The field of a union a value of the type becomes, or 0. +#! @param this The checker. +#! @param from The value's type. +#! @param to The union's type. +#! @returns The field's declaration, or 0. +pub def checker::united_field(&mut this, from: u32, to: u32): u32 { + val decl := this.types.first_of(to); + val run: u32 = this.decls.children.p[decl]; + val settled := this.types.is_untyped(from) ? this.settle(from) : from; + var found: u32 = 0; + var none_value := constant {}; + for i in 0..this.decls.list_length(run) { + val field := this.decls.list_at(run, i as u32); + continue if this.decls.kinds.p[field] != dk::field; + this.resolve(field); + val kind := this.instantiated(this.decls.types.p[field], decl, to); + return field if kind == from || kind == settled; + val how := this.fits(from, kind, &none_value, false, 1); + if how != fit::none && how != fit::overflow && how != fit::unite && found == 0 { + found = field; + } + } + return found; +} + +#! Converts the node's value to the type, reporting where it does not fit. +#! @param this The checker. +#! @param node The value's node. +#! @param to The type expected. +#! @returns Whether it fits. +pub def checker::convert(&mut this, node: u32, to: u32): bool { + return true if to == bt::error; + + val from := this.type_at(node); + val how := this.fits_node(node, to); + match how { + fit::exact => return true; + fit::none => { + # A reference written as one is a pointer at what it refers to where one + # is expected, which keeps nothing alive. + if this.lends_pointer(node, from, to) { + this.refuse_lent_temporary(node); + this.set_convert(node, to); + return true; + } + # A function named where another function type is expected is called as + # that type asks, by a function made for it. + if this.adapts(node, from, to) { + this.set_convert(node, to); + this.set_flag(node, rf::adapted); + return true; + } + this.report_mismatch(node, from, to); + return false; + } + fit::overflow => { + var text := string::from("The constant is outside the range of `", nothing {}); + val named := this.describe(to); + text.append(named.view()); + text.append("`."); + this.report_text(node, ec::overflow, &text); + return false; + } + else => { + this.set_convert(node, to); + return true; + } + } + return true; +} + +#! Whether a function named as a value, of the type `from`, is called as the +#! function type `to` asks, as a function of `to`'s type made for it calls it: +#! each of `to`'s parameters given as a call gives an argument, those after them +#! given their defaults, and what it gives converted to what `to` gives. A +#! function type matching it exactly takes it as it is. +#! @param this The checker. +#! @param node The node naming it. +#! @param from Its type. +#! @param to The function type expected. +#! @returns Whether it is. +pub def checker::adapts(&mut this, node: u32, from: u32, to: u32): bool { + return false if this.kind_of(node) != nk::name && this.kind_of(node) != nk::path; + val source := this.unalias(from); + val target := this.unalias(to); + return false if this.types.kind_of(source) != ty::function || this.types.kind_of(target) != ty::function; + return false if this.types.second_of(source) != 0 || this.types.second_of(target) != 0; + return false if source == target || this.strip(source, 0) == this.strip(target, 0); + + val ref := this.ref_at(node); + return false if ref == 0 || (ref & (ref_local | ref_type)) != 0; + return this.adapt_cost(ref, source, target) >= 0; +} + +#! How far a function of the type `from` is from being called as the function +#! type `to` asks, as `adapts` says it is: 0 for each parameter given as it is, +#! 1 for one lent or read through, and 2 for one converted, or -1 where it is not +#! called so. A call chooses between overloads by it. +#! @param this The checker. +#! @param decl The function's declaration, whose defaults it is given. +#! @param from Its type. +#! @param to The function type expected. +#! @returns How far, or -1. +pub def checker::adapt_cost(&mut this, decl: u32, from: u32, to: u32): i32 { + val source := this.unalias(from); + val target := this.unalias(to); + return -1 if this.types.kind_of(source) != ty::function || this.types.kind_of(target) != ty::function; + return -1 if this.types.second_of(source) != 0 || this.types.second_of(target) != 0; + + # Only a function of the program is called so, with the defaults it declares. + val kind_of: dk = this.decls.kinds.p[decl]; + return -1 if kind_of != dk::function && kind_of != dk::property; + return -1 if kind_of == dk::function && (this.decls.has(decl, df::foreign) || this.decls.has(decl, df::intrinsic) + || this.decls.has(decl, df::variadic)); + + val given := this.types.part_count(target); + val takes := this.types.part_count(source); + val required: u32 = kind_of == dk::function ? this.required_params(decl) : takes; + return -1 if given > takes || given < required; + var cost: i32 = 0; + for i in 0..given { + val wanted := this.types.part_at(target, i as u32); + val param := this.types.part_at(source, i as u32); + return -1 if !this.passes(wanted, param); + if this.unalias(wanted) != this.unalias(param) { + cost += this.unalias(this.reached(wanted)) == this.unalias(this.reached(param)) ? 1 : 2; + } + } + + # What a call around it still infers from what it gives, as `U` of `map`, + # takes whatever it gives. + return cost if this.free_result; + val none := constant {}; + val gives := this.types.first_of(source); + val wants := this.types.first_of(target); + if this.types.kind_of(this.unalias(gives)) == ty::reference && this.types.kind_of(this.unalias(wants)) != ty::reference + && this.closes(this.reached(gives)) { + return -1; + } + val how := this.fits(gives, wants, &none, false, 0); + return -1 if how == fit::none || how == fit::overflow; + return cost + (how == fit::exact ? 0 : 1); +} + +#! Whether a value of the type `given` is given for a parameter of the type +#! `param` as a call gives it: a value lent where the parameter is a reference, +#! a reference read through to one of the type asked, and what a reference +#! reaches copied where the parameter takes a value, where that closes nothing. +#! @param this The checker. +#! @param given The type given. +#! @param param The parameter's type. +#! @returns Whether it is. +def checker::passes(&mut this, given: u32, param: u32): bool { + val none := constant {}; + val wanted := this.unalias(param); + val held := this.unalias(given); + if this.types.kind_of(wanted) == ty::reference && this.types.kind_of(held) != ty::reference { + val how := this.fits(held, this.types.first_of(wanted), &none, false, 0); + return how == fit::exact || how == fit::convert; + } + if this.types.kind_of(wanted) != ty::reference && this.types.kind_of(held) == ty::reference + && this.closes(this.reached(held)) { + return false; + } + val how := this.fits(held, wanted, &none, false, 0); + return how == fit::exact || how == fit::convert; +} + +#! Whether a value is a reference written as one, `&x` or `&mut x`, given where +#! a pointer at what it refers to is expected, which it becomes: `&T` a `*T`, and +#! `&mut T` a `*mut T` or a `*T`. Nothing else becomes a pointer without `as`, +#! so taking an address is always written. +#! @param this The checker. +#! @param node The value's node. +#! @param from Its type. +#! @param to The type expected. +#! @returns Whether it is. +pub def checker::lends_pointer(&mut this, node: u32, from: u32, to: u32): bool { + return false if !this.lent(node); + val source := this.unalias(from); + val target := this.unalias(to); + return false if this.types.kind_of(source) != ty::reference || this.types.kind_of(target) != ty::pointer; + return false if this.types.second_of(target) != 0 && this.types.second_of(source) == 0; + val inner_from := this.types.first_of(source); + val inner_to := this.types.first_of(target); + # A reference to a constant, as `&10`, refers to a copy of it of the type + # pointed at. + if this.types.is_untyped(inner_from) { + val none := constant {}; + val how := this.fits(inner_from, inner_to, &none, false, 0); + return how != fit::none && how != fit::overflow; + } + return this.unalias(inner_from) == this.unalias(inner_to); +} + +#! Whether a reference written as one refers to a value that is no place, as +#! `&10` or `&make()`, which lives to the end of its statement, or as long as a +#! name a reference binds. +#! @param this The checker. +#! @param node The value's node. +#! @returns Whether it does. +pub def checker::lends_temporary(&mut this, node: u32): bool { + if this.kind_of(node) == nk::ternary { + return this.lends_temporary(this.record(node, if_slot::then)) || this.lends_temporary(this.record(node, if_slot::other)); + } + return false if this.kind_of(node) != nk::reference; + val operand := this.left_of(node); + return !this.is_place(operand) && this.types.kind_of(this.unalias(this.type_at(operand))) != ty::reference; +} + +#! Reports a pointer kept past its statement at a value that ends with it: a +#! pointer keeps nothing alive, as a reference bound to a name does. +#! @param this The checker. +#! @param node The value's node: a reference written as one, or one cast to a +#! pointer. +pub def checker::refuse_lent_temporary(&mut this, node: u32): void { + val lent := this.kind_of(node) == nk::cast ? this.left_of(node) : node; + return if !this.lends_temporary(lent); + this.report(node, ec::invalid, + "A pointer keeps nothing alive, and this one points at a value that ends with its statement: keep the value in a variable first, or refer to it, as a reference bound to a name keeps it."); +} + +#! Reports a value of one type where another is expected. +#! @param this The checker. +#! @param node The value's node. +#! @param from Its type. +#! @param to The type expected. +pub def checker::report_mismatch(&mut this, node: u32, from: u32, to: u32): void { + var text := string::from("Expected `", nothing {}); + val want := this.describe(to); + val given := this.describe(from); + text.append(want.view()); + text.append("`, but the value is `"); + text.append(given.view()); + text.append("`."); + this.report_text(node, ec::mismatch, &text); +} + +#! The type a value of the type becomes where nothing is expected of it: a +#! number constant its default type, and text a `strview`, or a `string` where +#! std declares no `strview`. +#! @param this The checker. +#! @param kind The type. +#! @returns The type it settles as. +pub def checker::settle(&mut this, kind: u32): u32 { + if this.types.kind_of(kind) == ty::reference && this.types.is_untyped(this.types.first_of(kind)) { + return this.types.reference(this.settle(this.types.first_of(kind)), this.types.second_of(kind) != 0); + } + # A literal is a view of the bytes the program was written with, or a `string` + # where std declares no `strview`. + if this.types.kind_of(kind) == ty::untyped_text { + val view := this.std_type(word::strview, span::::empty()); + return view != bt::error ? view : this.std_type(word::string, span::::empty()); + } + if this.types.kind_of(kind) == ty::null_type || this.types.kind_of(kind) == ty::empty { + return kind; + } + return this.types.settled(kind); +} + +#! The type two values share, as the operands of an operator or the branches +#! of a ternary, or the error type where they share none. +#! @param this The checker. +#! @param a One value's type. +#! @param b The other's. +#! @returns The type they share, or the error type. +pub def checker::common(&mut this, a: u32, b: u32): u32 { + return a if a == b; + return b if a == bt::error; + return a if b == bt::error; + + val none := constant {}; + val a_untyped := this.types.is_untyped(a); + val b_untyped := this.types.is_untyped(b); + if a_untyped && b_untyped { + val a_float := this.types.is_float(a); + val b_float := this.types.is_float(b); + return a if a_float && !b_float; + return b if b_float && !a_float; + return a if this.types.kind_of(a) == ty::untyped_uint; + return b if this.types.kind_of(b) == ty::untyped_uint; + return a if this.types.is_integer(a) && this.types.is_integer(b); + return bt::error; + } + + if a_untyped { + val how := this.fits(a, b, &none, false, 0); + return how == fit::none ? bt::error : b; + } + if b_untyped { + val how := this.fits(b, a, &none, false, 0); + return how == fit::none ? bt::error : a; + } + + val forward := this.fits(a, b, &none, false, 0); + val backward := this.fits(b, a, &none, false, 0); + return b if forward == fit::convert && backward == fit::none; + return a if backward == fit::convert && forward == fit::none; + return a if forward != fit::none && backward != fit::none; + return bt::error; +} diff --git a/analyzer/checker/declare.sakura b/analyzer/checker/declare.sakura new file mode 100644 index 00000000..9321756e --- /dev/null +++ b/analyzer/checker/declare.sakura @@ -0,0 +1,627 @@ +#! @file declare.sakura +#! @author John Christman (sorakatadzuma@gmail.com) +#! @copyright Malunal Studios, LLC. +#! @license MIT +#! +#! Contains the declaring of what each file declares: its modules, its +#! imports, and every declaration outside a function, with the members of +#! types and the type parameters of generics. A declaration made through a +#! type, as `vec2::length`, waits until every file is declared, since its type +#! may be declared in any of them. + +module sakura::analyzer; + + +#! Declares what the file declares. +#! @param this The checker. +#! @param file The file. +pub def checker::declare_unit(&mut this, file: u32): void { + this.use_table(this.units[file].table); + this.at.home = 0; + this.at.scope = 0; + + val decls := this.left_of(this.units[file].root); + var active := true; + var begun := false; + var sections := false; + var first_library: u32 = 0; + this.external = false; + for &node in this.run_view(decls) { + match this.kind_of(node) { + nk::import_decl, nk::extern_import => { + if begun { + this.report(node, ec::invalid, "Imports come before every other declaration."); + } + if this.kind_of(node) == nk::import_decl { + this.pending_imports.append(pair_key(file, node)); + } else if this.right_of(node) == 0 || this.target_holds(this.right_of(node)) { + first_library = first_library == 0 ? node : first_library; + this.add_library(file, node); + } + } + nk::module_decl, nk::extern_module => { + begun = true; + this.at.home = this.module_path(this.left_of(node), true); + this.modules.named[this.at.home] = true; + active = this.right_of(node) == 0 || this.target_holds(this.right_of(node)); + this.external = this.kind_of(node) == nk::extern_module; + if this.external { + sections = true; + this.check_section(node); + } + } + else => { + begun = true; + if active { + this.declare_top(node); + } + } + } + } + this.external = false; + + if first_library != 0 && !sections { + this.warn(first_library, ec::invalid, + "Nothing in this file is C's, so nothing uses the libraries it imports: C's functions are declared in an `extern module`."); + } +} + +#! Checks that an `extern module` says which systems it is for, since a library +#! is one system's and C's calling convention is the system's too. +#! @param this The checker. +#! @param node The `extern_module` node. +def checker::check_section(&mut this, node: u32): void { + val condition := this.right_of(node); + if condition == 0 || !this.names_system(condition) { + this.report(node, ec::invalid, "An `extern module` says which systems it's for: `when os == ...`, `arch == ...`, or both."); + } +} + +#! Whether a condition on the target names `os` or `arch` anywhere. +#! @param this The checker. +#! @param node The condition's node. +#! @returns Whether it does. +def checker::names_system(&this, node: u32): bool { + return match this.kind_of(node) { + nk::unary => this.names_system(this.left_of(node)), + nk::binary => this.token_kind(node) == tk::logand || this.token_kind(node) == tk::logor + ? this.names_system(this.left_of(node)) || this.names_system(this.right_of(node)) + : this.name_of(this.left_of(node)) == word::os || this.name_of(this.left_of(node)) == word::arch, + else => false + }; +} + +#! Notes a library a file's C functions come from. On Windows each function is +#! listed under its library, so a file names one there. +#! @param this The checker. +#! @param file The file. +#! @param node The `extern_import` node. +def checker::add_library(&mut this, file: u32, node: u32): void { + if this.names.text(this.target.os) == "windows" { + for i in 0..this.libraries.length { + if (this.libraries[i] >> 32) as u32 == file { + this.report(node, ec::invalid, + "A file names one library on Windows, which lists each C function under its library: declare the functions of another in a file of their own."); + return; + } + } + } + this.libraries.append(pair_key(file, node)); +} + +#! Marks what an `extern module` declares as C's: a function without a body, a +#! struct, or a union. Whatever else it declares is ordinary Sakura. +#! @param this The checker. +#! @param id The declaration. +#! @param kind Its kind. +#! @param node Its node. +def checker::mark_external(&mut this, id: u32, kind: dk, node: u32): void { + if kind == dk::struct_type || kind == dk::union_type + || kind == dk::function && this.record(node, function_slot::body) == 0 { + this.decls.mark(id, df::foreign); + } +} + +#! The module a path names, made where `make` says and it is new, or 0 where +#! it names none. +#! @param this The checker. +#! @param path The `path` node. +#! @param make Whether a module it names is made where it is new. +#! @returns The module, or 0. +pub def checker::module_path(&mut this, path: u32, make: bool): u32 { + var at: u32 = 0; + for i in 0..this.segment_count(path) { + val name := this.segment_name(path, i as u32); + if make { + at = this.modules.child(at, name); + continue; + } + + at = this.modules.find(at, name); + return 0 if at == 0; + } + return at; +} + +#! Declares a declaration at the top level, or those of the branch of a `when` +#! the target takes. +#! @param this The checker. +#! @param node The top-level node. +def checker::declare_top(&mut this, node: u32): void { + match this.kind_of(node) { + nk::when_block => { + val chosen := this.when_branch(node); + return if chosen == 0; + + val decls := this.left_of(chosen); + for &node in this.run_view(decls) { + this.declare_top(node); + } + } + nk::error => {} + else => { + this.decls.top = node; + this.declare_decl(node, 0); + this.decls.top = 0; + } + } +} + +#! The block of a `when` the target takes, following `else when`, or 0. +#! @param this The checker. +#! @param node The `when_block` node. +#! @returns The block, or 0. +pub def checker::when_branch(&mut this, node: u32): u32 { + var at := node; + while at != 0 && this.kind_of(at) == nk::when_block { + return this.record(at, if_slot::then) if this.target_holds(this.left_of(at)); + at = this.record(at, if_slot::other); + } + return at; +} + +#! Whether the target meets the condition of a `when`, reporting a key or a +#! value it does not know. +#! @param this The checker. +#! @param node The condition's node. +#! @returns Whether it does. +pub def checker::target_holds(&mut this, node: u32): bool { + match this.kind_of(node) { + nk::unary => return !this.target_holds(this.left_of(node)); + nk::binary => { + val operator := this.token_kind(node); + if operator == tk::logand { + val left := this.target_holds(this.left_of(node)); + return this.target_holds(this.right_of(node)) && left; + } + if operator == tk::logor { + val left := this.target_holds(this.left_of(node)); + return this.target_holds(this.right_of(node)) || left; + } + + val key := this.name_of(this.left_of(node)); + val value := this.name_of(this.right_of(node)); + val held := this.target_value(this.left_of(node), key, this.right_of(node), value); + return operator == tk::equals ? held : !held; + } + else => return false; + } + return false; +} + +#! Whether the target's value of the key is the value, reporting a key or a +#! value no target has. +#! @param this The checker. +#! @param key_node The node of the key, which a note is placed at. +#! @param key The ID of the key, as `os`. +#! @param value_node The node of the value. +#! @param value The ID of the value, as `linux`. +#! @returns Whether it is. +def checker::target_value(&mut this, key_node: u32, key: u32, value_node: u32, value: u32): bool { + val text := this.names.text(value); + if key == word::os { + if text != "linux" && text != "macos" && text != "windows" && text != "freebsd" { + this.report(value_node, ec::invalid, "`os` is `linux`, `macos`, `windows`, or `freebsd`."); + } + return value == this.target.os; + } + + if key == word::arch { + if text != "x86_64" && text != "aarch64" { + this.report(value_node, ec::invalid, "`arch` is `x86_64` or `aarch64`."); + } + return value == this.target.arch; + } + + if key == word::backend { + if text != "vm" && text != "native" { + this.report(value_node, ec::invalid, "`backend` is `vm` or `native`."); + } + return value == this.target.backend; + } + + this.report(key_node, ec::invalid, "The target keys are `os`, `arch`, and `backend`."); + return false; +} + +#! The kind of declaration a node declares. +#! @param this The checker. +#! @param node The node. +#! @returns The kind. +def checker::decl_kind(&this, node: u32): dk { + return match this.kind_of(node) { + nk::function => dk::function, + nk::variable => dk::variable, + nk::field => dk::field, + nk::property => dk::property, + nk::struct_decl => dk::struct_type, + nk::union_decl => dk::union_type, + nk::trait_decl => dk::trait_type, + nk::enumeration => dk::enum_type, + nk::alias => dk::alias_type, + nk::assoc_type => dk::assoc_type, + nk::enumerator => dk::enum_member, + else => dk::none + }; +} + +#! The receiver a declaration is made through, as `vec2` of `vec2::length`, or +#! 0. +#! @param this The checker. +#! @param node The declaration's node. +#! @returns The receiver's `type_name`, or 0. +def checker::receiver_of(&this, node: u32): u32 { + return match this.kind_of(node) { + nk::function, nk::variable, nk::property, nk::struct_decl, nk::union_decl, + nk::trait_decl, nk::enumeration, nk::alias => this.record(node, decl_slot::receiver), + else => 0 + }; +} + +#! The run of a declaration's own type parameters, or 0. +#! @param this The checker. +#! @param node The declaration's node. +#! @returns The run, or 0. +def checker::own_params_of(&this, node: u32): u32 { + return match this.kind_of(node) { + nk::function, nk::struct_decl, nk::union_decl, nk::trait_decl, nk::alias => this.record(node, decl_slot::type_params), + else => 0 + }; +} + +#! The run of a declaration's attributes, or 0. +#! @param this The checker. +#! @param node The declaration's node. +#! @returns The run, or 0. +pub def checker::attributes_of(&this, node: u32): u32 { + return match this.kind_of(node) { + nk::function, nk::variable, nk::field, nk::property, nk::struct_decl, nk::union_decl, + nk::trait_decl, nk::enumeration, nk::alias, nk::assoc_type => this.record(node, decl_slot::attributes), + nk::enumerator => this.left_of(node), + else => 0 + }; +} + +#! Declares the declaration, as a member of `owner` where it is given, or +#! else in the module, or waiting for its receiver. +#! @param this The checker. +#! @param node The declaration's node. +#! @param owner The type it is a member of, or 0. +#! @returns Its ID, or 0 where it declares nothing. +pub def checker::declare_decl(&mut this, node: u32, owner: u32): u32 { + val kind := this.decl_kind(node); + return 0 if kind == dk::none; + + val id := this.decls.add(kind, this.name_of(node), this.at.file, node, this.at.home); + val flags := this.node_flags(node); + if (flags & nf::exported as u32) != 0 { this.decls.mark(id, df::exported); } + if (flags & nf::mutable as u32) != 0 { this.decls.mark(id, df::mutable); } + if (flags & nf::constant as u32) != 0 { this.decls.mark(id, df::constant); } + if kind == dk::assoc_type && (flags & nf::packed as u32) != 0 { this.decls.mark(id, df::packed); } + this.mark_attributes(id, node); + if this.external && owner == 0 { + this.mark_external(id, kind, node); + } + + if kind == dk::function { + this.mark_signature(id, node); + } + + # A trait's members and the fields of a struct belong to it as they are + # declared. Anything else declared through a type waits for its type. + if owner != 0 { + this.add_member(owner, id); + } else if this.receiver_of(node) != 0 { + this.pending.append(id); + } else { + this.add_global(id); + } + + val own := this.declare_params(this.own_params_of(node), id); + this.record_shape(id, this.own_params_of(node)); + # A function's type parameters are inferred from its arguments, and an alias is + # the type it is written as, so only a struct, union, or trait takes a pattern. + if kind == dk::function || kind == dk::alias_type { + val run := this.own_params_of(node); + for ¶m in this.run_view(run) { + val written := this.kind_of(param); + if written == nk::type_pattern || written == nk::array_pattern { + this.report(param, ec::generic, "Only a struct, union, or trait takes a pattern parameter, as `def(Ts...): R` or `L[N]`."); + } + } + } + # The names of generic functions, which an argument naming one waits by. + if kind == dk::function && own.length != 0 { + val name := this.name_of(node); + if this.generic_names.length <= name as u64 { + this.generic_names.resize(name as u64 + 1, false); + } + this.generic_names[name] = true; + } + if this.receiver_of(node) == 0 { + this.set_params(id, own.view()); + } else { + this.decls.params.p[id] = this.decls.make_list(own.view()); + } + + this.declare_members(id, node); + return id; +} + +#! Gives the declaration its own type parameters, which make it generic. +#! @param this The checker. +#! @param id The declaration. +#! @param own Its own type parameters' declarations. +def checker::set_params(&mut this, id: u32, own: span): void { + this.decls.params.p[id] = this.decls.make_list(own); + if own.length != 0 { + this.decls.mark(id, df::generic); + } +} + +#! Declares the type parameters of the run, each owned by the declaration. +#! @param this The checker. +#! @param run The run of `type_param` nodes. +#! @param owner The declaration they belong to. +#! @returns Their declarations. +def checker::declare_params(&mut this, run: u32, owner: u32): vector { + var made := vector::::new(); + for &node in this.run_view(run) { + # A pattern, `def(Ts...): R`, declares the type parameters it names, those of + # its parameters and then its result's. + if this.kind_of(node) == nk::type_pattern { + val named := this.declare_params(this.left_of(node), owner); + made.extend(named.view()); + if this.right_of(node) != 0 { + val result := this.decls.add(dk::type_param, this.name_of(this.right_of(node)), this.at.file, this.right_of(node), this.at.home); + this.decls.own(result, owner); + made.append(result); + } + continue; + } + # A pattern, `L[N]`, declares its element's type parameter, and its length's + # constant one. + if this.kind_of(node) == nk::array_pattern { + val element := this.decls.add(dk::type_param, this.name_of(this.left_of(node)), this.at.file, this.left_of(node), this.at.home); + this.decls.own(element, owner); + made.append(element); + if this.right_of(node) != 0 { + val length := this.decls.add(dk::type_param, this.name_of(this.right_of(node)), this.at.file, this.right_of(node), this.at.home); + this.decls.own(length, owner); + this.decls.mark(length, df::valued); + made.append(length); + } + continue; + } + val id := this.decls.add(dk::type_param, this.name_of(node), this.at.file, node, this.at.home); + this.decls.own(id, owner); + # A constant parameter stands for a value, whose type it resolves with its bounds. + if this.kind_of(node) == nk::const_param { + this.decls.mark(id, df::valued); + } else if this.node_has(node, nf::packed) { + this.decls.mark(id, df::packed); + # A function's variadic parameter takes a pack, and a struct, union, or + # trait takes one for what it holds or asks for to pass on. + val kind: dk = this.decls.kinds.p[owner]; + if kind != dk::function && kind != dk::struct_type && kind != dk::union_type && kind != dk::trait_type { + this.report(node, ec::generic, "Only a function, struct, union, or trait takes a pack."); + } + } + made.append(id); + } + return made; +} + +#! Declares the fields of a struct or union, the members of a trait, the +#! members of an enum, and the accessors of a property. +#! @param this The checker. +#! @param id The declaration. +#! @param node Its node. +def checker::declare_members(&mut this, id: u32, node: u32): void { + val kind := this.kind_of(node); + if kind != nk::struct_decl && kind != nk::union_decl && kind != nk::trait_decl + && kind != nk::enumeration && kind != nk::property { + return; + } + + var children := vector::::new(); + val members := this.right_of(node); + for &member in this.run_view(members) { + if kind == nk::property { + children.append(this.declare_accessor(id, member)); + continue; + } + + val made := this.declare_decl(member, id); + if made != 0 { + children.append(made); + } + } + this.decls.children.p[id] = this.decls.make_list(children.view()); +} + +#! Declares an accessor of a property, a function of the property's name taking +#! `this`, which is no member of its own: reading or writing the property +#! calls it. +#! @param this The checker. +#! @param property The property's declaration. +#! @param node The `accessor` node. +#! @returns The accessor's declaration. +def checker::declare_accessor(&mut this, property: u32, node: u32): u32 { + val id := this.decls.add(dk::function, this.decls.names.p[property], this.at.file, node, this.at.home); + this.decls.own(id, property); + this.decls.mark(id, df::accessor); + this.decls.mark(id, df::method); + if this.name_of(node) == this.names.intern(&"set") { + this.decls.mark(id, df::setter); + } + if this.decls.has(property, df::exported) || this.node_has(node, nf::exported) { + this.decls.mark(id, df::exported); + } + if this.decls.has(property, df::inline) { + this.decls.mark(id, df::inline); + } + + val params := this.left_of(node); + if this.run_length(params) != 0 && this.node_has(this.run_at(params, 0), nf::mutable) { + this.decls.mark(id, df::mut_this); + } + return id; +} + +#! Marks what the attributes the compiler reads say of the declaration. +#! @param this The checker. +#! @param id The declaration. +#! @param node Its node. +def checker::mark_attributes(&mut this, id: u32, node: u32): void { + val attrs := this.attributes_of(node); + for &attr in this.run_view(attrs) { + continue if this.kind_of(attr) != nk::attribute; + + val named := this.left_of(attr); + val name := this.segment_name(named, this.segment_count(named) - 1); + if name == word::intrinsic { + this.decls.mark(id, df::intrinsic); + } else if name == word::optional { + this.decls.mark(id, df::optional); + } else if name == word::nodiscard { + this.decls.mark(id, df::nodiscard); + } else if name == word::allow { + this.decls.mark(id, df::allows); + } else if name == word::inline { + this.decls.mark(id, df::inline); + } + } +} + +#! Marks what a function's parameters say of it: whether it takes `this`, and +#! `&mut this`, and whether its last parameter is variadic. +#! @param this The checker. +#! @param id The function's declaration. +#! @param node Its node. +def checker::mark_signature(&mut this, id: u32, node: u32): void { + val params := this.record(node, function_slot::params); + val count := this.run_length(params); + return if count == 0; + + # `&this` takes the value a method is called on, as does `this` written with + # a reference to the method's type, `this: &mut T`. + val first := this.run_at(params, 0); + if this.name_of(first) == names::this_id { + val written := this.left_of(first); + if written == 0 { + this.decls.mark(id, df::method); + if this.node_has(first, nf::mutable) { + this.decls.mark(id, df::mut_this); + } + } else if this.kind_of(written) == nk::type_ref { + this.decls.mark(id, df::method); + if this.node_has(written, nf::mutable) { + this.decls.mark(id, df::mut_this); + } + } + } + + if this.node_has(this.run_at(params, count - 1), nf::variadic) { + this.decls.mark(id, df::variadic); + } +} + +#! Declares the declaration in its module, as an overload of the functions of +#! its name there, or reporting a name already taken. +#! @param this The checker. +#! @param id The declaration. +def checker::add_global(&mut this, id: u32): void { + val home: u32 = this.decls.modules.p[id]; + val name: u32 = this.decls.names.p[id]; + val first := this.modules.decl(home, name); + if first == 0 { + this.modules.set_decl(home, name, id); + return; + } + + if this.decls.kinds.p[first] == dk::function && this.decls.kinds.p[id] == dk::function { + this.decls.chain(first, id); + return; + } + + this.report_duplicate(id, first); +} + +#! Makes the declaration a member of the type, as an overload of the functions +#! of its name, or reporting a name already taken. A field is reached through a +#! value, and a type declared through the type through the type, so those two +#! may share a name, as `kind` and `token::kind`. One declared outside `core` on +#! `core`'s type, of a name `core` gives it a member or type of too, is kept +#! apart from `core`'s. +#! @param this The checker. +#! @param owner The type's declaration. +#! @param id The member's declaration. +def checker::add_member(&mut this, owner: u32, id: u32): void { + val name: u32 = this.decls.names.p[id]; + val types := this.decls.nests(id); + val same := this.decls.member_in(owner, name, types); + val other := this.decls.member_in(owner, name, !types); + + # A member or type of `core`'s type declared outside `core`, of a name `core` + # gives it too, is kept apart and chosen over `core`'s where it is seen, so + # `core` adding one later never refuses a program or takes its calls. + val core_id := this.in_core(this.decls.modules.p[id]); + if !core_id && ((same != 0 && this.in_core(this.decls.modules.p[same])) + || (other != 0 && this.in_core(this.decls.modules.p[other]))) { + val first := this.decls.added_member(owner, name); + if first == 0 || (this.decls.kinds.p[first] == dk::function && this.decls.kinds.p[id] == dk::function) { + this.decls.add_added(owner, id); + return; + } + this.decls.own(id, owner); + this.report_duplicate(id, first); + return; + } + # `core`'s, declared after them, takes their place. + if core_id && this.decls.added_member(owner, name) == 0 { + if same != 0 && !this.in_core(this.decls.modules.p[same]) { + this.decls.set_aside(owner, name, types); + this.add_member(owner, id); + return; + } + if other != 0 && !this.in_core(this.decls.modules.p[other]) { + this.decls.set_aside(owner, name, !types); + this.add_member(owner, id); + return; + } + } + val shares := other == 0 || this.decls.kinds.p[types ? other : id] == dk::field; + if shares && (same == 0 || (this.decls.kinds.p[same] == dk::function && this.decls.kinds.p[id] == dk::function)) { + this.decls.add_member(owner, id); + return; + } + + this.decls.own(id, owner); + this.report_duplicate(id, same != 0 ? same : other); +} + +def checker::report_duplicate(&mut this, id: u32, first: u32): void { + this.report_decl_related(id, ec::duplicate, "The name is already declared here.", first, "First declared here."); + this.decls.mark(id, df::failed); +} diff --git a/analyzer/checker/decls.sakura b/analyzer/checker/decls.sakura new file mode 100644 index 00000000..b2a4729c --- /dev/null +++ b/analyzer/checker/decls.sakura @@ -0,0 +1,579 @@ +#! @file decls.sakura +#! @author John Christman (sorakatadzuma@gmail.com) +#! @copyright Malunal Studios, LLC. +#! @license MIT +#! +#! Contains the declaration table, which gives every declaration outside a +#! function an ID of its own, with each of its fields in a column of its own +#! and the declarations of each file, owner, and module listed, and the modules +#! declarations are made in. Locals and parameters are no declarations here: +#! each is known by the node declaring it, whose type the results of the body +#! it is in hold. + +import std::containers; +module sakura::analyzer; + + +#! The kinds of declaration. +pub enum dk : u8 { + none, #! Declaration 0, which stands for "no declaration". + builtin, #! A type every program has, as `i64`, which methods may be declared through. + function, #! A function or method, whose type is its function type. + variable, #! A global variable or constant, or one declared through a type. + field, #! A field of a struct or union. + struct_type, #! A struct. + union_type, #! A union. + enum_type, #! An enum. + enum_member, #! A member of an enum, a constant of it. + trait_type, #! A trait. + alias_type, #! A type alias. + type_param, #! A type parameter of a generic declaration. + assoc_type, #! A type a trait asks for. + property, #! A property, whose accessors are functions declared through its type. + attribute, #! An attribute written on a declaration, as `attributes_of` gives it: a constant of its type, whose value it writes. +} + +#! What a declaration's `flags` hold. +pub enum df : u32 { + exported = 0x0001, #! `pub`. + mutable = 0x0002, #! `var`. + constant = 0x0004, #! `const`, or `const def`. + method = 0x0008, #! A function taking `this`. + mut_this = 0x0010, #! A method taking `&mut this`. + variadic = 0x0020, #! A function whose last parameter is variadic. + generic = 0x0040, #! A declaration with type parameters of its own or of its owner. + intrinsic = 0x0080, #! Given by the compiler, `@intrinsic`. + foreign = 0x0100, #! C's: a function without a body, a struct, or a union of an `extern module`. + failed = 0x0200, #! Its signature is wrong, so what uses it reports nothing more. + optional = 0x0400, #! A trait's member written `@optional`. + packed = 0x0800, #! A type parameter that is a pack, `Ts...`. + accessor = 0x1000, #! A function that is a property's accessor. + setter = 0x2000, #! The `set` of a property. + checked = 0x4000, #! Its body has been checked. + nodiscard = 0x8000, #! What it gives, or a value of it, must be handled where it is made: `@nodiscard`. + valued = 0x10000, #! A type parameter that is a constant parameter, `const N: u64`, whose value's type is its target. + bounding = 0x20000, #! A method whose `where` bounds its type's parameters further, so only the types meeting them have it. + allows = 0x40000, #! A function whose warnings are quieted: `@allow`. + callback = 0x80000, #! A function given where a `cfn` is expected, which C calls back through an entry of its own. + inline = 0x100000, #! A function each call of which is copied, at every level: `@inline`, or an accessor of a property written so. +} + +#! How far a declaration's signature is resolved, which says where one depends +#! on itself. +pub enum ds : u8 { + unresolved, #! Not yet resolved. + resolving, #! Being resolved, so meeting it again means it depends on itself. + resolved, #! Resolved. +} + +#! Every declaration, by its ID, a field in a column of its own. +pub struct decl_table { + # The columns the compiler reads too, through each one's `p`, without a call. + pub var kinds: column; #! The kind of each declaration. + pub var names: column; #! The name of each, by its ID. + pub var files: column; #! The file each is declared in. + pub var nodes: column; #! The node declaring each. + pub var modules: column; #! The module each belongs to. + pub var owners: column; #! The type a member belongs to, or the declaration a type parameter belongs to. + pub var types: column; #! What a variable holds, a function's type, or the type a type declares. + pub var overloads: column; #! The next declaration of the same name and place. + pub var children: column; #! The run of a type's fields, enum members, or trait members in `lists`, or a type parameter's bounds. + + var flags: column; #! The flags of each, as `df` says. + var states: column; #! How far each is resolved. + var params: column; #! The run of a declaration's type parameters in `lists`, its owner's first. + var targets: column; #! What an alias stands for, an enum's integer type, or the default of a type a trait asks for. + var tops: column; #! The node of the top-level declaration each was declared with, or 0 for what the checker made. + var top: u32; #! The node of the top-level declaration being declared, which `add` gives what it adds. + var lists: runs; #! The runs `params` and `children` name. + var members: keymap; #! The first member of each name of a type: `owner << 32 | name`. + var nested: keymap; #! The type of each name declared through a type, as `token::kind`: `owner << 32 | name`. + var added: keymap; #! The first member, or the type, of each name a module outside `core` declares through a type `core` gives a member or type of that name too: `owner << 32 | name`. + + # The declarations of each file, owner, and module, for what walks only those + # rather than every declaration. + var by_file: decl_index; #! The declarations of each file. + var by_owner: decl_index; #! The declarations each declaration has owned: a type's members, or a declaration's type parameters. + var by_module: decl_index; #! The declarations each module has held. +} + +#! Makes a declaration table holding declaration 0, which stands for no +#! declaration. +#! @returns The table. +pub def decl_table::new(): decl_table { + var made := decl_table { + kinds = column::::new(), + names = column::::new(), + files = column::::new(), + nodes = column::::new(), + modules = column::::new(), + owners = column::::new(), + types = column::::new(), + flags = column::::new(), + states = column::::new(), + overloads = column::::new(), + params = column::::new(), + children = column::::new(), + targets = column::::new(), + tops = column::::new(), + lists = runs::::new(), + members = keymap::new(), + nested = keymap::new(), + added = keymap::new(), + by_file = decl_index::new(), + by_owner = decl_index::new(), + by_module = decl_index::new() + }; + + made.add(dk::none, 0, 0, 0, 0); + return made; +} + +#! How many declarations there are. +#! @param this The declaration table. +#! @returns The number, which is one more than the newest's ID. +pub val decl_table::count: u64 { get => this.kinds.length; } + +#! Appends a declaration. +#! @param this The declaration table. +#! @param kind Its kind. +#! @param name Its name's ID. +#! @param file The file it is declared in. +#! @param node The node declaring it. +#! @param home The module it belongs to. +#! @returns Its ID. +pub def decl_table::add(&mut this, kind: dk, name: u32, file: u32, node: u32, home: u32): u32 { + val id := this.kinds.length as u32; + this.kinds.append(kind); + this.names.append(name); + this.files.append(file); + this.nodes.append(node); + this.modules.append(home); + this.owners.append(0); + this.types.append(0); + this.flags.append(0); + this.states.append(ds::unresolved); + this.overloads.append(0); + this.params.append(0); + this.children.append(0); + this.targets.append(0); + this.tops.append(this.top); + if id != 0 { + this.by_file.add(file, id); + this.by_module.add(home, id); + } + return id; +} + +#! Makes a declaration belong to an owner: a member to its type, or a type +#! parameter to the declaration it is of. +#! @param this The declaration table. +#! @param id The declaration. +#! @param owner Its owner. +pub def decl_table::own(&mut this, id: u32, owner: u32): void { + this.owners.p[id] = owner; + if owner != 0 { + this.by_owner.add(owner, id); + } +} + +#! Makes a top-level declaration anew at its new node, as declaring it again +#! does: it keeps its ID, kind, name, file, and type, and is otherwise as `add` +#! made it, with no owner, overloads, flags, or runs. +#! @param this The declaration table. +#! @param id The declaration. +#! @param node Its new node, which is its top-level declaration's too. +#! @param home The module it belongs to now. +pub def decl_table::renew(&mut this, id: u32, node: u32, home: u32): void { + this.nodes.p[id] = node; + this.tops.p[id] = node; + this.modules.p[id] = home; + this.owners.p[id] = 0; + this.overloads.p[id] = 0; + this.flags.p[id] = 0; + this.states.p[id] = ds::unresolved; + this.params.p[id] = 0; + this.children.p[id] = 0; + this.targets.p[id] = 0; + this.by_module.add(home, id); +} + +#! Whether a declaration has a flag. +#! @param this The declaration table. +#! @param id The declaration. +#! @param flag The flag. +#! @returns Whether it has it. +pub def decl_table::has(&this, id: u32, flag: df): bool { + return (this.flags.p[id] & flag as u32) != 0; +} + +#! Gives a declaration a flag. +#! @param this The declaration table. +#! @param id The declaration. +#! @param flag The flag. +pub def decl_table::mark(&mut this, id: u32, flag: df): void { + this.flags.p[id] |= flag as u32; +} + +#! Adds a run of the items to `lists`. +#! @param this The declaration table. +#! @param items The items, which are no view of `lists`. +#! @returns The run's ID, or 0 for none. +pub def decl_table::make_list(&mut this, items: span): u32 { + return this.lists.add(items); +} + +#! How many items a run of `lists` holds. +#! @param this The declaration table. +#! @param run The run's ID. +#! @returns How many items it holds. +pub def decl_table::list_length(&this, run: u32): u32 { + return this.lists.length(run) as u32; +} + +#! The items of a run of `lists`, copied. +#! @param this The declaration table. +#! @param run The run's ID, or 0 for none. +#! @returns The items. +pub def decl_table::list_of(&this, run: u32): vector { + var made := vector::::new(); + made.extend(this.lists.view(run)); + return made; +} + +#! The items of a run of `lists`, where they are. +#! @param this The declaration table. +#! @param run The run's ID, or 0 for none. +#! @returns The items, a view only good until a run is added, so a loop that +#! may add one, as by resolving a declaration, walks them by +#! `list_at`, or copies them by `list_of`. +pub def decl_table::list_view(&this, run: u32): span { + return this.lists.view(run); +} + +#! An item of a run of `lists`, by its position. +#! @param this The declaration table. +#! @param run The run's ID. +#! @param index The position, below its length. +#! @returns The item. +pub def decl_table::list_at(&this, run: u32, index: u32): u32 { + return this.lists.at(run, index as u64); +} + +#! The first member of the type of the name, or 0. A field and a type declared +#! through the type may share a name, and this is the field. +#! @param this The declaration table. +#! @param owner The type's declaration. +#! @param name The name's ID. +#! @returns The member, whose overloads follow it, or 0 where the type has none +#! of the name. +pub def decl_table::member(&this, owner: u32, name: u32): u32 { + val found := this.member_in(owner, name, false); + return found != 0 ? found : this.member_in(owner, name, true); +} + +#! The member of the type of the name `::` reaches: a type declared through it, +#! as `token::kind`, before a field of the same name, which only a value reaches. +#! @param this The declaration table. +#! @param owner The type's declaration. +#! @param name The name's ID. +#! @returns The member, whose overloads follow it, or 0 where the type has none +#! of the name. +pub def decl_table::path_member(&this, owner: u32, name: u32): u32 { + val found := this.member_in(owner, name, true); + return found != 0 ? found : this.member_in(owner, name, false); +} + +#! The first member of the type of the name among its types, or among the +#! rest of its members. +#! @param this The declaration table. +#! @param owner The type's declaration. +#! @param name The name's ID. +#! @param types Whether it is a type declared through the type. +#! @returns The member, or 0. +pub def decl_table::member_in(&this, owner: u32, name: u32, types: bool): u32 { + val key := pair_key(owner, name); + return types ? this.nested.get_or(&key, 0) : this.members.get_or(&key, 0); +} + +#! The first member of the name a module outside `core` declares on the type, +#! where `core` declares one of that name on it too, or 0. Where it is seen, it +#! is chosen over `core`'s, so `core` adding a member never takes a program's +#! place. +#! @param this The declaration table. +#! @param owner The type's declaration. +#! @param name The name's ID. +#! @returns The member, whose overloads follow it, or 0. +pub def decl_table::added_member(&this, owner: u32, name: u32): u32 { + val key := pair_key(owner, name); + return this.added.get_or(&key, 0); +} + +#! Makes a member declared outside `core` one of those `added_member` gives, +#! after the others of its name, or the first. +#! @param this The declaration table. +#! @param owner The type's declaration. +#! @param id The member's declaration. +pub def decl_table::add_added(&mut this, owner: u32, id: u32): void { + this.own(id, owner); + val key := pair_key(owner, this.names.p[id]); + val first := this.added.get_or(&key, 0); + if first == 0 { + this.added.set(key, id); + } else { + this.chain(first, id); + } +} + +#! Makes the members or the type of a name declared outside `core` what +#! `added_member` gives, once `core` declares a member or type of that name too. +#! @param this The declaration table. +#! @param owner The type's declaration. +#! @param name The name's ID. +#! @param types Whether it is a type declared through the type. +pub def decl_table::set_aside(&mut this, owner: u32, name: u32, types: bool): void { + val key := pair_key(owner, name); + val first := this.member_in(owner, name, types); + return if first == 0; + this.added.set(key, first); + if types { + this.nested.remove(&key); + } else { + this.members.remove(&key); + } +} + +#! Whether a member is a type declared through its type, which is kept apart +#! from the type's other members. +#! @param this The declaration table. +#! @param id The member's declaration. +#! @returns Whether it is. +pub def decl_table::nests(&this, id: u32): bool { + return match this.kinds.p[id] { + dk::struct_type, dk::union_type, dk::enum_type, dk::trait_type, dk::alias_type => true, + else => false + }; +} + +#! Makes the declaration a member of its type, after the members of its name +#! already there. +#! @param this The declaration table. +#! @param owner The type's declaration. +#! @param id The member's declaration. +#! @returns The first member of the name. +pub def decl_table::add_member(&mut this, owner: u32, id: u32): u32 { + this.own(id, owner); + val key := pair_key(owner, this.names.p[id]); + val types := this.nests(id); + val first := this.member_in(owner, this.names.p[id], types); + if first == 0 { + if types { + this.nested.set(key, id); + } else { + this.members.set(key, id); + } + return id; + } + + this.chain(first, id); + return first; +} + +#! Puts the declaration last among the overloads beginning with `first`. +#! @param this The declaration table. +#! @param first The first of the overloads. +#! @param id The declaration to put last. +pub def decl_table::chain(&mut this, first: u32, id: u32): void { + var last := first; + var walk := this.walk_overloads(first); + while true { + val at := walk.next(); + break if at == 0; + last = at; + } + this.overloads.p[last] = id; +} + +#! A walk along a chain of overloads from its first, in the order they were +#! chained: `next` gives each in turn, then 0 from then on. +#! +#! Each step reads the overload after the one given last as `next` is called, +#! so what is chained after it while the walk is on it is met, and the table's +#! columns may move as declarations are made. +pub struct overload_walk { + var decls: &decl_table; #! The table holding the chain. + var at: u32; #! The overload given last, or 0 before the first. + var first: u32; #! The first overload, until it is given. + var left: u32; #! How many more overloads it gives at most. +} + +#! The most overloads a walk gives where it is not limited, more than any chain +#! holds. +pub const overload_walk::unlimited: u32 = 0xFFFFFFFF; + +#! A walk along the overloads beginning with `first`. +#! @param this The declaration table. +#! @param first The first of the overloads, or 0 for none. +#! @param limit The most overloads it gives, past which it ends. +#! @returns The walk. +pub def decl_table::walk_overloads(&this, first: u32, limit: u32 = overload_walk::unlimited): overload_walk { + return overload_walk { decls = this, first = first, left = limit }; +} + +#! The next overload of the walk. +#! @param this The walk. +#! @returns The overload, or 0 where there are no more, or the walk gave as +#! many as it was limited to. +pub def overload_walk::next(&mut this): u32 { + return 0 if this.left == 0; + this.left--; + + # Held in a local, so it is not read back after it is stored, which keeps the + # walk short enough to be inlined where it is used. + val at := this.at == 0 ? this.first : this.decls.overloads.p[this.at]; + this.at = at; + this.first = 0; + return at; +} + +#! Lists of declarations by a key, as the declarations of each file, each in +#! increasing ID order, so walking one meets them in the order walking every +#! declaration would. +#! +#! A declaration is listed under a key once given it, and stays listed once it +#! no longer has it, as where it is forgotten or declared again elsewhere, so +#! what walks a list asks each declaration for the key, and its kind, as it +#! would walking every declaration. +pub struct decl_index { + var lists: vector>; #! The declarations of each key, in increasing ID order. +} + +#! Makes an index listing no declaration. +#! @returns The index. +pub def decl_index::new(): decl_index { + return decl_index { lists = vector::>::new() }; +} + +#! Lists a declaration under a key, where it is not listed already. +#! @param this The index. +#! @param key The key, as a file, a module, or a declaration, which are +#! counted from 0, so each has a list of its own. +#! @param id The declaration. +pub def decl_index::add(&mut this, key: u32, id: u32): void { + if key as u64 >= this.lists.length { + this.lists.resize(key as u64 + 1, vector::::new()); + } + val list := &mut this.lists[key]; + + # A declaration just made is the newest, which goes last. + if list.length == 0 || list.last() < id { + list.append(id); + return; + } + val at := list.view().lower_bound(&id); + if list[at] != id { + list.insert_at(at, id); + } +} + +#! The declarations listed under a key. +#! @param this The index. +#! @param key The key. +#! @returns The declarations, in increasing ID order, a view only good until +#! one is listed under the key, so a loop that may add a declaration +#! of it, as by resolving one, copies them first. +pub def decl_index::of(&this, key: u32): span { + return (key as u64) < this.lists.length ? this.lists[key].view() : span::::empty(); +} + +#! The modules of a program. Module 0 is the program itself, which files +#! declaring no module are part of. +pub struct module_table { + pub var names: vector; #! The name of each module, by its ID. + pub var parents: vector; #! The module each is within. + pub var named: vector; #! Whether a file's `module` line names each, rather than only one within it. + var children: keymap; #! Each module by its parent and name: `parent << 32 | name`. + var decls: keymap; #! The first declaration of each name a module makes: `module << 32 | name`. +} + +#! Makes a module table holding module 0, the program itself. +#! @returns The table. +pub def module_table::new(): module_table { + var made := module_table { + names = vector::::new(), + parents = vector::::new(), + named = vector::::new(), + children = keymap::new(), + decls = keymap::new() + }; + + made.names.append(0); + made.parents.append(0); + made.named.append(true); + return made; +} + +#! The module of the name within the parent, made where it is new. +#! @param this The module table. +#! @param parent The module it is within. +#! @param name Its name's ID. +#! @returns The module. +pub def module_table::child(&mut this, parent: u32, name: u32): u32 { + val key := pair_key(parent, name); + if this.children.get(&key) is some(got) { + return got; + } + + val id := this.names.length as u32; + this.names.append(name); + this.parents.append(parent); + this.named.append(false); + this.children.set(key, id); + return id; +} + +#! The module of the name within the parent, or 0 where there is none. +#! @param this The module table. +#! @param parent The module it is within. +#! @param name Its name's ID. +#! @returns The module, or 0. +pub def module_table::find(&this, parent: u32, name: u32): u32 { + val key := pair_key(parent, name); + return this.children.get_or(&key, 0); +} + +#! The first declaration of the name the module makes, or 0. +#! @param this The module table. +#! @param home The module. +#! @param name The name's ID. +#! @returns The declaration, whose overloads follow it, or 0. +pub def module_table::decl(&this, home: u32, name: u32): u32 { + val key := pair_key(home, name); + return this.decls.get_or(&key, 0); +} + +#! Records the first declaration of a name a module makes. +#! @param this The module table. +#! @param home The module. +#! @param name The name's ID. +#! @param id The declaration. +pub def module_table::set_decl(&mut this, home: u32, name: u32, id: u32): void { + this.decls.set(pair_key(home, name), id); +} + +#! Whether `inner` is `outer`, or within it. +#! @param this The module table. +#! @param inner The module asked about. +#! @param outer The module it may be within. +#! @returns Whether it is. +pub def module_table::within(&this, inner: u32, outer: u32): bool { + var at := inner; + var steps := 0; + while steps < 64 { + return true if at == outer; + return false if at == 0; + at = this.parents[at]; + steps++; + } + return false; +} diff --git a/analyzer/checker/describe.sakura b/analyzer/checker/describe.sakura new file mode 100644 index 00000000..f71a4f67 --- /dev/null +++ b/analyzer/checker/describe.sakura @@ -0,0 +1,198 @@ +#! @file describe.sakura +#! @author John Christman (sorakatadzuma@gmail.com) +#! @copyright Malunal Studios, LLC. +#! @license MIT +#! +#! Contains how the checker writes types and declarations as notes spell them, +#! as `&mut list` or `def(u8): bool`. + +module sakura::analyzer; + + +#! The type, as notes spell it. +#! @param this The checker. +#! @param kind The type. +#! @returns Its spelling, as `list`. +pub def checker::describe(&this, kind: u32): string { + var out := string::new(nothing {}); + this.describe_into(kind, &mut out, 0); + return out; +} + +def checker::describe_into(&this, kind: u32, out: &mut string, depth: u32): void { + if depth > 16 { + out.append("..."); + return; + } + + val first := this.types.first_of(kind); + match this.types.kind_of(kind) { + ty::error => out.append("?"); + ty::void_type => out.append("void"); + ty::null_type => out.append("null"); + ty::boolean => out.append("bool"); + ty::untyped_bool => out.append("bool"); + ty::untyped_int => out.append("integer constant"); + ty::untyped_uint => out.append("unsigned integer constant"); + ty::untyped_char => out.append("character constant"); + ty::untyped_float => out.append("float constant"); + ty::untyped_float32 => out.append("float constant"); + ty::untyped_text => out.append("text"); + ty::empty => out.append("empty array element"); + ty::signed => out.append(first == 64 ? "int" : first == 32 ? "i32" : first == 16 ? "i16" : "i8"); + ty::unsigned => out.append(first == 64 ? "uint" : first == 32 ? "u32" : first == 16 ? "u16" : "u8"); + ty::floating => out.append(first == 64 ? "float" : "f32"); + ty::reference, ty::pointer => { + out.append(this.types.kind_of(kind) == ty::reference ? "&" : "*"); + if this.types.second_of(kind) != 0 { + out.append("mut "); + } + this.describe_into(first, out, depth + 1); + } + ty::fixed => { + this.describe_into(first, out, depth + 1); + if this.types.part_count(kind) != 0 { + out.append("["); + this.describe_into(this.types.part_at(kind, 0), out, depth + 1); + out.append("]"); + } else { + val count := $"[{this.types.second_of(kind)}]"; + out.append(count.view()); + } + } + # A constant is written as its value, as `4` of `buffer`. + ty::value => this.describe_known(this.types.second_of(kind), out, depth + 1); + ty::function => { + # A pack parameter says `...` of itself. + out.append("def("); + this.describe_parts(kind, out, depth); + val count := this.types.part_count(kind); + if this.types.second_of(kind) != 0 && (count == 0 || !this.types.is_open_pack(this.types.part_at(kind, count - 1))) { + out.append("..."); + } + out.append("): "); + this.describe_into(first, out, depth + 1); + } + # A pack among the type arguments is written as the types it gives, as + # `box` of `box`. + ty::named => { + if this.qualified_names { + this.module_names(first, out); + } + if this.owned_names || this.qualified_names { + this.owner_names(first, out, 0); + } + out.append(this.names.text(this.decls.names.p[first])); + if this.types.part_count(kind) != 0 { + out.append("<"); + if this.has_patterns(first) { + this.describe_written(kind, out, depth); + } else { + this.describe_args(this.types.parts_view(kind), out, depth + 1); + } + out.append(">"); + } + } + ty::param => out.append(this.names.text(this.decls.names.p[first])); + ty::pack => { + if this.types.part_count(kind) == 0 && first != 0 { + out.append(this.names.text(this.decls.names.p[first])); + out.append("..."); + } else { + # A variadic function's pack of parameters ends in the one taking the rest. + out.append("("); + this.describe_parts(kind, out, depth); + if this.types.second_of(kind) != 0 { + out.append("..."); + } + out.append(")"); + } + } + } +} + +#! The type, with the module of each type it names, as `path_of` spells it: +#! `std::containers::dict`, which no two types share. +#! @param this The checker. +#! @param kind The type. +#! @returns Its spelling. +pub def checker::describe_path(&mut this, kind: u32): string { + val saved := this.qualified_names; + this.qualified_names = true; + var out := this.describe(kind); + this.qualified_names = saved; + return out; +} + +#! Writes the modules a declaration is in, outermost first, as `std::io::`. +#! @param this The checker. +#! @param decl The declaration. +#! @param out Where they are written. +def checker::module_names(&this, decl: u32, out: &mut string): void { + var modules := vector::::new(); + var at: u32 = this.decls.modules.p[decl]; + while at != 0 && modules.length < 64 { + modules.append(at); + at = this.modules.parents[at]; + } + var i := modules.length; + while i > 0 { + i--; + out.append(this.names.text(this.modules.names[modules[i]])); + out.append("::"); + } +} + +#! Writes the types a type is declared through, as `token::` of `token::kind`. +#! @param this The checker. +#! @param decl The type's declaration. +#! @param out Where they are written. +#! @param depth How many have been written. +def checker::owner_names(&this, decl: u32, out: &mut string, depth: u32): void { + val owner: u32 = this.decls.owners.p[decl]; + return if owner == 0 || depth > 8 || !this.decls.nests(decl) || this.decls.kinds.p[owner] == dk::builtin; + this.owner_names(owner, out, depth + 1); + out.append(this.names.text(this.decls.names.p[owner])); + out.append("::"); +} + +def checker::describe_parts(&this, kind: u32, out: &mut string, depth: u32): void { + for i in 0..this.types.part_count(kind) { + if i != 0 { + out.append(", "); + } + this.describe_into(this.types.part_at(kind, i as u32), out, depth + 1); + } +} + +#! The name of the declaration, as notes spell it. +#! @param this The checker. +#! @param id The declaration. +#! @returns The name. +pub def checker::decl_text(&this, id: u32): strview { + return this.names.text(this.decls.names.p[id]); +} + +#! What the declaration is, in a word or two, as "function" or "struct". +#! @param this The checker. +#! @param id The declaration. +#! @returns The word. +pub def checker::decl_word(&this, id: u32): strview { + return match this.decls.kinds.p[id] { + dk::builtin => "type", + dk::function => "function", + dk::variable => this.decls.has(id, df::constant) ? "constant" : "variable", + dk::field => "field", + dk::struct_type => "struct", + dk::union_type => "union", + dk::enum_type => "enum", + dk::enum_member => "enum member", + dk::trait_type => "trait", + dk::alias_type => "type alias", + dk::type_param => "type parameter", + dk::assoc_type => "type", + dk::property => "property", + dk::attribute => "constant", + else => "declaration" + }; +} diff --git a/analyzer/checker/evaluator.sakura b/analyzer/checker/evaluator.sakura new file mode 100644 index 00000000..29d1a846 --- /dev/null +++ b/analyzer/checker/evaluator.sakura @@ -0,0 +1,594 @@ +#! @file evaluator.sakura +#! @author John Christman (sorakatadzuma@gmail.com) +#! @copyright Malunal Studios, LLC. +#! @license MIT +#! +#! Contains the evaluator, which runs code while checking where a value must be +#! known and folding its operators does not give it: a constant's value that +#! calls a function, or the length of a fixed array. It runs over the checked +#! results of what it runs, so it needs nothing of its own made first, and +#! what goes wrong, as an index past the end or a run that never ends, is +#! reported at what asked for the value. +#! +#! It runs integers, floats, and `bool`, and fixed arrays of them, through +#! locals, assignments, branches, loops, and calls of functions that are not +#! generic. What it does not run leaves the value unknown, as before. + +import std::containers; +module sakura::analyzer; + + +#! A value the evaluator holds: a constant, or a fixed array whose elements +#! are `count` constants from `start` of the heap. +pub struct ev { + var array: bool; #! Whether it is an array, rather than a constant. + var scalar: constant; #! The constant, where it is one. + var start: u32; #! Where the array's elements begin on the heap. + var count: u32; #! How many elements the array holds. +} + +#! How evaluating a statement ended. +pub enum eflow : u8 { + goes_on, #! It went on to its end. + returns, #! It returned, with the value in `ev_result`. + breaks, #! It broke out of a loop. + continues, #! It went on to a loop's next turn. + fails, #! It went wrong, which was reported, or it ran into what the evaluator does not run. +} + +#! The most steps an evaluation takes, past which it is reported as never +#! ending. +pub const checker::max_steps: u64 = 10000000; + +#! How deeply evaluated calls nest. +pub const checker::max_calls: u32 = 200; + +#! Works out the value of the expression, which checking did not, by running +#! it, reporting at `site` what goes wrong. +#! @param this The checker. +#! @param node The expression. +#! @param site The node that asked for the value, which a failure is reported +#! at. +#! @param out Where the value is written. +#! @returns Whether it was worked out, with the value in `out`. +pub def checker::evaluate(&mut this, node: u32, site: u32, out: &mut ev): bool { + this.ev_steps = 0; + this.ev_depth = 0; + this.ev_site = site; + this.ev_file = this.at.file; + this.ev_failed = false; + this.ev_frames.append(dict::::new()); + val held := this.ev_expr(node, out); + this.ev_frames.truncate(); + return held && !this.ev_failed; +} + +#! Reports what went wrong while evaluating, at what asked for the value. +#! @param this The checker. +#! @param detail What went wrong, finishing the note's sentence. +def checker::ev_fault(&mut this, detail: strview): void { + return if this.ev_failed; + this.ev_failed = true; + var text := string::from("The value could not be worked out while compiling: ", nothing {}); + text.append(detail); + this.report_in(this.ev_file, this.ev_site, ec::constant, text.view()); +} + +#! Takes one step, reporting a run that never ends. +#! @param this The checker. +#! @returns Whether evaluation may go on, which it may not past `max_steps`. +def checker::ev_step(&mut this): bool { + this.ev_steps++; + if this.ev_steps > checker::max_steps { + this.ev_fault("it runs for too long, as one that never ends does."); + return false; + } + return true; +} + +def checker::ev_scalar(&this, value: constant): ev { + return ev { scalar = value }; +} + +#! The local of the frame being run at the node, or false. +#! @param this The checker. +#! @param node The node declaring the local. +#! @param out Where its value is written. +#! @returns Whether the frame holds it. +def checker::ev_local(&mut this, node: u32, out: &mut ev): bool { + val top := this.ev_frames.length - 1; + return false if !this.ev_frames[top].contains(&node); + val held: ev = this.ev_frames[top][node]; + out = held; + return true; +} + +def checker::ev_set_local(&mut this, node: u32, value: ev): void { + val top := this.ev_frames.length - 1; + this.ev_frames[top].set(node, value); +} + +#! A copy of an array, with elements of its own, so assigning one copies it. +#! @param this The checker. +#! @param value The value, which is given back as it is where it is no array. +#! @returns The copy. +def checker::ev_copy(&mut this, value: ev): ev { + return value if !value.array; + val start := this.ev_heap.length as u32; + for i in 0..value.count { + val element: constant = this.ev_heap[value.start as u64 + i as u64]; + this.ev_heap.append(element); + } + return ev { array = true, start = start, count = value.count }; +} + +#! The constant made to fit an integer type of its bits, wrapping as the +#! program running wraps. +#! @param this The checker. +#! @param value The constant. +#! @param kind The integer type. +#! @returns The constant wrapped to its bits. +def checker::ev_wrap(&mut this, value: constant, kind: u32): constant { + val plain := this.unalias(kind); + val tkd := this.types.kind_of(plain); + return value if value.floating || (tkd != ty::signed && tkd != ty::unsigned); + val bits := this.types.first_of(plain); + var raw := value.bits(); + if bits < 64 { + raw &= (1u << bits as u64) - 1; + if tkd == ty::signed && (raw >> (bits - 1) as u64) != 0 { + raw |= ~((1u << bits as u64) - 1); + } + } + return constant::from_bits(raw, tkd == ty::signed); +} + +#! Evaluates an expression. +#! @param this The checker. +#! @param node The expression. +#! @param out Where its value is written. +#! @returns Whether it was evaluated. +def checker::ev_expr(&mut this, node: u32, out: &mut ev): bool { + return false if !this.ev_step() || node == 0; + + if this.is_known(node) { + out = this.ev_scalar(this.value_at(node)); + return true; + } + + match this.kind_of(node) { + nk::name => { + val ref := this.ref_at(node); + if (ref & ref_local) != 0 { + var held := ev {}; + if !this.ev_local(ref & ref_mask, &mut held) { + return false; + } + out = held; + return true; + } + return this.ev_global(ref, out); + } + nk::path => return this.ev_global(this.ref_at(node), out); + nk::unary => { + var operand := ev {}; + return false if !this.ev_expr(this.left_of(node), &mut operand) || operand.array; + val value := operand.scalar; + match this.token_kind(node) { + tk::minus => out = this.ev_scalar(value.floating ? constant::real_of(-value.real) : constant::integer(value.magnitude, !value.negative)); + tk::negate => out = this.ev_scalar(constant::truth(value.magnitude == 0)); + tk::bitnot => out = this.ev_scalar(constant::from_bits(~value.bits(), this.types.is_signed(this.type_at(node)))); + else => return false; + } + out.scalar = this.ev_wrap(out.scalar, this.type_at(node)); + return true; + } + nk::binary => { + val operator := this.token_kind(node); + var left := ev {}; + return false if !this.ev_expr(this.left_of(node), &mut left) || left.array; + if operator == tk::logand || operator == tk::logor { + val holds := left.scalar.magnitude != 0; + if (operator == tk::logand && !holds) || (operator == tk::logor && holds) { + out = this.ev_scalar(constant::truth(holds)); + return true; + } + } + var right := ev {}; + return false if !this.ev_expr(this.right_of(node), &mut right) || right.array; + var made := constant {}; + if !this.fold_binary(operator, &left.scalar, &right.scalar, this.types.is_signed(this.type_at(this.left_of(node))), &mut made) { + this.ev_fault("an operator overflows 64 bits, or divides by zero."); + return false; + } + out = this.ev_scalar(this.ev_wrap(made, this.type_at(node))); + return true; + } + nk::ternary => { + var condition := ev {}; + return false if !this.ev_expr(this.left_of(node), &mut condition); + return this.ev_expr(this.record(node, condition.scalar.magnitude != 0 ? if_slot::then : if_slot::other), out); + } + nk::cast => { + var value := ev {}; + return false if !this.ev_expr(this.left_of(node), &mut value) || value.array; + val target := this.unalias(this.type_at(node)); + var held := value.scalar; + if this.types.is_float(target) && !held.floating { + held = constant::real_of(held.as_real()); + } else if this.types.is_integer(target) && held.floating { + held = constant::integer((held.real < 0.0 ? -held.real : held.real) as u64, held.real < 0.0); + } + out = this.ev_scalar(this.ev_wrap(held, target)); + return true; + } + nk::array => { + val run := this.left_of(node); + var items := vector::::new(); + for &each in this.run_view(run) { + var element := ev {}; + return false if !this.ev_expr(each, &mut element) || element.array; + items.append(element.scalar); + } + this.ev_heap.extend(items.view()); + out = ev { array = true, start = this.ev_heap.length as u32 - items.length as u32, count = items.length as u32 }; + return true; + } + nk::index => { + var object := ev {}; + var at := ev {}; + return false if !this.ev_expr(this.left_of(node), &mut object) || !object.array; + return false if !this.ev_expr(this.right_of(node), &mut at) || at.array; + if at.scalar.negative || at.scalar.magnitude >= object.count as u64 { + this.ev_fault("an index is past the end of the array."); + return false; + } + out = this.ev_scalar(this.ev_heap[object.start as u64 + at.scalar.magnitude]); + return true; + } + nk::member => { + var object := ev {}; + return false if !this.ev_expr(this.left_of(node), &mut object); + if object.array && this.name_of(node) == word::length { + out = this.ev_scalar(constant::integer(object.count as u64, false)); + return true; + } + return false; + } + nk::assign => return this.ev_assign(node, out); + nk::postfix => return this.ev_step_place(node, this.left_of(node), true, out); + nk::call => return this.ev_call(node, out); + else => return false; + } + return false; +} + +#! The value of a global constant or an enum member, evaluated where checking +#! did not give it. +#! @param this The checker. +#! @param ref The declaration. +#! @param out Where its value is written. +#! @returns Whether it was evaluated. +def checker::ev_global(&mut this, ref: u32, out: &mut ev): bool { + return false if ref == 0 || (ref & (ref_local | ref_type)) != 0; + var value := constant {}; + if this.decl_value(ref, &mut value) { + out = this.ev_scalar(value); + return true; + } + if this.ev_arrays.get(&ref) is some(got) { + out = got; + return true; + } + return false; +} + +#! `x = y`, `x op= y`, and the place each writes: a local, or an element of an +#! array a local holds. +#! @param this The checker. +#! @param node The `assign` node. +#! @param out Where the value assigned is written. +#! @returns Whether it was evaluated. +def checker::ev_assign(&mut this, node: u32, out: &mut ev): bool { + val target := this.left_of(node); + val value := this.right_of(node); + var given := ev {}; + return false if !this.ev_expr(value, &mut given); + + val operator := this.token_kind(node); + if operator != tk::assign { + var current := ev {}; + return false if !this.ev_expr(target, &mut current) || current.array || given.array; + var made := constant {}; + if !this.fold_binary(operator.applied(), ¤t.scalar, &given.scalar, + this.types.is_signed(this.type_at(target)), &mut made) { + this.ev_fault("an operator overflows 64 bits, or divides by zero."); + return false; + } + given = this.ev_scalar(this.ev_wrap(made, this.type_at(target))); + } else { + given = this.ev_copy(given); + if !given.array { + given.scalar = this.ev_wrap(given.scalar, this.type_at(target)); + } + } + + return false if !this.ev_write(target, given); + out = given; + return true; +} + +#! Writes the value to a place: a local, or an element of an array a local +#! holds. +#! @param this The checker. +#! @param target The node of the place. +#! @param value The value to write. +#! @returns Whether it was written. +def checker::ev_write(&mut this, target: u32, value: ev): bool { + match this.kind_of(target) { + nk::name => { + val ref := this.ref_at(target); + return false if (ref & ref_local) == 0; + this.ev_set_local(ref & ref_mask, value); + return true; + } + nk::index => { + var object := ev {}; + var at := ev {}; + return false if !this.ev_expr(this.left_of(target), &mut object) || !object.array || value.array; + return false if !this.ev_expr(this.right_of(target), &mut at); + if at.scalar.negative || at.scalar.magnitude >= object.count as u64 { + this.ev_fault("an index is past the end of the array."); + return false; + } + this.ev_heap[object.start as u64 + at.scalar.magnitude] = value.scalar; + return true; + } + else => return false; + } + return false; +} + +#! `x++` and `x--`, which give the value from before. +#! @param this The checker. +#! @param node The operator's node. +#! @param target The node of the number changed. +#! @param after Whether the operator follows its operand, as `x++`, giving +#! the value from before. +#! @param out Where the value it gives is written. +#! @returns Whether it was evaluated. +def checker::ev_step_place(&mut this, node: u32, target: u32, after: bool, out: &mut ev): bool { + var current := ev {}; + return false if !this.ev_expr(target, &mut current) || current.array; + val one := constant::integer(1, false); + var made := constant {}; + val operator := this.token_kind(node) == tk::increment ? tk::plus : tk::minus; + return false if !this.fold_binary(operator, ¤t.scalar, &one, true, &mut made); + return false if !this.ev_write(target, this.ev_scalar(this.ev_wrap(made, this.type_at(target)))); + out = current; + return true; +} + +#! A call of a function that is not generic, with its arguments evaluated, run +#! over its checked body in a frame of its own. +#! @param this The checker. +#! @param node The `call` node. +#! @param out Where what it gives is written. +#! @returns Whether it was evaluated. +def checker::ev_call(&mut this, node: u32, out: &mut ev): bool { + val decl := this.ref_at(node); + return false if decl == 0 || (decl & (ref_local | ref_type)) != 0; + return false if this.decls.kinds.p[decl] != dk::function || this.decls.has(decl, df::generic); + return false if this.decls.has(decl, df::intrinsic) || this.decls.has(decl, df::foreign) || this.decls.has(decl, df::method); + if this.ev_depth >= checker::max_calls { + this.ev_fault("its calls nest too deeply, as one calling itself without end does."); + return false; + } + + var args := vector::::new(); + val run := this.right_of(node); + for &arg in this.run_view(run) { + var value := ev {}; + return false if !this.ev_expr(arg, &mut value); + args.append(this.ev_copy(value)); + } + + # The function's body is checked first, so its results are there to run. + this.check_decl(decl); + val saved := this.at; + this.use_table(this.units[this.decls.files.p[decl]].table); + val fnode: u32 = this.decls.nodes.p[decl]; + val params := this.record(fnode, function_slot::params); + val body := this.record(fnode, function_slot::body); + if body == 0 || this.run_length(params) != args.length as u32 { + this.at = saved; + return false; + } + + var frame := dict::::new(); + for i in 0..args.length { + frame.set(this.run_at(params, i as u32), args[i]); + } + this.ev_frames.append(move(&mut frame)); + this.ev_depth++; + this.ev_result = ev {}; + val how := this.ev_block(body); + this.ev_depth--; + this.ev_frames.truncate(); + this.at = saved; + + return false if how == eflow::fails; + out = this.ev_result; + return true; +} + +#! Runs a block or a statement. +#! @param this The checker. +#! @param node The block or statement. +#! @returns How it ended. +def checker::ev_block(&mut this, node: u32): eflow { + return eflow::goes_on if node == 0; + if this.kind_of(node) != nk::block { + return this.ev_stmt(node); + } + val run := this.left_of(node); + for &stmt in this.run_view(run) { + val how := this.ev_stmt(stmt); + return how if how != eflow::goes_on; + } + return eflow::goes_on; +} + +#! Runs a statement. +#! @param this The checker. +#! @param node The statement. +#! @returns How it ended. +def checker::ev_stmt(&mut this, node: u32): eflow { + return eflow::fails if !this.ev_step(); + match this.kind_of(node) { + nk::block => return this.ev_block(node); + nk::variable => { + val value := this.record(node, variable_slot::value); + var held := ev {}; + # `undefined` memory holds what it may, which zeroes are. + if value != 0 && this.kind_of(value) != nk::undefined { + return eflow::fails if !this.ev_expr(value, &mut held); + held = this.ev_copy(held); + if !held.array { + held.scalar = this.ev_wrap(held.scalar, this.type_at(node)); + } + } else { + held = this.ev_zero(this.type_at(node)); + } + this.ev_set_local(node, held); + return eflow::goes_on; + } + nk::expr_stmt => { + var ignored := ev {}; + return this.ev_expr(this.left_of(node), &mut ignored) ? eflow::goes_on : eflow::fails; + } + nk::if_stmt, nk::if_const => { + var condition := ev {}; + return eflow::fails if !this.ev_expr(this.left_of(node), &mut condition); + return this.ev_block(this.record(node, condition.scalar.magnitude != 0 ? if_slot::then : if_slot::other)); + } + nk::while_stmt => { + while true { + var condition := ev {}; + return eflow::fails if !this.ev_expr(this.left_of(node), &mut condition); + break if condition.scalar.magnitude == 0; + val how := this.ev_block(this.right_of(node)); + return how if how == eflow::returns || how == eflow::fails; + break if how == eflow::breaks; + } + return eflow::goes_on; + } + nk::for_stmt => return this.ev_for(node); + nk::return_stmt => { + val value := this.left_of(node); + this.ev_result = ev {}; + if value != 0 { + var held := ev {}; + return eflow::fails if !this.ev_expr(value, &mut held); + this.ev_result = this.ev_copy(held); + } + return eflow::returns; + } + nk::break_stmt => return eflow::breaks; + nk::continue_stmt => return eflow::continues; + # A contract that fails, and an `ensures`, are left to the machine, which + # says what failed. + nk::contract => { + return eflow::goes_on if this.contracts_off; + return eflow::fails if this.clause_of(node) == clause::ensures; + var condition := ev {}; + return eflow::fails if !this.ev_expr(this.left_of(node), &mut condition); + return condition.scalar.magnitude != 0 ? eflow::goes_on : eflow::fails; + } + else => return eflow::fails; + } + return eflow::fails; +} + +#! `for i in a..b` or `a..=b`, over integers or the members of an enum, and +#! `for x in a` over an array, by copy. +#! @param this The checker. +#! @param node The `for_stmt` node. +#! @returns How it ended. +def checker::ev_for(&mut this, node: u32): eflow { + val variable := this.record(node, for_slot::variable); + val iterated := this.record(node, for_slot::iterated); + val end := this.record(node, for_slot::end); + val index := this.record(node, for_slot::index); + return eflow::fails if this.node_has(node, nf::reference) || this.node_has(node, nf::constant); + + var first := ev {}; + return eflow::fails if !this.ev_expr(iterated, &mut first); + var count: u64 = 0; + var from := constant {}; + var members := vector::::new(); + var enumerated := false; + if end != 0 { + var last := ev {}; + return eflow::fails if !this.ev_expr(end, &mut last) || first.array || last.array; + from = first.scalar; + val inclusive := this.node_has(node, nf::inclusive); + val kind := this.unalias(this.type_at(variable != 0 ? variable : iterated)); + enumerated = this.named_kind(kind) == dk::enum_type; + val order := this.compare_constants(&first.scalar, &last.scalar); + if enumerated { + members = this.members_between(kind, &first.scalar, &last.scalar, inclusive); + count = members.length; + } else if order < 0 { + var span := constant {}; + this.fold_binary(tk::minus, &last.scalar, &first.scalar, true, &mut span); + count = span.magnitude; + } + # `a..=b` gives `b` too, where it gives any, the count held at the most a + # word holds, which the evaluator's steps stop long before. + if !enumerated && inclusive && order <= 0 { + count = count == 0xFFFFFFFFFFFFFFFFu ? count : count + 1; + } + } else { + return eflow::fails if !first.array; + count = first.count as u64; + } + + for i in 0..count { + if enumerated { + this.ev_set_local(variable, this.ev_scalar(members[i])); + } else if end != 0 { + var at := constant {}; + val step := constant::integer(i, false); + this.fold_binary(tk::plus, &from, &step, true, &mut at); + this.ev_set_local(variable, this.ev_scalar(at)); + } else { + this.ev_set_local(variable, this.ev_scalar(this.ev_heap[first.start as u64 + i])); + } + if index != 0 { + this.ev_set_local(index, this.ev_scalar(constant::integer(i, false))); + } + val how := this.ev_block(this.right_of(node)); + return how if how == eflow::returns || how == eflow::fails; + break if how == eflow::breaks; + } + return eflow::goes_on; +} + +#! The zero value of a type the evaluator holds. +#! @param this The checker. +#! @param kind The type. +#! @returns Its zero value. +def checker::ev_zero(&mut this, kind: u32): ev { + val plain := this.unalias(kind); + if this.types.kind_of(plain) == ty::fixed { + val start := this.ev_heap.length as u32; + val count := this.types.second_of(plain); + val element := this.types.is_float(this.unalias(this.types.first_of(plain))); + for _ in 0..count { + this.ev_heap.append(element ? constant::real_of(0.0) : constant {}); + } + return ev { array = true, start = start, count = count }; + } + return this.ev_scalar(this.types.is_float(plain) ? constant::real_of(0.0) : constant {}); +} diff --git a/analyzer/checker/expressions.sakura b/analyzer/checker/expressions.sakura new file mode 100644 index 00000000..770bd382 --- /dev/null +++ b/analyzer/checker/expressions.sakura @@ -0,0 +1,847 @@ +#! @file expressions.sakura +#! @author John Christman (sorakatadzuma@gmail.com) +#! @copyright Malunal Studios, LLC. +#! @license MIT +#! +#! Contains the checking of expressions. Each is checked once, with the type +#! expected of it where one is, which a constant, an array, or an anonymous +#! function takes its type from, and is then converted to that type. What an +#! expression is checked as is passed down rather than kept on the checker, +#! so nothing has to put it back. + +module sakura::analyzer; + + +#! Checks the expression, converting it to the type expected, where one is. +#! @param this The checker. +#! @param node The expression. +#! @param expected The type expected, or the error type where none is. +#! @returns The type it is used as: the type expected, or its own where none is. +pub def checker::check_expr(&mut this, node: u32, expected: u32): u32 { + return bt::error if node == 0; + + val own := this.has_flag(node, rf::checked) + ? this.type_at(node) + : this.expr(node, expected); + return own if expected == bt::error; + return this.convert(node, expected) ? expected : bt::error; +} + +#! Checks the expression where nothing is expected of it. +#! @param this The checker. +#! @param node The expression. +#! @returns Its own type, which may be a constant's. +pub def checker::infer_expr(&mut this, node: u32): u32 { + return bt::error if node == 0; + return this.type_at(node) if this.has_flag(node, rf::checked); + return this.expr(node, bt::error); +} + +#! Checks the expression with a type in mind, which gives what it leaves open +#! but is not what it is converted to, as the right of `+=` is checked before +#! what `+` takes there is known. +#! @param this The checker. +#! @param node The expression. +#! @param expected The type in mind. +#! @returns Its own type, which may be a constant's. +pub def checker::hinted_expr(&mut this, node: u32, expected: u32): u32 { + return bt::error if node == 0; + return this.type_at(node) if this.has_flag(node, rf::checked); + return this.expr(node, expected); +} + +#! Checks the expression as a condition, which is a `bool`. +#! @param this The checker. +#! @param node The expression. +pub def checker::check_condition(&mut this, node: u32): void { + this.check_expr(node, bt::boolean); +} + +#! Checks the expression, recording and giving its own type. +#! @param this The checker. +#! @param node The expression. +#! @param expected The type expected, or the error type where none is. +#! @returns Its own type, or the error type where it is not valid. +def checker::expr(&mut this, node: u32, expected: u32): u32 { + this.set_flag(node, rf::checked); + val kind := this.expr_kind(node, expected); + this.set_type(node, kind); + return kind; +} + +def checker::expr_kind(&mut this, node: u32, expected: u32): u32 { + match this.kind_of(node) { + nk::number => return this.number(node); + nk::character => { + this.set_value(node, constant::integer(this.read_character(this.text_of(node)), false)); + return bt::untyped_char; + } + nk::string => return bt::untyped_text; + nk::istring => return this.interpolated(node); + nk::boolean => { + this.set_value(node, constant::truth(this.token_kind(node) == tk::kw_true)); + return bt::untyped_bool; + } + nk::null_lit => return bt::null_type; + nk::name => return this.name_value(node, expected); + nk::path => return this.path_value(node, expected); + nk::unary => return this.unary(node, expected); + nk::postfix => return this.step(node, this.left_of(node)); + nk::reference => return this.reference(node, expected); + nk::binary => return this.binary(node, expected); + nk::assign => return this.assign(node); + nk::ternary => return this.ternary(node, expected); + nk::fallback => return this.fallback(node, expected); + nk::call => return this.call(node, expected); + nk::index => return this.index(node); + nk::slice => return this.slice(node); + nk::member => return this.member(node); + nk::member_of => return this.member_of(node); + nk::type_args => return this.type_args_value(node); + nk::cast => return this.cast(node); + nk::is_test => return this.is_test(node); + nk::construct => return this.construct(node, expected); + nk::array => return this.array(node, expected); + nk::lambda => return this.lambda(node, expected); + nk::match_value => return this.match_value(node, expected); + nk::range => return this.range_value(node, expected); + nk::old_value => return this.old_value(node); + nk::undefined => { + this.report(node, ec::invalid, "`undefined` is only a local `var`'s value, which leaves its memory as it is."); + return bt::error; + } + nk::error => return bt::error; + else => { + this.unsupported(node); + return bt::error; + } + } + return bt::error; +} + +#! Marks the node a place, which can be written where `writable` says. +#! @param this The checker. +#! @param node The node. +#! @param writable Whether the place can be written. +pub def checker::mark_place(&mut this, node: u32, writable: bool): void { + this.set_flag(node, rf::place); + if writable { + this.set_flag(node, rf::writable); + } +} + +#! Whether a node is a place: a variable, parameter, field, element, or what a +#! reference or pointer reaches. +#! @param this The checker. +#! @param node The node. +#! @returns Whether it is. +pub def checker::is_place(&this, node: u32): bool { return this.has_flag(node, rf::place); } + +#! Whether a node is a place that can be written. +#! @param this The checker. +#! @param node The node. +#! @returns Whether it is. +pub def checker::is_writable(&this, node: u32): bool { return this.has_flag(node, rf::writable); } + +#! A number literal: an integer, an integer written with `u`, or a float. +#! @param this The checker. +#! @param node The `number` node. +#! @returns The constant's type: an untyped integer, unsigned integer, or float. +def checker::number(&mut this, node: u32): u32 { + val text := this.text_of(node); + if this.token_kind(node) == tk::float { + this.set_value(node, constant::real_of(this.read_real(text))); + return text[text.length - 1] == 'f' ? bt::untyped_float32 : bt::untyped_float; + } + + var value := constant {}; + if !this.read_integer(text, &mut value) { + this.report(node, ec::overflow, "Integer constants fit in 64 bits."); + return bt::error; + } + this.set_value(node, value); + return this.token_kind(node) == tk::unsigned ? bt::untyped_uint : bt::untyped_int; +} + +#! An interpolated string, whose holes may hold anything, which builds a +#! `string`. +#! @param this The checker. +#! @param node The `istring` node. +#! @returns The `string` type. +def checker::interpolated(&mut this, node: u32): u32 { + val run := this.left_of(node); + for &piece in this.run_view(run) { + continue if this.kind_of(piece) == nk::string; + this.settle_expr(piece); + } + return this.std_type(word::string, span::::empty()); +} + +#! Checks the expression where nothing is expected of it, then settles a +#! constant to its default type. +#! @param this The checker. +#! @param node The expression. +#! @returns The type it settles as. +pub def checker::settle_expr(&mut this, node: u32): u32 { + val own := this.infer_expr(node); + var settled := this.settle(own); + # An integer constant past what an `i64` holds is a `u64`, as `1 << 63` is. + if this.types.kind_of(own) == ty::untyped_int && this.is_known(node) { + val held := this.value_at(node); + if !held.floating && !held.negative && held.magnitude > 0x7FFFFFFFFFFFFFFF { + settled = bt::uint64; + } + } + if settled != own && settled != bt::error { + this.set_convert(node, settled); + } + return settled; +} + +#! A name written as a value: a local, or a declaration. +#! @param this The checker. +#! @param node The `name` node. +#! @param expected The type expected, or the error type where none is. +#! @returns Its type, or the error type where it names nothing. +def checker::name_value(&mut this, node: u32, expected: u32): u32 { + val name := this.name_of(node); + val bound := this.bound(name); + val found := bound != 0 ? checker::found { decl = bound } : this.lookup_named(name, node, false); + if found.decl == 0 { + this.report_undeclared(node, name); + return bt::error; + } + return this.scoped_value(node, found, expected) if found.owner != 0; + return this.ref_value(node, found.decl, expected); +} + +#! The value of what a type around a name gives it, as though it were named +#! through the type, as `zero` within `vec2` is `vec2::zero`. +#! @param this The checker. +#! @param node The `name` node. +#! @param found The member and the type giving it. +#! @param expected The type expected, or the error type where none is. +#! @returns Its type. +def checker::scoped_value(&mut this, node: u32, found: checker::found, expected: u32): u32 { + val made := this.decl_value_of(node, found.decl, expected); + # A member of a generic enum is of the enum given its arguments. + val owner := found.owner; + if this.decls.kinds.p[found.decl] == dk::enum_member && made != bt::error + && this.types.kind_of(owner) == ty::named && this.types.part_count(owner) != 0 + && this.types.first_of(owner) == this.decls.owners.p[found.decl] { + return owner; + } + return made; +} + +#! The value of what a name refers to. +#! @param this The checker. +#! @param node The node naming it. +#! @param ref What it refers to: a local, with `ref_local`, or a +#! declaration. +#! @param expected The type expected, or the error type where none is. +#! @returns Its type. +def checker::ref_value(&mut this, node: u32, ref: u32, expected: u32): u32 { + this.set_ref(node, ref); + if (ref & ref_local) != 0 { + val local := ref & ref_mask; + this.mark_place(node, this.has_flag(local, rf::mutable)); + if this.is_known(local) { + this.set_value(node, this.value_at(local)); + } + val described := this.reflected_at(local); + if described != checker::no_reflection { + this.reflections.set(this.result_key(node), described); + this.set_flag(node, rf::reflected); + } + return this.type_at(local); + } + + if (ref & ref_type) != 0 { + val kind := ref & ref_mask; + return this.constant_ref(node, kind) if this.is_constant_arg(kind); + this.report(node, ec::not_value, "A type is not a value."); + return bt::error; + } + return this.decl_value_of(node, ref, expected); +} + +#! The value of a declaration named as one: a function, a variable, an enum +#! member, or a property, whose value is its `get`. +#! @param this The checker. +#! @param node The node naming it. +#! @param decl The declaration. +#! @param expected The type expected, or the error type where none is. +#! @returns Its type, or the error type where it is no value. +pub def checker::decl_value_of(&mut this, node: u32, decl: u32, expected: u32): u32 { + # A property named as a value is its `get`, a function of `&this`, as + # `rect::area` is a `def(&rect): f32`. + if this.decls.kinds.p[decl] == dk::property { + val getter := this.property_getter(decl); + return this.decl_value_of(node, getter, expected) if getter != 0; + } + if !this.visible(decl) && decl != this.consent { + this.report_hidden(node, decl); + } + + this.set_ref(node, decl); + match this.decls.kinds.p[decl] { + dk::function => { + # A generic function named as a value is the instance the function type + # expected of it gives the type arguments of, as is a method of a generic + # type named without them, as `result::is_ok` given for a + # `def(&result): bool`. + if this.decls.overloads.p[decl] == 0 && decl != this.consent { + this.resolve(decl); + if this.decls.has(decl, df::generic) && (this.own_param_count(decl) != 0 || this.decls.owners.p[decl] != 0) { + val made := this.function_instance(node, decl, expected, bt::error); + return made if made != bt::error; + } + } + # Where C's address of a function is expected, the function is chosen by + # the type C calls it with. + val plain_expected := this.unalias(expected); + val c_expected := this.is_std(plain_expected, word::cfn) && this.types.part_count(plain_expected) == 1 + ? this.types.part_at(plain_expected, 0) + : 0; + val chosen := this.function_value(node, decl, c_expected != 0 ? c_expected : expected); + this.set_ref(node, chosen); + return bt::error if chosen == 0; + # An overload of a generic type's member is the instance chosen. + if chosen != decl || this.decls.overloads.p[decl] != 0 { + if this.decls.has(chosen, df::generic) && this.own_param_count(chosen) == 0 && this.decls.owners.p[chosen] != 0 { + val made := this.function_instance(node, chosen, expected, bt::error); + return made if made != bt::error; + } + } + # A C function is taken as its address, which is what C calls, and a + # function of the program given where C's address is expected gets an + # entry C calls it back through. + val c_given := this.decls.has(chosen, df::foreign); + if (c_given || c_expected != 0) && this.std_decl(word::cfn) != 0 { + if !c_given { + this.check_callback(node, chosen); + this.decls.mark(chosen, df::callback); + } + var parts: u32[1] = [this.decls.types.p[chosen]]; + return this.types.named(this.std_decl(word::cfn), parts[:]); + } + return this.decls.types.p[chosen]; + } + dk::variable => { + this.resolve(decl); + val writes := this.decls.has(decl, df::mutable) && !this.decls.has(decl, df::constant); + this.mark_place(node, writes); + var value := constant {}; + if this.decl_value(decl, &mut value) { + this.set_value(node, value); + } + return this.decls.types.p[decl]; + } + dk::enum_member => { + this.resolve(decl); + var value := constant {}; + if this.decl_value(decl, &mut value) { + this.set_value(node, value); + } + return this.decls.types.p[decl]; + } + dk::attribute => return this.decls.types.p[decl]; + else => { + var text := string::from("`", nothing {}); + text.append(this.decl_text(decl)); + val word := this.decl_word(decl); + text.append(word[0] == 'e' ? "` is an " : "` is a "); + text.append(word); + text.append(", not a value."); + this.report_text(node, ec::not_value, &text); + return bt::error; + } + } + return bt::error; +} + +#! The type of the instance of a generic function the function type expected of +#! it gives the type arguments of, as `val f: def(i64): i64 = id;` makes +#! `id`, or the error type where it gives them not all. +#! @param this The checker. +#! @param node The node naming it. +#! @param decl The generic function. +#! @param expected The type expected, or the error type where none is. +#! @param owner The type it is a member of, given its arguments, which are +#! its first, or the error type. +#! @returns The instance's function type, or the error type. +def checker::function_instance(&mut this, node: u32, decl: u32, expected: u32, owner: u32): u32 { + var inferred := this.begin_inference(decl, owner, span::::empty()); + val made := this.instance_type(decl, expected, &mut inferred); + return bt::error if made == bt::error; + val instance := this.instance_of(decl, inferred.binds.view(), node); + if instance != 0 { + this.called.set(this.result_key(node), instance); + } + return made; +} + +#! The function type of the instance of a generic function the function type +#! expected of it gives the type arguments of, without making the instance, or +#! the error type. Its parameters are given those of the type expected, as many +#! as it has, so those it leaves to their defaults give nothing. +#! @param this The checker. +#! @param decl The generic function. +#! @param expected The type expected. +#! @param inferred What is inferred, which this adds to. +#! @returns The instance's function type, or the error type. +def checker::instance_type(&mut this, decl: u32, expected: u32, inferred: &mut checker::inferred): u32 { + val wanted := this.unalias(expected); + return bt::error if this.types.kind_of(wanted) != ty::function; + val kind: u32 = this.decls.types.p[decl]; + val count := this.types.part_count(kind) < this.types.part_count(wanted) + ? this.types.part_count(kind) : this.types.part_count(wanted); + for i in 0..count { + this.unify(this.types.part_at(kind, i as u32), this.types.part_at(wanted, i as u32), inferred, 0); + } + # A result the call around it is still inferring, as `U` of `map`'s, is what + # the function gives once its parameters' types give its arguments. + if !this.free_result { + this.unify(this.types.first_of(kind), this.types.first_of(wanted), inferred, 0); + } + return bt::error if this.unbound(inferred) != 0; + return this.apply(kind, inferred); +} + +#! The overload a function named as a value is: the only one, or the one whose +#! type is the function type expected. +#! @param this The checker. +#! @param node The node naming it. +#! @param first The first of its overloads. +#! @param expected The type expected, or the error type where none is. +#! @returns The overload's function type, or the error type where none is +#! chosen. +def checker::function_value(&mut this, node: u32, first: u32, expected: u32): u32 { + if this.decls.overloads.p[first] == 0 { + this.resolve(first); + if this.decls.has(first, df::generic) && this.own_param_count(first) != 0 { + # A generic function is a value once given its type arguments, which + # reflection, reaching it as it is, reports in its own words. + if first != this.consent { + this.report(node, ec::generic, "A generic function is a value once given its type arguments, as `max::`."); + } + return 0; + } + return first; + } + + var walk := this.decls.walk_overloads(first); + while true { + val at := walk.next(); + break if at == 0; + this.resolve(at); + return at if this.decls.types.p[at] == expected; + } + + # Where none is of that type, the one a call with its parameters would choose + # is, called as the type asks: a member of a generic type as the instance the + # type gives its arguments. + if this.types.kind_of(this.unalias(expected)) == ty::function { + var best: u32 = 0; + var least: i32 = -1; + var tied := false; + var each := this.decls.walk_overloads(first); + while true { + val at := each.next(); + break if at == 0; + continue if this.decls.has(at, df::generic) && this.own_param_count(at) != 0; + var kind: u32 = this.decls.types.p[at]; + if this.decls.has(at, df::generic) { + var inferred := this.begin_inference(at, bt::error, span::::empty()); + kind = this.instance_type(at, expected, &mut inferred); + continue if kind == bt::error; + if kind == expected { + return at; + } + } + val cost := this.adapt_cost(at, kind, expected); + continue if cost < 0; + if least < 0 || cost < least { + best = at; + least = cost; + tied = false; + } else if cost == least { + tied = true; + } + } + return best if best != 0 && !tied; + } + + this.report(node, ec::ambiguous, "The function is overloaded, so it is a value only where the type of one of them is expected, or one a call as that type asks chooses."); + return 0; +} + +#! What a path names: a module, a type, or a declaration, in order of its +#! segments. +pub struct checker::named { + var decl: u32; #! The declaration named, or 0. + var kind: u32; #! The type named, where it names one. + pub var owner: u32; #! The type a member is of, as `box` of `box::::new`. +} + +#! What the segments of a path, from the first, name. A local or parameter +#! never hides a type or module there. +#! @param this The checker. +#! @param node The `path` or `type_name` node. +#! @returns The declaration or type named, and the type a member is of. +pub def checker::path_target(&mut this, node: u32): checker::named { + var made := checker::named {}; + var home: u32 = 0; + var in_module := false; + # A generic type named without type arguments before a function lets the call + # infer them, as `box::new(5)` does. + var open := false; + val count := this.segment_count(node); + for i in 0..count { + val name := this.segment_name(node, i as u32); + val segment := this.segment_node(node, i as u32); + if i == 0 { + val bound := this.bound(name); + if (bound & ref_type) != 0 { + made.kind = bound & ref_mask; + made.decl = this.type_decl(made.kind); + if segment != node { + this.set_ref(segment, bound); + } + continue; + } + + # A module the first of several segments names comes before a declaration of + # the name, as `serial::encode` names the module where `serial` is also the + # attribute it declares. + if count > 1 { + home = this.lookup_module(name); + if home != 0 { + in_module = true; + continue; + } + } + # What a type around it gives is reached through that type, as `kind::word` + # within `token` is `token::kind::word`. + val found := this.lookup_named(name, segment, count > 1); + made.decl = found.decl; + if found.owner != 0 { + made.owner = found.owner; + } + if made.decl == 0 { + home = this.lookup_module(name); + in_module = home != 0; + if !in_module { + this.report_undeclared(segment, name); + return checker::named {}; + } + continue; + } + } else if in_module { + made.decl = this.modules.decl(home, name); + if made.decl == 0 { + home = this.modules.find(home, name); + if home == 0 { + var text := string::from("The module declares no `", nothing {}); + text.append(this.names.text(name)); + text.append("`."); + this.report_text(segment, ec::undefined, &text); + return checker::named {}; + } + continue; + } + in_module = false; + } else { + # A type a bound asks of a type parameter given a type, as `F::result` where + # `F: signature` is given a function type, is the one the type gives. + if i == 1 && made.kind != bt::error { + val param := this.param_named(this.segment_name(node, 0)); + val asked := param != 0 ? this.asked_of_bounds(made.kind, param, name) : bt::error; + if asked != bt::error { + made.kind = asked; + made.decl = this.type_decl(asked); + continue; + } + } + + val owner := made.decl; + if !this.is_type_decl(owner) { + this.report(segment, ec::member, "Only a module or a type has members named with `::`."); + return checker::named {}; + } + + made.owner = made.kind != bt::error ? made.kind : this.decls.types.p[owner]; + val found := this.find_path_member(made.owner, name); + # A trait's static methods and constants belong to the types implementing + # it, which the trait's own name does not say. + if found.decl != 0 && this.trait_asks(found.decl) && this.named_kind(this.unalias(made.owner)) == dk::trait_type { + val kind_of: dk = this.decls.kinds.p[found.decl]; + if kind_of == dk::variable || (kind_of == dk::function && !this.decls.has(found.decl, df::method)) { + this.report(segment, ec::invalid, kind_of == dk::variable + ? "A constant of a trait belongs to the types implementing it, so read it through a type parameter the trait bounds, as `T::name`." + : "A static method of a trait belongs to the types implementing it, so call it through a type parameter the trait bounds, as `T::name()`."); + return checker::named {}; + } + } + made.decl = found.decl; + if found.decl != 0 && this.types.kind_of(found.owner) == ty::named + && this.decls.kinds.p[this.types.first_of(found.owner)] != dk::trait_type { + made.owner = found.owner; + } + made.kind = bt::error; + if open && made.decl != 0 && (this.decls.kinds.p[made.decl] == dk::function || this.decls.kinds.p[made.decl] == dk::property) { + made.owner = bt::error; + } + if made.decl == 0 { + var text := string::from("`", nothing {}); + val owner_text := this.describe(made.owner); + text.append(owner_text.view()); + text.append("` has no member `"); + text.append(this.names.text(name)); + text.append("`."); + this.report_text(segment, ec::member, &text); + return checker::named {}; + } + } + + if !this.visible(made.decl) { + this.report_hidden(segment, made.decl); + } + # What each segment names is kept for the editor, which shows it and finds + # where it is declared. + if segment != node { + this.set_ref(segment, made.decl); + } + + # A type named along the path takes the type arguments its segment gives. + if this.is_type_decl(made.decl) && i + 1 < count { + var args := vector::::new(); + if made.owner != bt::error && this.types.kind_of(made.owner) == ty::named { + args.extend(this.types.parts_view(made.owner)); + } + val run := this.segment_args(node, i as u32); + for &arg in this.run_view(run) { + args.append(this.type_arg_of(arg, made.decl, args.length as u32, args.view())); + } + open = this.decls.kinds.p[made.decl] != dk::builtin && args.length == 0 && this.decls.params.p[made.decl] != 0 + && this.at.decl != made.decl; + made.kind = this.decls.kinds.p[made.decl] == dk::builtin || args.length != 0 || this.decls.params.p[made.decl] == 0 + ? this.named_of(made.decl, args.view(), segment) + : this.decls.types.p[made.decl]; + } + } + + if in_module { + this.report(node, ec::not_value, "A module is not a value."); + return checker::named {}; + } + return made; +} + +#! A path written as a value, as `color::red` or `vec2::zero`. +#! @param this The checker. +#! @param node The `path` node. +#! @param expected The type expected, or the error type where none is. +#! @returns Its type, or the error type where it names nothing. +def checker::path_value(&mut this, node: u32, expected: u32): u32 { + val target := this.path_target(node); + return bt::error if target.decl == 0; + + # A generic function given its type arguments, as `max::`, is the + # instance they make. + if this.decls.kinds.p[target.decl] == dk::function && this.decls.overloads.p[target.decl] == 0 { + this.resolve(target.decl); + val written := this.segment_args(node, this.segment_count(node) - 1); + if written != 0 && this.decls.has(target.decl, df::generic) && this.own_param_count(target.decl) != 0 { + # A method of a generic type takes the type's arguments before its own, as + # `pair::::make::` does. + var args := vector::::new(); + if target.owner != bt::error && this.types.kind_of(target.owner) == ty::named { + args.extend(this.types.parts_view(target.owner)); + } + args.extend(this.written_args(target.decl, target.owner, written).view()); + val instance := this.instance_of(target.decl, args.view(), node); + if instance != 0 { + this.set_ref(node, target.decl); + this.called.set(this.result_key(node), instance); + return this.instances[instance - 1].kind; + } + # Within a generic, type arguments naming its own parameters make an + # instance only once it is compiled for its own arguments. + var from := this.decls.list_of(this.decls.params.p[target.decl]); + if this.any_open(args.view()) && args.length == from.length { + this.set_ref(node, target.decl); + return this.substitute(this.decls.types.p[target.decl], from.view(), args.view()); + } + } + } + + # A property of a type given its arguments is its `get`, as a method is. + var member := target.decl; + if this.decls.kinds.p[member] == dk::property && target.owner != bt::error { + member = this.property_getter(member); + if member != 0 && !this.visible(member) { + this.report_hidden(node, member); + } + } + if member != 0 && this.decls.kinds.p[member] == dk::function && target.owner != bt::error { + this.set_ref(node, member); + this.resolve(member); + # A generic function of a type, named without its own type arguments, as + # `integer::parse`, is the instance the function type expected gives them. + if this.decls.overloads.p[member] == 0 && this.own_param_count(member) != 0 { + val made := this.function_instance(node, member, expected, target.owner); + return made if made != bt::error; + this.report(node, ec::generic, + "A generic function is a value once given its type arguments, and the function type expected doesn't give them all: write them, as `max::`."); + return bt::error; + } + return this.member_function_type(member, target.owner); + } + val made := this.decl_value_of(node, target.decl, expected); + # A member of a generic enum is of the enum given the arguments its path + # gives, as `bag::::state::full` is a `bag::state`. + if this.decls.kinds.p[target.decl] == dk::enum_member && made != bt::error + && this.types.kind_of(target.owner) == ty::named && this.types.part_count(target.owner) != 0 + && this.types.first_of(target.owner) == this.decls.owners.p[target.decl] { + return target.owner; + } + return made; +} + +#! The type of a function declared through a type, given the type's arguments. +#! @param this The checker. +#! @param decl The function's declaration. +#! @param owner The type, given its arguments. +#! @returns The function's type. +pub def checker::member_function_type(&mut this, decl: u32, owner: u32): u32 { + this.resolve(decl); + val kind: u32 = this.decls.types.p[decl]; + return kind if this.types.kind_of(owner) != ty::named || this.types.part_count(owner) == 0; + + var from := vector::::new(); + val run: u32 = this.decls.params.p[decl]; + val count := this.types.part_count(owner); + for i in 0..count { + break if i >= this.decls.list_length(run); + from.append(this.decls.list_at(run, i as u32)); + } + val args := this.types.parts_of(owner); + return this.substitute(kind, from.view(), args.view()); +} + +#! A value given type arguments after it, as `value_of(d)::`: the instance +#! of the generic function a description names that they make. +#! @param this The checker. +#! @param node The `type_args` node. +#! @returns The instance's function type, or the error type. +def checker::type_args_value(&mut this, node: u32): u32 { + val callee := this.left_of(node); + var decl: u32 = 0; + if this.kind_of(callee) == nk::call && this.kind_of(this.left_of(callee)) == nk::name { + val named := this.lookup(this.name_of(this.left_of(callee)), this.left_of(callee)); + val run := this.right_of(callee); + if named != 0 && (named & (ref_local | ref_type)) == 0 && this.decls.kinds.p[named] == dk::function + && this.is_reflection(named) && this.names.text(this.decls.names.p[named]) == "value_of" + && this.run_length(run) == 1 { + val arg := this.run_at(run, 0); + this.infer_expr(arg); + val one := this.described_arg(arg, "`value_of`"); + return bt::error if one == checker::no_reflection; + val held: desc = this.descs[one]; + decl = held.param == 0 ? held.decl : 0; + } + } + if decl == 0 || this.decls.kinds.p[decl] != dk::function || this.decls.overloads.p[decl] != 0 { + this.report(node, ec::generic, "Type arguments are given after a value only to `value_of` of a generic function, as `value_of(d)::`."); + return bt::error; + } + + this.resolve(decl); + if !this.decls.has(decl, df::generic) || this.own_param_count(decl) == 0 { + this.report(node, ec::generic, "The function takes no type arguments."); + return bt::error; + } + var args := this.written_args(decl, bt::error, this.right_of(node)); + val instance := this.instance_of(decl, args.view(), node); + return bt::error if instance == 0; + this.set_ref(node, decl); + this.called.set(this.result_key(node), instance); + return this.instances[instance - 1].kind; +} + +#! `x.(d)`, the member of `x` a description known while compiling describes, as +#! though its name were written there: a field, or a property. A method it +#! names is called, which the call checks. +#! @param this The checker. +#! @param node The `member_of` node. +#! @returns The member's type, or the error type. +def checker::member_of(&mut this, node: u32): u32 { + val object := this.left_of(node); + val kind := this.infer_expr(object); + val found := this.described_member(node, kind); + return bt::error if found.decl == 0; + + this.set_ref(node, found.decl); + this.resolve(found.decl); + match this.decls.kinds.p[found.decl] { + dk::field => { + this.mark_place(node, this.reaches_writable(kind, object) && this.decls.has(found.decl, df::mutable)); + return this.instantiated(this.decls.types.p[found.decl], this.types.first_of(found.owner), found.owner); + } + dk::property => { + val property: u32 = this.decls.types.p[found.decl]; + val held := this.types.kind_of(found.owner) == ty::named + ? this.instantiated(property, found.decl, found.owner) + : property; + if this.property_setter(found.decl) != 0 && this.reaches_writable(kind, object) { + this.set_flag(node, rf::writable); + } + this.want_accessor(this.property_getter(found.decl), found.owner, node); + return held; + } + dk::function => { + this.report(node, ec::not_value, "A method is called, as `x.(d)()`; take it through its type for its value."); + return bt::error; + } + else => { + this.unsupported(node); + return bt::error; + } + } + return bt::error; +} + +#! The member of a value that `x.(d)` names: the declaration `d` describes, +#! where it is a member of the value's type. +#! @param this The checker. +#! @param node The `member_of` node. +#! @param kind The type of the value. +#! @returns The member and the type it is of, or no member where it names none. +def checker::described_member(&mut this, node: u32, kind: u32): checker::found { + val named := this.right_of(node); + this.infer_expr(named); + return checker::found {} if kind == bt::error || this.type_at(named) == bt::error; + val one := this.reflected_one(named); + if one == checker::no_reflection { + if !this.waits_for_instance() { + this.report(named, ec::constant, "A member written `x.(d)` takes a declaration known while compiling, as the variable of `for const d in declarations()` is."); + } + return checker::found {}; + } + + # Any overload of the name is the member it names. + val held: desc = this.descs[one]; + val found := held.param != 0 ? checker::found {} : this.find_member(this.reached(kind), this.decls.names.p[held.decl]); + var walk := this.decls.walk_overloads(found.decl); + var at := walk.next(); + while at != 0 && at != held.decl { + at = this.decls.kinds.p[at] == dk::function ? walk.next() : 0; + } + if at == 0 { + this.report(node, ec::member, "`x.(d)` names a member of `x`, and `d` describes none of it."); + return checker::found {}; + } + return checker::found { decl = held.decl, owner = found.owner }; +} diff --git a/analyzer/checker/generics.sakura b/analyzer/checker/generics.sakura new file mode 100644 index 00000000..c2e6acde --- /dev/null +++ b/analyzer/checker/generics.sakura @@ -0,0 +1,738 @@ +#! @file generics.sakura +#! @author John Christman (sorakatadzuma@gmail.com) +#! @copyright Malunal Studios, LLC. +#! @license MIT +#! +#! Contains generics: inferring the type arguments of a call from what it is +#! given, and the instances of generic functions. A generic's body is checked +#! once against its bounds, then again for each instance the program uses, +#! over the template's own nodes with a result table of the instance's, so the +#! template is never copied. An instance is made where a call gives a generic +#! types holding no type parameter, and its body is checked once every +#! declaration has been. + +module sakura::analyzer; + + +#! What inferring type arguments works out: the type of each parameter of the +#! declaration, its owner's first, and whether each was only suggested by a +#! constant, which a typed value given for it overrules. +pub struct checker::inferred { + var params: vector; #! The declarations of the type parameters. + var binds: vector; #! The type of each, or `unknown_type` where nothing gave it yet. + var soft: vector; #! Whether each was only suggested by a constant. + var outer: vector; #! The parameters a trait's default names beside its own: the trait's, and `self`. + var given: vector; #! The type each of those is given by the value it is called on. +} + +#! Begins inferring the declaration's type arguments, with those of its owner +#! and those written given. +#! @param this The checker. +#! @param decl The generic declaration. +#! @param owner The type it is a member of, given its arguments, or the +#! error type. +#! @param written The type arguments written for its own parameters. +#! @returns What is known so far. +pub def checker::begin_inference(&mut this, decl: u32, owner: u32, written: span): checker::inferred { + var made := checker::inferred { + params = vector::::new(), + binds = vector::::new(), + soft = vector::::new(), + outer = vector::::new(), + given = vector::::new() + }; + + val params := this.decls.list_view(this.decls.params.p[decl]); + made.params.extend(params); + made.binds.resize(params.length, checker::unknown_type); + made.soft.resize(params.length, false); + + var at: u64 = 0; + if owner != bt::error && this.types.kind_of(owner) == ty::named { + for &part in this.types.parts_view(owner) { + break if at >= made.binds.length; + made.binds[at] = part; + at++; + } + } + # Written type arguments fill a pack with whatever the parameters before it + # leave, as `show_all::`. + for i in 0..written.length { + break if at >= made.binds.length; + val param := made.params[at]; + if this.decls.has(param, df::packed) { + made.binds[at] = this.gather_pack(written, i, 0); + break; + } + made.binds[at] = written[i]; + at++; + } + return made; +} + +#! Binds a pack parameter to the types of the arguments a call gives it from +#! `from` on, each spread pack already its own types. +#! @param this The checker. +#! @param pack The pack parameter's type. +#! @param slots The types of the call's arguments. +#! @param from The first argument the pack takes. +#! @param into What is inferred, which the pack's types are written to. +pub def checker::bind_pack(&mut this, pack: u32, slots: span, from: u64, into: &mut checker::inferred): void { + var types := vector::::new(); + for i in from..slots.length { + types.append(slots[i] == 0 ? bt::error : this.settle(slots[i])); + } + + val decl := this.types.first_of(pack); + for i in 0..into.params.length { + if into.params[i] == decl && (into.binds[i] == checker::unknown_type || into.soft[i]) { + into.binds[i] = this.types.pack(types.view(), 0); + into.soft[i] = false; + } + } +} + +#! Infers type parameters a type holds from the type given where it is +#! expected, as `T` of `&T` from a `&i64`. +#! @param this The checker. +#! @param pattern The type written, holding the parameters. +#! @param actual The type given. +#! @param into What is inferred. +#! @param depth How deeply the search has gone, which stops a type nesting +#! without end. +pub def checker::unify(&mut this, pattern: u32, actual: u32, into: &mut checker::inferred, depth: u32): void { + return if depth > 16 || !this.types.is_open(pattern) || actual == bt::error; + + # A reference is read through to what it refers to wherever a type that is no + # reference is wanted, so `through(r)` takes the pointer `r` refers to. + val shape := this.types.kind_of(pattern); + if shape != ty::param && shape != ty::pack && shape != ty::reference { + actual = this.reached(actual); + } + + match shape { + ty::param => { + val decl := this.types.first_of(pattern); + # A constant parameter is given a constant, and a type parameter a type. + val given := this.types.kind_of(actual); + val constant := given == ty::value || (given == ty::param && this.decls.has(this.types.first_of(actual), df::valued)); + return if this.decls.has(decl, df::valued) != constant; + for i in 0..into.params.length { + continue if into.params[i] != decl; + + if this.types.is_untyped(actual) { + if into.binds[i] == checker::unknown_type { + into.binds[i] = this.settle(actual); + into.soft[i] = true; + } else if into.soft[i] && this.types.is_float(actual) && !this.types.is_float(into.binds[i]) { + # An integer constant and a float constant share the float. + into.binds[i] = this.settle(actual); + } + return; + } + if into.binds[i] == checker::unknown_type || into.soft[i] { + into.binds[i] = actual; + into.soft[i] = false; + } + return; + } + } + ty::reference, ty::pointer => { + val plain := this.unalias(actual); + if this.types.kind_of(plain) == this.types.kind_of(pattern) { + this.unify(this.types.first_of(pattern), this.types.first_of(plain), into, depth + 1); + } else if this.types.kind_of(pattern) == ty::reference { + this.unify(this.types.first_of(pattern), actual, into, depth + 1); + } + } + ty::fixed => { + val plain := this.unalias(this.reached_value(actual)); + if this.types.kind_of(plain) == ty::fixed { + this.unify(this.types.first_of(pattern), this.types.first_of(plain), into, depth + 1); + # A length that is a constant parameter is given the length of the array. + if this.types.part_count(pattern) != 0 { + val length := this.types.part_at(pattern, 0); + if this.types.part_count(plain) != 0 { + this.unify(length, this.types.part_at(plain, 0), into, depth + 1); + } else if this.types.kind_of(length) == ty::param && this.decls.has(this.types.first_of(length), df::valued) { + val of := this.constant_type(length); + val tkd := this.types.kind_of(this.unalias(of)); + if tkd == ty::signed || tkd == ty::unsigned { + val count := this.known_number(constant::integer(this.types.second_of(plain) as u64, false), of); + this.unify(length, this.known_type(count), into, depth + 1); + } + } + } + } + } + ty::function => { + val plain := this.unalias(actual); + return if this.types.kind_of(plain) != ty::function; + # A pack among the parameters, as `Ts` of `def(Ts...): R`, takes the types of + # those after the ones before it, and is variadic where the function is. + val count := this.types.part_count(pattern); + val given := this.types.part_count(plain); + if this.types.second_of(pattern) != 0 && count != 0 && this.types.is_open_pack(this.types.part_at(pattern, count - 1)) { + return if given + 1 < count; + for i in 0..count - 1 { + this.unify(this.types.part_at(pattern, i as u32), this.types.part_at(plain, i as u32), into, depth + 1); + } + this.bind_param(this.types.first_of(this.types.part_at(pattern, count - 1)), this.types.params_pack(plain, count - 1), into); + this.unify(this.types.first_of(pattern), this.types.first_of(plain), into, depth + 1); + return; + } + if given == count { + for i in 0..count { + this.unify(this.types.part_at(pattern, i as u32), this.types.part_at(plain, i as u32), into, depth + 1); + } + this.unify(this.types.first_of(pattern), this.types.first_of(plain), into, depth + 1); + } + } + # A pack whose types are not known takes those of the pack given. + ty::pack => { + if this.types.is_open_pack(pattern) && this.types.kind_of(actual) == ty::pack { + this.bind_param(this.types.first_of(pattern), actual, into); + } else if !this.types.is_open_pack(pattern) && this.types.kind_of(actual) == ty::pack + && this.types.part_count(actual) == this.types.part_count(pattern) { + for i in 0..this.types.part_count(pattern) { + this.unify(this.types.part_at(pattern, i as u32), this.types.part_at(actual, i as u32), into, depth + 1); + } + } + } + ty::named => { + var plain := this.reached_value(actual); + if this.types.kind_of(plain) == ty::named && this.types.first_of(plain) != this.types.first_of(pattern) { + plain = this.unalias(plain); + } + # A value of a type implementing a generic trait gives its parameters + # through what implements the trait's members. + val wanted := this.types.first_of(pattern); + if this.decls.kinds.p[wanted] == dk::trait_type && this.named_kind(plain) != dk::trait_type + && this.types.kind_of(plain) != ty::param { + this.unify_named(pattern, plain, into, depth); + this.unify_members(pattern, plain, into, depth); + return; + } + if this.types.kind_of(plain) == ty::named && this.types.first_of(plain) == this.types.first_of(pattern) { + for i in 0..this.types.part_count(pattern) { + break if i >= this.types.part_count(plain); + this.unify(this.types.part_at(pattern, i as u32), this.types.part_at(plain, i as u32), into, depth + 1); + } + } + } + else => {} + } +} + +#! Gives a type parameter, or a pack, the type inferred for it, where nothing +#! but a constant has given it one yet. +#! @param this The checker. +#! @param decl The parameter's declaration. +#! @param given The type it is given. +#! @param into What is inferred. +def checker::bind_param(&mut this, decl: u32, given: u32, into: &mut checker::inferred): void { + for i in 0..into.params.length { + continue if into.params[i] != decl; + if into.binds[i] == checker::unknown_type || into.soft[i] { + into.binds[i] = given; + into.soft[i] = false; + } + return; + } +} + +#! Infers type parameters a generic trait holds from a type naming it, as the +#! type names it: `x : into` gives the `T` of `into` as `int`. A +#! member's types may be what the trait's arguments ask for, as `F::arg`, which +#! say nothing of the argument itself, so what the type names is read first. +#! @param this The checker. +#! @param pattern The trait's type, holding the parameters. +#! @param kind The type given. +#! @param into What is inferred. +#! @param depth How deeply the search has gone. +def checker::unify_named(&mut this, pattern: u32, kind: u32, into: &mut checker::inferred, depth: u32): void { + return if depth > 16; + val holder := this.types.first_of(pattern); + val named := this.implemented(this.reached_value(kind), holder); + return if named == this.decls.types.p[holder] || this.types.first_of(named) != holder; + for i in 0..this.types.part_count(pattern) { + break if i >= this.types.part_count(named); + this.unify(this.types.part_at(pattern, i as u32), this.types.part_at(named, i as u32), into, depth + 1); + } +} + +#! Infers type parameters a generic trait holds from a type implementing it, +#! through what implements each of the trait's members, as `count::into(&this): +#! int` gives the `T` of `into`, and through what implements those of the +#! traits it composes. +#! @param this The checker. +#! @param pattern The trait's type, holding the parameters. +#! @param kind The type given. +#! @param into What is inferred. +#! @param depth How deeply the search has gone. +def checker::unify_members(&mut this, pattern: u32, kind: u32, into: &mut checker::inferred, depth: u32): void { + return if depth > 16; + val holder := this.types.first_of(pattern); + val run: u32 = this.decls.children.p[holder]; + for i in 0..this.decls.list_length(run) { + val wanted := this.decls.list_at(run, i as u32); + val kind_of: dk = this.decls.kinds.p[wanted]; + continue if kind_of != dk::function && kind_of != dk::variable; + val found := this.find_member(kind, this.decls.names.p[wanted]); + # A method the compiler gives a built-in type, as a function's `invoke`, says + # what it takes and gives as a declared one does. + if found.decl == 0 && kind_of == dk::function && this.decls.has(wanted, df::method) { + val given := this.builtin_method(kind, this.decls.names.p[wanted]); + if given != 0 { + this.resolve(wanted); + val asked := this.trait_in_terms(this.decls.types.p[wanted], holder, pattern, kind); + this.unify(this.past_receiver(asked), this.past_receiver(given), into, depth + 1); + } + continue; + } + continue if found.decl == 0 || this.enclosing_trait(found.decl) != 0; + this.resolve(wanted); + val asked := this.trait_in_terms(this.decls.types.p[wanted], holder, pattern, kind); + if kind_of == dk::variable { + continue if this.decls.kinds.p[found.decl] != dk::variable; + this.resolve(found.decl); + this.unify(asked, this.instantiated(this.decls.types.p[found.decl], this.type_decl(found.owner), found.owner), into, depth + 1); + continue; + } + + # Of overloads, one of the shape asked for. + val count := this.types.part_count(asked); + var walk := this.decls.walk_overloads(found.decl); + while true { + val at := walk.next(); + break if at == 0; + if this.decls.kinds.p[at] == dk::function && this.decls.has(at, df::method) == this.decls.has(wanted, df::method) + && this.member_seen(at) { + val given := this.method_type(at, found.owner); + if this.types.kind_of(given) == ty::function && this.types.part_count(given) == count { + val skip: u64 = this.decls.has(wanted, df::method) ? 1 : 0; + for p in skip..count as u64 { + this.unify(this.types.part_at(asked, p as u32), this.types.part_at(given, p as u32), into, depth + 1); + } + this.unify(this.types.first_of(asked), this.types.first_of(given), into, depth + 1); + break; + } + } + } + } + + val composed := this.composed_of(holder); + for i in 0..this.decls.list_length(composed) { + val inner := this.trait_in_terms(this.decls.list_at(composed, i as u32), holder, pattern, kind); + this.unify_members(inner, kind, into, depth + 1); + } +} + +#! A method's type without its receiver: the function its other parameters and +#! its result make, variadic where the method is. +#! @param this The checker. +#! @param method The method's type. +#! @returns The function's type. +def checker::past_receiver(&mut this, method: u32): u32 { + var parts := vector::::new(); + for i in 1..this.types.part_count(method) { + parts.append(this.types.part_at(method, i as u32)); + } + return this.types.function(parts.view(), this.types.first_of(method), this.types.second_of(method) != 0); +} + +#! What the type arguments inferred so far give those their bounds name, as `C`, +#! where `C: iterable`, gives `T` the type of the elements it lends. A bound +#! may name a parameter another bound then gives more of, so the bounds are read +#! again until they give nothing new. +#! @param this The checker. +#! @param into What is inferred. +#! @param depth How many times the bounds have been read. +pub def checker::unify_bounds(&mut this, into: &mut checker::inferred, depth: u32): void { + return if depth > 4 || this.unbound(into) == 0; + val before := this.unbound_count(into); + for i in 0..into.params.length { + val param: u32 = into.params[i]; + val given: u32 = into.binds[i]; + continue if given == checker::unknown_type || into.soft[i] || this.decls.has(param, df::valued); + this.resolve(param); + val bounds: u32 = this.decls.children.p[param]; + for j in 0..this.decls.list_length(bounds) { + val bound := this.outer_terms(this.decls.list_at(bounds, j as u32), into); + if this.types.is_open(bound) { + this.unify_trait(bound, given, into, 0); + } + } + } + if this.unbound_count(into) != before { + this.unify_bounds(into, depth + 1); + } +} + +#! A type a trait's default names, with the trait's parameters and `self` given +#! the types the value it is called on gives them, leaving its own parameters. +#! @param this The checker. +#! @param kind The type. +#! @param into What is inferred. +#! @returns The type in those terms. +pub def checker::outer_terms(&mut this, kind: u32, into: &checker::inferred): u32 { + return kind if into.outer.length == 0; + return this.substitute(kind, into.outer.view(), into.given.view()); +} + +#! Gives what is inferred for a trait's default compiled for each type the +#! terms its bounds are read in: the trait's parameters, given the trait the +#! value it is called on implements, and `self`, given the value's type. +#! @param this The checker. +#! @param method The default's declaration. +#! @param through The type of the value it is called on, read through its +#! references. +#! @param into What is inferred. +pub def checker::give_outer(&mut this, method: u32, through: u32, into: &mut checker::inferred): void { + val holder := this.enclosing_trait(method); + return if holder == 0; + val plain := this.unalias(through); + val trait_kind := this.trait_reached(method, plain); + val params: u32 = this.decls.params.p[holder]; + for i in 0..this.decls.list_length(params) { + into.outer.append(this.decls.list_at(params, i as u32)); + into.given.append(i < this.types.part_count(trait_kind) ? this.types.part_at(trait_kind, i as u32) : bt::error); + } + into.outer.append(this.self_decl(holder)); + into.given.append(plain); +} + +#! How many type parameters nothing has given a type yet. +#! @param this The checker. +#! @param inferred What was inferred. +#! @returns How many. +def checker::unbound_count(&this, inferred: &checker::inferred): u32 { + var count: u32 = 0; + for i in 0..inferred.binds.length { + count += inferred.binds[i] == checker::unknown_type ? 1 : 0; + } + return count; +} + +#! Infers the arguments of a trait a type implements from how it implements it: +#! each type the trait asks for is the one the type gives, which the bounds it is +#! asked with say more of, and each method's parameters and result are those of +#! the type's method. +#! @param this The checker. +#! @param pattern The trait, as the template writes it. +#! @param actual The type implementing it. +#! @param into What is inferred. +#! @param depth How deeply the search has gone. +def checker::unify_trait(&mut this, pattern: u32, actual: u32, into: &mut checker::inferred, depth: u32): void { + return if depth > 8 || actual == bt::error; + val plain := this.unalias(pattern); + return if this.named_kind(plain) != dk::trait_type; + val asked := this.types.first_of(plain); + this.resolve(asked); + this.unify_named(plain, actual, into, depth); + + # The trait's own parameters are the pattern's arguments, and `self` the type. + var from := vector::::new(); + var to := vector::::new(); + val params: u32 = this.decls.params.p[asked]; + for i in 0..this.decls.list_length(params) { + from.append(this.decls.list_at(params, i as u32)); + to.append(i < this.types.part_count(plain) ? this.types.part_at(plain, i as u32) : bt::error); + } + from.append(this.self_decl(asked)); + to.append(actual); + + val members: u32 = this.decls.children.p[asked]; + for i in 0..this.decls.list_length(members) { + val member := this.decls.list_at(members, i as u32); + if this.decls.kinds.p[member] == dk::assoc_type { + val given := this.member_type(actual, this.decls.names.p[member]); + continue if given == bt::error; + this.resolve(member); + val bounds: u32 = this.decls.children.p[member]; + for j in 0..this.decls.list_length(bounds) { + val bound := this.substitute(this.decls.list_at(bounds, j as u32), from.view(), to.view()); + this.unify_trait(bound, given, into, depth + 1); + } + continue; + } + continue if this.decls.kinds.p[member] != dk::function; + val found := this.find_member(this.reached_value(actual), this.decls.names.p[member]); + # A method the compiler gives a built-in type, as a function's `invoke`. + if found.decl == 0 && this.decls.has(member, df::method) { + val given := this.builtin_method(this.reached_value(actual), this.decls.names.p[member]); + if given != 0 { + this.resolve(member); + val want := this.substitute(this.decls.types.p[member], from.view(), to.view()); + this.unify(this.past_receiver(want), this.past_receiver(given), into, depth + 1); + } + continue; + } + continue if found.decl == 0 || this.decls.kinds.p[found.decl] != dk::function; + this.resolve(member); + val want := this.substitute(this.decls.types.p[member], from.view(), to.view()); + val have := this.member_function_type(found.decl, found.owner); + this.unify(want, have, into, depth + 1); + } +} + +#! What a value of the type is, read through a reference. +#! @param this The checker. +#! @param kind The type. +#! @returns What it reaches, or the type itself. +def checker::reached_value(&mut this, kind: u32): u32 { + return this.types.kind_of(kind) == ty::reference ? this.types.first_of(kind) : kind; +} + +#! The first type parameter nothing gave a type, or 0 where every one has one. +#! @param this The checker. +#! @param inferred What was inferred. +#! @returns The type parameter's declaration, or 0. +pub def checker::unbound(&this, inferred: &checker::inferred): u32 { + for i in 0..inferred.params.length { + return inferred.params[i] if inferred.binds[i] == checker::unknown_type; + } + return 0; +} + +#! What a type parameter is inferred as while nothing has given it a type. +pub const checker::unknown_type: u32 = 0xFFFFFFFF; + +#! The type with the inferred type parameters replaced by their types. +#! @param this The checker. +#! @param kind The type. +#! @param inferred What was inferred. +#! @returns The type with them replaced. +pub def checker::apply(&mut this, kind: u32, inferred: &checker::inferred): u32 { + return this.substitute(kind, inferred.params.view(), inferred.binds.view()); +} + +#! The type with the type parameters inferred so far replaced by their types, +#! and those nothing has given a type yet left as they are. +#! @param this The checker. +#! @param kind The type. +#! @param inferred What was inferred. +#! @returns The type with the known ones replaced. +pub def checker::apply_known(&mut this, kind: u32, inferred: &checker::inferred): u32 { + var from := vector::::new(); + var to := vector::::new(); + for i in 0..inferred.params.length { + continue if inferred.binds[i] == checker::unknown_type; + from.append(inferred.params[i]); + to.append(inferred.binds[i]); + } + return this.substitute(kind, from.view(), to.view()); +} + +#! Whether a type holds a type parameter, so it belongs to a template rather +#! than an instance. +#! @param this The checker. +#! @param kinds The types. +#! @returns Whether any does. +pub def checker::any_open(&this, kinds: span): bool { + for &each in kinds { + return true if this.types.is_open(each); + } + return false; +} + +#! How deeply type arguments nest within the type. +#! @param this The checker. +#! @param kind The type. +#! @param depth How deeply it already nests. +#! @returns How deeply its arguments nest. +def checker::nesting(&this, kind: u32, depth: u32): u32 { + return depth if depth > checker::max_nesting; + + var deepest := depth; + match this.types.kind_of(kind) { + ty::reference, ty::pointer, ty::fixed => { + return this.nesting(this.types.first_of(kind), depth + 1); + } + ty::function, ty::named, ty::pack => { + for &part in this.types.parts_view(kind) { + val inner := this.nesting(part, depth + 1); + deepest = inner > deepest ? inner : deepest; + } + } + else => {} + } + return deepest; +} + +#! The instance of the generic function given the type arguments, made where it +#! is new and waiting for its body to be checked. +#! @param this The checker. +#! @param decl The generic function. +#! @param args Its type arguments, its owner's first. +#! @param node The node a note is placed at, where too many instances are +#! made. +#! @returns One more than its index, or 0 where the arguments hold type +#! parameters, or the program has made as many instances as it may. +pub def checker::instance_of(&mut this, decl: u32, args: span, node: u32): u32 { + return 0 if this.any_open(args) || args.length == 0; + for &each in args { + return 0 if each == bt::error; + } + + val pack := this.types.pack(args, 0); + val key := pair_key(decl, pack); + if this.instanced.get(&key) is some(got) { + return got; + } + + if this.instances.length as u32 >= checker::max_instances { + this.report(node, ec::limit, "The program makes more instances of generics than the checker allows."); + return 0; + } + if this.nesting(pack, 0) > checker::max_nesting { + this.report(node, ec::limit, "The type arguments nest too deeply, as a generic instantiating itself with ever larger types does."); + return 0; + } + + this.resolve(decl); + val params: u32 = this.decls.params.p[decl]; + var from := this.decls.list_of(params); + + val id := this.instances.length as u32; + this.instances.append(instance { + decl = decl, + args = pack, + kind = this.substitute(this.decls.types.p[decl], from.view(), args) + }); + this.instanced.set(key, id + 1); + this.wants.append(id); + return id + 1; +} + +#! The instance of a trait's default method a type takes. A default of a trait +#! that is only a bound is compiled for each type taking it, with the trait's +#! parameters bound to its arguments, `self` to the type, and its own type +#! parameters to those the call gives. Any other is compiled for the trait, +#! given its arguments, with `self` the trait itself, called through as a +#! reference to the trait is, and a default of a trait without parameters is +#! then its own template. +#! @param this The checker. +#! @param method The default's declaration. +#! @param trait_kind The trait declaring it, given its arguments. +#! @param self_kind The type taking it. +#! @param own The method's own type arguments, which a default +#! compiled for each type takes after `self`. +#! @returns One more than the instance, or 0 where it is its own template or +#! its arguments are not known. +pub def checker::default_instance(&mut this, method: u32, trait_kind: u32, self_kind: u32, own: span): u32 { + val holder := this.enclosing_trait(method); + return 0 if holder == 0 || holder == method || this.types.kind_of(trait_kind) != ty::named; + val params: u32 = this.decls.params.p[holder]; + val typed := this.typed_default(method); + return 0 if !typed && this.decls.list_length(params) == 0; + var args := this.types.parts_of(trait_kind); + if typed { + return 0 if own.length != this.decls.list_length(this.decls.params.p[method]); + args.append(self_kind); + args.extend(own); + } + return 0 if args.length == 0 || this.any_open(args.view()); + for &each in args { + return 0 if each == bt::error; + } + + val pack := this.types.pack(args.view(), 0); + val key := pair_key(method, pack); + if this.instanced.get(&key) is some(got) { + return got; + } + if this.instances.length as u32 >= checker::max_instances { + this.report(this.decls.nodes.p[method], ec::limit, "The program makes more instances of generics than the checker allows."); + return 0; + } + if this.nesting(pack, 0) > checker::max_nesting { + this.report(this.decls.nodes.p[method], ec::limit, "The type arguments nest too deeply, as a generic instantiating itself with ever larger types does."); + return 0; + } + + this.resolve(method); + var from := vector::::new(); + var to := vector::::new(); + val trait_args := this.types.part_count(trait_kind); + for i in 0..this.decls.list_length(params) { + from.append(this.decls.list_at(params, i as u32)); + to.append(i < trait_args ? this.types.part_at(trait_kind, i as u32) : bt::error); + } + from.append(this.self_decl(holder)); + to.append(typed ? self_kind : trait_kind); + if typed { + from.extend(this.decls.list_view(this.decls.params.p[method])); + to.extend(own); + } + + val id := this.instances.length as u32; + this.instances.append(instance { + decl = method, + args = pack, + kind = this.substitute(this.decls.types.p[method], from.view(), to.view()) + }); + this.instanced.set(key, id + 1); + this.wants.append(id); + return id + 1; +} + +#! The first node of a declaration's nodes, which are one run of indexes, the +#! parser having made them as it went, the declaration's own last. +#! @param this The checker. +#! @param decl The declaration. +#! @returns The node. +pub def checker::first_node(&mut this, decl: u32): u32 { + val held := this.decl_bases.at_or_zero(decl); + return held if held != 0; + + val saved := this.at; + this.use_table(this.units[this.decls.files.p[decl]].table); + val node: u32 = this.decls.nodes.p[decl]; + var lowest := node; + var todo := vector::::new(); + todo.append(node); + while todo.length != 0 { + val at: u32 = todo.last(); + todo.truncate(); + lowest = at < lowest ? at : lowest; + this.syn().children(at, &mut todo); + } + this.at = saved; + + this.decl_bases.put(decl, lowest); + return lowest; +} + +#! Checks the bodies of the instances the program uses, including those the +#! bodies checked here use in turn. +#! @param this The checker. +pub def checker::check_wanted(&mut this): void { + while this.wants_checked < this.wants.length { + val id: u32 = this.wants[this.wants_checked]; + this.wants_checked++; + this.check_instance(id); + } +} + +#! Checks an instance's body over its template's nodes, with a result table of +#! its own and the type parameters bound to its arguments. +#! @param this The checker. +#! @param id The instance's index. +def checker::check_instance(&mut this, id: u32): void { + val held: instance = this.instances[id]; + val decl := held.decl; + return if this.decls.has(decl, df::failed); + + val first := this.first_node(decl); + val last: u32 = this.decls.nodes.p[decl]; + val table := this.add_table(this.decls.files.p[decl], first, last - first + 1, id + 1); + this.instances[id].table = table + 1; + + val saved := this.at; + this.enter_decl(decl, held.args); + this.use_table(table); + this.at.instance = id + 1; + this.check_function_body(decl, held.kind); + this.leave(saved); +} diff --git a/analyzer/checker/incremental.sakura b/analyzer/checker/incremental.sakura new file mode 100644 index 00000000..ff0c4718 --- /dev/null +++ b/analyzer/checker/incremental.sakura @@ -0,0 +1,671 @@ +#! @file incremental.sakura +#! @author John Christman (sorakatadzuma@gmail.com) +#! @copyright Malunal Studios, LLC. +#! @license MIT +#! +#! Contains checking again after an edit. While a declaration is checked, what +#! it depends on is recorded: each declaration it resolves, and each name it +#! looks up outside any scope, found or not. Once a file is parsed again, which +#! keeps the nodes of the top-level declarations an edit did not touch, the +#! checker keeps what it worked out of those, declares what is new, lets go of +#! what is gone, and checks again only what depends on what changed. A changed +#! declaration of the same kind, module, and name keeps its ID, so what other +#! files worked out of it stays. + +import std::containers; +module sakura::analyzer; + + +#! Records that the declaration being checked depends on the declaration. +#! @param this The checker. +#! @param id The declaration depended on. +pub def checker::depend(&mut this, id: u32): void { + val from := this.top_decl(this.at.decl); + return if from == 0 || id == 0 || from == id; + if id as u64 >= this.depended.length { + this.depended.resize(this.decls.count > id as u64 ? this.decls.count : id as u64 + 1); + } + this.depended[id] = true; + return if !this.tracks; + this.add_dependency(from, id); +} + +#! Whether any declaration depends on a declaration, as resolving it. +#! @param this The checker. +#! @param id The declaration. +#! @returns Whether one does. +pub def checker::is_depended(&this, id: u32): bool { + return (id as u64) < this.depended.length && this.depended[id]; +} + +#! Records that the declaration being checked looked up the name outside any +#! scope, so a declaration of the name made later may be what it means. +#! @param this The checker. +#! @param name The ID of the name. +pub def checker::depend_name(&mut this, name: u32): void { + return if !this.tracks; + val from := this.top_decl(this.at.decl); + return if from == 0; + this.add_dependency(from, name | checker::named_dependency); +} + +#! What a dependency on a name, rather than a declaration, has set. +pub const checker::named_dependency: u32 = 0x80000000; + +def checker::add_dependency(&mut this, from: u32, to: u32): void { + val key := pair_key(from, to); + return if !this.dep_seen.insert(key, 1); + this.dep_from.append(from); + this.dep_to.append(to); +} + +#! The top-level declaration a declaration was declared with: itself, or the +#! type a field or member is of, or the declaration a type parameter is of. +#! @param this The checker. +#! @param id The declaration. +#! @returns The top-level declaration. +pub def checker::top_decl(&this, id: u32): u32 { + var at := id; + var steps := 0; + while at != 0 && steps < 8 { + val node: u32 = this.decls.nodes.p[at]; + val top: u32 = this.decls.tops.p[at]; + return at if top == 0 || node == top; + at = this.decls.owners.p[at]; + steps++; + } + return id; +} + +#! A top-level declaration of a file, and the module it is declared in. +struct checker::placed { + var node: u32; #! The declaration's node. + var home: u32; #! The module it is declared in. + var external: bool; #! Whether it is in an `extern module`. +} + +#! The top-level declarations the file declares, in the branches of `when` the +#! target takes, each with the module it is declared in, noting the libraries +#! its `extern import`s name anew. +#! @param this The checker. +#! @param file The file. +#! @returns Each declaration's node and module, in order. +def checker::placements(&mut this, file: u32): vector { + var kept := vector::::new(); + for &each in this.libraries { + if (each >> 32) as u32 != file { + kept.append(each); + } + } + this.libraries = move(&mut kept); + + var made := vector::::new(); + val decls := this.left_of(this.units[file].root); + var home: u32 = 0; + var active := true; + var external := false; + for &node in this.run_view(decls) { + match this.kind_of(node) { + nk::import_decl => {} + nk::extern_import => { + if this.right_of(node) == 0 || this.target_holds(this.right_of(node)) { + this.add_library(file, node); + } + } + nk::module_decl, nk::extern_module => { + home = this.module_path(this.left_of(node), true); + active = this.right_of(node) == 0 || this.target_holds(this.right_of(node)); + external = this.kind_of(node) == nk::extern_module; + if external { + this.check_section(node); + } + } + else => { + if active { + this.place_top(node, home, external, &mut made); + } + } + } + } + return made; +} + +def checker::place_top(&mut this, node: u32, home: u32, external: bool, into: &mut vector): void { + match this.kind_of(node) { + nk::when_block => { + val chosen := this.when_branch(node); + return if chosen == 0; + val decls := this.left_of(chosen); + for &node in this.run_view(decls) { + this.place_top(node, home, external, into); + } + } + nk::error => {} + else => into.append(checker::placed { node = node, home = home, external = external }); + } +} + +#! The key a top-level declaration is matched by across an edit: its kind, +#! module, and name, each whole, so no two declarations differing in any share +#! one. +struct checker::match_key : hashable, equatable { + var kind: dk; #! Its kind. + var home: u32; #! The module it is declared in. + var name: u32; #! The ID of its name. +} + +#! Hashes the key, as the dictionary of keys asks. +#! @param this The key. +#! @returns Its hash code. +pub def checker::match_key::hash(&this): u64 { + return mix(pair_key(this.home, this.name), this.kind as u64); +} + +#! Whether two keys are of the same kind, module, and name. +#! @param this The key. +#! @param other The other key. +#! @returns Whether they are. +pub def checker::match_key::equals(&this, other: &checker::match_key): bool { + return this.kind == other.kind && this.home == other.home && this.name == other.name; +} + +#! Checks the file again once it is parsed again, as `syntax::reparse` does, +#! checking again only what the edit affects. +#! @param this The checker. +#! @param file The file. +#! @param source The file's text as it was edited, which its tokens are of +#! now. +#! @param root The file's `document` node, as parsing it again gave it. +#! @returns How many top-level declarations were checked again. +pub def checker::update(&mut this, file: u32, source: &source, root: u32): u32 { + val saved := this.at; + this.units[file].source = &source; + this.units[file].root = root; + val old_table: u32 = this.units[file].table; + val count := this.units[file].syntax.node_count as u32; + val fresh := this.add_table(file, 0, count, 0); + this.units[file].table = fresh; + this.use_table(fresh); + + # The top-level declarations the file has now, and those it had. + val placed := this.placements(file); + var now := dict::::new(); # Each top-level node now, with its module. + for &each in placed { + now.set(each.node, each.home); + } + + # Parsing the file whole again made every node anew, so none of the old ones + # is kept, however their indexes fall. + val whole := this.units[file].syntax.parses != this.units[file].parses; + this.units[file].parses = this.units[file].syntax.parses; + + var kept := dict::::new(); # The top-level nodes kept, and their declarations. + var gone := vector::::new(); # The top-level declarations whose nodes are gone. + for &decl in this.decls.by_file.of(file) { + continue if this.decls.kinds.p[decl] == dk::none || this.decls.kinds.p[decl] == dk::builtin; + val top: u32 = this.decls.tops.p[decl]; + continue if top == 0 || this.decls.nodes.p[decl] != top; + if !whole && now.contains(&top) && this.decl_kind(top) == this.decls.kinds.p[decl] { + if !kept.contains(&top) { + kept.set(top, decl); + } + } else { + gone.append(decl); + } + } + + # What is kept keeps what was worked out of it. + for &each in placed { + val decl := kept.get(&each.node) else { continue; }; + this.move_results(old_table, fresh, each.node, decl); + } + this.repoint_tables(old_table, fresh); + + # A top-level declaration gone whose kind, module, and name a new one has + # keeps its ID, so what other files worked out of it stays. + var reusable := dict::::new(); + for &decl in gone { + val key := checker::match_key { + kind = this.decls.kinds.p[decl as u32], + home = this.decls.modules.p[decl as u32], + name = this.decls.names.p[decl as u32] + }; + if !reusable.contains(&key) { + reusable.set(key, decl); + } + } + + var changed := vector::::new(); + var olds := dict::::new(); # The type each reused declaration had. + for &decl in gone { + this.forget_members(decl, file); + } + + this.pending.clear(); + this.at.scope = 0; + var made := vector::::new(); + for &each in placed { + continue if kept.contains(&each.node); + this.at.home = each.home; + val kind := this.decl_kind(each.node); + val name := this.name_of(each.node); + val key := checker::match_key { kind = kind, home = each.home, name = name }; + if reusable.contains(&key) { + val decl: u32 = reusable[key]; + reusable.remove(&key); + olds.set(decl, this.decls.types.p[decl]); + this.external = each.external; + this.redeclare(decl, each.node, each.home); + this.external = false; + made.append(decl); + continue; + } + + this.decls.top = each.node; + this.external = each.external; + val decl := this.declare_decl(each.node, 0); + this.external = false; + this.decls.top = 0; + if decl != 0 { + made.append(decl); + changed.append(decl); + } + } + + # What is gone and not reused leaves every scope it was in. + for &each in gone { + val decl: u32 = each; + continue if olds.contains(&decl); + this.forget(decl); + changed.append(decl); + } + + this.relink(file); + this.forget_caches(); + + # Checking again: what is new or reused, then whatever depends on what + # changed, and on what that changes in turn. + var checked := hashset::::new(); + var queue := vector::::new(); + queue.extend(made.view()); + var at: u64 = 0; + var rounds := 0; + while rounds < 64 { + rounds++; + while at < queue.length { + val decl: u32 = queue[at]; + at++; + continue if checked.contains(&decl) || this.decls.kinds.p[decl] == dk::none; + checked.insert(decl); + + val before := olds.get_or(&decl, this.decls.types.p[decl]); + this.check_again(decl); + val after: u32 = this.decls.types.p[decl]; + if !olds.contains(&decl) || before != after || this.is_type_decl(decl) { + changed.append(decl); + } + } + + # Whatever depends on what changed is checked again. + val queued := queue.length; + var names := hashset::::new(); + var ids := hashset::::new(); + for &decl in changed { + ids.insert(decl); + names.insert(this.decls.names.p[decl as u32]); + } + changed.clear(); + for i in 0..this.dep_from.length { + val to: u32 = this.dep_to[i]; + val from: u32 = this.dep_from[i]; + val hit := (to & checker::named_dependency) != 0 + ? names.contains(&(to & ~checker::named_dependency)) + : ids.contains(&to); + if hit && !checked.contains(&from) { + queue.append(from); + } + } + break if queue.length == queued; + } + + this.check_wanted(); + this.recount_notes(); + this.at = saved; + return checked.length as u32; +} + +#! Copies what was worked out of a top-level declaration's nodes from one +#! table of its file to another. +#! @param this The checker. +#! @param from The table to copy from. +#! @param to The table to copy to. +#! @param top The top-level declaration's node, whose nodes run from its +#! first to it. +#! @param decl The declaration. +def checker::move_results(&mut this, from: u32, to: u32, top: u32, decl: u32): void { + val first := this.first_node(decl); + val source: rtable = this.tables.p[from]; + val target: rtable = this.tables.p[to]; + for node in first..(top + 1) { + val n := node as u32; + continue if n >= source.count || n >= target.count; + this.copy_results(source.offset as u64 + n as u64, target.offset as u64 + n as u64); + this.move_key(from, to, n); + } +} + +#! Moves what the sparse results hold of the node from one table to another. +#! @param this The checker. +#! @param from The table to move from. +#! @param to The table to move to. +#! @param node The node. +def checker::move_key(&mut this, from: u32, to: u32, node: u32): void { + val old_key := pair_key(from, node); + val new_key := pair_key(to, node); + if this.reflections.get(&old_key) is some(held) { + this.reflections.set(new_key, held); + } + if this.lengths.get(&old_key) is some(held) { + this.lengths.set(new_key, held); + } + if this.called.get(&old_key) is some(held) { + this.called.set(new_key, held); + } +} + +#! Makes the tables made within the file's old table, for `for const`, be within +#! its new one. +#! @param this The checker. +#! @param from The file's old table. +#! @param to Its new table. +def checker::repoint_tables(&mut this, from: u32, to: u32): void { + for i in 0..this.tables.length { + if this.tables.p[i].parent == from + 1 { + this.tables.p[i].parent = to + 1; + } + } +} + +#! Lets go of what a top-level declaration declared within it: its members, +#! its type parameters, and what the checker made of it, which declaring it +#! again makes anew. +#! @param this The checker. +#! @param decl The top-level declaration. +#! @param file The file it is declared in. +def checker::forget_members(&mut this, decl: u32, file: u32): void { + val top: u32 = this.decls.tops.p[decl]; + for &each in this.decls.by_file.of(file) { + continue if each == decl || this.decls.tops.p[each] != top; + this.forget(each); + } + this.decls.children.p[decl] = 0; +} + +#! Lets go of a declaration: it leaves the module or type declaring it, and is +#! no longer anything. +#! @param this The checker. +#! @param decl The declaration. +def checker::forget(&mut this, decl: u32): void { + val kind: dk = this.decls.kinds.p[decl]; + return if kind == dk::none; + + val owner: u32 = this.decls.owners.p[decl]; + val name: u32 = this.decls.names.p[decl]; + if owner != 0 && (kind != dk::type_param) { + this.leave_type(owner, decl); + } else if kind != dk::type_param { + val home: u32 = this.decls.modules.p[decl]; + val key := pair_key(home, name); + this.unchain(this.modules.decl(home, name), decl, key, chained::modules); + } + + this.decls.kinds.p[decl] = dk::none; + this.decls.overloads.p[decl] = 0; + this.decls.tops.p[decl] = 0; +} + +#! Takes a member out of its type's members, or out of the types declared +#! through its type. +#! @param this The checker. +#! @param owner The type's declaration. +#! @param decl The member's declaration. +def checker::leave_type(&mut this, owner: u32, decl: u32): void { + val name: u32 = this.decls.names.p[decl]; + val key := pair_key(owner, name); + val added := this.decls.added_member(owner, name); + if added != 0 && !this.in_core(this.decls.modules.p[decl]) { + this.unchain(added, decl, key, chained::added); + return; + } + if this.decls.nests(decl) { + if this.decls.member_in(owner, name, true) == decl { + this.decls.nested.remove(&key); + } + return; + } + this.unchain(this.decls.member_in(owner, name, false), decl, key, chained::members); +} + +#! Which dictionary holds the first of a chain of overloads by its key. +enum chained : u8 { + members, #! A type's members, `decls.members`. + added, #! Those declared outside `core` on `core`'s type, `decls.added`. + modules, #! A module's, `modules.decls`. +} + +#! Takes the declaration out of the chain of overloads beginning with `first`, +#! which the dictionary holds by the key. +#! @param this The checker. +#! @param first The first of the overloads, or 0. +#! @param decl The declaration to take out. +#! @param key The key the dictionary holds the first by. +#! @param held Which dictionary that is. +def checker::unchain(&mut this, first: u32, decl: u32, key: u64, held: chained): void { + return if first == 0; + if first == decl { + val next: u32 = this.decls.overloads.p[decl]; + var dict := match held { + chained::members => &mut this.decls.members, + chained::added => &mut this.decls.added, + chained::modules => &mut this.modules.decls + }; + if next == 0 { dict.remove(&key); } else { dict.set(key, next); } + return; + } + + var walk := this.decls.walk_overloads(first, 4096); + while true { + val at := walk.next(); + break if at == 0; + if this.decls.overloads.p[at] == decl { + val after: u32 = this.decls.overloads.p[decl]; + this.decls.overloads.p[at] = after; + return; + } + } +} + +#! Declares a top-level declaration again, at its new node, keeping its ID: it +#! leaves where it was declared and is declared there again, with its members +#! and type parameters made anew. +#! @param this The checker. +#! @param decl The declaration. +#! @param node Its new node. +#! @param home The module it is declared in. +def checker::redeclare(&mut this, decl: u32, node: u32, home: u32): void { + val kind: dk = this.decls.kinds.p[decl]; + val owner: u32 = this.decls.owners.p[decl]; + val name: u32 = this.decls.names.p[decl]; + if owner != 0 { + this.leave_type(owner, decl); + } else { + val key := pair_key(this.decls.modules.p[decl], name); + this.unchain(this.modules.decl(this.decls.modules.p[decl], name), decl, key, chained::modules); + } + + this.decls.renew(decl, node, home); + this.decl_bases.put(decl, 0); + this.decl_values.put(decl, 0); + + val flags := this.node_flags(node); + if (flags & nf::exported as u32) != 0 { this.decls.mark(decl, df::exported); } + if (flags & nf::mutable as u32) != 0 { this.decls.mark(decl, df::mutable); } + if (flags & nf::constant as u32) != 0 { this.decls.mark(decl, df::constant); } + this.mark_attributes(decl, node); + if this.external { + this.mark_external(decl, kind, node); + } + if kind == dk::function { + this.mark_signature(decl, node); + } + + this.decls.top = node; + if this.receiver_of(node) != 0 { + this.pending.append(decl); + } else { + this.add_global(decl); + } + val own := this.declare_params(this.own_params_of(node), decl); + this.record_shape(decl, this.own_params_of(node)); + if this.receiver_of(node) == 0 { + this.set_params(decl, own.view()); + } else { + this.decls.params.p[decl] = this.decls.make_list(own.view()); + } + this.declare_members(decl, node); + this.decls.top = 0; +} + +#! Links what was declared anew: the file's imports, the declarations made +#! through types, and the types of new type declarations. +#! @param this The checker. +#! @param file The file. +def checker::relink(&mut this, file: u32): void { + var imports := vector::::new(); + val decls := this.left_of(this.units[file].root); + for &node in this.run_view(decls) { + continue if this.kind_of(node) != nk::import_decl; + val found := this.module_path(this.left_of(node), false); + if found == 0 { + this.report(node, ec::undefined, "No file declares this module."); + continue; + } + imports.append(found); + } + val run := this.decls.make_list(imports.view()); + this.units[file].imports = run; + + this.attach_pending(); + this.pending.clear(); + this.give_accessors_params(); + this.name_types(); +} + +#! Lets go of what was worked out of types and traits, which what changed may +#! have changed, to be worked out again as it is needed. +#! @param this The checker. +def checker::forget_caches(&mut this): void { + this.satisfied.clear(); + this.types.forget(); + this.only_bounds.clear(); + this.outers.clear(); + this.composed.resize(0); + this.known.clear(); +} + +#! Checks a top-level declaration again: its notes are let go of, what it and +#! what it declares worked out is let go of, and it is resolved and checked as +#! though for the first time, with the instances of it the program uses. +#! @param this The checker. +#! @param decl The top-level declaration. +def checker::check_again(&mut this, decl: u32): void { + val top: u32 = this.decls.tops.p[decl]; + val file: u32 = this.decls.files.p[decl]; + this.forget_notes(decl); + + var family := vector::::new(); + for &each in this.decls.by_file.of(file) { + if each == decl || (top != 0 && this.decls.tops.p[each] == top && this.decls.kinds.p[each] != dk::none) { + family.append(each); + } + } + + for &each in family { + this.decls.states.p[each as u32] = ds::unresolved; + this.decls.flags.p[each as u32] &= ~(df::checked as u32 | df::failed as u32); + } + this.clear_results(decl); + for &each in family { + this.resolve(each); + } + for &each in family { + this.check_decl(each); + } + + # The instances of what is checked again are checked again with it. + for i in 0..this.instances.length { + val held: instance = this.instances[i]; + continue if !family.view().contains(&held.decl); + var from := this.decls.list_of(this.decls.params.p[held.decl]); + var args := this.types.parts_of(held.args); + val kind := this.substitute(this.decls.types.p[held.decl], from.view(), args.view()); + this.instances[i].kind = kind; + this.instances[i].table = 0; + this.wants.append(i as u32); + } +} + +#! Lets go of what was worked out of a declaration's nodes in its file's table. +#! @param this The checker. +#! @param decl The top-level declaration. +def checker::clear_results(&mut this, decl: u32) : void { + val file: u32 = this.decls.files.p[decl]; + val table: u32 = this.units[file].table; + val held: rtable = this.tables.p[table]; + val first := this.first_node(decl); + val last: u32 = this.decls.nodes.p[decl]; + for node in first..(last + 1) { + val n := node as u32; + continue if n >= held.count; + this.drop_results(held.offset as u64 + n as u64); + val key := pair_key(table, n); + this.reflections.remove(&key); + this.lengths.remove(&key); + this.called.remove(&key); + } +} + +#! Lets go of the notes the checker made checking the declaration, or what it +#! declares. +#! @param this The checker. +#! @param decl The top-level declaration. +def checker::forget_notes(&mut this, decl: u32): void { + # Those kept are moved down over those let go of, which are closed as they + # are written over, and those left past the last kept are closed with them. + var kept: u64 = 0; + for i in 0..this.sink.notes.length { + val origin := this.sink.notes[i].origin; + continue if origin != 0 && this.top_decl(origin) == decl; + if kept != i { + this.sink.notes[kept] = move(&mut this.sink.notes[i]); + } + kept++; + } + while this.sink.notes.length > kept { + this.sink.notes.truncate(); + } +} + +#! Counts the notes the checker made, which the most it makes bounds, and +#! whether the program is valid, once some are made again. +#! @param this The checker. +def checker::recount_notes(&mut this): void { + var count: u32 = 0; + for i in 0..this.sink.notes.length { + if this.sink.notes[i].origin != 0 { + count++; + } + } + this.sink.count = count; + this.failed = count != 0; +} diff --git a/analyzer/checker/knowns.sakura b/analyzer/checker/knowns.sakura new file mode 100644 index 00000000..b7c50e18 --- /dev/null +++ b/analyzer/checker/knowns.sakura @@ -0,0 +1,1372 @@ +#! @file knowns.sakura +#! @author John Christman (sorakatadzuma@gmail.com) +#! @copyright Malunal Studios, LLC. +#! @license MIT +#! +#! Contains the values the checker works out while checking, which are what a +#! constant type argument is, as `4` of `buffer`: numbers, text, +#! structs, unions and arrays of them, functions, and the addresses of +#! constants. Each is interned, so two equal values are one, and one type +#! argument, however each is written. Within a template, a value worked out +#! from its own constant parameters is kept as the expression over them, which +#! each instance works out. + +module sakura::analyzer; + + +#! The kinds of value the checker works out. +pub enum kk : u8 { + invalid, #! Known value 0, which stands for "not known". + number, #! An integer, `bool`, character, or member of an enum: `value`. + real, #! A float, rounded to its type: `value`. + text, #! Text: the bytes `text` holds. + fields, #! A struct's fields in order, or the elements of a fixed array or a view: `parts`. + held, #! A union holding its field `value.magnitude`, which holds its one part. + null_lit, #! `null`. + function, #! A function: `decl`. + address, #! The address of a constant: `decl`. + param, #! Within a template, a constant parameter: `decl`, its declaration. + unary, #! Within a template, `op` applied to its one part. + binary, #! Within a template, `op` between its two parts. + cast, #! Within a template, its one part converted to its type. + opaque, #! Within a template, anything else, the same only where written once: `node` of `file`. +} + +#! A value the checker worked out, by its ID in `knowns`. +pub struct known { + pub var kind: kk; #! What it is. + var of: u32; #! The type it is a value of. + pub var value: constant; #! A number's or float's value, or a union's field. + var text: u32; #! Text's bytes, by index in `known_texts`. + var parts: u32; #! Its parts' run in `known_parts`, 0 where it has none. + pub var decl: u32; #! A function, a constant whose address it is, or a constant parameter. + var op: tk; #! The operator of a value over constant parameters. + var node: u32; #! Of `opaque`, its expression. + var file: u32; #! Of `opaque`, the file of its expression. +} + +#! The value of the ID, as a copy. +#! @param this The checker. +#! @param id The value's ID. +#! @returns The value. +pub def checker::known_at(&this, id: u32): known { + return this.knowns.p[id]; +} + +#! How many parts a value has. +#! @param this The checker. +#! @param id The value's ID. +#! @returns How many. +pub def checker::known_count(&this, id: u32): u32 { + return this.known_parts.length(this.knowns.p[id].parts) as u32; +} + +#! A part of a value. +#! @param this The checker. +#! @param id The value's ID. +#! @param index The part's position. +#! @returns The part's ID. +pub def checker::known_part(&this, id: u32, index: u32): u32 { + return this.known_parts.at(this.knowns.p[id].parts, index as u64); +} + +#! The parts of a value, where they are. +#! @param this The checker. +#! @param id The value's ID. +#! @returns The IDs of its parts, in order, a view only good until a value with +#! parts is interned, so a loop that may intern one walks them by +#! `known_part`. +pub def checker::known_view(&this, id: u32): span { + return this.known_parts.view(this.knowns.p[id].parts); +} + +#! The ID of a value, interned, so an equal value made before is the one given. +#! @param this The checker. +#! @param made The value, whose `parts` and `text` are given apart. +#! @param parts The IDs of its parts, in order. +#! @param text The bytes of text. +#! @returns Its ID. +pub def checker::intern_known(&mut this, made: known, parts: span, text: strview): u32 { + val hash := known_hash(&made, parts, text); + var walk := this.known_index.walk(hash); + var at := this.known_index.next(&mut walk); + while at != 0 { + val id := at - 1; + return id if this.same_known(id, &made, parts, text); + at = this.known_index.next(&mut walk); + } + + var held := made; + held.parts = this.known_parts.add(parts); + if made.kind == kk::text { + held.text = this.known_texts.length as u32; + this.known_texts.append(string::from(text, nothing {})); + } + + val id := this.knowns.length as u32; + this.knowns.append(held); + this.known_index.add(hash, id); + return id; +} + +#! Whether a value interned is the one given: the same in each field but its +#! parts and text, its float the same to the bit, and with the same parts, by +#! their own IDs, interned already, and the same text. +#! @param this The checker. +#! @param id The interned value's ID. +#! @param made The value, whose `parts` and `text` are given apart. +#! @param parts The IDs of its parts, in order. +#! @param text The bytes of text, which only text holds. +#! @returns Whether it is. +def checker::same_known(&this, id: u32, made: &known, parts: span, text: strview): bool { + val held: known = this.knowns.p[id]; + return false if held.kind != made.kind || held.of != made.of || held.decl != made.decl || held.op != made.op + || held.node != made.node || held.file != made.file + || held.value.negative != made.value.negative || held.value.magnitude != made.value.magnitude; + return false if made.kind == kk::real && real_bits(held.value.real) != real_bits(made.value.real); + return false if !this.known_parts.view(held.parts).equals(&parts); + return made.kind != kk::text || this.known_texts[held.text].view().equals(&text); +} + +#! The hash a value is interned by, of what `same_known` compares. +#! @param made The value, whose `parts` and `text` are given apart. +#! @param parts The IDs of its parts, in order. +#! @param text The bytes of text. +#! @returns The hash. +def known_hash(made: &known, parts: span, text: strview): u64 { + var hash := mix(mix(parts.length, made.kind as u64), made.of as u64); + hash = mix(hash, made.value.magnitude); + hash = mix(hash, pair_key(made.decl, made.value.negative ? 1 : 0)); + hash = mix(hash, pair_key(made.node, made.file)); + hash = mix(hash, made.op as u64); + if made.kind == kk::real { + hash = mix(hash, real_bits(made.value.real)); + } + for &each in parts { + hash = mix(hash, each as u64); + } + return mix(hash, text.hash()); +} + +#! The bits of a float, which tell apart what `==` does not, as `-0.0` from +#! `0.0`. +#! @param value The float. +#! @returns Its bits. +def real_bits(value: f64): u64 { + var held := value; + return ((&mut held) as *mut u64)[0]; +} + +#! The text a value holds. +#! @param this The checker. +#! @param id The value's ID. +#! @returns The bytes it holds. +pub def checker::known_text(&this, id: u32): strview { + return this.known_texts[this.knowns.p[id].text].view(); +} + +#! A number or float of the type. +#! @param this The checker. +#! @param value The number. +#! @param of Its type. +#! @returns Its ID. +pub def checker::known_number(&mut this, value: constant, of: u32): u32 { + var made := value; + val plain := this.unalias(of); + if this.types.kind_of(plain) == ty::floating && !made.floating { + made = constant::real_of(made.as_real()); + } + if made.floating && this.types.kind_of(plain) == ty::floating && this.types.first_of(plain) == 32 { + made = constant::real_of(made.real as f32 as f64); + } + return this.intern_known(known { kind = made.floating ? kk::real : kk::number, of = of, value = made }, + span::::empty(), ""); +} + +#! The value as one of the type it is wanted as, where the checker already let it +#! convert: an integer constant as `u64`, or as a float. A value already of the +#! type, or wanted as no type, is given back as it is. +#! @param this The checker. +#! @param id The value's ID. +#! @param of The type, or 0. +#! @returns The value's ID. +pub def checker::known_as(&mut this, id: u32, of: u32): u32 { + return id if id == 0 || of == 0 || of == bt::error; + val held: known = this.knowns.p[id]; + return id if held.of == of; + if held.kind == kk::number || held.kind == kk::real { + return this.known_number(held.value, of); + } + + var parts := vector::::new(); + parts.extend(this.known_view(id)); + var made := held; + made.of = of; + val text := held.kind == kk::text ? this.known_text(id) : ""; + return this.intern_known(made, parts.view(), text); +} + +#! Whether a value depends on constant parameters only each instance knows. +#! @param this The checker. +#! @param id The value's ID. +#! @returns Whether it does. +pub def checker::known_depends(&this, id: u32): bool { + return false if id == 0; + val kind: kk = this.knowns.p[id].kind; + return true if kind == kk::param || kind == kk::unary || kind == kk::binary || kind == kk::cast || kind == kk::opaque; + for &part in this.known_view(id) { + return true if this.known_depends(part); + } + return false; +} + +#! The type argument a value is, as a value of the type: the constant parameter +#! itself where it is one alone of that type, and otherwise the type holding the +#! value. +#! @param this The checker. +#! @param id The value's ID. +#! @returns The type. +pub def checker::known_type(&mut this, id: u32): u32 { + val held: known = this.knowns.p[id]; + if held.kind == kk::param && this.decls.targets.p[held.decl] == held.of { + return this.decls.types.p[held.decl]; + } + # One worked out from constant parameters holds them as its parts, so it stands + # for other values once they are given. + var params := vector::::new(); + this.known_params(id, &mut params, 0); + return this.types.intern(ty::value, held.of, id, params.view()); +} + +#! Gathers the types of the constant parameters a value is worked out from. +#! @param this The checker. +#! @param id The value's ID. +#! @param into Where each is added, once. +#! @param depth How deeply the search has gone. +def checker::known_params(&mut this, id: u32, into: &mut vector, depth: u32): void { + return if id == 0 || depth > 32; + val held: known = this.knowns.p[id]; + if held.kind == kk::param { + val kind: u32 = this.decls.types.p[held.decl]; + for &each in into.view() { + return if each == kind; + } + into.append(kind); + return; + } + for &part in this.known_view(id) { + this.known_params(part, into, depth + 1); + } +} + +#! The type with each type parameter `from` names replaced by the type `to` +#! gives at the same index, with each constant worked out from them once they +#! are known, as `N + 1` is `5` where `N` is given `4`, and a fixed array of a +#! length that is now a number holding that many. +#! @param this The checker. +#! @param kind The type. +#! @param from The type parameters to replace. +#! @param to The types to replace each with. +#! @returns The type made. +pub def checker::substitute(&mut this, kind: u32, from: span, to: span): u32 { + return kind if !this.types.is_open(kind) || from.length == 0; + if this.stand_ins.length != 0 && this.projects(from) { + return this.substitute_projected(kind, from, to); + } + val made := this.types.substitute(kind, from, to); + return this.types.holds_value(kind) ? this.settle_values(made, from, to, 0) : made; +} + +#! Whether a type parameter substitution replaces has types its bounds ask for +#! standing in for them, as `C` of `C::cursor`. +#! @param this The checker. +#! @param from The type parameters replaced. +#! @returns Whether one has. +def checker::projects(&this, from: span): bool { + for &each in this.stand_ins { + val base := this.types.first_of(each.base); + for ¶m in from { + return true if param == base; + } + } + return false; +} + +#! Substitutes the type parameters, and the parameters standing for the types +#! their bounds ask for with the types the types given for them give, as +#! `C::cursor` is `ctr` where `C` is given `one` and `type one::cursor = ctr`. +#! @param this The checker. +#! @param kind The type. +#! @param from The type parameters to replace. +#! @param to The types to replace each with. +#! @returns The type made. +def checker::substitute_projected(&mut this, kind: u32, from: span, to: span): u32 { + var wider := vector::::new(); + var given := vector::::new(); + for i in 0..from.length { + wider.append(from[i]); + given.append(i < to.length ? to[i] : bt::error); + } + # Asking may make more, which this substitution leaves. + val count := this.stand_ins.length; + for p in 0..count { + val each: checker::stand_in = this.stand_ins[p]; + for i in 0..from.length { + continue if from[i] != this.types.first_of(each.base) || i >= to.length; + val bound := this.types.substitute(each.bound, from, to); + wider.append(each.param); + given.append(this.asked_type(to[i], each.asked, bound)); + } + } + val made := this.types.substitute(kind, wider.view(), given.view()); + return this.types.holds_value(kind) ? this.settle_values(made, wider.view(), given.view(), 0) : made; +} + +#! Works out the constants within a type substitution made, as `substitute` +#! says. +#! @param this The checker. +#! @param kind The type substitution made. +#! @param from The type parameters it replaced. +#! @param to The types it replaced each with. +#! @param depth How deeply the search has gone. +#! @returns The type with its constants worked out. +def checker::settle_values(&mut this, kind: u32, from: span, to: span, depth: u32): u32 { + return kind if depth > 16; + val tkd := this.types.kind_of(kind); + if tkd == ty::value { + val id := this.types.second_of(kind); + val of := this.substitute(this.types.first_of(kind), from, to); + val made := this.known_as(this.known_subst(id, from, to), of); + return this.known_type(made); + } + if tkd == ty::fixed && this.types.part_count(kind) != 0 { + val element := this.settle_values(this.types.first_of(kind), from, to, depth + 1); + val length := this.settle_values(this.types.part_at(kind, 0), from, to, depth + 1); + if this.types.kind_of(length) == ty::value && !this.known_depends(this.types.second_of(length)) { + val count: known = this.knowns.p[this.types.second_of(length)]; + return bt::error if count.kind != kk::number || count.value.negative || count.value.magnitude > 0x1000000; + return this.types.fixed(element, count.value.magnitude as u32); + } + return this.types.fixed_of(element, length); + } + match tkd { + ty::reference, ty::pointer, ty::fixed => { + val inner := this.settle_values(this.types.first_of(kind), from, to, depth + 1); + return inner == this.types.first_of(kind) ? kind + : this.types.intern(tkd, inner, this.types.second_of(kind), span::::empty()); + } + ty::function, ty::named, ty::pack => { + var parts := vector::::new(); + var changed := false; + for i in 0..this.types.part_count(kind) { + val part := this.types.part_at(kind, i as u32); + val made := this.settle_values(part, from, to, depth + 1); + changed = changed || made != part; + parts.append(made); + } + var first := this.types.first_of(kind); + if tkd == ty::function { + val result := this.settle_values(first, from, to, depth + 1); + changed = changed || result != first; + first = result; + } + return changed ? this.types.intern(tkd, first, this.types.second_of(kind), parts.view()) : kind; + } + else => return kind; + } + return kind; +} + +#! Whether a type argument is a constant: a value, or within a template the +#! parameter standing for one. +#! @param this The checker. +#! @param kind The type. +#! @returns Whether it is. +pub def checker::is_constant_arg(&this, kind: u32): bool { + val tkd := this.types.kind_of(kind); + return tkd == ty::value || (tkd == ty::param && this.decls.has(this.types.first_of(kind), df::valued)); +} + +#! The type of the value a constant type argument stands for. +#! @param this The checker. +#! @param kind The constant type argument. +#! @returns The type of its value. +pub def checker::constant_type(&mut this, kind: u32): u32 { + if this.types.kind_of(kind) == ty::value { + return this.types.first_of(kind); + } + val decl := this.types.first_of(kind); + this.resolve(decl); + val of: u32 = this.decls.targets.p[decl]; + return of == 0 ? bt::error : of; +} + +#! The value a constant type argument stands for. +#! @param this The checker. +#! @param kind The constant type argument. +#! @returns The value's ID. +pub def checker::constant_known(&mut this, kind: u32): u32 { + return this.types.second_of(kind) if this.types.kind_of(kind) == ty::value; + return this.intern_known(known { kind = kk::param, of = this.constant_type(kind), decl = this.types.first_of(kind) }, + span::::empty(), ""); +} + +#! Decodes the escapes of text written between quotes, as the program holds it. +#! @param this The checker. +#! @param written The text between the quotes. +#! @param out Where the bytes are written. +pub def checker::decode_text(&this, written: strview, out: &mut string): void { + var i := 0u; + while i < written.length { + val c := written[i]; + if c != '\\' || i + 1 >= written.length { + out.push(c); + i++; + continue; + } + val e := written[i + 1]; + i += 2; + if e == 'n' { out.push('\n'); } + else if e == 't' { out.push('\t'); } + else if e == 'r' { out.push('\r'); } + else if e == '0' { out.push('\0'); } + else if e == 'x' && i + 1 < written.length { + val high := written.substr(i, 2); + out.push(this.read_hex(high) as u8); + i += 2; + } else { + out.push(e); + } + } +} + +#! The value of the field of a struct type at a position, or 0. +#! @param this The checker. +#! @param kind The struct or union type. +#! @param name The ID of the field's name. +#! @returns The field's position, or `no_length` where it has none of the name. +def checker::field_index(&mut this, kind: u32, name: u32): u32 { + val plain := this.unalias(kind); + return checker::no_length if this.types.kind_of(plain) != ty::named; + val decl := this.types.first_of(plain); + val run: u32 = this.decls.children.p[decl]; + var at: u32 = 0; + for &field in this.decls.list_view(run) { + continue if this.decls.kinds.p[field] != dk::field; + return at if this.decls.names.p[field] == name; + at++; + } + return checker::no_length; +} + +#! The value a type is zeroed as, which a struct literal leaving out a field gives +#! it: 0, `false`, `null`, empty text, the member of value 0, a union's first +#! field, and each field's default or zero value, or 0 where it has none. +#! @param this The checker. +#! @param kind The type. +#! @param depth How deeply the search has gone. +#! @returns The value's ID, or 0. +def checker::known_zero(&mut this, kind: u32, depth: u32): u32 { + return 0 if depth > 16; + val plain := this.unalias(kind); + match this.types.kind_of(plain) { + ty::boolean, ty::signed, ty::unsigned, ty::floating => return this.known_number(constant {}, kind); + ty::pointer => return this.intern_known(known { kind = kk::null_lit, of = kind }, span::::empty(), ""); + ty::fixed => { + return 0 if this.types.part_count(plain) != 0; + var parts := vector::::new(); + val element := this.types.first_of(plain); + for _ in 0..this.types.second_of(plain) { + val zero := this.known_zero(element, depth + 1); + return 0 if zero == 0; + parts.append(zero); + } + return this.intern_known(known { kind = kk::fields, of = kind }, parts.view(), ""); + } + ty::named => {} + else => return 0; + } + + val decl := this.types.first_of(plain); + if this.decls.kinds.p[decl] == dk::enum_type { + return this.known_number(constant {}, kind); + } + if this.is_std(plain, word::span) || this.is_std(plain, word::slice) { + val element := this.types.part_count(plain) != 0 ? this.unalias(this.types.part_at(plain, 0)) : bt::error; + if element == bt::uint8 || element == bt::int8 { + return this.intern_known(known { kind = kk::text, of = kind }, span::::empty(), ""); + } + return this.intern_known(known { kind = kk::fields, of = kind }, span::::empty(), ""); + } + + val kinds := this.field_types(plain); + if this.decls.kinds.p[decl] == dk::union_type { + return 0 if kinds.length == 0; + val zero := this.known_zero(kinds[0], depth + 1); + return 0 if zero == 0; + var parts := vector::::new(); + parts.append(zero); + return this.intern_known(known { kind = kk::held, of = kind }, parts.view(), ""); + } + if this.decls.kinds.p[decl] != dk::struct_type { + return 0; + } + + var parts := vector::::new(); + val run: u32 = this.decls.children.p[decl]; + var at: u64 = 0; + for i in 0..this.decls.list_length(run) { + val field := this.decls.list_at(run, i as u32); + continue if this.decls.kinds.p[field] != dk::field; + val default := this.field_default(field); + val made := default != 0 + ? this.known_in(this.decls.files.p[field], default, kinds[at], depth + 1) + : this.known_zero(kinds[at], depth + 1); + return 0 if made == 0; + parts.append(made); + at++; + } + return this.intern_known(known { kind = kk::fields, of = kind }, parts.view(), ""); +} + +#! The value of an expression of another file, worked out over that file's +#! results, as a constant's value or a field's default. +#! @param this The checker. +#! @param file The file. +#! @param node The expression. +#! @param of The type it is wanted as, or 0. +#! @param depth How deeply the search has gone. +#! @returns The value's ID, or 0. +def checker::known_in(&mut this, file: u32, node: u32, of: u32, depth: u32): u32 { + return this.known_of(node, of, depth) if file == this.at.file; + val saved := this.at; + this.use_table(this.units[file].table); + val made := this.known_of(node, of, depth); + this.at = saved; + return made; +} + +#! The value of an integer or float once converted to a type, as `as` converts +#! it: wrapped to an integer's bits, as a float, or as the member of an enum it is +#! the value of. Anything else is only renamed, as a pointer cast to another. +#! @param this The checker. +#! @param id The value's ID. +#! @param to The type. +#! @returns The value's ID, or 0 where none converts. +def checker::known_convert(&mut this, id: u32, to: u32): u32 { + val held: known = this.knowns.p[id]; + val plain := this.unalias(to); + val tkd := this.types.kind_of(plain); + if tkd == ty::signed || tkd == ty::unsigned { + return 0 if held.kind != kk::number && held.kind != kk::real; + var value := held.value; + if value.floating { + # Toward zero, saturating at the ends of the range, with NaN as 0. + val bits := this.types.first_of(plain); + val half := (1u << (bits - 1) as u64) as f64; + val low := tkd == ty::signed ? -half : 0.0; + val high := tkd == ty::signed ? half : 2.0 * half; + val real := value.real; + if real != real { + value = constant {}; + } else if real <= low { + value = tkd == ty::signed ? constant::integer(1u << (bits - 1) as u64, true) : constant {}; + } else if real >= high { + value = tkd == ty::signed ? constant::integer((1u << (bits - 1) as u64) - 1, false) + : constant::from_bits(bits == 64 ? 0xFFFFFFFFFFFFFFFFu : (1u << bits as u64) - 1, false); + } else { + value = real < 0.0 ? constant::integer((-real) as u64, true) : constant::integer(real as u64, false); + } + } + return this.known_number(this.ev_wrap(value, plain), to); + } + if tkd == ty::floating { + return 0 if held.kind != kk::number && held.kind != kk::real; + return this.known_number(constant::real_of(held.value.as_real()), to); + } + if this.named_kind(plain) == dk::enum_type && held.kind == kk::number { + return this.known_number(held.value, to); + } + return this.known_as(id, to); +} + +#! The value of a binary operator between two values worked out, or 0 where it +#! has none, as dividing by zero or overflowing has none. +#! @param this The checker. +#! @param operator The operator. +#! @param a One value. +#! @param b The other. +#! @param of The type it gives. +#! @returns The value's ID, or 0. +def checker::known_compute(&mut this, operator: tk, a: u32, b: u32, of: u32): u32 { + val x: known = this.knowns.p[a]; + val y: known = this.knowns.p[b]; + val comparison := operator.compares(); + if (x.kind == kk::number || x.kind == kk::real) && (y.kind == kk::number || y.kind == kk::real) { + var out := constant {}; + if operator == tk::modulo && (x.value.floating || y.value.floating) { + out = constant::real_of(x.value.as_real() % y.value.as_real()); + } else if !this.fold_binary(operator, &x.value, &y.value, x.value.negative || y.value.negative || this.types.is_signed(this.unalias(of)), &mut out) { + return 0; + } + return this.known_number(out, comparison || operator == tk::logand || operator == tk::logor ? bt::boolean : of); + } + + # Text is equal where it holds the same bytes. + if x.kind == kk::text && y.kind == kk::text && (operator == tk::equals || operator == tk::noteq) { + val same := this.known_text(a) == this.known_text(b); + return this.known_number(constant::truth(operator == tk::equals ? same : !same), bt::boolean); + } + return 0; +} + +#! A value worked out from constant parameters, kept as the expression over them. +#! @param this The checker. +#! @param kind The kind of expression. +#! @param node The expression's node. +#! @param parts The values it is worked out from. +#! @returns The value's ID. +def checker::known_over(&mut this, kind: kk, node: u32, parts: span): u32 { + var made := known { kind = kind, of = this.type_at(node), op = this.token_kind(node) }; + if kind == kk::opaque { + made.node = node; + made.file = this.at.file; + } + return this.intern_known(made, parts, ""); +} + +#! Works out the value a checked expression gives, which is what a constant +#! argument is: a literal, a `const`, a member of an enum, a function, `null`, +#! the address of a constant, a struct, union, or array literal of those, a +#! field or element of one, and arithmetic, comparisons, and conversions over +#! them. Within a template, what depends on its constant parameters is kept as +#! the expression over them. +#! @param this The checker. +#! @param node The expression. +#! @param of The type it is wanted as, or 0. +#! @param depth How deeply the search has gone. +#! @returns The value's ID, or 0 where it cannot be worked out. +pub def checker::known_of(&mut this, node: u32, of: u32, depth: u32): u32 { + return 0 if node == 0 || depth > 32; + + # A value converts where the checker said it does: a union holds it, or a view + # is of an array's elements. + val converts := this.converted(node); + if converts != 0 && converts != this.type_at(node) && converts != bt::error { + val raw := this.known_raw(node, 0, depth); + return 0 if raw == 0; + val plain := this.unalias(converts); + if this.named_kind(plain) == dk::union_type && !this.known_depends(raw) { + val kinds := this.field_types(plain); + val have: u32 = this.knowns.p[raw].of; + var index: u32 = 0; + for i in 0..kinds.length { + if this.unalias(kinds[i]) == this.unalias(this.settle(have)) { + index = i as u32; + break; + } + } + var parts := vector::::new(); + parts.append(this.known_as(raw, kinds.length != 0 ? kinds[index] : 0)); + val held := this.intern_known(known { kind = kk::held, of = converts, value = constant::integer(index as u64, false) }, + parts.view(), ""); + return this.known_as(held, of); + } + return this.known_as(this.known_as(raw, converts), of); + } + return this.known_raw(node, of, depth); +} + +#! The value of an expression as it is, before any conversion the checker made. +#! @param this The checker. +#! @param node The expression. +#! @param of The type it is wanted as, or 0. +#! @param depth How deeply the search has gone. +#! @returns The value's ID, or 0. +def checker::known_raw(&mut this, node: u32, of: u32, depth: u32): u32 { + val gives := of != 0 ? of : this.settle(this.type_at(node)); + if this.is_known(node) { + return this.known_number(this.value_at(node), gives); + } + + match this.kind_of(node) { + nk::number => { + val text := this.text_of(node); + var value := constant {}; + if this.token_kind(node) == tk::float { + value = constant::real_of(this.read_real(text)); + } else if !this.read_integer(text, &mut value) { + return 0; + } + return this.known_number(value, gives); + } + nk::boolean => return this.known_number(constant::truth(this.token_kind(node) == tk::kw_true), gives); + nk::character => return this.known_number(constant::integer(this.read_character(this.text_of(node)), false), gives); + nk::string => { + val written := this.text_of(node); + return 0 if written.length < 2; + var bytes := string::new(nothing {}); + if written.length >= 6 && written.starts_with("\"\"\"") { + this.literal_text(written, &mut bytes); + } else { + this.decode_text(written.substr(1, written.length - 2), &mut bytes); + } + return this.intern_known(known { kind = kk::text, of = gives }, span::::empty(), bytes.view()); + } + nk::null_lit => return this.intern_known(known { kind = kk::null_lit, of = gives }, span::::empty(), ""); + nk::name, nk::path, nk::type_name => { + val ref := this.ref_at(node); + return 0 if ref == 0 || (ref & ref_local) != 0; + if (ref & ref_type) != 0 { + val kind := ref & ref_mask; + return 0 if !this.is_constant_arg(kind); + return this.known_as(this.constant_known(kind), of); + } + if this.decls.kinds.p[ref] == dk::function { + return this.intern_known(known { kind = kk::function, of = gives, decl = ref }, span::::empty(), ""); + } + if this.decls.kinds.p[ref] == dk::variable && this.decls.has(ref, df::constant) { + this.resolve(ref); + val value := this.record_in(ref, variable_slot::value); + return 0 if value == 0; + return this.known_as(this.known_in(this.decls.files.p[ref], value, this.decls.types.p[ref], depth + 1), of); + } + return 0; + } + nk::unary => { + val operand := this.known_of(this.left_of(node), 0, depth + 1); + return 0 if operand == 0; + var parts := vector::::new(); + parts.append(operand); + return this.known_over(kk::unary, node, parts.view()) if this.known_depends(operand); + val held: known = this.knowns.p[operand]; + if held.kind == kk::real && this.token_kind(node) == tk::minus { + return this.known_number(constant::real_of(-held.value.real), gives); + } + return 0; + } + nk::binary => { + val left := this.known_of(this.left_of(node), 0, depth + 1); + val right := this.known_of(this.right_of(node), 0, depth + 1); + return 0 if left == 0 || right == 0; + if this.known_depends(left) || this.known_depends(right) { + var parts := vector::::new(); + parts.append(left); + parts.append(right); + return this.known_over(kk::binary, node, parts.view()); + } + val own := this.type_at(node); + return this.known_as(this.known_compute(this.token_kind(node), left, right, + this.types.is_untyped(own) ? gives : own), of); + } + nk::cast => { + val operand := this.known_of(this.left_of(node), 0, depth + 1); + return 0 if operand == 0; + if this.known_depends(operand) { + var parts := vector::::new(); + parts.append(operand); + return this.known_over(kk::cast, node, parts.view()); + } + return this.known_as(this.known_convert(operand, this.type_at(node)), of); + } + nk::ternary => { + val condition := this.known_of(this.left_of(node), 0, depth + 1); + return 0 if condition == 0; + return this.known_over(kk::opaque, node, span::::empty()) if this.known_depends(condition); + return this.known_of(this.record(node, condition_holds(this.knowns.p[condition]) ? if_slot::then : if_slot::other), of, depth + 1); + } + nk::construct => return this.known_as(this.known_literal(node, depth), of); + nk::array => { + val made := this.type_at(node); + val plain := this.unalias(made); + val element := this.types.kind_of(plain) == ty::fixed ? this.types.first_of(plain) : 0; + var parts := vector::::new(); + val run := this.left_of(node); + for &item in this.run_view(run) { + val each := this.known_of(item, element, depth + 1); + return 0 if each == 0; + parts.append(each); + } + return this.known_as(this.intern_known(known { kind = kk::fields, of = made }, parts.view(), ""), of); + } + nk::reference, nk::type_ref => { + val operand := this.left_of(node); + return 0 if this.kind_of(operand) != nk::name && this.kind_of(operand) != nk::path + && this.kind_of(operand) != nk::type_name; + val ref := this.ref_at(operand); + return 0 if ref == 0 || (ref & (ref_local | ref_type)) != 0; + return 0 if this.decls.kinds.p[ref] != dk::variable || !this.decls.has(ref, df::constant); + return this.intern_known(known { kind = kk::address, of = gives, decl = ref }, span::::empty(), ""); + } + nk::member => { + val object := this.left_of(node); + val held := this.type_at(object); + val plain := this.unalias(this.reached(held)); + # The length of a fixed array only each instance knows is its constant. + if this.types.kind_of(plain) == ty::fixed && this.types.part_count(plain) != 0 + && this.name_of(node) == word::length { + return this.known_as(this.constant_known(this.types.part_at(plain, 0)), of); + } + val whole := this.known_of(object, 0, depth + 1); + return 0 if whole == 0; + return this.known_over(kk::opaque, node, span::::empty()) if this.known_depends(whole); + val got: known = this.knowns.p[whole]; + if got.kind == kk::text && this.name_of(node) == word::length { + return this.known_number(constant::integer(this.known_text(whole).length, false), gives); + } + return 0 if got.kind != kk::fields; + val index := this.field_index(got.of, this.name_of(node)); + return 0 if index == checker::no_length || index >= this.known_count(whole); + return this.known_as(this.known_part(whole, index), of); + } + nk::index => { + val whole := this.known_of(this.left_of(node), 0, depth + 1); + val at := this.known_of(this.right_of(node), 0, depth + 1); + return 0 if whole == 0 || at == 0; + return this.known_over(kk::opaque, node, span::::empty()) + if this.known_depends(whole) || this.known_depends(at); + val index: known = this.knowns.p[at]; + return 0 if index.kind != kk::number || index.value.negative; + val got: known = this.knowns.p[whole]; + if got.kind == kk::fields && index.value.magnitude < this.known_count(whole) as u64 { + return this.known_as(this.known_part(whole, index.value.magnitude as u32), of); + } + if got.kind == kk::text && index.value.magnitude < this.known_text(whole).length { + val byte := this.known_text(whole)[index.value.magnitude]; + return this.known_number(constant::integer(byte as u64, false), gives); + } + return 0; + } + else => return 0; + } + return 0; +} + +#! Whether a condition worked out holds. +#! @param value The condition's value. +#! @returns Whether it holds. +def condition_holds(value: known): bool { + return value.value.magnitude != 0; +} + +#! A node of a declaration's record, as its value, in the file declaring it. +#! @param this The checker. +#! @param decl The declaration. +#! @param index The record's slot. +#! @returns The node, or 0. +def checker::record_in(&this, decl: u32, index: u32): u32 { + val syntax := &this.units[this.decls.files.p[decl]].syntax; + val record := syntax.node_lefts[this.decls.nodes.p[decl]]; + return syntax.extras[record as u64 + index as u64]; +} + +#! The value of a struct or union literal: each field it is given, and each it +#! is not its default or zero value, or the one field a union holds. +#! @param this The checker. +#! @param node The `construct` node. +#! @param depth How deeply the search has gone. +#! @returns The value's ID, or 0. +def checker::known_literal(&mut this, node: u32, depth: u32): u32 { + val made := this.type_at(node); + val plain := this.unalias(made); + return 0 if this.types.kind_of(plain) != ty::named; + val decl := this.types.first_of(plain); + val kinds := this.field_types(plain); + val inits := this.right_of(node); + + if this.decls.kinds.p[decl] == dk::union_type { + return this.known_zero(made, depth + 1) if this.run_length(inits) == 0; + val init := this.run_at(inits, 0); + val index := this.field_index(plain, this.name_of(init)); + return 0 if index == checker::no_length; + val value := this.known_of(this.left_of(init), kinds[index], depth + 1); + return 0 if value == 0; + var parts := vector::::new(); + parts.append(value); + return this.intern_known(known { kind = kk::held, of = made, value = constant::integer(index as u64, false) }, + parts.view(), ""); + } + return 0 if this.decls.kinds.p[decl] != dk::struct_type; + + var parts := vector::::new(); + parts.resize(kinds.length); + var position: u32 = 0; + for &init in this.run_view(inits) { + var index := position; + if this.node_has(init, nf::named) { + index = this.field_index(plain, this.name_of(init)); + } else { + position++; + } + return 0 if index == checker::no_length || index as u64 >= kinds.length; + val value := this.known_of(this.left_of(init), kinds[index], depth + 1); + return 0 if value == 0; + parts[index] = value; + } + + # Each field left out is its default, or its zero value. + val run: u32 = this.decls.children.p[decl]; + var at: u64 = 0; + for i in 0..this.decls.list_length(run) { + val field := this.decls.list_at(run, i as u32); + continue if this.decls.kinds.p[field] != dk::field; + if parts[at] == 0 { + val default := this.field_default(field); + val value := default != 0 + ? this.known_in(this.decls.files.p[field], default, kinds[at], depth + 1) + : this.known_zero(kinds[at], depth + 1); + return 0 if value == 0; + parts[at] = value; + } + at++; + } + return this.intern_known(known { kind = kk::fields, of = made }, parts.view(), ""); +} + +#! What a value depending on constant parameters is once they are given types, +#! worked out where every one it depends on is known. +#! @param this The checker. +#! @param id The value's ID. +#! @param from The type parameters given types. +#! @param to The type given each. +#! @returns The value's ID. +pub def checker::known_subst(&mut this, id: u32, from: span, to: span): u32 { + return id if id == 0 || !this.known_depends(id); + val held: known = this.knowns.p[id]; + if held.kind == kk::param { + for i in 0..from.length { + continue if from[i] != held.decl || i >= to.length; + val given := to[i]; + return this.known_as(this.constant_known(given), held.of) if this.is_constant_arg(given); + return id; + } + return id; + } + return id if held.kind == kk::opaque; + + var parts := vector::::new(); + var changed := false; + var depends := false; + for i in 0..this.known_count(id) { + val part := this.known_part(id, i as u32); + val made := this.known_subst(part, from, to); + changed = changed || made != part; + depends = depends || this.known_depends(made); + parts.append(made); + } + return id if !changed; + + if !depends { + if held.kind == kk::binary { + val made := this.known_compute(held.op, parts[0], parts[1], held.of); + return made if made != 0; + } else if held.kind == kk::cast { + val made := this.known_convert(parts[0], held.of); + return made if made != 0; + } else if held.kind == kk::unary { + val operand: known = this.knowns.p[parts[0]]; + if held.op == tk::minus && operand.kind == kk::real { + return this.known_number(constant::real_of(-operand.value.real), held.of); + } + if held.op == tk::minus && operand.kind == kk::number { + return this.known_number(constant::integer(operand.value.magnitude, !operand.value.negative), held.of); + } + if held.op == tk::negate && operand.kind == kk::number { + return this.known_number(constant::truth(operand.value.magnitude == 0), held.of); + } + if held.op == tk::bitnot && operand.kind == kk::number { + return this.known_number(this.ev_wrap(constant::from_bits(~operand.value.bits(), true), this.unalias(held.of)), held.of); + } + } + } + return this.intern_known(held, parts.view(), ""); +} + +#! Writes how a value is spelled, as it is written: `4`, `true`, `color::red`, +#! `"text"`, `point{ x = 1, y = 2 }`, or `N + 1`. +#! @param this The checker. +#! @param id The value's ID. +#! @param out Where it is written. +#! @param depth How deeply the writing has gone. +pub def checker::describe_known(&this, id: u32, out: &mut string, depth: u32): void { + if depth > 8 || id == 0 { + out.append("..."); + return; + } + + val held: known = this.knowns.p[id]; + val plain := this.unaliased(held.of); + match held.kind { + kk::number => { + if this.types.kind_of(plain) == ty::boolean || this.types.kind_of(plain) == ty::untyped_bool { + out.append(held.value.magnitude != 0 ? "true" : "false"); + return; + } + if this.named_kind(plain) == dk::enum_type { + val decl := this.types.first_of(plain); + val run: u32 = this.decls.children.p[decl]; + for &member in this.decls.list_view(run) { + var value := constant {}; + continue if !this.decl_value(member, &mut value); + if value.magnitude == held.value.magnitude && value.negative == held.value.negative { + out.append(this.decl_text(decl)); + out.append("::"); + out.append(this.decl_text(member)); + return; + } + } + } + val text := $"{held.value.negative ? "-" : ""}{held.value.magnitude}"; + out.append(text.view()); + } + kk::real => { + val text := $"{held.value.real}"; + out.append(text.view()); + if !text.view().contains('.') && !text.view().contains('e') && !text.view().contains('n') { + out.append(".0"); + } + } + kk::text => { + out.append("\""); + for &byte in this.known_text(id) { + if byte == '"' || byte == '\\' { + out.push('\\'); + out.push(byte); + } else if byte == '\n' { + out.append("\\n"); + } else if byte == '\t' { + out.append("\\t"); + } else if byte < 0x20 || byte == 0x7F { + val hex := "0123456789ABCDEF"; + out.append("\\x"); + out.push(hex[(byte >> 4) as u64]); + out.push(hex[(byte & 0xF) as u64]); + } else { + out.push(byte); + } + } + out.append("\""); + } + kk::fields => { + # A struct names its fields, and an array or a view lists its elements. + val decl := this.types.kind_of(plain) == ty::named ? this.types.first_of(plain) : 0; + val named := decl != 0 && this.decls.kinds.p[decl] == dk::struct_type + && this.decls.names.p[decl] != word::span && this.decls.names.p[decl] != word::slice; + if named { + this.describe_into(held.of, out, depth + 1); + out.append("{"); + } else { + out.append("["); + } + var field_at: u32 = 0; + val run: u32 = named ? this.decls.children.p[this.types.first_of(plain)] : 0; + for i in 0..this.known_count(id) { + out.append(i == 0 ? (named ? " " : "") : ", "); + if named { + while field_at < this.decls.list_length(run) && this.decls.kinds.p[this.decls.list_at(run, field_at)] != dk::field { + field_at++; + } + if field_at < this.decls.list_length(run) { + out.append(this.decl_text(this.decls.list_at(run, field_at))); + out.append(" = "); + field_at++; + } + } + this.describe_known(this.known_part(id, i as u32), out, depth + 1); + } + out.append(named ? (this.known_count(id) != 0 ? " }" : "}") : "]"); + } + kk::held => { + this.describe_into(held.of, out, depth + 1); + out.append("{ "); + if this.types.kind_of(plain) == ty::named { + val run: u32 = this.decls.children.p[this.types.first_of(plain)]; + var at: u64 = 0; + for &field in this.decls.list_view(run) { + continue if this.decls.kinds.p[field] != dk::field; + if at == held.value.magnitude { + out.append(this.decl_text(field)); + out.append(" = "); + } + at++; + } + } + this.describe_known(this.known_part(id, 0), out, depth + 1); + out.append(" }"); + } + kk::null_lit => out.append("null"); + kk::function => out.append(this.decl_text(held.decl)); + kk::address => { + out.append("&"); + out.append(this.decl_text(held.decl)); + } + kk::param => out.append(this.decl_text(held.decl)); + kk::unary => { + out.append(operator_text(held.op)); + this.describe_known(this.known_part(id, 0), out, depth + 1); + } + kk::binary => { + for i in 0..2 { + val part := this.known_part(id, i as u32); + val grouped := this.knowns.p[part].kind == kk::binary; + if i != 0 { + out.append(" "); + out.append(operator_text(held.op)); + out.append(" "); + } + out.append(grouped ? "(" : ""); + this.describe_known(part, out, depth + 1); + out.append(grouped ? ")" : ""); + } + } + kk::cast => { + this.describe_known(this.known_part(id, 0), out, depth + 1); + out.append(" as "); + this.describe_into(held.of, out, depth + 1); + } + kk::opaque => out.append("..."); + kk::invalid => out.append("?"); + } +} + +#! The type at the end of its aliases, without resolving anything. +#! @param this The checker. +#! @param kind The type. +#! @returns The type it stands for. +def checker::unaliased(&this, kind: u32): u32 { + var at := kind; + var steps := 0; + while this.is_alias(at) && steps < 32 { + val target: u32 = this.decls.targets.p[this.types.first_of(at)]; + break if target == 0; + at = target; + steps++; + } + return at; +} + +#! The spelling of an operator a value over constant parameters is worked out +#! with. +#! @param operator The operator. +#! @returns Its spelling. +def operator_text(operator: tk): strview { + return match operator { + tk::plus => "+", tk::minus => "-", tk::star => "*", tk::slash => "/", + tk::modulo => "%", tk::bitand => "&", tk::bitor => "|", tk::bitxor => "^", + tk::bitnot => "~", tk::lshift => "<<", tk::rshift => ">>", tk::equals => "==", + tk::noteq => "!=", tk::less => "<", tk::lesseq => "<=", tk::more => ">", + tk::moreeq => ">=", tk::logand => "&&", tk::logor => "||", tk::negate => "!", + else => "?" + }; +} + +#! The value a constant parameter's name gives: the constant its instance is +#! given, known while checking where it is a number, or within the template, a +#! value of its type only each instance knows. +#! @param this The checker. +#! @param node The node naming it. +#! @param kind The constant type argument it names. +#! @returns The type of its value. +pub def checker::constant_ref(&mut this, node: u32, kind: u32): u32 { + if this.types.kind_of(kind) == ty::value { + val held: known = this.knowns.p[this.types.second_of(kind)]; + if held.kind == kk::number || held.kind == kk::real { + this.set_value(node, held.value); + } + } + return this.constant_type(kind); +} + +#! Whether a node is a type as written, rather than a value. +#! @param this The checker. +#! @param node The node. +#! @returns Whether it is. +def checker::is_type_node(&this, node: u32): bool { + return match this.kind_of(node) { + nk::type_name, nk::type_ref, nk::type_ptr, nk::type_fixed, nk::type_func, nk::type_spread, nk::type_of, nk::error => true, + else => false + }; +} + +#! The type argument a generic's type parameter is given by what is written for +#! it: a type, or for a constant parameter, the value written, worked out while +#! checking. +#! @param this The checker. +#! @param node What is written. +#! @param decl The generic declaration. +#! @param index The parameter's position among the declaration's, its owner's +#! first. +#! @param given The type arguments given the parameters before it. +#! @returns The type argument, or the error type. +pub def checker::type_arg_of(&mut this, node: u32, decl: u32, index: u32, given: span): u32 { + # With patterns among its type parameters, what is written at a place is given + # to the type parameter written there, and to a pattern's the parts of it. + val params: u32 = decl != 0 ? this.decls.params.p[decl] : 0; + val written: u32 = decl != 0 && this.has_patterns(decl) + ? this.param_written_at(decl, index) + : index < this.decls.list_length(params) ? this.decls.list_at(params, index) : 0; + if written != 0 { + val param := written; + if this.decls.has(param, df::valued) { + this.resolve(param); + var from := vector::::new(); + for i in 0..given.length { + break if i >= this.decls.list_length(params) as u64; + from.append(this.decls.list_at(params, i as u32)); + } + val wanted := this.substitute(this.decls.targets.p[param], from.view(), given); + return this.constant_arg(node, wanted, param, decl); + } + if !this.is_type_node(node) && !this.decls.has(param, df::packed) { + var text := string::from("`", nothing {}); + text.append(this.decl_text(param)); + text.append("` of `"); + text.append(this.decl_text(decl)); + text.append("` takes a type, so it is not given a value."); + this.report_text(node, ec::generic, &text); + this.infer_expr(node); + return bt::error; + } + } + if !this.is_type_node(node) { + this.report(node, ec::generic, "A value is given only to a constant parameter, as `N` of `struct buffer`."); + this.infer_expr(node); + return bt::error; + } + + # `Ts...` passes a pack on, which gives its types where it is written. + if this.kind_of(node) == nk::type_spread { + val made := this.resolve_type(this.left_of(node)); + if made != bt::error && this.types.kind_of(made) != ty::pack { + this.report(node, ec::generic, "Only a pack is passed on with `...`, as `Ts...`."); + return bt::error; + } + return made; + } + val made := this.resolve_type(node); + if this.types.kind_of(made) == ty::pack { + this.report(node, ec::generic, "A pack is passed on among type arguments written `Ts...`."); + return bt::error; + } + return made; +} + +#! The type argument a constant parameter is given by what is written for it: +#! the value of the expression, worked out while checking, as a value of the +#! parameter's type where that is known. A name written alone was read as a +#! type, and is the constant it names, and `&table` the address of one. +#! @param this The checker. +#! @param node What is written. +#! @param wanted The parameter's type, given the arguments before it. +#! @param param The constant parameter. +#! @param decl The generic declaration. +#! @returns The type argument, or the error type. +def checker::constant_arg(&mut this, node: u32, wanted: u32, param: u32, decl: u32): u32 { + val known_type := wanted != bt::error && !this.types.is_open(wanted); + var kind: u32 = bt::error; + val written := this.kind_of(node); + if written == nk::type_name || (written == nk::type_ref && this.kind_of(this.left_of(node)) == nk::type_name) { + # A name read as a type is the constant it names, and `&table` the address of + # one. A name of a type is a type given where a value is wanted. + val named := written == nk::type_ref ? this.left_of(node) : node; + if this.names_type(named) { + var text := string::from("`", nothing {}); + text.append(this.decl_text(param)); + text.append("` of `"); + text.append(this.decl_text(decl)); + text.append("` is a constant, so it is given a value, not the type `"); + text.append(this.names.text(this.segment_name(named, 0))); + text.append("`."); + this.report_text(named, ec::generic, &text); + return bt::error; + } + kind = this.constant_name(named, written == nk::type_ref ? bt::error : wanted); + return bt::error if kind == bt::error; + if written == nk::type_ref { + kind = this.types.reference(kind, this.node_has(node, nf::mutable)); + this.set_type(node, kind); + if known_type && !this.convert(node, wanted) { + return bt::error; + } + } + } else if this.is_type_node(node) && written != nk::error { + var text := string::from("`", nothing {}); + text.append(this.decl_text(param)); + text.append("` of `"); + text.append(this.decl_text(decl)); + text.append("` is a constant, so it is given a value rather than a type."); + this.report_text(node, ec::generic, &text); + return bt::error; + } else { + kind = known_type ? this.check_expr(node, wanted) : this.infer_expr(node); + } + return bt::error if kind == bt::error; + + val of := known_type ? wanted : this.settle(kind); + val id := this.known_of(node, of, 0); + if id == 0 { + var text := string::from("`", nothing {}); + text.append(this.decl_text(param)); + text.append("` of `"); + text.append(this.decl_text(decl)); + text.append("` is given a constant, which is worked out while checking: a literal, a `const`, a member of an enum, a function, `null`, the address of a constant, a struct, union, or array literal of those, or arithmetic over them."); + this.report_text(node, ec::constant, &text); + return bt::error; + } + + val held: known = this.knowns.p[id]; + val plain := this.unalias(of); + if held.kind == kk::number && (this.types.kind_of(plain) == ty::signed || this.types.kind_of(plain) == ty::unsigned) + && !this.in_range(plain, &held.value) { + var text := string::from("The constant is outside the range of `", nothing {}); + val shown := this.describe(of); + text.append(shown.view()); + text.append("`."); + this.report_text(node, ec::overflow, &text); + return bt::error; + } + return this.known_type(id); +} + +#! Whether a type name of one segment names a type, rather than a constant. +#! @param this The checker. +#! @param node The `type_name` node. +#! @returns Whether it does. +def checker::names_type(&mut this, node: u32): bool { + return false if this.segment_count(node) != 1; + val bound := this.bound(this.segment_name(node, 0)); + return !this.is_constant_arg(bound & ref_mask) if (bound & ref_type) != 0; + return false if bound != 0; + val decl := this.lookup_type(this.segment_name(node, 0), 0); + return decl != 0 && this.is_type_decl(decl); +} + +#! Checks a name or path written as a type as the value it names, recording +#! what it refers to and its type as an expression's. +#! @param this The checker. +#! @param node The `type_name` node. +#! @param wanted The type expected, or the error type. +#! @returns Its type, or the error type. +def checker::constant_name(&mut this, node: u32, wanted: u32): u32 { + var kind: u32 = bt::error; + if this.segment_count(node) == 1 { + val name := this.segment_name(node, 0); + val ref := this.lookup(name, node); + if ref == 0 { + this.report_undeclared(node, name); + return bt::error; + } + kind = this.ref_value(node, ref, wanted); + } else { + val target := this.path_target(node); + return bt::error if target.decl == 0; + kind = this.decl_value_of(node, target.decl, wanted); + } + this.set_type(node, kind); + this.set_flag(node, rf::checked); + return bt::error if kind == bt::error; + if wanted != bt::error && !this.types.is_open(wanted) && !this.convert(node, wanted) { + return bt::error; + } + return kind; +} diff --git a/analyzer/checker/lifetimes.sakura b/analyzer/checker/lifetimes.sakura new file mode 100644 index 00000000..94e2ac60 --- /dev/null +++ b/analyzer/checker/lifetimes.sakura @@ -0,0 +1,491 @@ +#! @file lifetimes.sakura +#! @author John Christman (sorakatadzuma@gmail.com) +#! @copyright Malunal Studios, LLC. +#! @license MIT +#! +#! Contains the lifetime warnings: where a function keeps a reference past what +#! it refers to, as the checker is sure of it. A reference, a view, or an +#! anonymous function refers to the locals it names, which end where their +#! scopes do, and to a value a statement makes, which ends with the statement +#! unless a name is bound to it. Nothing keeps what they refer to alive, so one +#! that outlives it dangles, which is the program's mistake, as in C++. +#! +#! The checker is sure of what it sees written: a value refers to a local where +#! it is `&` of the local's own storage, a `val` bound to such a value, an +#! anonymous function naming the local, or a struct, union, or array literal +#! holding one. It is sure the value outlives the local where it is returned +#! from the function declaring the local, or written into a global, into what +#! a parameter refers or points to, or into a local of a scope around the +#! local's. A value a statement makes outlives it where it is returned, written +#! anywhere, or held in a literal a name is bound to. What a call does with +#! what it is given, the checker does not follow, and says nothing of. +#! +#! Only functions that are no generic's are walked, so each warning is said +#! once, and `@allow` quiets those of a function. + +import std::containers; +module sakura::analyzer; + + +#! What a value refers to, as far as the checker is sure. +enum lifetime_kind : u8 { + none, #! Nothing it is sure of. + local, #! A local, as `local` says. + temporary, #! A value its statement makes. +} + +#! What a value refers to, the local where it is one, and the node of the +#! value saying so: the `&`, the slice, the anonymous function, or the `val` +#! named, within any literal holding it. +struct lifetime_ref { + var kind: lifetime_kind; #! What it is. + var local: u32; #! The node declaring the local, where it is one. + var at: u32; #! The node saying so, which a warning is made at. +} + +#! What a walk of a function's body holds. One is kept by the checker and +#! walks each function in turn, so what it holds is made once. +struct lifetime_walk { + var scopes: vector; #! The scopes it is within, innermost last: the function, then each block, loop, test, arm, and anonymous function. + var functions: vector; #! The function and the anonymous functions within it it is within, innermost last. + var nodes: vector; #! The nodes each node being walked holds, which it walks in turn, those of the nodes around it before them. + var notes: column; #! What was noted of each node of the file that may declare a local, by the node. + var walk: u32; #! Which walk this is, counted from 1, so what earlier walks noted is told apart without being cleared. + var depth: u32; #! How deeply the walk is nested, which a body nested past `lifetime_depth` stops. +} + +#! Where a node that may declare a local is: its scope, and the function or +#! anonymous function it is in, as the walk that noted them found them. +struct lifetime_note { + var scope: u32; #! The scope it is in. + var owner: u32; #! The function or anonymous function it is in. + var walk: u32; #! The walk that noted them. +} + +#! Makes a walk, which walks nothing until `check_lifetimes` starts it. +#! @returns The walk. +def lifetime_walk::new(): lifetime_walk { + return lifetime_walk { + scopes = vector::::new(), + functions = vector::::new(), + nodes = vector::::new(), + notes = column::::new() + }; +} + +#! What the walk noted of a node, or nothing noted where it noted nothing. +#! @param this The walk. +#! @param node The node. +#! @returns The note. +def lifetime_walk::note_of(&this, node: u32): lifetime_note { + if (node as u64) < this.notes.length { + val held: lifetime_note = this.notes.p[node]; + return held if held.walk == this.walk; + } + return lifetime_note {}; +} + +#! How deeply a walk goes before it stops, saying nothing of what is deeper. +const lifetime_depth: u32 = 400; + +#! Warns of where a function's body keeps a reference past what it refers to, +#! unless it is a generic's, which each instance would warn of again, or is +#! `@allow`. +#! @param this The checker. +#! @param id The function's declaration. +pub def checker::check_lifetimes(&mut this, id: u32): void { + return if this.decls.has(id, df::generic) || this.decls.has(id, df::allows) || this.decls.has(id, df::accessor); + val node: u32 = this.decls.nodes.p[id]; + return if node == 0 || this.kind_of(node) != nk::function; + val walk := &mut this.lifetimes; + walk.walk++; + walk.scopes.clear(); + walk.functions.clear(); + walk.nodes.clear(); + walk.depth = 0; + this.lifetime_visit(walk, node); +} + +#! Walks a node, noting where what it declares is, then warns of what it keeps +#! past what that refers to. +#! @param this The checker. +#! @param walk The walk. +#! @param node The node. +def checker::lifetime_visit(&mut this, walk: &mut lifetime_walk, node: u32): void { + return if node == 0 || walk.depth >= lifetime_depth; + val kind := this.kind_of(node); + if kind == nk::variable || kind == nk::param || kind == nk::name || kind == nk::reference { + if walk.scopes.length != 0 { + walk.notes.put(node, lifetime_note { scope = walk.scopes.last(), owner = walk.functions.last(), walk = walk.walk }); + } + } + + val function := kind == nk::function || kind == nk::lambda; + val scope := function || kind == nk::block || kind == nk::for_stmt || kind == nk::if_stmt + || kind == nk::while_stmt || kind == nk::match_arm; + if function { + walk.functions.append(node); + } + if scope { + walk.scopes.append(node); + } + + # Only what was checked is walked: of a `when` or an `if const`, the branch + # taken, and of a block, the statements up to one decided to leave it. The + # nodes a node holds are put on the walk's, past those of the nodes around + # it, walked from there, and taken off again. + val mark := walk.nodes.length; + match kind { + nk::when_block => walk.nodes.append(this.when_branch(node)); + nk::if_const => { + val condition := this.left_of(node); + if this.is_known(condition) { + walk.nodes.append(this.value_at(condition).magnitude != 0 ? this.record(node, if_slot::then) : this.record(node, if_slot::other)); + } + } + nk::block => { + val run := this.left_of(node); + for i in 0..this.run_length(run) { + val each := this.run_at(run, i as u32); + walk.nodes.append(each); + break if this.lifetime_skips(each); + } + } + else => this.syn().children(node, &mut walk.nodes); + } + val end := walk.nodes.length; + walk.depth++; + for i in mark..end { + this.lifetime_visit(walk, walk.nodes[i]); + } + walk.depth--; + if end != mark { + walk.nodes.resize(mark); + } + + match kind { + nk::return_stmt => this.lifetime_returned(walk, this.left_of(node)); + nk::lambda => { + # A lambda whose body is a value returns it. + val body := this.record(node, lambda_slot::body); + if body != 0 && this.kind_of(body) != nk::block { + this.lifetime_returned(walk, body); + } + } + nk::assign => { + if this.token_kind(node) == tk::assign { + this.lifetime_written(walk, this.left_of(node), this.right_of(node)); + } + } + nk::variable => { + # A name bound to a value its statement makes refers to it as long as + # the name lives, but a literal holding a reference to one does not. + val value := this.record(node, variable_slot::value); + if value != 0 && this.kind_of(value) != nk::reference { + val held := this.lifetime_of(walk, value, 0); + if held.kind == lifetime_kind::temporary { + this.warn(held.at, ec::lifetime, + "The value referred to is made in the statement, and ends with it, so the value holding a reference to it outlives it. Bound to a name, as `val p := &point { x = 1 };`, a value lives as long as the name."); + } + } + } + else => {} + } + + if scope { + walk.scopes.truncate(); + } + if function { + walk.functions.truncate(); + } +} + +#! Warns where a value returned refers to a local of the function returning it, +#! or to a value the `return` makes. +#! @param this The checker. +#! @param walk The walk. +#! @param value The value returned, or 0. +def checker::lifetime_returned(&mut this, walk: &mut lifetime_walk, value: u32): void { + return if value == 0 || walk.functions.length == 0; + val held := this.lifetime_of(walk, value, 0); + if held.kind == lifetime_kind::temporary { + this.warn(held.at, ec::lifetime, "The value returned refers to a value made in the statement, which ends with it."); + return; + } + return if held.kind != lifetime_kind::local || walk.note_of(held.local).owner != walk.functions.last(); + var text := string::from("The value returned refers to `", nothing {}); + text.append(this.names.text(this.local_name(held.local))); + text.append("`, which ends as the function returns."); + this.warn_text(held.at, ec::lifetime, &text, held.local); +} + +#! Warns where a value written to a place refers to a local the place outlives, +#! or to a value the statement makes. +#! @param this The checker. +#! @param walk The walk. +#! @param target The place written. +#! @param value The value written. +def checker::lifetime_written(&mut this, walk: &mut lifetime_walk, target: u32, value: u32): void { + return if this.kind_of(target) == nk::name && this.names.text(this.name_of(target)) == "_"; + val held := this.lifetime_of(walk, value, 0); + if held.kind == lifetime_kind::temporary { + this.warn(held.at, ec::lifetime, + "The value referred to is made in the statement, and ends with it, so the reference written here outlives it. Bound to a name, as `val p := &point { x = 1 };`, a value lives as long as the name."); + return; + } + return if held.kind != lifetime_kind::local; + + # The local or global whose storage the place is within, and whether it is + # reached through a reference or pointer. + var at := target; + var through := false; + var steps := 0; + while steps < 64 { + steps++; + val kind := this.kind_of(at); + if kind == nk::member || kind == nk::index || kind == nk::slice { + val object := this.left_of(at); + val held_type := this.types.kind_of(this.unalias(this.type_at(object))); + if kind == nk::member { + through = through || held_type == ty::reference || held_type == ty::pointer; + } else { + through = through || held_type != ty::fixed; + } + at = object; + continue; + } + if kind == nk::unary && this.token_kind(at) == tk::star { + through = true; + at = this.left_of(at); + continue; + } + break; + } + return if this.kind_of(at) != nk::name; + val ref := this.ref_at(at); + return if ref == 0 || (ref & ref_type) != 0; + + var outlives := false; + var into := string::new(nothing {}); + if (ref & ref_local) == 0 { + # A global outlives every local. + outlives = this.decls.kinds.p[ref & ref_mask] == dk::variable; + into.append("a global"); + } else { + val root := ref & ref_mask; + if through { + # What a parameter refers or points to is the caller's, which outlives + # every local of the function. + val root_type := this.types.kind_of(this.unalias(this.type_at(root))); + outlives = this.kind_of(root) == nk::param && (root_type == ty::reference || root_type == ty::pointer); + into.append("what `"); + into.append(this.names.text(this.local_name(root))); + into.append("` refers to"); + } else { + # A local of a scope around the local's outlives it. + val outer := this.lifetime_scope(walk, root); + val inner := this.lifetime_scope(walk, held.local); + outlives = outer >= 0 && inner >= 0 && outer < inner; + into.append("`"); + into.append(this.names.text(this.local_name(root))); + into.append("`"); + } + } + return if !outlives; + var text := string::from("`", nothing {}); + text.append(this.names.text(this.local_name(held.local))); + text.append("` ends where its scope does, so the reference written to "); + text.append(into.view()); + text.append(" outlives it."); + this.warn_text(held.at, ec::lifetime, &text, held.local); +} + +#! Where among the scopes the walk is within a local is declared. +#! @param this The checker. +#! @param walk The walk. +#! @param local The node declaring the local. +#! @returns The index of its scope, or -1 where it is in none of them. +def checker::lifetime_scope(&this, walk: &lifetime_walk, local: u32): i64 { + val scope := walk.note_of(local).scope; + return -1 if scope == 0; + for i in 0..walk.scopes.length { + return i as i64 if walk.scopes[i] == scope; + } + return -1; +} + +#! What a value refers to, as far as the checker is sure. +#! @param this The checker. +#! @param walk The walk. +#! @param node The value. +#! @param depth How many `val`s it was followed through. +#! @returns What it refers to. +def checker::lifetime_of(&mut this, walk: &lifetime_walk, node: u32, depth: u32): lifetime_ref { + val none := lifetime_ref { kind = lifetime_kind::none }; + return none if node == 0 || depth > 8; + match this.kind_of(node) { + nk::reference => { + val inner := this.left_of(node); + if this.is_place(inner) { + val root := this.lifetime_root(inner); + return root != 0 ? lifetime_ref { kind = lifetime_kind::local, local = root, at = node } : none; + } + # `&` of a reference refers to what it does, which is not known. + val given := this.types.kind_of(this.unalias(this.type_at(inner))); + return given == ty::reference ? none : lifetime_ref { kind = lifetime_kind::temporary, at = node }; + } + nk::slice => { + val object := this.left_of(node); + val held := this.types.kind_of(this.unalias(this.type_at(object))); + return none if held != ty::fixed || !this.is_place(object); + val root := this.lifetime_root(object); + return root != 0 ? lifetime_ref { kind = lifetime_kind::local, local = root, at = node } : none; + } + nk::name => { + # A `val` refers to what its value does, and one bound to a value its + # statement makes refers to it as long as the `val` lives. + val ref := this.ref_at(node); + return none if (ref & ref_local) == 0; + val local := ref & ref_mask; + return none if this.kind_of(local) != nk::variable || this.node_has(local, nf::mutable); + val value := this.record(local, variable_slot::value); + return none if value == 0; + val held := this.lifetime_of(walk, value, depth + 1); + if held.kind == lifetime_kind::temporary { + return this.kind_of(value) == nk::reference ? lifetime_ref { kind = lifetime_kind::local, local = local, at = node } : none; + } + return held.kind == lifetime_kind::none ? none : lifetime_ref { kind = held.kind, local = held.local, at = node }; + } + nk::lambda => { + # An anonymous function refers to the locals around it that it names. + var held := this.lifetime_captured(walk, node); + held.at = node; + return held; + } + nk::construct => { + for &each in this.run_view(this.right_of(node)) { + val held := this.lifetime_of(walk, this.left_of(each), depth); + return held if held.kind != lifetime_kind::none; + } + return none; + } + nk::array => { + for &each in this.run_view(this.left_of(node)) { + val held := this.lifetime_of(walk, each, depth); + return held if held.kind != lifetime_kind::none; + } + return none; + } + else => return none; + } +} + +#! The local an anonymous function names that a function around it declares, +#! the one declared first where it names several. +#! @param this The checker. +#! @param walk The walk. +#! @param node The `lambda` node. +#! @returns The local, or nothing it is sure of. +def checker::lifetime_captured(&mut this, walk: &lifetime_walk, node: u32): lifetime_ref { + var todo := vector::::new(); + this.syn().children(node, &mut todo); + var seen := 0; + var first: u32 = 0; + while todo.length != 0 && seen < 4096 { + seen++; + val at: u32 = todo.last(); + todo.truncate(); + if this.kind_of(at) == nk::name { + val ref := this.ref_at(at); + if (ref & ref_local) != 0 { + val local := ref & ref_mask; + val owner := walk.note_of(local).owner; + if owner != 0 && walk.functions.view().contains(&owner) + && (first == 0 || this.node_offset_of(local) < this.node_offset_of(first)) { + first = local; + } + } + } + this.syn().children(at, &mut todo); + } + return first != 0 ? lifetime_ref { kind = lifetime_kind::local, local = first } : lifetime_ref { kind = lifetime_kind::none }; +} + +#! The local whose own storage a place is within, past fields and the elements +#! of fixed arrays it holds as values. A local that is a reference names what +#! it refers to, so a place within it is within no local the checker knows. +#! @param this The checker. +#! @param node The place. +#! @returns The node declaring the local, or 0 where the place is not within one. +def checker::lifetime_root(&mut this, node: u32): u32 { + var at := node; + var steps := 0; + while steps < 64 { + steps++; + val kind := this.kind_of(at); + if kind == nk::member || kind == nk::index { + val object := this.left_of(at); + val held := this.types.kind_of(this.unalias(this.type_at(object))); + return 0 if kind == nk::member && (held == ty::reference || held == ty::pointer); + return 0 if kind == nk::index && held != ty::fixed; + if kind == nk::member { + val ref := this.ref_at(at); + return 0 if ref == 0 || (ref & (ref_local | ref_type)) != 0 || this.decls.kinds.p[ref] != dk::field; + } + at = object; + continue; + } + break; + } + return 0 if this.kind_of(at) != nk::name; + val ref := this.ref_at(at); + return 0 if (ref & ref_local) == 0; + val held := this.types.kind_of(this.unalias(this.type_at(ref & ref_mask))); + return held == ty::reference ? 0 : ref & ref_mask; +} + +#! Whether a statement leaves where it was decided while checking, so the +#! checker checked nothing after it, as the emitter's `skips` says. +#! @param this The checker. +#! @param node The statement. +#! @returns Whether it does. +def checker::lifetime_skips(&mut this, node: u32): bool { + match this.kind_of(node) { + nk::block => { + val run := this.left_of(node); + for i in 0..this.run_length(run) { + return true if this.lifetime_skips(this.run_at(run, i as u32)); + } + } + nk::when_block => return this.lifetime_skips(this.when_branch(node)); + nk::if_const => { + val condition := this.left_of(node); + return false if !this.is_known(condition); + val then := this.record(node, if_slot::then); + val other := this.record(node, if_slot::other); + if this.value_at(condition).magnitude != 0 { + return this.lifetime_skips(then) || (other == 0 && this.has_flag(then, rf::leaves)); + } + return other != 0 && this.lifetime_skips(other); + } + else => {} + } + return false; +} + +#! Where in the file a node's token begins. +#! @param this The checker. +#! @param node The node. +#! @returns The token's offset. +def checker::node_offset_of(&this, node: u32): u32 { + val syntax := &this.syn(); + return syntax.token_offsets[syntax.node_tokens[node]]; +} + +#! The name a local is declared with. +#! @param this The checker. +#! @param local The node declaring it. +#! @returns The name's ID. +def checker::local_name(&this, local: u32): u32 { + return this.name_of(local); +} diff --git a/analyzer/checker/link.sakura b/analyzer/checker/link.sakura new file mode 100644 index 00000000..17dc8c79 --- /dev/null +++ b/analyzer/checker/link.sakura @@ -0,0 +1,297 @@ +#! @file link.sakura +#! @author John Christman (sorakatadzuma@gmail.com) +#! @copyright Malunal Studios, LLC. +#! @license MIT +#! +#! Contains the linking of what every file declared: each file's imports are +#! found among the modules declared, and each declaration made through a type, +#! as `vec2::length` or `list::iter`, becomes a member of its type, with the +#! type parameters its receiver names. A nested type may itself wait for its +#! type, so those whose types are not yet members wait for another pass. + +module sakura::analyzer; + + +#! Links the imports and the declarations made through types. +#! @param this The checker. +pub def checker::link(&mut this): void { + var imports := vector::>::new(); + for _ in 0..this.units.length { + imports.append(vector::::new()); + } + + for i in 0..this.pending_imports.length { + val each := this.pending_imports[i]; + val file := pair_high(each); + val node := pair_low(each); + this.use_table(this.units[file].table); + + val found := this.module_path(this.left_of(node), false); + if found == 0 { + this.report(node, ec::undefined, "No file declares this module."); + continue; + } + imports[file].append(found); + } + + for file in 0..this.units.length { + val run := this.decls.make_list(imports[file].view()); + this.units[file].imports = run; + } + + this.attach_pending(); + this.give_accessors_params(); +} + +#! Makes each declaration made through a type a member of it. Each pass attaches +#! what it can. One whose type is a nested type not yet attached waits for the +#! next, and what is left when a pass attaches nothing names no type. +#! @param this The checker. +def checker::attach_pending(&mut this): void { + var waiting := vector::::new(); + waiting.extend(this.pending.view()); + + var progress := true; + while progress && waiting.length != 0 { + progress = false; + var later := vector::::new(); + for &id in waiting { + if this.attach(id, false) { + progress = true; + } else { + later.append(id); + } + } + waiting = move(&mut later); + } + + for &id in waiting { + this.attach(id, true); + } +} + +#! Gives each accessor its property's type parameters, which its receiver named. +#! @param this The checker. +def checker::give_accessors_params(&mut this): void { + for id in 1..this.decls.count { + continue if !this.decls.has(id as u32, df::accessor) || this.decls.kinds.p[id] == dk::none; + val params: u32 = this.decls.params.p[this.decls.owners.p[id]]; + this.decls.params.p[id] = params; + if params != 0 { + this.decls.mark(id as u32, df::generic); + } + } +} + +#! Makes the declaration a member of the type its receiver names. +#! @param this The checker. +#! @param id The declaration. +#! @param last Whether this is the last chance, which reports a receiver +#! naming no type rather than waiting. +#! @returns Whether it was attached, or reported. +def checker::attach(&mut this, id: u32, last: bool): bool { + val saved := this.at; + this.use_table(this.units[this.decls.files.p[id]].table); + this.at.home = this.decls.modules.p[id]; + # A receiver is a path from the module, which no type around it shortens. + this.at.scope = 0; + + val node: u32 = this.decls.nodes.p[id]; + val receiver := this.receiver_of(node); + this.decls.top = this.decls.tops.p[id]; + val owner := this.receiver_decl(receiver, last); + if owner == 0 { + this.at = saved; + this.decls.top = 0; + if last { + this.decls.mark(id, df::failed); + } + return last; + } + + # What a trait asks for is declared within it. Through it, outside it, only + # functions of its own are, which take no `this`. + if this.decls.kinds.p[owner] == dk::trait_type + && (this.decls.kinds.p[id] != dk::function || this.decls.has(id, df::method)) { + this.report(receiver, ec::invalid, + "A trait has no methods, associated variables, or nested types declared outside it. What it asks for is declared within it, and outside it only functions of its own, which take no `this`, as `def real::parse(text: strview)`."); + this.decls.mark(id, df::failed); + this.at = saved; + this.decls.top = 0; + return true; + } + # A function of the trait's own takes a name it does not ask for. + if this.decls.kinds.p[owner] == dk::trait_type { + val asked := this.decls.member(owner, this.decls.names.p[id]); + if asked != 0 && this.decls.owners.p[asked] == owner && !this.receiver_declared(asked) { + this.report(node, ec::duplicate, "The trait already asks for a member of this name."); + this.decls.mark(id, df::failed); + this.at = saved; + this.decls.top = 0; + return true; + } + } + + # Each segment of the receiver names the type parameters of the type it + # names, as `T` of `box::get`, which the declaration takes first. + var params := vector::::new(); + var level := owner; + for step in 0..this.segment_count(receiver) { + val index := this.segment_count(receiver) - 1 - step as u32; + val named := this.segment_args(receiver, index); + val made := this.declare_params(named, id); + # A `where` bounding the type's parameters further makes the method one only + # the types meeting it have. + for &written in this.run_view(named) { + if this.kind_of(written) == nk::type_param && this.left_of(written) != 0 { + this.decls.mark(id, df::bounding); + } + } + for k in 0..made.length { + params.insert_at(k, made[k]); + } + + # Each stands for a parameter of the type, whose bounds it takes. + val wanted := this.own_param_count(level); + val owned: u32 = this.decls.params.p[level]; + val total := this.decls.list_length(owned); + for k in 0..made.length { + if k < wanted as u64 && total >= wanted { + val source := this.decls.list_at(owned, total - wanted + k as u32); + val param: u32 = made[k]; + this.mirrors.put(param, source); + # A constant parameter of the type is named a constant here too. + if this.decls.has(source, df::valued) { + this.decls.mark(param, df::valued); + } else if this.kind_of(this.decls.nodes.p[param]) == nk::const_param { + this.report(this.decls.nodes.p[param], ec::generic, + "A type parameter of the type is named here without `const`."); + } + } + } + if made.length as u32 != wanted && level != 0 { + var text := string::from("`", nothing {}); + text.append(this.decl_text(level)); + val words := $"` takes {wanted} type parameters, which a declaration through it names, as `box::get`."; + text.append(words.view()); + this.report_text(this.segment_node(receiver, index), ec::generic, &text); + } + level = this.decls.owners.p[level]; + break if level == 0 || this.decls.kinds.p[level] == dk::none; + } + + # A variable of a generic type would be one for each of its instances, which + # nothing makes, so it is declared through an alias of one, as `vec3f::zero`. + if this.decls.kinds.p[id] == dk::variable && params.length != 0 { + this.report(receiver, ec::invalid, + "A generic type has no variables of its own, since each instance would need its own; declare it through an alias of one instance, as `val vec3f::zero`."); + this.decls.mark(id, df::failed); + } + + val own: u32 = this.decls.params.p[id]; + params.extend(this.decls.list_view(own)); + this.decls.params.p[id] = this.decls.make_list(params.view()); + if params.length != 0 { + this.decls.mark(id, df::generic); + } + + this.add_member(owner, id); + this.decls.top = 0; + this.at = saved; + return true; +} + +#! How many type parameters a type declares of its own, not counting those of +#! the type it is nested in. +#! @param this The checker. +#! @param id The type's declaration. +#! @returns How many. +pub def checker::own_param_count(&this, id: u32): u32 { + return 0 if id == 0 || this.decls.kinds.p[id] == dk::builtin; + + val saved_file: u32 = this.decls.files.p[id]; + val syntax := &this.units[saved_file].syntax; + val node: u32 = this.decls.nodes.p[id]; + val kind := syntax.node_kinds[node]; + return 0 if kind != nk::struct_decl && kind != nk::union_decl && kind != nk::trait_decl + && kind != nk::alias && kind != nk::function; + + # A pattern, `def(Ts...): R` or `L[N]`, declares one for each type parameter it + # names. + val record := syntax.node_lefts[node]; + var made: u32 = 0; + for &each in syntax.run_view(syntax.extras[record as u64 + decl_slot::type_params as u64]) { + if syntax.node_kinds[each] == nk::array_pattern { + made += syntax.node_rights[each] != 0 ? 2 : 1; + continue; + } + if syntax.node_kinds[each] != nk::type_pattern { + made++; + continue; + } + val inner := syntax.node_lefts[each]; + made += syntax.run_length(inner) + (syntax.node_rights[each] != 0 ? 1 : 0); + } + return made; +} + +#! The type declaration a receiver names, or 0 where it names none yet. +#! @param this The checker. +#! @param receiver The receiver's `type_name` node. +#! @param last Whether this is the last chance, which reports a receiver +#! naming no type. +#! @returns The declaration, or 0. +def checker::receiver_decl(&mut this, receiver: u32, last: bool): u32 { + var at: u32 = 0; + var home: u32 = 0; + var in_module := false; + for i in 0..this.segment_count(receiver) { + val name := this.segment_name(receiver, i as u32); + if i == 0 { + at = this.lookup_global(name, 0); + if at == 0 { + home = this.lookup_module(name); + in_module = home != 0; + } + } else if in_module { + at = this.modules.decl(home, name); + if at == 0 { + home = this.modules.find(home, name); + in_module = home != 0; + } else { + in_module = false; + } + } else { + at = this.decls.path_member(at, name); + } + + if at == 0 && !in_module { + if last { + this.report(this.segment_node(receiver, i as u32), ec::not_type, + "A declaration is made through a type, and this names none."); + } + return 0; + } + } + + return 0 if in_module; + if !this.is_type_decl(at) { + if last { + this.report(receiver, ec::not_type, "A declaration is made through a type, and this names none."); + } + return 0; + } + return at; +} + +#! Whether the declaration declares a type. +#! @param this The checker. +#! @param id The declaration. +#! @returns Whether it does. +pub def checker::is_type_decl(&this, id: u32): bool { + return match this.decls.kinds.p[id] { + dk::builtin, dk::struct_type, dk::union_type, dk::enum_type, dk::trait_type, + dk::alias_type, dk::type_param, dk::assoc_type => true, + else => false + }; +} diff --git a/analyzer/checker/lookup.sakura b/analyzer/checker/lookup.sakura new file mode 100644 index 00000000..abfa0e2a --- /dev/null +++ b/analyzer/checker/lookup.sakura @@ -0,0 +1,453 @@ +#! @file lookup.sakura +#! @author John Christman (sorakatadzuma@gmail.com) +#! @copyright Malunal Studios, LLC. +#! @license MIT +#! +#! Contains how names are found where they are written. A name is first what +#! a scope binds it to, then what the types around it give, as `kind` within +#! `token` is `token::kind`, then a declaration of the module it is written in, +#! or of the modules holding that one, nearest first, then of the modules its +#! file imports, then a built-in type, then a declaration of `core`'s root. The program, where the files declaring +#! no module are, holds no module, so a module never names what it declares. A name a type gives that the module or +#! a module holding it declares too is ambiguous, as are two imports declaring +#! the name, unless they declare the same thing. + +module sakura::analyzer; + + +#! What the name refers to where it is written, or 0 where nothing declares it. +#! @param this The checker. +#! @param name The ID of the name. +#! @param node Where the name is written, for reporting it ambiguous, or 0. +#! @returns A local or type parameter with its bit of `ref_local` or `ref_type`, +#! a declaration, or 0. +pub def checker::lookup(&mut this, name: u32, node: u32): u32 { + val bound := this.bound(name); + return bound if bound != 0; + return this.lookup_global(name, node); +} + +#! The declaration the name refers to outside any scope, or 0. +#! @param this The checker. +#! @param name The ID of the name. +#! @param node Where the name is written, for reporting it ambiguous, or 0. +#! @returns The declaration, or 0. +pub def checker::lookup_global(&mut this, name: u32, node: u32): u32 { + return this.lookup_named(name, node, false).decl; +} + +#! The declaration the name refers to outside any scope where only a type is +#! meant, as in a type, or 0. +#! @param this The checker. +#! @param name The ID of the name. +#! @param node Where the name is written, for reporting it ambiguous, or 0. +#! @returns The declaration, or 0. +pub def checker::lookup_type(&mut this, name: u32, node: u32): u32 { + return this.lookup_named(name, node, true).decl; +} + +#! The declaration the name refers to outside any scope, and where a type +#! around it gives it, that type, given the arguments it has there. +#! @param this The checker. +#! @param name The ID of the name. +#! @param node Where the name is written, for reporting it ambiguous, or 0. +#! @param types Whether only a type is meant, so what else a type around it +#! gives is passed over, as a member `u8` of an enum is in `u8`. +#! @returns The declaration and the type giving it, or no declaration. +pub def checker::lookup_named(&mut this, name: u32, node: u32, types: bool): checker::found { + this.depend_name(name); + val scoped := this.in_scope(name, types); + var home := this.at.home; + var steps := 0; + while steps < 64 { + val found := this.modules.decl(home, name); + if found != 0 { + if scoped.decl != 0 && scoped.decl != found && node != 0 { + this.report_ambiguous(node, name, scoped.decl, found); + } + return scoped.decl != 0 ? scoped : checker::found { decl = found }; + } + # The program is where the files declaring no module are, so it holds no + # module: a module of one segment is within none. + break if home == 0 || this.modules.parents[home] == 0; + home = this.modules.parents[home]; + steps++; + } + return scoped if scoped.decl != 0; + + var found: u32 = 0; + var hidden: u32 = 0; + val imports: u32 = this.units[this.at.file].imports; + for &imported in this.decls.list_view(imports) { + val each := this.modules.decl(imported, name); + continue if each == 0; + if !this.visible(each) { + hidden = each; + continue; + } + + if found != 0 && found != each { + if node != 0 { + var text := string::from("More than one imported module declares `", nothing {}); + text.append(this.names.text(name)); + text.append("`, so write the module it is of, as `io::println`."); + this.report_text(node, ec::ambiguous, &text); + } + return checker::found { decl = found }; + } + found = each; + } + + return checker::found { decl = found } if found != 0; + if this.builtins.get(&name) is some(got) { + return checker::found { decl = got }; + } + + # Last, the names of `core`'s root, which every file sees, and which anything + # declared or imported hides. + val core := this.modules.find(0, word::core); + if core != 0 && core != this.at.home { + val each := this.modules.decl(core, name); + if each != 0 { + return checker::found { decl = each } if this.visible(each); + hidden = hidden != 0 ? hidden : each; + } + } + + # A declaration only hidden from where it is named is found, so what names + # it is told it is not `pub` rather than that it does not exist. + return checker::found { decl = hidden }; +} + +#! What the types around where checking is give the name, innermost first. +#! Within a type, and what is declared through it, its nested types and +#! associated variables, and an enum's members, are named without it, as +#! `kind` is `token::kind` within `token`. A field or method belongs to a value, +#! so it is named through one, and a type's functions are named through the +#! type, since they are often named for the free functions they implement, as +#! `vector::decode` calls `decode::`. +#! @param this The checker. +#! @param name The ID of the name. +#! @param types Whether only a type is meant. +#! @returns The member and the type giving it, or no member. +pub def checker::in_scope(&mut this, name: u32, types: bool): checker::found { + var kind := this.at.scope; + var steps := 0; + while kind != 0 && steps < 16 { + steps++; + val decl := this.type_decl(kind); + break if decl == 0; + val member := this.scope_member(decl, name, types); + return checker::found { decl = member, owner = kind } if member != 0; + + # A type nested in another is named within that one, whose arguments are + # the first of its own. + val outer: u32 = this.decls.owners.p[decl]; + break if outer == 0 || !this.gives_scope(outer); + kind = this.scope_type(outer, kind); + } + return checker::found {}; +} + +#! The member of the name a type gives the names within it, or 0. +#! @param this The checker. +#! @param decl The type's declaration. +#! @param name The ID of the name. +#! @param types Whether only a type is meant. +#! @returns The member, or 0. +def checker::scope_member(&mut this, decl: u32, name: u32, types: bool): u32 { + val nested := this.decls.member_in(decl, name, true); + if nested != 0 { + return this.visible(nested) ? nested : 0; + } + + val member := types ? 0 : this.decls.member_in(decl, name, false); + return 0 if member == 0 || !this.visible(member); + return match this.decls.kinds.p[member] { + dk::variable, dk::enum_member => member, + else => 0 + }; +} + +#! Whether a type gives the names within it: a struct, union, or enum, or a +#! built-in type. A trait gives its members `self` and the types it asks for. +#! @param this The checker. +#! @param decl The type's declaration. +#! @returns Whether it does. +pub def checker::gives_scope(&this, decl: u32): bool { + return match this.decls.kinds.p[decl] { + dk::struct_type, dk::union_type, dk::enum_type, dk::builtin => true, + else => false + }; +} + +#! The type giving the names within a declaration: the type itself, or the +#! one it is a member of or is declared through, given the arguments it is +#! checked with, or 0. +#! @param this The checker. +#! @param id The declaration. +#! @param args The pack of its type arguments, or 0 where it is checked as +#! itself. +#! @returns The type, or 0. +pub def checker::scope_of(&mut this, id: u32, args: u32): u32 { + var owner: u32 = this.decls.owners.p[id]; + var holder := id; + match this.decls.kinds.p[id] { + dk::type_param => return owner == 0 ? 0 : this.scope_of(owner, 0); + dk::struct_type, dk::union_type, dk::enum_type => return this.own_scope(id, id, args); + dk::field, dk::enum_member => return owner != 0 && this.gives_scope(owner) ? this.decls.types.p[owner] : 0; + dk::function, dk::variable, dk::property, dk::alias_type, dk::trait_type => {} + else => return 0; + } + + # An accessor is checked as a member of its property's type. + if owner != 0 && this.decls.kinds.p[owner] == dk::property { + holder = owner; + owner = this.decls.owners.p[owner]; + } + return 0 if owner == 0 || !this.gives_scope(owner); + return this.own_scope(owner, holder, args); +} + +#! A type, given the first of the arguments of a declaration within it, which +#! names the type's parameters first. +#! @param this The checker. +#! @param decl The type's declaration. +#! @param holder The declaration within it. +#! @param args The pack of the holder's type arguments, or 0 where it is +#! checked as itself. +#! @returns The type. +def checker::own_scope(&mut this, decl: u32, holder: u32, args: u32): u32 { + return this.decls.types.p[decl] if this.decls.kinds.p[decl] == dk::builtin; + val count := this.decls.list_length(this.decls.params.p[decl]); + val run: u32 = this.decls.params.p[holder]; + var given := vector::::new(); + for i in 0..count { + if args != 0 && i < this.types.part_count(args) { + given.append(this.types.part_at(args, i as u32)); + } else if i < this.decls.list_length(run) { + given.append(this.decls.types.p[this.decls.list_at(run, i as u32)]); + } else { + given.append(bt::error); + } + } + return this.types.named(decl, given.view()); +} + +#! A type a nested one is declared through, given the first of the nested +#! one's arguments. +#! @param this The checker. +#! @param outer The outer type's declaration. +#! @param inner The nested type, given its arguments. +#! @returns The outer type. +def checker::scope_type(&mut this, outer: u32, inner: u32): u32 { + return this.decls.types.p[outer] if this.decls.kinds.p[outer] == dk::builtin; + val count := this.decls.list_length(this.decls.params.p[outer]); + var given := vector::::new(); + for i in 0..count { + given.append(this.types.kind_of(inner) == ty::named && i < this.types.part_count(inner) + ? this.types.part_at(inner, i as u32) + : bt::error); + } + return this.types.named(outer, given.view()); +} + +#! Reports a name both a type around it and its module give, which only a +#! path tells apart. +#! @param this The checker. +#! @param node Where the name is written. +#! @param name The ID of the name. +#! @param scoped What the type gives it. +#! @param other What the module gives it. +def checker::report_ambiguous(&mut this, node: u32, name: u32, scoped: u32, other: u32): void { + var text := string::from("`", nothing {}); + text.append(this.names.text(name)); + text.append("` names both `"); + var first := this.path_text(scoped); + text.append(first.view()); + if this.decls.modules.p[other] == 0 && this.decls.owners.p[other] == 0 { + text.append("` and the program's own `"); + text.append(this.names.text(name)); + text.append("`, so write `"); + text.append(first.view()); + text.append("` for the first, or rename one of them."); + } else { + text.append("` and `"); + var second := this.path_text(other); + text.append(second.view()); + text.append("`, so write the path of the one meant."); + } + this.report_text(node, ec::ambiguous, &text); +} + +#! The path a declaration is written as from anywhere, as `token::kind` or +#! `std::io::println`. One declared outside any module has only its name. +#! @param this The checker. +#! @param id The declaration. +#! @returns The path. +pub def checker::path_text(&this, id: u32): string { + var made := string::new(nothing {}); + val owner: u32 = this.decls.owners.p[id]; + if owner != 0 && this.decls.kinds.p[id] != dk::type_param { + made = this.path_text(owner); + made.append("::"); + } else { + var modules := vector::::new(); + var at: u32 = this.decls.modules.p[id]; + var steps := 0; + while at != 0 && steps < 64 { + modules.append(at); + at = this.modules.parents[at]; + steps++; + } + var i := modules.length; + while i > 0 { + i--; + made.append(this.names.text(this.modules.names[modules[i]])); + made.append("::"); + } + } + made.append(this.names.text(this.decls.names.p[id])); + return made; +} + +#! Reports a name nothing declares where it is used. A module sees the names of +#! those holding it without an import, so where no file of one was read, as a +#! library's root left out, the note says so. +#! @param this The checker. +#! @param node The node naming it. +#! @param name The ID of the name. +pub def checker::report_undeclared(&mut this, node: u32, name: u32): void { + var text := string::from("`", nothing {}); + text.append(this.names.text(name)); + text.append("` is not declared where it is used."); + var at: u32 = this.at.home == 0 ? 0 : this.modules.parents[this.at.home]; + var steps := 0; + while at != 0 && steps < 64 { + if !this.modules.named[at] { + text.append(" No file of `"); + text.append(this.module_text(at).view()); + text.append("`, which holds this file's module and whose names it sees, was read: is one missing?"); + break; + } + at = this.modules.parents[at]; + steps++; + } + this.report_text(node, ec::undefined, &text); +} + +#! A module's path, as `std::io`. +#! @param this The checker. +#! @param id The module. +#! @returns The path. +pub def checker::module_text(&this, id: u32): string { + var made := string::new(nothing {}); + var at := id; + var steps := 0; + while at != 0 && steps < 64 { + var each := string::from(this.names.text(this.modules.names[at]), nothing {}); + if made.length != 0 { + each.append("::"); + each.append(made.view()); + } + made = move(&mut each); + at = this.modules.parents[at]; + steps++; + } + return made; +} + +#! The module the name refers to where it is written: one within the module it +#! is written in or a module holding it, or the last segment of an import. +#! @param this The checker. +#! @param name The ID of the name. +#! @returns The module, or 0. +pub def checker::lookup_module(&mut this, name: u32): u32 { + var home := this.at.home; + var steps := 0; + while steps < 64 { + val found := this.modules.find(home, name); + return found if found != 0; + break if home == 0; + home = this.modules.parents[home]; + steps++; + } + + val imports: u32 = this.units[this.at.file].imports; + for &imported in this.decls.list_view(imports) { + return imported if this.modules.names[imported] == name; + } + return 0; +} + +#! Whether the declaration can be named where checking is: it is `pub`, or +#! declared in the module checked or one holding it. +#! @param this The checker. +#! @param id The declaration. +#! @returns Whether it can. +pub def checker::visible(&this, id: u32): bool { + return true if this.decls.has(id, df::exported) || this.decls.kinds.p[id] == dk::builtin; + + # A property is seen where an accessor of it is `pub`, as `pub get`. + if this.decls.kinds.p[id] == dk::property { + val run: u32 = this.decls.children.p[id]; + for &each in this.decls.list_view(run) { + return true if this.decls.has(each, df::exported); + } + } + + # Enum members, and what a trait asks for, are as visible as their type. A + # field takes its own `pub`, as a method does. + val owner: u32 = this.decls.owners.p[id]; + val kind: dk = this.decls.kinds.p[id]; + if owner != 0 && (kind == dk::enum_member + || (this.decls.kinds.p[owner] == dk::trait_type && !this.receiver_declared(id))) { + return this.visible(owner); + } + + var home: u32 = this.decls.modules.p[id]; + return this.modules.within(this.at.home, home); +} + +#! Whether a trait asks for the declaration: it is declared within the trait, +#! or is an accessor of a property that is. A function declared through a +#! trait, outside it, as `def real::parse`, is the trait's own instead, +#! called through the trait's name as any type's static function is. +#! @param this The checker. +#! @param id The declaration. +#! @returns Whether it does. +pub def checker::trait_asks(&this, id: u32): bool { + var at := id; + var owner: u32 = this.decls.owners.p[id]; + if owner != 0 && this.decls.kinds.p[owner] == dk::property { + at = owner; + owner = this.decls.owners.p[owner]; + } + return owner != 0 && this.decls.kinds.p[owner] == dk::trait_type && !this.receiver_declared(at); +} + +#! Whether a trait's default is compiled for each type taking it, with `self` +#! that type, as the type's own methods are: one of a trait that is only a +#! bound, which no table calls through. Any other default is compiled once, +#! taking `this` as a reference to the trait. +#! @param this The checker. +#! @param id The method's declaration. +#! @returns Whether it is. +pub def checker::typed_default(&mut this, id: u32): bool { + return false if !this.trait_asks(id) || !this.has_body(id); + val holder := this.enclosing_trait(id); + return holder != 0 && holder != id && this.bound_only(holder); +} + +#! Whether a declaration was made through a type, outside it, rather than +#! within it, so it takes its own `pub`. +#! @param this The checker. +#! @param id The declaration. +#! @returns Whether it was. +pub def checker::receiver_declared(&this, id: u32): bool { + val syntax := &this.units[this.decls.files.p[id]].syntax; + val node: u32 = this.decls.nodes.p[id]; + val kind := syntax.node_kinds[node]; + return false if kind != nk::function && kind != nk::variable && kind != nk::property; + return syntax.extras[syntax.node_lefts[node] as u64 + decl_slot::receiver as u64] != 0; +} diff --git a/analyzer/checker/nodes.sakura b/analyzer/checker/nodes.sakura new file mode 100644 index 00000000..71c27f63 --- /dev/null +++ b/analyzer/checker/nodes.sakura @@ -0,0 +1,186 @@ +#! @file nodes.sakura +#! @author John Christman (sorakatadzuma@gmail.com) +#! @copyright Malunal Studios, LLC. +#! @license MIT +#! +#! Contains how the checker reads the nodes of the file it is checking: their +#! kinds, tokens, slots, records, and runs, and the names and text of tokens. + +module sakura::analyzer; + + +#! The syntax of the file being checked. +#! @param this The checker. +#! @returns The syntax. +pub def checker::syn(&this): &syntax { + return this.units[this.at.file].syntax; +} + +#! The source of the file being checked. +#! @param this The checker. +#! @returns The source. +pub def checker::src(&this): &source { + return this.units[this.at.file].source; +} + +#! The kind of a node of the file being checked. +#! @param this The checker. +#! @param node The node. +#! @returns Its kind. +pub def checker::kind_of(&this, node: u32): nk { + return this.at.kinds[node]; +} + +#! The token a node of the file being checked says what it is by. +#! @param this The checker. +#! @param node The node. +#! @returns The token's index. +pub def checker::token_of(&this, node: u32): u32 { + return this.at.tokens[node]; +} + +#! A node's first slot, which its kind's shape says the meaning of. +#! @param this The checker. +#! @param node The node. +#! @returns The slot. +pub def checker::left_of(&this, node: u32): u32 { + return this.at.lefts[node]; +} + +#! A node's second slot, which its kind's shape says the meaning of. +#! @param this The checker. +#! @param node The node. +#! @returns The slot. +pub def checker::right_of(&this, node: u32): u32 { + return this.at.rights[node]; +} + +#! The name the node's token is, as a declaration's name or a `name` node's. +#! @param this The checker. +#! @param node The node. +#! @returns The name's ID, or 0 where its token is no word. +pub def checker::name_of(&this, node: u32): u32 { + return this.at.names[this.at.tokens[node]]; +} + +#! The name a parameter is known by: its own, or of one an accessor implies, +#! whose token is the `get` or `set`, `this`, or a `set`'s `value`. +#! @param this The checker. +#! @param node The parameter's node, or any other. +#! @returns The ID of the name. +pub def checker::param_name(&this, node: u32): u32 { + return this.name_of(node) if this.kind_of(node) != nk::param || !this.node_has(node, nf::implied); + return this.name_of(node) == names::set_id && !this.node_has(node, nf::mutable) ? names::value_id : names::this_id; +} + +#! The kind of the node's token. +#! @param this The checker. +#! @param node The node. +#! @returns The kind. +pub def checker::token_kind(&this, node: u32): tk { + return this.at.tkinds[this.at.tokens[node]]; +} + +#! The text of the node's token, as it is written. +#! @param this The checker. +#! @param node The node. +#! @returns The text, which views the file's source. +pub def checker::text_of(&this, node: u32): strview { + val syntax := &this.syn(); + val token := this.token_of(node); + return this.src().make_lexeme(syntax.token_offsets[token], syntax.token_length(token, this.names)); +} + +#! The slot of the node's record at the index, in whichever of its slots its +#! shape says holds the record. +#! @param this The checker. +#! @param node The node. +#! @param index The slot's position in the record. +#! @returns The slot, or 0 where the node has no record. +pub def checker::record(&this, node: u32, index: u32): u32 { + val at: u32 = shapes[this.at.kinds[node] as u64].left == slot::extra ? this.at.lefts[node] : this.at.rights[node]; + return this.at.extras[at + index]; +} + +#! The flags of the node, wherever its shape keeps them. +#! @param this The checker. +#! @param node The node. +#! @returns The flags, as `nf` says, or 0. +pub def checker::node_flags(&this, node: u32): u32 { + return this.syn().flags_at(node); +} + +#! Whether a node has a flag. +#! @param this The checker. +#! @param node The node. +#! @param flag The flag. +#! @returns Whether it has it. +pub def checker::node_has(&this, node: u32, flag: nf): bool { + return (this.node_flags(node) & flag as u32) != 0; +} + +#! How many nodes a run of the file being checked holds. +#! @param this The checker. +#! @param run Where the run begins. +#! @returns How many nodes it holds. +pub def checker::run_length(&this, run: u32): u32 { + return this.at.extras[run]; +} + +#! A node of a run, by its position. +#! @param this The checker. +#! @param run Where the run begins. +#! @param index The position, below its length. +#! @returns The node. +pub def checker::run_at(&this, run: u32, index: u32): u32 { + return this.at.extras[run + 1 + index]; +} + +#! The nodes of a run of the file being checked, where they are, which checking +#! never moves. +#! @param this The checker. +#! @param run Where the run begins. +#! @returns The nodes. +pub def checker::run_view(&this, run: u32): span { + return span::::over(this.at.extras + run + 1, this.at.extras[run] as u64); +} + +#! How many segments a `type_name` or `path` has. +#! @param this The checker. +#! @param node The `type_name` or `path` node. +#! @returns How many. +pub def checker::segment_count(&this, node: u32): u32 { + val run := this.left_of(node); + return run == 0 ? 1 : this.run_length(run); +} + +#! The name of a segment of a `type_name` or `path`. +#! @param this The checker. +#! @param node The `type_name` or `path` node. +#! @param index The segment's position. +#! @returns The ID of its name. +pub def checker::segment_name(&this, node: u32, index: u32): u32 { + val run := this.left_of(node); + return run == 0 ? this.name_of(node) : this.name_of(this.run_at(run, index)); +} + +#! The node of a segment, where it holds type arguments, or the `type_name` +#! itself for one of a single segment. +#! @param this The checker. +#! @param node The `type_name` or `path` node. +#! @param index The segment's position. +#! @returns The node. +pub def checker::segment_node(&this, node: u32, index: u32): u32 { + val run := this.left_of(node); + return run == 0 ? node : this.run_at(run, index); +} + +#! The run of type arguments a segment is given, or 0. +#! @param this The checker. +#! @param node The `type_name` or `path` node. +#! @param index The segment's position. +#! @returns The run, or 0. +pub def checker::segment_args(&this, node: u32, index: u32): u32 { + val run := this.left_of(node); + return run == 0 ? 0 : this.left_of(this.run_at(run, index)); +} diff --git a/analyzer/checker/notes.sakura b/analyzer/checker/notes.sakura new file mode 100644 index 00000000..9d7edadf --- /dev/null +++ b/analyzer/checker/notes.sakura @@ -0,0 +1,242 @@ +#! @file notes.sakura +#! @author John Christman (sorakatadzuma@gmail.com) +#! @copyright Malunal Studios, LLC. +#! @license MIT +#! +#! Contains how the checker reports what is wrong: at a node of the file being +#! checked, or of another, with the instance of a generic it was found in and +#! a related place where there is one. A note holds a copy of its text, made +#! once the note is admitted, so text made for a note that is dropped, as one +#! made while an argument is tried quietly, is let go of with what made it. + +module sakura::analyzer; + + +#! Reports what is wrong at the node of the file being checked. +#! @param this The checker. +#! @param node The node. +#! @param code What kind of mistake it is. +#! @param detail What the note says. +pub def checker::report(&mut this, node: u32, code: ec, detail: strview): void { + this.report_in(this.at.file, node, code, detail); +} + +#! Reports what is wrong at the node, with text made for it. +#! @param this The checker. +#! @param node The node. +#! @param code What kind of mistake it is. +#! @param text What the note says, which the note copies. +pub def checker::report_text(&mut this, node: u32, code: ec, text: &string): void { + this.report_in(this.at.file, node, code, text.view()); +} + +#! Reports what is wrong at the node of the file. +#! @param this The checker. +#! @param file The file. +#! @param node The node. +#! @param code What kind of mistake it is. +#! @param detail What the note says. +pub def checker::report_in(&mut this, file: u32, node: u32, code: ec, detail: strview): void { + this.report_place(file, node, code, detail, 0, 0, 0, ""); +} + +#! Reports what is wrong at the declaration, in its own file, wherever checking +#! is. +#! @param this The checker. +#! @param id The declaration. +#! @param code What kind of mistake it is. +#! @param detail What the note says. +pub def checker::report_decl(&mut this, id: u32, code: ec, detail: strview): void { + this.report_in(this.decls.files.p[id], this.decls.nodes.p[id], code, detail); +} + +#! Reports what is wrong at the node of the file, and a place it relates to, +#! where it says something of one: to whatever hears the checker's notes, or in +#! its notes. +#! @param this The checker. +#! @param file The file. +#! @param node The node. +#! @param code What kind of mistake it is. +#! @param detail What the note says. +#! @param related_file The file of the place it relates to. +#! @param related_offset Where that place begins. +#! @param related_length How many bytes it covers. +#! @param related What the note says of it, or empty where it relates +#! to none. +def checker::report_place( + &mut this, + file: u32, + node: u32, + code: ec, + detail: strview, + related_file: u32, + related_offset: u32, + related_length: u32, + related: strview +): void { + if this.mute != 0 { + this.dropped++; + if code == ec::generic && detail.starts_with("Nothing gives") { + this.uninferred++; + } + return; + } + this.failed = true; + this.errors++; + return if !this.sink.admits(); + + val syntax := &this.units[file].syntax; + val token := syntax.node_tokens[node]; + var made := note { + file = file, + offset = syntax.token_offsets[token], + length = syntax.token_length(token, this.names), + code = code, + detail = string::from(detail, nothing {}), + instance = this.instance_text(), + related_file = related_file, + related_offset = related_offset, + related_length = related_length, + related = string::from(related, nothing {}), + origin = this.at.decl + }; + this.sink.give(&mut made); +} + +#! Warns of what is likely wrong at the node of the file being checked, which +#! never stops a program, nor marks what is checked as failed. +#! @param this The checker. +#! @param node The node. +#! @param code What kind of mistake it is about. +#! @param detail What the note says. +pub def checker::warn(&mut this, node: u32, code: ec, detail: strview): void { + this.warn_place(node, code, detail, 0); +} + +#! Warns of what is likely wrong at the node, with text made for it, and the +#! node declaring what it is about, where one is given. +#! @param this The checker. +#! @param node The node. +#! @param code What kind of mistake it is about. +#! @param text What the note says, which the note copies. +#! @param related The node declaring what it is about, in the same file, or 0. +pub def checker::warn_text(&mut this, node: u32, code: ec, text: &string, related: u32): void { + this.warn_place(node, code, text.view(), related); +} + +#! Warns of what is likely wrong at the node: to whatever hears the checker's +#! notes, or in its notes. +#! @param this The checker. +#! @param node The node. +#! @param code What kind of mistake it is about. +#! @param detail What the note says. +#! @param related The node declaring what it is about, in the same file, or 0. +def checker::warn_place(&mut this, node: u32, code: ec, detail: strview, related: u32): void { + return if this.mute != 0 || !this.sink.admits(); + val file := this.at.file; + val syntax := &this.units[file].syntax; + val token := syntax.node_tokens[node]; + var made := note { + file = file, + offset = syntax.token_offsets[token], + length = syntax.token_length(token, this.names), + code = code, + detail = string::from(detail, nothing {}), + warning = true, + instance = this.instance_text(), + origin = this.at.decl + }; + if related != 0 { + val other := syntax.node_tokens[related]; + made.related_file = file; + made.related_offset = syntax.token_offsets[other]; + made.related_length = syntax.token_length(other, this.names); + made.related = string::from("It is declared here.", nothing {}); + } + this.sink.give(&mut made); +} + +#! Reports what is wrong at the node, and the place of another it relates to, +#! as where a name was first declared. +#! @param this The checker. +#! @param node The node. +#! @param code What kind of mistake it is. +#! @param detail What the note says. +#! @param file The file of the other node. +#! @param other The other node. +#! @param related What the note says of it. +pub def checker::report_related( + &mut this, + node: u32, + code: ec, + detail: strview, + file: u32, + other: u32, + related: strview +): void { + this.report_related_in(this.at.file, node, code, detail, file, other, related); +} + +#! Reports what is wrong at the declaration, in its own file, wherever checking +#! is, and the place of another declaration it relates to, as where the name +#! was first declared. +#! @param this The checker. +#! @param id The declaration. +#! @param code What kind of mistake it is. +#! @param detail What the note says. +#! @param other The other declaration. +#! @param related What the note says of it. +pub def checker::report_decl_related(&mut this, id: u32, code: ec, detail: strview, other: u32, related: strview): void { + this.report_related_in(this.decls.files.p[id], this.decls.nodes.p[id], code, detail, + this.decls.files.p[other], this.decls.nodes.p[other], related); +} + +#! Reports what is wrong at the node of the file, and the place of another node +#! it relates to. +#! @param this The checker. +#! @param file The file. +#! @param node The node. +#! @param code What kind of mistake it is. +#! @param detail What the note says. +#! @param other_file The file of the other node. +#! @param other The other node. +#! @param related What the note says of it. +def checker::report_related_in( + &mut this, + file: u32, + node: u32, + code: ec, + detail: strview, + other_file: u32, + other: u32, + related: strview +): void { + val syntax := &this.units[other_file].syntax; + val token := syntax.node_tokens[other]; + this.report_place(file, node, code, detail, other_file, syntax.token_offsets[token], syntax.token_length(token, this.names), related); +} + +#! What notes made in the instance being checked say of it, as "In `max`", +#! or nothing outside an instance. +#! @param this The checker. +#! @returns The text, or empty text. +def checker::instance_text(&mut this): string { + return string::new(nothing {}) if this.at.instance == 0; + + val held: instance = this.instances[this.at.instance - 1]; + var text := string::from("In `", nothing {}); + text.append(this.names.text(this.decls.names.p[held.decl])); + text.append("<"); + # A pack's types are written as the arguments they are, as `show_all`. + this.describe_args(this.types.parts_view(held.args), &mut text); + text.append(">`"); + return text; +} + +#! Counts what the checker met and does not check yet, which it lets through +#! rather than reporting, so a program using it is not wrongly refused. +#! @param this The checker. +#! @param node The node. +pub def checker::unsupported(&mut this, node: u32): void { + this.skipped++; +} diff --git a/analyzer/checker/operators.sakura b/analyzer/checker/operators.sakura new file mode 100644 index 00000000..d0435cf9 --- /dev/null +++ b/analyzer/checker/operators.sakura @@ -0,0 +1,1491 @@ +#! @file operators.sakura +#! @author John Christman (sorakatadzuma@gmail.com) +#! @copyright Malunal Studios, LLC. +#! @license MIT +#! +#! Contains the checking of operators: prefix and postfix operators, taking a +#! reference, the binary operators, assignment, ternaries, casts with `as`, +#! and tests with `is`. Operators on constants give constants, so the length +#! of an array or the value of an enum member may be worked out of them. + +module sakura::analyzer; + + +#! A prefix operator: `-x`, `!x`, `~x`, `++x`, `--x`, or `*p`. +#! @param this The checker. +#! @param node The operator's node. +#! @param expected The type expected of its value, or the error type where +#! none is. +#! @returns The type of its value, or the error type where it is not valid. +def checker::unary(&mut this, node: u32, expected: u32): u32 { + val operand := this.left_of(node); + match this.token_kind(node) { + tk::minus => { + val kind := this.infer_expr(operand); + return bt::error if kind == bt::error; + if this.types.kind_of(kind) == ty::untyped_uint { + this.report(node, ec::overflow, "An integer written with `u` is unsigned, so it cannot be negated."); + return bt::error; + } + if this.operates_by_method(kind) { + return this.operate(node, word::negate, operand, 0, expected); + } + if !this.numeric_like(this.read_type(kind)) { + this.report_operand(node, kind, "`-` negates a number."); + return bt::error; + } + + if this.is_known(operand) { + val value := this.value_at(operand); + if value.floating { + this.set_value(node, constant::real_of(-value.real)); + } else { + this.set_value(node, constant::integer(value.magnitude, !value.negative)); + } + } + return this.operated(kind, kind, this.read_type(kind)); + } + tk::negate => { + val kind := this.infer_expr(operand); + return bt::error if kind == bt::error; + if !this.types.is_boolean(this.read_type(kind)) { + this.report_operand(node, kind, "`!` denies a `bool`."); + return bt::error; + } + if this.is_known(operand) { + this.set_value(node, constant::truth(this.value_at(operand).magnitude == 0)); + } + return this.read_type(kind); + } + tk::bitnot => { + val kind := this.infer_expr(operand); + return bt::error if kind == bt::error; + if this.operates_by_method(kind) { + return this.operate(node, word::bit_not, operand, 0, expected); + } + val read := this.read_type(kind); + if !this.integer_like(read) { + this.report_operand(node, kind, "`~` flips the bits of an integer."); + return bt::error; + } + if this.is_known(operand) { + val value := this.value_at(operand); + val plain := this.unalias(read); + val signed := this.types.kind_of(plain) != ty::untyped_uint && this.types.kind_of(plain) != ty::unsigned; + # An unsigned type keeps only its own bits, so `~0` of a `u8` is 255. + var flipped := ~value.bits(); + if this.types.kind_of(plain) == ty::unsigned && this.types.first_of(plain) < 64 { + flipped &= (1u << this.types.first_of(plain) as u64) - 1; + } + this.set_value(node, constant::from_bits(flipped, signed)); + } + return this.operated(kind, kind, read); + } + tk::increment, tk::decrement => return this.step(node, operand); + tk::star => { + # References are read through to the pointer they refer to. + val kind := this.infer_expr(operand); + return bt::error if kind == bt::error; + val inner := this.unalias(this.reached(kind)); + if this.types.kind_of(inner) == ty::pointer { + this.mark_place(node, this.types.second_of(inner) != 0); + return this.types.first_of(inner); + } + this.report_operand(node, kind, "`*` reaches what a pointer points at."); + return bt::error; + } + tk::spread => { + this.report(node, ec::operands, "`...` spreads a view or a pack into the arguments of a call, and is only written there."); + this.infer_expr(operand); + return bt::error; + } + else => {} + } + return bt::error; +} + +#! The type a value of the type is read as: what plain references refer to, +#! however many there are, and an alias's own type where it stands for a number. +#! @param this The checker. +#! @param kind The type. +#! @returns The type it is read as. +pub def checker::read_type(&mut this, kind: u32): u32 { + var at := kind; + var steps := 0; + while this.types.kind_of(at) == ty::reference && steps < 8 { + at = this.types.first_of(at); + steps++; + } + val plain := this.unalias(at); + return this.types.is_numeric(plain) || this.types.is_boolean(plain) ? plain : at; +} + +#! `x++`, `x--`, `++x`, or `--x`, which change a number in place. +#! @param this The checker. +#! @param node The operator's node. +#! @param operand The node of the number it changes. +#! @returns The number's type, or the error type where it is not valid. +def checker::step(&mut this, node: u32, operand: u32): u32 { + val kind := this.infer_expr(operand); + return bt::error if kind == bt::error; + if !this.numeric_like(this.read_type(kind)) && this.types.kind_of(this.unalias(kind)) != ty::pointer { + this.report_operand(node, kind, "`++` and `--` change a number."); + return bt::error; + } + this.require_writable(operand); + return this.read_type(kind); +} + +#! Whether a place holding a reference is pointed elsewhere by assigning it a +#! reference: a variable or field that can be written, but not a parameter, +#! through which a reference writes what it refers to, as the C compiler does. +#! @param this The checker. +#! @param target The place's node. +#! @returns Whether it is. +pub def checker::rebinds(&this, target: u32): bool { + return false if !this.is_place(target) || !this.is_writable(target); + if this.kind_of(target) == nk::name { + val ref := this.ref_at(target); + if (ref & ref_local) != 0 && this.kind_of(ref & ref_mask) == nk::param { + return false; + } + } + return true; +} + +#! The name an `is` test or an arm gave a copy of what a union's field refers to, +#! where a place is reached from one, or 0. +#! @param this The checker. +#! @param node The place. +#! @returns The node declaring the name, or 0. +def checker::copied_binding(&this, node: u32): u32 { + var at := node; + var steps := 0; + while (this.kind_of(at) == nk::member || this.kind_of(at) == nk::index) && steps < 64 { + at = this.left_of(at); + steps++; + } + return 0 if this.kind_of(at) != nk::name; + val ref := this.ref_at(at); + return 0 if (ref & ref_local) == 0; + val local := ref & ref_mask; + return local if this.has_flag(local, rf::narrowed) && this.has_flag(local, rf::valued); + return 0; +} + +#! Reports what is written to where it cannot be. +#! @param this The checker. +#! @param node The node of what is written. +#! @returns Whether it can be written. +pub def checker::require_writable(&mut this, node: u32): bool { + this.check_unlocked(node); + return true if this.is_writable(node) || this.type_at(node) == bt::error; + + # What a `&mut` reference refers to is written through it, whether a call + # gives it or a `val` holds it. + val kind := this.type_at(node); + return true if this.types.kind_of(kind) == ty::reference && this.types.second_of(kind) != 0; + + if this.is_place(node) { + # What an `is` test named by a copy of what a field refers to, as `p` of + # `x is some(p)` of a `maybe<&mut T>`, is only read; `&mut p` names the + # reference, which writes through. + val copied := this.copied_binding(node); + if copied != 0 { + val name := this.names.text(this.name_of(copied)); + var text := string::from("`", nothing {}); + text.append(name); + text.append("` is a copy of what the field refers to, which is only read: `&mut "); + text.append(name); + text.append("` names the reference itself, which writes through."); + this.report_text(node, ec::assignable, &text); + return false; + } + this.report(node, ec::assignable, + "This cannot be written: it is a `val` or a constant, or reached through `&` rather than `&mut`."); + } else if this.types.kind_of(kind) == ty::reference { + this.report(node, ec::assignable, "A `&` reference reads what it refers to; write through a `&mut` one."); + } else { + this.report(node, ec::assignable, "Only a variable, a field, an element, or what a reference reaches is written."); + } + return false; +} + +#! `&x` or `&mut x`. A value that is no place is copied to a new place first, so +#! `&200` refers to a copy of the constant. +#! @param this The checker. +#! @param node The `reference` node. +#! @param expected The type expected of it, or the error type where none is. +#! @returns The reference's type, or the error type where it is not valid. +def checker::reference(&mut this, node: u32, expected: u32): u32 { + val operand := this.left_of(node); + val mutable := this.node_has(node, nf::mutable); + # What a reference or a pointer is expected to reach types a constant it is to. + val reaching := this.unalias(expected); + val wanted: u32 = this.types.kind_of(reaching) == ty::reference || this.types.kind_of(reaching) == ty::pointer + ? this.types.first_of(reaching) + : bt::error; + + # A reference to a constant keeps the constant's type until the type it + # refers to is known, as `&"text"` given for a `&strview`. + var kind := this.infer_expr(operand); + return bt::error if kind == bt::error; + if this.types.is_untyped(kind) && wanted != bt::error { + kind = this.check_expr(operand, wanted); + } + + if mutable { + this.check_unlocked(operand); + } + # A property's value is copied as any other value is, so only `&mut` is refused. + val held := this.ref_at(operand); + if mutable && this.kind_of(operand) == nk::member && held != 0 && (held & (ref_local | ref_type)) == 0 + && this.decls.kinds.p[held] == dk::property { + this.report(node, ec::invalid, "A property is read and written through its accessors, so `&mut` has no place to refer to; assign it instead."); + } + # A reference, as a variable or a call gives one, is lent as it is, since + # references never stack: `&` of one is that reference, and `&mut` of one + # writes where it does, whatever holds it. A `&` one only reads. + val given := this.unalias(kind); + if this.decide(node, rf::relent, this.types.kind_of(given) == ty::reference) { + if mutable && this.types.second_of(given) == 0 { + this.report(node, ec::assignable, "`&mut` refers to what can be written, and this is reached through `&`."); + } + return this.types.reference(this.types.first_of(given), mutable); + } + + if mutable && this.is_place(operand) && !this.is_writable(operand) { + this.report(node, ec::assignable, + "`&mut` refers to what can be written, and this is a `val` or a constant, or reached through `&`."); + } + this.check_lends_field(node, operand, mutable); + return this.types.reference(kind, mutable); +} + +#! Whether a value is a reference written as one, `&x` or `&mut x`, or a choice +#! between such, as `c ? &a : &b`. Only these lend: anything else, though its +#! type is a reference, as a call giving one, is taken as the value it reaches +#! where a binding, `for`, a pattern, or inference takes it. +#! @param this The checker. +#! @param node The value's node. +#! @returns Whether it is. +pub def checker::lent(&this, node: u32): bool { + match this.kind_of(node) { + nk::reference => return true; + nk::ternary => return this.lent(this.record(node, if_slot::then)) && this.lent(this.record(node, if_slot::other)); + nk::match_value => { + val arms := this.right_of(node); + return false if this.run_length(arms) == 0; + for &arm in this.run_view(arms) { + return false if !this.lent(this.right_of(arm)); + } + return true; + } + else => return false; + } + return false; +} + +#! Reports `&` or `&mut` lending a union's field, or what is within one, where +#! it could outlive the union holding that field: written through `&mut` once +#! the union holds another, or read through `&`, where what it refers to +#! closes, once that is closed. A test asks which field the union holds first, +#! as `is some(&mut q)`. +#! @param this The checker. +#! @param node The `reference` node. +#! @param operand What it refers to. +#! @param mutable Whether it is `&mut`. +def checker::check_lends_field(&mut this, node: u32, operand: u32, mutable: bool): void { + var at := operand; + var steps := 0; + while steps < 64 && (this.kind_of(at) == nk::member || this.kind_of(at) == nk::index) { + steps++; + val left := this.left_of(at); + # What a reference or pointer reaches is not held within the value it is in. + val through := this.types.kind_of(this.unalias(this.type_at(left))); + if this.kind_of(at) == nk::member { + val held := this.ref_at(at); + if held != 0 && (held & (ref_local | ref_type)) == 0 && this.decls.kinds.p[held] == dk::field { + val owner: u32 = this.decls.owners.p[held]; + if this.decls.kinds.p[owner] == dk::union_type && !this.decls.has(owner, df::foreign) { + if mutable { + this.report(node, ec::invalid, "`&mut` of a union's field would write it whichever field the union holds: name it where it is held, as `if m is some(&mut q)`, or `match` by `&mut`."); + return; + } + val kind := this.type_at(operand); + if this.closes(kind) { + var text := string::from("`", nothing {}); + val named := this.describe(kind); + text.append(named.view()); + text.append("` is closed once the union holds another field, so `&` of it could outlive it: name it where it is held, as `if r is value(&p)`, or `match` by `&`."); + this.report_text(node, ec::owned, &text); + return; + } + } + } + } + break if through == ty::reference || through == ty::pointer; + at = left; + } +} + +#! Reports an operator applied to what it does not take. +#! @param this The checker. +#! @param node The operator's node. +#! @param kind The operand's type, which the note names. +#! @param detail What the note says after naming it. +def checker::report_operand(&mut this, node: u32, kind: u32, detail: strview): void { + var text := string::from(detail, nothing {}); + text.append(" This is `"); + val named := this.describe(kind); + text.append(named.view()); + text.append("`."); + this.report_text(node, ec::operands, &text); +} + +#! A binary operator. +#! @param this The checker. +#! @param node The operator's node. +#! @param expected The type expected of its value, or the error type where +#! none is. +#! @returns The type of its value, or the error type where it is not valid. +def checker::binary(&mut this, node: u32, expected: u32): u32 { + val operator := this.token_kind(node); + val left := this.left_of(node); + val right := this.right_of(node); + if operator == tk::logand || operator == tk::logor { + # What the left of `&&` names where it holds is named on its right, and what the + # left of `||` names where it does not. + this.check_condition(left); + val mark := this.scope_mark(); + this.bind_tests(left, operator == tk::logand); + this.check_condition(right); + this.unbind_to(mark); + this.fold(node, operator, left, right, false); + return bt::boolean; + } + + val a := this.infer_expr(left); + val b := this.infer_expr(right); + return bt::error if a == bt::error || b == bt::error; + + if operator == tk::lshift || operator == tk::rshift { + # A shift of what is no number is a call of `shift_left` or `shift_right`. + if this.operates_by_method(a) { + return this.operate(node, this.arithmetic_word(operator), left, right, expected); + } + return this.shift(node, operator, left, right, a, b); + } + + val comparing := operator.compares(); + + # Pointers move by elements, and two count the elements between them, as do values + # of a type parameter `pointer` bounds. + val pa := this.unalias(a); + if (operator == tk::plus || operator == tk::minus) && !comparing && this.pointer_like(pa) { + val pb := this.unalias(this.read_type(b)); + if operator == tk::minus && (this.types.kind_of(pb) == ty::pointer || pb == pa) { + return bt::int64; + } + if this.types.is_integer(pb) { + if this.types.is_untyped(b) { + this.check_expr(right, bt::int64); + } + return a; + } + } + + # Arithmetic on what is no number is a call of the method that gives the + # operator, as `+` is of `add`, which the left operand's type is asked for: a + # struct or union, a type parameter through its bounds, or a number where the + # right operand is none. + val word := this.arithmetic_word(operator); + if word != 0 { + val numbered := this.types.is_numeric(this.unalias(this.read_type(a))); + if numbered ? !this.types.is_numeric(this.unalias(this.read_type(b))) && this.operates_by_method(b) : this.operates_by_method(a) { + return this.operate(node, word, left, right, expected); + } + } + + # Bitwise operators take enums as their integers, as flags are combined. + val bitwise_op := operator == tk::bitand || operator == tk::bitor || operator == tk::bitxor; + var la := a; + var lb := b; + if bitwise_op && this.named_kind(this.unalias(this.read_type(a))) == dk::enum_type { + la = this.enum_integer(this.unalias(this.read_type(a))); + this.set_convert(left, la); + } + if bitwise_op && this.named_kind(this.unalias(this.read_type(b))) == dk::enum_type { + lb = this.enum_integer(this.unalias(this.read_type(b))); + this.set_convert(right, lb); + } + if la != a || lb != b { + val joined := this.common(la, lb); + if joined != bt::error { + this.fold(node, operator, left, right, false); + return joined; + } + } + + # A string owns its text and a view only reads one, so which of the two a + # mixed comparison reads is not obvious, and `view()` says it. Text written in + # place is whichever the other is. + if comparing { + val ra := this.read_type(a); + val rb := this.read_type(b); + if (this.is_std(this.unalias(ra), word::string) && this.is_byte_view(rb)) + || (this.is_byte_view(ra) && this.is_std(this.unalias(rb), word::string)) { + this.report(node, ec::operands, "A string owns its text and a view only reads one, so compare the text of both, as `s.view() == v`."); + return bt::error; + } + } + + val shared := this.shared_type(node, operator, a, b); + return bt::error if shared == bt::error; + + if comparing { + # Integers of different signs compare exactly, as they are. + val ra := this.unalias(this.read_type(a)); + val rb := this.unalias(this.read_type(b)); + val mixed := this.types.is_integer(ra) && this.types.is_integer(rb) && !this.types.is_untyped(ra) + && !this.types.is_untyped(rb) && this.types.is_signed(ra) != this.types.is_signed(rb); + if !mixed { + this.convert_operand(left, shared); + this.convert_operand(right, shared); + } + this.check_compared(node, operator, shared); + this.fold(node, operator, left, right, this.types.is_signed(shared)); + return this.types.is_untyped(a) && this.types.is_untyped(b) && this.is_known(node) + ? bt::untyped_bool + : bt::boolean; + } + + this.convert_operand(left, shared); + this.convert_operand(right, shared); + val numeric := this.read_type(shared); + val bitwise := operator == tk::bitand || operator == tk::bitor || operator == tk::bitxor; + if bitwise && !this.integer_like(numeric) { + this.report_operands(node, a, b, "are not both integers, which the operator takes"); + return bt::error; + } + if !bitwise && !this.numeric_like(numeric) { + this.report_operands(node, a, b, "are not both numbers, which the operator takes"); + return bt::error; + } + + if !this.fold(node, operator, left, right, this.types.is_signed(numeric)) && this.is_known(left) && this.is_known(right) { + this.report(node, ec::overflow, "The constant overflows 64 bits, or divides by zero."); + return bt::error; + } + if this.is_known(node) && !this.types.is_untyped(numeric) { + val value := this.value_at(node); + if !this.in_range(numeric, &value) { + var text := string::from("The constant is outside the range of `", nothing {}); + val named := this.describe(numeric); + text.append(named.view()); + text.append("`."); + this.report_text(node, ec::overflow, &text); + } + } + return this.operated(a, b, numeric); +} + +#! The type an arithmetic or bitwise operator gives, which keeps an alias its +#! operands are written with, as C's checker does: the right operand's type where +#! it is the number they operate as, else the left's, else that number. So `a | b` +#! of two masks is a mask, with a mask's methods. +#! @param this The checker. +#! @param a The left operand's type. +#! @param b The right operand's type. +#! @param numeric The number they operate as. +#! @returns The type. +def checker::operated(&mut this, a: u32, b: u32, numeric: u32): u32 { + val written_b := this.types.kind_of(b) == ty::reference ? this.types.first_of(b) : b; + val written_a := this.types.kind_of(a) == ty::reference ? this.types.first_of(a) : a; + return written_b if this.unalias(written_b) == numeric; + return written_a if this.unalias(written_a) == numeric; + return numeric; +} + +#! The type both operands of a binary operator take: the type they share, an +#! integer and a float operating as the float, and integers of different signs +#! comparing exactly. +#! @param this The checker. +#! @param node The operator's node. +#! @param operator The operator. +#! @param a The left operand's type. +#! @param b The right operand's type. +#! @returns The type they share, or the error type where they share none. +def checker::shared_type(&mut this, node: u32, operator: tk, a: u32, b: u32): u32 { + val ra := this.read_type(a); + val rb := this.read_type(b); + val shared := this.common(ra, rb); + return shared if shared != bt::error; + + val comparing := operator.compares(); + if this.types.is_integer(ra) && this.types.is_integer(rb) && comparing { + return this.types.is_untyped(ra) ? rb : ra; + } + + # An enum is its integer type with an integer. + val ua := this.unalias(ra); + val ub := this.unalias(rb); + if this.named_kind(ua) == dk::enum_type && this.types.is_integer(ub) { + return this.shared_type(node, operator, this.enum_integer(ua), b); + } + if this.named_kind(ub) == dk::enum_type && this.types.is_integer(ua) { + return this.shared_type(node, operator, a, this.enum_integer(ub)); + } + if this.types.is_float(ua) && this.types.is_integer(ub) && !this.types.is_untyped(ub) { + return ua; + } + if this.types.is_float(ub) && this.types.is_integer(ua) && !this.types.is_untyped(ua) { + return ub; + } + + # A pointer compares with `null`. + if comparing && (this.types.kind_of(ua) == ty::null_type || this.types.kind_of(ub) == ty::null_type) { + return this.types.kind_of(ua) == ty::null_type ? rb : ra; + } + + this.report_operands(node, a, b, "share no type, so convert one with `as`"); + return bt::error; +} + +#! Converts an operand to the type both operands share, where an integer +#! operating with a float operates as the float. +#! @param this The checker. +#! @param node The operand's node. +#! @param shared The type both share. +def checker::convert_operand(&mut this, node: u32, shared: u32): void { + val kind := this.read_type(this.type_at(node)); + if this.types.is_float(this.unalias(shared)) && this.types.is_integer(this.unalias(kind)) && !this.types.is_untyped(kind) { + this.set_convert(node, shared); + return; + } + this.convert(node, shared); +} + +#! Reports operands an operator does not take. +#! @param this The checker. +#! @param node The operator's node. +#! @param a The left operand's type. +#! @param b The right operand's type. +#! @param why What the note says after naming them. +def checker::report_operands(&mut this, node: u32, a: u32, b: u32, why: strview): void { + var text := string::from("`", nothing {}); + val first := this.describe(a); + val other := this.describe(b); + text.append(first.view()); + text.append("` and `"); + text.append(other.view()); + text.append("` "); + text.append(why); + text.append("."); + this.report_text(node, ec::operands, &text); +} + +#! Checks that values of the type compare as the operator asks: `==` and `!=` +#! on what is equatable, and `<` and the others on what is ordered. +#! @param this The checker. +#! @param node The comparison's node. +#! @param operator The comparison. +#! @param kind The type compared. +def checker::check_compared(&mut this, node: u32, operator: tk, kind: u32): void { + val plain := this.unalias(this.read_type(kind)); + val equal := operator == tk::equals || operator == tk::noteq; + val ordered := this.types.is_numeric(plain) || this.named_kind(plain) == dk::enum_type + || this.pointer_like(plain) || this.types.kind_of(plain) == ty::untyped_char; + return if ordered; + return if equal && (this.types.is_boolean(plain) || this.types.kind_of(plain) == ty::null_type); + return if equal && this.native_equality(plain, 0); + + val word := equal ? word::equals : word::compare; + if this.has_method(plain, word) { + return; + } + # What an integer or an enum stands for is ordered as one is. + if this.types.kind_of(plain) == ty::param && this.param_ordinal(this.types.first_of(plain)) { + return; + } + + var text := string::from("`", nothing {}); + val named := this.describe(kind); + text.append(named.view()); + text.append(equal + ? "` has no `==`: a struct or union compares by implementing `equatable`." + : "` has no order: a struct or union is ordered by implementing `ordered`."); + this.report_text(node, ec::operands, &text); +} + +#! Whether `==` compares values of the type without a method: numbers, `bool`, +#! enums, pointers, and fixed arrays of them. +#! @param this The checker. +#! @param kind The type. +#! @param depth How many fixed arrays deep it is, which stops a type nesting +#! without end. +#! @returns Whether it compares without one. +def checker::native_equality(&mut this, kind: u32, depth: u32): bool { + return false if depth > 8; + val plain := this.unalias(kind); + return true if this.types.is_numeric(plain) || this.types.is_boolean(plain) + || this.named_kind(plain) == dk::enum_type || this.types.kind_of(plain) == ty::pointer + || this.is_std(plain, word::cfn); + if this.types.kind_of(plain) == ty::fixed { + val element := this.types.first_of(plain); + return this.native_equality(element, depth + 1) || this.has_method(this.unalias(element), word::equals); + } + return false; +} + +#! A shift, which takes integers of any types and gives its left's type. +#! @param this The checker. +#! @param node The shift's node. +#! @param operator `<<` or `>>`. +#! @param left The node of what is shifted. +#! @param right The node of the count. +#! @param a The type of what is shifted. +#! @param b The count's type. +#! @returns The left's type, or the error type where either is no integer. +def checker::shift(&mut this, node: u32, operator: tk, left: u32, right: u32, a: u32, b: u32): u32 { + val ra := this.read_type(a); + val rb := this.read_type(b); + if !this.integer_like(ra) || !this.integer_like(rb) { + this.report_operands(node, a, b, "are not both integers, which a shift takes"); + return bt::error; + } + if this.types.is_untyped(rb) && !this.types.is_untyped(ra) { + this.check_expr(right, bt::uint64); + } + this.fold(node, operator, left, right, this.types.is_signed(ra)); + return this.operated(a, a, ra); +} + +#! Folds a binary operator of two constants into the constant it gives. +#! @param this The checker. +#! @param node The operator's node, which takes the constant. +#! @param operator The operator. +#! @param left The left operand's node. +#! @param right The right operand's node. +#! @param signed Whether the operands are signed, which division and shifts +#! care about. +#! @returns Whether it gives one. +def checker::fold(&mut this, node: u32, operator: tk, left: u32, right: u32, signed: bool): bool { + return false if !this.is_known(left) || !this.is_known(right); + + val a := this.value_at(left); + val b := this.value_at(right); + var out := constant {}; + return false if !this.fold_binary(operator, &a, &b, signed, &mut out); + this.set_value(node, out); + return true; +} + +#! Whether arithmetic applies to values of the type: a number, or a type +#! parameter bounded by `numeric` or `integer`. +#! @param this The checker. +#! @param kind The type. +#! @returns Whether it applies. +pub def checker::numeric_like(&mut this, kind: u32): bool { + val plain := this.unalias(kind); + return this.types.is_numeric(plain) || (this.types.kind_of(plain) == ty::param && this.param_has_numeric(this.types.first_of(plain))); +} + +#! Whether bitwise operators apply to values of the type: an integer, or a type +#! parameter bounded by `integer`. +#! @param this The checker. +#! @param kind The type. +#! @returns Whether they apply. +pub def checker::integer_like(&mut this, kind: u32): bool { + val plain := this.unalias(kind); + if this.types.kind_of(plain) == ty::param { + val integer := this.std_decl(word::integer); + return integer != 0 && this.param_bounded(plain, integer); + } + return this.types.is_integer(plain); +} + +#! Whether a value of the type is an address: a pointer, or a value of a type +#! parameter bounded by `pointer`. +#! @param this The checker. +#! @param kind The type. +#! @returns Whether it is one. +pub def checker::pointer_like(&mut this, kind: u32): bool { + val plain := this.unalias(kind); + if this.types.kind_of(plain) == ty::param { + val pointer := this.std_decl(word::pointer); + return pointer != 0 && this.param_bounded(plain, pointer); + } + return this.types.kind_of(plain) == ty::pointer; +} + +#! The method an arithmetic or bitwise operator, or a shift, calls on what is no +#! number. +#! @param this The checker. +#! @param operator The operator, as `+` or `+=`. +#! @returns The ID of the method's name, as `add`. +def checker::arithmetic_word(&this, operator: tk): u32 { + return match operator { + tk::plus, tk::pluseq => word::add, + tk::minus, tk::minuseq => word::sub, + tk::star, tk::stareq => word::mul, + tk::slash, tk::slasheq => word::div, + tk::modulo, tk::moduloeq => word::rem, + tk::bitand, tk::bitandeq => word::bit_and, + tk::bitor, tk::bitoreq => word::bit_or, + tk::bitxor, tk::bitxoreq => word::bit_xor, + tk::lshift, tk::lshifteq => word::shift_left, + tk::rshift, tk::rshifteq => word::shift_right, + else => 0 + }; +} + +#! The method a compound assignment calls on its target in place, where the +#! target's type has one taking the value, as `+=` calls `add_assign`, or 0. +#! @param this The checker. +#! @param operator The compound assignment's operator. +#! @returns The ID of the method's name, or 0. +def checker::in_place_word(&this, operator: tk): u32 { + return match operator { + tk::pluseq => word::add_assign, + tk::minuseq => word::sub_assign, + tk::stareq => word::mul_assign, + tk::slasheq => word::div_assign, + tk::moduloeq => word::rem_assign, + tk::bitandeq => word::bit_and_assign, + tk::bitoreq => word::bit_or_assign, + tk::bitxoreq => word::bit_xor_assign, + tk::lshifteq => word::shift_left_assign, + tk::rshifteq => word::shift_right_assign, + else => 0 + }; +} + +#! Whether an operator on a value of the type is a call of the method that +#! gives it: a struct or union, or a type parameter no bound makes a number or +#! a pointer of, which has the methods its bounds ask for. +#! @param this The checker. +#! @param kind The type. +#! @returns Whether it is. +pub def checker::operates_by_method(&mut this, kind: u32): bool { + val plain := this.unalias(this.reached(kind)); + val named := this.named_kind(plain); + return true if named == dk::struct_type || named == dk::union_type; + return this.types.kind_of(plain) == ty::param && !this.numeric_like(plain) && !this.pointer_like(plain); +} + +#! An operator calling the method that gives it, as `+` calls `add`. The type of +#! the operand it is called on is asked for the method, and the overload the +#! other operand fits is chosen as a call's is, so a constant takes the type of +#! the parameter, and the operator gives what the method gives. The node keeps +#! the method, which the compiler calls. +#! @param this The checker. +#! @param node The operator's node. +#! @param word The ID of the method's name. +#! @param left The node of the operand the method is called on. +#! @param right The node of the other operand, or 0 for a prefix operator. +#! @param expected The type expected of what it gives, or the error type +#! where none is. +#! @returns The type the method gives, or the error type where the type has no +#! such method taking the other operand. +def checker::operate(&mut this, node: u32, word: u32, left: u32, right: u32, expected: u32): u32 { + # A constant is asked as the number it is alone. + var kind := this.type_at(left); + if this.types.is_untyped(kind) { + kind = this.settle_expr(left); + } + val through := this.reached(kind); + val found := this.find_member(through, word); + + var args := vector::::new(); + var kinds := vector::::new(); + if right != 0 { + args.append(right); + kinds.append(this.infer_expr(right)); + } + + var best := checker::candidate { worst = fit::none }; + var tied := false; + if found.decl != 0 && this.decls.kinds.p[found.decl] == dk::function { + val alone := this.decls.overloads.p[found.decl] == 0 && this.decls.has(found.decl, df::generic); + val writes := this.receiver_writable(left); + val plain := this.unalias(through); + # An `@optional` method may be missing from what a bound stands for. + val bounded := this.types.kind_of(plain) == ty::param || this.named_kind(plain) == dk::trait_type; + # A method with type parameters of its own, beyond its type's, is none an + # operator calls, since nothing is written to give them. + val owned: u32 = this.types.kind_of(found.owner) == ty::named ? this.types.part_count(found.owner) : 0; + # A program's method on `core`'s type is chosen where it fits, and `core`'s + # of its name where none does. + var chain := found.decl; + while chain != 0 { + var walk := this.decls.walk_overloads(chain); + while true { + val at := walk.next(); + break if at == 0; + val own := this.enclosing_trait(at) == 0 && this.decls.list_length(this.decls.params.p[at]) > owned; + if this.decls.has(at, df::method) && !own && !(bounded && this.decls.has(at, df::optional)) && this.member_seen(at) { + val made := this.try_candidate(at, left, found.owner, through, span::::empty(), args.view(), kinds.view(), expected, alone); + # An operator's method takes its operands and nothing more: `this`, and the + # other operand by reference. + val shaped := this.types.part_count(made.kind) as u64 == args.length + 1 && this.types.second_of(made.kind) == 0 + && (right == 0 || this.types.kind_of(this.unalias(this.types.part_at(made.kind, 1))) == ty::reference); + if made.worst != fit::none && made.worst != fit::overflow && !made.later && shaped { + this.keep_better(&made, &mut best, &mut tied, true, writes); + } + } + } + break if best.decl != 0; + chain = this.core_behind(chain); + } + } + + if best.decl == 0 { + var text := string::from("`", nothing {}); + val named := this.describe(through); + text.append(named.view()); + text.append("` has no `"); + text.append(this.names.text(word)); + if right != 0 && kinds[0] != bt::error { + text.append("` taking a `&"); + val other := this.describe(this.settle(this.reached(kinds[0]))); + text.append(other.view()); + } + text.append("`, which `"); + text.append(this.text_of(node)); + text.append("` calls."); + this.report_text(node, ec::operands, &text); + return bt::error; + } + if tied { + var text := string::from("The operands fit more than one `", nothing {}); + text.append(this.names.text(word)); + text.append("` as well, so convert the right one to the type of the one meant."); + this.report_text(node, ec::ambiguous, &text); + } + return this.apply_candidate(node, node, &best, left, args.view(), kinds.view()); +} + +#! An assignment, `=` or a compound one as `+=`, which gives the value assigned. +#! @param this The checker. +#! @param node The `assign` node. +#! @returns The type of the value assigned, or the error type where it is not +#! valid. +def checker::assign(&mut this, node: u32): u32 { + val operator := this.token_kind(node); + val target := this.left_of(node); + val value := this.right_of(node); + + # `_ = x` evaluates `x` and lets go of it. + if operator == tk::assign && this.kind_of(target) == nk::name && this.name_of(target) == names::underscore_id { + return this.settle_expr(value); + } + + val kind := this.infer_expr(target); + if kind == bt::error { + this.infer_expr(value); + return bt::error; + } + + # A property is written through its `set`, wanted as its `get` is where read. + val written := this.ref_at(target); + if this.kind_of(target) == nk::member && written != 0 && (written & (ref_local | ref_type)) == 0 + && this.decls.kinds.p[written] == dk::property { + this.want_accessor(this.property_setter(written), this.reached(this.type_at(this.left_of(target))), target); + } + + # A variable holding a reference is pointed elsewhere by a reference written + # as one, `r = &x`, where it can be written, and anything else writes what it + # refers to, a reference too, as `r = s` writes what `s` reaches. + if operator == tk::assign && this.types.kind_of(kind) == ty::reference { + val given := this.infer_expr(value); + val none := constant {}; + # Only a variable that can be written is pointed elsewhere; through one that + # cannot, or a parameter, a reference writes what it refers to. Within an + # instance, a place the template held a value of a type parameter in is + # given the value, as the template's was, though it is a reference here. + val points := this.rebinds(target) && this.lent(value) && this.types.kind_of(given) == ty::reference + && this.fits(given, kind, &none, false, 0) != fit::none; + if !this.decide(node, rf::valued, !points) { + this.check_unlocked(target); + this.convert(value, kind); + return kind; + } + if this.types.second_of(kind) == 0 { + this.report(target, ec::assignable, "A `&` reference reads what it refers to; write through a `&mut` one."); + return kind; + } + this.convert(value, this.types.first_of(kind)); + this.check_owned(value, this.types.first_of(kind)); + return kind; + } + + this.require_writable(target); + if operator == tk::assign { + this.check_expr(value, kind); + this.check_owned(value, kind); + return kind; + } + + # A compound assignment applies its operator, as `x = x + y` would, so where + # that is a call of a method, what the method gives is written over the target. + # Where the target's type has the method changing it in place, as `+=` has + # `add_assign`, and it takes the value, that is called instead, giving nothing. + val read := this.read_type(kind); + val word := this.arithmetic_word(operator); + if word != 0 { + val given := this.hinted_expr(value, read); + val numbered := this.types.is_numeric(this.unalias(read)); + if given != bt::error && !numbered && this.operates_by_method(read) && this.changes_in_place(operator, target, value, read) { + val made := this.operate(node, this.in_place_word(operator), target, value, read); + if made != bt::error && this.unalias(made) != bt::void_type { + var text := string::from("`", nothing {}); + text.append(this.names.text(this.in_place_word(operator))); + text.append("` changes what it is called on in place, so it gives nothing, and it gives `"); + val gives := this.describe(made); + text.append(gives.view()); + text.append("` here."); + this.report_text(node, ec::operands, &text); + } + return kind; + } + if given != bt::error && (numbered + ? !this.types.is_numeric(this.unalias(this.read_type(given))) && this.operates_by_method(given) + : this.operates_by_method(read)) { + val made := this.operate(node, word, target, value, read); + if made != bt::error && this.unalias(this.read_type(made)) != this.unalias(read) { + var text := string::from("`", nothing {}); + text.append(this.text_of(node)); + text.append("` writes what `"); + text.append(this.names.text(word)); + text.append("` gives over the `"); + val held := this.describe(read); + text.append(held.view()); + text.append("` it is called on, and `"); + text.append(this.names.text(word)); + text.append("` gives `"); + val gives := this.describe(made); + text.append(gives.view()); + text.append("` here."); + this.report_text(node, ec::operands, &text); + } + return kind; + } + } + + if operator == tk::lshifteq || operator == tk::rshifteq { + val shift := this.infer_expr(value); + if !this.integer_like(read) || !this.integer_like(this.read_type(shift)) { + this.report_operands(node, kind, shift, "are not both integers, which a shift takes"); + } + return kind; + } + + if this.pointer_like(read) && (operator == tk::pluseq || operator == tk::minuseq) { + this.check_expr(value, bt::int64); + return kind; + } + + this.check_expr(value, read); + val bitwise := operator == tk::bitandeq || operator == tk::bitoreq || operator == tk::bitxoreq; + val plain := this.unalias(read); + if bitwise && !this.integer_like(plain) { + this.report_operand(node, kind, "The operator takes integers."); + } else if !bitwise && !this.numeric_like(plain) { + this.report_operand(node, kind, "The operator takes numbers."); + } + return kind; +} + +#! Whether a compound assignment's target has the method changing it in place +#! that its operator calls, as `add_assign` for `+=`, taking the value. +#! @param this The checker. +#! @param operator The compound assignment's operator. +#! @param target The target's node. +#! @param value The value's node. +#! @param read The target's type, as read. +#! @returns Whether it has. +def checker::changes_in_place(&mut this, operator: tk, target: u32, value: u32, read: u32): bool { + val word := this.in_place_word(operator); + return false if word == 0; + val through := this.reached(read); + val found := this.find_member(through, word); + return false if found.decl == 0 || this.decls.kinds.p[found.decl] != dk::function; + var args := vector::::new(); + args.append(value); + return this.fits_overload(found.decl, target, found.owner, through, args.view()); +} + +#! `cond ? a : b`, whose branches share a type, or both take the type expected. +#! @param this The checker. +#! @param node The `ternary` node. +#! @param expected The type expected of its value, or the error type where +#! none is. +#! @returns The type its branches share, or the error type where they share +#! none. +def checker::ternary(&mut this, node: u32, expected: u32): u32 { + val condition := this.left_of(node); + this.check_condition(condition); + val then := this.record(node, if_slot::then); + val other := this.record(node, if_slot::other); + # The names the condition's `is` tests give are named where they hold, as an + # `if`'s are: those of `x is f(v)` in the first branch, and of `x is not f(v)` + # in the second. + val mark := this.scope_mark(); + if expected != bt::error { + this.bind_tests(condition, true); + this.check_expr(then, expected); + this.check_owned(then, expected); + this.unbind_to(mark); + this.bind_tests(condition, false); + this.check_expr(other, expected); + this.check_owned(other, expected); + this.unbind_to(mark); + return expected; + } + + this.bind_tests(condition, true); + val a := this.infer_expr(then); + this.unbind_to(mark); + this.bind_tests(condition, false); + val b := this.infer_expr(other); + this.unbind_to(mark); + return bt::error if a == bt::error || b == bt::error; + + var shared := this.common(a, b); + if shared == bt::error { + shared = this.common(this.reached_value(a), this.reached_value(b)); + } + if shared == bt::error { + this.report_operands(node, a, b, "are the branches, which share no type"); + return bt::error; + } + this.bind_tests(condition, true); + this.convert(then, shared); + this.check_owned(then, shared); + this.unbind_to(mark); + this.bind_tests(condition, false); + this.convert(other, shared); + this.check_owned(other, shared); + this.unbind_to(mark); + + if this.is_known(condition) && this.is_known(then) && this.is_known(other) { + this.set_value(node, this.value_at(condition).magnitude != 0 ? this.value_at(then) : this.value_at(other)); + } + return shared; +} + +#! `x as T`, which converts between numbers, between integers and enums, +#! between pointers and integers, and between pointers of the same +#! mutability, as well as whatever converts without `as`. +#! @param this The checker. +#! @param node The `cast` node. +#! @returns The type converted to, or the error type where `as` does not convert +#! to it. +def checker::cast(&mut this, node: u32): u32 { + val value := this.left_of(node); + val target := this.resolve_type(this.right_of(node)); + val kind := this.infer_expr(value); + return bt::error if kind == bt::error || target == bt::error; + + val from := this.unalias(this.read_type(kind)); + val to := this.unalias(target); + val known := this.is_known(value); + + # A reference converts as the value it refers to, so `&x` written to convert + # to a number would give `x`, where its address was surely meant. + if this.kind_of(value) == nk::reference + && (this.types.is_numeric(to) || this.types.is_boolean(to) || this.named_kind(to) == dk::enum_type) { + this.report(node, ec::conversion, "`&x as` a number converts the value `x` holds, not its address: convert to a pointer first for the address, as `&x as *u8 as u64`, or drop the `&` for the value."); + return bt::error; + } + + # An enum member's value is known as an integer. + if known && this.named_kind(from) == dk::enum_type && this.types.is_integer(to) { + this.set_value(node, this.value_at(value)); + return target; + } + if known && this.types.is_numeric(from) && this.types.is_numeric(to) { + val held := this.value_at(value); + var made := held; + if this.types.is_float(to) && !held.floating { + made = constant::real_of(held.as_real()); + } else if this.types.is_integer(to) && held.floating { + made = constant::integer((held.real < 0.0 ? -held.real : held.real) as u64, held.real < 0.0); + } + # A typed value converts as the program running converts it, wrapping, and + # only a constant of no type is outside the range of what it converts to. + if this.types.is_integer(to) && !held.floating && !this.in_range(to, &made) && !this.types.is_untyped(kind) { + this.set_value(node, this.ev_wrap(made, to)); + return target; + } + if this.types.is_integer(to) && !held.floating && !this.in_range(to, &made) { + var text := string::from("The constant is outside the range of `", nothing {}); + val named := this.describe(target); + text.append(named.view()); + text.append("`."); + this.report_text(node, ec::overflow, &text); + return target; + } + this.set_value(node, made); + return target; + } + + return target if this.casts(kind, from, to); + + var text := string::from("`", nothing {}); + val given := this.describe(kind); + val want := this.describe(target); + text.append(given.view()); + text.append("` does not convert to `"); + text.append(want.view()); + text.append("` with `as`."); + this.report_text(node, ec::conversion, &text); + return bt::error; +} + +#! Whether `as` converts a value of the type `kind`, read as `from`, to `to`. +#! @param this The checker. +#! @param kind The value's type, as written. +#! @param from The type it is read as. +#! @param to The type converted to. +#! @returns Whether it converts. +def checker::casts(&mut this, kind: u32, from: u32, to: u32): bool { + val none := constant {}; + val how := this.fits(kind, to, &none, false, 0); + return true if how != fit::none; + + # A reference is the address of what it refers to, and a reference to an + # array that of its first element. + val raw := this.unalias(kind); + if this.types.kind_of(raw) == ty::reference + && (this.types.kind_of(to) == ty::pointer || this.is_std(to, word::cfn)) { + return this.is_std(to, word::cfn) || this.types.second_of(to) == 0 || this.types.second_of(raw) != 0; + } + + # What a type parameter's bounds let it be converted to, and from. + if this.types.kind_of(from) == ty::param && this.param_converts(from) + && (this.types.is_numeric(to) || this.named_kind(to) == dk::enum_type || this.types.kind_of(to) == ty::param) { + return true; + } + if this.types.kind_of(to) == ty::param && this.param_converts(to) + && (this.types.is_numeric(from) || this.named_kind(from) == dk::enum_type) { + return true; + } + + val fk := this.types.kind_of(from); + val tok := this.types.kind_of(to); + val from_number := this.types.is_numeric(from); + val to_number := this.types.is_numeric(to); + return true if from_number && to_number; + return true if (this.types.is_boolean(from) && to_number) || (from_number && this.types.is_boolean(to)); + return true if this.named_kind(from) == dk::enum_type && (to_number || this.named_kind(to) == dk::enum_type); + return true if from_number && this.named_kind(to) == dk::enum_type && this.types.is_integer(from); + + # Pointers convert to and from integers, and between types of the same + # mutability, or dropping it. A reference is the address of what it refers to. + val cfn_from := this.is_std(from, word::cfn); + val cfn_to := this.is_std(to, word::cfn); + val ptr_from := fk == ty::pointer || cfn_from; + val ptr_to := tok == ty::pointer || cfn_to; + return true if ptr_from && this.types.is_integer(to); + return true if this.types.is_integer(from) && ptr_to; + if (ptr_from || fk == ty::reference) && ptr_to { + return true if cfn_from || cfn_to; + val writes := this.types.second_of(from) != 0; + val wants := this.types.second_of(to) != 0; + return !wants || writes; + } + return fk == ty::null_type && ptr_to; +} + +#! Whether a type parameter's bounds let `as` convert it to and from numbers: +#! `numeric`, `integer`, `ordinal`, or `real`. +#! @param this The checker. +#! @param kind The type parameter's type. +#! @returns Whether its bounds let it. +def checker::param_converts(&mut this, kind: u32): bool { + val numeric := this.std_decl(word::numeric); + val integer := this.std_decl(word::integer); + val ordinal := this.std_decl(word::ordinal); + val real := this.std_decl(word::real); + return (numeric != 0 && this.param_bounded(kind, numeric)) || (integer != 0 && this.param_bounded(kind, integer)) + || (ordinal != 0 && this.param_bounded(kind, ordinal)) || (real != 0 && this.param_bounded(kind, real)); +} + +#! What `is` and `match` say of a C union, which holds no tag. +pub const c_union_untagged: strview = "A C union holds nothing saying which field it holds, so `is` and `match` can't ask: read the field it was written through."; + +#! `x is T`, `x is field`, `x is field(value)`, or `T is bound`: whether a type +#! satisfies a trait or is a type, or which field a union holds. +#! @param this The checker. +#! @param node The `is_test` node. +#! @returns `bool`, the test's type. +def checker::is_test(&mut this, node: u32): u32 { + val value := this.left_of(node); + val target := this.record(node, is_slot::target); + val binding := this.record(node, is_slot::binding); + val negated := this.node_has(node, nf::negated); + # `x is (d)` tests for the field of a union a description names, as though its + # name were written. Over a generic's own type parameters it waits for each + # instance, as reflection of them does. + if this.node_has(node, nf::computed) { + val kind := this.infer_expr(value); + this.infer_expr(target); + return bt::boolean if this.waits_for_instance() || kind == bt::error || this.type_at(target) == bt::error; + + val one := this.reflected_one(target); + if one == checker::no_reflection { + this.report(target, ec::constant, "`x is (d)` takes a declaration known while compiling, as the variable of `for const d in declarations()` is."); + return bt::boolean; + } + val held: desc = this.descs[one]; + val union_value := this.unalias(this.read_type(kind)); + val holder := this.named_kind(union_value) == dk::union_type ? this.types.first_of(union_value) : 0; + if holder != 0 && this.decls.has(holder, df::foreign) { + this.report(target, ec::invalid, c_union_untagged); + return bt::boolean; + } + if held.param != 0 || holder == 0 || this.decls.member(holder, this.decls.names.p[held.decl]) != held.decl + || this.decls.kinds.p[held.decl] != dk::field { + this.report(target, ec::invalid, "`x is (d)` asks which field a union holds, and `d` describes no field of this one."); + return bt::boolean; + } + this.set_ref(node, held.decl); + return bt::boolean; + } + + # Where the left names a type, the test asks of the type itself. `type_of(d)` + # always names one, which is not known where reflection waits for an instance. + val tested := this.tested_type(value); + if tested == bt::error && this.kind_of(value) == nk::type_of { + return bt::boolean; + } + if tested != 0 { + val bound := this.resolve_type(target); + this.decide_bound(node, tested, bound, negated); + return bt::boolean; + } + + val kind := this.infer_expr(value); + return bt::boolean if kind == bt::error; + + # A union's field, as `r is data`, with the value it holds where it is named. + val held := this.unalias(this.read_type(kind)); + if this.named_kind(held) == dk::union_type && this.kind_of(target) == nk::type_name && this.segment_count(target) == 1 { + val field := this.decls.member(this.types.first_of(held), this.name_of(target)); + if field != 0 && this.decls.kinds.p[field] == dk::field && this.decls.has(this.types.first_of(held), df::foreign) { + this.report(target, ec::invalid, c_union_untagged); + return bt::boolean; + } + if field != 0 && this.decls.kinds.p[field] == dk::field { + this.check_reaches(target, held, field); + this.set_ref(node, field); + if binding != 0 { + this.declare_binding(binding, this.instantiated(this.decls.types.p[field], this.types.first_of(held), held), value); + } + return bt::boolean; + } + } + + val bound := this.resolve_type(target); + if this.at.instance == 0 && this.is_fields_type(target, held, bound) { + return bt::boolean; + } + this.decide_bound(node, this.read_type(kind), bound, negated); + if binding != 0 { + this.report(binding, ec::invalid, "Only a union's field names the value it holds, as `r is data(text)`."); + } + return bt::boolean; +} + +#! Reports `x is T` of a union where `T` is the type of one of its fields, as +#! `m is nothing` of a `maybe`: `is` with a type asks the value's own type, +#! which is the union, so it is never true, and the field was meant. +#! @param this The checker. +#! @param target The node of the type. +#! @param held The type of the value tested. +#! @param bound The type it is tested against. +#! @returns Whether it was reported. +def checker::is_fields_type(&mut this, target: u32, held: u32, bound: u32): bool { + return false if bound == bt::error || bound == held || this.named_kind(held) != dk::union_type; + val holder := this.types.first_of(held); + for &field in this.decls.list_view(this.decls.children.p[holder]) { + continue if this.decls.kinds.p[field] != dk::field; + continue if this.instantiated(this.decls.types.p[field], holder, held) != bound; + var text := string::from("`is` with a type asks the value's own type, `", nothing {}); + text.append(this.describe(held).view()); + text.append("`, so this is never true; name the field holding a `"); + text.append(this.describe(bound).view()); + text.append("`, as `is "); + text.append(this.decl_text(field)); + text.append("`."); + this.report_text(target, ec::invalid, &text); + return true; + } + return false; +} + +#! The type an `is` test's left names, where it names one rather than a value, +#! or 0. +#! @param this The checker. +#! @param node The test's left. +#! @returns The type it names, the error type where it names one wrongly, or 0 +#! where it is a value. +def checker::tested_type(&mut this, node: u32): u32 { + match this.kind_of(node) { + nk::type_of => return this.resolve_type(node); + nk::name => { + # A constant parameter names a value, which is tested as one. + val bound := this.bound(this.name_of(node)); + return 0 if (bound & ref_type) != 0 && this.is_constant_arg(bound & ref_mask); + return bound & ref_mask if (bound & ref_type) != 0; + return 0 if bound != 0; + val decl := this.lookup_global(this.name_of(node), 0); + return this.is_type_decl(decl) ? this.decls.types.p[decl] : 0; + } + nk::path => { + val first := this.segment_name(node, 0); + return 0 if this.bound(first) != 0 && (this.bound(first) & ref_type) == 0; + val decl := this.lookup_type(first, 0); + if (this.bound(first) & ref_type) != 0 || this.is_type_decl(decl) { + val target := this.path_target(node); + return target.kind != bt::error ? target.kind : this.is_type_decl(target.decl) ? this.decls.types.p[target.decl] : 0; + } + return 0; + } + else => return 0; + } + return 0; +} + +#! Decides a test of whether a type satisfies a trait, or is a type, where it +#! can be decided while checking. +#! @param this The checker. +#! @param node The test's node, which takes the constant decided. +#! @param given The type tested. +#! @param bound The trait or type it is tested against. +#! @param negated Whether the test is `is not`. +def checker::decide_bound(&mut this, node: u32, given: u32, bound: u32, negated: bool): void { + return if given == bt::error || bound == bt::error; + + # A constant is tested as the type it settles as, as `1 is integer` is. + val kind := this.types.is_untyped(given) ? this.settle(given) : given; + var holds := false; + if this.named_kind(bound) == dk::trait_type { + holds = this.satisfies(kind, bound); + } else { + holds = kind == bound; + } + + # What a type parameter satisfies is known by its bounds, and what it is not + # is only known of each instance. + if this.types.is_open(kind) && !holds { + return; + } + this.set_value(node, constant::truth(holds != negated)); +} + +#! Declares the name an `is` test or an arm gives the value of a union's field, +#! a copy of it, or with `&` or `&mut` a reference to it. A field that closes is +#! taken out of a value a call made, which hands it over, as `else` and `for` +#! take theirs, where a variable keeps it. A value of its own can be changed and +#! moved from, as a `var` can. +#! @param this The checker. +#! @param binding The node of the name, or of `&name` or `&mut name`. +#! @param kind The field's type. +#! @param union_value The node of the union tested or matched. +pub def checker::declare_binding(&mut this, binding: u32, kind: u32, union_value: u32): void { + # A field holding a reference, as `some` of a `maybe<&T>`, gives that + # reference: `&` and `&mut` name it, and a name alone takes what it reaches. + val holds_reference := this.types.kind_of(this.unalias(kind)) == ty::reference; + if this.kind_of(binding) == nk::reference { + val name := this.left_of(binding); + val mutable := this.node_has(binding, nf::mutable); + if this.decide(binding, rf::relent, holds_reference) { + if mutable && this.types.second_of(this.unalias(kind)) == 0 { + this.report(binding, ec::assignable, "`&mut` refers to what can be written, and the field holds a `&` reference."); + } + this.set_type(name, this.types.reference(this.types.first_of(this.unalias(kind)), mutable)); + this.set_flag(name, rf::local); + this.set_flag(name, rf::narrowed); + return; + } + if mutable && !this.is_writable(union_value) { + this.report(binding, ec::assignable, "`&mut` refers to the field in place, so the union must be writable."); + } + this.set_type(name, this.types.reference(kind, mutable)); + this.set_flag(name, rf::local); + this.set_flag(name, rf::narrowed); + return; + } + + val unnamed := this.kind_of(binding) == nk::name && this.name_of(binding) == names::underscore_id; + # Within an instance, a field the template held as a value, as `T`, stays as + # the template took it. + val copies := !unnamed && this.decide(binding, rf::valued, this.has_value(kind)); + val held := copies ? this.types.first_of(this.unalias(kind)) : kind; + val kept := copies || this.is_place(union_value) + || this.types.kind_of(this.unalias(this.type_at(union_value))) == ty::reference; + if !unnamed && kept && this.closes(held) { + var text := string::from("`", nothing {}); + val named := this.describe(held); + text.append(named.view()); + text.append(copies + ? "` is closed where its scope ends, and the field refers to it where its owner holds it; name it by `&` or `&mut` rather than taking a copy of it." + : "` is closed where its scope ends, so the variable holding the union owns the field; name it by `&` or `&mut` rather than taking a copy of it."); + this.report_text(binding, ec::owned, &text); + } + this.set_type(binding, held); + this.set_flag(binding, rf::local); + this.set_flag(binding, rf::narrowed); + # A copy of what a reference reaches is only read, as a `for` pass's is. + if !copies { + this.set_flag(binding, rf::mutable); + } +} + +#! The node an `is` test or an arm names the value of a union's field by, as +#! `v`, `&v`, or `&mut v`, or 0 where it names none, or names it `_`, which takes +#! nothing out of the union: `x is some(_)` asks only what `x is some` does. +#! @param this The checker. +#! @param binding The node written for it, or 0. +#! @returns The node, or 0. +pub def checker::named_binding(&this, binding: u32): u32 { + return 0 if binding != 0 && this.kind_of(binding) == nk::name && this.name_of(binding) == names::underscore_id; + return binding; +} + +#! Binds the names the tests of a condition give, where the condition holding +#! means what `positive` says: the names of `x is f(v)` where it holds, and of +#! `x is not f(v)` where it does not. +#! @param this The checker. +#! @param condition The condition's node. +#! @param positive Whether the condition holds where the names are bound. +pub def checker::bind_tests(&mut this, condition: u32, positive: bool): void { + return if condition == 0; + match this.kind_of(condition) { + nk::is_test => { + val negated := this.node_has(condition, nf::negated); + return if negated == positive; + val binding := this.record(condition, is_slot::binding); + return if binding == 0; + val name := this.kind_of(binding) == nk::reference ? this.left_of(binding) : binding; + return if !this.has_flag(name, rf::narrowed); + this.bind(this.name_of(name), ref_local | name); + } + nk::binary => { + val operator := this.token_kind(condition); + if (operator == tk::logand && positive) || (operator == tk::logor && !positive) { + this.bind_tests(this.left_of(condition), positive); + this.bind_tests(this.right_of(condition), positive); + } + } + nk::unary => { + if this.token_kind(condition) == tk::negate { + this.bind_tests(this.left_of(condition), !positive); + } + } + else => {} + } +} diff --git a/analyzer/checker/ownership.sakura b/analyzer/checker/ownership.sakura new file mode 100644 index 00000000..3dc8a4aa --- /dev/null +++ b/analyzer/checker/ownership.sakura @@ -0,0 +1,184 @@ +#! @file ownership.sakura +#! @author John Christman (sorakatadzuma@gmail.com) +#! @copyright Malunal Studios, LLC. +#! @license MIT +#! +#! Contains the rules of owning values: a value of a type that closes, as a +#! `string`, has one owner, so it is never copied out of the place holding it +#! without saying so, and what a loop iterates is locked while the loop's body +#! runs, so the body cannot change it. + +module sakura::analyzer; + + +#! Whether values of the type are closed where their scope ends: the type +#! names `owning`, or holds a value that does in its fields or +#! elements. A reference or pointer holds nothing of its own. +#! @param this The checker. +#! @param kind The type. +#! @returns Whether they are. +pub def checker::closes(&mut this, kind: u32): bool { + return false if kind == bt::error || this.types.is_untyped(kind); + val flags := this.types.flags.p[kind]; + return (flags & tf::closes as u8) != 0 if (flags & tf::weighed as u8) != 0; + # Weighed as closing nothing while it is worked out, so a type holding + # itself through a pointer is met again as one that does not. + this.types.flags.p[kind] = flags | tf::weighed as u8; + + val plain := this.unalias(kind); + var made := false; + match this.types.kind_of(plain) { + ty::fixed => made = this.closes(this.types.first_of(plain)); + ty::named => { + val decl := this.types.first_of(plain); + val kind_of: dk = this.decls.kinds.p[decl]; + if kind_of == dk::struct_type || kind_of == dk::union_type { + val owning := this.std_decl(word::owning); + made = owning != 0 && this.names_trait(plain, owning) && this.has_close(plain); + if !made { + val fields := this.field_types(plain); + for &each in fields { + made = made || this.closes(each); + } + } + } + } + ty::param => { + val owning := this.std_decl(word::owning); + made = owning != 0 && this.param_bounded(plain, owning); + } + else => {} + } + + if made { + this.types.flags.p[kind] |= tf::closes as u8; + } + return made; +} + +#! Whether the type has the `close(&mut this): void` of `owning`. +#! @param this The checker. +#! @param kind The type. +#! @returns Whether it has. +def checker::has_close(&mut this, kind: u32): bool { + val found := this.find_member(kind, word::close); + return false if found.decl == 0 || this.decls.kinds.p[found.decl] != dk::function; + var walk := this.decls.walk_overloads(found.decl); + while true { + val at := walk.next(); + break if at == 0; + continue if !this.member_seen(at); + this.resolve(at); + if this.decls.has(at, df::mut_this) && this.types.part_count(this.decls.types.p[at]) == 1 { + return true; + } + } + return false; +} + +#! Reports a value that closes copied out of the place holding it, where it is +#! taken as a value of the type `to`. A new value, as a call gives, is moved. +#! What a reference refers to is copied where it is read through as a whole, and +#! its owner still holds it. +#! @param this The checker. +#! @param node The value's node. +#! @param to The type it is taken as. +pub def checker::check_owned(&mut this, node: u32, to: u32): void { + return if node == 0 || to == bt::error; + return if this.types.kind_of(this.unalias(to)) == ty::reference; + val kind := this.type_at(node); + if this.types.kind_of(kind) == ty::reference { + return if !this.closes(to); + var text := string::from("`", nothing {}); + val named := this.describe(to); + text.append(named.view()); + text.append("` is closed where its scope ends, so it has one owner, which still holds what the reference refers to. Refer to it with `&` or `&mut`, or copy or move it by name."); + this.report_text(node, ec::owned, &text); + return; + } + # The field of a union is read as a copy, but the union still owns what it + # holds and closes it, even where the union is only a call's result. + if this.union_field(node) && this.closes(kind) && this.closes(to) { + var text := string::from("`", nothing {}); + val named := this.describe(kind); + text.append(named.view()); + text.append("` is closed where its scope ends, so the union holding it owns it and it cannot be copied out. Name it with `match` by `&` or `&mut`, and copy or move it by name."); + this.report_text(node, ec::owned, &text); + return; + } + # Taken as a view, as a string lends a `span` of itself, it is not copied. + return if !this.is_place(node) || !this.closes(kind) || !this.closes(to); + + var text := string::from("`", nothing {}); + val named := this.describe(kind); + text.append(named.view()); + text.append("` is closed where its scope ends, so it has one owner and is not copied out of the place holding it. Refer to it with `&` or `&mut`, or copy or move it by name."); + this.report_text(node, ec::owned, &text); +} + +#! Whether a node reads a field of a union, as `r.value` does of a `result`. +#! @param this The checker. +#! @param node The node. +#! @returns Whether it does. +def checker::union_field(&mut this, node: u32): bool { + return false if this.kind_of(node) != nk::member; + val held := this.unalias(this.reached_value(this.type_at(this.left_of(node)))); + return this.named_kind(held) == dk::union_type; +} + +#! Whether a place is part of what a pointer points at, as `p[0]` and +#! `(*p).next` are, which the compiler never closes, since a pointer owns +#! nothing. +#! @param this The checker. +#! @param node The place's node. +#! @returns Whether it is. +pub def checker::pointed_at(&mut this, node: u32): bool { + var at := node; + var steps := 0; + while at != 0 && steps < 64 { + steps++; + val kind := this.kind_of(at); + return false if kind != nk::member && kind != nk::index && !(kind == nk::unary && this.token_kind(at) == tk::star); + at = this.left_of(at); + return true if this.types.kind_of(this.unalias(this.type_at(at))) == ty::pointer; + } + return false; +} + +#! What a place is a part of, followed to the variable it is in: the local or +#! declaration it names, or 0 where it is in none, as a new value. +#! @param this The checker. +#! @param node The place's node. +#! @returns What the variable's name refers to, or 0. +pub def checker::root_ref(&this, node: u32): u32 { + var at := node; + var steps := 0; + while at != 0 && steps < 64 { + steps++; + match this.kind_of(at) { + nk::name => return this.ref_at(at); + nk::member, nk::index, nk::slice => at = this.left_of(at); + nk::unary => { + return 0 if this.token_kind(at) != tk::star; + at = this.left_of(at); + } + else => return 0; + } + } + return 0; +} + +#! Reports a change of what a loop around it iterates. +#! @param this The checker. +#! @param node The node of what is changed. +pub def checker::check_unlocked(&mut this, node: u32): void { + return if this.locks.length == 0; + val root := this.root_ref(node); + return if root == 0; + for i in 0..this.locks.length { + if this.locks[i] == root { + this.report(node, ec::locked, "A loop iterates this, so the loop's body does not change it."); + return; + } + } +} diff --git a/analyzer/checker/patterns.sakura b/analyzer/checker/patterns.sakura new file mode 100644 index 00000000..f2dc3554 --- /dev/null +++ b/analyzer/checker/patterns.sakura @@ -0,0 +1,509 @@ +#! @file patterns.sakura +#! @author John Christman (sorakatadzuma@gmail.com) +#! @copyright Malunal Studios, LLC. +#! @license MIT +#! +#! Contains how the type arguments written for a generic type are given to its +#! type parameters: one each, a pack the arguments after those before it, and a +#! pattern parameter, `def(Ts...): R`, the parts of the function type it is +#! given, as `invokable` gives `Ts` the pack `(i64, bool)` +#! and `R` the type `u8`. A declaration's type parameters are those its +#! patterns name, so everything past writing its arguments sees only them. + +module sakura::analyzer; + + +#! What marks a pattern among the entries of a written shape, as `record_shape` +#! makes them: 0 for a type parameter written plainly, 1 for a pack, and for a +#! pattern this mark, with how many parameter types it names shifted left by 2, +#! 2 where the last of them is a pack, and 1 where it names its result. +pub const checker::pattern_mark: u32 = 0x80000000; + +#! What marks a pattern of a fixed array, `L[N]`, beside `pattern_mark`, which +#! names its element's type and its length. +pub const checker::array_mark: u32 = 0x40000000; + +#! Records the written shape of a declaration's own type parameters where a +#! pattern is among them, while the file declaring it is the one checked, so +#! its type arguments are given their parameters from any file. +#! @param this The checker. +#! @param decl The declaration. +#! @param run The run of its own type parameters as written. +pub def checker::record_shape(&mut this, decl: u32, run: u32): void { + var entries := vector::::new(); + var any := false; + for &each in this.run_view(run) { + if this.kind_of(each) == nk::type_pattern { + val params := this.left_of(each); + val count := this.run_length(params); + val packed := count != 0 && this.node_has(this.run_at(params, count - 1), nf::packed); + entries.append(checker::pattern_mark | (count << 2) | (packed ? 2 : 0) | (this.right_of(each) != 0 ? 1 : 0)); + any = true; + } else if this.kind_of(each) == nk::array_pattern { + entries.append(checker::pattern_mark | checker::array_mark); + any = true; + } else { + entries.append(this.kind_of(each) == nk::type_param && this.node_has(each, nf::packed) ? 1 : 0); + } + } + if any { + this.shapes.set(decl, this.decls.make_list(entries.view())); + } +} + +#! The written shape of a declaration's own type parameters: as recorded where +#! a pattern is among them, or else one entry for each, a pack's 1. +#! @param this The checker. +#! @param decl The declaration. +#! @returns The entries, as `pattern_mark` says. +def checker::shape_of(&this, decl: u32): vector { + if this.shapes.get(&decl) is some(got) { + return this.decls.list_of(got); + } + var made := vector::::new(); + val params: u32 = this.decls.params.p[decl]; + val wanted := this.decls.list_length(params); + val own := this.own_param_count(decl); + for k in (wanted >= own ? wanted - own : 0)..wanted { + made.append(this.decls.has(this.decls.list_at(params, k as u32), df::packed) ? 1 : 0); + } + return made; +} + +#! How many type parameters an entry of a written shape names: a pattern one +#! for each of its parameter types and one for its result, or of a fixed array +#! its element's and its length's, and anything else itself. +#! @param this The checker. +#! @param entry The entry. +#! @returns How many. +def checker::named_count(&this, entry: u32): u32 { + return 1 if (entry & checker::pattern_mark) == 0; + return 2 if (entry & checker::array_mark) != 0; + return ((entry & ~checker::pattern_mark) >> 2) + (entry & 1); +} + +#! Whether a declaration is written with a pattern among its own type +#! parameters. +#! @param this The checker. +#! @param decl The declaration. +#! @returns Whether it is. +pub def checker::has_patterns(&this, decl: u32): bool { + return this.shapes.contains(&decl); +} + +#! The type parameter a type argument written at a place is given to: one of a +#! type the declaration is within, one of its own, or the pack taking the rest, +#! or 0 for a pattern, whose type parameters are given the parts of what is +#! written. +#! @param this The checker. +#! @param decl The generic declaration. +#! @param index The place of the type argument among those written. +#! @returns The type parameter's declaration, or 0. +pub def checker::param_written_at(&this, decl: u32, index: u32): u32 { + val params: u32 = this.decls.params.p[decl]; + val wanted := this.decls.list_length(params); + var shape := this.shape_of(decl); + var own: u32 = 0; + for &each in shape { + own += this.named_count(each); + } + val lead: u32 = wanted >= own ? wanted - own : 0; + return index < wanted ? this.decls.list_at(params, index) : 0 if index < lead; + + var at := lead; + for i in 0..shape.length { + val each := shape[i]; + val packs := each == 1; + if i as u32 == index - lead || (packs && index - lead > i as u32) { + return (each & checker::pattern_mark) != 0 || at >= wanted ? 0 : this.decls.list_at(params, at); + } + at += this.named_count(each); + } + return 0; +} + +#! Gives the type arguments written for a generic type to its type parameters, +#! after those of any type it is declared within, which are given one each: one +#! each to those written plainly, the rest to a pack, and to a pattern the parts +#! of the function type it is given. +#! @param this The checker. +#! @param decl The generic type's declaration. +#! @param args The type arguments as written, those of the types it is +#! declared within first. +#! @param node The node notes are placed at. +#! @param into What each of its type parameters is given, in order. +#! @returns Whether they were given, which notes say why not where not. +pub def checker::bind_written(&mut this, decl: u32, args: span, node: u32, into: &mut vector): bool { + val params: u32 = this.decls.params.p[decl]; + val wanted := this.decls.list_length(params); + var shape := this.shape_of(decl); + var own: u32 = 0; + for &each in shape { + own += this.named_count(each); + } + # A type declared within a generic one takes that one's parameters first. + val lead: u32 = wanted >= own ? wanted - own : 0; + val count := shape.length as u32; + val last_packs := count != 0 && shape[count as u64 - 1] == 1; + val written := lead + count; + + var at: u64 = 0; + for i in 0..lead { + break if at >= args.length; + into.append(args[at]); + at++; + } + for i in 0..count { + val each := shape[i]; + if each == 1 { + # A pack takes the type arguments after those before it. + val pack := this.gather_pack(args, at, node); + return false if pack == bt::error; + into.append(pack); + at = args.length; + continue; + } + break if at >= args.length; + if (each & checker::array_mark) != 0 { + return false if !this.destructure_array(decl, args[at], node, into); + } else if (each & checker::pattern_mark) != 0 { + return false if !this.destructure(each, decl, args[at], node, into); + } else { + if this.types.kind_of(args[at]) == ty::pack { + this.report(node, ec::generic, "A pack is passed on with `...` only for a pack parameter, as `Ts` of `box`."); + return false; + } + into.append(args[at]); + } + at++; + } + + if at != args.length || into.length != wanted as u64 { + var text := string::from("`", nothing {}); + text.append(this.decl_text(decl)); + val words := last_packs + ? $"` takes at least {written - 1} type arguments, but is given {args.length}." + : $"` takes {written} type arguments, but is given {args.length}."; + text.append(words.view()); + this.report_text(node, ec::generic, &text); + return false; + } + return true; +} + +#! Gives a pattern parameter's type parameters the parts of the function type it +#! is given: those of its parameters before a pack each take one of the +#! function's parameters, the pack the rest, as a variadic function's are where +#! it is one, and its result the function's. +#! @param this The checker. +#! @param pattern The pattern's entry in its declaration's written shape. +#! @param decl The generic type's declaration. +#! @param arg The type the pattern is given. +#! @param node The node notes are placed at. +#! @param into What the pattern's type parameters are given, in order. +#! @returns Whether the type fits the pattern, which a note says why not where +#! not. +def checker::destructure(&mut this, pattern: u32, decl: u32, arg: u32, node: u32, into: &mut vector): bool { + val count := (pattern & ~checker::pattern_mark) >> 2; + val packed := (pattern & 2) != 0; + val result := (pattern & 1) != 0; + val fixed := packed ? count - 1 : count; + + # The address of a C function is given as the function type it is of, and a + # type parameter that is a `signature`, as `F`, its `F::params` and `F::result`. + val plain := this.signature_function(arg); + val bare := this.unalias(arg); + if plain == 0 && this.types.kind_of(bare) == ty::param { + val sig := this.std_decl(word::signature); + if sig != 0 && this.satisfies(bare, this.decls.types.p[sig]) { + if fixed != 0 || !packed { + var text := string::from("`", nothing {}); + val named := this.describe(arg); + text.append(named.view()); + text.append("` is a signature whose parameters are not known yet, so the pattern of `"); + text.append(this.decl_text(decl)); + text.append("` takes it only where it names them as one pack, as `def(Ts...): R`."); + this.report_text(node, ec::generic, &text); + return false; + } + into.append(this.projected(bare, this.trait_member(sig, word::params), this.decls.types.p[sig])); + if result { + into.append(this.projected(bare, this.trait_member(sig, word::result), this.decls.types.p[sig])); + } + return true; + } + } + if plain == 0 { + var text := string::from("`", nothing {}); + text.append(this.decl_text(decl)); + text.append("` is given a function type where it takes `def(...)`, as `def(i64): i64`, and this is `"); + val named := this.describe(arg); + text.append(named.view()); + text.append("`."); + this.report_text(node, ec::generic, &text); + return false; + } + + # The parameters taking one value each, before any taking the rest. + val parts := this.types.part_count(plain); + val variadic := this.types.second_of(plain) != 0 && parts != 0; + val singles := variadic ? parts - 1 : parts; + val open := variadic && this.types.is_open_pack(this.types.part_at(plain, parts - 1)); + if (packed && singles < fixed) || (!packed && (variadic || singles != fixed)) || (packed && open && singles != fixed) { + var text := string::from("`", nothing {}); + val named := this.describe(arg); + text.append(named.view()); + text.append(open && singles > fixed + ? "` ends in a pack whose types are not known yet, which a pattern's pack takes only alone." + : "` does not have the parameters the pattern of `"); + if !(open && singles > fixed) { + text.append(this.decl_text(decl)); + text.append(packed + ? "` asks for: at least as many before any taking the rest as it names before its pack." + : "` asks for: as many as it names, none taking the rest."); + } + this.report_text(node, ec::generic, &text); + return false; + } + + for k in 0..fixed { + into.append(this.types.part_at(plain, k as u32)); + } + if packed { + into.append(open ? this.types.part_at(plain, parts - 1) : this.types.params_pack(plain, fixed)); + } + if result { + into.append(this.types.first_of(plain)); + } + return true; +} + +#! Gives a pattern parameter, `L[N]`, the parts of the fixed array it is given: +#! its element's type to `L`, and its length to `N`, as a `u64`. +#! @param this The checker. +#! @param decl The generic type's declaration. +#! @param arg The type the pattern is given. +#! @param node The node notes are placed at. +#! @param into What the pattern's type parameters are given, in order. +#! @returns Whether the type fits the pattern, which a note says why not where +#! not. +def checker::destructure_array(&mut this, decl: u32, arg: u32, node: u32, into: &mut vector): bool { + val plain := this.unalias(arg); + if this.types.kind_of(plain) != ty::fixed { + var text := string::from("`", nothing {}); + text.append(this.decl_text(decl)); + text.append("` is given a fixed array where it takes `L[N]`, as `f32[4]`, and this is `"); + val named := this.describe(arg); + text.append(named.view()); + text.append("`."); + this.report_text(node, ec::generic, &text); + return false; + } + into.append(this.types.first_of(plain)); + # A length only each instance knows is given as it is. + if this.types.part_count(plain) != 0 { + into.append(this.types.part_at(plain, 0)); + } else { + into.append(this.known_type(this.known_number(constant::integer(this.types.second_of(plain) as u64, false), bt::uint64))); + } + return true; +} + +#! Writes the type arguments of a type declared with patterns as they are written, +#! a function type for each pattern, as `invokable`. +#! @param this The checker. +#! @param kind The named type. +#! @param out What it is written into. +#! @param depth How deeply the writing has gone. +def checker::describe_written(&this, kind: u32, out: &mut string, depth: u32): void { + val decl := this.types.first_of(kind); + var shape := this.shape_of(decl); + val total := this.types.part_count(kind); + var own: u32 = 0; + for &each in shape { + own += this.named_count(each); + } + val lead: u32 = total >= own ? total - own : 0; + + var at: u32 = 0; + var written := false; + for i in 0..lead { + this.describe_arg(this.types.part_at(kind, at), out, depth + 1, &mut written); + at++; + } + for i in 0..shape.length { + val each := shape[i]; + break if at >= total; + if (each & checker::pattern_mark) == 0 { + this.describe_arg(this.types.part_at(kind, at), out, depth + 1, &mut written); + at++; + continue; + } + out.append(written ? ", " : ""); + written = true; + + # A fixed array's pattern, as the array it was given the parts of. + if (each & checker::array_mark) != 0 { + this.describe_into(this.types.part_at(kind, at), out, depth + 1); + out.append("["); + if at + 1 < total { + this.describe_into(this.types.part_at(kind, at + 1), out, depth + 1); + } + out.append("]"); + at += 2; + continue; + } + + # A signature `F` given whole is written as itself. + val count := (each & ~checker::pattern_mark) >> 2; + val packed := (each & 2) != 0; + if count == 1 && packed && (each & 1) != 0 && at + 1 < total { + val given := this.signature_given(this.types.part_at(kind, at), this.types.part_at(kind, at + 1)); + if given != 0 { + this.describe_into(given, out, depth + 1); + at += 2; + continue; + } + } + + # The function type the pattern's type parameters were given the parts of. + out.append("def("); + for k in 0..count { + break if at >= total; + out.append(k != 0 ? ", " : ""); + val part := this.types.part_at(kind, at); + if packed && k + 1 == count && this.types.is_known_pack(part) { + for j in 0..this.types.part_count(part) { + out.append(j != 0 ? ", " : ""); + this.describe_into(this.types.part_at(part, j as u32), out, depth + 1); + } + if this.types.second_of(part) != 0 { + out.append("..."); + } + } else { + this.describe_into(part, out, depth + 1); + } + at++; + } + out.append("): "); + if (each & 1) != 0 && at < total { + this.describe_into(this.types.part_at(kind, at), out, depth + 1); + at++; + } + } +} + +#! Writes type arguments as notes spell them, each after a comma but the +#! first: a pack whose types are known as the types it gives, as `i64, bool` +#! of a pack given for `Ts...`, and an empty one as none. +#! @param this The checker. +#! @param args The type arguments. +#! @param out What they are written into. +#! @param depth How deeply the writing has gone, at the arguments. +pub def checker::describe_args(&this, args: span, out: &mut string, depth: u32 = 0): void { + var written := false; + for &arg in args { + this.describe_arg(arg, out, depth, &mut written); + } +} + +#! Writes a type argument after those already written: a pack whose types are +#! known as the types it gives, or another type as it is. +#! @param this The checker. +#! @param arg The type argument. +#! @param out What it is written into. +#! @param depth How deeply the writing has gone, at the argument. +#! @param written Whether a type argument is written before it, which it sets. +pub def checker::describe_arg(&this, arg: u32, out: &mut string, depth: u32, written: &mut bool): void { + if !this.types.is_known_pack(arg) { + out.append(written ? ", " : ""); + this.describe_into(arg, out, depth); + written = true; + return; + } + for &part in this.types.parts_view(arg) { + out.append(written ? ", " : ""); + this.describe_into(part, out, depth); + written = true; + } +} + +#! The type of a value a pack holds: its type, or for the last of a variadic +#! function's pack, the view of the rest it holds. +#! @param this The checker. +#! @param pack The pack's type. +#! @param index The value's place. +#! @returns The type. +pub def checker::pack_value_type(&mut this, pack: u32, index: u32): u32 { + val part := this.types.part_at(pack, index); + return this.types.second_of(pack) != 0 && index + 1 == this.types.part_count(pack) ? this.span_of(part) : part; +} + +#! The function type a signature is: a function type itself, or the one the +#! address of a C function, `cfn`, is of. +#! @param this The checker. +#! @param kind The type. +#! @returns The function type, or 0 where the type is no signature. +pub def checker::signature_function(&mut this, kind: u32): u32 { + val plain := this.unalias(kind); + return plain if this.types.kind_of(plain) == ty::function; + if this.is_std(plain, word::cfn) && this.types.part_count(plain) != 0 { + val inner := this.unalias(this.types.part_at(plain, 0)); + return inner if this.types.kind_of(inner) == ty::function; + } + return 0; +} + +#! What `signature` asks of a type it decides: a function's `result`, and its +#! `params`, the pack of its parameters' types, variadic where it is. +#! @param this The checker. +#! @param kind The type. +#! @param asked The declaration of the type `signature` asks for. +#! @returns The type, or 0 where the type is no signature or the trait asking +#! is not `signature`. +pub def checker::signature_part(&mut this, kind: u32, asked: u32): u32 { + val holder: u32 = this.decls.owners.p[asked]; + return 0 if holder == 0 || this.decls.names.p[holder] != word::signature || this.std_decl(word::signature) != holder; + val function := this.signature_function(kind); + return 0 if function == 0; + return this.types.first_of(function) if this.decls.names.p[asked] == word::result; + return this.parameters_of(function, 0) if this.decls.names.p[asked] == word::params; + return 0; +} + +#! The pack of a function type's parameter types from `from` on, variadic where +#! the function is, or where they are only a pack whose types are not known, as +#! those of `def(Ts...): R`, that pack. +#! @param this The checker. +#! @param function The function type. +#! @param from The first parameter the pack holds. +#! @returns The pack. +pub def checker::parameters_of(&mut this, function: u32, from: u32): u32 { + val count := this.types.part_count(function); + if this.types.second_of(function) != 0 && count == from + 1 && this.types.is_open_pack(this.types.part_at(function, from)) { + return this.types.part_at(function, from); + } + return this.types.params_pack(function, from); +} + +#! The type `F` whose `params` and `result` stand in for what a pattern's type +#! parameters were given, where they do, so a type it was given `F` is written +#! with it, as `invokable`. +#! @param this The checker. +#! @param pack What the pattern's pack was given. +#! @param result What its result was given. +#! @returns `F`, or 0. +def checker::signature_given(&this, pack: u32, result: u32): u32 { + return 0 if !this.types.is_open_pack(pack) || this.types.kind_of(result) != ty::param; + var base: u32 = 0; + for &each in this.stand_ins { + if each.param == this.types.first_of(pack) && this.decls.names.p[each.asked] == word::params { + base = each.base; + } + } + return 0 if base == 0; + for &each in this.stand_ins { + return base if each.param == this.types.first_of(result) && each.base == base && this.decls.names.p[each.asked] == word::result; + } + return 0; +} diff --git a/analyzer/checker/reflection.sakura b/analyzer/checker/reflection.sakura new file mode 100644 index 00000000..5e52691d --- /dev/null +++ b/analyzer/checker/reflection.sakura @@ -0,0 +1,523 @@ +#! @file reflection.sakura +#! @author John Christman (sorakatadzuma@gmail.com) +#! @copyright Malunal Studios, LLC. +#! @license MIT +#! +#! Contains reflection: what a program reads of its own declarations while +#! compiling. A description names a declaration, or a function's parameter, +#! and an expression giving one, or a list of them, as `declarations()` or +#! `params_of(d)`, has them as a result of its own. What they say that `if +#! const` decides by, as `d.kind` or how many there are, is known while +#! checking, and `for const` walks a list, checking its body once for each. + +module sakura::analyzer; + + +#! What reflection describes: a declaration, or one of a function's parameters, +#! and where it is in a generic type, the instance it was reached through, as +#! `page` of `decl_of::>()` and of each of its members. +pub struct desc { + pub var decl: u32; #! The declaration. + pub var param: u32; #! One more than the index of the parameter it is, or 0 for the declaration itself. + var owner: u32; #! The instance whose arguments the generic type's parameters take, or 0. + var next: u32; #! The description of the same declaration through another instance, or `no_reflection`. +} + +#! The kinds of what an expression of reflection gives. +pub enum rk : u32 { + one = 1, #! A description. + list = 2, #! A list of descriptions. +} + +#! The description of the declaration, or of its parameter, made where it is +#! new. +#! @param this The checker. +#! @param decl The declaration. +#! @param param One more than the index of the parameter, or 0 for the +#! declaration itself. +#! @returns The description's index in `descs`. +pub def checker::describe_decl(&mut this, decl: u32, param: u32): u32 { + return this.describe_owned(decl, param, 0); +} + +#! The description of the declaration, or of its parameter, reached through the +#! instance of the generic type it is in, made where it is new. +#! @param this The checker. +#! @param decl The declaration. +#! @param param One more than the index of the parameter, or 0 for the +#! declaration itself. +#! @param owner The instance it is reached through, or 0. +#! @returns The description's index in `descs`. +pub def checker::describe_owned(&mut this, decl: u32, param: u32, owner: u32): u32 { + val key := pair_key(decl, param); + var first := checker::no_reflection; + if this.desc_ids.get(&key) is some(got) { + first = got; + } + var at := first; + while at != checker::no_reflection { + val held: desc = this.descs[at]; + return at if held.owner == owner; + at = held.next; + } + + val id := this.descs.length as u32; + this.descs.append(desc { decl = decl, param = param, owner = owner, next = first }); + this.desc_ids.set(key, id); + return id; +} + +#! The instance a member of the description's declaration is reached through: +#! the description's own, where it describes a generic type through one. +#! @param this The checker. +#! @param held The description. +#! @returns The instance, or 0. +def checker::member_owner(&mut this, held: desc): u32 { + return 0 if held.owner == 0 || this.type_decl(held.owner) != held.decl; + return held.owner; +} + +#! Records that the node gives the descriptions, one or a list of them. +#! @param this The checker. +#! @param node The node. +#! @param kind Whether it gives one or a list. +#! @param items The descriptions' indices in `descs`. +pub def checker::set_reflected(&mut this, node: u32, kind: rk, items: span): void { + this.reflected.push(kind as u32); + for &each in items { + this.reflected.push(each); + } + this.reflections.set(this.result_key(node), this.reflected.end()); + this.set_flag(node, rf::reflected); +} + +#! Where the descriptions the node gives are recorded, or `no_reflection`. +#! @param this The checker. +#! @param node The node. +#! @returns Their run in `reflected`, or `no_reflection`. +pub def checker::reflected_at(&this, node: u32): u32 { + # A node a table holds says whether it gives any, which most give none of. + val at := this.slot(node); + if at < this.r_flags.length && (this.r_flags.p[at] & rf::reflected as u16) == 0 { + return checker::no_reflection; + } + val key := this.result_key(node); + return this.reflections.get_or(&key, checker::no_reflection); +} + +#! What says a node gives no descriptions, and a description has no other +#! instance. +pub const checker::no_reflection: u32 = 0xFFFFFFFF; + +#! Whether what a node gives is one description or a list, as `rk` says. +#! @param this The checker. +#! @param at Its run in `reflected`. +#! @returns The `rk`, as an integer. +pub def checker::reflected_kind(&this, at: u32): u32 { return this.reflected.at(at, 0); } + +#! How many descriptions a node gives. +#! @param this The checker. +#! @param at Their run in `reflected`. +#! @returns How many. +pub def checker::reflected_count(&this, at: u32): u32 { return (this.reflected.length(at) - 1) as u32; } + +#! One of the descriptions a node gives. +#! @param this The checker. +#! @param at Their run in `reflected`. +#! @param index Its position, below their count. +#! @returns The description's index in `descs`. +pub def checker::reflected_item(&this, at: u32, index: u32): u32 { return this.reflected.at(at, index as u64 + 1); } + +#! The one description the node gives, or `no_reflection`. +#! @param this The checker. +#! @param node The node. +#! @returns The description's index in `descs`, or `no_reflection`. +pub def checker::reflected_one(&this, node: u32): u32 { + val at := this.reflected_at(node); + return checker::no_reflection if at == checker::no_reflection || this.reflected_kind(at) != rk::one as u32; + return this.reflected_item(at, 0); +} + +#! Whether the call is of an intrinsic of reflection, by the name it is. +#! @param this The checker. +#! @param decl The function called. +#! @returns Whether it is. +pub def checker::is_reflection(&mut this, decl: u32): bool { + return false if !this.decls.has(decl, df::intrinsic); + val name := this.names.text(this.decls.names.p[decl]); + return name == "declarations" || name == "decl_of" || name == "members_of" || name == "owner_of" + || name == "attributes_of" || name == "attached" || name == "value_of" || name == "params_of" + || name == "name_of" || name == "path_of"; +} + +#! A call of an intrinsic of reflection. +#! @param this The checker. +#! @param node The `call` node. +#! @param callee The node of what is called. +#! @param decl The intrinsic's declaration. +#! @param written The run of the type arguments written, as `T` of +#! `decl_of::()`. +#! @param args The arguments' nodes. +#! @param expected The type expected of what it gives, or the error type where +#! none is. +#! @returns The type it gives. +pub def checker::reflect_call(&mut this, node: u32, callee: u32, decl: u32, written: u32, args: span, expected: u32): u32 { + val name := this.names.text(this.decls.names.p[decl]); + this.resolve(decl); + val result := this.types.first_of(this.decls.types.p[decl]); + this.set_ref(callee, decl); + + if name == "value_of" { + return bt::error if args.length != 1; + this.infer_expr(args[0]); + val one := this.described_arg(args[0], "`value_of`"); + if one == checker::no_reflection { + return bt::error; + } + # What reflection was given, it reaches, as an attribute consents to. + val held: desc = this.descs[one]; + return bt::error if held.param != 0; + val saved := this.consent; + this.consent = held.decl; + val made := this.decl_value_of(node, held.decl, expected); + this.consent = saved; + return made; + } + + if name == "declarations" { + var items := vector::::new(); + for id in 1..this.decls.count { + if this.reflectable(id as u32) { + items.append(this.describe_decl(id as u32, 0)); + } + } + this.set_reflected(node, rk::list, items.view()); + return result; + } + + if name == "decl_of" || name == "name_of" || name == "path_of" { + val kind := this.run_length(written) == 1 ? this.resolve_type(this.run_at(written, 0)) : bt::error; + # The type named is kept as the callee's, which lowering spells. + if name == "name_of" || name == "path_of" { + this.set_type(callee, kind); + } + val plain := this.unalias(kind); + val target := this.type_decl(plain); + # A type no declaration makes, as a reference or a number, has none to give. + if name == "decl_of" && target == 0 && kind != bt::error && !this.types.is_open(kind) { + var text := string::from("`decl_of` takes a type a declaration makes, as a struct, union, enum, or trait, and `", nothing {}); + val named := this.describe(kind); + text.append(named.view()); + text.append("` is none: `name_of` and `path_of` name any type."); + this.report_text(node, ec::invalid, &text); + return result; + } + if name == "decl_of" && target != 0 && !this.types.is_open(kind) { + # An instance of a generic type gives its members the types it takes. + val owner: u32 = this.decls.params.p[target] != 0 ? plain : 0; + var items := vector::::new(); + items.append(this.describe_owned(target, 0, owner)); + this.set_reflected(node, rk::one, items.view()); + } + return result; + } + + # What the rest take is a description. + for &each in args { + this.infer_expr(each); + } + var what := string::from("`", nothing {}); + what.append(name); + what.append("`"); + val one := args.length == 0 ? checker::no_reflection : this.described_arg(args[0], what.view()); + + # What `attached` gives is a view of the attribute's type, which is known even + # where the declaration is not, as in a generic's own body. + if one == checker::no_reflection && name == "attached" { + val wanted := this.run_length(written) == 1 ? this.resolve_type(this.run_at(written, 0)) : bt::error; + return wanted == bt::error ? bt::error : this.span_of(wanted); + } + return result if one == checker::no_reflection; + val held: desc = this.descs[one]; + + if name == "params_of" { + var items := vector::::new(); + if held.param == 0 && this.decls.kinds.p[held.decl] == dk::function { + this.resolve(held.decl); + for i in 0..this.types.part_count(this.decls.types.p[held.decl]) { + items.append(this.describe_owned(held.decl, i as u32 + 1, held.owner)); + } + } + this.set_reflected(node, rk::list, items.view()); + return result; + } + + if name == "members_of" { + var items := vector::::new(); + if held.param == 0 { + val owner := this.member_owner(held); + val run: u32 = this.decls.children.p[held.decl]; + for &member in this.decls.list_view(run) { + items.append(this.describe_owned(member, 0, owner)); + } + for &member in this.decls.by_owner.of(held.decl) { + if this.decls.owners.p[member] == held.decl && this.receiver_declared(member) && this.visible(member) { + items.append(this.describe_owned(member, 0, owner)); + } + } + } + this.set_reflected(node, rk::list, items.view()); + return result; + } + + if name == "owner_of" { + val owner: u32 = held.param != 0 ? held.decl : this.decls.owners.p[held.decl]; + if owner != 0 { + val through: u32 = held.owner != 0 && this.type_decl(held.owner) == owner ? held.owner : 0; + var items := vector::::new(); + items.append(this.describe_owned(owner, 0, through)); + this.set_reflected(node, rk::one, items.view()); + } + return result; + } + + if name == "attached" { + # A span of the values of the attributes of the type given, of which how + # many there are is known. + val wanted := this.run_length(written) == 1 ? this.resolve_type(this.run_at(written, 0)) : bt::error; + var count := 0u; + if held.param == 0 { + val kinds := this.attribute_types(held.decl); + for &each in kinds { + if each == wanted { count++; } + } + } + this.set_known_length(node, count); + return wanted == bt::error ? bt::error : this.span_of(wanted); + } + + if name == "attributes_of" { + var items := vector::::new(); + if held.param == 0 { + val made := this.attribute_decls(held.decl); + for &each in made { + items.append(this.describe_decl(each, 0)); + } + } + this.set_reflected(node, rk::list, items.view()); + return result; + } + return result; +} + +#! The attributes written on a declaration, in the order they are written, +#! each a declaration of its own, as `attributes_of` gives them: a constant of +#! the attribute's type, named as it is written, as `@tag`, whose value is the +#! attribute's. Each is made the first time it is asked for. +#! @param this The checker. +#! @param id The declaration. +#! @returns The attributes' declarations. +def checker::attribute_decls(&mut this, id: u32): vector { + var made := vector::::new(); + val kinds := this.attribute_types(id); + val file: u32 = this.decls.files.p[id]; + val saved := this.at; + this.use_table(this.units[file].table); + val attrs := this.attributes_of(this.decls.nodes.p[id]); + var at: u64 = 0; + for &attr in this.run_view(attrs) { + continue if this.kind_of(attr) != nk::attribute; + val kind := at < kinds.length ? kinds[at] : bt::error; + at++; + continue if kind == bt::error; + + val key := pair_key(file, attr); + if this.attr_decls.get(&key) is some(got) { + made.append(got); + continue; + } + var name := string::from("@", nothing {}); + val named := this.describe(kind); + name.append(named.view()); + val decl := this.decls.add(dk::attribute, this.names.intern(&name.view()), file, attr, 0); + this.decls.types.p[decl] = kind; + this.decls.states.p[decl] = ds::resolved; + this.decls.mark(decl, df::constant); + this.decls.mark(decl, df::checked); + this.attr_decls.set(key, decl); + made.append(decl); + } + this.at = saved; + return made; +} + +#! The description an argument of reflection gives, reporting one giving none +#! where checking is not within a generic's own body, which each instance +#! checks. +#! @param this The checker. +#! @param arg The argument's node. +#! @param what The intrinsic, as a note names it. +#! @returns The description's index in `descs`, or `no_reflection`. +def checker::described_arg(&mut this, arg: u32, what: strview): u32 { + val one := this.reflected_one(arg); + if one == checker::no_reflection && !this.waits_for_instance() && this.type_at(arg) != bt::error { + var text := string::from(what, nothing {}); + text.append(" takes a declaration known while compiling, as the variable of `for const d in declarations()` is."); + this.report_text(arg, ec::constant, &text); + } + return one; +} + +#! Records how many values a view an expression of reflection gives holds, +#! which its `length` is known as. +#! @param this The checker. +#! @param node The expression. +#! @param count How many values the view holds. +def checker::set_known_length(&mut this, node: u32, count: u64): void { + this.lengths.set(this.result_key(node), count as u32); +} + +#! Whether reflection lists the declaration among `declarations()`: it is +#! declared outside any function, and the module checking can name it, or it +#! carries an attribute whose type that module declares. +#! @param this The checker. +#! @param id The declaration. +#! @returns Whether it does. +def checker::reflectable(&mut this, id: u32): bool { + val kind: dk = this.decls.kinds.p[id]; + match kind { + dk::function, dk::variable, dk::struct_type, dk::union_type, dk::enum_type, + dk::trait_type, dk::alias_type, dk::property => {} + else => return false; + } + return false if this.decls.has(id, df::accessor) || this.decls.nodes.p[id] == 0; + val owner: u32 = this.decls.owners.p[id]; + return false if owner != 0 && !this.receiver_declared(id); + + return true if this.visible(id); + val kinds := this.attribute_types(id); + for &each in kinds { + val decl := this.type_decl(each); + return true if decl != 0 && this.decls.modules.p[decl] == this.at.home; + } + return false; +} + +#! The types of the attributes written before the declaration, resolved where +#! it is declared. +#! @param this The checker. +#! @param id The declaration. +#! @returns The attributes' types, in the order they are written. +pub def checker::attribute_types(&mut this, id: u32): vector { + var made := vector::::new(); + val saved := this.at; + this.enter_decl(id, 0); + val attrs := this.attributes_of(this.decls.nodes.p[id]); + for &attr in this.run_view(attrs) { + continue if this.kind_of(attr) != nk::attribute; + made.append(this.quiet_type(this.left_of(attr))); + } + this.leave(saved); + return made; +} + +#! The type a type name names, without reporting what is wrong with it, which +#! checking the declaration it is written on reports. +#! @param this The checker. +#! @param node The `type_name` node. +#! @returns The type, or the error type. +def checker::quiet_type(&mut this, node: u32): u32 { + val name := this.segment_name(node, this.segment_count(node) - 1); + val decl := this.segment_count(node) == 1 ? this.lookup_type(name, 0) : 0; + return this.decls.types.p[decl] if decl != 0 && this.is_type_decl(decl) && this.decls.params.p[decl] == 0; + # What it names wrongly is reported where its declaration's attributes are + # checked, once. + this.mute++; + val kind := this.resolve_type(node); + this.mute--; + return kind; +} + +#! What a description says of itself, read as a field of it: its `kind`, as +#! the bit of `core::target`, whether it is `exported` or `generic`, which are +#! known, and its `name` and `path`. +#! @param this The checker. +#! @param node The `member` node, which takes what the field is known to be. +#! @param one The description's index in `descs`. +#! @param name The ID of the field's name. +pub def checker::reflected_field(&mut this, node: u32, one: u32, name: u32): void { + val held: desc = this.descs[one]; + val text := this.names.text(name); + if text == "kind" { + val bit := held.param != 0 ? 0x2000u : this.target_bit(held.decl); + this.set_value(node, constant::integer(bit, false)); + } else if text == "exported" { + this.set_value(node, constant::truth(held.param == 0 && this.decls.has(held.decl, df::exported))); + } else if text == "generic" { + val own := held.param == 0 && this.own_param_count(held.decl) != 0; + this.set_value(node, constant::truth(own)); + } +} + +#! The type of what a description describes: a function's own type, or what a +#! variable, field, parameter, or property holds. +#! @param this The checker. +#! @param one The description's index in `descs`. +#! @returns The type. +pub def checker::reflected_type(&mut this, one: u32): u32 { + val held: desc = this.descs[one]; + this.resolve(held.decl); + var kind: u32 = this.decls.types.p[held.decl]; + if held.owner != 0 { + kind = this.instantiated(kind, this.type_decl(held.owner), held.owner); + } + if held.param != 0 { + return held.param <= this.types.part_count(kind) ? this.types.part_at(kind, held.param - 1) : bt::error; + } + return kind; +} + +#! `for const d in declarations()`, or over any list of descriptions: its body +#! is checked once for each, with `d` describing it, each with a result table +#! of its own. +#! @param this The checker. +#! @param node The `for_stmt` node. +#! @param variable The node of the loop's variable. +#! @param list The list's run in `reflected`. +#! @param kind The type of the descriptions, `core::decl`. +pub def checker::unroll_reflection(&mut this, node: u32, variable: u32, list: u32, kind: u32): void { + val body := this.right_of(node); + val outer := this.at.table; + val count := this.reflected_count(list); + var element: u32 = bt::error; + if this.is_std(this.unalias(kind), word::span) { + element = this.types.part_at(this.unalias(kind), 0); + } + + for i in 0..count { + val item := this.reflected_item(list, i as u32); + val table := this.add_child_table(variable, body - variable + 1); + this.use_table(table); + val mark := this.scope_mark(); + this.declare_local(variable, this.name_of(variable), element); + var items := vector::::new(); + items.append(item); + this.set_reflected(variable, rk::one, items.view()); + this.at.loops++; + this.check_block(body); + this.at.loops--; + this.unbind_to(mark); + this.use_table(outer); + } +} + +#! Whether checking is within a generic's own body, where what reflection says +#! of its type parameters waits for each instance. +#! @param this The checker. +#! @returns Whether it is. +pub def checker::waits_for_instance(&mut this): bool { + return false if this.at.instance != 0 || this.at.decl == 0; + return true if this.decls.has(this.at.decl, df::generic); + # A default compiled for each type taking it is checked as a template too. + return this.decls.kinds.p[this.at.decl] == dk::function && this.typed_default(this.at.decl); +} diff --git a/analyzer/checker/resolve.sakura b/analyzer/checker/resolve.sakura new file mode 100644 index 00000000..68a4cf2c --- /dev/null +++ b/analyzer/checker/resolve.sakura @@ -0,0 +1,1353 @@ +#! @file resolve.sakura +#! @author John Christman (sorakatadzuma@gmail.com) +#! @copyright Malunal Studios, LLC. +#! @license MIT +#! +#! Contains the resolving of declarations: what each is, as a function's +#! parameters and result, a variable's type, an enum's members, or what an +#! alias stands for, worked out where it is first needed. A declaration being +#! resolved that is needed again depends on itself, which is reported rather +#! than followed. Also contains the resolving of types as they are written. + +module sakura::analyzer; + + +#! Gives each type declaration its type, which naming it needs nothing else to +#! know: the type of its declaration, given its own type parameters. +#! @param this The checker. +pub def checker::name_types(&mut this): void { + for id in 1..this.decls.count { + val kind: dk = this.decls.kinds.p[id]; + if kind == dk::struct_type || kind == dk::union_type || kind == dk::enum_type + || kind == dk::trait_type || kind == dk::alias_type { + val own := this.param_types(id as u32); + this.decls.types.p[id] = this.types.named(id as u32, own.view()); + } else if kind == dk::assoc_type { + this.decls.types.p[id] = this.types.param(id as u32); + } else if kind == dk::type_param { + this.decls.types.p[id] = this.decls.has(id as u32, df::packed) + ? this.types.pack(span::::empty(), id as u32) + : this.types.param(id as u32); + } + } +} + +#! The types of the declaration's type parameters, as its own body sees them. +#! @param this The checker. +#! @param id The declaration. +#! @returns The type of each of its type parameters, its owner's first. +pub def checker::param_types(&mut this, id: u32): vector { + var made := vector::::new(); + val run: u32 = this.decls.params.p[id]; + for ¶m in this.decls.list_view(run) { + made.append(this.decls.has(param, df::packed) + ? this.types.pack(span::::empty(), param) + : this.types.param(param)); + } + return made; +} + +#! Begins checking within the declaration: in its file and module, with its +#! type parameters bound to the types of its arguments, where `args` gives +#! them, or else to themselves. Within a trait, `self` is bound too. +#! @param this The checker. +#! @param id The declaration. +#! @param args The pack of its type arguments, or 0 where it is checked as +#! itself. +#! @remarks The caller keeps `at` beforehand, and gives it to `leave`. +pub def checker::enter_decl(&mut this, id: u32, args: u32): void { + this.use_table(this.units[this.decls.files.p[id]].table); + this.at.home = this.decls.modules.p[id]; + this.at.decl = id; + this.at.scope = this.scope_of(id, args); + this.at.instance = 0; + this.at.loops = 0; + this.at.result = bt::void_type; + this.at.marks = this.scope_mark(); + this.at.opened = this.at.marks; + + # Within a trait, `self` is what implements it, and each type it asks for is + # named as what that gives. In an instance of a default compiled for each type, + # the trait's parameters are its arguments, `self` is the type, and the + # default's own parameters follow. In an instance of any other generic trait's + # default, the trait's parameters are its arguments, and `self` is the trait + # given them. + val holder := this.enclosing_trait(id); + var skip: u32 = 0; + if holder != 0 && holder != id && args != 0 && this.typed_default(id) { + skip = this.decls.list_length(this.decls.params.p[holder]); + val self_kind := skip < this.types.part_count(args) ? this.types.part_at(args, skip) : bt::error; + this.bind(names::self_id, ref_type | self_kind); + this.bind_params(holder, args); + skip++; + } else if holder != 0 && holder != id && args != 0 && this.decls.list_length(this.decls.params.p[holder]) != 0 { + skip = this.decls.list_length(this.decls.params.p[holder]); + var given := vector::::new(); + for i in 0..skip { + given.append(i < this.types.part_count(args) ? this.types.part_at(args, i as u32) : bt::error); + } + this.bind(names::self_id, ref_type | this.types.named(holder, given.view())); + this.bind_params(holder, args); + } else if holder != 0 { + this.bind(names::self_id, ref_type | this.types.param(this.self_decl(holder))); + if holder != id { + this.bind_params(holder, 0); + } + } + if holder != 0 { + val asked: u32 = this.decls.children.p[holder]; + for &member in this.decls.list_view(asked) { + if this.decls.kinds.p[member] == dk::assoc_type { + this.bind(this.decls.names.p[member], ref_type | this.decls.types.p[member]); + } + } + } + + # A member declared within its type names the type's parameters, and a type + # parameter's bounds name those of what declares it. + val kind: dk = this.decls.kinds.p[id]; + val owner: u32 = this.decls.owners.p[id]; + if owner != 0 && owner != holder && (kind == dk::field || kind == dk::enum_member || kind == dk::assoc_type + || kind == dk::type_param) { + this.bind_params(owner, 0); + } + this.bind_params_from(id, args, skip); +} + +#! Ends checking within a declaration, putting back where checking was. +#! @param this The checker. +#! @param saved Where checking was, as `at` held it before `enter_decl`. +pub def checker::leave(&mut this, saved: checker::frame): void { + this.unbind_to(this.at.marks); + this.at = saved; +} + +#! Binds the names of the declaration's type parameters to the types of the +#! arguments `args` gives, or else to the parameters themselves. +#! @param this The checker. +#! @param id The declaration. +#! @param args The pack of its type arguments, or 0 to bind each parameter to +#! itself. +pub def checker::bind_params(&mut this, id: u32, args: u32): void { + this.bind_params_from(id, args, 0); +} + +#! Binds the names of the declaration's type parameters to the types of the +#! arguments `args` gives from one on, as an instance of a generic trait's +#! default gives its own after the trait's. +#! @param this The checker. +#! @param id The declaration. +#! @param args The pack of type arguments, or 0 to bind each parameter to +#! itself. +#! @param from The argument its first parameter is given. +def checker::bind_params_from(&mut this, id: u32, args: u32, from: u32): void { + val run: u32 = this.decls.params.p[id]; + for i in 0..this.decls.list_length(run) { + val param := this.decls.list_at(run, i as u32); + val at := from + i as u32; + val kind := args != 0 && at < this.types.part_count(args) + ? this.types.part_at(args, at) + : this.decls.types.p[param]; + this.bind(this.decls.names.p[param], ref_type | kind); + } +} + +#! The trait the declaration is, or is a member of, or 0. +#! @param this The checker. +#! @param id The declaration. +#! @returns The trait's declaration, or 0. +pub def checker::enclosing_trait(&this, id: u32): u32 { + var at := id; + var steps := 0; + while at != 0 && steps < 4 { + return at if this.decls.kinds.p[at] == dk::trait_type; + at = this.decls.owners.p[at]; + steps++; + } + return 0; +} + +#! The declaration `self` is within the trait: a type parameter standing for +#! whatever implements it. +#! @param this The checker. +#! @param holder The trait's declaration. +#! @returns The declaration of its `self`, made the first time it is asked for. +pub def checker::self_decl(&mut this, holder: u32): u32 { + if this.selves.get(&holder) is some(got) { + return got; + } + + val id := this.decls.add(dk::type_param, names::self_id, this.decls.files.p[holder], + this.decls.nodes.p[holder], this.decls.modules.p[holder]); + this.decls.own(id, holder); + this.decls.types.p[id] = this.types.param(id); + this.decls.states.p[id] = ds::resolved; + this.selves.set(holder, id); + return id; +} + +#! Resolves what the declaration is, where it is not yet resolved. +#! @param this The checker. +#! @param id The declaration. +pub def checker::resolve(&mut this, id: u32): void { + this.depend(id); + val state: ds = this.decls.states.p[id]; + return if state == ds::resolved; + # A type parameter is its own type while its bounds are resolved, so a bound + # naming it, as `T: ceiling`, is no cycle. + return if state == ds::resolving && this.decls.kinds.p[id] == dk::type_param && !this.decls.has(id, df::valued); + if state == ds::resolving { + this.report_cycle(id); + return; + } + + this.decls.states.p[id] = ds::resolving; + val saved := this.at; + # What is wrong with a declaration is its own, noted wherever it is first + # resolved, even where what reached it was being tried quietly. + val mute := this.mute; + this.mute = 0; + this.enter_decl(id, 0); + match this.decls.kinds.p[id] { + dk::function => this.resolve_function(id); + dk::variable => this.resolve_variable(id); + dk::field => this.resolve_variable(id); + dk::property => this.resolve_property(id); + dk::enum_type => this.resolve_enum(id); + dk::enum_member => { + this.leave(saved); + this.decls.states.p[id] = ds::unresolved; + this.resolve(this.decls.owners.p[id]); + return; + } + dk::alias_type => { + val target := this.resolve_type(this.syn().node_rights[this.decls.nodes.p[id]]); + this.decls.targets.p[id] = target; + # An alias of an alias is followed now, so one that comes back to itself is + # reported where it is declared. + if this.is_alias(target) { + this.resolve(this.types.first_of(target)); + if this.decls.has(id, df::failed) { + this.decls.targets.p[id] = bt::error; + } + } + } + dk::type_param => { + if this.decls.has(id, df::valued) { + this.resolve_constant(id); + } else { + this.resolve_bounds(id, this.left_of(this.decls.nodes.p[id])); + this.inherit_bounds(id); + } + } + dk::assoc_type => { + val node: u32 = this.decls.nodes.p[id]; + this.resolve_bounds(id, this.record(node, assoc_slot::bounds)); + # Resolving a type may declare more, which moves the declaration's + # vectors, so what is resolved is stored once it is made. + val fallback := this.right_of(node); + val target: u32 = fallback == 0 ? 0 : this.resolve_type(fallback); + this.decls.targets.p[id] = target; + } + else => {} + } + + this.leave(saved); + this.mute = mute; + this.decls.states.p[id] = ds::resolved; +} + +#! Reports a declaration depending on itself. +#! @param this The checker. +#! @param id The declaration. +def checker::report_cycle(&mut this, id: u32): void { + return if this.decls.has(id, df::failed); + + this.decls.mark(id, df::failed); + var text := string::from("`", nothing {}); + text.append(this.decl_text(id)); + text.append("` depends on itself, so what it is cannot be worked out."); + this.report_decl(id, ec::cycle, text.view()); +} + +#! Resolves a function's parameters and result into its function type. +#! @param this The checker. +#! @param id The function's declaration. +def checker::resolve_function(&mut this, id: u32): void { + val node: u32 = this.decls.nodes.p[id]; + if this.decls.has(id, df::accessor) { + this.resolve_accessor(id, node); + return; + } + + # What a trait's method asks of the trait's parameters and `self` holds within + # its signature, as it does within its body. + val proved := this.proved_params.length; + this.prove_outer(id); + + # A variadic last parameter may take a pack, as `args: Ts...` does. + var params := vector::::new(); + val run := this.record(node, function_slot::params); + val count := this.run_length(run); + for i in 0..count { + val param := this.run_at(run, i as u32); + if i == 0 && this.decls.has(id, df::method) { + params.append(this.types.reference(this.self_type(id), this.decls.has(id, df::mut_this))); + # A type written for `this`, as `this: &rect`, is what `this` is, so it is + # resolved only for what its names name, which an editor shows. + if this.left_of(param) != 0 { + this.resolve_quietly(this.left_of(param)); + } + continue; + } + val written := this.left_of(param); + val kind := this.resolve_type(written); + val packs := i as u32 + 1 == count && this.decls.has(id, df::variadic) && this.types.kind_of(kind) == ty::pack; + params.append(packs || this.valid_value(written, kind) ? kind : bt::error); + } + + val written := this.record(node, function_slot::result); + val result := written == 0 ? bt::void_type : this.result_type(written); + this.decls.types.p[id] = this.types.function(params.view(), result, this.decls.has(id, df::variadic)); + this.unprove_to(proved); +} + +#! The bounds a trait's method puts on the trait's type parameters and `self`, +#! as `where self: backward_iterator`, which only that method asks of them: +#! a list of each parameter's declaration followed by its bound, worked out the +#! first time it is asked for. +#! @param this The checker. +#! @param method The method's declaration. +#! @returns The list, or 0 where it puts none. +pub def checker::outer_bounds(&mut this, method: u32): u32 { + return 0 if this.decls.kinds.p[method] != dk::function || !this.writes_outer(method); + val holder := this.enclosing_trait(method); + return 0 if holder == 0 || holder == method; + if this.outers.get(&method) is some(got) { + return got; + } + this.outers.set(method, 0); + val syntax := &this.units[this.decls.files.p[method]].syntax; + val node: u32 = this.decls.nodes.p[method]; + val run := syntax.extras[syntax.node_lefts[node] as u64 + function_slot::outer as u64]; + + var made := vector::::new(); + val saved := this.at; + this.enter_decl(method, 0); + for &each in this.run_view(run) { + val name := this.name_of(each); + var param: u32 = name == names::self_id ? this.self_decl(holder) : 0; + for &own in this.decls.list_view(this.decls.params.p[holder]) { + param = this.decls.names.p[own] == name ? own : param; + } + continue if param == 0; + for &written in this.run_view(this.left_of(each)) { + val kind := this.resolve_type(written); + if kind != bt::error && this.named_kind(kind) != dk::trait_type { + this.report(written, ec::not_type, "A bound is a trait."); + continue; + } + continue if kind == bt::error; + made.append(param); + made.append(kind); + } + } + this.leave(saved); + val list := this.decls.make_list(made.view()); + this.outers.set(method, list); + return list; +} + +#! Gives the trait's parameters and `self` the bounds a trait's method puts on +#! them, where its signature and its own body are checked, as an `if const` +#! gives the branch it guards those it proves. +#! @param this The checker. +#! @param method The method's declaration. +pub def checker::prove_outer(&mut this, method: u32): void { + val list := this.outer_bounds(method); + var i: u32 = 0; + while i + 1 < this.decls.list_length(list) { + this.proved_params.append(this.decls.list_at(list, i)); + this.proved_bounds.append(this.decls.list_at(list, i + 1)); + i += 2; + } +} + +#! Resolves a type for what its names name, noting nothing of it. +#! @param this The checker. +#! @param node The type's node. +def checker::resolve_quietly(&mut this, node: u32): void { + val dropped := this.dropped; + val uninferred := this.uninferred; + this.mute++; + this.resolve_type(node); + this.mute--; + this.dropped = dropped; + this.uninferred = uninferred; +} + +#! Resolves an accessor of a property: a getter takes `this` and gives the +#! property's type, and a setter takes `this` and a value of it. +#! @param this The checker. +#! @param id The accessor's declaration. +#! @param node The `accessor` node. +def checker::resolve_accessor(&mut this, id: u32, node: u32): void { + val property: u32 = this.decls.owners.p[id]; + this.resolve(property); + val kind: u32 = this.decls.types.p[property]; + + var params := vector::::new(); + params.append(this.types.reference(this.self_type(id), this.decls.has(id, df::mut_this))); + val run := this.left_of(node); + for i in 1..this.run_length(run) { + val param := this.run_at(run, i as u32); + val written := this.left_of(param); + params.append(written == 0 ? kind : this.resolve_type(written)); + } + + val result: u32 = this.decls.has(id, df::setter) ? bt::void_type : kind; + this.decls.types.p[id] = this.types.function(params.view(), result, false); +} + +#! The type `this` refers to within a method: its type, given the method's +#! first type parameters, which its receiver named, or `self` within a trait. +#! @param this The checker. +#! @param id The method's declaration. +#! @returns The type `this` refers to. +pub def checker::self_type(&mut this, id: u32): u32 { + var owner: u32 = this.decls.owners.p[id]; + if owner != 0 && this.decls.kinds.p[owner] == dk::property { + owner = this.decls.owners.p[owner]; + } + return bt::error if owner == 0; + + return this.types.param(this.self_decl(owner)) if this.decls.kinds.p[owner] == dk::trait_type; + + # The owner's parameters are the first of the method's, from its receiver. + val from_property := this.decls.kinds.p[this.decls.owners.p[id]] == dk::property; + return this.own_scope(owner, from_property ? this.decls.owners.p[id] : id, 0); +} + +#! Resolves a variable, constant, or field: its type as written, or as its +#! value gives it. A constant's value is worked out here, since a type may need +#! it, as the length of a fixed array. +#! @param this The checker. +#! @param id The declaration. +def checker::resolve_variable(&mut this, id: u32): void { + val node: u32 = this.decls.nodes.p[id]; + val written := this.record(node, variable_slot::type_expr); + val value := this.record(node, variable_slot::value); + var kind: u32 = bt::error; + if written != 0 && this.kind_of(written) == nk::spread { + kind = this.resolve_type(this.left_of(written)); + } else if written != 0 { + kind = this.value_type(written); + } else if value != 0 { + # A constant declared through a type is of that type where it fits it, so + # `val open_flags::read := 1;` is an `open_flags`. + val own := this.infer_expr(value); + val owner: u32 = this.decls.owners.p[id]; + kind = this.settle(own); + if this.types.is_untyped(own) && owner != 0 && this.is_type_decl(owner) && this.decls.kinds.p[owner] != dk::trait_type { + val held: u32 = this.decls.types.p[owner]; + if this.fits_node(value, held) == fit::constant { + kind = held; + this.set_convert(value, held); + } + } else if kind != own && kind != bt::error { + this.set_convert(value, kind); + } + this.set_flag(value, rf::checked); + } + this.decls.types.p[id] = kind; + + if this.decls.has(id, df::constant) && value != 0 { + if written != 0 { + this.check_expr(value, kind); + this.set_flag(value, rf::checked); + } + + # A constant's value that folding does not give, as one calling a + # function, is run while checking. + if !this.is_known(value) && this.type_at(value) != bt::error { + var made := ev {}; + if this.evaluate(value, this.decls.nodes.p[id], &mut made) { + if made.array { + this.ev_arrays.set(id, made); + } else { + this.set_value(value, made.scalar); + } + } + } + if this.is_known(value) { + this.set_decl_value(id, this.value_at(value)); + } + } +} + +#! Resolves a property's type, which is never `void`. +#! @param this The checker. +#! @param id The property's declaration. +def checker::resolve_property(&mut this, id: u32): void { + val written := this.record(this.decls.nodes.p[id], property_slot::type_expr); + val kind := this.resolve_type(written); + if kind == bt::void_type { + this.report(written, ec::invalid, "A property holds a value, so its type is not `void`."); + } + this.decls.types.p[id] = kind; +} + +#! Records the constant a declaration holds. +#! @param this The checker. +#! @param id The declaration. +#! @param value The constant. +pub def checker::set_decl_value(&mut this, id: u32, value: constant): void { + this.decl_values.put(id, this.intern_constant(value) + 1); +} + +#! The constant the declaration holds, where it holds one known while compiling. +#! @param this The checker. +#! @param id The declaration. +#! @param out Where the constant is written, where it holds one. +#! @returns Whether it holds one. +pub def checker::decl_value(&this, id: u32, out: &mut constant): bool { + val held := this.decl_values.at_or_zero(id); + return false if held == 0; + out = this.constants.p[held - 1]; + return true; +} + +#! Resolves an enum: the integer type holding it, and each member's value, one +#! more than the member before unless given one. A member given an earlier +#! member's value is another name for it, but one counting up onto it is a +#! mistake. +#! @param this The checker. +#! @param id The enum's declaration. +def checker::resolve_enum(&mut this, id: u32): void { + val node: u32 = this.decls.nodes.p[id]; + val written := this.record(node, enumeration_slot::integer); + var integer: u32 = bt::int32; + if written != 0 { + integer = this.resolve_type(written); + if !this.types.is_integer(integer) && integer != bt::error { + this.report(written, ec::not_type, "An enum is held as an integer type."); + integer = bt::int32; + } + } + this.decls.targets.p[id] = integer; + + var seen := vector::::new(); + var next := constant {}; + val run: u32 = this.decls.children.p[id]; + for i in 0..this.decls.list_length(run) { + val member := this.decls.list_at(run, i as u32); + val at: u32 = this.decls.nodes.p[member]; + val given := this.right_of(at); + var value := next; + if given != 0 { + this.check_expr(given, integer); + if this.is_known(given) { + value = this.value_at(given); + } else if this.type_at(given) != bt::error { + this.report(given, ec::constant, "A member's value is known while compiling: a literal, a constant, or another member."); + } + } else { + for &earlier in seen { + if this.compare_constants(earlier, &value) == 0 { + this.report(at, ec::duplicate, "The member counts up onto the value of an earlier one; give it a value of its own."); + break; + } + } + if !this.in_range(integer, &value) { + var text := string::from("The member's value is outside the range of `", nothing {}); + val named := this.describe(integer); + text.append(named.view()); + text.append("`."); + this.report_text(at, ec::overflow, &text); + } + } + + seen.append(value); + this.set_decl_value(member, value); + this.decls.types.p[member] = this.decls.types.p[id]; + this.decls.states.p[member] = ds::resolved; + this.fold_add(&value, 1, false, &mut next); + } +} + +#! Resolves the bounds of a type parameter, or of a type a trait asks for, each +#! a trait. +#! @param this The checker. +#! @param id The type parameter's declaration. +#! @param run The run of the nodes of its bounds. +def checker::resolve_bounds(&mut this, id: u32, run: u32): void { + var bounds := vector::::new(); + for &written in this.run_view(run) { + val kind := this.resolve_type(written); + if kind != bt::error && this.named_kind(kind) != dk::trait_type { + this.report(written, ec::not_type, "A bound is a trait."); + continue; + } + bounds.append(kind); + } + this.decls.children.p[id] = this.decls.make_list(bounds.view()); +} + +#! Resolves the type of a constant parameter's value: the type written for it, or +#! where a receiver names one of its type's, the type that declares it. A +#! constant is of its type, so it takes no bounds, and of a type that closes +#! nothing, since instances are told apart by it and it is copied wherever it is +#! read. +#! @param this The checker. +#! @param id The constant parameter's declaration. +def checker::resolve_constant(&mut this, id: u32): void { + val node: u32 = this.decls.nodes.p[id]; + if this.run_length(this.left_of(node)) != 0 { + this.report(this.run_at(this.left_of(node), 0), ec::generic, + "A constant parameter is a value of the type written for it, so it takes no bounds."); + } + + # The length a pattern, `L[N]`, names is a `u64`, as the lengths of arrays are. + val written: u32 = this.kind_of(node) == nk::const_param ? this.right_of(node) : 0; + var kind: u32 = written != 0 ? this.value_type(written) : this.kind_of(node) == nk::const_param ? bt::uint64 : bt::error; + if this.mirrors.at_or_zero(id) != 0 { + val source: u32 = this.mirrors.at_or_zero(id); + this.resolve(source); + # The type's parameters are the parameters of the declaration standing for them. + var from := vector::::new(); + var to := vector::::new(); + val holder: u32 = this.decls.owners.p[id]; + val run: u32 = this.decls.params.p[holder]; + for ¶m in this.decls.list_view(run) { + if this.mirrors.at_or_zero(param) != 0 { + from.append(this.mirrors.at_or_zero(param)); + to.append(this.decls.types.p[param]); + } + } + val given := this.substitute(this.decls.targets.p[source], from.view(), to.view()); + if written != 0 && kind != given && kind != bt::error && given != bt::error { + var text := string::from("The constant is of `", nothing {}); + val named := this.describe(given); + text.append(named.view()); + text.append("` where its type declares it, so it is written that way here, or by its name alone."); + this.report_text(written, ec::generic, &text); + } + this.decls.targets.p[id] = given; + return; + } + + this.decls.targets.p[id] = kind; + if written != 0 && kind != bt::error && !this.types.is_open(kind) { + this.check_constant_type(written, kind); + } +} + +#! Reports a type no constant can be of: `void`, a trait, the address of a C +#! function, and what closes what it holds. +#! @param this The checker. +#! @param node The node a note is placed at. +#! @param kind The type. +#! @returns Whether a constant can be of it. +pub def checker::check_constant_type(&mut this, node: u32, kind: u32): bool { + val plain := this.unalias(kind); + if this.is_std(plain, word::cfn) { + this.report(node, ec::generic, "The address of a C function is only known once the program runs, so it is no constant."); + return false; + } + if this.types.kind_of(plain) == ty::pack { + this.report(node, ec::generic, "A pack is many values, so it is no constant."); + return false; + } + if this.closes(kind) { + var text := string::from("`", nothing {}); + val named := this.describe(kind); + text.append(named.view()); + text.append("` closes what it holds, so it is no constant: a constant parameter is given a value that closes nothing, such as a number, text, or a struct of them."); + this.report_text(node, ec::generic, &text); + return false; + } + return true; +} + +#! Gives a type parameter a receiver names, as `T` of `box::get`, the +#! bounds of the type's parameter it stands for, in terms of the declaration's +#! own parameters. +#! @param this The checker. +#! @param id The type parameter's declaration. +def checker::inherit_bounds(&mut this, id: u32): void { + val source: u32 = this.mirrors.at_or_zero(id); + return if source == 0; + + this.resolve(source); + val inherited: u32 = this.decls.children.p[source as u32]; + return if this.decls.list_length(inherited) == 0; + + # The type's parameters become the parameters of the declaration standing for them. + val holder: u32 = this.decls.owners.p[id]; + var from := vector::::new(); + var to := vector::::new(); + val run: u32 = this.decls.params.p[holder]; + for ¶m in this.decls.list_view(run) { + if this.mirrors.at_or_zero(param) != 0 { + from.append(this.mirrors.at_or_zero(param)); + to.append(this.decls.types.p[param]); + } + } + + var bounds := this.decls.list_of(this.decls.children.p[id]); + for i in 0..this.decls.list_length(inherited) { + bounds.append(this.substitute(this.decls.list_at(inherited, i as u32), from.view(), to.view())); + } + this.decls.children.p[id] = this.decls.make_list(bounds.view()); +} + +#! The type a type is written as. +#! @param this The checker. +#! @param node The type's node. +#! @returns The type, or the error type where it is wrongly written. +pub def checker::resolve_type(&mut this, node: u32): u32 { + return bt::error if node == 0; + + match this.kind_of(node) { + nk::type_name => return this.resolve_type_name(node); + nk::type_ref, nk::type_ptr => { + val inner := this.resolve_type(this.left_of(node)); + val mutable := this.node_has(node, nf::mutable); + + # A reference to a trait dispatches through what the trait asks for, + # which a trait only a bound cannot do. + val plain := this.unalias(inner); + if this.named_kind(plain) == dk::trait_type && this.bound_only(this.types.first_of(plain)) { + var text := string::from("`", nothing {}); + text.append(this.decl_text(this.types.first_of(plain))); + text.append("` names `self`, asks for types, or has generic methods, or composes a trait that does, which only what implements it gives, so it is only a bound, written in a `where` clause, and never the type of a value or reference."); + this.report_text(this.left_of(node), ec::not_type, &text); + return bt::error; + } + return this.kind_of(node) == nk::type_ref + ? this.types.reference(inner, mutable) + : this.types.pointer(inner, mutable); + } + nk::type_fixed => { + val element := this.value_type(this.left_of(node)); + var length: u32 = 0; + val count := this.const_length(this.right_of(node), &mut length); + if length != 0 { + return element == bt::error ? bt::error : this.types.fixed_of(element, length); + } + return element == bt::error || count == checker::no_length ? bt::error : this.types.fixed(element, count); + } + nk::type_func => { + # The last parameter written `T...` takes any number of arguments, or where + # `T` is a pack, one of each of its types. + var params := vector::::new(); + var variadic := false; + val run := this.left_of(node); + val count := this.run_length(run); + for i in 0..count { + val each := this.run_at(run, i as u32); + if this.kind_of(each) == nk::type_spread { + if i as u32 + 1 != count { + this.report(this.left_of(each), ec::invalid, "Only the last parameter type is written `T...`, since it takes every argument after those before it."); + } + # A pack whose types are known, as an instance's `Ts`, gives a parameter + # of each of its types, as substituting it into the type would, and the + # function is variadic only where the pack is a variadic function's. + val spread := this.resolve_type(this.left_of(each)); + if this.types.is_known_pack(spread) && i as u32 + 1 == count { + params.extend(this.types.parts_view(spread)); + variadic = this.types.second_of(spread) != 0; + continue; + } + params.append(spread); + variadic = i as u32 + 1 == count; + continue; + } + val made := this.resolve_type(each); + if this.types.kind_of(made) == ty::pack { + this.report(each, ec::invalid, "A pack is the last parameter type, written `Ts...`."); + params.append(bt::error); + continue; + } + params.append(made); + } + return this.types.function(params.view(), this.resolve_type(this.right_of(node)), variadic); + } + nk::type_spread => { + this.report(node, ec::invalid, "`...` follows only the last parameter type of a function type, or a pack passed on among type arguments."); + return bt::error; + } + nk::type_of => { + # The type of what a description known while compiling describes. + val named := this.left_of(node); + this.infer_expr(named); + val one := this.reflected_one(named); + if one == checker::no_reflection { + if !this.waits_for_instance() { + this.unsupported(node); + } + return bt::error; + } + return this.reflected_type(one); + } + else => return bt::error; + } + return bt::error; +} + +#! What `const_length` gives for a length that is not one. +pub const checker::no_length: u32 = 0xFFFFFFFF; + +#! The type a value is written as, which is no bare trait, and not `void`. +#! @param this The checker. +#! @param node The type's node. +#! @returns The type, or the error type where it is wrong or no value can be of +#! it. +pub def checker::value_type(&mut this, node: u32): u32 { + val kind := this.resolve_type(node); + return this.valid_value(node, kind) ? kind : bt::error; +} + +#! The type a function's result is written as, which may be `void`. +#! @param this The checker. +#! @param node The type's node, or 0 for `void`. +#! @returns The type, or the error type where it is wrongly written. +pub def checker::result_type(&mut this, node: u32): u32 { + val kind := this.resolve_type(node); + return kind if kind == bt::void_type; + return this.valid_value(node, kind) ? kind : bt::error; +} + +#! Whether a value can be of the type, reporting a trait used as the type of a +#! value rather than through a reference or as a bound. `void` is a value's type +#! too, of the one value holding nothing, which a function giving nothing gives. +#! @param this The checker. +#! @param node The node a note is placed at. +#! @param kind The type. +#! @returns Whether it can be. +pub def checker::valid_value(&mut this, node: u32, kind: u32): bool { + if this.named_kind(this.unalias(kind)) == dk::trait_type { + this.report(node, ec::not_type, + "A trait is no value's type: refer to a value implementing it with `&`, or bound a type parameter by it."); + return false; + } + if this.types.kind_of(kind) == ty::pack { + this.report(node, ec::not_type, "A pack is the type only of a variadic parameter, as `args: Ts...`, and is passed on with `...`."); + return false; + } + return true; +} + +#! Whether a trait's method writes bounds on the trait's type parameters or +#! `self`, which only a type implementing it meets. +#! @param this The checker. +#! @param method The method's declaration. +#! @returns Whether it does. +pub def checker::writes_outer(&this, method: u32): bool { + return false if this.decls.has(method, df::accessor); + val syntax := &this.units[this.decls.files.p[method]].syntax; + val node: u32 = this.decls.nodes.p[method]; + val record := syntax.node_lefts[node]; + return record != 0 && syntax.extras[record as u64 + function_slot::outer as u64] != 0; +} + +#! Whether a trait is only a bound: it names `self`, asks for types, or has +#! generic methods or ones bounding its parameters, or composes a trait that +#! does, which only what implements it gives, and no table holds. +#! @param this The checker. +#! @param holder The trait's declaration. +#! @returns Whether it is only a bound. +pub def checker::bound_only(&mut this, holder: u32): bool { + if this.only_bounds.get(&holder) is some(got) { + return got; + } + this.only_bounds.set(holder, false); + + var only := false; + var skipped := false; + val self_kind := this.types.param(this.self_decl(holder)); + val run: u32 = this.decls.children.p[holder]; + for i in 0..this.decls.list_length(run) { + val member := this.decls.list_at(run, i as u32); + if this.decls.kinds.p[member] == dk::assoc_type { + only = true; + break; + } + # A method being resolved, as one taking a reference to its own trait, is + # passed over, and what is found is not kept, to be worked out again. + if this.decls.kinds.p[member] == dk::function && this.decls.states.p[member] == ds::resolving { + skipped = true; + continue; + } + # A method's `this` refers to what implements the trait through the trait's + # reference, so only `self` elsewhere makes the trait only a bound. + if this.decls.kinds.p[member] == dk::function { + if (this.decls.list_length(this.decls.params.p[member]) != 0 || this.writes_outer(member)) && this.trait_asks(member) { + only = true; + break; + } + this.resolve(member); + val kind: u32 = this.decls.types.p[member]; + val from: u32 = this.decls.has(member, df::method) ? 1 : 0; + for p in from..this.types.part_count(kind) { + only = only || this.mentions(this.types.part_at(kind, p as u32), self_kind, 0); + } + only = only || this.mentions(this.types.first_of(kind), self_kind, 0); + break if only; + } + } + + val composed := this.composed_of(holder); + for i in 0..this.decls.list_length(composed) { + only = only || this.bound_only(this.types.first_of(this.decls.list_at(composed, i as u32))); + } + if skipped && !only { + this.only_bounds.remove(&holder); + } else { + this.only_bounds.set(holder, only); + } + return only; +} + +#! Whether the type holds the type `target` anywhere within it. +#! @param this The checker. +#! @param kind The type to look within. +#! @param target The type to look for. +#! @param depth How deeply the search has gone, which stops a type nesting +#! without end. +#! @returns Whether it holds it. +pub def checker::mentions(&this, kind: u32, target: u32, depth: u32): bool { + return true if kind == target; + return false if depth > 16 || !this.types.is_open(kind); + match this.types.kind_of(kind) { + ty::reference, ty::pointer => return this.mentions(this.types.first_of(kind), target, depth + 1); + ty::fixed => { + return true if this.types.part_count(kind) != 0 && this.mentions(this.types.part_at(kind, 0), target, depth + 1); + return this.mentions(this.types.first_of(kind), target, depth + 1); + } + else => {} + } + for &part in this.types.parts_view(kind) { + return true if this.mentions(part, target, depth + 1); + } + return this.types.kind_of(kind) == ty::function && this.mentions(this.types.first_of(kind), target, depth + 1); +} + +#! The length of a fixed array, an integer known while compiling, or +#! `no_length` where it is not one. Within a template, one worked out from its +#! constant parameters is known only to each instance, and is given as the +#! constant standing for it instead. +#! @param this The checker. +#! @param node The length's node. +#! @param dependent Where such a constant is written, or 0 where there is none. +#! @returns The length, or `no_length`. +def checker::const_length(&mut this, node: u32, dependent: &mut u32): u32 { + val kind := this.infer_expr(node); + return checker::no_length if kind == bt::error; + if !this.types.is_integer(this.unalias(this.read_type(kind))) && this.named_kind(this.unalias(kind)) != dk::enum_type { + this.report_operand(node, kind, "The length of a fixed array is an integer."); + return checker::no_length; + } + if !this.is_known(node) { + val worked := this.known_of(node, this.settle(kind), 0); + if worked != 0 && this.known_depends(worked) { + dependent = this.known_type(worked); + return checker::no_length; + } + } + if !this.is_known(node) { + var made := ev {}; + if this.evaluate(node, node, &mut made) && !made.array { + this.set_value(node, made.scalar); + } else if !this.ev_failed { + this.report(node, ec::constant, "The length of a fixed array is known while compiling: a literal, a constant, or what a function gives of them."); + return checker::no_length; + } else { + return checker::no_length; + } + } + + val value := this.value_at(node); + if value.negative || value.magnitude > 0x1000000 { + this.report(node, ec::limit, "A fixed array holds from 0 to 16777216 elements."); + return checker::no_length; + } + return value.magnitude as u32; +} + +#! The type a named type is written as, as `std::list` or `T`. +#! @param this The checker. +#! @param node The `type_name` node. +#! @returns The type, or the error type where it names none. +pub def checker::resolve_type_name(&mut this, node: u32): u32 { + var decl: u32 = 0; + var home: u32 = 0; + var in_module := false; + var args := vector::::new(); + val count := this.segment_count(node); + for i in 0..count { + val name := this.segment_name(node, i as u32); + val segment := this.segment_node(node, i as u32); + if i == 0 { + val bound := this.bound(name); + if (bound & ref_type) != 0 { + val kind := bound & ref_mask; + if this.is_constant_arg(kind) { + var text := string::from("`", nothing {}); + text.append(this.names.text(name)); + text.append("` is a constant, not a type."); + this.report_text(segment, ec::not_type, &text); + return bt::error; + } + this.set_ref(segment, bound); + if count == 1 { + this.no_type_args(node, 0); + return kind; + } + return this.projection(kind, node, 1, this.param_named(name)); + } + + # A module the first of several segments names comes before a declaration of + # the name, as `serial::options` names the module's type where `serial` is + # also the attribute it declares. + if count > 1 { + home = this.lookup_module(name); + in_module = home != 0; + } + # A type a type around it gives takes that type's arguments first, as + # `node` within `list` is `list::node`. + if !in_module { + val found := this.lookup_named(name, segment, true); + decl = found.decl; + if found.owner != 0 && this.is_type_decl(decl) && this.types.kind_of(found.owner) == ty::named { + args.extend(this.types.parts_view(found.owner)); + } + } + if decl == 0 && !in_module { + home = this.lookup_module(name); + in_module = home != 0; + if !in_module { + var text := string::from("No type `", nothing {}); + text.append(this.names.text(name)); + text.append("` is declared where it is written."); + this.report_text(segment, ec::undefined, &text); + return bt::error; + } + } + } else if in_module { + decl = this.modules.decl(home, name); + if decl == 0 { + home = this.modules.find(home, name); + if home == 0 { + var text := string::from("The module declares no `", nothing {}); + text.append(this.names.text(name)); + text.append("`."); + this.report_text(segment, ec::undefined, &text); + return bt::error; + } + continue; + } + in_module = false; + } else { + # A type the program declares through `core`'s, of a name `core` gives it + # too, is the program's outside `core`. + val added := this.in_core(this.at.home) || this.cores_own != 0 ? 0 : this.decls.added_member(decl, name); + val member := added != 0 && this.is_type_decl(added) ? added : this.decls.path_member(decl, name); + if member == 0 || !this.is_type_decl(member) { + var text := string::from("`", nothing {}); + text.append(this.decl_text(decl)); + text.append("` declares no type `"); + text.append(this.names.text(name)); + text.append("`."); + this.report_text(segment, ec::undefined, &text); + return bt::error; + } + decl = member; + } + + # What each segment names is kept for the editor, which shows it and finds + # where it is declared. + this.set_ref(segment, decl); + val run := this.segment_args(node, i as u32); + for &arg in this.run_view(run) { + args.append(this.type_arg_of(arg, decl, args.length as u32, args.view())); + } + } + + if in_module { + this.report(node, ec::not_type, "A module is not a type."); + return bt::error; + } + if !this.is_type_decl(decl) { + var text := string::from("`", nothing {}); + text.append(this.decl_text(decl)); + text.append("` is a "); + text.append(this.decl_word(decl)); + text.append(", not a type."); + this.report_text(node, ec::not_type, &text); + return bt::error; + } + if !this.visible(decl) { + this.report_hidden(node, decl); + } + + return this.named_of(decl, args.view(), node); +} + +#! The type of the declaration given the type arguments, reporting arguments +#! that are wrong in number or do not satisfy their bounds. +#! @param this The checker. +#! @param decl The declaration of the type. +#! @param args Its type arguments. +#! @param node The node notes are placed at. +#! @returns The type, or the error type where the arguments are wrong. +pub def checker::named_of(&mut this, decl: u32, args: span, node: u32, given: bool = false): u32 { + match this.decls.kinds.p[decl] { + dk::builtin, dk::type_param => { + if args.length != 0 { + this.report(node, ec::generic, "The type takes no type arguments."); + } + return this.decls.types.p[decl]; + } + dk::assoc_type => return this.decls.types.p[decl]; + else => {} + } + + val params: u32 = this.decls.params.p[decl]; + val wanted := this.decls.list_length(params); + for &arg in args { + return bt::error if arg == bt::error; + } + + # What is written gives each type parameter its argument: one each, the rest to + # a pack, and a pattern's the parts of its function type. What inference gives + # already has one for each. + var grouped := vector::::new(); + if given { + grouped.extend(args); + if grouped.length != wanted as u64 { + var text := string::from("`", nothing {}); + text.append(this.decl_text(decl)); + val words := $"` takes {wanted} type arguments, but is given {args.length}."; + text.append(words.view()); + this.report_text(node, ec::generic, &text); + return bt::error; + } + } else { + return bt::error if !this.bind_written(decl, args, node, &mut grouped); + } + + # A pack is given only for a pack parameter, as the pack it is. + for i in 0..wanted { + val is_pack := this.types.kind_of(grouped[i]) == ty::pack; + if is_pack != this.decls.has(this.decls.list_at(params, i as u32), df::packed) { + this.report(node, ec::generic, is_pack + ? "A pack is passed on with `...` only for a pack parameter, as `Ts` of `box`." + : "A pack parameter is given types, or a pack passed on as `Ts...`."); + return bt::error; + } + } + + val made := this.types.named(decl, grouped.view()); + if grouped.length != 0 { + this.check_bounds(decl, made, node); + } + return made; +} + +#! The pack a pack parameter is given by the type arguments from `from` on: the +#! types, with each pack passed on as `Ts...` giving its types in their place. A +#! pack whose types are not known is only passed on alone, since where the types +#! after it go is not known until it is. +#! @param this The checker. +#! @param args The type arguments. +#! @param from The first the pack takes. +#! @param node The node notes are placed at. +#! @returns The pack, or the error type. +def checker::gather_pack(&mut this, args: span, from: u64, node: u32): u32 { + var items := vector::::new(); + for i in from..args.length { + val each := args[i]; + if this.types.kind_of(each) != ty::pack { + items.append(each); + continue; + } + if this.types.is_open_pack(each) { + if args.length - from != 1 { + if node != 0 { + this.report(node, ec::generic, "A pack whose types are not known yet is passed on alone, as the whole of what a pack parameter is given."); + } + return bt::error; + } + return each; + } + items.extend(this.types.parts_view(each)); + } + return this.types.pack(items.view(), 0); +} + +#! Reports type arguments given to what takes none. +#! @param this The checker. +#! @param node The `type_name` node. +#! @param index The segment that names what takes none. +def checker::no_type_args(&mut this, node: u32, index: u32): void { + if this.segment_args(node, index) != 0 { + this.report(node, ec::generic, "A type parameter takes no type arguments."); + } +} + +#! The type the segments of a type name from `from` name within the type: a +#! type a bound asks of a type parameter, as `C::cursor` where `C: iterable`, +#! or a nested type, as `cursor` of `vector::cursor`. In an instance, the +#! type parameter is the type it was given, which gives the type its bound asks +#! for, or else the bound's default, as `storage` of `type storage = self`. +#! @param this The checker. +#! @param kind The type the name is within. +#! @param node The `type_name` node. +#! @param from The first segment to resolve within the type. +#! @param param The type parameter the first segment names, or 0. +#! @returns The type named, or the error type where the type has none of a name. +def checker::projection(&mut this, kind: u32, node: u32, from: u32, param: u32): u32 { + var at := kind; + for i in from..this.segment_count(node) { + val name := this.segment_name(node, i as u32); + val segment := this.segment_node(node, i as u32); + var made := this.member_type(at, name); + if made == bt::error && i == from as u64 && param != 0 && this.types.kind_of(this.unalias(at)) != ty::param { + made = this.asked_of_bounds(at, param, name); + } + if made == bt::error { + var text := string::from("`", nothing {}); + val named := this.describe(at); + text.append(named.view()); + text.append("` has no type `"); + text.append(this.names.text(name)); + text.append("`."); + this.report_text(segment, ec::undefined, &text); + return bt::error; + } + at = made; + } + return at; +} + +#! The type parameter of the name that the declaration being checked, or one +#! it is declared within, declares. +#! @param this The checker. +#! @param name The ID of the name. +#! @returns The type parameter's declaration, or 0. +def checker::param_named(&this, name: u32): u32 { + var at := this.at.decl; + var steps := 0; + while at != 0 && steps < 4 { + val run: u32 = this.decls.params.p[at]; + for ¶m in this.decls.list_view(run) { + return param if this.decls.names.p[param] == name; + } + at = this.decls.owners.p[at]; + steps++; + } + return 0; +} + +#! The type a type given for a type parameter gives for one the parameter's +#! bounds ask for: its own of the name, or the bound's default. +#! @param this The checker. +#! @param kind The type given. +#! @param param The type parameter's declaration. +#! @param name The ID of the name. +#! @returns The type, or the error type where no bound asks for one of the name. +def checker::asked_of_bounds(&mut this, kind: u32, param: u32, name: u32): u32 { + this.resolve(param); + val run: u32 = this.decls.children.p[param]; + for i in 0..this.decls.list_length(run) { + val bound := this.decls.list_at(run, i as u32); + continue if this.types.kind_of(bound) != ty::named; + val member := this.trait_member(this.types.first_of(bound), name); + continue if member == 0 || this.decls.kinds.p[member] != dk::assoc_type; + return this.asked_type(kind, member, this.declaring_bound(bound, member)); + } + return bt::error; +} + +#! The type of the name a type has: what a bound asks of a type parameter, or +#! a type nested in it, given its arguments, or the error type. +#! @param this The checker. +#! @param kind The type. +#! @param name The ID of the name. +#! @returns The type, or the error type where it has none of the name. +pub def checker::member_type(&mut this, kind: u32, name: u32): u32 { + val plain := this.unalias(kind); + if this.types.kind_of(plain) == ty::param { + val found := this.find_in_bounds(plain, name); + return bt::error if found.decl == 0 || this.decls.kinds.p[found.decl] != dk::assoc_type; + return this.projected(plain, found.decl, found.owner); + } + + val found := this.find_path_member(kind, name); + return bt::error if found.decl == 0 || !this.is_type_decl(found.decl); + this.resolve(found.decl); + return this.instantiated(this.decls.types.p[found.decl], found.decl, found.owner); +} + +#! The type parameter standing for the type a bound asks of a type parameter, +#! as `C::cursor`, whose bounds are those the trait gives the type it asks for. +#! @param this The checker. +#! @param kind The type parameter's type. +#! @param asked The declaration of the type the bound asks for. +#! @param bound The bound asking for it. +#! @returns The type parameter's type. +pub def checker::projected(&mut this, kind: u32, asked: u32, bound: u32): u32 { + val key := pair_key(kind, asked); + if this.projections.get(&key) is some(got) { + val made: u32 = got; + return this.decls.types.p[made]; + } + + # A pack asked for, as `F::params`, is stood in for by a pack whose types are + # not known. + val id := this.decls.add(dk::type_param, this.decls.names.p[asked], this.decls.files.p[asked], + this.decls.nodes.p[asked], this.decls.modules.p[asked]); + this.decls.own(id, this.decls.owners.p[asked]); + if this.decls.has(asked, df::packed) { + this.decls.mark(id, df::packed); + this.decls.types.p[id] = this.types.pack(span::::empty(), id); + } else { + this.decls.types.p[id] = this.types.param(id); + } + this.decls.states.p[id] = ds::resolved; + this.projections.set(key, id); + this.stand_ins.append(checker::stand_in { base = kind, asked = asked, param = id, bound = bound }); + + # Its bounds are the trait's for the type it asks for, with the trait's + # parameters given the bound's arguments and `self` the type parameter. + this.resolve(asked); + val holder: u32 = this.decls.owners.p[asked]; + var from := vector::::new(); + var to := vector::::new(); + from.append(this.self_decl(holder)); + to.append(kind); + val params: u32 = this.decls.params.p[holder]; + for i in 0..this.decls.list_length(params) { + from.append(this.decls.list_at(params, i as u32)); + to.append(i < this.types.part_count(bound) ? this.types.part_at(bound, i as u32) : bt::error); + } + var bounds := vector::::new(); + val run: u32 = this.decls.children.p[asked]; + for i in 0..this.decls.list_length(run) { + bounds.append(this.substitute(this.decls.list_at(run, i as u32), from.view(), to.view())); + } + this.decls.children.p[id] = this.decls.make_list(bounds.view()); + return this.decls.types.p[id]; +} + +#! Reports a declaration named from where it is not visible. +#! @param this The checker. +#! @param node The node naming it. +#! @param decl The declaration. +pub def checker::report_hidden(&mut this, node: u32, decl: u32): void { + var text := string::from("`", nothing {}); + text.append(this.decl_text(decl)); + text.append("` is not `pub`, so only its own module and those within it see it."); + this.report_text(node, ec::hidden, &text); +} diff --git a/analyzer/checker/results.sakura b/analyzer/checker/results.sakura new file mode 100644 index 00000000..77e902e9 --- /dev/null +++ b/analyzer/checker/results.sakura @@ -0,0 +1,376 @@ +#! @file results.sakura +#! @author John Christman (sorakatadzuma@gmail.com) +#! @copyright Malunal Studios, LLC. +#! @license MIT +#! +#! Contains the result tables, which hold what the checker works out of each +#! node: its type, what it refers to, and its flags, with the constant it is +#! and the type it converts to where it has them. A file has a table of all of +#! its nodes, and an instance of a generic a table of its template's nodes, so +#! the same node has the results of each instance it is checked in. + +module sakura::analyzer; + + +#! What a node's flags hold. +pub enum rf : u16 { + place = 0x0001, #! It names a place: a variable, parameter, field, element, or what a reference or pointer reaches. + writable = 0x0002, #! The place can be written. + known = 0x0004, #! Its value is known while compiling, and is in `r_values`. + local = 0x0008, #! It declares a local, whose type is the node's type. + mutable = 0x0010, #! The local it declares can be written. + checked = 0x0020, #! It has been checked, which a node reached twice is checked once for. + borrowed = 0x0040, #! A reference to it was taken for a parameter, as `&` before it would. + leaves = 0x0080, #! A statement after which the block never goes on: it returns, breaks, or continues. + method = 0x0100, #! A member that is a method, which a call gives `this`. + narrowed = 0x0200, #! A binding of what an `is` test or match arm names. + reflected = 0x0400, #! It gives descriptions of reflection, which are in `reflections`. + invokes = 0x0800, #! A call of a value of no function type, through its `invoke`, whose `this` the callee is. + valued = 0x1000, #! A reference taken as the value it reaches, as a binding, a pattern, `for`, or inference takes one not written with `&`. + relent = 0x2000, #! `&` of a reference, or of a field holding one, which is that reference, since references never stack. + adapted = 0x4000, #! A function named as a value of another function type, which a function made for it calls it as, as a call would. +} + +#! What a node's reference holds: a declaration, or with one of these bits, the +#! node declaring a local, or a type a type parameter is bound to. +pub const ref_local: u32 = 0x80000000; #! The node declaring a local, in the bits of `ref_mask`. +pub const ref_type: u32 = 0x40000000; #! A type a type parameter is bound to, in the bits of `ref_mask`. +pub const ref_mask: u32 = 0x3FFFFFFF; #! The bits holding the declaration, node, or type. + +#! Adds a result table of `count` nodes from `base` of the file. +#! @param this The checker. +#! @param file The file whose nodes it holds results of. +#! @param base The first node it holds. +#! @param count How many nodes it holds. +#! @param instance One more than the instance it is of, or 0 for the file's +#! own. +#! @returns Its index. +pub def checker::add_table(&mut this, file: u32, base: u32, count: u32, instance: u32): u32 { + val index := this.tables.length as u32; + this.tables.append(rtable { + file = file, + base = base, + count = count, + offset = this.r_types.length as u32, + instance = instance + }); + + this.resize_results(this.r_types.length + count as u64); + return index; +} + +#! Makes each result column hold a number of nodes' results, the nodes added +#! holding none. +#! @param this The checker. +#! @param total How many nodes' results each holds after. +def checker::resize_results(&mut this, total: u64): void { + this.r_types.resize(total); + this.r_refs.resize(total); + this.r_flags.resize(total); +} + +#! Copies a node's results, at one row of the results, to another. +#! @param this The checker. +#! @param from The row to copy from. +#! @param to The row to copy to. +def checker::copy_results(&mut this, from: u64, to: u64): void { + this.r_types.p[to] = this.r_types.p[from]; + this.r_refs.p[to] = this.r_refs.p[from]; + this.r_flags.p[to] = this.r_flags.p[from]; + copy_row(&mut this.r_converts, from, to); + copy_row(&mut this.r_values, from, to); +} + +# Copies what a map holds of one row to another, or takes what it holds of the +# other where it holds nothing of the one. +def copy_row(rows: &mut keymap, from: u64, to: u64): void { + if rows.get(&from) is some(held) { + rows.set(to, held); + } else { + rows.remove(&to); + } +} + +#! Lets go of a node's results, at a row of the results. +#! @param this The checker. +#! @param at The row. +def checker::drop_results(&mut this, at: u64): void { + this.r_types.p[at] = 0; + this.r_refs.p[at] = 0; + this.r_flags.p[at] = 0; + this.r_converts.remove(&at); + this.r_values.remove(&at); +} + +#! Adds a result table of the nodes from `base`, within the one being written, +#! whose nodes it holds but for its own: what a body checked once for each of +#! several things, as `for const`, writes for each. +#! @param this The checker. +#! @param base The first node it holds. +#! @param count How many nodes it holds. +#! @returns Its index. +pub def checker::add_child_table(&mut this, base: u32, count: u32): u32 { + val index := this.add_table(this.at.file, base, count, this.tables.p[this.at.table].instance); + this.tables.p[index].parent = this.at.table + 1; + return index; +} + +#! Makes the table the one results are read from and written to. +#! @param this The checker. +#! @param table The table's index. +pub def checker::use_table(&mut this, table: u32): void { + val held: rtable = this.tables.p[table]; + this.at.table = table; + this.at.file = held.file; + this.at.base = held.base; + this.at.offset = held.offset; + this.at.count = held.count; + + val syntax := &this.units[held.file].syntax; + this.at.kinds = syntax.node_kinds.view().data; + this.at.tokens = syntax.node_tokens.view().data; + this.at.lefts = syntax.node_lefts.view().data; + this.at.rights = syntax.node_rights.view().data; + this.at.extras = syntax.extras.view().data; + this.at.names = syntax.token_names.view().data; + this.at.tkinds = syntax.token_kinds.view().data; +} + +#! The table holding the node's results: the one being written, or the one it +#! was made within that holds the node, or `no_table`. +#! @param this The checker. +#! @param node The node. +#! @returns The table's index, or `no_table`. +def checker::holding(&this, node: u32): u32 { + return this.at.table if node >= this.at.base && node - this.at.base < this.at.count; + + var table: u32 = this.tables.p[this.at.table].parent; + var steps := 0; + while table != 0 && steps < 32 { + val held: rtable = this.tables.p[table - 1]; + return table - 1 if node >= held.base && node - held.base < held.count; + table = held.parent; + steps++; + } + return checker::no_table; +} + +#! What says no table holds a node. +pub const checker::no_table: u32 = 0xFFFFFFFF; + +#! Where the node's results are in the result vectors, or past their end where +#! no table being written holds the node. Every read and write of a result +#! finds it here, so it is copied where it is called. +#! @param this The checker. +#! @param node The node. +#! @returns The index of its results. +@inline +def checker::slot(&this, node: u32): u64 { + if node >= this.at.base && node - this.at.base < this.at.count { + return this.at.offset as u64 + (node - this.at.base) as u64; + } + return this.slot_elsewhere(node); +} + +#! Where the results are of a node the table being written does not hold, as +#! `slot` says, which is apart so `slot` stays small where it is copied. +#! @param this The checker. +#! @param node The node. +#! @returns The index of its results. +def checker::slot_elsewhere(&this, node: u32): u64 { + val table := this.holding(node); + return this.r_types.length if table == checker::no_table; + val held: rtable = this.tables.p[table]; + return held.offset as u64 + (node - held.base) as u64; +} + +#! The type checking gave a node. +#! @param this The checker. +#! @param node The node. +#! @returns Its type, or 0 where it has none, or no table being written holds +#! it. +@inline +pub def checker::type_at(&this, node: u32): u32 { + val at := this.slot(node); + return at < this.r_types.length ? this.r_types.p[at] : 0; +} + +#! Records the type of a node. +#! @param this The checker. +#! @param node The node, whose type is not recorded where no table being +#! written holds it. +#! @param kind The type. +@inline +pub def checker::set_type(&mut this, node: u32, kind: u32): void { + val at := this.slot(node); + if at < this.r_types.length { + this.r_types.p[at] = kind; + } +} + +#! What a node refers to. +#! @param this The checker. +#! @param node The node. +#! @returns A declaration, a local or a type with its bit of `ref_local` or +#! `ref_type`, or 0. +@inline +pub def checker::ref_at(&this, node: u32): u32 { + val at := this.slot(node); + return at < this.r_refs.length ? this.r_refs.p[at] : 0; +} + +#! Records what a node refers to. +#! @param this The checker. +#! @param node The node. +#! @param ref A declaration, or a local or a type with its bit. +@inline +pub def checker::set_ref(&mut this, node: u32, ref: u32): void { + val at := this.slot(node); + if at < this.r_refs.length { + this.r_refs.p[at] = ref; + } +} + +#! The flags of a node, as `rf` says. +#! @param this The checker. +#! @param node The node. +#! @returns Its flags, or 0. +@inline +pub def checker::flags_at(&this, node: u32): u32 { + val at := this.slot(node); + return at < this.r_flags.length ? this.r_flags.p[at] as u32 : 0; +} + +#! Whether a node has a flag. +#! @param this The checker. +#! @param node The node. +#! @param flag The flag. +#! @returns Whether it has it. +@inline +pub def checker::has_flag(&this, node: u32, flag: rf): bool { + return (this.flags_at(node) & flag as u32) != 0; +} + +#! Gives a node a flag. +#! @param this The checker. +#! @param node The node. +#! @param flag The flag. +@inline +pub def checker::set_flag(&mut this, node: u32, flag: rf): void { + val at := this.slot(node); + if at < this.r_flags.length { + this.r_flags.p[at] |= flag as u16; + } +} + +#! Takes a flag from a node. +#! @param this The checker. +#! @param node The node. +#! @param flag The flag. +@inline +pub def checker::clear_flag(&mut this, node: u32, flag: rf): void { + val at := this.slot(node); + if at < this.r_flags.length { + this.r_flags.p[at] &= ~(flag as u16); + } +} + +#! The key of the node within the current table, for the sparse results. +#! @param this The checker. +#! @param node The node. +#! @returns The key: `table << 32 | node`. +pub def checker::result_key(&this, node: u32): u64 { + val table := this.holding(node); + return pair_key(table == checker::no_table ? this.at.table : table, node); +} + +#! Records that the node's value converts to the type, which is not its own. +#! @param this The checker. +#! @param node The node. +#! @param kind The type it converts to. +pub def checker::set_convert(&mut this, node: u32, kind: u32): void { + val at := this.slot(node); + if at < this.r_types.length { + if kind != 0 { + this.r_converts.set(at, kind); + } else { + this.r_converts.remove(&at); + } + return; + } + this.converts.set(this.result_key(node), kind); +} + +#! The type the node's value becomes where it is used: what it converts to, or +#! its own type. +#! @param this The checker. +#! @param node The node. +#! @returns The type. +pub def checker::converted(&this, node: u32): u32 { + val at := this.slot(node); + if at < this.r_types.length { + return this.r_converts.get_or(&at, this.r_types.p[at]); + } + val key := this.result_key(node); + return this.converts.get_or(&key, this.type_at(node)); +} + +#! Records that the node's value is known while compiling. +#! @param this The checker. +#! @param node The node. +#! @param value Its value. +pub def checker::set_value(&mut this, node: u32, value: constant): void { + val id := this.intern_constant(value); + val at := this.slot(node); + if at < this.r_types.length { + this.r_values.set(at, id); + this.r_flags.p[at] |= rf::known as u16; + return; + } + this.values.set(this.result_key(node), id); + this.set_flag(node, rf::known); +} + +#! The ID of a constant among `constants`, which it is added to where it is +#! new, so each value is held once however many nodes are it: most are 0, 1, +#! or a small number. +#! @param this The checker. +#! @param value The constant. +#! @returns Its ID. +pub def checker::intern_constant(&mut this, value: constant): u32 { + val hash := mix(mix(value.word, value.negative ? 1 : 0), value.floating ? 1 : 0); + var walk := this.constant_index.walk(hash); + var at := this.constant_index.next(&mut walk); + while at != 0 { + return at - 1 if this.constants.p[at - 1].same(&value); + at = this.constant_index.next(&mut walk); + } + val id := this.constants.length as u32; + this.constants.append(value); + this.constant_index.add(hash, id); + return id; +} + +#! Whether the node's value is known while compiling. +#! @param this The checker. +#! @param node The node. +#! @returns Whether it is. +@inline +pub def checker::is_known(&this, node: u32): bool { + return this.has_flag(node, rf::known); +} + +#! The node's value, where it is known, or a zero constant: constant 0, which +#! stands for none. +#! @param this The checker. +#! @param node The node. +#! @returns Its value. +pub def checker::value_at(&this, node: u32): constant { + # A node a table holds says whether it has a value, which most have none of. + val at := this.slot(node); + if at < this.r_types.length { + return (this.r_flags.p[at] & rf::known as u16) != 0 ? this.constants.p[this.r_values.get_or(&at, 0)] : constant {}; + } + val key := this.result_key(node); + return this.constants.p[this.values.get_or(&key, 0)]; +} diff --git a/analyzer/checker/scopes.sakura b/analyzer/checker/scopes.sakura new file mode 100644 index 00000000..2c4c031c --- /dev/null +++ b/analyzer/checker/scopes.sakura @@ -0,0 +1,67 @@ +#! @file scopes.sakura +#! @author John Christman (sorakatadzuma@gmail.com) +#! @copyright Malunal Studios, LLC. +#! @license MIT +#! +#! Contains the bindings of names to the locals, parameters, and type +#! parameters they refer to. They are one stack, and each name keeps the +#! binding of it nearest the top, so finding what a name refers to takes one +#! read, and a scope ends by cutting the stack back to where it began. + +module sakura::analyzer; + + +#! Where the bindings are now, which a scope ending cuts them back to. +#! @param this The checker. +#! @returns The mark. +pub def checker::scope_mark(&this): u32 { + return this.bind_names.length as u32; +} + +#! Binds the name to what it refers to, hiding what it referred to before +#! until the scope ends. `_` is never bound, since nothing reads it. +#! @param this The checker. +#! @param name The ID of the name. +#! @param value What it refers to: a local or type parameter with its bit of +#! `ref_local` or `ref_type`. +pub def checker::bind(&mut this, name: u32, value: u32): void { + return if name == names::underscore_id || name == 0; + + if this.innermost.length <= name as u64 { + this.innermost.resize(name as u64 + 1); + } + + this.bind_names.append(name); + this.bind_values.append(value); + this.bind_prev.append(this.innermost[name]); + this.innermost[name] = this.bind_names.length as u32; +} + +#! Ends the scopes begun since the mark. +#! @param this The checker. +#! @param mark Where the bindings were, as `scope_mark` gave it. +pub def checker::unbind_to(&mut this, mark: u32): void { + # Each name is given back what it hid from the top down, so a name bound more + # than once since the mark is given back what it was bound to before. + var top := this.bind_names.length; + return if top <= mark as u64; + while top > mark as u64 { + top--; + val name: u32 = this.bind_names[top]; + this.innermost[name] = this.bind_prev[top]; + } + this.bind_names.resize(mark as u64); + this.bind_values.resize(mark as u64); + this.bind_prev.resize(mark as u64); +} + +#! What the name is bound to, or 0 where it is bound to nothing. +#! @param this The checker. +#! @param name The ID of the name. +#! @returns What it is bound to, or 0. +pub def checker::bound(&this, name: u32): u32 { + return 0 if name as u64 >= this.innermost.length; + + val at: u32 = this.innermost[name]; + return at == 0 ? 0 : this.bind_values[at - 1]; +} diff --git a/analyzer/checker/statements.sakura b/analyzer/checker/statements.sakura new file mode 100644 index 00000000..84f974f1 --- /dev/null +++ b/analyzer/checker/statements.sakura @@ -0,0 +1,1445 @@ +#! @file statements.sakura +#! @author John Christman (sorakatadzuma@gmail.com) +#! @copyright Malunal Studios, LLC. +#! @license MIT +#! +#! Contains the checking of statements: blocks and the locals declared in +#! them, branches, loops, matches, and leaving by `return`, `break`, and +#! `continue`. Each statement says whether the block never goes on past it, +#! which tells a function that can end without returning a value, and where +#! the names an `is not` test gives are named for the rest of the block. + +module sakura::analyzer; + + +#! What checking a statement says of what follows it. +pub enum flow : u8 { + goes_on, #! The block goes on past it. + leaves, #! The block never goes on past it: it returns, breaks, or continues on every path. + skips, #! It leaves, as decided while checking, so what follows is never checked. +} + +#! Checks a block, whose locals are of its scope. +#! @param this The checker. +#! @param node The `block` node. +#! @returns Whether the block never goes on past its end. +pub def checker::check_block(&mut this, node: u32): flow { + return flow::goes_on if node == 0; + if this.kind_of(node) != nk::block { + return this.check_stmt(node); + } + + val mark := this.scope_mark(); + val proved := this.proved_params.length; + val outer := this.at.block; + val opened := this.at.opened; + var how := flow::goes_on; + val run := this.left_of(node); + this.at.block = node; + this.at.opened = mark; + for &stmt in this.run_view(run) { + val made := this.check_stmt(stmt); + if made == flow::skips { + how = flow::skips; + break; + } + if made == flow::leaves { + how = flow::leaves; + } + } + this.at.block = outer; + this.at.opened = opened; + this.unbind_to(mark); + this.unprove_to(proved); + if how != flow::goes_on { + this.set_flag(node, rf::leaves); + } + return how; +} + +#! Forgets the bounds proved since the mark. +#! @param this The checker. +#! @param mark How many bounds were proved before, as `proved_params` held. +def checker::unprove_to(&mut this, mark: u64): void { + if this.proved_params.length > mark { + this.proved_params.resize(mark); + this.proved_bounds.resize(mark); + } +} + +#! Proves the bounds an `if const` condition tests of type parameters, where it +#! holds as `positive` says: `T is Shown` where it holds, `T is not Shown` where +#! it does not. +#! @param this The checker. +#! @param condition The condition's node. +#! @param positive Whether the condition holds where the bounds are proved. +def checker::prove(&mut this, condition: u32, positive: bool): void { + match this.kind_of(condition) { + nk::is_test => { + return if this.node_has(condition, nf::negated) == positive || this.node_has(condition, nf::computed); + val value := this.left_of(condition); + var tested := this.tested_type(value); + if tested == 0 { + tested = this.read_type(this.type_at(value)); + } + val plain := this.unalias(tested); + return if this.types.kind_of(plain) != ty::param; + + val bound := this.resolve_type(this.record(condition, is_slot::target)); + return if this.named_kind(bound) != dk::trait_type; + this.proved_params.append(this.types.first_of(plain)); + this.proved_bounds.append(bound); + } + nk::binary => { + val operator := this.token_kind(condition); + if (operator == tk::logand && positive) || (operator == tk::logor && !positive) { + this.prove(this.left_of(condition), positive); + this.prove(this.right_of(condition), positive); + } + } + nk::unary => { + if this.token_kind(condition) == tk::negate { + this.prove(this.left_of(condition), !positive); + } + } + else => {} + } +} + +#! Checks a branch of an `if const` a generic's own body does not decide. Where +#! its condition says a type parameter is a type, as `T is strview`, the branch +#! names the type by the parameter's name, and is checked in each instance +#! taking it, where the parameter is that type, rather than here, where it is +#! still a parameter, so what it says of the parameter is noted only there. +#! Where evaluating decides it, a `compile_error` within waits for evaluating to +#! choose the branch. +#! @param this The checker. +#! @param branch The branch. +#! @param condition The condition. +#! @param positive Whether the condition holds in the branch. +#! @param decided The `if_const` node, where evaluating decides it, or 0. +#! @returns How the branch ends. +def checker::check_proved(&mut this, branch: u32, condition: u32, positive: bool, decided: u32): flow { + val mark := this.scope_mark(); + val same := this.identify(condition, positive); + if same { + this.mute++; + } + if decided != 0 { + this.branches.append(checker::branch { table = this.at.table, node = decided, holds = positive }); + } + val made := this.check_block(branch); + if decided != 0 { + this.branches.truncate(); + } + if same { + this.mute--; + } + this.unbind_to(mark); + return made; +} + +#! Binds the name of each type parameter an `if const` condition says is a +#! type to that type, where it holds as `positive` says: `T is strview` where it +#! holds, `T is not strview` where it does not. A trait is a bound, which +#! `prove` proves instead. +#! @param this The checker. +#! @param condition The condition's node. +#! @param positive Whether the condition holds. +#! @returns Whether it bound any. +def checker::identify(&mut this, condition: u32, positive: bool): bool { + match this.kind_of(condition) { + nk::is_test => { + return false if this.node_has(condition, nf::negated) == positive || this.node_has(condition, nf::computed); + val value := this.left_of(condition); + var tested := this.tested_type(value); + if tested == 0 { + tested = this.read_type(this.type_at(value)); + } + val plain := this.unalias(tested); + return false if this.types.kind_of(plain) != ty::param; + + val target := this.resolve_type(this.record(condition, is_slot::target)); + return false if target == bt::error || this.named_kind(target) == dk::trait_type; + this.bind(this.decls.names.p[this.types.first_of(plain)], ref_type | target); + return true; + } + nk::binary => { + val operator := this.token_kind(condition); + if (operator == tk::logand && positive) || (operator == tk::logor && !positive) { + val left := this.identify(this.left_of(condition), positive); + val right := this.identify(this.right_of(condition), positive); + return left || right; + } + } + nk::unary => { + if this.token_kind(condition) == tk::negate { + return this.identify(this.left_of(condition), !positive); + } + } + else => {} + } + return false; +} + +#! Checks a statement. +#! @param this The checker. +#! @param node The statement. +#! @returns How it ends: whether what follows it runs. +pub def checker::check_stmt(&mut this, node: u32): flow { + match this.kind_of(node) { + nk::block => return this.check_block(node); + nk::variable => this.local(node); + nk::if_stmt => return this.check_if(node); + nk::if_const => return this.check_if_const(node); + nk::when_block => return this.check_block(this.when_branch(node)); + nk::while_stmt => this.check_while(node); + nk::for_stmt => this.check_for(node); + nk::match_stmt => return this.check_match_stmt(node); + nk::return_stmt => { + this.check_return(node); + return flow::leaves; + } + nk::break_stmt, nk::continue_stmt => { + if this.at.loops == 0 { + this.report(node, ec::control, "`break` and `continue` leave a loop, and this is in none."); + } + return flow::leaves; + } + nk::expr_stmt => { + val inner := this.left_of(node); + val kind := this.settle_expr(inner); + this.check_handled(inner, kind); + return this.ends_program(inner) ? flow::leaves : flow::goes_on; + } + nk::contract => this.check_contract(node); + nk::error => {} + else => { + this.settle_expr(node); + } + } + return flow::goes_on; +} + +#! Reports a value let go of where it is made that is `@nodiscard`: given by a +#! function marked so, or of a type marked so. An assignment is the value it +#! handles, and `_ = x` lets go of a value on purpose. +#! @param this The checker. +#! @param node The expression of the statement. +#! @param kind Its type. +def checker::check_handled(&mut this, node: u32, kind: u32): void { + return if this.kind_of(node) == nk::assign || kind == bt::error; + + val named := this.unalias(kind); + val typed := this.types.kind_of(named) == ty::named && this.decls.has(this.types.first_of(named), df::nodiscard); + var called := false; + if this.kind_of(node) == nk::call { + val decl := this.ref_at(node); + called = decl != 0 && (decl & (ref_local | ref_type)) == 0 && this.decls.has(decl, df::nodiscard); + } + return if !typed && !called; + + var text := string::from("`", nothing {}); + if typed { + val described := this.describe(kind); + text.append(described.view()); + } else { + text.append(this.decl_text(this.ref_at(node))); + } + text.append("` is `@nodiscard`, so what is made here is handled; `_ = ...` lets go of it on purpose."); + this.report_text(node, ec::unhandled, &text); +} + +#! Whether an expression is a call of `system::exit`, `system::abort`, or +#! `fault`, after which the program never goes on, or of `compile_error`, +#! after which nothing in its branch is checked. +#! @param this The checker. +#! @param node The expression. +#! @returns Whether it is. +def checker::ends_program(&mut this, node: u32): bool { + return false if this.kind_of(node) != nk::call; + val decl := this.ref_at(node); + return false if decl == 0 || (decl & (ref_local | ref_type)) != 0; + val name := this.names.text(this.decls.names.p[decl]); + return (name == "exit" || name == "abort" || name == "fault" || name == "compile_error") && this.decls.has(decl, df::intrinsic); +} + +#! Which contract a `contract` node is, as its word says. +#! @param this The checker. +#! @param node The `contract` node. +#! @returns Which it is. +pub def checker::clause_of(&this, node: u32): clause { + val word := this.name_of(node); + return word == names::expects_id ? clause::expects + : word == names::asserts_id ? clause::asserts + : clause::ensures; +} + +#! A contract: its condition is a `bool`, and what it says failed a `strview`. +#! An `ensures` in a function's own block may name what the function returns, +#! as `ensures(r: r > 0)`, which only its condition sees. Its own type is the +#! `string` its report is made as where it fails. +#! @param this The checker. +#! @param node The `contract` node. +def checker::check_contract(&mut this, node: u32): void { + val condition := this.left_of(node); + val bound := this.record(node, contract_slot::bound); + val text := this.record(node, contract_slot::text); + this.set_type(node, this.std_type(word::string, span::::empty())); + + val mark := this.scope_mark(); + if bound != 0 { + val result := this.at.result; + if result == bt::void_type { + this.report(bound, ec::invalid, "An `ensures` names what the function returns, and this one returns nothing."); + } else if this.at.block != this.at.body { + this.report(bound, ec::invalid, + "An `ensures` names what the function returns only in the function's own block, which every `return` leaves."); + } + this.declare_local(bound, this.name_of(bound), result); + } + this.check_condition(condition); + this.unbind_to(mark); + if text != 0 { + this.check_expr(text, this.std_type(word::strview, span::::empty())); + } + this.refuse_changes(condition); +} + +#! Reports what a contract's condition changes, by `=`, `+=` and the like, or +#! `++` and `--`, since `--contracts off` leaves the condition out, which would +#! change what the program does. What an anonymous function within it does is +#! its own. +#! @param this The checker. +#! @param condition The condition. +def checker::refuse_changes(&mut this, condition: u32): void { + var todo := vector::::new(); + todo.append(condition); + while todo.length != 0 { + val at: u32 = todo.last(); + todo.truncate(); + continue if at == 0; + val kind := this.kind_of(at); + continue if kind == nk::lambda; + val token := this.token_kind(at); + if kind == nk::assign || kind == nk::postfix || (kind == nk::unary && (token == tk::increment || token == tk::decrement)) { + this.report(at, ec::invalid, + "A contract's condition changes nothing, since `--contracts off` leaves it out, and the program would then do otherwise."); + } + this.syn().children(at, &mut todo); + } +} + +#! `old(e)` within an `ensures`: what `e` was where the `ensures` was reached, +#! read through references, kept as a copy until the `ensures` is checked, so +#! it is of a type that closes nothing. +#! @param this The checker. +#! @param node The `old_value` node. +#! @returns Its type, or the error type where it is not valid. +pub def checker::old_value(&mut this, node: u32): u32 { + val inner := this.left_of(node); + val own := this.settle_expr(inner); + return bt::error if own == bt::error; + val held := this.read_type(own); + if held != own && !this.convert(inner, held) { + return bt::error; + } + if this.closes(held) { + var text := string::from("`old` keeps a copy of what it is given until the `ensures` is checked, so it takes what closes nothing, as a number or a view, and `", nothing {}); + val described := this.describe(held); + text.append(described.view()); + text.append("` closes."); + this.report_text(inner, ec::owned, &text); + return bt::error; + } + return held; +} + +#! A local variable or constant, or a function declared within a block, which +#! is named before its body is checked so it can call itself. +#! @param this The checker. +#! @param node The `variable` or `function` node. +def checker::local(&mut this, node: u32): void { + val name := this.name_of(node); + this.check_redeclared(node, name); + val written := this.record(node, variable_slot::type_expr); + val value := this.record(node, variable_slot::value); + var kind: u32 = written != 0 ? this.value_type(written) : 0; + + if this.node_has(node, nf::function) && value != 0 && this.kind_of(value) == nk::lambda { + kind = this.lambda_signature(value); + this.declare_local(node, name, kind); + this.check_expr(value, kind); + return; + } + + if value != 0 && this.kind_of(value) == nk::undefined { + this.undefined_local(node, value, kind); + } else if value != 0 { + # A pointer bound to a name is no reference, which would keep what `&` makes. + if this.kind_of(value) == nk::cast { + this.infer_expr(value); + if this.types.kind_of(this.unalias(this.type_at(value))) == ty::pointer { + this.refuse_lent_temporary(value); + } + } + if kind != 0 { + this.check_expr(value, kind); + this.check_owned(value, kind); + } else { + val own := this.infer_expr(value); + kind = this.settle(own); + # A binding takes the value it is given: what a reference reaches is copied + # unless `&` is written, as `val e := &v[i]`. + if this.takes_value(value, kind) { + kind = this.types.first_of(this.unalias(kind)); + } + if this.types.kind_of(kind) == ty::null_type || this.types.kind_of(kind) == ty::empty { + this.report(value, ec::mismatch, "Nothing gives the variable a type: write one, as `val p: *u8 = null;`."); + kind = bt::error; + } else if kind != own && kind != bt::error { + this.set_convert(value, kind); + } + this.check_owned(value, kind); + } + } else if kind != 0 && !this.has_zero(kind, 0) { + var text := string::from("`", nothing {}); + val named := this.describe(kind); + text.append(named.view()); + text.append(this.types.kind_of(this.unalias(kind)) == ty::param + ? "` may be a reference, which has no zero value, so the variable is given a value where it is declared, or the parameter is bounded by `zeroable`." + : "` has no zero value, so the variable is given a value where it is declared."); + this.report_text(node, ec::zero_value, &text); + } + + # A constant's value that folding does not give, as a table of numbers, is + # run while checking, as a global constant's is. + if this.node_has(node, nf::constant) && value != 0 && !this.is_known(value) && this.type_at(value) != bt::error { + var made := ev {}; + val worked := this.evaluate(value, value, &mut made); + if worked && !made.array { + this.set_value(value, made.scalar); + } + # What the checker's evaluator does not run is evaluated once checking is + # done, where the language whole runs, apart from the locals around it. + if !worked && !this.ev_failed && this.reads_outer_locals(value) { + this.report(value, ec::constant, "A constant's value is known while compiling."); + } else if (!worked && !this.ev_failed) || (worked && made.array) { + this.wait_for_evaluation(node); + } + } + if this.node_has(node, nf::constant) && value != 0 && this.is_known(value) { + this.set_value(node, this.value_at(value)); + } + + this.declare_local(node, name, kind == 0 ? bt::error : kind); + if this.node_has(node, nf::mutable) { + this.set_flag(node, rf::mutable); + } +} + +#! `undefined` as a local's value, which leaves its memory as it is until the +#! program writes it: only a `var` with a type written, of what has a zero value +#! and closes nothing, since closing it, or reading it as a reference or a +#! function, would read what the memory happened to hold. +#! @param this The checker. +#! @param node The `variable` node. +#! @param value The `undefined` node. +#! @param kind The type written, or 0. +def checker::undefined_local(&mut this, node: u32, value: u32, kind: u32): void { + if !this.node_has(node, nf::mutable) { + this.report(value, ec::invalid, + "`undefined` leaves a variable's memory as it is until the program writes it, so it is a `var`'s value, never a `val`'s or a constant's."); + return; + } + if kind == 0 { + this.report(value, ec::invalid, "`undefined` gives the variable no type: write one, as `var buffer: u8[64] = undefined;`."); + return; + } + return if kind == bt::error; + this.set_type(value, kind); + if !this.has_zero(kind, 0) || this.closes(kind) { + var text := string::from("`", nothing {}); + val named := this.describe(kind); + text.append(named.view()); + text.append(this.closes(kind) + ? "` closes, which would close what the memory happened to hold, so the variable is given a value: `undefined` is for what closes nothing, as numbers, pointers, and arrays of them." + : "` has no zero value, so the variable is given a value where it is declared, rather than `undefined`."); + this.report_text(value, ec::invalid, &text); + } +} + +#! Reports a local declared where its block already declares one of its name, +#! or names one where an `is not` test before it leaves. One within the block, +#! or of a parameter, may hide it. +#! @param this The checker. +#! @param node The local's node. +#! @param name The ID of its name. +def checker::check_redeclared(&mut this, node: u32, name: u32): void { + return if name == names::underscore_id || name as u64 >= this.innermost.length; + val at: u32 = this.innermost[name]; + return if at <= this.at.opened || (this.bind_values[at - 1] & ref_local) == 0; + val first: u32 = this.bind_values[at - 1] & ref_mask; + this.report_related(node, ec::duplicate, "The block already declares a local of this name: name this one apart, or assign the first.", + this.at.file, first, "Declared first here."); +} + +#! Declares a local of the type at the node, binding its name. +#! @param this The checker. +#! @param node The node declaring it, which records its type and which its +#! name refers to. +#! @param name The ID of its name. +#! @param kind Its type. +pub def checker::declare_local(&mut this, node: u32, name: u32, kind: u32): void { + this.set_type(node, kind); + this.set_flag(node, rf::local); + this.bind(name, ref_local | node); +} + +#! The function type an anonymous function's written types give. +#! @param this The checker. +#! @param node The `lambda` node. +#! @returns The function type. +def checker::lambda_signature(&mut this, node: u32): u32 { + var kinds := vector::::new(); + val params := this.left_of(node); + for ¶m in this.run_view(params) { + kinds.append(this.resolve_type(this.left_of(param))); + } + val result := this.record(node, lambda_slot::result); + return this.types.function(kinds.view(), result == 0 ? bt::void_type : this.resolve_type(result), false); +} + +#! `if`, with the names its condition's `is` tests give named where they hold: +#! those of `x is f(v)` in the branch it guards, and those of `x is not f(v)` in +#! the `else`, and for the rest of the block where the branch always leaves. +#! @param this The checker. +#! @param node The `if_stmt` node. +#! @returns How it ends: `leaves` where both branches do. +def checker::check_if(&mut this, node: u32): flow { + val condition := this.left_of(node); + val then := this.record(node, if_slot::then); + val other := this.record(node, if_slot::other); + + this.check_condition(condition); + val mark := this.scope_mark(); + this.bind_tests(condition, true); + val then_flow := this.check_block(then); + this.unbind_to(mark); + + var other_flow := flow::goes_on; + if other != 0 { + this.bind_tests(condition, false); + other_flow = this.check_block(other); + this.unbind_to(mark); + } + if then_flow != flow::goes_on { + this.bind_tests(condition, false); + } + + return flow::leaves if other != 0 && then_flow != flow::goes_on && other_flow != flow::goes_on; + return flow::goes_on; +} + +#! `if const`, whose condition is known while checking where it can be: only +#! the branch it takes is checked, and where that branch always leaves and +#! there is no `else`, nothing after it is either. +#! @param this The checker. +#! @param node The `if_const` node. +#! @returns How it ends: `skips` where the branch it takes leaves and there is +#! no `else`, so nothing after it is checked. +def checker::check_if_const(&mut this, node: u32): flow { + val condition := this.left_of(node); + val then := this.record(node, if_slot::then); + val other := this.record(node, if_slot::other); + this.check_condition(condition); + + # Where it is not decided, as of a type parameter, each branch is checked + # with the bounds its condition proves. What is worked out once checking is + # done reads no local the program running gives a value, which a generic's + # body walking what each instance knows, as `for const` over its type's + # members, leaves to each instance. + if !this.is_known(condition) { + val read := this.undecided == 0 && !this.waits_for_instance() ? this.runtime_local_read(condition) : 0; + if read != 0 { + this.report_runtime_read(read); + } else { + this.wait_for_evaluation(node); + } + # Where evaluating decides it, what a branch reports only where it is + # taken, a `compile_error`, waits for evaluating to choose the branch. + val decided := read == 0 && !this.waits_for_instance() ? node : 0; + val mark := this.proved_params.length; + this.undecided++; + this.prove(condition, true); + val then_flow := this.check_proved(then, condition, true, decided); + this.unprove_to(mark); + + var other_flow := flow::goes_on; + if other != 0 { + this.prove(condition, false); + other_flow = this.check_proved(other, condition, false, decided); + this.unprove_to(mark); + } else if then_flow != flow::goes_on { + this.prove(condition, false); + } + this.undecided--; + return other != 0 && then_flow != flow::goes_on && other_flow != flow::goes_on ? flow::leaves : flow::goes_on; + } + + if this.value_at(condition).magnitude != 0 { + val taken := this.check_block(then); + return taken != flow::goes_on && other == 0 ? flow::skips : taken; + } + return other != 0 ? this.check_block(other) : flow::goes_on; +} + +#! Whether an expression reads a local declared outside it, which a constant's +#! value cannot, being worked out apart from the locals around it. +#! @param this The checker. +#! @param node The expression. +#! @returns Whether it does. +def checker::reads_outer_locals(&mut this, node: u32): bool { + var todo := vector::::new(); + var lowest := node; + todo.append(node); + var seen := vector::::new(); + while todo.length != 0 { + val at: u32 = todo.last(); + todo.truncate(); + continue if at == 0; + lowest = at < lowest ? at : lowest; + seen.append(at); + this.syn().children(at, &mut todo); + } + for &each in seen { + continue if this.kind_of(each) != nk::name; + val ref := this.ref_at(each); + continue if (ref & ref_local) == 0; + val local := ref & ref_mask; + return true if local < lowest || local > node; + } + return false; +} + +#! The first name within an expression that reads a local declared outside it +#! whose value only the program running gives: not a constant, nor one known +#! while checking, nor the declaration `for const` walks. +#! @param this The checker. +#! @param node The expression. +#! @returns The `name` node, or 0. +def checker::runtime_local_read(&mut this, node: u32): u32 { + var todo := vector::::new(); + var seen := vector::::new(); + var lowest := node; + todo.append(node); + while todo.length != 0 { + val at: u32 = todo.last(); + todo.truncate(); + continue if at == 0; + lowest = at < lowest ? at : lowest; + seen.append(at); + this.syn().children(at, &mut todo); + } + var first: u32 = 0; + for &each in seen { + continue if this.kind_of(each) != nk::name; + val ref := this.ref_at(each); + continue if (ref & ref_local) == 0; + val local := ref & ref_mask; + continue if local >= lowest && local <= node; + continue if this.is_known(local) || this.reflected_at(local) != checker::no_reflection; + continue if this.kind_of(local) == nk::variable && this.node_has(local, nf::constant); + first = first == 0 || each < first ? each : first; + } + return first; +} + +#! Reports a local whose value only the program running gives, read by what is +#! computed while compiling. +#! @param this The checker. +#! @param read The `name` node reading it. +def checker::report_runtime_read(&mut this, read: u32): void { + var text := string::from("`", nothing {}); + text.append(this.names.text(this.name_of(read))); + text.append("` only exists once the program runs, so the value computed while compiling cannot use it."); + this.report_text(read, ec::constant, &text); +} + +#! Notes a local constant, or the condition of an `if const`, that checking +#! leaves to evaluating, which works it out once checking is done. Those of a +#! generic's own body are worked out for each of its instances. +#! @param this The checker. +#! @param node The `variable` or `if_const` node. +def checker::wait_for_evaluation(&mut this, node: u32): void { + return if this.waits_for_instance(); + this.to_evaluate.append(pair_key(this.at.table, node)); +} + +#! `while`, with the names its condition gives named in its body. +#! @param this The checker. +#! @param node The `while_stmt` node. +def checker::check_while(&mut this, node: u32): void { + val condition := this.left_of(node); + this.check_condition(condition); + + val mark := this.scope_mark(); + this.bind_tests(condition, true); + this.at.loops++; + this.check_block(this.right_of(node)); + this.at.loops--; + this.unbind_to(mark); +} + +#! `for`, over a range of integers or of an enum's members, the elements of a +#! fixed array, or what an iterator gives, by copy or by reference. +#! @param this The checker. +#! @param node The `for_stmt` node. +def checker::check_for(&mut this, node: u32): void { + val index := this.record(node, for_slot::index); + val variable := this.record(node, for_slot::variable); + val iterated := this.record(node, for_slot::iterated); + val end := this.record(node, for_slot::end); + val reference := this.node_has(node, nf::reference); + val mutable := this.node_has(node, nf::mutable); + val mark := this.scope_mark(); + + var element: u32 = bt::error; + val unrolled := this.node_has(node, nf::constant); + if unrolled && end != 0 { + this.unroll_range(node, variable, iterated, end); + this.unbind_to(mark); + return; + } + if unrolled { + val kind := this.infer_expr(iterated); + val plain := this.unalias(this.reached(kind)); + if this.types.kind_of(plain) == ty::pack { + this.unroll_pack(node, variable, plain); + this.unbind_to(mark); + return; + } + val list := this.reflected_at(iterated); + if list != checker::no_reflection && this.reflected_kind(list) == rk::list as u32 { + this.unroll_reflection(node, variable, list, kind); + this.unbind_to(mark); + return; + } + # Reflection of a generic's type parameters waits for each instance. + if !this.waits_for_instance() { + this.unsupported(node); + } + this.undecided++; + } else if end != 0 { + element = this.range_type(iterated, end); + } else { + element = this.element_type(iterated, mutable); + } + + # `for x in` takes each element's value, copied out of where it is, which a + # pass only reads, and `for &x in` refers to it in place. An element given by + # value is the pass's own. + var copied := false; + if this.decide(variable != 0 ? variable : node, rf::valued, !reference && this.has_value(element)) { + element = this.types.first_of(this.unalias(element)); + copied = true; + if variable != 0 && this.closes(element) { + var text := string::from("`", nothing {}); + val named := this.describe(element); + text.append(named.view()); + text.append("` is closed where its scope ends, so each element has one owner, which still holds it: refer to each with `for &x in`."); + this.report_text(variable, ec::owned, &text); + } + } + + if index != 0 { + this.declare_local(index, this.name_of(index), bt::uint64); + } + if variable != 0 { + this.declare_local(variable, this.name_of(variable), element); + if !copied { + this.set_flag(variable, rf::mutable); + } + } + + # What the loop iterates is locked while its body runs. + val root := end == 0 ? this.root_ref(iterated) : 0; + if root != 0 { + this.locks.append(root); + } + this.at.loops++; + this.check_block(this.right_of(node)); + this.at.loops--; + if root != 0 { + this.locks.truncate(); + } + if unrolled { + this.undecided--; + } + this.unbind_to(mark); +} + +#! `for const x in args` over a pack: its body is checked once for each of the +#! pack's values, with `x` that value at its own type, each with a result table +#! of its own, so `if const x is Show` is decided for each. In a generic's own +#! body, where the pack's types are not known, the body is checked once, with +#! `x` of what the pack's bounds say of each. +#! @param this The checker. +#! @param node The `for_stmt` node. +#! @param variable The node of the loop's variable. +#! @param pack The pack's type. +def checker::unroll_pack(&mut this, node: u32, variable: u32, pack: u32): void { + val body := this.right_of(node); + if this.types.is_open_pack(pack) { + this.declare_local(variable, this.name_of(variable), this.types.param(this.types.first_of(pack))); + this.set_flag(variable, rf::mutable); + this.at.loops++; + this.check_block(body); + this.at.loops--; + return; + } + + val outer := this.at.table; + for i in 0..this.types.part_count(pack) { + val table := this.add_child_table(variable, body - variable + 1); + this.use_table(table); + val mark := this.scope_mark(); + this.declare_local(variable, this.name_of(variable), this.pack_value_type(pack, i as u32)); + this.set_flag(variable, rf::mutable); + this.at.loops++; + this.check_block(body); + this.at.loops--; + this.unbind_to(mark); + this.use_table(outer); + } +} + +#! The most passes `for const` unrolls a range to. +pub const checker::max_unrolled: u64 = 1024; + +#! `for const i in start..end` over a range whose ends are known while +#! checking: its body is checked once for each number, from the start to just +#! before the end, or through it for `start..=end`, or for each member of an +#! enum between them, with `i` a constant of the range's type, each with a +#! result table of its own, so `if const i == 0` is decided for each. Within a +#! generic's own body, where an end waits for each instance, the body is +#! checked once, with `i` a value of the type. +#! @param this The checker. +#! @param node The `for_stmt` node. +#! @param variable The node of the loop's variable. +#! @param start The node of the range's start. +#! @param end The node of its end. +def checker::unroll_range(&mut this, node: u32, variable: u32, start: u32, end: u32): void { + val body := this.right_of(node); + val kind := this.range_type(start, end); + val named := variable != 0 ? variable : node; + if this.node_has(node, nf::reference) || this.record(node, for_slot::index) != 0 { + this.report(named, ec::invalid, this.node_has(node, nf::reference) + ? "A range gives numbers, not references to them." + : "A range has no index apart from its numbers."); + return; + } + return if kind == bt::error; + + this.ev_failed = false; + val first_known := this.known_end(start); + val last_known := first_known && this.known_end(end); + if !first_known || !last_known { + if !this.waits_for_instance() && !this.ev_failed { + this.report(first_known ? end : start, ec::constant, + "`for const` counts through a range whose ends are known while checking: literals, constants, and what a function gives of them."); + } + this.undecided++; + if variable != 0 { + this.declare_local(variable, this.name_of(variable), kind); + } + this.at.loops++; + this.check_block(body); + this.at.loops--; + this.undecided--; + return; + } + + # How many numbers the range counts, from its start, or which members. + val first := this.value_at(start); + val last := this.value_at(end); + val inclusive := this.node_has(node, nf::inclusive); + val enumerated := this.named_kind(this.unalias(kind)) == dk::enum_type; + var members := vector::::new(); + var count: u64 = 0; + if enumerated { + members = this.members_between(kind, &first, &last, inclusive); + count = members.length; + } else if !first.negative && !last.negative { + count = last.magnitude > first.magnitude ? last.magnitude - first.magnitude : 0; + } else if first.negative && last.negative { + count = first.magnitude > last.magnitude ? first.magnitude - last.magnitude : 0; + } else if first.negative { + count = first.magnitude > checker::max_unrolled || last.magnitude > checker::max_unrolled + ? checker::max_unrolled + 1 + : first.magnitude + last.magnitude; + } + # `a..=b` counts `b` too, where it counts any. + if !enumerated && inclusive + && (count != 0 || (first.negative == last.negative && first.magnitude == last.magnitude)) { + count++; + } + if count > checker::max_unrolled { + this.report(named, ec::limit, "`for const` unrolls a range of at most 1024 numbers."); + return; + } + + val outer := this.at.table; + for k in 0..count { + var value := constant::integer(first.magnitude + k, false); + if enumerated { + value = members[k]; + } else if first.negative { + value = k >= first.magnitude + ? constant::integer(k - first.magnitude, false) + : constant::integer(first.magnitude - k, true); + } + val table := this.add_child_table(variable, body - variable + 1); + this.use_table(table); + val mark := this.scope_mark(); + this.declare_local(variable, this.name_of(variable), kind); + this.set_value(variable, value); + this.at.loops++; + this.check_block(body); + this.at.loops--; + this.unbind_to(mark); + this.use_table(outer); + } +} + +#! Whether an end of a range is known while checking, working it out by running +#! it where folding did not. +#! @param this The checker. +#! @param node The end's node. +#! @returns Whether it is known, with its value at the node. +def checker::known_end(&mut this, node: u32): bool { + return true if this.is_known(node); + return false if this.waits_for_instance() || this.type_at(node) == bt::error; + var made := ev {}; + return false if !this.evaluate(node, node, &mut made) || made.array; + this.set_value(node, made.scalar); + return true; +} + +#! The type a range counts in: the integer type or the enum its ends share. +#! @param this The checker. +#! @param start The node of the range's start. +#! @param end The node of its end. +#! @returns The type, or the error type where the ends share none. +def checker::range_type(&mut this, start: u32, end: u32): u32 { + val a := this.infer_expr(start); + val b := this.infer_expr(end); + return bt::error if a == bt::error || b == bt::error; + + val shared := this.common(this.read_type(a), this.read_type(b)); + if shared == bt::error || !this.counted(shared) { + this.report_operands(start, a, b, "are the ends of a range, which are integers of one type or members of one enum"); + return bt::error; + } + + val settled := this.settle(shared); + this.convert(start, settled); + this.convert(end, settled); + return settled; +} + +#! Whether a range counts in a type: an integer type, an enum, whose members +#! it counts through in the order of their values, or a type parameter bounded +#! by `integer` or `ordinal`. +#! @param this The checker. +#! @param kind The type. +#! @returns Whether it does. +def checker::counted(&mut this, kind: u32): bool { + val plain := this.unalias(kind); + return true if this.types.is_integer(plain) || this.named_kind(plain) == dk::enum_type; + val integer := this.std_decl(word::integer); + val ordinal := this.std_decl(word::ordinal); + return (integer != 0 && this.param_bounded(plain, integer)) || (ordinal != 0 && this.param_bounded(plain, ordinal)); +} + +#! The values of the members of an enum a range counts through, in order: from +#! its start up to its end, or through it where the range is `a..=b`. +#! @param this The checker. +#! @param kind The enum's type. +#! @param first The start's value. +#! @param last The end's value. +#! @param inclusive Whether the end is counted too. +#! @returns The values. +pub def checker::members_between(&mut this, kind: u32, first: &constant, last: &constant, inclusive: bool): vector { + val flip := this.member_flip(kind); + val from := first.bits() ^ flip; + val to := last.bits() ^ flip; + val order := this.member_order(kind); + var made := vector::::new(); + for each in order { + if each >= from && (each < to || (inclusive && each == to)) { + made.append(constant::from_bits(each ^ flip, flip != 0)); + } + } + return made; +} + +#! `a..b`, or `a..=b`, as a value: std's `range` of the integers or the +#! members of the enum its ends are. A range expected gives its ends its type, +#! as `val r: range = 0..9;`. +#! @param this The checker. +#! @param node The `range` node. +#! @param expected The type expected, or the error type. +#! @returns The range's type, or the error type. +def checker::range_value(&mut this, node: u32, expected: u32): u32 { + val decl := this.std_decl(word::range); + val start := this.left_of(node); + val end := this.right_of(node); + if decl == 0 { + this.infer_expr(start); + this.infer_expr(end); + this.report(node, ec::undefined, "A range is std's `range`, which is not declared here."); + return bt::error; + } + + var element: u32 = bt::error; + val wanted := this.unalias(expected); + if expected != bt::error && this.types.kind_of(wanted) == ty::named && this.types.first_of(wanted) == decl + && this.types.part_count(wanted) == 1 && this.counted(this.types.part_at(wanted, 0)) { + element = this.types.part_at(wanted, 0); + this.check_expr(start, element); + this.check_expr(end, element); + } else { + element = this.range_type(start, end); + } + return bt::error if element == bt::error; + val args: u32[1] = [element]; + return this.types.named(decl, args[0:1]); +} + +#! The type of each element a loop over the value gives. A loop variable takes +#! what it is given: a reference to each element an array holds or an iterator +#! gives by reference, writing it with `&mut`, and each one an iterator gives by +#! value, which is then the loop's own. +#! @param this The checker. +#! @param node The node of what the loop walks. +#! @param mutable Whether the loop writes its elements, as `for &mut x` does. +#! @returns The element's type, or the error type where the value cannot be +#! walked. +def checker::element_type(&mut this, node: u32, mutable: bool): u32 { + var kind := this.infer_expr(node); + return bt::error if kind == bt::error; + # A literal of text is walked as the `strview` it settles as. + if this.types.kind_of(kind) == ty::untyped_text { + kind = this.settle_expr(node); + } + + val through := this.reached(kind); + val plain := this.unalias(through); + if this.types.kind_of(plain) == ty::fixed { + val element := this.types.first_of(plain); + if mutable && !this.reaches_writable(kind, node) { + this.report(node, ec::assignable, "`for &mut` changes the elements in place, so the array must be writable."); + } + return this.types.reference(element, mutable); + } + + # What lends an iterator is walked by it, and an iterator is walked itself. + var cursor := through; + if !this.has_method(through, word::next) { + val lends := this.pick_iter(through, mutable); + if lends == 0 { + var text := string::from("`", nothing {}); + val named := this.describe(kind); + text.append(named.view()); + text.append("` is not iterated: a type is by lending an iterator through `iter`, or being one."); + this.report_text(node, ec::member, &text); + return bt::error; + } + cursor = this.types.first_of(this.method_type(lends, through)); + } + + val next := this.find_member(cursor, word::next); + return bt::error if next.decl == 0; + val given := this.types.first_of(this.method_type(next.decl, cursor)); + val plain_given := this.unalias(given); + if this.named_kind(plain_given) != dk::union_type || this.types.part_count(plain_given) == 0 { + return bt::error; + } + + # `next` gives each element in a `maybe`, as a reference where it is one. + val each := this.types.part_at(plain_given, 0); + if this.types.kind_of(each) == ty::reference { + return mutable ? each : this.types.reference(this.types.first_of(each), false); + } + return each; +} + +#! The `iter` of a type lending its iterator: the one taking `&mut this` for +#! `for &mut`, or the one taking `&this`, or 0. +#! @param this The checker. +#! @param kind The type walked. +#! @param mutable Whether the loop writes its elements. +#! @returns The method's declaration, or 0. +pub def checker::pick_iter(&mut this, kind: u32, mutable: bool): u32 { + val found := this.find_member(kind, word::iter); + return 0 if found.decl == 0 || this.decls.kinds.p[found.decl] != dk::function; + + var reads: u32 = 0; + var walk := this.decls.walk_overloads(found.decl); + while true { + val at := walk.next(); + break if at == 0; + continue if !this.member_seen(at); + if this.decls.has(at, df::mut_this) == mutable { + return at; + } + if !this.decls.has(at, df::mut_this) && reads == 0 { + reads = at; + } + } + return mutable ? 0 : reads; +} + +#! `return`, whose value converts to the function's result. +#! @param this The checker. +#! @param node The `return_stmt` node. +def checker::check_return(&mut this, node: u32): void { + val value := this.left_of(node); + val result := this.at.result; + # `return;` gives `void`, which converts to what the function gives where a + # `result` or `maybe` holds it. + if value == 0 { + val none := constant {}; + if result != bt::void_type && result != bt::error && this.fits(bt::void_type, result, &none, false, 0) == fit::none { + this.report(node, ec::mismatch, "The function returns a value, which `return` gives."); + } + return; + } + + # What gives nothing may be returned from a function giving nothing, as generic + # code returning what a call gives writes it. + if result == bt::void_type { + val given := this.read_type(this.infer_expr(value)); + if given != bt::void_type && given != bt::error { + this.report(value, ec::mismatch, "The function returns nothing, so `return` gives no value."); + } + return; + } + this.check_expr(value, result); + + # Returning a local hands it to the caller rather than copying it, and so does + # returning what a pointer points at, which only the program closes. What a local + # reference refers to is still copied. + val local := this.kind_of(value) == nk::name && (this.ref_at(value) & ref_local) != 0 + && this.types.kind_of(this.type_at(value)) != ty::reference; + val handed := local || (this.is_place(value) && this.pointed_at(value)); + if !handed { + this.check_owned(value, result); + } +} + +#! `value else fallback`: what a `result` or a `maybe` holds, or else what +#! stands in for it, a value or a block that leaves. +#! @param this The checker. +#! @param node The `fallback` node. +#! @param expected The type expected of its value, or the error type where +#! none is. +#! @returns The type held, or the error type where the value is neither a +#! `result` nor a `maybe`. +def checker::fallback(&mut this, node: u32, expected: u32): u32 { + val value := this.left_of(node); + val error := this.record(node, fallback_slot::error); + val other := this.record(node, fallback_slot::other); + val kind := this.infer_expr(value); + if kind == bt::error { + if other != 0 && this.kind_of(other) != nk::block { this.infer_expr(other); } + return bt::error; + } + + val plain := this.unalias(this.read_type(kind)); + var held: u32 = bt::error; + var fault: u32 = 0; + if this.is_std(plain, word::maybe) { + held = this.types.part_at(plain, 0); + } else if this.is_std(plain, word::result) { + held = this.types.part_at(plain, 0); + fault = this.types.part_at(plain, 1); + } else { + this.report_operand(node, kind, "`else` takes what a `result` or a `maybe` holds."); + return bt::error; + } + + # A value that closes has one owner. A variable keeps what it holds, so taking + # a copy out of it would close it twice, where a value a call made is handed + # over, and the result owns the error it holds. + if this.is_place(value) && this.closes(held) { + var text := string::from("`", nothing {}); + val named := this.describe(held); + text.append(named.view()); + text.append("` is closed where its scope ends, so the variable tested owns it; name it in place with `if x is not value(&v) { ... }` instead."); + this.report_text(value, ec::owned, &text); + } + if error != 0 && fault != 0 && this.name_of(error) != names::underscore_id && this.closes(fault) { + var text := string::from("`", nothing {}); + val named := this.describe(fault); + text.append(named.view()); + text.append("` is closed where its scope ends, so the result owns the error; leave it unnamed, with `else (_)`, or test the result with `is` or `match`."); + this.report_text(error, ec::owned, &text); + } + + if this.kind_of(other) == nk::block { + val mark := this.scope_mark(); + if error != 0 { + if fault == 0 { + this.report(error, ec::invalid, "A `maybe` holds no error, so `else` names none."); + } + this.declare_local(error, this.name_of(error), fault == 0 ? bt::error : fault); + } + # A block stands in for `void` by ending, since it gives nothing. + if this.check_block(other) == flow::goes_on && this.unalias(held) != bt::void_type { + this.report(other, ec::control, "The block standing in for the value leaves, by `return`, `break`, or `continue`."); + } + this.unbind_to(mark); + return held; + } + + this.check_expr(other, held); + this.check_owned(other, held); + return held; +} + +#! A `match` statement. +#! @param this The checker. +#! @param node The `match_stmt` node. +#! @returns How it ends: `leaves` where it handles every case and every arm +#! leaves. +def checker::check_match_stmt(&mut this, node: u32): flow { + var made := checker::matched { shared = bt::error, every = true, all_leave = true }; + this.check_match(node, false, bt::error, &mut made); + return made.every && made.all_leave ? flow::leaves : flow::goes_on; +} + +#! A `match` used as a value, whose arms share a type, or take the type +#! expected. +#! @param this The checker. +#! @param node The `match_value` node. +#! @param expected The type expected of its value, or the error type where +#! none is. +#! @returns The type its arms share, or the error type. +def checker::match_value(&mut this, node: u32, expected: u32): u32 { + var made := checker::matched { shared = 0, every = true, all_leave = true }; + this.check_match(node, true, expected, &mut made); + if !made.every { + this.report(node, ec::arms, "A match used as a value handles every case, or ends with `else`."); + } + return expected != bt::error ? expected : (made.shared == 0 ? bt::error : this.settle(made.shared)); +} + +#! What checking a match finds. +pub struct checker::matched { + var shared: u32; #! The type its arms' values share. + var every: bool; #! Whether it handles every case. + var all_leave: bool; #! Whether every arm leaves. +} + +#! Checks a match: on a union, its arms name fields; on an enum, members; and +#! on anything else, values compared with the subject. +#! @param this The checker. +#! @param node The match's node. +#! @param value Whether it is used as a value, whose arms are expressions. +#! @param expected The type expected of its value, or the error type where +#! none is. +#! @param made Where what checking finds is written. +def checker::check_match(&mut this, node: u32, value: bool, expected: u32, made: &mut checker::matched): void { + val subject := this.left_of(node); + val arms := this.right_of(node); + val kind := this.infer_expr(subject); + val plain := this.unalias(this.read_type(kind)); + val union_like := this.named_kind(plain) == dk::union_type; + val enum_like := this.named_kind(plain) == dk::enum_type; + if union_like && this.decls.has(this.types.first_of(plain), df::foreign) { + this.report(subject, ec::invalid, c_union_untagged); + } + + var handled := vector::::new(); + var has_else := false; + for &arm in this.run_view(arms) { + val patterns := this.left_of(arm); + val body := this.right_of(arm); + val mark := this.scope_mark(); + if patterns == 0 { + has_else = true; + } + + for &pattern in this.run_view(patterns) { + if kind == bt::error { + continue; + } + if union_like { + this.union_pattern(pattern, plain, subject, &mut handled); + } else if enum_like { + this.enum_pattern(pattern, plain, &mut handled); + } else { + this.check_expr(pattern, this.read_type(kind)); + this.check_compared(pattern, tk::equals, this.read_type(kind)); + } + } + + if value { + if expected != bt::error { + this.check_expr(body, expected); + if !this.gives_binding(arm) { + this.check_owned(body, expected); + } + } else { + val given := this.infer_expr(body); + if made.shared == 0 { + made.shared = given; + } else if made.shared != bt::error && given != bt::error { + val joined := this.common(made.shared, given); + if joined == bt::error { + this.report_operands(body, made.shared, given, "are the values of arms of one match, which share no type"); + } + made.shared = joined; + } + } + } else if this.check_block(body) == flow::goes_on { + made.all_leave = false; + } + this.unbind_to(mark); + } + + if value && expected == bt::error && made.shared != 0 && made.shared != bt::error { + for &arm in this.run_view(arms) { + this.convert(this.right_of(arm), this.settle(made.shared)); + if !this.gives_binding(arm) { + this.check_owned(this.right_of(arm), this.settle(made.shared)); + } + } + } + + # A match on a union or an enum handles each case, or ends with `else`. + made.every = has_else || kind == bt::error; + if !has_else && (union_like || enum_like) { + val decl := this.types.first_of(plain); + val run: u32 = this.decls.children.p[decl]; + var count := 0u; + for &member in this.decls.list_view(run) { + continue if union_like && this.decls.kinds.p[member] != dk::field; + # A member given an earlier one's value is another name for it. + continue if enum_like && this.enum_canonical(decl, member) != member; + count++; + } + var distinct := 0u; + for i in 0..handled.length { + var seen := false; + for j in 0..i { + seen = seen || handled[j] == handled[i]; + } + if !seen { distinct++; } + } + made.every = distinct >= count; + if !made.every && !value { + this.report(node, ec::arms, "The match does not handle every case; handle each, or end with `else`."); + } + } +} + +#! Whether an arm's value is the value its pattern names, as `some(v) => v`, +#! which the arm hands over as it ends rather than copying it. +#! @param this The checker. +#! @param arm The arm's node. +#! @returns Whether it is. +def checker::gives_binding(&this, arm: u32): bool { + val body := this.right_of(arm); + val patterns := this.left_of(arm); + return false if this.kind_of(body) != nk::name || (this.ref_at(body) & ref_local) == 0; + return false if patterns == 0 || this.run_length(patterns) != 1; + val pattern := this.run_at(patterns, 0); + return false if this.kind_of(pattern) != nk::call || this.run_length(this.right_of(pattern)) != 1; + return this.run_at(this.right_of(pattern), 0) == (this.ref_at(body) & ref_mask); +} + +#! An arm's pattern on a union: the field it names, as `data` or `data(text)`. +#! @param this The checker. +#! @param pattern The pattern's node. +#! @param kind The union's type. +#! @param subject The node of the value matched. +#! @param handled The fields the arms handle so far, which the field is added +#! to. +def checker::union_pattern(&mut this, pattern: u32, kind: u32, subject: u32, handled: &mut vector): void { + var name_node := pattern; + var binding: u32 = 0; + if this.kind_of(pattern) == nk::call { + name_node = this.left_of(pattern); + val run := this.right_of(pattern); + if this.run_length(run) == 1 { + binding = this.run_at(run, 0); + } + } + + val decl := this.types.first_of(kind); + val field := this.kind_of(name_node) == nk::name ? this.decls.member(decl, this.name_of(name_node)) : 0; + if field == 0 || this.decls.kinds.p[field] != dk::field { + this.report(pattern, ec::arms, "An arm on a union names one of its fields."); + return; + } + + handled.append(field); + this.set_ref(pattern, field); + this.check_reaches(name_node, kind, field); + if binding != 0 { + this.resolve(field); + val held := this.instantiated(this.decls.types.p[field], decl, kind); + this.declare_binding(binding, held, subject); + val named := this.kind_of(binding) == nk::reference ? this.left_of(binding) : binding; + this.bind(this.name_of(named), ref_local | named); + } +} + +#! An arm's pattern on an enum: a member, named with or without its enum. +#! @param this The checker. +#! @param pattern The pattern's node. +#! @param kind The enum's type. +#! @param handled The members the arms handle so far, which the member is +#! added to. +def checker::enum_pattern(&mut this, pattern: u32, kind: u32, handled: &mut vector): void { + val decl := this.types.first_of(kind); + if this.kind_of(pattern) == nk::name { + val member := this.decls.member(decl, this.name_of(pattern)); + if member != 0 && this.decls.kinds.p[member] == dk::enum_member { + this.resolve(member); + handled.append(this.enum_canonical(decl, member)); + this.set_ref(pattern, member); + this.set_type(pattern, kind); + return; + } + } + + this.check_expr(pattern, kind); + val ref := this.ref_at(pattern); + if ref != 0 && (ref & (ref_local | ref_type)) == 0 && this.decls.kinds.p[ref] == dk::enum_member { + handled.append(this.enum_canonical(decl, ref)); + } +} + +#! The first member of an enum of the same value as the member, which a member +#! given an earlier one's value is another name for. +#! @param this The checker. +#! @param decl The enum's declaration. +#! @param member The member's declaration. +#! @returns The first member of its value. +def checker::enum_canonical(&mut this, decl: u32, member: u32): u32 { + var value := constant {}; + return member if !this.decl_value(member, &mut value); + + val run: u32 = this.decls.children.p[decl]; + for &each in this.decls.list_view(run) { + var other := constant {}; + if this.decl_value(each, &mut other) && this.compare_constants(&value, &other) == 0 { + return each; + } + } + return member; +} diff --git a/analyzer/checker/traits.sakura b/analyzer/checker/traits.sakura new file mode 100644 index 00000000..6ddde7fb --- /dev/null +++ b/analyzer/checker/traits.sakura @@ -0,0 +1,895 @@ +#! @file traits.sakura +#! @author John Christman (sorakatadzuma@gmail.com) +#! @copyright Malunal Studios, LLC. +#! @license MIT +#! +#! Contains traits: what a trait asks for, and whether a type satisfies it. A +#! type satisfies a trait by its shape, having each method the trait asks for +#! with the signature it asks, where `self` is the type, whether or not the +#! type names the trait. A type parameter satisfies what its bounds do. What +#! was worked out of a type and a trait is kept, so it is worked out once. + +module sakura::analyzer; + + +#! Resolves the traits a declaration names after its name: those a struct or +#! union implements, or a trait composes. +#! @param this The checker. +#! @param id The declaration. +pub def checker::resolve_composed(&mut this, id: u32): void { + return if this.composed.at_or_zero(id) != 0; + this.composed.put(id, 1); + + val kind: dk = this.decls.kinds.p[id]; + return if kind != dk::struct_type && kind != dk::union_type && kind != dk::trait_type; + + val saved := this.at; + this.enter_decl(id, 0); + var traits := vector::::new(); + val run := this.record(this.decls.nodes.p[id], aggregate_slot::traits); + for &written in this.run_view(run) { + val made := this.resolve_type(written); + if made != bt::error && this.named_kind(made) != dk::trait_type { + this.report(written, ec::not_type, kind == dk::trait_type + ? "A trait composes traits." + : "A struct or union names the traits it implements."); + continue; + } + if made != bt::error { + traits.append(made); + } + } + this.leave(saved); + this.composed.put(id, this.decls.make_list(traits.view()) + 1); +} + +#! The traits a declaration names after its name, resolved. +#! @param this The checker. +#! @param id The declaration. +#! @returns The run of the traits' types, in `lists`. +pub def checker::composed_of(&mut this, id: u32): u32 { + this.resolve_composed(id); + return this.composed.at_or_zero(id) - 1; +} + +#! Whether a value of the type satisfies the trait, given its arguments. +#! @param this The checker. +#! @param kind The type. +#! @param trait_kind The trait's type, given its arguments. +#! @returns Whether it does. +pub def checker::satisfies(&mut this, kind: u32, trait_kind: u32): bool { + return true if kind == bt::error || trait_kind == bt::error; + + # What a type parameter satisfies changes as `if const` proves bounds of it, + # so only what holds no parameter is kept. + if this.types.is_open(kind) { + return this.works_out(kind, trait_kind); + } + + val key := pair_key(kind, trait_kind); + if this.satisfied.get(&key) is some(got) { + return got != 0; + } + + # A type asked of again while it is being worked out satisfies the trait so + # far, which lets a trait ask for methods taking the trait itself. + this.satisfied.set(key, 1); + val holds := this.works_out(kind, trait_kind); + this.satisfied.set(key, holds ? 1 : 0); + return holds; +} + +def checker::works_out(&mut this, kind: u32, trait_kind: u32): bool { + val holder := this.types.first_of(trait_kind); + val name: u32 = this.decls.names.p[holder]; + val is_std := this.std_decl(name) == holder; + val plain := this.unalias(kind); + + # The bounds the compiler decides. + if is_std && name == word::integer { + return this.types.is_integer(plain) && !this.types.is_untyped(plain) || this.param_bounded(plain, holder); + } + if is_std && name == word::real { + return this.types.is_float(plain) && !this.types.is_untyped(plain) || this.param_bounded(plain, holder); + } + # Every integer is ordinal, so a type parameter bounded by `integer` is too. + if is_std && name == word::ordinal { + val integer := this.std_decl(word::integer); + return (this.types.is_integer(plain) && !this.types.is_untyped(plain)) || this.named_kind(plain) == dk::enum_type + || this.param_bounded(plain, holder) || (integer != 0 && this.param_bounded(plain, integer)); + } + if is_std && name == word::pointer { + return this.types.kind_of(plain) == ty::pointer || this.param_bounded(plain, holder); + } + # A function type, a variadic one too, and the address of a C function are + # signatures, and nothing else is. + if is_std && name == word::signature { + return this.signature_function(plain) != 0 || this.param_bounded(plain, holder); + } + + # A type is `closeable` where its values close, and a type parameter where its + # bounds say so, or say it is `owning`. + if is_std && name == word::closeable { + if this.types.kind_of(plain) == ty::param || this.types.kind_of(plain) == ty::pack { + val owning := this.std_decl(word::owning); + return this.param_bounded(plain, holder) || (owning != 0 && this.param_bounded(plain, owning)); + } + return this.closes(plain); + } + + # A type is `zeroable` where it has a zero value, and a type parameter where + # its bounds say so. + if is_std && name == word::zeroable { + return this.has_zero(plain, 0); + } + + # A type is `lockfree` where it is a word or less that every processor reads and + # writes whole without a lock: an integer, `bool`, enum, or pointer. + if is_std && name == word::lockfree { + val of := this.types.kind_of(plain); + return (this.types.is_integer(plain) && !this.types.is_untyped(plain)) || plain == bt::boolean + || this.named_kind(plain) == dk::enum_type || of == ty::pointer || this.param_bounded(plain, holder); + } + + # A type parameter satisfies what one of its bounds is, or composes. + if this.types.kind_of(plain) == ty::param || this.types.kind_of(plain) == ty::pack { + return this.param_bounded(plain, holder); + } + + # A reference satisfies what its referent does, where the trait asks only for what + # can be called through it. + if this.types.kind_of(plain) == ty::reference && this.lends(plain, trait_kind, holder) { + return true; + } + + # A trait reference satisfies the trait it is, and those it composes. + if this.named_kind(plain) == dk::trait_type && this.composes(plain, holder, 0) { + return true; + } + + # A type is `owning` only by naming it, so a `close` meant to be called by hand + # never makes its values closed by accident. + if is_std && name == word::owning && !this.names_trait(plain, holder) { + return false; + } + + # Only a struct naming it implements `attribute`. + if is_std && name == word::attribute { + return this.names_trait(plain, holder); + } + + return this.has_requirements(kind, trait_kind, holder, 0); +} + +#! Whether a reference satisfies a trait through what it refers to, as `&mut +#! file` satisfies what `file` does, so a generic can be given either. Its +#! methods are its referent's, called through it, so the trait asks only for +#! methods taking `this`, and only for ones taking `&this` where it only reads. +#! It is compared, ordered, and hashed as what it refers to, so it takes a trait +#! naming `self` where `self` is only taken by reference, but none giving or +#! taking a `self` by value, since what is made from the referent is no +#! reference. It owns nothing, so it is never `owning`. A pointer is an address, +#! and takes nothing from what it points at. +#! @param this The checker. +#! @param kind The reference's type. +#! @param trait_kind The trait's type, given its arguments. +#! @param holder The trait's declaration. +#! @returns Whether it does. +def checker::lends(&mut this, kind: u32, trait_kind: u32, holder: u32): bool { + return false if this.about_values(holder); + return false if this.unreached(holder, this.types.second_of(kind) == 1, 0) != 0; + return this.satisfies(this.types.first_of(kind), trait_kind); +} + +# Whether a trait of std is one the compiler gives a meaning, which says what a value +# itself is. +def checker::about_values(&mut this, holder: u32): bool { + val name: u32 = this.decls.names.p[holder]; + return this.std_decl(name) == holder + && (name == word::owning || name == word::attribute + || name == word::integer || name == word::ordinal || name == word::real || name == word::closeable + || name == word::zeroable || name == word::pointer + || name == word::lockfree); +} + +# The first member a trait, or a trait it composes, asks for that a reference cannot +# reach through it: one not taking `this`, taking `&mut this` where it only reads, or +# not reading through to `self`. A type it asks for is the referent's, an `@optional` +# method taking `&mut this` is only not there to call through a reference that reads, +# and a default compiled for each type is the reference's own, as it is any type's. +# Gives 0 where there is none. +def checker::unreached(&mut this, holder: u32, writes: bool, depth: u32): u32 { + return holder if depth > 16; + + val self_kind := this.types.param(this.self_decl(holder)); + val run: u32 = this.decls.children.p[holder]; + for i in 0..this.decls.list_length(run) { + val member := this.decls.list_at(run, i as u32); + this.resolve(member); + val kind: dk = this.decls.kinds.p[member]; + if (kind == dk::property && writes) || kind == dk::assoc_type { + continue; + } + if kind == dk::function && !writes && this.decls.has(member, df::mut_this) && this.decls.has(member, df::optional) { + continue; + } + if kind == dk::function && this.typed_default(member) { + continue; + } + return member if kind != dk::function || !this.decls.has(member, df::method); + return member if !writes && this.decls.has(member, df::mut_this); + return member if !this.reads_through(member, self_kind); + } + + val composed := this.composed_of(holder); + for i in 0..this.decls.list_length(composed) { + val inner := this.unreached(this.types.first_of(this.decls.list_at(composed, i as u32)), writes, depth + 1); + return inner if inner != 0; + } + return 0; +} + +# Whether a method of a trait is called through a reference to what implements it as +# it is on what that refers to: `self` is taken only by reference, which a reference +# to the reference reads through to, and is never given, since what is made from the +# referent is no reference. +def checker::reads_through(&mut this, method: u32, self_kind: u32): bool { + val kind: u32 = this.decls.types.p[method]; + return false if this.mentions(this.types.first_of(kind), self_kind, 0); + for p in 1..this.types.part_count(kind) { + val taken := this.types.part_at(kind, p as u32); + continue if !this.mentions(taken, self_kind, 0); + return false if this.types.kind_of(taken) != ty::reference || this.types.first_of(taken) != self_kind; + } + return true; +} + +#! Why a reference or a pointer does not satisfy a trait that what it refers to +#! does, or empty text where its referent does not either. +#! @param this The checker. +#! @param kind The reference's or pointer's type. +#! @param trait_kind The trait's type. +#! @returns Why, as a note's detail, or empty text. +def checker::unlent(&mut this, kind: u32, trait_kind: u32): string { + val plain := this.unalias(kind); + val held := this.types.kind_of(plain); + val holder := this.types.first_of(trait_kind); + var why := string::new(nothing {}); + return move(why) if held != ty::reference && held != ty::pointer; + return move(why) if !this.satisfies(this.types.first_of(plain), trait_kind); + + val name: u32 = this.decls.names.p[holder]; + if held == ty::pointer { + why.append("a pointer is an address, so what it points at is reached through `*p`"); + return move(why); + } + if this.std_decl(name) == holder && name == word::owning { + why.append("it owns nothing it refers to, though `close` can be called through it"); + return move(why); + } + if this.about_values(holder) { + why.append("the trait says what a value itself is, not what it refers to"); + return move(why); + } + + val writes := this.types.second_of(plain) == 1; + val member := this.unreached(holder, writes, 0); + return move(why) if member == 0; + val self_kind := this.types.param(this.self_decl(this.decls.owners.p[member])); + why.append("`"); + why.append(this.decl_text(member)); + if this.decls.kinds.p[member] != dk::function || !this.decls.has(member, df::method) { + why.append("` takes no `this`, so it is not reached through a reference"); + } else if !writes && this.decls.has(member, df::mut_this) { + why.append("` takes `&mut this`, and the reference only reads"); + } else if this.mentions(this.types.first_of(this.decls.types.p[member]), self_kind, 0) { + why.append("` gives `self`, and what it makes is not a reference"); + } else { + why.append("` takes `self` by value, and a reference reaches only what takes it by reference"); + } + return move(why); +} + +#! Whether a type parameter's bounds include the trait, or a trait composing it. +#! @param this The checker. +#! @param kind The type parameter's type. +#! @param holder The trait's declaration. +#! @returns Whether they do. +def checker::param_bounded(&mut this, kind: u32, holder: u32): bool { + return false if this.types.kind_of(kind) != ty::param && this.types.kind_of(kind) != ty::pack; + + val param := this.types.first_of(kind); + return false if param == 0; + if this.decls.names.p[param] == names::self_id + && (this.decls.owners.p[param] == holder || this.composes(this.decls.types.p[this.decls.owners.p[param]], holder, 0)) { + return true; + } + + return this.bounded_by(param, holder, 0, 0); +} + +#! Whether a type parameter is bounded by any of up to three traits, through a +#! bound it declares, or one an `if const` proved of it in the branch it guards. +#! @param this The checker. +#! @param param The parameter's declaration. +#! @param first A trait's declaration, or 0. +#! @param second Another, or 0. +#! @param third Another, or 0. +#! @returns Whether it is. +def checker::bounded_by(&mut this, param: u32, first: u32, second: u32, third: u32): bool { + return false if first == 0 && second == 0 && third == 0; + this.resolve(param); + val run: u32 = this.decls.children.p[param]; + for i in 0..this.decls.list_length(run) { + return true if this.composes_any(this.decls.list_at(run, i as u32), first, second, third); + } + for i in 0..this.proved_params.length { + return true if this.proved_params[i] == param && this.composes_any(this.proved_bounds[i], first, second, third); + } + return false; +} + +#! Whether a bound composes any of up to three traits. +#! @param this The checker. +#! @param bound The bound. +#! @param first A trait's declaration, or 0. +#! @param second Another, or 0. +#! @param third Another, or 0. +#! @returns Whether it does. +def checker::composes_any(&mut this, bound: u32, first: u32, second: u32, third: u32): bool { + return (first != 0 && this.composes(bound, first, 0)) || (second != 0 && this.composes(bound, second, 0)) + || (third != 0 && this.composes(bound, third, 0)); +} + +#! Whether the trait type is the trait, or composes it. +#! @param this The checker. +#! @param trait_kind The trait type asked about. +#! @param holder The declaration of the trait looked for. +#! @param depth How deeply composition has been followed, which stops one +#! composing itself without end. +#! @returns Whether it is, or does. +pub def checker::composes(&mut this, trait_kind: u32, holder: u32, depth: u32): bool { + return false if depth > 16 || this.types.kind_of(trait_kind) != ty::named; + + val decl := this.types.first_of(trait_kind); + return true if decl == holder; + val run := this.composed_of(decl); + for i in 0..this.decls.list_length(run) { + return true if this.composes(this.decls.list_at(run, i as u32), holder, depth + 1); + } + return false; +} + +#! Whether a struct or union names the trait after its name. +#! @param this The checker. +#! @param kind The struct's or union's type. +#! @param holder The trait's declaration. +#! @returns Whether it does. +def checker::names_trait(&mut this, kind: u32, holder: u32): bool { + return false if this.types.kind_of(kind) != ty::named; + + val run := this.composed_of(this.types.first_of(kind)); + for i in 0..this.decls.list_length(run) { + return true if this.composes(this.decls.list_at(run, i as u32), holder, 0); + } + return false; +} + +#! Whether the type has what the trait asks for, and what each trait it +#! composes asks for. +#! @param this The checker. +#! @param kind The type. +#! @param trait_kind The trait's type, given its arguments. +#! @param holder The trait's declaration. +#! @param depth How deeply composition has been followed. +#! @returns Whether it has. +def checker::has_requirements(&mut this, kind: u32, trait_kind: u32, holder: u32, depth: u32): bool { + return false if depth > 16; + + val run: u32 = this.decls.children.p[holder]; + for i in 0..this.decls.list_length(run) { + val wanted := this.decls.list_at(run, i as u32); + continue if this.decls.has(wanted, df::optional); + # A method the trait writes a body for is its default, which the type may leave out. + continue if this.decls.kinds.p[wanted] == dk::function && this.has_body(wanted); + return false if !this.meets(kind, trait_kind, wanted); + } + + val composed := this.composed_of(holder); + for i in 0..this.decls.list_length(composed) { + val inner := this.decls.list_at(composed, i as u32); + val given := this.trait_in_terms(inner, holder, trait_kind, kind); + return false if !this.satisfies(kind, given); + } + return true; +} + +#! A type a trait names, given the trait's arguments, `self`, and each type it +#! asks for as what implements it gives. +#! @param this The checker. +#! @param inner The type the trait names. +#! @param holder The trait's declaration. +#! @param trait_kind The trait's type, given its arguments. +#! @param self_kind The type standing for `self`. +#! @returns The type in those terms. +def checker::trait_in_terms(&mut this, inner: u32, holder: u32, trait_kind: u32, self_kind: u32): u32 { + return inner if !this.types.is_open(inner); + + var from := vector::::new(); + var to := vector::::new(); + from.append(this.self_decl(holder)); + to.append(self_kind); + val params: u32 = this.decls.params.p[holder]; + for i in 0..this.decls.list_length(params) { + from.append(this.decls.list_at(params, i as u32)); + to.append(i < this.types.part_count(trait_kind) ? this.types.part_at(trait_kind, i as u32) : bt::error); + } + + val asked: u32 = this.decls.children.p[holder]; + for i in 0..this.decls.list_length(asked) { + val member := this.decls.list_at(asked, i as u32); + continue if this.decls.kinds.p[member] != dk::assoc_type; + from.append(member); + to.append(this.asked_type(self_kind, member, trait_kind)); + } + return this.substitute(inner, from.view(), to.view()); +} + +#! The type a type gives for one a trait asks for: its own of the name, or the +#! trait's default, or for a type parameter, the parameter standing for it. A +#! trait of `core`'s is given what `core` declares through its own types. +#! @param this The checker. +#! @param self_kind The type implementing the trait. +#! @param asked The declaration of the type the trait asks for. +#! @param trait_kind The trait's type, given its arguments. +#! @returns The type, or the error type where it gives none. +def checker::asked_type(&mut this, self_kind: u32, asked: u32, trait_kind: u32): u32 { + val cores := this.in_core(this.decls.modules.p[this.decls.owners.p[asked]]); + if cores { this.cores_own++; } + val made := this.asked_one(self_kind, asked, trait_kind); + if cores { this.cores_own--; } + return made; +} + +#! The type a type gives for one a trait asks for, as `asked_type` says. +#! @param this The checker. +#! @param self_kind The type implementing the trait. +#! @param asked The declaration of the type the trait asks for. +#! @param trait_kind The trait's type, given its arguments. +#! @returns The type, or the error type where it gives none. +def checker::asked_one(&mut this, self_kind: u32, asked: u32, trait_kind: u32): u32 { + val plain := this.unalias(self_kind); + if this.types.kind_of(plain) == ty::param || self_kind == bt::error { + return self_kind == bt::error ? bt::error : this.projected(plain, asked, trait_kind); + } + val part := this.signature_part(plain, asked); + return part if part != 0; + + # A reference gives the types what it refers to gives. + val found := this.find_path_member(this.reached(self_kind), this.decls.names.p[asked]); + if found.decl != 0 && this.is_type_decl(found.decl) && found.decl != asked { + this.resolve(found.decl); + return this.instantiated(this.decls.types.p[found.decl], found.decl, found.owner); + } + + this.resolve(asked); + val fallback: u32 = this.decls.targets.p[asked]; + return bt::error if fallback == 0; + + val holder: u32 = this.decls.owners.p[asked]; + var from := vector::::new(); + var to := vector::::new(); + from.append(this.self_decl(holder)); + to.append(self_kind); + return this.substitute(fallback, from.view(), to.view()); +} + +#! Whether the type meets one thing a trait asks for: a method of its name and +#! signature, a property, or a type. A trait of `core`'s is met by what `core` +#! gives its own types, whatever a program declares through them beside it. +#! @param this The checker. +#! @param kind The type. +#! @param trait_kind The trait's type, given its arguments. +#! @param wanted The declaration of what the trait asks for. +#! @returns Whether it does. +def checker::meets(&mut this, kind: u32, trait_kind: u32, wanted: u32): bool { + val cores := this.in_core(this.decls.modules.p[this.decls.owners.p[wanted]]); + if cores { this.cores_own++; } + val made := this.meets_one(kind, trait_kind, wanted); + if cores { this.cores_own--; } + return made; +} + +#! Whether the type meets one thing a trait asks for, as `meets` says. +#! @param this The checker. +#! @param kind The type. +#! @param trait_kind The trait's type, given its arguments. +#! @param wanted The declaration of what the trait asks for. +#! @returns Whether it does. +def checker::meets_one(&mut this, kind: u32, trait_kind: u32, wanted: u32): bool { + val name: u32 = this.decls.names.p[wanted]; + match this.decls.kinds.p[wanted] { + dk::function => { + this.resolve(wanted); + val signature := this.requirement_type(wanted, trait_kind, kind); + val found := this.find_member(kind, name); + if found.decl == 0 || this.decls.kinds.p[found.decl] != dk::function { + val given := this.builtin_method(kind, name); + return given != 0 && this.same_signature(this.as_writing(given, wanted), signature); + } + + # A number's methods from the compiler are asked first, so a number meets a + # trait without the program's methods beside them being worked out. One of + # those may be what asked, as `def f32::mul(&this, v: &vec3)` asks + # whether `f32` is `numeric` for `vec3`. + if this.types.is_numeric(this.unalias(kind)) { + val builtin := this.builtin_method(kind, name); + return true if builtin != 0 && this.same_signature(this.as_writing(builtin, wanted), signature); + } + + # A default of a trait the type names is its own, taking it as `self`. A + # method taking `&this` meets one asked for taking `&mut this`, since what + # can be written can be read. `core`'s methods behind a program's on its + # type meet what they did. + var chain := found.decl; + while chain != 0 { + var walk := this.decls.walk_overloads(chain); + while true { + val at := walk.next(); + break if at == 0; + continue if !this.member_seen(at); + this.resolve(at); + val declarer := this.enclosing_trait(at); + var given := declarer != 0 + ? this.requirement_type(at, this.implemented(kind, declarer), kind) + : this.method_type(at, found.owner); + if this.decls.has(at, df::method) && !this.decls.has(at, df::mut_this) { + given = this.as_writing(given, wanted); + } + if this.decls.has(at, df::method) == this.decls.has(wanted, df::method) + && this.same_signature(given, signature) && this.bounds_met(at, found.owner) { + return true; + } + } + chain = this.core_behind(chain); + } + # A method a program declares on a built-in type is beside those the + # compiler gives it, which still meet what they did. + val given := this.builtin_method(kind, name); + return given != 0 && this.same_signature(this.as_writing(given, wanted), signature); + } + dk::property => { + val found := this.find_member(kind, name); + return found.decl != 0 && this.decls.kinds.p[found.decl] == dk::property; + } + dk::assoc_type => { + val found := this.find_member(kind, name); + return (found.decl != 0 && this.is_type_decl(found.decl)) || this.decls.targets.p[wanted] != 0; + } + dk::variable => { + val found := this.find_member(kind, name); + return found.decl != 0 && this.decls.kinds.p[found.decl] == dk::variable; + } + else => return true; + } + return true; +} + +#! Whether a type has a method whose `where` bounds the type's parameters +#! further: whether its arguments meet those bounds. Any other method it has +#! always. +#! @param this The checker. +#! @param method The method's declaration. +#! @param owner The type it is a member of, given its arguments. +#! @returns Whether they do. +pub def checker::bounds_met(&mut this, method: u32, owner: u32): bool { + return true if !this.decls.has(method, df::bounding); + val plain := this.unalias(owner); + return true if this.types.kind_of(plain) != ty::named || this.types.is_open(plain); + var params := this.decls.list_of(this.decls.params.p[method]); + var args := this.types.parts_of(plain); + if params.length > args.length { + params.resize(args.length); + } + return true if params.length == 0; + + val dropped := this.dropped; + val uninferred := this.uninferred; + this.mute++; + val met := this.check_bounds_of(method, params.view(), args.view(), 0); + this.mute--; + this.dropped = dropped; + this.uninferred = uninferred; + return met; +} + +#! A method's type as one asked for taking `&mut this` sees it, where the method +#! takes `&this`: taking `&mut this` too, since what can be written can be read. +#! @param this The checker. +#! @param given The method's type, `this` first. +#! @param wanted The declaration of the method asked for. +#! @returns The type, as it is where the method asked for takes `&this`. +def checker::as_writing(&mut this, given: u32, wanted: u32): u32 { + return given if !this.decls.has(wanted, df::mut_this) || this.types.kind_of(given) != ty::function + || this.types.part_count(given) == 0 || this.types.kind_of(this.types.part_at(given, 0)) != ty::reference; + var parts := this.types.parts_of(given); + parts[0] = this.types.reference(this.types.first_of(parts[0]), true); + return this.types.function(parts.view(), this.types.first_of(given), this.types.second_of(given) != 0); +} + +#! Whether two function types are the same but for aliases. +#! @param this The checker. +#! @param a One function type. +#! @param b The other. +#! @returns Whether they are. +def checker::same_signature(&mut this, a: u32, b: u32): bool { + return a == b || (this.types.kind_of(a) == ty::function && this.types.kind_of(b) == ty::function + && this.types.second_of(a) == this.types.second_of(b) && this.same_function(a, b)); +} + +#! The type of a method a trait asks for, given the trait's arguments and the +#! type standing for `self`. +#! @param this The checker. +#! @param method The method's declaration. +#! @param trait_kind The trait's type, given its arguments. +#! @param self_kind The type standing for `self`. +#! @returns The method's type. +pub def checker::requirement_type(&mut this, method: u32, trait_kind: u32, self_kind: u32): u32 { + this.resolve(method); + val holder: u32 = this.decls.owners.p[method]; + return this.trait_in_terms(this.decls.types.p[method], holder, trait_kind, self_kind); +} + +#! The type of a trait's method called on a value of the type: through a bound +#! of a type parameter, or through a trait reference. +#! @param this The checker. +#! @param method The method's declaration. +#! @param kind The type of the value it is called on. +#! @returns The method's type, or the error type where the value's type gives no +#! trait declaring it. +pub def checker::trait_method_type(&mut this, method: u32, kind: u32): u32 { + val plain := this.unalias(kind); + return this.requirement_type(method, this.trait_reached(method, plain), plain); +} + +#! The trait declaring a method, given its arguments, as a value of the type it +#! is called on reaches it: through a bound of a type parameter, through a +#! trait reference, or as the trait the type implements. +#! @param this The checker. +#! @param method The method's declaration. +#! @param kind The type of the value it is called on. +#! @returns The trait's type. +pub def checker::trait_reached(&mut this, method: u32, kind: u32): u32 { + val holder: u32 = this.decls.owners.p[method]; + val plain := this.unalias(kind); + # A trait reference has the methods of the traits it composes, in terms of + # its own arguments. + if this.named_kind(plain) == dk::trait_type { + return this.bound_for(plain, this.enclosing_trait(method)); + } + + if this.types.kind_of(plain) == ty::param { + val param := this.types.first_of(plain); + this.resolve(param); + val run: u32 = this.decls.children.p[param]; + for i in 0..this.decls.list_length(run) { + val bound := this.decls.list_at(run, i as u32); + if this.composes(bound, holder, 0) { + return this.bound_for(bound, holder); + } + } + # What an `if const` proved of it, in the branch it guards, given its arguments. + for i in 0..this.proved_params.length { + continue if this.proved_params[i] != param; + val bound: u32 = this.proved_bounds[i]; + if this.composes(bound, holder, 0) { + return this.bound_for(bound, holder); + } + } + # Within a trait, `self` has the members of the traits it composes, in terms + # of its own arguments. + if this.decls.names.p[param] == names::self_id { + val declarer: u32 = this.decls.owners.p[param]; + if declarer != 0 && declarer != holder && this.decls.kinds.p[declarer] == dk::trait_type { + val own: u32 = this.decls.types.p[declarer]; + if this.composes(own, holder, 0) { + return this.bound_for(own, holder); + } + } + return this.decls.types.p[holder]; + } + } + return this.implemented(plain, this.enclosing_trait(method)); +} + +#! The trait, given its arguments, that a type implements where it has a +#! trait's member: the trait the type names that is the one declaring it, or +#! composes it, in terms of the type's arguments, as `pair` for `one: +#! pair`, or the trait's own type where it names none. +#! @param this The checker. +#! @param kind The type. +#! @param holder The declaration of the trait declaring the member. +#! @returns The trait's type. +pub def checker::implemented(&mut this, kind: u32, holder: u32): u32 { + val plain := this.unalias(kind); + if this.types.kind_of(plain) == ty::named { + val decl := this.types.first_of(plain); + val run := this.composed_of(decl); + for i in 0..this.decls.list_length(run) { + val named := this.instantiated(this.decls.list_at(run, i as u32), decl, plain); + return this.bound_for(named, holder) if this.composes(named, holder, 0); + } + } + return this.decls.types.p[holder]; +} + +#! The trait a bound is, or the trait it composes that declares a member, given +#! the bound's arguments. +#! @param this The checker. +#! @param bound The bound's type. +#! @param holder The declaration of the trait declaring the member. +#! @returns That trait's type, given the bound's arguments, or the bound itself +#! where no trait it composes declares the member. +pub def checker::bound_for(&mut this, bound: u32, holder: u32): u32 { + return bound if this.types.first_of(bound) == holder; + val decl := this.types.first_of(bound); + val run := this.composed_of(decl); + for i in 0..this.decls.list_length(run) { + val inner := this.trait_in_terms(this.decls.list_at(run, i as u32), decl, bound, bt::error); + return this.bound_for(inner, holder) if this.composes(inner, holder, 0); + } + return bound; +} + +#! Whether a type parameter is bounded by `ordinal`, `integer`, or `real`, which +#! only numbers and enums satisfy, so its values are ordered as theirs are. +#! @param this The checker. +#! @param param The parameter's declaration. +#! @returns Whether it is. +pub def checker::param_ordinal(&mut this, param: u32): bool { + return this.bounded_by(param, this.std_decl(word::ordinal), this.std_decl(word::integer), this.std_decl(word::real)); +} + +#! Whether the type parameter's bounds let numbers stand in for it. +#! @param this The checker. +#! @param param The type parameter's type. +#! @returns Whether they do. +pub def checker::param_has_numeric(&mut this, param: u32): bool { + return this.bounded_by(param, this.std_decl(word::numeric), this.std_decl(word::integer), this.std_decl(word::real)); +} + +#! Checks that each type argument of a named type satisfies the bounds of its +#! parameter. +#! @param this The checker. +#! @param decl The declaration of the generic type. +#! @param kind The named type, given its arguments. +#! @param node The node notes are placed at. +pub def checker::check_bounds(&mut this, decl: u32, kind: u32, node: u32): void { + val params: u32 = this.decls.params.p[decl]; + var args := this.types.parts_of(kind); + this.check_args_bounds(decl, params, args.view(), node); + if this.is_std(kind, word::simd) || this.is_std(kind, word::mask) { + this.check_lanes(decl, kind, node); + } +} + +#! Checks that a vector, or a mask of one, holds 16 or 32 bytes of numbers, or +#! 64 bytes of at most 32, as the processor's vector instructions take them: a +#! mask's bits are a `u32`. +#! @param this The checker. +#! @param decl `simd` or `mask`. +#! @param kind The vector's type, given its lanes. +#! @param node The node notes are placed at. +def checker::check_lanes(&mut this, decl: u32, kind: u32, node: u32): void { + return if this.types.part_count(kind) < 2; + val lane := this.unalias(this.types.part_at(kind, 0)); + val count := this.types.part_at(kind, 1); + # Within a template, what it is given is known only in each instance. + return if this.types.is_open(lane) || this.types.kind_of(count) != ty::value; + val held: known = this.knowns.p[this.types.second_of(count)]; + val number := this.types.kind_of(lane) == ty::signed || this.types.kind_of(lane) == ty::unsigned + || this.types.kind_of(lane) == ty::floating; + val bytes := number && held.kind == kk::number ? held.value.magnitude * (this.types.first_of(lane) as u64 / 8) : 0; + return if bytes == 16 || bytes == 32 || (bytes == 64 && held.value.magnitude <= 32); + var text := string::from("`", nothing {}); + text.append(this.decl_text(decl)); + text.append("` holds 16 or 32 bytes of numbers, as `f32[4]` or `u8[32]`, or 64 of at most 32, as `f32[16]`, and is given `"); + val named := this.describe(this.types.part_at(kind, 0)); + text.append(named.view()); + text.append("["); + val length := this.describe(count); + text.append(length.view()); + text.append("]`."); + this.report_text(node, ec::generic, &text); +} + +#! Checks that each type argument satisfies the bounds of its parameter, each +#! bound given the arguments for the parameters it names. +#! @param this The checker. +#! @param decl The generic declaration. +#! @param params The run of its type parameters. +#! @param args The type arguments. +#! @param node The node notes are placed at. +#! @returns Whether each satisfies them. +pub def checker::check_args_bounds(&mut this, decl: u32, params: u32, args: span, node: u32): bool { + val from := this.decls.list_of(params); + return this.check_bounds_of(decl, from.view(), args, node); +} + +#! Checks that each type argument satisfies the bounds of its parameter, as +#! `check_args_bounds` does, given the parameters themselves. +#! @param this The checker. +#! @param decl The generic declaration. +#! @param from Its type parameters. +#! @param args The type arguments, one for each. +#! @param node The node a note is placed at. +#! @returns Whether every argument satisfies its bounds. +pub def checker::check_bounds_of(&mut this, decl: u32, from: span, args: span, node: u32): bool { + var valid := true; + for i in 0..from.length { + break if i >= args.length; + val param: u32 = from[i]; + val given := args[i]; + continue if given == bt::error; + + # A pack's bounds are each of its types'. + var each := vector::::new(); + if this.types.is_known_pack(given) { + each.extend(this.types.parts_view(given)); + } else { + each.append(given); + } + + this.resolve(param); + val run: u32 = this.decls.children.p[param]; + for j in 0..this.decls.list_length(run) { + val bound := this.substitute(this.decls.list_at(run, j as u32), from, args); + for &arg in each { + continue if this.satisfies(arg, bound); + + valid = false; + var text := string::from("`", nothing {}); + val named_arg := this.describe(arg); + text.append(named_arg.view()); + + # What has no zero value is named, since the type may be one holding it. + if this.types.first_of(bound) == this.std_decl(word::zeroable) { + val lacking := this.zero_lacking(arg); + text.append("` is not `zeroable`, which `"); + text.append(this.decl_text(param)); + text.append("` of `"); + text.append(this.decl_text(decl)); + text.append("` requires: "); + text.append(lacking.view()); + text.append("."); + this.report_text(node, ec::bound, &text); + continue; + } + val named := this.describe(bound); + text.append("` does not implement `"); + text.append(named.view()); + + # A reference whose referent satisfies the trait says why it does not. + val why := this.unlent(arg, bound); + if why.length > 0 { + text.append("`, though what it refers to does: "); + text.append(why.view()); + text.append(". `"); + text.append(this.decl_text(param)); + text.append("` of `"); + text.append(this.decl_text(decl)); + text.append("` requires it."); + this.report_text(node, ec::bound, &text); + continue; + } + text.append("`, which `"); + text.append(this.decl_text(param)); + text.append("` of `"); + text.append(this.decl_text(decl)); + text.append("` requires."); + this.report_text(node, ec::bound, &text); + } + } + } + return valid; +} diff --git a/analyzer/checker/types.sakura b/analyzer/checker/types.sakura new file mode 100644 index 00000000..4daff016 --- /dev/null +++ b/analyzer/checker/types.sakura @@ -0,0 +1,581 @@ +#! @file types.sakura +#! @author John Christman (sorakatadzuma@gmail.com) +#! @copyright Malunal Studios, LLC. +#! @license MIT +#! +#! Contains the type table, which gives every type the checker meets an ID of +#! its own. A type is interned by its kind, two numbers, and its parts, so two +#! types are the same exactly where their IDs are, and the parts of each are a +#! run of one vector, as the runs of a syntax are. + +module sakura::analyzer; + + +#! The kinds of type. +pub enum ty : u8 { + error, #! What a mistake gives, which fits anywhere, so a mistake is reported once. + void_type, #! `void`, which a function giving nothing gives. + null_type, #! The type of `null`, which becomes any pointer. + boolean, #! `bool`. + signed, #! `first` is its bits. + unsigned, #! `first` is its bits. + floating, #! `first` is its bits. + untyped_int, #! An integer constant, an `i64` unless another number type is expected. + untyped_uint, #! An integer written with `u`, a `uint` unless another unsigned type is expected. + untyped_char, #! A character, a `u32` unless another integer type is expected. + untyped_float, #! A float constant, an `f64` unless another float type is expected. + untyped_float32, #! A float constant written with `f`, an `f32` unless an `f64` is expected. + untyped_bool, #! A constant `true` or `false`. + untyped_text, #! Text, a `span` or a `string`, whichever is expected. + empty, #! The element of `[]`, which becomes any element. + reference, #! `first` is what it refers to, and `second` is 1 where it writes. + pointer, #! `first` is what it points at, and `second` is 1 where it writes. + fixed, #! `first` is its element, and `second` how many it holds, or within a template its one part, a constant only each instance knows. + function, #! `first` is its result, `parts` its parameters, and `second` 1 where the last is variadic. + named, #! `first` is its declaration, and `parts` its type arguments. + param, #! `first` is the declaration of the type parameter it is. + pack, #! `parts` are its types, or `first` is the declaration of the pack it is, while unknown. + value, #! A constant type argument: `first` is the type of its value, `second` its ID among the checker's known values, and `parts` the constant parameters it is worked out from, within a template. +} + +#! What a type's `flags` hold: what is so of it, which interning it works out, +#! and what the checker worked out of it and keeps, which `forget` lets go of. +pub enum tf : u8 { + open = 0x01, #! It holds a type parameter anywhere within. + holds = 0x02, #! It holds a constant, or a fixed array whose length is one, anywhere within. + asked = 0x04, #! Whether it is an alias was worked out, which `alias` says. + alias = 0x08, #! It is an alias. + weighed = 0x10, #! Whether values of it close was worked out, which `closes` says. + closes = 0x20, #! Values of it close, or hold what does. +} + +#! Lets go of what the checker worked out of each type and kept in its flags, +#! which a change may have changed. +#! @param this The type table. +pub def type_table::forget(&mut this): void { + val kept := tf::open as u8 | tf::holds as u8; + for id in 0..this.flags.length { + this.flags.p[id] &= kept; + } +} + +#! The IDs of the types every program has, which the type table interns first +#! and in this order. +pub enum bt : u32 { + #! The error type. + error, + #! `void`. + void_type, + #! The type of `null`. + null_type, + #! `bool`. + boolean, + #! `i8`. + int8, + #! `i16`. + int16, + #! `i32`. + int32, + #! `i64`. + int64, + #! `u8`. + uint8, + #! `u16`. + uint16, + #! `u32`. + uint32, + #! `u64`. + uint64, + #! `f32`. + float32, + #! `f64`. + float64, + #! An integer constant. + untyped_int, + #! An integer constant written with `u`. + untyped_uint, + #! A character. + untyped_char, + #! A float constant. + untyped_float, + #! A float constant written with `f`. + untyped_float32, + #! A constant `true` or `false`. + untyped_bool, + #! Text written as a literal. + untyped_text, + #! The element of `[]`. + empty, + #! How many built-in types there are, which is the ID of the first other type. + count, +} + +#! Every type, by its ID, a field in a column of its own. +pub struct type_table { + var kinds: column; #! The kind of each type. + var firsts: column; #! The first number of each type, which its kind says the meaning of. + var seconds: column; #! The second number of each type. + var parts: column; #! The run of each type's parts in `runs`, 0 where it has none. + pub var flags: column; #! What is so of each type, as `tf` says: what it holds, and what was worked out of it. + var runs: column; #! The runs of parts, each a count and then the parts. + var index: id_index; #! The types of each hash, which interning finds them by. + var scratch: column; #! The parts of the types substituting is making, those of each inner one past those of the ones around it. +} + +#! Makes a type table holding the types every program has. +#! @returns The table, in which the IDs of `bt` are those types. +pub def type_table::new(): type_table { + var made := type_table { + kinds = column::::new(), + firsts = column::::new(), + seconds = column::::new(), + parts = column::::new(), + flags = column::::new(), + runs = column::::new(), + index = id_index::new(), + scratch = column::::new() + }; + + made.runs.append(0); + val none := span::::empty(); + made.intern(ty::error, 0, 0, none); + made.intern(ty::void_type, 0, 0, none); + made.intern(ty::null_type, 0, 0, none); + made.intern(ty::boolean, 8, 0, none); + made.intern(ty::signed, 8, 0, none); + made.intern(ty::signed, 16, 0, none); + made.intern(ty::signed, 32, 0, none); + made.intern(ty::signed, 64, 0, none); + made.intern(ty::unsigned, 8, 0, none); + made.intern(ty::unsigned, 16, 0, none); + made.intern(ty::unsigned, 32, 0, none); + made.intern(ty::unsigned, 64, 0, none); + made.intern(ty::floating, 32, 0, none); + made.intern(ty::floating, 64, 0, none); + made.intern(ty::untyped_int, 0, 0, none); + made.intern(ty::untyped_uint, 0, 0, none); + made.intern(ty::untyped_char, 0, 0, none); + made.intern(ty::untyped_float, 0, 0, none); + made.intern(ty::untyped_float32, 0, 0, none); + made.intern(ty::untyped_bool, 0, 0, none); + made.intern(ty::untyped_text, 0, 0, none); + made.intern(ty::empty, 0, 0, none); + expects(made.kinds.length == bt::count as u64); + return made; +} + +#! How many types there are. +#! @param this The type table. +#! @returns The number of types, which is one more than the newest's ID. +pub val type_table::count: u64 { get => this.kinds.length; } + +#! The ID of the type of the kind, numbers, and parts, made where it is new. +#! @param this The type table. +#! @param kind The type's kind. +#! @param first Its first number, which its kind says the meaning of. +#! @param second Its second number. +#! @param items Its parts, in order. +#! @returns The type's ID. +pub def type_table::intern(&mut this, kind: ty, first: u32, second: u32, items: span): u32 { + var hash := mix(mix(mix(items.length, kind as u64), first as u64), second as u64); + for &item in items { + hash = mix(hash, item as u64); + } + + var walk := this.index.walk(hash); + var at := this.index.next(&mut walk); + while at != 0 { + val id := at - 1; + if this.kinds.p[id] == kind && this.firsts.p[id] == first && this.seconds.p[id] == second + && this.same_parts(id, items) { + return id; + } + at = this.index.next(&mut walk); + } + + # A type is open where it is a type parameter, or holds one. + var open := kind == ty::param || (kind == ty::pack && items.length == 0 && first != 0); + if kind == ty::reference || kind == ty::pointer || kind == ty::fixed || kind == ty::function + || kind == ty::value { + open = open || this.is_open(first); + } + # A type holds a constant where it is one, is a fixed array whose length is one, + # or holds either, which only substituting within it may work out. + var held := kind == ty::value || (kind == ty::fixed && items.length != 0); + if kind == ty::reference || kind == ty::pointer || kind == ty::fixed || kind == ty::function { + held = held || this.holds_value(first); + } + for &item in items { + open = open || this.is_open(item as u32); + held = held || this.holds_value(item as u32); + } + + var run: u32 = 0; + if items.length != 0 { + run = this.runs.length as u32; + this.runs.append(items.length as u32); + this.runs.extend(items); + } + + val id := this.kinds.length as u32; + this.kinds.append(kind); + this.firsts.append(first); + this.seconds.append(second); + this.parts.append(run); + this.flags.append((open ? tf::open as u8 : 0) | (held ? tf::holds as u8 : 0)); + this.index.add(hash, id); + return id; +} + +def type_table::same_parts(&this, id: u32, items: span): bool { + val run: u32 = this.parts.p[id]; + val count: u32 = run == 0 ? 0 : this.runs.p[run]; + return false if count as u64 != items.length; + for i in 0..items.length { + return false if this.runs.p[run as u64 + 1 + i] != items[i]; + } + return true; +} + +#! The kind of a type. +#! @param this The type table. +#! @param id The type's ID. +#! @returns Its kind. +pub def type_table::kind_of(&this, id: u32): ty { return this.kinds.p[id]; } +#! The first number of a type, which its kind says the meaning of. +#! @param this The type table. +#! @param id The type's ID. +#! @returns The number. +pub def type_table::first_of(&this, id: u32): u32 { return this.firsts.p[id]; } +#! The second number of a type, which its kind says the meaning of. +#! @param this The type table. +#! @param id The type's ID. +#! @returns The number. +pub def type_table::second_of(&this, id: u32): u32 { return this.seconds.p[id]; } +#! Whether a type holds a type parameter anywhere within, so it stands for other +#! types once the parameter is known. +#! @param this The type table. +#! @param id The type's ID. +#! @returns Whether it holds one. +pub def type_table::is_open(&this, id: u32): bool { return (this.flags.p[id] & tf::open as u8) != 0; } +#! Whether a type holds a constant, or a fixed array whose length is one, +#! anywhere within. +#! @param this The type table. +#! @param id The type's ID. +#! @returns Whether it holds one. +pub def type_table::holds_value(&this, id: u32): bool { return (this.flags.p[id] & tf::holds as u8) != 0; } + +#! How many parts the type has: the parameters of a function, the type +#! arguments of a named type, or the types of a pack. +#! @param this The type table. +#! @param id The type's ID. +#! @returns How many parts it has. +pub def type_table::part_count(&this, id: u32): u32 { + val run: u32 = this.parts.p[id]; + return run == 0 ? 0 : this.runs.p[run]; +} + +#! A part of a type, by its position. +#! @param this The type table. +#! @param id The type's ID. +#! @param index The part's position, below `part_count`. +#! @returns The part's ID. +pub def type_table::part_at(&this, id: u32, index: u32): u32 { + return this.runs.p[this.parts.p[id] as u64 + 1 + index as u64]; +} + +#! The parts of the type, where they are. +#! @param this The type table. +#! @param id The type's ID. +#! @returns The IDs of its parts, in order, a view only good until a type with +#! parts is interned, so a loop that may intern one walks them by +#! `part_at`, or copies them by `parts_of`. +pub def type_table::parts_view(&this, id: u32): span { + val run: u32 = this.parts.p[id]; + return span::::over(this.runs.p + run + 1, run == 0 ? 0 : this.runs.p[run] as u64); +} + +#! The parts of the type, copied, since interning may move where they are. +#! @param this The type table. +#! @param id The type's ID. +#! @returns The IDs of its parts, in order. +pub def type_table::parts_of(&this, id: u32): vector { + var made := vector::::new(); + made.extend(this.parts_view(id)); + return made; +} + +#! The type of a reference. +#! @param this The type table. +#! @param referent The type it refers to. +#! @param mutable Whether it writes, as `&mut` does. +#! @returns The reference's ID. +pub def type_table::reference(&mut this, referent: u32, mutable: bool): u32 { + return this.intern(ty::reference, referent, mutable ? 1 : 0, span::::empty()); +} + +#! The type of a pointer. +#! @param this The type table. +#! @param pointee The type it points at. +#! @param mutable Whether it writes, as `*mut` does. +#! @returns The pointer's ID. +pub def type_table::pointer(&mut this, pointee: u32, mutable: bool): u32 { + return this.intern(ty::pointer, pointee, mutable ? 1 : 0, span::::empty()); +} + +#! The type of a fixed array. +#! @param this The type table. +#! @param element The type of its elements. +#! @param count How many it holds. +#! @returns The array's ID. +pub def type_table::fixed(&mut this, element: u32, count: u32): u32 { + return this.intern(ty::fixed, element, count, span::::empty()); +} + +#! The type of a fixed array whose length only each instance of a template knows. +#! @param this The type table. +#! @param element The type of its elements. +#! @param length The constant parameter or value it holds as many as. +#! @returns The array's ID. +pub def type_table::fixed_of(&mut this, element: u32, length: u32): u32 { + var parts := vector::::new(); + parts.append(length); + return this.intern(ty::fixed, element, 0, parts.view()); +} + +#! The type of a function. +#! @param this The type table. +#! @param params The types of its parameters, in order. +#! @param result The type it gives. +#! @param variadic Whether its last parameter takes any number of values. +#! @returns The function's ID. +pub def type_table::function(&mut this, params: span, result: u32, variadic: bool): u32 { + return this.intern(ty::function, result, variadic ? 1 : 0, params); +} + +#! The type a declaration names, given its type arguments. +#! @param this The type table. +#! @param decl The declaration of the struct, union, enum, trait, or alias. +#! @param args Its type arguments, or none where it is not generic. +#! @returns The type's ID. +pub def type_table::named(&mut this, decl: u32, args: span): u32 { + return this.intern(ty::named, decl, 0, args); +} + +#! The type a type parameter is, while what it stands for is not known. +#! @param this The type table. +#! @param decl The type parameter's declaration. +#! @returns The type's ID. +pub def type_table::param(&mut this, decl: u32): u32 { + return this.intern(ty::param, decl, 0, span::::empty()); +} + +#! The pack of the types, or while they are unknown, the pack of the parameter. +#! @param this The type table. +#! @param items The types the pack holds, or none while they are unknown. +#! @param decl The declaration of the pack parameter, while its types are +#! unknown. +#! @returns The pack's ID. +pub def type_table::pack(&mut this, items: span, decl: u32): u32 { + return this.intern(ty::pack, items.length == 0 ? decl : 0, 0, items); +} + +#! The pack of the parameters of a variadic function, whose last takes any number +#! of values of its type, as `(str, i64...)` of `def(str, i64...): void`. Spread +#! into a function's parameters, it makes the function variadic. +#! @param this The type table. +#! @param items The types of the parameters, the last that of the values it +#! takes. +#! @returns The pack's ID. +pub def type_table::variadic_pack(&mut this, items: span): u32 { + return this.intern(ty::pack, 0, 1, items); +} + +#! The pack of a function type's parameters, variadic where it is. +#! @param this The type table. +#! @param id The function type's ID. +#! @param from The first parameter the pack holds. +#! @returns The pack's ID. +pub def type_table::params_pack(&mut this, id: u32, from: u32): u32 { + var items := vector::::new(); + for i in from..this.part_count(id) { + items.append(this.part_at(id, i as u32)); + } + return this.seconds.p[id] != 0 && items.length != 0 ? this.variadic_pack(items.view()) : this.pack(items.view(), 0); +} + +#! Whether the type is an integer of a known size, or an integer constant. +#! @param this The type table. +#! @param id The type's ID. +#! @returns Whether it is one. +pub def type_table::is_integer(&this, id: u32): bool { + return match this.kinds.p[id] { + ty::signed, ty::unsigned, ty::untyped_int, ty::untyped_uint, ty::untyped_char => true, + else => false + }; +} + +#! Whether a type is a float of a known size, or a float constant. +#! @param this The type table. +#! @param id The type's ID. +#! @returns Whether it is one. +pub def type_table::is_float(&this, id: u32): bool { + return match this.kinds.p[id] { + ty::floating, ty::untyped_float, ty::untyped_float32 => true, + else => false + }; +} + +#! Whether a type is a number: an integer or a float, of a known size or a +#! constant. +#! @param this The type table. +#! @param id The type's ID. +#! @returns Whether it is one. +pub def type_table::is_numeric(&this, id: u32): bool { + return this.is_integer(id) || this.is_float(id); +} + +#! Whether a type is `bool`, or a constant `true` or `false`. +#! @param this The type table. +#! @param id The type's ID. +#! @returns Whether it is one. +pub def type_table::is_boolean(&this, id: u32): bool { + val kind: ty = this.kinds.p[id]; + return kind == ty::boolean || kind == ty::untyped_bool; +} + +#! Whether the type is a constant's, which takes the type expected of it. +#! @param this The type table. +#! @param id The type's ID. +#! @returns Whether it is one. +pub def type_table::is_untyped(&this, id: u32): bool { + return match this.kinds.p[id] { + ty::untyped_int, ty::untyped_uint, ty::untyped_char, ty::untyped_float, + ty::untyped_float32, ty::untyped_bool, ty::untyped_text, ty::empty, ty::null_type => true, + else => false + }; +} + +#! Whether the type is a signed integer, of a known size or not. +#! @param this The type table. +#! @param id The type's ID. +#! @returns Whether it is one. +pub def type_table::is_signed(&this, id: u32): bool { + val kind: ty = this.kinds.p[id]; + return kind == ty::signed || kind == ty::untyped_int; +} + +#! The numeric type an untyped one becomes where nothing else is expected. +#! @param this The type table. +#! @param id The type's ID. +#! @returns The type it becomes, or the type itself where it is not untyped. +pub def type_table::settled(&this, id: u32): u32 { + return match this.kinds.p[id] { + ty::untyped_int => bt::int64, + ty::untyped_uint => bt::uint64, + ty::untyped_char => bt::uint32, + ty::untyped_float => bt::float64, + ty::untyped_float32 => bt::float32, + ty::untyped_bool => bt::boolean, + else => id + }; +} + +#! The type with each type parameter `from` names replaced by the type `to` +#! gives at the same index. A type holding no parameter is itself. +#! @param this The type table. +#! @param id The type's ID. +#! @param from The type parameters to replace. +#! @param to The types to replace each with. +#! @returns The type made. +pub def type_table::substitute(&mut this, id: u32, from: span, to: span): u32 { + return id if !this.is_open(id) || from.length == 0; + + val kind: ty = this.kinds.p[id]; + val first: u32 = this.firsts.p[id]; + match kind { + ty::param => { + for i in 0..from.length { + return to[i] if from[i] == first && i < to.length; + } + return id; + } + ty::reference, ty::pointer => { + val inner := this.substitute(first, from, to); + return this.intern(kind, inner, this.seconds.p[id], span::::empty()); + } + # A length only each instance knows is given its parameter's argument, which the + # checker then works out. + ty::fixed => { + val inner := this.substitute(first, from, to); + val mark := this.scratch.length; + for i in 0..this.part_count(id) { + val part := this.substitute(this.part_at(id, i as u32), from, to); + this.scratch.append(part); + } + return this.intern_scratch(kind, inner, this.seconds.p[id], mark); + } + else => {} + } + + # A pack parameter stands for the pack it is given, whose types it spreads into + # the parts around it, as `Ts` in `def(Ts...): void`. + if kind == ty::pack && this.part_count(id) == 0 { + for i in 0..from.length { + return to[i] if from[i] == first && i < to.length; + } + return id; + } + + # A pack given for a pack parameter among a function's parameters becomes a + # parameter for each of its types, so the function is no longer variadic, + # unless the pack is a variadic function's parameters. A named type holds the + # pack as the one argument it is, as `Ts` of `box`. The parts are put + # on the scratch column past those of the substitutions around this one, each + # part's own substitution taking what it put there off again, so they lie + # together where interning them reads them. + val mark := this.scratch.length; + var spread := false; + var rest: u32 = 0; + for i in 0..this.part_count(id) { + val written: u32 = this.part_at(id, i as u32); + val part := this.substitute(written, from, to); + val known_pack := this.kinds.p[part] == ty::pack && this.firsts.p[part] == 0; + if known_pack && this.kinds.p[written] == ty::pack && kind == ty::function { + this.scratch.extend(this.parts_view(part)); + spread = true; + rest = this.seconds.p[part]; + continue; + } + this.scratch.append(part); + } + + val result := kind == ty::function ? this.substitute(first, from, to) : first; + val second: u32 = kind == ty::function && spread ? rest : this.seconds.p[id]; + return this.intern_scratch(kind, result, second, mark); +} + +# Interns a type whose parts are those on the scratch column from `mark`, then +# takes them off it. +def type_table::intern_scratch(&mut this, kind: ty, first: u32, second: u32, mark: u64): u32 { + val made := this.intern(kind, first, second, span::::over(this.scratch.p + mark, this.scratch.length - mark)); + this.scratch.resize(mark); + return made; +} + +#! Whether the type is a pack whose types are not yet known: a pack parameter. +#! @param this The type table. +#! @param id The type's ID. +#! @returns Whether it is one. +pub def type_table::is_open_pack(&this, id: u32): bool { + return this.kinds.p[id] == ty::pack && this.part_count(id) == 0 && this.firsts.p[id] != 0; +} + +#! Whether the type is a pack whose types are known: one a pack parameter was +#! given, which is written as the types it gives. +#! @param this The type table. +#! @param id The type's ID. +#! @returns Whether it is one. +pub def type_table::is_known_pack(&this, id: u32): bool { + return this.kinds.p[id] == ty::pack && !this.is_open_pack(id); +} diff --git a/analyzer/column.sakura b/analyzer/column.sakura new file mode 100644 index 00000000..6e797ff6 --- /dev/null +++ b/analyzer/column.sakura @@ -0,0 +1,127 @@ +#! @file column.sakura +#! @author John Christman (sorakatadzuma@gmail.com) +#! @copyright Malunal Studios, LLC. +#! @license MIT +#! +#! Contains the column, which holds one field of the rows of a table, as the +#! kind of every type or the owner of every declaration, with a pointer to its +#! elements that it keeps where they are, so hot code reads and writes them +#! without a call and never through a pointer gone stale. + +module sakura::analyzer; + + +#! One field of the rows of a table, by row: the field's values, one after +#! another in a block of the program's heap, and where they are. +#! +#! Tables keep each field in a column of its own, so a pass reading one field +#! reads only that, and code that reads them often does so through `p`, as +#! `kinds.p[id]`, without a call or a check. Whatever moves the values makes +#! `p` again, so only the column that grew is pointed again, and never another. +#! A column is no more than the pointer and two counts, so the pointers of a +#! table's columns, which hot code reads one after another, lie close together. +#! It owns its block, which it gives back as it closes, so a table that closes, +#! as a checker the language server makes for each check does, keeps nothing. +#! @tparam T The type of the field, which closes nothing. +pub struct column : owning { + pub var p: *mut T; #! Where the values are, which the column keeps; read and written as `p[row]`, below `length`. + var count: u64; #! How many rows it holds. + var room: u64; #! How many rows the block has room for. +} + +#! Makes a column holding no rows, which takes memory once one is added. +#! @returns The column. +pub def column::new(): column { + return column:: { p = null, count = 0, room = 0 }; +} + +#! Gives back the column's block, leaving it holding no rows. +#! @param this The column. +pub def column::close(&mut this): void { + dispose::(nothing {}, this.p, this.room); + this.p = null; + this.count = 0; + this.room = 0; +} + +#! How many rows the column holds. +#! @param this The column. +#! @returns The number of rows. +pub val column::length: u64 { get => this.count; } + +#! Adds a row's value after the last. +#! @param this The column. +#! @param item The value. +pub def column::append(&mut this, item: T): void { + if this.count == this.room { + this.grow(); + } + this.p[this.count] = item; + this.count++; +} + +#! Adds the values of a view after the last, in order. +#! @param this The column. +#! @param items The values. +pub def column::extend(&mut this, items: span): void { + return if items.length == 0; + val wanted := this.count + items.length; + if wanted > this.room { + this.grow(wanted > this.room * 2 ? wanted : this.room * 2); + } + memcpy((this.p + this.count) as *mut u8, items.data as *u8, bytes_of::(items.length)); + this.count = wanted; +} + +#! Makes the column hold a number of rows, adding zeroed ones or letting go of +#! those past it. +#! @param this The column. +#! @param size How many rows it holds after. +pub def column::resize(&mut this, size: u64): void { + # Growing doubles at least, so resizing a little at a time copies little. + if size > this.room { + this.grow(size > this.room * 2 ? size : this.room * 2); + } + if size > this.count { + memset((this.p + this.count) as *mut u8, 0, bytes_of::(size - this.count)); + } + this.count = size; +} + +#! The value of a row, or a zero value past the last, as of a column by ID +#! that grows only as it is written. +#! @param this The column. +#! @param row The row. +#! @returns Its value. +pub def column::at_or_zero(&this, row: u64): T where T: zeroable { + if row < this.count { + return this.p[row]; + } + var none: T; + return none; +} + +#! Writes the value of a row, growing the column to hold it where it is past +#! the last, the rows between holding zero values. +#! @param this The column. +#! @param row The row. +#! @param item Its value. +pub def column::put(&mut this, row: u64, item: T): void { + if row >= this.count { + this.resize(row + 1); + } + this.p[row] = item; +} + +# Gives the column room for twice as many rows, which is apart from `append`, so +# `append` is small enough to be inlined. +def column::grow(&mut this): void { + this.grow(this.room == 0 ? 4 : this.room * 2); +} + +# Gives the column room for a number of rows, moving its values, which `p` +# follows. +def column::grow(&mut this, size: u64): void { + this.p = this.p == null ? acquire::(nothing {}, size) : resize::(nothing {}, this.p, this.room, size); + this.room = size; +} diff --git a/analyzer/errors.sakura b/analyzer/errors.sakura new file mode 100644 index 00000000..34bb84e1 --- /dev/null +++ b/analyzer/errors.sakura @@ -0,0 +1,56 @@ +#! @file errors.sakura +#! @author John Christman (sorakatadzuma@gmail.com) +#! @copyright Malunal Studios, LLC. +#! @license MIT +#! +#! Contains `ec`, the codes of the notes the analyzer makes, which say what kind +#! of mistake each note is about. +module sakura::analyzer; + + +#! The codes of the notes the analyzer makes, which say what kind of mistake +#! each is about. +pub enum ec { + # Lexing and parsing + syntax, #! Source nested deeper than the parser allows. + token, #! A token the parser does not expect where it is. + expr, #! An expression missing where one is expected. + ident, #! A name missing where one is expected. + kind, #! A type missing where one is expected. + decl, #! A declaration written wrongly, or missing what it must have. + escape, #! An escape that is none of those text and characters allow. + char, #! A character literal that is not one character or escape. + block, #! A text block, `"""`, laid out wrongly. + + # Checking + undefined, #! A name nothing declares where it is used, or a module nothing declares. + duplicate, #! A name declared twice in one place. + ambiguous, #! A name more than one import declares, or a call more than one overload fits as well. + hidden, #! A declaration that is not `pub`, used from outside the modules that see it. + not_type, #! A name used as a type that names no type. + not_value, #! A name used as a value that names no value. + mismatch, #! A value of one type where another is expected. + operands, #! An operator applied to what it does not take. + overflow, #! A constant outside the range of its type. + conversion, #! `as` between types that do not convert. + callable, #! A call of what is not a function. + arguments, #! Too few or too many arguments, or none fitting any overload. + member, #! A member a type does not have. + assignable, #! An assignment to what cannot be written. + generic, #! Type arguments wrong in number, given where none are taken, or that cannot be inferred. + bound, #! A type argument that does not satisfy a bound of its parameter. + cycle, #! A declaration that depends on itself. + limit, #! Something nested or repeated past what the checker allows. + control, #! `break` or `continue` outside a loop, or a function that can end without returning. + arms, #! A match missing cases, or with an arm that is not one of them. + constant, #! A value that must be known while compiling, and is not. + zero_value, #! A variable or field left without a value, whose type has no zero value. + invalid, #! A declaration that is not allowed as written, or where it is written. + recursive, #! A struct or union that holds itself, other than through a pointer or reference. + unhandled, #! What is `@nodiscard`, let go of where it is made. + locked, #! What a loop iterates, changed by the loop's body. + owned, #! A value that closes, copied out of the place holding it. + + # Warnings, which never stop a program + lifetime, #! A reference, view, or closure kept past what it refers to. +} diff --git a/analyzer/idindex.sakura b/analyzer/idindex.sakura new file mode 100644 index 00000000..09106cb4 --- /dev/null +++ b/analyzer/idindex.sakura @@ -0,0 +1,126 @@ +#! @file idindex.sakura +#! @author John Christman (sorakatadzuma@gmail.com) +#! @copyright Malunal Studios, LLC. +#! @license MIT +#! +#! Contains the ID index, which interning finds values by their hash with: the +#! type table its types, and the checker its known values and constants. + +module sakura::analyzer; + + +#! The IDs of interned values by their hash, held open: a power of two of +#! slots, a quarter of them free at least, each holding the top half of a +#! value's hash beside one more than its ID, or 0 where it is free. A value's +#! search begins at the slot its hash's top half says, and goes on to the next +#! until a free one, so it reads only eight bytes for each value it passes, and +#! compares only those whose hash shares its top half. +#! +#! What is interned keeps its own fields, which the one interning compares for +#! each ID a walk gives, and gives its values IDs in the order they are made, +#! which no hash decides. +pub struct id_index : owning { + var slots: *mut u64; #! Each slot's hash's top half and one more than its ID, or 0. + var count: u64; #! How many IDs it holds. + var room: u64; #! How many slots there are, a power of two, or 0. +} + +#! Where a walk over the IDs of one hash is. +pub struct id_walk { + var at: u64; #! The slot it reads next. + var tag: u64; #! The top half of the hash, as each slot holds it. +} + +#! Makes an index holding no ID, which takes no memory until it holds one. +#! @returns The index. +pub def id_index::new(): id_index { + return id_index { slots = null, count = 0, room = 0 }; +} + +#! Gives back the index's block, leaving it empty. +#! @param this The index. +pub def id_index::close(&mut this): void { + dispose::(nothing {}, this.slots, this.room); + this.slots = null; + this.count = 0; + this.room = 0; +} + +#! How many IDs the index holds. +#! @param this The index. +#! @returns How many. +pub val id_index::length: u64 { get => this.count; } + +#! How many slots the index has, which is more than it holds. +#! @param this The index. +#! @returns How many. +pub val id_index::capacity: u64 { get => this.room; } + +#! A walk over the IDs whose values may have the hash, which `next` gives. +#! @param this The index. +#! @param hash The hash. +#! @returns The walk. +@inline +pub def id_index::walk(&this, hash: u64): id_walk { + val tag := hash >> 32; + return id_walk { at = this.room == 0 ? 0 : tag & (this.room - 1), tag = tag }; +} + +#! One more than the next ID whose value may have the walk's hash, or 0 where +#! there are no more. +#! @param this The index. +#! @param walk The walk. +#! @returns One more than the ID, or 0. +@inline +pub def id_index::next(&this, walk: &mut id_walk): u32 { + return 0 if this.room == 0; + val mask := this.room - 1; + while true { + val held := this.slots[walk.at]; + return 0 if held == 0; + walk.at = (walk.at + 1) & mask; + if (held >> 32) == walk.tag { + return (held & 0xFFFFFFFF) as u32; + } + } + return 0; +} + +#! Adds the ID of a value of the hash, which it does not hold yet. +#! @param this The index. +#! @param hash The value's hash. +#! @param id Its ID. +pub def id_index::add(&mut this, hash: u64, id: u32): void { + if (this.count + 1) * 4 > this.room * 3 { + this.grow(this.room == 0 ? 64 : this.room * 2); + } + this.put((hash >> 32) << 32 | (id as u64 + 1)); + this.count++; +} + +# Puts a slot's word in the first free slot from where its hash's top half +# says, which there is. +def id_index::put(&mut this, word: u64): void { + val mask := this.room - 1; + var at := (word >> 32) & mask; + while this.slots[at] != 0 { + at = (at + 1) & mask; + } + this.slots[at] = word; +} + +# Moves the IDs into a block of a number of slots, a power of two. +def id_index::grow(&mut this, size: u64): void { + val old := this.slots; + val old_room := this.room; + this.slots = acquire_zeroed::(nothing {}, size); + this.room = size; + for i in 0..old_room { + if old[i] != 0 { + this.put(old[i]); + } + } + if old_room != 0 { + dispose::(nothing {}, old, old_room); + } +} diff --git a/analyzer/keymap.sakura b/analyzer/keymap.sakura new file mode 100644 index 00000000..0aae7f9d --- /dev/null +++ b/analyzer/keymap.sakura @@ -0,0 +1,226 @@ +#! @file keymap.sakura +#! @author John Christman (sorakatadzuma@gmail.com) +#! @copyright Malunal Studios, LLC. +#! @license MIT +#! +#! Contains the key map, which finds a `u32` by a `u64` key, as the instance a +#! call uses by its table and node, in twelve bytes a slot, where a dictionary +#! takes forty: the key, its value, and nothing more, as an integer's hash is +#! quickly made again. + +module sakura::analyzer; + + +#! A map of `u64` keys to `u32` values, held open: a power of two of slots, a +#! quarter of them free at least, and each key in the first slot from where its +#! hash begins that is free or holds it. Keys and values are each kept in a +#! block of their own, slot by slot, so finding a key reads only keys. A key of +#! all ones stands for a free slot, which no key the checker makes is: a +#! `pair_key` of two IDs, an index, or an ID. +pub struct keymap : owning { + var keys: *mut u64; #! Each slot's key, or `keymap::free`. + var values: *mut u32; #! Each slot's value. + var count: u64; #! How many keys it holds. + var room: u64; #! How many slots there are, a power of two, or 0. +} + +#! The key of a free slot. +pub const keymap::free: u64 = 0xFFFFFFFFFFFFFFFF; + +#! Makes a map holding nothing, which takes no memory until it holds a key. +#! @returns The map. +pub def keymap::new(): keymap { + return keymap { keys = null, values = null, count = 0, room = 0 }; +} + +#! Gives back the map's blocks, leaving it empty. +#! @param this The map. +pub def keymap::close(&mut this): void { + dispose::(nothing {}, this.keys, this.room); + dispose::(nothing {}, this.values, this.room); + this.keys = null; + this.values = null; + this.count = 0; + this.room = 0; +} + +#! How many keys the map holds. +#! @param this The map. +#! @returns How many. +pub val keymap::length: u64 { get => this.count; } + +#! How many slots the map has, which is more than it holds. +#! @param this The map. +#! @returns How many. +pub val keymap::capacity: u64 { get => this.room; } + +#! The value of a key, where the map holds it. +#! @param this The map. +#! @param key The key. +#! @returns The value, or nothing. +pub def keymap::get(&this, key: &u64): maybe { + val at := this.find(key); + return nothing {} if at == this.room; + return this.values[at]; +} + +#! The value of a key, or another where the map does not hold it. +#! @param this The map. +#! @param key The key. +#! @param missing What is given where it does not. +#! @returns The value. +pub def keymap::get_or(&this, key: &u64, missing: u32): u32 { + val at := this.find(key); + return at == this.room ? missing : this.values[at]; +} + +#! Whether the map holds a key. +#! @param this The map. +#! @param key The key. +#! @returns Whether it does. +pub def keymap::contains(&this, key: &u64): bool { + return this.find(key) != this.room; +} + +#! Gives a key a value, the one it held replaced. +#! @param this The map. +#! @param key The key, which is not `keymap::free`. +#! @param value The value. +pub def keymap::set(&mut this, key: u64, value: u32): void { + val at := this.place(key); + this.values[at] = value; +} + +#! Gives a key a value where the map does not hold it already. +#! @param this The map. +#! @param key The key, which is not `keymap::free`. +#! @param value The value. +#! @returns Whether the key was new and took the value. A key the map already +#! holds keeps the value it has. +pub def keymap::insert(&mut this, key: u64, value: u32): bool { + val held := this.count; + val at := this.place(key); + return false if this.count == held; + this.values[at] = value; + return true; +} + +#! Takes a key and its value from the map, where it holds it. +#! @param this The map. +#! @param key The key. +pub def keymap::remove(&mut this, key: &u64): void { + var at := this.find(key); + return if at == this.room; + + # Each key after the gap that would be found past it moves back into it, so + # every key is still found from where its hash begins, and no slot is marked + # as having held one. + val mask := this.room - 1; + var next := (at + 1) & mask; + while this.keys[next] != keymap::free { + val home := keymap::home(this.keys[next], mask); + if ((next - home) & mask) >= ((next - at) & mask) { + this.keys[at] = this.keys[next]; + this.values[at] = this.values[next]; + at = next; + } + next = (next + 1) & mask; + } + this.keys[at] = keymap::free; + this.count--; +} + +#! The key a slot holds, or `keymap::free`, for walking every key the map +#! holds, as each of its `capacity` slots: in no order the keys were given in. +#! @param this The map. +#! @param slot The slot, below `capacity`. +#! @returns The key. +pub def keymap::key_at(&this, slot: u64): u64 { + return this.keys[slot]; +} + +#! The value a slot holds, where it holds a key. +#! @param this The map. +#! @param slot The slot, below `capacity`. +#! @returns The value. +pub def keymap::value_at(&this, slot: u64): u32 { + return this.values[slot]; +} + +#! Takes every key from the map, keeping its slots. +#! @param this The map. +pub def keymap::clear(&mut this): void { + if this.room != 0 { + memset(this.keys as *mut u8, 0xFF, bytes_of::(this.room)); + } + this.count = 0; +} + +# The slot a key's search begins at: its bits mixed, as `mix` does, then +# masked. +def keymap::home(key: u64, mask: u64): u64 { + val bits := key * 0x9E3779B97F4A7C15; + return (bits ^ (bits >> 29)) & mask; +} + +# The slot holding a key, or `room` where none does. +def keymap::find(&this, key: u64): u64 { + return this.room if this.count == 0; + val mask := this.room - 1; + var at := keymap::home(key, mask); + while true { + val held := this.keys[at]; + return at if held == key; + return this.room if held == keymap::free; + at = (at + 1) & mask; + } + return this.room; +} + +# The slot holding a key, which it is put in where it is new, growing the map +# first where a quarter of its slots would no longer be free. +def keymap::place(&mut this, key: u64): u64 { + if (this.count + 1) * 4 > this.room * 3 { + this.grow(this.room == 0 ? 16 : this.room * 2); + } + val mask := this.room - 1; + var at := keymap::home(key, mask); + while true { + val held := this.keys[at]; + return at if held == key; + if held == keymap::free { + this.keys[at] = key; + this.count++; + return at; + } + at = (at + 1) & mask; + } + return at; +} + +# Moves the keys into blocks of a number of slots, a power of two. +def keymap::grow(&mut this, size: u64): void { + val old_keys := this.keys; + val old_values := this.values; + val old_room := this.room; + this.keys = acquire::(nothing {}, size); + this.values = acquire::(nothing {}, size); + this.room = size; + memset(this.keys as *mut u8, 0xFF, bytes_of::(size)); + + val mask := size - 1; + for i in 0..old_room { + val key := old_keys[i]; + continue if key == keymap::free; + var at := keymap::home(key, mask); + while this.keys[at] != keymap::free { + at = (at + 1) & mask; + } + this.keys[at] = key; + this.values[at] = old_values[i]; + } + if old_room != 0 { + dispose::(nothing {}, old_keys, old_room); + dispose::(nothing {}, old_values, old_room); + } +} diff --git a/analyzer/lexer.sakura b/analyzer/lexer.sakura new file mode 100644 index 00000000..f68bd4ba --- /dev/null +++ b/analyzer/lexer.sakura @@ -0,0 +1,668 @@ +#! @file lexer.sakura +#! @author John Christman (sorakatadzuma@gmail.com) +#! @copyright Malunal Studios, LLC. +#! @license MIT +#! +#! Contains the lexer, which reads the text of a source into tokens. It notes +#! what is wrong with the text as it goes, keeps the comments and documentation +#! for the tokens they are written before, and follows the holes of interpolated +#! strings, so the parser is given tokens alone. + +import std::containers; +import core::swar; +module sakura::analyzer; + + +#! Represents a structure capable of lexically analyzing a source object. +#! +#! The lexer reports what is wrong with the text it reads itself: numbers and +#! quotes that are malformed, escapes that do not exist, character literals of +#! more or less than one character, and text spanning lines that is laid out +#! wrong. A character that is no part of the language is reported and dropped, +#! so the parser never sees it. +#! +#! A `>` begins the longest operator it can, as `>>`, `>=`, or `>>=`, and a +#! token is made at each `>` and `=` after its first as well, holding what is +#! left of it: `>>=` is `>>=`, `>=`, then `=`. An operator is the first of those +#! tokens, and the parser moves past the rest with it, while type arguments +#! closed by `>>` take its tokens one `>` at a time. So no token is ever split, +#! and the tokens of a file are always those the lexer made. +pub struct lexer { + var source: &source; #! The file being lexed. + var names: &mut names; #! The names it interns words into. + var holes: stack; #! The holes of interpolated strings it is within, innermost on top. + var text: *u8; #! The bytes of the source's text, read where they are. + var size: u32; #! How many bytes the text holds. + var file: u32; #! The index of the file, which its notes give. + var index: u32; #! The byte it is at. + var within: u32; #! Where the `>` operator the index is within ends, past which none of its tokens reach. + var name: u32; #! The ID of the last word scanned. + + # Where what it finds wrong is noted, which `max_notes` bounds: kept, or + # heard as it is made, as where another thread reports it. + pub var sink: note_sink; #! Where what it finds wrong is noted. +} + +#! A hole of an interpolated string that the lexer is within. +#! +#! The braces opened within the hole are counted, so that the `}` closing it is +#! told apart from one closing a block or a struct literal inside it. +pub struct lexer::hole { + var braces: u32; #! How many braces are open within it. + var block: bool; #! Whether its string is a text block, `$"""`. + var text: u32; #! Where the text of the string begins, past its `$"` or `$"""`. +} + +#! The maximum depth that the lexer allows the nesting of interpolated strings. +pub const lexer::max_depth := 16; + +#! The most notes the lexer makes for one file. +pub const lexer::max_notes: u32 = 100; + +#! Creates a new lexer from the provided source and names references. +#! @param source The source that this lexer will be tokenizing. +#! @param names A place to store and track already known names. +#! @param notes Where the lexer reports what is wrong with the text. +#! @param file The index of the file the source is. +#! @returns The instantiated lexer. +pub def lexer::new( + source: &source, + names: &mut names, + notes: &mut vector, + file: u32 +): lexer { + return lexer { + source = source, + names = names, + sink = note_sink::new(notes, lexer::max_notes), + holes = stack::::new(), + text = source.text.view().data, + size = source.length as u32, + file = file + }; +} + +#! Tokenizes the whole source into the syntax, through the `eof` that ends it, +#! with the comments and documentation lines written before each token. +#! @param this The lexer. +#! @param syntax The syntax the tokens and comments are written to. +pub def lexer::tokenize_all(&mut this, syntax: &mut syntax): void { + syntax.reserve_for_text(this.size); + while true { + this.skip_fluff(syntax); + this.name = 0; + + val start := this.index; + val kind := this.scan(); + if kind == tk::unknown { + this.report(start, this.index - start, ec::token, "The character is no part of the language."); + continue; + } + + # What follows the first `>` of an operator is read again, as the tokens of + # what is left of it. + val end := this.index; + if kind.has(tt::angle) && end - start > 1 { + this.within = end; + this.index = start + 1; + } + + syntax.add_token(kind, start, end - start, this.name); + break if kind == tk::eof; + } + syntax.fit_tokens(); +} + +val lexer::curr: u8 { get => this.peek(0); } +val lexer::next: u8 { get => this.peek(1); } +val lexer::ahead: u8 { get => this.peek(2); } +val lexer::eof: bool { get => this.index >= this.size; } +val lexer::eol: bool { get => this.eof || this.curr.is_eol; } + +#! Whether the current byte is of the class. +#! @param this The lexer. +#! @param class The class of byte. +#! @returns Whether it is. +def lexer::curr_is(&this, class: cc): bool { + return (char_classes[this.curr as u64] & class as u8) != 0; +} + +val lexer::at_block_quote: bool { + get { + return this.curr.is_dquote && + this.next.is_dquote && + this.ahead.is_dquote; + } +} + +val lexer::in_line_hole: bool { + get { + return this.holes.length > 0 && + !this.holes.peek().block; + } +} + +def lexer::advance(&mut this): void { + if this.index < this.size { + this.index++; + } +} + +def lexer::advance_for(&mut this, count: u64): void { + for _ in 0..count { this.advance(); } +} + +def lexer::skip_line(&mut this): void { + val text := this.text; + val size := this.size; + var at := this.index; + # Sixteen bytes at a time while none is `\n` where vectors are held in + # registers, then eight, as `source::find_lines` finds them. + if lanes_held() { + val newline := u8x16::splat('\n'); + while at + 16 <= size { + val chunk: u8x16 = *((text + at) as *u8x16); + val marks := chunk.equal(&newline).bits(); + if marks != 0 { + this.index = at + trailing_zeros(marks); + return; + } + at += 16; + } + } + while at + 8 <= size { + val word := *((text + at) as *u64) ^ 0x0A0A0A0A0A0A0A0A; + break if ((word - 0x0101010101010101) & ~word & 0x8080808080808080) != 0; + at += 8; + } + while at < size && text[at] != '\n' { + at++; + } + this.index = at; +} + +#! Skips spacing and comments, keeping each comment in the syntax: a `#!` line +#! as documentation, and any other as a comment, each for the token after it. +#! @param this The lexer. +#! @param syntax The syntax the comments are written to. +def lexer::skip_fluff(&mut this, syntax: &mut syntax): void { + # The index is held here, and written back for a comment and where it ends. + val text := this.text; + val size := this.size; + var at := this.index; + while at < size { + val byte: u8 = text[at]; + if (char_classes[byte as u64] & cc::space as u8) != 0 { + at++; + continue; + } + + break if !byte.is_cmnt; + val start := at; + this.index = at; + this.skip_line(); + at = this.index; + + val token := syntax.token_count as u32; + val length := at - start; + if this.byte_at(start + 1) == '!' { + syntax.docs.append(doc { offset = start, length = length, token = token }); + } else { + syntax.comments.append(comment { offset = start, length = length, token = token }); + } + } + this.index = at; +} + +def lexer::peek(&this, offset: u32): u8 { + val index := this.index + offset; + return index < this.size ? this.text[index] : '\0'; +} + +#! The byte of the source text at the offset, or `\0` past its end. +#! @param this The lexer. +#! @param offset The byte's offset. +#! @returns The byte. +def lexer::byte_at(&this, offset: u32): u8 { + return offset < this.size ? this.text[offset] : '\0'; +} + +def lexer::scan(&mut this): tk { + return tk::eof if this.eof; + + val byte := this.curr; + val class := char_classes[byte as u64]; + return this.close_hole() if byte.is_eol && this.in_line_hole; + return this.scan_word() if (class & cc::start as u8) != 0; + return this.scan_number() if (class & cc::digit as u8) != 0; + return this.scan_quoted('\"', this.at_block_quote) if byte.is_dquote; + return this.scan_quoted('\'', false) if byte.is_squote; + return this.scan_istring() if byte.is_format && this.next.is_dquote; + return this.scan_brace() if this.holes.length != 0 && byte.is_brace; + return this.scan_foreign() if byte >= 0x80; + return this.scan_punct(); +} + +def lexer::scan_word(&mut this): tk { + val start := this.index; + val text := this.text; + val size := this.size; + var at := start; + while at < size && (char_classes[text[at] as u64] & cc::word as u8) != 0 { + at++; + } + this.index = at; + + val lex := strview::over(text + start, (at - start) as u64); + val id := this.names.intern(&lex); + this.name = id; + return id <= tk::kw_end as u32 ? id as tk : tk::name; +} + +def lexer::scan_number(&mut this): tk { + var base: u8 = 10; + var valid: bool = true; + var start: u32 = this.index; + if this.curr.is_zero { + base = match this.next { + 'x' => 16, + 'o' => 8, + 'b' => 2, + else => 10 + }; + } + + var sym := tk::signed; + if base != 10 { + this.advance(); + this.advance(); + while this.curr.is_base_digit(base) { + this.advance(); + } + valid = this.index > start + 2; + + # `u` makes an integer unsigned, in any base: `0xFFu`. + if this.curr == 'u' { + sym = tk::unsigned; + this.advance(); + } + } else { + while this.curr_is(cc::digit) { this.advance(); } + if this.curr.is_dot && this.next.is_digit { + sym = tk::float; + this.advance(); + while this.curr_is(cc::digit) { + this.advance(); + } + } + + # An exponent makes a float too: `e` or `E`, an optional sign, then digits, as + # `6.02e23` and `1e-9`. An `e` without digits after it is left to the check below. + val signed := this.next == '+' || this.next == '-'; + val digit := signed ? this.ahead.is_digit : this.next.is_digit; + if (this.curr == 'e' || this.curr == 'E') && digit { + sym = tk::float; + this.advance(); + if signed { + this.advance(); + } + while this.curr_is(cc::digit) { + this.advance(); + } + } + + # A fraction cannot be unsigned, so `1.5u` is left to the check below. + if this.curr == 'f' { + sym = tk::float; + this.advance(); + } else if this.curr == 'u' && sym != tk::float { + sym = tk::unsigned; + this.advance(); + } + } + + if this.curr_is(cc::word) { + valid = false; + while this.curr_is(cc::word) { + this.advance(); + } + } + + return sym if valid; + this.report(start, this.index - start, ec::token, + "The number is malformed, as a digit outside its base or letters after it."); + return tk::bad_number; +} + +def lexer::scan_istring(&mut this): tk { + val start := this.index; + this.advance(); + val block := this.at_block_quote; + this.advance_for(block ? 3 : 1); + + val text := this.index; + val stop := this.scan_text(block); + return this.open_hole(block, text) if stop == tk::lbrace; + if stop != tk::string { + return this.unclosed(start); + } + + if block { + this.check_block(text, this.index - 3); + } + return tk::istring; +} + +def lexer::scan_quoted(&mut this, quote: u8, block: bool): tk { + val start := this.index; + val quotes: u64 = block ? 3 : 1; + this.advance_for(quotes); + + # A character literal holds one character, which is one or more bytes, or one + # escape, so what it holds is counted as it is read. + var count: u32 = 0; + while true { + # A string's bytes are passed eight at a time to the next that may end it, + # since only a character literal counts what it holds. + if quote == '"' { + this.index = quoted_run(this.text, this.index, this.size, false); + } + return this.unclosed(start) if this.eof; + return this.unclosed(start) if this.eol && !block; + + # Happy path break aways. + break if block && this.at_block_quote; + break if !block && this.curr == quote; + + if !this.curr.is_continuation { + count++; + } + + if this.curr.is_escape { + this.check_escape(); + } else { + this.advance(); + } + } + + val end := this.index; + this.advance_for(quotes); + if quote == '\'' && count != 1 { + this.report(start, this.index - start, ec::char, + "Character literals must contain exactly one character or escape."); + } + + if block { + this.check_block(start + 3, end); + } + + return match quote { + '\"' => tk::string, + '\'' => tk::char, + else => tk::unknown + }; +} + +def lexer::scan_brace(&mut this): tk { + val hole := &mut this.holes.peek(); + if this.curr.is_lbrace { + hole.braces++; + return this.scan_punct(); + } + + if hole.braces != 0 { + hole.braces--; + return this.scan_punct(); + } + + val start := this.index; + this.advance(); + val stop := this.scan_text(hole.block); + return tk::istring_mid if stop == tk::lbrace; + if stop != tk::string { + this.unclosed(start); + return this.close_hole(); + } + + if hole.block { + this.check_block(hole.text, this.index - 3); + } + return this.close_hole(tk::istring_end); +} + +#! Reads the text of an interpolated string through the `{` opening a hole, or +#! through its closing quotes. +#! @param this The lexer. +#! @param block Whether the text is a text block, `"""`. +#! @returns `lbrace` at a hole, `string` at its end, or `bad_quote` where it is +#! never closed. +def lexer::scan_text(&mut this, block: bool): tk { + while true { + this.index = quoted_run(this.text, this.index, this.size, true); + return tk::bad_quote if this.eof; + return tk::bad_quote if this.eol && !block; + if block && this.at_block_quote { + this.advance_for(3); + return tk::string; + } + + if this.curr.is_escape { + this.check_escape(); + continue; + } + + val curr := this.curr; + this.advance(); + return tk::string if !block && curr.is_dquote; + return tk::lbrace if curr.is_lbrace; + } + + return tk::bad_quote; +} + +#! Where the bytes of quoted text from a place stop needing a look one at a +#! time: at the next `"`, `\`, line break, or, in interpolated text, `{`, found +#! eight bytes at a time. Fewer than eight left are looked at one at a time. +#! @param text The source's bytes. +#! @param from Where to begin. +#! @param size How many bytes the source has. +#! @param holes Whether `{` opens a hole, as in interpolated text. +#! @returns Where the first such byte is, or where fewer than eight are left. +def quoted_run(text: *u8, from: u64, size: u64, holes: bool): u32 { + var at := from; + while at + 8 <= size { + val word := swar::load(text + at); + var stops: swar::mask8 = word.equal('"') | word.equal('\\') | word.equal('\n'); + if holes { + stops = stops | word.equal('{'); + } + return (at + stops.first()) as u32 if stops.any(); + at += 8; + } + return at as u32; +} + +#! Reports text that begins at `start` and is never closed. +#! @param this The lexer. +#! @param start Where the text begins. +#! @returns `bad_quote`. +def lexer::unclosed(&mut this, start: u32): tk { + this.report(start, 1, ec::token, "The text is not closed before the end of its line, or of the file."); + return tk::bad_quote; +} + +#! Moves past the escape at the current `\`, reporting it where it is not one of +#! the language's. +#! @param this The lexer. +def lexer::check_escape(&mut this): void { + val start := this.index; + this.advance(); + if this.eol { + this.report(start, 1, ec::escape, "Valid escapes are \\n, \\t, \\r, \\0, \\\\, \\', \\\", \\{, \\}, and \\xHH."); + return; + } + + val which := this.curr; + this.advance(); + match which { + 'n', 't', 'r', '0', '\\', '\'', '\"', '{', '}' => return; + 'x' => { + if this.curr.is_base_digit(16) && this.next.is_base_digit(16) { + this.advance_for(2); + return; + } + } + } + + this.report(start, 2, ec::escape, "Valid escapes are \\n, \\t, \\r, \\0, \\\\, \\', \\\", \\{, \\}, and \\xHH."); +} + +#! Checks how text spanning lines is laid out, between `text`, past the quotes +#! opening it, and `end`, where the quotes closing it begin. +#! +#! Nothing but the line break follows the opening quotes, the closing quotes +#! stand on a line of their own, and every line of the text is indented at least +#! as far as they are, or holds only whitespace, since that much is taken off. +#! @param this The lexer. +#! @param text Where the text begins, past the quotes opening it. +#! @param end Where the quotes closing it begin. +def lexer::check_block(&mut this, text: u32, end: u32): void { + var first := text; + while first < end && this.byte_at(first).is_blank { first++; } + if first == end || !this.byte_at(first).is_eol { + this.report(text - 3, 3, ec::block, + "The text of a block begins on the line below the `\"\"\"` that opens it, so nothing else is written there."); + return; + } + + var last := end; + while last > first && !this.byte_at(last - 1).is_eol { last--; } + for at in last..end { + if !this.byte_at(at as u32).is_blank { + this.report(last, end - last + 3, ec::block, + "The `\"\"\"` that closes a block is written on a line of its own, and how far it is indented is how far its text is."); + return; + } + } + + val indent := end - last; + var line := first + 1; + while line < last { + var stop := line; + while stop < last && !this.byte_at(stop).is_eol { stop++; } + + var at := line; + while at < stop && at - line < indent && this.byte_at(at).is_blank { at++; } + if at < stop && at - line < indent { + this.report(line, stop - line, ec::block, + "This line is indented less than the `\"\"\"` that closes the block, so the block cannot take that much off it."); + return; + } + line = stop + 1; + } +} + +#! A punctuator, as long as it can be. One within a `>` operator ends where the +#! operator does, as what is left of it. +#! @param this The lexer. +#! @returns The punctuator's kind, or `unknown` where no punctuator begins +#! there. +def lexer::scan_punct(&mut this): tk { + val limit := this.index < this.within ? this.within : this.size; + val text := this.text; + var at := this.index; + var kind: tk = punct_firsts[text[at] as u64]; + at++; + while (punct_longer[kind as u64] & 1) != 0 && at < limit { + val longer := kind.from(text[at]); + break if longer == tk::unknown; + kind = longer; + at++; + } + this.index = at; + return kind; +} + +#! The punctuator each byte begins, worked out while compiling, or `unknown`. +const punct_firsts: tk[256] = make_punct_firsts(); + +#! Whether each kind of token is a punctuator a byte may make longer, as `1`. +const punct_longer: u8[tk::count as u64] = make_punct_longer(); + +const def make_punct_firsts(): tk[256] { + var made: tk[256]; + for each in 0..256 { + made[each] = tk::unknown.from(each as u8); + } + return made; +} + +const def make_punct_longer(): u8[tk::count as u64] { + var made: u8[tk::count as u64]; + for kind in 0..tk::count as u64 { + continue if kind == tk::unknown as u64; + for each in 0..256 { + if (kind as tk).from(each as u8) != tk::unknown { + made[kind] = 1; + } + } + } + return made; +} + +#! A character beyond ASCII, which the language has no use for outside text and +#! comments. All of its bytes are read, so it is reported once. +#! @param this The lexer. +#! @returns `unknown`. +def lexer::scan_foreign(&mut this): tk { + this.advance(); + while this.curr.is_continuation { + this.advance(); + } + return tk::unknown; +} + +def lexer::open_hole( + &mut this, + block: bool, + text: u32 +): tk { + if this.holes.length == lexer::max_depth { + this.report(text, 1, ec::token, "Interpolated strings are nested within each other's holes too deeply."); + return tk::bad_quote; + } + + this.holes.push(lexer::hole { + braces = 0, + block = block, + text = text + }); + return tk::istring_beg; +} + +def lexer::close_hole( + &mut this, + kind: tk = tk::bad_quote +): tk { + this.holes.pop(); + return kind; +} + +#! Reports what is wrong with the text from `offset`, for `length` bytes. +#! @param this The lexer. +#! @param offset Where the text begins. +#! @param length How many bytes it covers. +#! @param code What kind of mistake it is. +#! @param detail What the note says. +def lexer::report(&mut this, offset: u32, length: u32, code: ec, detail: strview): void { + return if !this.sink.admits(); + var made := note { + file = this.file, + offset = offset, + length = length, + code = code, + detail = string::from(detail, nothing {}), + lexed = true + }; + this.sink.give(&mut made); +} diff --git a/analyzer/libraries.sakura b/analyzer/libraries.sakura new file mode 100644 index 00000000..f84503d3 --- /dev/null +++ b/analyzer/libraries.sakura @@ -0,0 +1,756 @@ +#! @file libraries.sakura +#! @author John Christman (sorakatadzuma@gmail.com) +#! @copyright Malunal Studios, LLC. +#! @license MIT +#! +#! Contains how the files of a program's libraries are found: those of each +#! module its files refer to, and of each module those refer to, until nothing +#! new is, so a program reads the modules it uses and none it does not. +#! +#! A library is a folder, and its modules are its folders and files by their +#! paths: in the library `std`, the module `std::a::b` is the folder `a/b`, or +#! the one file `a/b.sakura`, and the root `std` is the folder itself. A file or +#! folder within a module's folder belongs to it where its first `module` line +#! says so, and is otherwise a module of its own, as `std/testing.sakura` and +#! `std/io/` are; a folder is of each module a file within it is of. +#! +#! A library's name is the module its folder is, which may be within another, +#! as `std::yaml` or `sakura::analyzer`. A module is found in the library whose +#! name is the most of its path, so the library `std::yaml` holds `std::yaml` +#! and what is within it, and `std` the rest of `std`. A module holding a +#! library and in none itself, as `sakura` of `sakura::analyzer`, has no files. +#! +#! A file refers to each module it imports, to the modules its sections are +#! of and those holding them, whose names it sees, and to the module each path +#! it writes begins with, as `system` of `system::fd` or `std::io` of +#! `std::io::println`. A path's first segment is found as name lookup finds a +#! module: within the module the file is of or one holding it, then a library. +#! A segment naming no module's folder or file, as a type's, reads nothing. + +import std::io; +import system; +import std::containers; +module sakura::analyzer; + + +#! A library a program may read: its name, which its root module is, and its +#! folder. +pub struct library { + pub var name: string; #! The library's name, as `std` or `std::yaml`. + pub var folder: string; #! Its folder. + pub var whole: bool; #! Whether it is read whole, as `core` is, rather than by what refers to it. +} + +#! What finds the files of the modules a program's files refer to, keeping +#! which it found, so each file is read once. +pub struct resolver { + var libraries: vector; #! The libraries modules are found in. + var files: dict; #! The files found or read before, by path. + var modules: dict; #! The modules whose files were found, by path, as `std::io`. + var exists: dict; #! Whether each module looked for has a file or folder of its own, by path. + + # The paths files write, by the IDs of their names, as a tree, the empty path + # first: what was worked out of each is kept with it. + var paths: vector; #! Each path written, by its node. + var path_ids: keymap; #! Each path's node, by its parent's and its last name's: `parent << 32 | name`. +} + +#! A path a file writes, as the tree of them holds it: the path without its +#! last name, the name, and what was worked out of it. +struct module_path { + var parent: u32; #! The node of the path without its last name. + var name: u32; #! The ID of its last name. + var depth: u32; #! How many names it has. + var named: u8; #! Whether it names a module: 0 not yet asked, 1 where it does not, and 2 where it does. + var found: bool; #! Whether the files of the module it names were found. +} + +#! Makes a resolver of no library yet, which has found nothing. +#! @returns The resolver. +pub def resolver::new(): resolver { + var made := resolver { + libraries = vector::::new(), + files = dict::::new(), + modules = dict::::new(), + exists = dict::::new(), + paths = vector::::new(), + path_ids = keymap::new() + }; + # The empty path, which every path is within. + made.paths.append(module_path {}); + return made; +} + +#! Adds a library modules are found in, unless one of its name was added +#! before, which is the one found by the name. +#! @param this The resolver. +#! @param name The library's name, as `std` or `std::yaml`. +#! @param folder Its folder. +pub def resolver::add_library(&mut this, name: strview, folder: strview): void { + return if this.library_of(name) is some(_); + this.libraries.append(library { name = string::from(name, nothing {}), folder = string::from(folder, nothing {}) }); +} + +#! Adds a library read whole, as `core` is, whose files the caller reads, so +#! none is found by what refers to it. +#! @param this The resolver. +#! @param name The library's name. +#! @param folder Its folder. +pub def resolver::whole(&mut this, name: strview, folder: strview): void { + return if this.library_of(name) is some(_); + this.libraries.append(library { + name = string::from(name, nothing {}), folder = string::from(folder, nothing {}), whole = true + }); +} + +#! The libraries modules are found in. +#! @param this The resolver. +#! @returns A copy of each. +pub def resolver::held(&this): vector { + var made := vector::::new(); + for &each in this.libraries { + made.append(library { name = string::copy_of(&each.name), folder = string::copy_of(&each.folder), whole = each.whole }); + } + return made; +} + +#! How many files the libraries not read whole hold, which is the most what +#! refers to them can bring. +#! @param this The resolver. +#! @returns How many. +pub def resolver::files_held(&this): u64 { + var total: u64 = 0; + for &each in this.libraries { + total += each.whole ? 0 : count_files(each.folder.view()); + } + return total; +} + +#! Notes a file read whatever it refers to, as a program's own and `core`'s +#! are, so no module brings it again. +#! @param this The resolver. +#! @param path The file's path. +pub def resolver::mark(&mut this, path: strview): void { + this.files.set(string::from(path, nothing {}), true); +} + +#! Finds the files of a module asked for by its path, as `runtime` is for +#! an executable, and of the modules holding it. +#! @param this The resolver. +#! @param wanted The module's path. +#! @param into Where the paths of the files not found before are added. +pub def resolver::want(&mut this, wanted: strview, into: &mut vector): void { + var segments := vector::::new(); + for piece in wanted.split(':') { + continue if piece.length == 0; + segments.append(string::from(piece, nothing {})); + } + for count in 1..segments.length + 1 { + this.find_module(segments.view()[0:count], into); + } +} + +#! Finds the files of the modules a file refers to: those it imports, those its +#! sections are of and those holding them, and the module each path it writes +#! begins with. +#! +#! Each path is looked for by the IDs of its names, in a tree of the paths every +#! file wrote, so a path written again, in this file or another, is looked for +#! once, and its text is made only where it is asked whether it names a module. +#! @param this The resolver. +#! @param syntax The file, parsed. +#! @param names The names it was read with, which are those of every file +#! the resolver is given. +#! @param into Where the paths of the files not found before are added, in +#! the order they are first referred to. +pub def resolver::refer(&mut this, syntax: &syntax, names: &names, into: &mut vector): void { + # The modules its sections are of, whose names, and those of the modules + # holding them, the file sees. + var homes := vector::::new(); + for node in 0..syntax.node_count { + val kind: nk = syntax.node_kinds[node]; + continue if kind != nk::module_decl && kind != nk::extern_module; + val made := this.path_node(syntax, syntax.node_lefts[node]); + continue if made == 0; + this.find_prefixes(made, names, into); + homes.append(made); + } + + # A file writes the same paths again and again, as `nk::name`, so each is + # found once, by its node. + var tried := keymap::new(); + for node in 0..syntax.node_count { + val kind: nk = syntax.node_kinds[node]; + var path: u32 = 0; + if kind == nk::import_decl { + path = syntax.node_lefts[node]; + } else if kind == nk::path || kind == nk::type_name { + continue if syntax.node_lefts[node] == 0 || syntax.extras[syntax.node_lefts[node]] < 2; + path = node as u32; + } + continue if path == 0; + val written := this.path_node(syntax, path); + continue if written == 0 || !tried.insert(written as u64, 1); + this.find_path(written, homes.view(), names, into); + } +} + +#! The node of the path of a `path`, `type_name`, or `name` node's segments, +#! made where it is new. +#! @param this The resolver. +#! @param syntax The file. +#! @param node The node, or 0. +#! @returns The path's node, or 0 where the node is none of those. +def resolver::path_node(&mut this, syntax: &syntax, node: u32): u32 { + return 0 if node == 0; + val kind: nk = syntax.node_kinds[node]; + return 0 if kind != nk::path && kind != nk::type_name && kind != nk::name; + val run: u32 = syntax.node_lefts[node]; + if kind == nk::name || run == 0 { + return this.child(0, syntax.token_names[syntax.node_tokens[node]]); + } + var at: u32 = 0; + val count: u32 = syntax.extras[run]; + for i in 0..count { + val segment: u32 = syntax.extras[run as u64 + 1 + i]; + at = this.child(at, syntax.token_names[syntax.node_tokens[segment]]); + } + return at; +} + +#! The node of the path that is another's with one more name, made where it is +#! new. +#! @param this The resolver. +#! @param parent The other path's node, 0 for the empty path. +#! @param name The name's ID. +#! @returns The node. +def resolver::child(&mut this, parent: u32, name: u32): u32 { + val key := pair_key(parent, name); + val held := this.path_ids.get_or(&key, 0); + return held if held != 0; + val made := this.paths.length as u32; + this.paths.append(module_path { parent = parent, name = name, depth = this.paths[parent].depth + 1 }); + this.path_ids.set(key, made); + return made; +} + +#! The names of a path, by their text, its first first. +#! @param this The resolver. +#! @param node The path's node. +#! @param names The names its IDs are of. +#! @returns The names. +def resolver::segments_of(&this, node: u32, names: &names): vector { + var made := vector::::new(); + made.resize(this.paths[node].depth as u64); + var at := node; + while at != 0 { + val held: module_path = this.paths[at]; + made[held.depth as u64 - 1] = string::from(names.text(held.name), nothing {}); + at = held.parent; + } + return made; +} + +#! Whether a path names a module, as `module_exists` says, asked once. +#! @param this The resolver. +#! @param node The path's node. +#! @param names The names its IDs are of. +#! @returns Whether it does. +def resolver::names_module(&mut this, node: u32, names: &names): bool { + if this.paths[node].named == 0 { + val segments := this.segments_of(node, names); + this.paths[node].named = this.module_exists(segments.view()) ? 2 : 1; + } + return this.paths[node].named == 2; +} + +#! Finds the files of the module a path names, once. +#! @param this The resolver. +#! @param node The path's node. +#! @param names The names its IDs are of. +#! @param into Where the paths of the files not found before are added. +def resolver::find_node(&mut this, node: u32, names: &names, into: &mut vector): void { + return if this.paths[node].found; + this.paths[node].found = true; + val segments := this.segments_of(node, names); + this.find_module(segments.view(), into); +} + +#! Finds the files of the modules a path and each path that begins it name, the +#! shortest first, as a file's `module` line refers to them. +#! @param this The resolver. +#! @param node The path's node. +#! @param names The names its IDs are of. +#! @param into Where the paths of the files not found before are added. +def resolver::find_prefixes(&mut this, node: u32, names: &names, into: &mut vector): void { + var chain := vector::::new(); + var at := node; + while at != 0 { + chain.append(at); + at = this.paths[at].parent; + } + var i := chain.length; + while i > 0 { + i--; + this.find_node(chain[i], names, into); + } +} + +#! Finds the files of the modules a path names as many of its names as name +#! modules: from the first, within a module the file is of or one holding it, +#! nearest first, then as a library. +#! @param this The resolver. +#! @param written The path's node. +#! @param homes The nodes of the modules the file's sections are of. +#! @param names The names its IDs are of. +#! @param into Where the paths of the files not found before are added. +def resolver::find_path(&mut this, written: u32, homes: span, names: &names, into: &mut vector): void { + # The path's names, its first first. + var rest := vector::::new(); + rest.resize(this.paths[written].depth as u64); + var at := written; + while at != 0 { + rest[this.paths[at].depth as u64 - 1] = this.paths[at].name; + at = this.paths[at].parent; + } + return if rest.length == 0; + + for &home in homes { + var holder := home; + while holder != 0 { + val tried := this.child(holder, rest[0]); + if this.names_module(tried, names) { + this.find_deeper(tried, rest.view()[1:], names, into); + return; + } + holder = this.paths[holder].parent; + } + } + + val tried := this.child(0, rest[0]); + return if !this.names_module(tried, names); + this.find_deeper(tried, rest.view()[1:], names, into); +} + +#! Finds the files of a module the path's first name found, then of those +#! within it its next names name, while they name any. +#! @param this The resolver. +#! @param found The node of the module found, which grows by each name. +#! @param rest The IDs of the path's names after the first. +#! @param names The names its IDs are of. +#! @param into Where the paths of the files not found before are added. +def resolver::find_deeper(&mut this, found: u32, rest: span, names: &names, into: &mut vector): void { + this.find_node(found, names, into); + var at := found; + for &name in rest { + at = this.child(at, name); + return if !this.names_module(at, names); + this.find_node(at, names, into); + } +} + +#! The library of a name, or none. +#! @param this The resolver. +#! @param name The name. +#! @returns The library's index, or none. +def resolver::library_of(&this, name: strview): maybe { + for i in 0..this.libraries.length { + return i if this.libraries[i].name.view() == name; + } + return nothing {}; +} + +#! The library a module is found in, and how much of its path the library's +#! name is. +struct shelf { + var index: u64; #! The library's index. + var depth: u64; #! How many of the module's segments its name is. +} + +#! The library a module is found in: the one whose name is the most of the +#! module's path, from its start. +#! @param this The resolver. +#! @param segments The module's path. +#! @returns The library, or none where no library's name begins the path. +def resolver::library_for(&this, segments: span): maybe { + var found: u64 = 0; + var deepest: u64 = 0; + for i in 0..this.libraries.length { + val depth := covered(this.libraries[i].name.view(), segments); + if depth > deepest { + found = i; + deepest = depth; + } + } + return nothing {} if deepest == 0; + return shelf { index = found, depth = deepest }; +} + +#! Whether a module holds a library within it, as `sakura` holds +#! `sakura::analyzer`. +#! @param this The resolver. +#! @param segments The module's path. +#! @returns Whether it does. +def resolver::holds_library(&this, segments: span): bool { + for &each in this.libraries { + return true if holds(each.name.view(), segments); + } + return false; +} + +#! How many of a module's segments a library's name is, where the name is the +#! module's path or its start, as `std::yaml` is two of `std::yaml::text`. +#! @param name The library's name. +#! @param segments The module's path. +#! @returns How many, or 0 where the name does not begin the path. +def covered(name: strview, segments: span): u64 { + var at: u64 = 0; + for count in 0..segments.length { + val piece := segments[count].view(); + return 0 if name.length - at < piece.length || name.substr(at, piece.length) != piece; + at += piece.length; + return count + 1 if at == name.length; + return 0 if name.length - at < 2 || name[at] != ':' || name[at + 1] != ':'; + at += 2; + } + return 0; +} + +#! Whether a library's name is within a module, as `sakura::analyzer` is within +#! `sakura`. +#! @param name The library's name. +#! @param segments The module's path. +#! @returns Whether it is. +def holds(name: strview, segments: span): bool { + var at: u64 = 0; + for &each in segments { + val piece := each.view(); + return false if name.length - at < piece.length + 2 || name.substr(at, piece.length) != piece; + at += piece.length; + return false if name[at] != ':' || name[at + 1] != ':'; + at += 2; + } + return segments.length != 0; +} + +#! Whether a module's path names a library, or a folder or file within one of +#! that module, as its first `module` line says, or holds a library. Each is +#! looked at once. +#! @param this The resolver. +#! @param segments The module's path. +#! @returns Whether it does. +def resolver::module_exists(&mut this, segments: span): bool { + val found := this.library_for(segments) else { return this.holds_library(segments); }; + return true if segments.length == found.depth; + var key := module_key(segments); + if this.exists.get(&key) is some(&known) { + return known; + } + var at := this.within(&found, segments); + var named := is_folder(at.view()) && folder_of(at.view(), key.view()); + if !named { + at.append(".sakura"); + named = is_file(at.view()) && first_module(at.view()).view() == key.view(); + } + named = named || this.holds_library(segments); + this.exists.set(move(&mut key), named); + return named; +} + +#! A module's path as text, as `std::io`. +#! @param segments The path's segments. +#! @returns The text. +def module_key(segments: span): string { + var made := string::new(nothing {}); + for i in 0..segments.length { + if i != 0 { + made.append("::"); + } + made.append(segments[i].view()); + } + return made; +} + +#! The path of a module's folder within its library, as `std/io` of `std::io`. +#! @param this The resolver. +#! @param found The library, and how much of the path its name is. +#! @param segments The module's path, its library first. +#! @returns The path. +def resolver::within(&this, found: &shelf, segments: span): string { + var made := string::copy_of(&this.libraries[found.index].folder); + for i in found.depth..segments.length { + made.push('/'); + made.append(segments[i].view()); + } + return made; +} + +#! Finds the files of a module, once: its file, as `a/b.sakura`, and those of +#! its folder, as `a/b`, that are of the module, with the folders within it +#! that are. +#! @param this The resolver. +#! @param segments The module's path. +#! @param into Where the paths of the files not found before are added. +def resolver::find_module(&mut this, segments: span, into: &mut vector): void { + val found := this.library_for(segments) else { return; }; + return if this.libraries[found.index].whole; + var key := module_key(segments); + return if this.modules.get(&key) is some(_); + this.modules.set(string::copy_of(&key), true); + + var at := this.within(&found, segments); + if segments.length > found.depth { + var file := $"{at}.sakura"; + if is_file(file.view()) && first_module(file.view()).view() == key.view() { + this.add_file(file.view(), into); + } + } + if is_folder(at.view()) { + this.find_in_folder(at.view(), key.view(), into); + } +} + +#! Finds the files of a folder that are of a module, and those of the folders +#! within it that are, each in the order of its name. +#! @param this The resolver. +#! @param folder The folder. +#! @param of The module's path, as `std::io`. +#! @param into Where the paths of the files not found before are added. +def resolver::find_in_folder(&mut this, folder: strview, of: strview, into: &mut vector): void { + var listed := listing(folder); + for &each in listed { + if each.folder { + if folder_of(each.path.view(), of) { + this.find_in_folder(each.path.view(), of, into); + } + } else if first_module(each.path.view()).view() == of { + this.add_file(each.path.view(), into); + } + } +} + +#! Adds a file's path, unless it was found or read before. +#! @param this The resolver. +#! @param path The path. +#! @param into Where it is added. +def resolver::add_file(&mut this, path: strview, into: &mut vector): void { + var key := string::from(path, nothing {}); + return if this.files.get(&key) is some(_); + this.files.set(string::copy_of(&key), true); + into.append(move(&mut key)); +} + +#! The names of the modules within a module of a library, by its folder, as +#! completion offers them after `std::`, without reading their files whole, +#! with those of the libraries within it, as `yaml` of `std::yaml`. +#! @param libraries The libraries. +#! @param segments The module's path, its library first. +#! @returns The names, as `io` of `std::io`. +pub def modules_within(libraries: span, segments: span): vector { + var made := vector::::new(); + return made if segments.length == 0; + + # The libraries within it give their next segments. + val outer := module_key(segments); + for &each in libraries { + continue if !holds(each.name.view(), segments); + val rest := each.name.view().substr(outer.length + 2, each.name.length - outer.length - 2); + val next := rest.index_of(&':') else rest.length; + val name := rest.substr(0, next); + var known := false; + for &each in made { + known = known || each.view() == name; + } + if !known { + made.append(string::from(name, nothing {})); + } + } + + # Its library's folder gives the rest. + var folder := string::new(nothing {}); + var deepest: u64 = 0; + for &each in libraries { + val depth := covered(each.name.view(), segments); + if depth > deepest { + folder = string::copy_of(&each.folder); + deepest = depth; + } + } + return made if folder.length == 0; + for i in deepest..segments.length { + folder.push('/'); + folder.append(segments[i].view()); + } + for &each in listing(folder.view()) { + # The name is the entry's own, less its `.sakura`. + var name := each.path.view().substr(folder.length + 1, each.path.length - folder.length - 1); + if !each.folder { + name = name.substr(0, name.length - 7); + } + val inner := $"{outer}::{name}"; + val of := each.folder ? folder_of(each.path.view(), inner.view()) : first_module(each.path.view()).view() == inner.view(); + if of { + made.append(string::from(name, nothing {})); + } + } + return made; +} + +#! A name a folder holds: a `.sakura` file or a folder, which hidden ones are +#! not. +struct listed_entry { + var path: string; #! The folder and the name joined. + var folder: bool; #! Whether it is a folder. +} + +#! What a folder holds that a library is read from: its `.sakura` files and +#! its folders, in the order of their names, so the same files are read in the +#! same order whatever order the system lists them in. +#! @param folder The folder. +#! @returns What it holds. +def listing(folder: strview): vector { + var made := vector::::new(); + var at := path::parse(folder) else (_) { return made; }; + var opened := io::directory::open(&at) else (_) { return made; }; + var names := vector::::new(); + var kinds := vector::::new(); + while opened.next() is some(each) { + continue if each.name.length == 0 || each.name[0] == '.'; + var joined := $"{folder}/{each.name}"; + var is_dir := each.kind == file_kind::directory; + if each.kind == file_kind::link { + is_dir = is_folder(joined.view()); + } + continue if !is_dir && !each.name.ends_with(".sakura"); + made.append(listed_entry { path = move(&mut joined), folder = is_dir }); + } + made.sort_by(def(a: &listed_entry, b: &listed_entry): bool { return a.path.compare(b.path.view()) < 0; }); + return made; +} + +#! The paths of every `.sakura` file within a folder and the folders within it, +#! each folder's in the order of their names, as `core` is read whole. +#! @param folder The folder. +#! @param into Where the paths are added. +pub def every_file(folder: strview, into: &mut vector): void { + var listed := listing(folder); + for &mut each in listed { + if each.folder { + every_file(each.path.view(), into); + } else { + into.append(move(&mut each.path)); + } + } +} + +#! How many `.sakura` files are within a folder and those within it, which is +#! the most a program reads of it. +#! @param folder The folder. +#! @returns How many. +pub def count_files(folder: strview): u64 { + var made := vector::::new(); + every_file(folder, &mut made); + return made.length; +} + +#! Whether a folder holds a file of a module, or a folder within it does. Any +#! file says, not only the first by name, so a file of a module within it, as +#! `a/b/c.sakura` of `a::b::c` beside the files of `a::b`, hides nothing. +#! @param folder The folder. +#! @param of The module's path, as `std::io`. +#! @returns Whether it does. +def folder_of(folder: strview, of: strview): bool { + val listed := listing(folder); + for &each in listed { + return true if !each.folder && first_module(each.path.view()).view() == of; + } + for &each in listed { + return true if each.folder && folder_of(each.path.view(), of); + } + return false; +} + +#! The module of a file's first `module` or `extern module` line, read from the +#! start of its text, past its comments and imports. +#! @param at The file's path. +#! @returns The module's path, as `std::io`, or empty where the file declares +#! anything before such a line, or cannot be read. +pub def first_module(at: strview): string { + var found := path::parse(at) else (_) { return string::new(nothing {}); }; + var file := io::file::open(&found) else (_) { return string::new(nothing {}); }; + var buffer: u8[4096]; + val count := file.read(slice::::over((&mut buffer) as *mut u8, 4096)) else (_) { return string::new(nothing {}); }; + var text := strview::over((&buffer) as *u8, count); + var made := module_named(text); + # A file whose first lines run past what was read is read whole. + if made.length == 0 && count == 4096 { + var whole := io::read_file(&found) else (_) { return made; }; + made = module_named(whole.view()); + } + return made; +} + +#! The module the first `module` or `extern module` line of a text names, past +#! its comments, imports, and `extern import` lines. +#! @param text The text. +#! @returns The module's path, or empty where none comes first. +def module_named(text: strview): string { + var at: u64 = 0; + while at < text.length { + val byte := text[at]; + if byte == ' ' || byte == '\t' || byte == '\r' || byte == '\n' { + at++; + continue; + } + if byte == '#' { + while at < text.length && text[at] != '\n' { at++; } + continue; + } + var word := word_at(text, at); + if word == "extern" { + at += word.length; + while at < text.length && (text[at] == ' ' || text[at] == '\t') { at++; } + word = word_at(text, at); + } + if word == "import" { + while at < text.length && text[at] != ';' { at++; } + at++; + continue; + } + break if word != "module"; + at += word.length; + while at < text.length && (text[at] == ' ' || text[at] == '\t') { at++; } + val start := at; + while at < text.length && (text[at].is_alnum || text[at] == '_' || text[at] == ':') { at++; } + return string::from(text.substr(start, at - start), nothing {}); + } + return string::new(nothing {}); +} + +#! The word, letters, digits, and underscores, beginning at a place of a text. +#! @param text The text. +#! @param at The place. +#! @returns The word, which is empty where none begins there. +def word_at(text: strview, at: u64): strview { + var end := at; + while end < text.length && (text[end].is_alnum || text[end] == '_') { end++; } + return text.substr(at, end - at); +} + +#! Whether a path names a file, following a link it ends in. +#! @param at The path. +#! @returns Whether it does. +def is_file(at: strview): bool { + var found := path::parse(at) else (_) { return false; }; + val info := io::info(&found) else (_) { return false; }; + return info.kind == file_kind::regular; +} + +#! Whether a path names a folder, following a link it ends in. +#! @param at The path. +#! @returns Whether it does. +def is_folder(at: strview): bool { + var found := path::parse(at) else (_) { return false; }; + val info := io::info(&found) else (_) { return false; }; + return info.kind == file_kind::directory; +} diff --git a/analyzer/lines.sakura b/analyzer/lines.sakura new file mode 100644 index 00000000..b9998dac --- /dev/null +++ b/analyzer/lines.sakura @@ -0,0 +1,44 @@ +#! @file lines.sakura +#! @author John Christman (sorakatadzuma@gmail.com) +#! @copyright Malunal Studios, LLC. +#! @license MIT +#! +#! Contains `lines`, where each line of a source begins, and `place`, the line +#! and column an offset within the source is at. + +module sakura::analyzer; + +#! Defines a place within a source file. +#! +#! This is useful for diagnostics and debugging, especially within something +#! like a language server protocol. +pub struct place { + pub val line: u32; #! The line, counted from 1. + pub val column: u32; #! The byte within the line, counted from 1. +} + +#! Stores the starting offsets of the lines of a given source file. +#! +#! The length of the `starts` vector is the number of lines in the file and then +#! the value at a given line (index) is the offset within the file that the line +#! starts. +pub type lines = vector; + +#! Provides the place of a given offset within some source code. +#! +#! This is a binary search that will seek out a specific line and then mark the +#! column within the line, given the offset. Lines are stored in order by their +#! offset within the file, so the length of the `starts` vector is the number of +#! lines in the file and the value at that index is the offset within the file. +#! The line is the last starting at or before the offset, the one before the +#! first starting after it; the first line starts at 0, so there is always one. +#! @param this The lines structure to get the place of an offset. +#! @param offset The offset from the file to get the place of. +#! @returns The line and column of the given offset for a given file. +pub def lines::place_of(&this, offset: u32): place { + val low := this.view().upper_bound(&offset) - 1; + return place { + line = (low + 1) as u32, + column = offset - this[low] + 1 + }; +} diff --git a/analyzer/names.sakura b/analyzer/names.sakura new file mode 100644 index 00000000..189d57aa --- /dev/null +++ b/analyzer/names.sakura @@ -0,0 +1,412 @@ +#! @file names.sakura +#! @author John Christman (sorakatadzuma@gmail.com) +#! @copyright Malunal Studios, LLC. +#! @license MIT +#! +#! Contains the table of names, which gives every word written in a source an +#! ID of its own. The keywords are given theirs first, so a keyword's ID is its +#! token kind, and the reserved words and the words the parser knows by ID +#! follow them, in the order their lists give. + +import std::containers; +module sakura::analyzer; + +#! Responsible for keeping and tracking the names of non-punctuator tokens of +#! a given, or multiple, source code file(s). +#! +#! Each name's text is copied into a block of names, so a name outlives the +#! source it was first read in, as one an editor replaces does. A block is +#! filled but never grown, so a name's text stays where it was copied, and its +#! view, by its ID, is good for as long as the table is. A name is found by its +#! text through the IDs of its hash, comparing only those whose hash shares its +#! top half, and those by their length before their bytes. +pub struct names { + var views: vector; #! The text of each name, by its ID, where a block holds it. + var blocks: vector; #! The blocks the texts are copied into, the last being filled. + var index: id_index; #! The names of each hash, which finding a name's ID by its text walks. +} + +#! How many bytes a block of names holds, but for one of a name longer than a +#! sixteenth of that, which is a block of its own. +const names::block_size: u64 = 16384; + +#! Makes a new instance of the `names` structure to be used by the various +#! stages of the Sakura analyzer. +#! @returns The created names instance pre-containing the language keywords. +pub def names::new(): names { + var made := names { + views = vector::::new(), + blocks = vector::::new(), + index = id_index::new() + }; + made.views.reserve(512); + + # The lexer reads a keyword's ID as its token kind, so a list out of step with + # `tk` stops here rather than lexing one word as another. + for &word in _keywords { + val id := made.intern(word.text); + expects(id == word.kind as u32); + } + + # The parser knows these words by where they are interned, which a word listed + # twice would move. + for &word in _reserved { made.intern(word); } + for &word in _words { made.intern(word); } + + # The checker knows these by their members of `word`, which follow those. + for &each in _known { + expects(made.intern(each.text) == each.id); + } + expects(made.intern("this") == names::this_id); + expects(made.intern("get") == names::get_id); + expects(made.intern("set") == names::set_id); + expects(made.intern("type_of") == names::type_of_id); + expects(made.intern("old") == names::old_id); + expects(made.intern("self") == names::self_id); + return made; +} + +#! Maps names that are seen in the source code to a specific integer to reduce +#! copies and save memory. +#! @param this The names instance to copy the name into. +#! @param text The name to copy and mark by an ID. +#! @returns The newly created ID or an existing ID for the given name. +pub def names::intern(&mut this, text: &strview): u32 { + val hash := text.hash(); + var walk := this.index.walk(hash); + var at := this.index.next(&mut walk); + while at != 0 { + return at - 1 if same_text(this.views[at - 1], text); + at = this.index.next(&mut walk); + } + + val id := this.views.length as u32; + this.views.append(this.copy_text(text)); + this.index.add(hash, id); + return id; +} + +# A copy of a name's text in a block, which a new block is made for where the +# last has no room, or where the name is long. +def names::copy_text(&mut this, text: strview): strview { + if text.length * 16 > names::block_size { + this.blocks.append(string::from(text, nothing {})); + return this.blocks.last().view(); + } + if this.blocks.length == 0 || this.blocks.last().length + text.length > this.blocks.last().capacity { + var made := string::new(nothing {}); + made.reserve(names::block_size); + this.blocks.append(move(&mut made)); + } + val block := &mut this.blocks.last(); + val at := block.length; + block.append(text); + return strview::over(block.view().data + at, text.length); +} + +# Whether two texts are the same, their lengths first, then their bytes, a +# word at a time, the last word ending where they do, so a text of a few +# words is compared in as many loads, as `hash_bytes` reads one. +@inline +def same_text(a: strview, b: strview): bool { + val count := a.length; + return false if count != b.length; + val x := a.data; + val y := b.data; + if count >= 8 { + var at: u64 = 0; + while at + 8 < count { + return false if *((x + at) as *u64) != *((y + at) as *u64); + at += 8; + } + return *((x + count - 8) as *u64) == *((y + count - 8) as *u64); + } + if count >= 4 { + return *(x as *u32) == *(y as *u32) && *((x + count - 4) as *u32) == *((y + count - 4) as *u32); + } + if count >= 2 { + return *(x as *u16) == *(y as *u16) && *((x + count - 2) as *u16) == *((y + count - 2) as *u16); + } + return count == 0 || x[0] == y[0]; +} + +#! The text of the name of the ID. +#! @param this The table of names. +#! @param id The name's ID. +#! @returns The text, which lives as long as the table does. +pub def names::text(&this, id: u32): strview { + return this.views[id]; +} + +#! How many names there are. +#! @param this The table of names. +#! @returns The number of names, which is one more than the newest's ID. +pub val names::count: u64 { get => this.views.length; } + +#! Whether a name is one of the language's keywords. +#! @param this The table of names. +#! @param id The name's ID. +#! @returns Whether it is. +pub def names::is_keyword(&this, id: u32): bool { + return id >= tk::kw_beg && id <= tk::kw_end; +} + +#! Determines if the given ID corresponds to one of the language reserved words. +#! @param this The names instance to compare against. +#! @param id The ID of the name to check. +#! @returns Whether the ID belongs to a reserved word. +pub def names::is_reserved(&this, id: u32): bool { + return id >= names::this_id && id < names::get_id; +} + +#! A keyword, and the token kind it lexes as. +struct names::keyword { + val text: strview; + val kind: tk; +} + +const _keywords: names::keyword[31] = [ + names::keyword { text = "import", kind = tk::kw_imp }, + names::keyword { text = "module", kind = tk::kw_mod }, + names::keyword { text = "extern", kind = tk::kw_extern }, + names::keyword { text = "pub", kind = tk::kw_pub }, + names::keyword { text = "const", kind = tk::kw_const }, + names::keyword { text = "var", kind = tk::kw_var }, + names::keyword { text = "val", kind = tk::kw_val }, + names::keyword { text = "def", kind = tk::kw_def }, + names::keyword { text = "mut", kind = tk::kw_mut }, + names::keyword { text = "return", kind = tk::kw_ret }, + names::keyword { text = "if", kind = tk::kw_if }, + names::keyword { text = "else", kind = tk::kw_else }, + names::keyword { text = "for", kind = tk::kw_for }, + names::keyword { text = "in", kind = tk::kw_in }, + names::keyword { text = "while", kind = tk::kw_while }, + names::keyword { text = "break", kind = tk::kw_break }, + names::keyword { text = "continue", kind = tk::kw_cont }, + names::keyword { text = "type", kind = tk::kw_type }, + names::keyword { text = "enum", kind = tk::kw_enum }, + names::keyword { text = "struct", kind = tk::kw_struct }, + names::keyword { text = "union", kind = tk::kw_union }, + names::keyword { text = "trait", kind = tk::kw_trait }, + names::keyword { text = "as", kind = tk::kw_as }, + names::keyword { text = "is", kind = tk::kw_is }, + names::keyword { text = "not", kind = tk::kw_not }, + names::keyword { text = "match", kind = tk::kw_match }, + names::keyword { text = "when", kind = tk::kw_when }, + names::keyword { text = "where", kind = tk::kw_where }, + names::keyword { text = "true", kind = tk::kw_true }, + names::keyword { text = "false", kind = tk::kw_false }, + names::keyword { text = "null", kind = tk::kw_null }, +]; + +# Words that name what the language gives, which nothing may declare. `this` +# comes first, which the parser knows by ID. +const _reserved: strview[18] = [ + "this", "bool", "int", "uint", "float", "i8", "i16", "i32", "i64", + "u8", "u16", "u32", "u64", "f32", "f64", "void", "self", "_" +]; + +# Identifiers the grammar gives a meaning in one place each, which stay names +# everywhere else, so the parser knows them by ID. +const _words: strview[9] = [ + "get", "set", "type_of", "expects", "asserts", "ensures", "old", "undefined", "value" +]; + +#! The IDs of the names the parser reads as words, by where `names::new` interns +#! them: the reserved words right after the keywords, then `_words`. +pub const names::this_id: u32 = tk::kw_end as u32 + 1; #! `this`. +pub const names::get_id: u32 = names::this_id + _reserved.length as u32; #! `get`. +pub const names::set_id: u32 = names::get_id + 1; #! `set`. +pub const names::type_of_id: u32 = names::get_id + 2; #! `type_of`. +pub const names::expects_id: u32 = names::get_id + 3; #! `expects`, a contract at a statement's start. +pub const names::asserts_id: u32 = names::get_id + 4; #! `asserts`, a contract at a statement's start. +pub const names::ensures_id: u32 = names::get_id + 5; #! `ensures`, a contract at a statement's start. +pub const names::old_id: u32 = names::get_id + 6; #! `old`, an earlier value within an `ensures`. +pub const names::undefined_id: u32 = names::get_id + 7; #! `undefined`, a variable's value that opts out of zeroing. +pub const names::value_id: u32 = names::get_id + 8; #! `value`, what a `set` is given. +pub const names::self_id: u32 = names::this_id + 16; #! `self`, among the reserved words. +pub const names::underscore_id: u32 = names::this_id + 17; #! `_`, the last of the reserved words. + +#! The words the checker knows by ID, which `names::new` interns after the +#! parser's, in this order, so each is a constant. A member's name is its word. +pub enum word : u32 { + std = names::value_id + 1, #! `std`. + core, #! `core`, the library of the language's own, whose root every file sees. + system, #! `system`, the library of the platforms. + string, #! `string`. + strview, #! `strview`. + span, #! `span`. + simd, #! `simd`. + mask, #! `mask`. + slice, #! `slice`. + maybe, #! `maybe`. + result, #! `result`. + nothing, #! `nothing`. + equatable, #! `equatable`. + ordered, #! `ordered`. + numeric, #! `numeric`. + integer, #! `integer`. + ordinal, #! `ordinal`. + real, #! `real`. + hashable, #! `hashable`. + owning, #! `owning`. + closeable, #! `closeable`. + zeroable, #! `zeroable`. + lockfree, #! `lockfree`. + pointer, #! `pointer`. + copyable, #! `copyable`. + moveable, #! `moveable`. + indexable, #! `indexable`. + signature, #! `signature`. + params, #! `params`. + invokable, #! `invokable`. + invoke, #! `invoke`. + iterable, #! `iterable`. + iterator, #! `iterator`. + range, #! `range`. + attribute, #! `attribute`. + usage, #! `usage`. + optional, #! `optional`. + intrinsic, #! `intrinsic`. + foreign, #! `foreign`, an attribute C's declarations no longer take. + link, #! `link`, an attribute C's declarations no longer take. + nodiscard, #! `nodiscard`. + allow, #! `allow`. + inline, #! `inline`. + cfn, #! `cfn`. + equals, #! `equals`. + hash, #! `hash`. + compare, #! `compare`. + add, #! `add`. + sub, #! `sub`. + mul, #! `mul`. + div, #! `div`. + rem, #! `rem`. + negate, #! `negate`. + bit_and, #! `bit_and`. + bit_or, #! `bit_or`. + bit_xor, #! `bit_xor`. + bit_not, #! `bit_not`. + shift_left, #! `shift_left`. + shift_right, #! `shift_right`. + add_assign, #! `add_assign`, which `+=` calls where a type has it. + sub_assign, #! `sub_assign`. + mul_assign, #! `mul_assign`. + div_assign, #! `div_assign`. + rem_assign, #! `rem_assign`. + bit_and_assign, #! `bit_and_assign`. + bit_or_assign, #! `bit_or_assign`. + bit_xor_assign, #! `bit_xor_assign`. + shift_left_assign, #! `shift_left_assign`. + shift_right_assign, #! `shift_right_assign`. + close, #! `close`. + at, #! `at`. + iter, #! `iter`. + next, #! `next`. + next_back, #! `next_back`. + length, #! `length`. + data, #! `data`. + view, #! `view`. + main, #! `main`. + some, #! `some`. + none, #! `none`. + error, #! `error`. + os, #! `os`. + arch, #! `arch`. + backend, #! `backend`. +} + +#! A word the checker knows, and its member of `word`. +struct names::known { + val text: strview; + val id: word; +} + +# The text of each word the checker knows, which is its member's name, listed +# as `word` lists them, so `names::new` stops where the two are out of step. +const _known: names::known[84] = [ + names::known { text = "std", id = word::std }, + names::known { text = "core", id = word::core }, + names::known { text = "system", id = word::system }, + names::known { text = "string", id = word::string }, + names::known { text = "strview", id = word::strview }, + names::known { text = "span", id = word::span }, + names::known { text = "simd", id = word::simd }, + names::known { text = "mask", id = word::mask }, + names::known { text = "slice", id = word::slice }, + names::known { text = "maybe", id = word::maybe }, + names::known { text = "result", id = word::result }, + names::known { text = "nothing", id = word::nothing }, + names::known { text = "equatable", id = word::equatable }, + names::known { text = "ordered", id = word::ordered }, + names::known { text = "numeric", id = word::numeric }, + names::known { text = "integer", id = word::integer }, + names::known { text = "ordinal", id = word::ordinal }, + names::known { text = "real", id = word::real }, + names::known { text = "hashable", id = word::hashable }, + names::known { text = "owning", id = word::owning }, + names::known { text = "closeable", id = word::closeable }, + names::known { text = "zeroable", id = word::zeroable }, + names::known { text = "lockfree", id = word::lockfree }, + names::known { text = "pointer", id = word::pointer }, + names::known { text = "copyable", id = word::copyable }, + names::known { text = "moveable", id = word::moveable }, + names::known { text = "indexable", id = word::indexable }, + names::known { text = "signature", id = word::signature }, + names::known { text = "params", id = word::params }, + names::known { text = "invokable", id = word::invokable }, + names::known { text = "invoke", id = word::invoke }, + names::known { text = "iterable", id = word::iterable }, + names::known { text = "iterator", id = word::iterator }, + names::known { text = "range", id = word::range }, + names::known { text = "attribute", id = word::attribute }, + names::known { text = "usage", id = word::usage }, + names::known { text = "optional", id = word::optional }, + names::known { text = "intrinsic", id = word::intrinsic }, + names::known { text = "foreign", id = word::foreign }, + names::known { text = "link", id = word::link }, + names::known { text = "nodiscard", id = word::nodiscard }, + names::known { text = "allow", id = word::allow }, + names::known { text = "inline", id = word::inline }, + names::known { text = "cfn", id = word::cfn }, + names::known { text = "equals", id = word::equals }, + names::known { text = "hash", id = word::hash }, + names::known { text = "compare", id = word::compare }, + names::known { text = "add", id = word::add }, + names::known { text = "sub", id = word::sub }, + names::known { text = "mul", id = word::mul }, + names::known { text = "div", id = word::div }, + names::known { text = "rem", id = word::rem }, + names::known { text = "negate", id = word::negate }, + names::known { text = "bit_and", id = word::bit_and }, + names::known { text = "bit_or", id = word::bit_or }, + names::known { text = "bit_xor", id = word::bit_xor }, + names::known { text = "bit_not", id = word::bit_not }, + names::known { text = "shift_left", id = word::shift_left }, + names::known { text = "shift_right", id = word::shift_right }, + names::known { text = "add_assign", id = word::add_assign }, + names::known { text = "sub_assign", id = word::sub_assign }, + names::known { text = "mul_assign", id = word::mul_assign }, + names::known { text = "div_assign", id = word::div_assign }, + names::known { text = "rem_assign", id = word::rem_assign }, + names::known { text = "bit_and_assign", id = word::bit_and_assign }, + names::known { text = "bit_or_assign", id = word::bit_or_assign }, + names::known { text = "bit_xor_assign", id = word::bit_xor_assign }, + names::known { text = "shift_left_assign", id = word::shift_left_assign }, + names::known { text = "shift_right_assign", id = word::shift_right_assign }, + names::known { text = "close", id = word::close }, + names::known { text = "at", id = word::at }, + names::known { text = "iter", id = word::iter }, + names::known { text = "next", id = word::next }, + names::known { text = "next_back", id = word::next_back }, + names::known { text = "length", id = word::length }, + names::known { text = "data", id = word::data }, + names::known { text = "view", id = word::view }, + names::known { text = "main", id = word::main }, + names::known { text = "some", id = word::some }, + names::known { text = "none", id = word::none }, + names::known { text = "error", id = word::error }, + names::known { text = "os", id = word::os }, + names::known { text = "arch", id = word::arch }, + names::known { text = "backend", id = word::backend }, +]; diff --git a/analyzer/node.sakura b/analyzer/node.sakura new file mode 100644 index 00000000..df6c2b3f --- /dev/null +++ b/analyzer/node.sakura @@ -0,0 +1,136 @@ +#! @file node.sakura +#! @author John Christman (sorakatadzuma@gmail.com) +#! @copyright Malunal Studios, LLC. +#! @license MIT +#! +#! Contains the node of a syntax tree, as gathered from a `syntax`, with `nk`, +#! the kinds of node, and `nf`, the flags a node may hold. +module sakura::analyzer; + +#! A node of a syntax tree: its kind, the token it says what it is by, its two +#! slots, and the last token of what it was parsed from. +#! +#! A syntax keeps each field of its nodes in a vector of its own, and this is +#! the value `syntax::node` gathers from them. What the slots hold is what the +#! kind's shape says. Node 0 stands for no node, wherever an index may be +#! absent. +pub struct node { + val kind: nk; #! Its kind. + val token: u32; #! The token it says what it is by. + val left: u32; #! Its first slot, which its shape says the meaning of. + val right: u32; #! Its second slot. + val end: u32; #! The last token of what it was parsed from. +} + +#! Defines the different types of nodes. +#! +#! What the `left` and `right` of each kind hold is described by its entry in +#! `shapes`, which lists the kinds in this order. `count` is not a kind: it is +#! how many there are, which sizes that table. +pub enum nk : u8 { + # Structure + error, #! Where the parser made no sense of the source, holding what it did parse. Also node 0, which stands for "no node" wherever an index may be absent. + document, #! A file, whose run is its declarations. + block, #! A block, whose run is its statements. + + # Declarations + import_decl, #! `import`, of the module's `path`. + module_decl, #! `module`, of its `path` and any `when` condition. + extern_import, #! `extern import`, of the library's `string` and any `when` condition. + extern_module, #! `extern module`, of its `path` and any `when` condition: a section whose functions without a body, structs, and unions are C's. + when_block, #! At the top level, of declarations, or within a function, of statements. + function, #! A function, with its record and flags. + param, #! A parameter: its type, and a record of its default and flags. + variable, #! A variable or constant, with its record and flags. + field, #! A field of a struct or union, with its record and flags. + spread, #! A struct spread into another, as `...pair`, with its renames. + rename, #! A field a spread renames: its token the old name, and the node the new. + property, #! A property, with its record and its accessors. + accessor, #! A property's `get` or `set`: its parameters, and a record of its body and flags. + struct_decl, #! A struct, with its record and fields. + union_decl, #! A union, with its record and fields. + trait_decl, #! A trait, with its record and members. + assoc_type, #! A trait's associated type, with its record and default. + enumeration, #! An enum, with its record and members. + enumerator, #! A member of an enum: its attributes and its value. + alias, #! A type alias, with its record and the type it aliases. + attribute, #! An attribute: its `type_name` and its field inits. + type_param, #! A type parameter: its bounds, and whether it is a pack. + const_param, #! A constant parameter, `const N: u64`: its bounds, which it may not have, and its type. + type_pattern, #! A pattern parameter, `def(Ts...): R`: the type parameters its parameter types name, and the one its result names. + array_pattern, #! A pattern parameter, `L[N]`: the type parameter its element is, and the constant parameter its length is. + + # Types + segment, #! A segment of a type's name, with its type arguments or parameters. + type_name, #! A type's name, as its segments. + type_ref, #! A reference type: what it refers to, and whether it writes. + type_ptr, #! A pointer type: what it points at, and whether it writes. + type_fixed, #! A fixed array type: its element, and its length. + type_func, #! A function type: its parameter types, and its result. + type_spread, #! `T...`: a function type's variadic last parameter, or a pack passed on among type arguments. + type_of, #! `type_of(d)`, the type a declaration of reflection names. + + # Statements + if_stmt, #! `if`: its condition, and a record of its branches. + if_const, #! `if const`: its condition, and a record of its branches. + while_stmt, #! `while`: its condition and body. + for_stmt, #! `for`, with its record and body. + match_stmt, #! A `match` statement: its subject and arms. + match_arm, #! An arm of a match: its patterns, which are none for `else`, and its body. + return_stmt, #! `return`, with the value it gives. + break_stmt, #! `break`. + continue_stmt, #! `continue`. + expr_stmt, #! An expression as a statement. + contract, #! `expects`, `asserts`, or `ensures`: its condition, and a record of the name it gives what is returned, its text, and which it is. + + # Expressions + name, #! A name, which its token is. + path, #! A path of segments, as `std::io`. + number, #! A number, which its token is. + character, #! A character, which its token is. + string, #! Text, which its token is. + istring, #! Interpolated text: its pieces of text and its holes. + boolean, #! `true` or `false`. + null_lit, #! `null`. + unary, #! A prefix operator, its token, on its operand: also `*p` and `...xs`. + postfix, #! `++` or `--` after their operand. + reference, #! `&` or `&mut` before their operand. + binary, #! A binary operator, its token, on its left and right. + assign, #! An assignment, plain or compound: its target and value. + ternary, #! `c ? a : b`: its condition, and a record of its branches. + fallback, #! `x else y`: its value, and a record of its error's name and the fallback. + call, #! A call: its callee and arguments. + type_args, #! A value given type arguments after it, as `value_of(d)::`. + index, #! `x[i]`: its object and index. + slice, #! `x[a:b]`: its object, and a record of its start and count. + member, #! `x.name`, with any type arguments. + member_of, #! `x.(d)`: its object and the declaration of reflection. + cast, #! `x as T`: its value and type. + is_test, #! `x is T`, which is a bound test where `x` names a type, as `T is copyable`. + construct, #! A struct literal: its `type_name` and field inits. + field_init, #! A field given in a struct literal, whose token is the field where it is named. + array, #! An array literal, as its elements. + lambda, #! An anonymous function: its parameters, and a record of its result and body. + match_value, #! A `match` used as a value: its subject and arms. + range, #! `a..b`, or `a..=b` where its token is `..=`: its start and end. + old_value, #! `old(e)` within an `ensures`: what `e` was where the `ensures` was reached. + undefined, #! `undefined` as a variable's value: its memory left as it is, which nothing zeroes. + + count, #! How many kinds there are, which sizes `shapes`; not a kind itself. +} + +#! The bits a node's `flags` slot holds, where its kind has one. +pub enum nf : u32 { + exported = 0x0001, #! `pub`. + mutable = 0x0002, #! `var`, `&mut`, `*mut`, `&mut this`, and `for &mut x`. + constant = 0x0004, #! `const`, `const def`, and `for const`. + reference = 0x0008, #! `for &x`. + variadic = 0x0010, #! A parameter `name: T...`. + packed = 0x0020, #! A type parameter `Ts...`. + negated = 0x0040, #! `is not`. + computed = 0x0080, #! `x is (d)`. + function = 0x0100, #! A local declared with `def`, whose value is a `lambda`. + named = 0x0200, #! A `field_init` naming its field, as `x = 1`. + inclusive = 0x0400, #! A `for` loop's range written `a..=b`, which includes its end. + implied = 0x0800, #! A parameter of an accessor the syntax leaves out: `this` of a `get` or `set`, and a `set`'s `value`. +} diff --git a/analyzer/note.sakura b/analyzer/note.sakura new file mode 100644 index 00000000..05543d38 --- /dev/null +++ b/analyzer/note.sakura @@ -0,0 +1,113 @@ +#! @file note.sakura +#! @author John Christman (sorakatadzuma@gmail.com) +#! @copyright Malunal Studios, LLC. +#! @license MIT +#! +#! Contains `note`, a diagnostic the lexer, parser, or checker makes of what is +#! wrong with a file, the message it reads as, and `note_sink`, where each of +#! them puts the notes it makes. + +module sakura::analyzer; + + +#! A diagnostic reported while including or checking source files. +#! +#! It holds its text, so it is good for as long as it is kept, whatever made +#! it, and it has one owner: it is moved, as from where it was made to where it +#! is kept, rather than copied. This information can be used to present +#! warnings and errors for source code that failed stages of compilation. +pub struct note { + pub var file: u32; #! The index of the file it is about. + pub var offset: u32; #! Where what it is about begins in the source text. + pub var length: u32; #! How many bytes of the source text it is about, for underlining them. + pub var code: ec; #! What kind of mistake it is about. + pub var warning: bool; #! Whether it is a warning, which never stops a program, rather than an error. + var detail: string; #! What it says. + var found: bool; #! Whether it says what was expected, so the text it is about was found instead. + var lexed: bool; #! Whether the lexer made it, rather than the parser. + + # The instance of a generic the checker found it in, as "In `max`", which + # is empty where it was found in what was written. + pub var instance: string; #! The instance of a generic it was found in, as "In `max`", or empty. + + # A place the note refers to besides its own, as where a name was first + # declared, and what it says of it. Its detail is empty where there is none. + pub var related_file: u32; #! The file of a place it refers to besides its own. + pub var related_offset: u32; #! Where that place begins. + pub var related_length: u32; #! How many bytes it covers. + pub var related: string; #! What it says of that place, or empty where there is none. + + # The declaration the checker found it checking, whose notes are made again + # where it is checked again, or 0. + var origin: u32; #! The declaration being checked where it was made, or 0. +} + +#! What the note says, with what was found where it expected something else, as +#! "Expected `;` after the statement. Found `}`." +#! @param this The note. +#! @param source The source the note is about. +#! @returns The message. +pub def note::message(&this, source: &source): string { + var made := string::copy_of(&this.detail); + return made if !this.found; + + if this.length == 0 { + made.append(" Found the end of the file."); + return made; + } + + made.append(" Found `"); + made.append(source.make_lexeme(this.offset, this.length)); + made.append("`."); + return made; +} + +#! Where the lexer, the parser, or the checker puts the notes it makes: kept in +#! a vector of notes, or handed to what hears them as they are made, up to the +#! most notes it makes. +#! +#! A note is admitted before it is made, which counts it, so one past the limit +#! is never made at all, nor its text copied; one admitted is then given, to +#! what hears notes where something does, or kept. +pub struct note_sink { + var notes: &mut vector; #! Where notes are kept, where nothing hears them. + pub var heard: maybe; #! What hears each note as it is made, which may move it, as where another thread reports them, or nothing. + pub var count: u32; #! How many notes were made, which `limit` bounds. + val limit: u32; #! The most notes made. +} + +#! Makes a sink keeping notes in `notes`, which nothing hears yet. +#! @param notes Where the notes are kept. +#! @param limit The most notes made. +#! @returns The sink. +pub def note_sink::new(notes: &mut vector, limit: u32): note_sink { + return note_sink { + notes = notes, + limit = limit + }; +} + +#! Whether as many notes were made as the limit allows. +#! @param this The sink. +#! @returns Whether they were. +pub val note_sink::full: bool { get => this.count >= this.limit; } + +#! Counts a note about to be made, unless as many were made as the limit allows. +#! @param this The sink. +#! @returns Whether the note is to be made. +pub def note_sink::admits(&mut this): bool { + return false if this.count >= this.limit; + this.count++; + return true; +} + +#! Gives a note admitted to what hears notes, or keeps it where nothing does. +#! @param this The sink. +#! @param made The note, which is moved from. +pub def note_sink::give(&mut this, made: &mut note): void { + if this.heard is some(hear) { + hear(made); + return; + } + this.notes.append(move(made)); +} diff --git a/analyzer/parser.sakura b/analyzer/parser.sakura new file mode 100644 index 00000000..916afb05 --- /dev/null +++ b/analyzer/parser.sakura @@ -0,0 +1,125 @@ +#! @file parser.sakura +#! @author John Christman (sorakatadzuma@gmail.com) +#! @copyright Malunal Studios, LLC. +#! @license MIT +#! +#! Contains the parser, which builds the syntax tree of a file from its tokens, +#! and `parse`, where it begins. What it parses is split across the files of the +#! `parser` directory, one for each part of the language. + +import std::containers; +module sakura::analyzer; + + +#! The sakura language parser structure. +#! +#! This is responsible for taking a freshly lexed input syntax and to structure +#! it into an abstract syntax tree. It will assure that any syntax issues are +#! noted and reported to the next stage. The syntax tree produced is checked by +#! the next compiler step for semantic analysis. +#! +#! The parsing functions are split by what they parse across `parser/`: each +#! returns the index of the node it made, or of an `error` node where it found +#! none, and 0 where what it parses may be left out and was. +pub struct parser { + var syntax: &mut syntax; #! Reads tokens and appends nodes and extras. + var names: &names; #! The names the tokens were lexed with, which give a name's length. + var scratch: stack; #! A scratchpad when the parser needs to hold onto things. + var depth: u32; #! Cleanly stops heavily nested constructs. + var file: u32; #! Current file index. + var index: u32; #! Current token index. + var kind: tk; #! The kind of the current token, or `eof` at the limit. + var limit: u32; #! Where the tokens seem to end, short of their end while giving up on a declaration. + var panic: bool; #! Silences notes until the parser resynchronizes. + var halted: bool; #! Gave up on the declaration it is within, so notes nothing more of it. + var begun: u32; #! The token the top-level declaration being parsed begins at. + var cut: bool; #! Ran into the limit with something left open, while reparsing. + # Whether a constant argument is being parsed between `<` and `>`, outside any + # bracket it opens, where `>` closes the arguments rather than comparing. + var angled: bool; + # Whether a trait's members are being parsed, and the trait's type parameters, + # which a member's `where` may bound beside its own, as `self` may be. + var in_members: bool; + var member_params: u32; + # Whether an `ensures`'s condition is being parsed, where `old(e)` is what `e` + # was where it was reached. + var in_ensures: bool; + + # Where the parser puts its notes, which `max_notes` bounds: kept with the + # lexer's, or heard as each is made, as where another thread reports them. + pub var sink: note_sink; #! Where the parser puts its notes. +} + +#! The deepest the parser nests before it gives up on the declaration. +pub const parser::max_depth: u32 = 100; + +#! The most notes the parser makes for one file. +pub const parser::max_notes: u32 = 100; + +#! Creates a new parser from the provided information. +#! @param syntax Where the parser will store the nodes and extras that it +#! creates. +#! @param names The names the tokens were lexed with. +#! @param notes Where the parser will store the notes. +#! @param file The index of the file that it's parsing. +#! @returns The instantiated parser. +pub def parser::new( + syntax: &mut syntax, + names: &names, + notes: &mut vector, + file: u32 +): parser { + return parser { + syntax = syntax, + names = names, + sink = note_sink::new(notes, parser::max_notes), + scratch = stack::::new(), + file = file + }; +} + +#! Parses the token stream. +#! +#! This generates the abstract syntax tree within the `syntax` variable, such +#! that when the parser ends, the syntax can be evaluated by a checker. The +#! token stream must end with `tk::eof`. +#! @param this The parser. +#! @returns The index of the `document` node, the first the parser makes. +pub def parser::parse(&mut this): u32 { + this.syntax.reserve_for_tokens(); + this.limit = this.syntax.token_count as u32; + this.sync(); + + # The run is made before it is stored: making it appends nodes, which may move + # the vector a reference into it was taken from. + val document := this.make_node(nk::document, this.index); + val declared := this.declarations(this.limit); + this.syntax.node_lefts[document] = declared; + this.syntax.set_node_end(document, this.limit - 1); + this.syntax.whole_nodes = this.syntax.node_count; + this.syntax.whole_extras = this.syntax.extras.length; + this.syntax.fit_nodes(); + return document; +} + +#! The declarations from the current token through the limit, each recovered +#! from on its own. +#! @param this The parser. +#! @param limit The last token to parse. +#! @returns Their run. +def parser::declarations(&mut this, limit: u32): u32 { + val mark := this.mark; + while !this.check(tk::eof) { + this.begun = this.index; + this.push(this.declaration()); + if this.halted { + this.resume(limit); + } + + if this.panic { + this.synchronize(parser::scope::document); + } + } + + return this.make_run(mark); +} diff --git a/analyzer/parser/attribute.sakura b/analyzer/parser/attribute.sakura new file mode 100644 index 00000000..37d0851d --- /dev/null +++ b/analyzer/parser/attribute.sakura @@ -0,0 +1,44 @@ +#! @file attribute.sakura +#! @author John Christman (sorakatadzuma@gmail.com) +#! @copyright Malunal Studios, LLC. +#! @license MIT +#! +#! Contains the parsing of attributes, written `@name` or `@name{ fields }` +#! before a declaration. +module sakura::analyzer; + + +#! The attributes before a declaration, as `@name` or `@name{ fields }`. +#! @param this The parser. +#! @returns The run of `attribute` nodes, empty when there are none. +def parser::attributes(&mut this): u32 { + val mark := this.mark; + while this.check(tk::attr) { + val made := this.attribute(); + break if made == 0; + this.push(made); + } + + return this.make_run(mark); +} + +#! One attribute, from its `@`, whose value is the struct literal written, so +#! `@name` is `name{}`. +#! @param this The parser. +#! @returns The `attribute` node, or 0 where no type follows the `@`. +def parser::attribute(&mut this): u32 { + val token := this.index; + this.advance(); + val type_name := this.type_name(); + return 0 if this.syntax.node_kinds[type_name] == nk::error; + + + return this.make_node( + nk::attribute, + token, + type_name, + this.check(tk::lbrace) + ? this.field_list() + : 0 + ); +} diff --git a/analyzer/parser/declarations.sakura b/analyzer/parser/declarations.sakura new file mode 100644 index 00000000..bb36e11a --- /dev/null +++ b/analyzer/parser/declarations.sakura @@ -0,0 +1,889 @@ +#! @file declarations.sakura +#! @author John Christman (sorakatadzuma@gmail.com) +#! @copyright Malunal Studios, LLC. +#! @license MIT +#! +#! Contains the parsing of declarations: functions and their parameters and +#! where clauses, variables, properties and their accessors, structs, unions, +#! traits and their members, enums, and type aliases. + +module sakura::analyzer; + + +#! The name of a declaration, as `name`, `name`, or `box::name`. +struct parser::declared { + var receiver: u32; #! The type it is declared through, a `type_name` of every segment but the last, or 0. + var name: u32; #! The token of its name. + var params: u32; #! The run of its own type parameters. +} + +#! The parameters and result of a function or lambda. +struct parser::signature { + var params: u32; #! The run of `param` nodes. + var result: u32; #! The result type, 0 where a lambda leaves it out. +} + +#! A declaration at the top level of a file, or within a `when` there, with the +#! attributes and `pub` before it. A declaration's token is its name. +#! @param this The parser. +#! @returns The declaration's node, or an `error` node holding its attributes +#! where it is none. +def parser::declaration(&mut this): u32 { + var lead := parser::lead { start = this.index, attrs = this.attributes() }; + return this.error(this.index, lead.attrs) if this.panic; + + if this.accept(tk::kw_pub) { + lead.exported = true; + if this.check(tk::attr) { + this.report(ec::token, "Attributes are written before `pub`, as `@name pub def f(): void {}`."); + lead.attrs = this.join_runs(lead.attrs, this.attributes()); + return this.error(this.index, lead.attrs) if this.panic; + } + + if this.check(tk::kw_pub) { + this.fail(ec::token, "A declaration is `pub` once."); + return this.error(this.index, lead.attrs); + } + } + + # An import, a module, and the `when` around declarations name nothing of their + # own, so nothing describes them or exports them. + val unnamed := this.check(tk::kw_imp) || this.check(tk::kw_mod) || this.check(tk::kw_extern) || this.check(tk::kw_when); + if unnamed && lead.exported { + this.report(ec::token, "Only a declaration of a name can be `pub`, and this declares none."); + } else if unnamed && lead.attrs != 0 { + this.report(ec::token, "Attributes describe a declaration of a name, and this declares none."); + } + + val made := match this.kind { + tk::kw_imp => this.path_decl(nk::import_decl), + tk::kw_mod => this.path_decl(nk::module_decl), + tk::kw_extern => this.extern_decl(), + tk::kw_when => this.when_block(true), + tk::kw_def => this.function(&lead, false, parser::place::top), + tk::kw_const => this.peek(1) == tk::kw_def + ? this.const_function(&lead, parser::place::top) + : this.variable(&lead, parser::place::top), + tk::kw_val, tk::kw_var => this.variable(&lead, parser::place::top), + tk::kw_struct, tk::kw_union, tk::kw_trait => this.aggregate(&lead), + tk::kw_enum => this.enumeration(&lead), + tk::kw_type => this.alias(&lead), + else => this.no_declaration() + }; + return this.declared_at(made, &lead); +} + +def parser::no_declaration(&mut this): u32 { + this.fail(ec::decl, + "Expected an import, module, `extern`, `when`, function, struct, enum, trait, type, variable, or constant."); + return this.error_here(); +} + +#! `import path;`, or `module path;` and `module path when condition;`. +#! @param this The parser. +#! @param kind `import_decl` or `module_decl`. +#! @returns The node. +def parser::path_decl(&mut this, kind: nk): u32 { + val token := this.index; + this.advance(); + + val path := this.path(); + var condition: u32 = 0; + if kind == nk::module_decl && this.accept(tk::kw_when) { + condition = this.condition(); + } + + this.expect(tk::semicolon, "Expected `;` after the path."); + return this.make_node(kind, token, path, condition); +} + +#! `extern import "library";` or `extern module path;`, each with a `when` +#! condition where it is written. A section without one is parsed, so the +#! checker says what it lacks. +#! @param this The parser. +#! @returns The `extern_import` or `extern_module` node, or an `error` node. +def parser::extern_decl(&mut this): u32 { + val token := this.index; + this.advance(); + if this.check(tk::kw_mod) { + this.advance(); + val path := this.path(); + val condition := this.accept(tk::kw_when) ? this.condition() : 0; + this.expect(tk::semicolon, "Expected `;` after the path."); + return this.make_node(nk::extern_module, token, path, condition); + } + + if !this.accept(tk::kw_imp) { + this.fail(ec::token, "Expected `import` or `module` after `extern`: `extern import \"library\";` names a library, and `extern module path when ...;` begins C's declarations."); + return this.error_here(); + } + if !this.check(tk::string) { + this.fail(ec::token, "Expected the library, as `\"libvulkan.so.1\"` or `\"kernel32.dll\"`."); + return this.error_here(); + } + val library := this.literal(nk::string); + val condition := this.accept(tk::kw_when) ? this.condition() : 0; + this.expect(tk::semicolon, "Expected `;` after the library."); + return this.make_node(nk::extern_import, token, library, condition); +} + +#! The name of a declaration. Where receivers are allowed, `T::name` gives the +#! receiver as a `type_name` of every segment but the last, whose type +#! parameters are each segment's, as `T` of `box::get`. +#! @param this The parser. +#! @param receivers Whether the name may be declared through a type. +#! @returns The receiver, the name's token, and the type parameters. +def parser::decl_name(&mut this, receivers: bool): parser::declared { + if !this.check(tk::name) { + this.fail(ec::ident, "Expected a name for the declaration."); + return parser::declared { name = this.index }; + } + + var last := this.index; + this.advance(); + + val mark := this.mark; + var params := this.check(tk::less) ? this.type_params() : 0; + while receivers && this.check(tk::scope) { + this.advance(); + if !this.check(tk::name) { + this.fail(ec::ident, "Expected a name after `::`."); + break; + } + + this.push(this.make_node(nk::segment, last, params)); + last = this.index; + this.advance(); + params = this.check(tk::less) ? this.type_params() : 0; + } + + # The receiver ends where its last segment does, short of the name after it. + var receiver: u32 = 0; + if this.mark > mark { + val segments := this.scratch.view(); + val first: u32 = this.syntax.node_tokens[segments[mark]]; + val end: u32 = this.syntax.node_end(segments[this.mark - 1]); + receiver = this.make_node(nk::type_name, first, this.make_run(mark)); + this.syntax.set_node_end(receiver, end); + } + + return parser::declared { + receiver = receiver, + name = last, + params = params + }; +} + +#! `const def`, a function constants can call. +#! @param this The parser. +#! @param lead What came before it. +#! @param place Where it is written. +#! @returns The `function` node. +def parser::const_function(&mut this, lead: &parser::lead, place: parser::place): u32 { + this.advance(); + return this.function(lead, true, place); +} + +#! A function, from its `def`. One ending at its signature, rather than a body, +#! is one a trait requires, one the compiler gives, or one of C's, which the +#! checker tells apart by its attributes. A method of a trait takes no receiver. +#! @param this The parser. +#! @param lead What came before it. +#! @param constant Whether it is a `const def`. +#! @param place Where it is written. +#! @returns The `function` node, or an `error` node. +def parser::function(&mut this, lead: &parser::lead, constant: bool, place: parser::place): u32 { + this.advance(); + + val in_trait := place == parser::place::member; + val declared := this.decl_name(!in_trait); + val signature := this.params(false, in_trait || declared.receiver != 0); + val outer := this.where_clause(declared.params, declared.receiver); + + val body := this.accept(tk::semicolon) ? 0 : this.block(); + val record := this.make_record(lead.attrs, declared.receiver, declared.params, signature.params, signature.result, body, outer); + val flags := parser::bit(lead.exported, nf::exported) | parser::bit(constant, nf::constant); + return this.make_node(nk::function, declared.name, record, flags); +} + +#! The parameters and result of a function, from `(` through the result type. A +#! lambda may leave out its parameter types and its result, and a method may +#! begin with `&this` or `&mut this`. +#! @param this The parser. +#! @param lambda Whether they are a lambda's. +#! @param methods Whether they are a method's, which may take `this`. +#! @returns The run of parameters and the result type. +def parser::params(&mut this, lambda: bool, methods: bool): parser::signature { + if !this.expect(tk::lparen, "Expected `(` to begin the parameters.") { + return parser::signature {}; + } + + val mark := this.mark; + if !lambda && this.check(tk::bitand) { + this.push(this.this_param(methods)); + if !this.check(tk::rparen) { + this.expect(tk::comma, "Expected `,` or `)` after `this`."); + } + } + + var defaulted := false; + var variadic := false; + while !this.check(tk::rparen) && !this.check(tk::eof) { + if !this.check(tk::name) { + this.fail(ec::ident, "Expected a parameter name."); + break if !this.skip_item(tk::rparen) || !this.accept(tk::comma); + continue; + } + + val token := this.index; + this.advance(); + if variadic { + this.report_at(token, ec::token, + "A variadic parameter takes every argument after the parameters before it, so it is the last."); + } + + var type_expr: u32 = 0; + if !lambda || this.check(tk::colon) { + this.expect(tk::colon, "Expected `:` followed by the parameter type."); + type_expr = this.type_expr(); + } + + # `name: T...` takes the arguments after the parameters before it. + var flags: u32 = 0; + if type_expr != 0 && this.check(tk::spread) { + if lambda { + this.report(ec::token, + "Only a function declared by name takes a variadic parameter; an anonymous function takes a `span`."); + } + + this.advance(); + flags = parser::bit(!lambda, nf::variadic); + variadic = variadic || !lambda; + } + + # A parameter may be given the value a call takes where it leaves the argument + # out. Every parameter after one is given one too, so the arguments a call does + # give are always the first parameters. + var value: u32 = 0; + if flags != 0 && this.check(tk::assign) { + this.report(ec::token, + "A variadic parameter takes no default value, since a call giving no arguments for it gives it none."); + this.advance(); + value = this.expression(); + } else if this.accept(tk::assign) { + value = this.expression(); + defaulted = true; + } else if defaulted && flags == 0 { + this.report_at(token, ec::token, + "A parameter after one with a default value is given one too, so a call leaving arguments out always leaves out the last."); + } + + this.push(this.make_node(nk::param, token, type_expr, this.make_record(value, flags))); + break if this.panic && !this.skip_item(tk::rparen); + break if !this.accept(tk::comma); + } + + val params := this.make_run(mark); + this.expect(tk::rparen, "Expected `)` to close the parameters."); + if lambda && !this.check(tk::colon) { + return parser::signature { params = params }; + } + + this.expect(tk::colon, "Expected `:` followed by the return type."); + return parser::signature { + params = params, + result = this.type_expr() + }; +} + +#! `&this` or `&mut this`, the first parameter of a method, from its `&`. Its +#! type is left out, since it is a reference to the receiver. +#! @param this The parser. +#! @param methods Whether it is a method's, which may take `this`. +#! @returns The `param` node, or an `error` node. +def parser::this_param(&mut this, methods: bool): u32 { + this.advance(); + val mutable := this.accept(tk::kw_mut); + if !this.check_word(names::this_id) { + this.fail(ec::ident, "Expected `this`; other parameters are written `name: type`."); + return this.error_here(); + } + + val token := this.index; + this.advance(); + if !methods { + this.report_at(token, ec::token, "Only methods, declared as `type::name`, take `this`."); + } + + return this.make_node(nk::param, token, 0, this.make_record(0, parser::bit(mutable, nf::mutable))); +} + +#! The `where` clauses of a declaration, one for each type parameter it bounds, +#! as `where K: hashable, equatable where V: Show`. The bounds become those of +#! the `type_param` nodes of the declaration, or of its receiver, as `T` of +#! `box::get`. A trait's method may also bound the trait's type parameters +#! and `self`, which only that method then asks of them, as `where self: +#! backward_iterator`: each is a `type_param` of the name, made here. +#! @param this The parser. +#! @param params The run of the declaration's type parameters. +#! @param receiver The receiver's `type_name`, or 0. +#! @returns The run of the bounds a trait's method puts on the trait's type +#! parameters and `self`, or 0. +def parser::where_clause(&mut this, params: u32, receiver: u32): u32 { + val outer_mark := this.mark; + var outer := vector::::new(); + while this.accept(tk::kw_where) { + if !this.check(tk::name) { + this.fail(ec::ident, "Expected the name of a type parameter to bound."); + break; + } + + val name := this.index; + val word: u32 = this.syntax.token_names[this.index]; + var param := this.find_param(params, receiver, word); + if param == 0 && this.in_members && (word == names::self_id || this.find_in(this.member_params, word) != 0) { + for &each in outer { + param = this.name_of(each) == word ? each : param; + } + if param == 0 { + param = this.make_node(nk::type_param, name); + outer.append(param); + } + } + if param == 0 { + this.report(ec::token, this.in_members + ? "Only the type parameters of the method, of its trait, and `self` are bounded here." + : "Only the type parameters of the declaration, and of its receiver, are bounded here."); + } + this.advance(); + + # A pack's bounds are each of its types', written `where Ts...: Show`. + val dotted := this.accept(tk::spread); + val packed := param != 0 && this.syntax.node_kinds[param] == nk::type_param + && (this.syntax.node_rights[param] & nf::packed as u32) != 0; + if dotted && param != 0 && !packed { + this.report_at(name, ec::token, "Only a pack, declared `Ts...`, is bounded as `Ts...`."); + } else if packed && !dotted { + this.report_at(name, ec::token, "A pack's bounds are each of its types', written `where Ts...: Show`."); + } + this.expect(tk::colon, "Expected `:` followed by the bounds."); + + # The bounds it already has come first, since each `where` adds to them. + val mark := this.mark; + if param != 0 { + val had := this.syntax.node_lefts[param]; + for &node in this.run_view(had) { + this.push(node); + } + } + + while true { + this.push(this.type_name()); + break if !this.accept(tk::comma); + } + + if param != 0 { + val bounds := this.make_run(mark); + this.syntax.node_lefts[param] = bounds; + } else { + this.drop(mark); + } + } + + return 0 if outer.length == 0; + for &each in outer { + this.push(each); + } + return this.make_run(outer_mark); +} + +#! The `type_param` of the name among the type parameters, or those of the +#! receiver's segments, or 0 where there is none. +#! @param this The parser. +#! @param params The run of the declaration's type parameters. +#! @param receiver The receiver's `type_name`, or 0. +#! @param name The ID of the name. +#! @returns The `type_param` node, or 0. +def parser::find_param(&this, params: u32, receiver: u32, name: u32): u32 { + val own := this.find_in(params, name); + return own if own != 0 || receiver == 0; + + val segments := this.syntax.node_lefts[receiver]; + for &segment in this.run_view(segments) { + val found := this.find_in(this.syntax.node_lefts[segment], name); + return found if found != 0; + } + return 0; +} + +def parser::find_in(&this, params: u32, name: u32): u32 { + for ¶m in this.run_view(params) { + # A pattern's type parameters are its own parameters' and its result's. + if this.syntax.node_kinds[param] == nk::type_pattern { + val inner := this.find_in(this.syntax.node_lefts[param], name); + return inner if inner != 0; + val result := this.syntax.node_rights[param]; + return result if result != 0 && this.name_of(result) == name; + continue; + } + # An array pattern's are its element's and its length's. + if this.syntax.node_kinds[param] == nk::array_pattern { + val element := this.syntax.node_lefts[param]; + return element if this.name_of(element) == name; + val length := this.syntax.node_rights[param]; + return length if length != 0 && this.name_of(length) == name; + continue; + } + return param if this.name_of(param) == name; + } + return 0; +} + +#! A variable, constant, or field, from its `val`, `var`, or `const`, or the +#! property it begins where `{` follows its type. Where it is written says what +#! it may be: one at the top level may be declared through a type, as +#! `rect::unit`, one of a struct or union is a `field`, and one at the top level +#! or of a trait may be a property. +#! @param this The parser. +#! @param lead What came before it. +#! @param place Where it is written. +#! @returns The `variable`, `field`, or `property` node, or an `error` node. +def parser::variable(&mut this, lead: &parser::lead, place: parser::place): u32 { + val mutable := this.check(tk::kw_var); + val constant := this.check(tk::kw_const); + val kind := place == parser::place::field ? nk::field : nk::variable; + this.advance(); + + val declared := this.decl_name(place == parser::place::top); + if declared.params != 0 { + this.report_at(declared.name, ec::token, + "Only functions, types, and aliases take type parameters of their own; a member of a generic type is declared through it, as `box::empty`."); + } + + this.expect(tk::colon, "Expected `:` after the name, followed by a type, `=`, or both."); + var type_expr: u32 = 0; + if !this.check(tk::assign) && !this.check(tk::semicolon) { + type_expr = kind == nk::field && this.check(tk::spread) + ? this.spread() + : this.type_expr(); + } + + # `{` after the type opens the accessors of a property. + val properties := place == parser::place::top || place == parser::place::member; + if properties && !constant && type_expr != 0 && this.check(tk::lbrace) { + if place == parser::place::top && declared.receiver == 0 { + this.report_at(declared.name, ec::token, + "A property belongs to a type, so it is declared as `type::name`."); + } + return this.property(lead, declared, type_expr, mutable, place); + } + + # `= undefined;` leaves a variable's memory as it is, and is a word only there. + var value: u32 = 0; + if this.accept(tk::assign) { + val left := this.check_word(names::undefined_id) && this.peek(1) == tk::semicolon; + value = left ? this.literal(nk::undefined) : this.expression(); + } + if type_expr == 0 && value == 0 { + this.fail(ec::kind, "Expected a type or `=` followed by a value to infer it from."); + } + + this.expect(tk::semicolon, "Expected `;` after the declaration."); + val record := this.make_record(lead.attrs, declared.receiver, type_expr, value); + val flags := parser::bit(lead.exported, nf::exported) + | parser::bit(mutable, nf::mutable) + | parser::bit(constant, nf::constant); + return this.make_node(kind, declared.name, record, flags); +} + +#! The `{ get ... set ... }` of a property, from its `{`. Each accessor is as +#! visible as the property unless it takes its own `pub`, which is how a +#! property reads everywhere but is written only where it is declared. +#! @param this The parser. +#! @param lead What came before it. +#! @param declared Its name and receiver. +#! @param type_expr Its type's node. +#! @param mutable Whether it is declared `var`. +#! @param place Where it is written. +#! @returns The `property` node. +def parser::property( + &mut this, + lead: &parser::lead, + declared: parser::declared, + type_expr: u32, + mutable: bool, + place: parser::place +): u32 { + this.advance(); + + val in_trait := place == parser::place::member; + val methods := in_trait || declared.receiver != 0; + val mark := this.mark; + var getter := false; + var setter := false; + while !this.check(tk::rbrace) && !this.check(tk::eof) { + # A trait's members are as visible as the trait, so it takes none. + val marker := this.index; + var own := this.accept(tk::kw_pub); + if own && in_trait { + this.report_at(marker, ec::token, + "A trait's members are as visible as the trait, so its accessors are never `pub`."); + own = false; + } + + val get := this.check_word(names::get_id); + val set := this.check_word(names::set_id); + if !get && !set { + this.fail(ec::token, own + ? "Expected `get` or `set` after `pub`, the accessors of a property." + : "Expected `get` or `set`, the accessors of a property."); + break; + } + + if (get && getter) || (set && setter) { + this.fail(ec::token, get + ? "The property already has a `get`." + : "The property already has a `set`."); + break; + } + + if set && !mutable { + this.fail(ec::token, + "A `val` property only reads, so it has no `set`; declare it with `var` to write it."); + break; + } + + this.push(this.accessor(own, methods, get)); + getter = getter || get; + setter = setter || set; + break if this.panic; + } + + # Past a malformed accessor, skip to the brace closing them, so what follows + # is read as the declarations it is rather than as more of the property. + if this.panic { + this.skip_to_close(); + } + + val accessors := this.make_run(mark); + this.expect(tk::rbrace, "Expected `}` to close the accessors."); + if !getter { + this.report_at(declared.name, ec::decl, "A property is read through `get`, which it must declare."); + } + + val flags := parser::bit(mutable, nf::mutable) | parser::bit(lead.exported, nf::exported); + val record := this.make_record(lead.attrs, declared.receiver, type_expr, flags); + return this.make_node(nk::property, declared.name, record, accessors); +} + +#! One accessor of a property, `get` or `set`, from its name, followed by its +#! body: a block, `=> expression;`, or `;` where a trait asks for it. Its +#! parameters are implied, and made here: `this`, which a `get` reads and a +#! `set` writes, and a `set`'s `value`, of the property's type. `=>` gives what +#! a `get` returns, and is what a `set` does. +#! @param this The parser. +#! @param exported Whether the property is `pub`. +#! @param methods Whether it is declared through a type, so its accessors +#! take `this`. +#! @param get Whether it is the getter. +#! @returns The `accessor` node, or an `error` node. +def parser::accessor(&mut this, exported: bool, methods: bool, get: bool): u32 { + val token := this.index; + this.advance(); + + val mark := this.mark; + if this.check(tk::lparen) { + # The form before, read on so what follows is checked as it means. + this.report(ec::token, get + ? "A `get` takes no parameters written: it has `this`, as `get => this.w;` or `get { return this.w; }`." + : "A `set` takes no parameters written: it has `this`, and `value` of the property's type, as `set => this.w = value;` or `set { this.w = value; }`."); + this.written_params(methods, get); + } else { + this.push(this.make_node(nk::param, token, 0, this.make_record(0, parser::bit(!get, nf::mutable) | nf::implied as u32))); + if !get { + this.push(this.make_node(nk::param, token, 0, this.make_record(0, nf::implied as u32))); + } + } + val params := this.make_run(mark); + + var body: u32 = 0; + if this.check(tk::arrow) { + val arrow := this.index; + this.advance(); + val made := this.expression(); + this.expect(tk::semicolon, "Expected `;` after the accessor's expression."); + val stated := this.make_node(get ? nk::return_stmt : nk::expr_stmt, arrow, made); + body = this.make_node(nk::block, arrow, this.run_of(stated)); + } else if !this.accept(tk::semicolon) { + body = this.block(); + } + return this.make_node(nk::accessor, token, params, this.make_record(body, parser::bit(exported, nf::exported))); +} + +#! The parameters of an accessor written out, `(&this)` or `(&mut this, to)`, +#! as they were before they were implied, from its `(`, which a note refuses. +#! @param this The parser. +#! @param methods Whether it is declared through a type, so it takes `this`. +#! @param get Whether it is the getter. +def parser::written_params(&mut this, methods: bool, get: bool): void { + this.advance(); + if this.check(tk::bitand) { + this.push(this.this_param(methods)); + if !this.check(tk::rparen) { + this.expect(tk::comma, "Expected `,` or `)` after `this`."); + } + } else { + this.report(ec::token, get + ? "A getter reads the value it belongs to, so it takes `&this`." + : "A setter changes the value it belongs to, so it takes `&mut this` and the value to store."); + } + + while !this.check(tk::rparen) && !this.check(tk::eof) { + if !this.check(tk::name) { + this.fail(ec::ident, "Expected a parameter name."); + break if !this.skip_item(tk::rparen) || !this.accept(tk::comma); + continue; + } + + val name := this.index; + this.advance(); + val type_expr := this.accept(tk::colon) ? this.type_expr() : 0; + this.push(this.make_node(nk::param, name, type_expr)); + break if this.panic && !this.skip_item(tk::rparen); + break if !this.accept(tk::comma); + } + this.expect(tk::rparen, "Expected `)` to close the parameters of the accessor."); +} + +#! A struct, union, or trait, from its keyword. A struct or union names the +#! traits it implements, and a trait names the traits it composes. +#! @param this The parser. +#! @param lead What came before it. +#! @returns The `struct_decl`, `union_decl`, or `trait_decl` node. +def parser::aggregate(&mut this, lead: &parser::lead): u32 { + val kind := match this.kind { + tk::kw_struct => nk::struct_decl, + tk::kw_union => nk::union_decl, + else => nk::trait_decl + }; + val in_trait := kind == nk::trait_decl; + this.advance(); + + val declared := this.decl_name(true); + var traits: u32 = 0; + if this.accept(tk::colon) { + val mark := this.mark; + while true { + this.push(this.type_name()); + break if !this.accept(tk::comma); + } + traits = this.make_run(mark); + } + + this.where_clause(declared.params, 0); + + val flags := parser::bit(lead.exported, nf::exported); + val record := this.make_record(lead.attrs, declared.receiver, declared.params, traits, flags); + if !this.expect(tk::lbrace, "Expected `{` to begin the members.") { + return this.make_node(kind, declared.name, record); + } + + val scope := in_trait ? parser::scope::members : parser::scope::fields; + val mark := this.mark; + val was_in_members := this.in_members; + val was_params := this.member_params; + this.in_members = in_trait; + this.member_params = in_trait ? declared.params : 0; + while !this.check(tk::rbrace) && !this.check(tk::eof) { + var member_lead := parser::lead { start = this.index, attrs = this.attributes() }; + if this.panic { + this.push(this.error(this.index, member_lead.attrs)); + this.synchronize(scope); + continue; + } + + val member := in_trait + ? this.trait_member(&member_lead) + : this.field_member(&mut member_lead); + if member != 0 { + this.push(this.declared_at(member, &member_lead)); + } + + if this.panic { + this.synchronize(scope); + } + } + + this.in_members = was_in_members; + this.member_params = was_params; + val members := this.make_run(mark); + this.expect(tk::rbrace, "Expected `}` to close the members."); + return this.make_node(kind, declared.name, record, members); +} + +#! A field of a struct or union, which `pub` lets modules other than its own +#! reach. +#! @param this The parser. +#! @param lead What came before it, which `pub` is added to. +#! @returns The `field` node, or an `error` node holding the attributes before +#! what is not one, or 0 where there were none. +def parser::field_member(&mut this, lead: &mut parser::lead): u32 { + if this.accept(tk::kw_pub) { + lead.exported = true; + if this.check(tk::attr) { + this.report(ec::token, "Attributes are written before `pub`, as `@name pub var x: T;`."); + lead.attrs = this.join_runs(lead.attrs, this.attributes()); + return this.error(this.index, lead.attrs) if this.panic; + } + if this.check(tk::kw_pub) { + this.fail(ec::token, "A declaration is `pub` once."); + return this.error(this.index, lead.attrs); + } + } + if this.check(tk::kw_var) || this.check(tk::kw_val) { + return this.variable(lead, parser::place::field); + } + + this.fail(ec::token, "Expected a field declared with `var` or `val`."); + return lead.attrs != 0 ? this.error(this.index, lead.attrs) : 0; +} + +#! A member of a trait: a method, which `;` leaves to the implementer, a +#! constant, a property, or a type it asks for. +#! @param this The parser. +#! @param lead What came before it. +#! @returns The member's node, or an `error` node holding what was parsed of +#! what is not one, or 0 where nothing was. +def parser::trait_member(&mut this, lead: &parser::lead): u32 { + val place := parser::place::member; + match this.kind { + tk::kw_def => return this.function(lead, false, place); + tk::kw_type => return this.assoc_type(lead); + tk::kw_const => { + return this.const_function(lead, place) if this.peek(1) == tk::kw_def; + return this.variable(lead, place); + } + + # A trait requires a property by declaring its accessors without bodies, and + # `var` and `val` declare nothing else of a trait. + tk::kw_var, tk::kw_val => { + val keyword := this.index; + val member := this.variable(lead, place); + return member if this.syntax.node_kinds[member] == nk::property; + + this.fail_at(keyword, ec::token, + "A trait declares a property with its accessors, as `val area: int { get; }`, and a constant with `const`."); + return this.error(keyword, this.run_of(member)); + } + tk::kw_pub => this.fail(ec::token, "A trait's members are as visible as the trait, so they are never `pub`."); + else => this.fail(ec::token, + "Expected a method signature declared with `def`, a property with `var` or `val`, a constant with `const`, or a type with `type`."); + } + + return lead.attrs != 0 ? this.error(this.index, lead.attrs) : 0; +} + +#! `type name: A, B = T;`, a type a trait asks of what implements it, which the +#! bounds constrain and the default stands in for where the implementer gives +#! none. +#! @param this The parser. +#! @param lead What came before it. +#! @returns The `assoc_type` node. +def parser::assoc_type(&mut this, lead: &parser::lead): u32 { + this.advance(); + if !this.check(tk::name) { + this.fail(ec::ident, "Expected the name of the type the trait asks for."); + return this.error_here(); + } + + val token := this.index; + this.advance(); + # `type params...;` asks for a pack, which only the compiler gives. + val packed := this.accept(tk::spread); + + var bounds: u32 = 0; + if this.accept(tk::colon) { + val mark := this.mark; + while true { + this.push(this.type_name()); + break if !this.accept(tk::comma); + } + bounds = this.make_run(mark); + } + + val fallback := this.accept(tk::assign) ? this.type_expr() : 0; + this.expect(tk::semicolon, "Expected `;` after the type the trait asks for."); + return this.make_node(nk::assoc_type, token, this.make_record(lead.attrs, bounds, parser::bit(packed, nf::packed)), fallback); +} + +#! `enum name: type { member, member = value, ... }`, whose type may be left +#! out. An enum is never generic, but it may be nested in a type that is, as +#! `enum list::state`, naming that type's parameters. +#! @param this The parser. +#! @param lead What came before it. +#! @returns The `enumeration` node. +def parser::enumeration(&mut this, lead: &parser::lead): u32 { + this.advance(); + if !this.check(tk::name) { + this.fail(ec::ident, "Expected the name of the enumeration."); + return this.error_here(); + } + + val declared := this.decl_name(true); + if declared.params != 0 { + this.report_at(declared.name, ec::token, "An enum is never generic, though it may be nested in a type that is."); + } + + val integer := this.accept(tk::colon) ? this.type_expr() : 0; + val record := this.make_record(lead.attrs, declared.receiver, integer, parser::bit(lead.exported, nf::exported)); + if !this.accept(tk::lbrace) { + this.fail(ec::token, "Expected `{` to begin the members."); + return this.make_node(nk::enumeration, declared.name, record); + } + + val members := this.list(parser::item::enumerator, tk::rbrace, "Expected `,` between the members, or `}` to close them."); + return this.make_node(nk::enumeration, declared.name, record, members); +} + +#! `type name = type where T: bound;`. +#! @param this The parser. +#! @param lead What came before it. +#! @returns The `alias` node. +def parser::alias(&mut this, lead: &parser::lead): u32 { + this.advance(); + + val declared := this.decl_name(true); + this.expect(tk::assign, "Expected `=` followed by the aliased type."); + val aliased := this.type_expr(); + this.where_clause(declared.params, 0); + if this.check(tk::bitor) { + this.fail(ec::token, + "A value that is one of several types is a `union`, as `union name { var a: A; var b: B; }`."); + } else if this.check(tk::bitand) { + this.fail(ec::token, + "Types are combined as the fields of a `struct`, as `struct name { var a: A; var b: B; }`."); + } else { + this.expect(tk::semicolon, "Expected `;` after the type."); + } + + val record := this.make_record(lead.attrs, declared.receiver, declared.params, parser::bit(lead.exported, nf::exported)); + return this.make_node(nk::alias, declared.name, record, aliased); +} + +#! A member of an enum, with the attributes before it, and the value it is +#! given, which may be left out. +#! @param this The parser. +#! @returns The `enumerator` node, or an `error` node. +def parser::enumerator(&mut this): u32 { + val lead := parser::lead { start = this.index, attrs = this.attributes() }; + return this.error(this.index, lead.attrs) if this.panic; + if !this.check(tk::name) { + this.fail(ec::ident, "Expected the name of a member."); + return this.error(this.index, lead.attrs); + } + + val token := this.index; + this.advance(); + val value := this.accept(tk::assign) ? this.expression() : 0; + return this.declared_at(this.make_node(nk::enumerator, token, lead.attrs, value), &lead); +} diff --git a/analyzer/parser/expressions.sakura b/analyzer/parser/expressions.sakura new file mode 100644 index 00000000..62393c4b --- /dev/null +++ b/analyzer/parser/expressions.sakura @@ -0,0 +1,347 @@ +#! @file expressions.sakura +#! @author John Christman (sorakatadzuma@gmail.com) +#! @copyright Malunal Studios, LLC. +#! @license MIT +#! +#! Contains the expression parser, a Pratt parser, which reads each operator +#! by the binding power `token_powers` gives it. Prefix and postfix operators, +#! casts, `is` tests, ternaries, `else` fallbacks, calls, indexes, and members +#! are each parsed here. + +module sakura::analyzer; + + +#! How tightly each operator binds, loosest first. An operator continues an +#! expression only where it binds tighter than what the expression began under. +enum parser::bp : u32 { + none, #! Nothing has begun. + assign, #! `=`, `+=`, and the rest, which group to the right. + fallback, #! `x else y`, which groups to the right. + ternary, #! `c ? a : b`, which groups to the right. + range, #! `a..b` and `a..=b`. + logor, #! `||` + logand, #! `&&` + bitor, #! `|` + bitxor, #! `^` + bitand, #! `&` + equality, #! `==` and `!=` + compare, #! `<`, `<=`, `>`, and `>=` + shift, #! `<<` and `>>` + sum, #! `+` and `-` + product, #! `*`, `/`, and `%` + cast, #! `as` and `is`, after a prefix operator's operand, so `-x as u8` is `(-x) as u8`. + prefix, #! What a prefix operator applies to. + postfix, #! Calls, indexing, members, `++`, and `--`. +} + +#! An expression, where struct literals are allowed. +#! @param this The parser. +#! @returns The expression's node, or an `error` node. +def parser::expression(&mut this): u32 { + return this.pratt(parser::bp::none, true); +} + +#! The expression of a condition, or of what a `for` loop or `match` takes, +#! where `{` begins the block after it rather than a struct literal. +#! @param this The parser. +#! @returns The expression's node, or an `error` node. +def parser::condition_expr(&mut this): u32 { + return this.pratt(parser::bp::none, false); +} + +#! Parses an expression by precedence climbing: an operand, then each operator +#! binding tighter than `min` with what it applies to. +#! @param this The parser. +#! @param min The power an operator must bind tighter than to be taken. +#! @param structs Whether a name followed by `{` is a struct literal, which it +#! is not in conditions, so that `if x {` opens the block. It +#! is passed down rather than kept on the parser, so nothing +#! has to put it back. +#! @returns The expression's node, or an `error` node. +def parser::pratt(&mut this, min: parser::bp, structs: bool): u32 { + return this.error_here() if !this.enter(); + + var left := this.prefix(structs); + while true { + val power := this.power(left); + break if power as u32 <= min as u32; + left = this.infix(left, power, structs); + } + + this.leave(); + return left; +} + +#! How tightly the current token binds as an operator after `left`, or `none` +#! where it ends the expression. +#! @param this The parser. +#! @param left The operand before the token. +#! @returns The power. +def parser::power(&this, left: u32): parser::bp { + val power := token_powers[this.kind as u64]; + + # `else =>` is the last arm of a match, not a fallback, and `::<` gives type + # arguments only to what a call gives, as `value_of(d)::`. + return parser::bp::none if this.check(tk::kw_else) && this.peek(1) == tk::arrow; + # Within type arguments, `>` closes them, and nothing is assigned. + if this.angled { + val kind := this.kind; + return parser::bp::none if kind == tk::more || kind == tk::moreeq || kind == tk::rshift || kind == tk::rshifteq + || power == parser::bp::assign; + } + return parser::bp::none if this.check(tk::scope) && (this.syntax.node_kinds[left] != nk::call || this.peek(1) != tk::less); + return power; +} + +#! An operand: a prefix operator and what it applies to, or a primary. +#! @param this The parser. +#! @param structs Whether a name followed by `{` is a struct literal. +#! @returns The operand's node, or an `error` node. +def parser::prefix(&mut this, structs: bool): u32 { + val token := this.index; + match this.kind { + tk::minus, tk::negate, tk::bitnot, tk::increment, tk::decrement, tk::star => { + this.advance(); + return this.make_node(nk::unary, token, this.pratt(parser::bp::prefix, structs)); + } + tk::bitand => { + this.advance(); + val mutable := this.accept(tk::kw_mut); + val operand := this.pratt(parser::bp::prefix, structs); + return this.make_node(nk::reference, token, operand, parser::bit(mutable, nf::mutable)); + } + else => return this.primary(structs); + } + + return this.primary(structs); +} + +#! The operator at the current token applied to `left`, which binds as tightly +#! as `power`. What follows an operator grouping to the right is parsed under +#! the power just below its own, so another of it continues there. +#! @param this The parser. +#! @param left The operand before the operator. +#! @param power How tightly the operator binds. +#! @param structs Whether a name followed by `{` is a struct literal. +#! @returns The node of the operator applied. +def parser::infix(&mut this, left: u32, power: parser::bp, structs: bool): u32 { + val token := this.index; + match power { + parser::bp::assign => { + this.advance(); + return this.make_node(nk::assign, token, left, this.pratt(parser::bp::none, structs)); + } + parser::bp::fallback => return this.fallback(left, structs); + parser::bp::ternary => return this.ternary(left, structs); + parser::bp::cast => return this.check(tk::kw_as) ? this.cast_to(left) : this.is_test(left); + parser::bp::postfix => return this.postfix(left); + parser::bp::range => { + this.advance(); + return this.make_node(nk::range, token, left, this.pratt(power, structs)); + } + else => { + this.advance(); + return this.make_node(nk::binary, token, left, this.pratt(power, structs)); + } + } + + return left; +} + +#! `value else fallback`, which takes what a result or a maybe holds, or else +#! what stands in for it: `else (e)` names the error, and a block standing in +#! must leave, where an expression gives the value instead. +#! @param this The parser. +#! @param value The node of the value before `else`. +#! @param structs Whether a name followed by `{` is a struct literal. +#! @returns The `fallback` node. +def parser::fallback(&mut this, value: u32, structs: bool): u32 { + val token := this.index; + this.advance(); + + # `(e)` names the error only before the block standing in, so `else (x)` + # anywhere else is the value `x`. + var error: u32 = 0; + if this.check(tk::lparen) && this.peek(1) == tk::name && this.peek(2) == tk::rparen && this.peek(3) == tk::lbrace { + this.advance(); + error = this.name_node("Expected the name of the error."); + this.advance(); + } + + val other := this.check(tk::lbrace) + ? this.block() + : this.pratt(parser::bp::assign, structs); + return this.make_node(nk::fallback, token, value, this.make_record(error, other)); +} + +#! `cond ? then : else`. The branch taken where the condition holds ends at +#! `:`, so it may be a fallback, as `ok ? parse(text) else 0 : 1`. +#! @param this The parser. +#! @param condition The condition's node. +#! @param structs Whether a name followed by `{` is a struct literal. +#! @returns The `ternary` node. +def parser::ternary(&mut this, condition: u32, structs: bool): u32 { + val token := this.index; + this.advance(); + + val then := this.pratt(parser::bp::assign, structs); + this.expect(tk::colon, "Expected `:` between the ternary branches."); + val other := this.pratt(parser::bp::fallback, structs); + return this.make_node(nk::ternary, token, condition, this.make_record(then, other)); +} + +#! `x as T`. +#! @param this The parser. +#! @param value The node of the value converted. +#! @returns The `cast` node. +def parser::cast_to(&mut this, value: u32): u32 { + val token := this.index; + this.advance(); + if this.check(tk::kw_not) { + this.fail(ec::token, + "`not` follows `is`, which it denies; `as` converts a value and has nothing to deny."); + } + + val target := this.type_expr(); + return this.make_node(nk::cast, token, value, target); +} + +#! `x is T`, `x is not field(value)`, and `x is (d)`. +#! @param this The parser. +#! @param value The node of what is tested. +#! @returns The `is_test` node. +def parser::is_test(&mut this, value: u32): u32 { + val token := this.index; + this.advance(); + + # `x is not T` denies the test, which saves writing `!(x is T)`. + var flags := parser::bit(this.accept(tk::kw_not), nf::negated); + + # `x is (d)` names the field of a union a declaration known while compiling + # describes, as `x is field` would. + if this.accept(tk::lparen) { + val named := this.expression(); + this.expect(tk::rparen, "Expected `)` after the declaration naming the field."); + flags |= nf::computed as u32; + return this.make_node(nk::is_test, token, value, this.make_record(named, 0, flags)); + } + + val target := this.type_expr(); + + # `x is field(value)` names what the field holds, as an arm of a match does. + var binding: u32 = 0; + if this.accept(tk::lparen) { + binding = this.binding(); + this.expect(tk::rparen, "Expected `)` after the name of the value."); + } + + return this.make_node(nk::is_test, token, value, this.make_record(target, binding, flags)); +} + +#! The name given what a field holds, as `value` of `is field(value)`. `&name` +#! and `&mut name` refer to the field where the union holds it, rather than +#! naming a copy of what it holds. +#! @param this The parser. +#! @returns The `name` or `reference` node, or an `error` node. +def parser::binding(&mut this): u32 { + val detail := "Expected the name to give the value the field holds, as `is field(value)`."; + return this.name_node(detail) if !this.check(tk::bitand); + + val token := this.index; + this.advance(); + val mutable := this.accept(tk::kw_mut); + return this.make_node(nk::reference, token, this.name_node(detail), parser::bit(mutable, nf::mutable)); +} + +#! One postfix operator applied to `left`: a call, indexing or slicing, a +#! member, type arguments, `++`, or `--`. +#! @param this The parser. +#! @param left The operand. +#! @returns The node of the operator applied. +def parser::postfix(&mut this, left: u32): u32 { + val token := this.index; + match this.kind { + tk::lparen => { + this.advance(); + val args := this.list(parser::item::argument, tk::rparen, "Expected `)` to close the arguments."); + return this.make_node(nk::call, token, left, args); + } + tk::lbracket => return this.subscript(left); + tk::dot => return this.member(left); + tk::scope => { + this.advance(); + return this.make_node(nk::type_args, token, left, this.type_args()); + } + else => { + this.advance(); + return this.make_node(nk::postfix, token, left); + } + } + + return left; +} + +#! `xs[i]`, or a slice, `xs[a:n]`, either of whose bounds may be left out. +#! @param this The parser. +#! @param object The node of what is indexed. +#! @returns The `index` or `slice` node. +def parser::subscript(&mut this, object: u32): u32 { + val token := this.index; + val angled := this.angled; + this.angled = false; + this.advance(); + + val start := this.check(tk::colon) ? 0 : this.expression(); + if !this.accept(tk::colon) { + this.expect(tk::rbracket, "Expected `]` to close the index."); + this.angled = angled; + return this.make_node(nk::index, token, object, start); + } + + val count := this.check(tk::rbracket) ? 0 : this.expression(); + this.expect(tk::rbracket, "Expected `]` to close the slice."); + this.angled = angled; + return this.make_node(nk::slice, token, object, this.make_record(start, count)); +} + +#! `x.name`, `x.name::`, or `x.(d)`, which names the member a declaration +#! known while compiling describes. +#! @param this The parser. +#! @param object The node of the value. +#! @returns The `member` or `member_of` node. +def parser::member(&mut this, object: u32): u32 { + val token := this.index; + this.advance(); + if this.accept(tk::lparen) { + val named := this.expression(); + this.expect(tk::rparen, "Expected `)` after the declaration naming the member."); + return this.make_node(nk::member_of, token, object, named); + } + + if !this.check(tk::name) { + this.fail(ec::ident, "Expected a member name after `.`."); + return object; + } + + val name := this.index; + this.advance(); + var types: u32 = 0; + if this.at_value_args() { + this.advance(); + types = this.type_args(); + } + + return this.make_node(nk::member, name, object, types); +} + +#! An argument of a call. `...xs` spreads a view or a pack into the arguments, +#! and is only an argument. +#! @param this The parser. +#! @returns The argument's node. +def parser::argument(&mut this): u32 { + return this.expression() if !this.check(tk::spread); + + val token := this.index; + this.advance(); + return this.make_node(nk::unary, token, this.expression()); +} diff --git a/analyzer/parser/fields.sakura b/analyzer/parser/fields.sakura new file mode 100644 index 00000000..51cc787b --- /dev/null +++ b/analyzer/parser/fields.sakura @@ -0,0 +1,63 @@ +#! @file fields.sakura +#! @author John Christman (sorakatadzuma@gmail.com) +#! @copyright Malunal Studios, LLC. +#! @license MIT +#! +#! Contains the parsing of the fields of struct literals and attributes, with +#! their spreads and renames. +module sakura::analyzer; + + +#! The fields of a struct literal or an attribute, from its `{` to its `}`. +#! @param this The parser. +#! @returns The run of `field_init` nodes. +def parser::field_list(&mut this): u32 { + this.advance(); + return this.list(parser::item::field, tk::rbrace, "Expected `}` to close the structure literal."); +} + +#! A field of a struct literal or an attribute, a `field_init`, whose token is +#! the field where it is named, as `x` of `x = 1`, which its `named` flag says, +#! and the first of its value where it is given by position. +#! @param this The parser. +#! @returns The `field_init` node. +def parser::field_init(&mut this): u32 { + val token := this.index; + val named := this.check(tk::name) && this.peek(1) == tk::assign; + if named { + this.advance(); + this.advance(); + } + + return this.make_node(nk::field_init, token, this.expression(), parser::bit(named, nf::named)); +} + +#! The type of a field that spreads another's fields into its own, as `...T` or +#! `...T{ a as b }`, from its `...`. +#! @param this The parser. +#! @returns The `spread` node. +def parser::spread(&mut this): u32 { + val token := this.index; + this.advance(); + + val type_name := this.type_name(); + return this.make_node(nk::spread, token, type_name) if !this.accept(tk::lbrace); + + val renames := this.list(parser::item::rename, tk::rbrace, "Expected `}` to close the renames."); + return this.make_node(nk::spread, token, type_name, renames); +} + +#! `old as new`, which gives a spread field another name. +#! @param this The parser. +#! @returns The `rename` node, or an `error` node. +def parser::rename(&mut this): u32 { + if !this.check(tk::name) { + this.fail(ec::ident, "Expected the name of a field to rename."); + return this.error_here(); + } + + val old := this.index; + this.advance(); + this.expect(tk::kw_as, "Expected `as` followed by the new name."); + return this.make_node(nk::rename, old, this.name_node("Expected the new field name.")); +} diff --git a/analyzer/parser/helpers.sakura b/analyzer/parser/helpers.sakura new file mode 100644 index 00000000..999a8349 --- /dev/null +++ b/analyzer/parser/helpers.sakura @@ -0,0 +1,633 @@ +#! @file helpers.sakura +#! @author John Christman (sorakatadzuma@gmail.com) +#! @copyright Malunal Studios, LLC. +#! @license MIT +#! +#! Contains what the rest of the parser is made from: moving through the tokens, +#! making nodes, records, and runs, starting declarations, making notes, lists, +#! and recovering from what is wrong to parse what follows. + +module sakura::analyzer; + + +# Tokens + +#! Reads the kind of the current token into `kind`, which is `eof` at the limit. +#! @param this The parser. +def parser::sync(&mut this): void { + this.kind = this.index < this.limit + ? this.syntax.token_kinds[this.index] + : tk::eof; +} + +#! The kind of the token `ahead` past the current one, or `eof` past the limit. +#! @param this The parser. +#! @param ahead How many tokens past the current one, where 0 is the current +#! one. +#! @returns The token's kind. +def parser::peek(&this, ahead: u32): tk { + val at := this.index + ahead; + return at < this.limit + ? this.syntax.token_kinds[at] + : tk::eof; +} + +#! Moves to the next token, staying on the `eof` that ends them. +#! +#! A `>>`, `>=`, or `>>=` is followed by a token at each `>` and `=` after its +#! first, which `close_angle` takes one at a time, and which an operator is +#! moved past with, as one token for each byte it spans. +#! @param this The parser. +def parser::advance(&mut this): void { + return if this.kind == tk::eof; + if this.kind.has(tt::angle) { + this.index += this.kind.width; + } else { + this.index++; + } + this.sync(); +} + +def parser::check(&this, kind: tk): bool { + return this.kind == kind; +} + +#! Whether the current token is the name of the ID, as `names::this_id`. +#! @param this The parser. +#! @param word The ID of the name. +#! @returns Whether the current token is that name. +def parser::check_word(&this, word: u32): bool { + return this.kind == tk::name && this.syntax.token_names[this.index] == word; +} + +#! Whether the current token's kind has the trait. +#! @param this The parser. +#! @param which The trait to ask of the token's kind. +#! @returns Whether its kind has it. +def parser::at(&this, which: tt): bool { + return this.kind.has(which); +} + +#! Moves past the current token when it is of the kind. +#! @param this The parser. +#! @param kind The kind of token to move past. +#! @returns Whether it was, and so was moved past. +def parser::accept(&mut this, kind: tk): bool { + return false if this.kind != kind; + this.advance(); + return true; +} + +#! Moves past the current token when it is of the kind, or else reports the +#! detail and panics. +#! @param this The parser. +#! @param kind The kind of token wanted. +#! @param detail What the note says where it is not, as `Expected ";" after +#! the statement.`. +#! @returns Whether it was of the kind. +def parser::expect(&mut this, kind: tk, detail: strview): bool { + return true if this.accept(kind); + this.fail(ec::token, detail); + return false; +} + +#! Moves past the `>` closing type arguments or parameters, which may be the +#! first of `>>`, `>=`, or `>>=`. The lexer made a token of what is left of +#! those, which becomes the current token: `>`, `=`, or `>=`. +#! @param this The parser. +#! @param detail What the note says where no `>` is there. +#! @returns Whether a `>` was moved past. +def parser::close_angle(&mut this, detail: strview): bool { + if !this.at(tt::angle) { + this.fail(ec::token, detail); + return false; + } + + this.index++; + this.sync(); + return true; +} + +#! Whether the type whose `<` is at the token follows `as` or `is`, where a `<` +#! always begins type arguments, so what looks like a comparison is not one. +#! @param this The parser. +#! @param at The token of the `<`. +#! @returns Whether `as` or `is` comes before the type. +def parser::follows_cast(&this, at: u32): bool { + var back := at; + while back > 0 { + back--; + val kind := this.syntax.token_kinds[back]; + return kind == tk::kw_as || kind == tk::kw_is if !kind.has(tt::piece); + } + + return false; +} + + +# Nodes + +#! Appends a node, whose last token is the last the parser moved past, or its +#! own where it moved past none since. +#! @param this The parser. +#! @param kind The node's kind. +#! @param token Its token. +#! @param left Its first slot, which its kind's shape says the meaning of. +#! @param right Its second slot. +#! @returns The node. +def parser::make_node( + &mut this, + kind: nk, + token: u32, + left: u32 = 0, + right: u32 = 0 +): u32 { + val end := this.index > token ? this.index - 1 : token; + return this.syntax.add_node(kind, token, left, right, end); +} + +#! An `error` node at the token, standing where the parser made no sense of the +#! source, holding the run of what it did parse there, so that tools still find +#! what is within it. +#! @param this The parser. +#! @param token The token it stands at. +#! @param held The run of what was parsed there, or 0. +#! @returns The node. +def parser::error(&mut this, token: u32, held: u32 = 0): u32 { + return this.make_node(nk::error, token, held); +} + +#! An `error` node at the current token, holding nothing. +#! @param this The parser. +#! @returns The node. +def parser::error_here(&mut this): u32 { + return this.error(this.index); +} + +#! A `when_block`, `if_stmt`, `if_const`, or `ternary`: a condition, and what is +#! taken where it holds and where it does not. +#! @param this The parser. +#! @param kind The node's kind. +#! @param token Its token. +#! @param condition The condition. +#! @param then What is taken where it holds. +#! @param other What is taken where it does not, or 0. +#! @returns The node. +def parser::branch(&mut this, kind: nk, token: u32, condition: u32, then: u32, other: u32): u32 { + return this.make_node(kind, token, condition, this.make_record(then, other)); +} + +#! A `name` node of the current token, which is moved past. +#! @param this The parser. +#! @param detail What the note says where the current token is no name. +#! @returns The node, or an `error` node where the token is no name. +def parser::name_node(&mut this, detail: strview): u32 { + if !this.check(tk::name) { + this.fail(ec::ident, detail); + return this.error_here(); + } + + this.advance(); + return this.make_node(nk::name, this.index - 1); +} + +#! Writes a record of a node's slots to `extras`, unless every slot is 0, where +#! the zeros `extras` begins with stand for it. +#! @param this The parser. +#! @param slots The node's slots, in the order its shape lists them. +#! @returns Where the record begins, for the slot of the node holding it. +def parser::make_record(&mut this, slots: u32...): u32 { + var empty := true; + for slot in slots { + empty = empty && slot == 0; + } + return 0 if empty; + + val at := this.syntax.extras.length as u32; + this.syntax.extras.extend(slots); + return at; +} + +#! Where the nodes of a run begin on the scratchpad, for `make_run`. +#! @param this The parser. +#! @returns The scratchpad's length. +val parser::mark: u64 { get => this.scratch.length; } + +#! Holds a node of a run being parsed on the scratchpad. +#! @param this The parser. +#! @param node The node. +def parser::push(&mut this, node: u32): void { + this.scratch.push(node); +} + +#! Moves the nodes held on the scratchpad since the mark to a run in `extras`. +#! @param this The parser. +#! @param mark Where the nodes begin, as `mark` gave it. +#! @returns Where the run begins, or 0 for a run of no nodes. +def parser::make_run(&mut this, mark: u64): u32 { + val count := this.scratch.length - mark; + return 0 if count == 0; + + val at := this.syntax.extras.length as u32; + this.syntax.extras.append(count as u32); + this.syntax.extras.extend(span::::over(this.scratch.view().data + mark, count)); + + this.drop(mark); + return at; +} + +#! A run of the nodes given, leaving out those that are absent. +#! @param this The parser. +#! @param nodes The nodes, of which 0 is left out. +#! @returns Where the run begins, or 0 where it holds none. +def parser::run_of(&mut this, nodes: u32...): u32 { + val mark := this.mark; + for node in nodes { + if node != 0 { + this.push(node); + } + } + return this.make_run(mark); +} + +#! Lets go of the nodes held on the scratchpad since the mark. +#! @param this The parser. +#! @param mark Where the nodes begin, as `mark` gave it. +def parser::drop(&mut this, mark: u64): void { + this.scratch.resize(mark); +} + +#! A run of the nodes of `first` followed by those of `second`. +#! @param this The parser. +#! @param first The run whose nodes come first. +#! @param second The run whose nodes come after. +#! @returns The joined run, or 0 where both are empty. +def parser::join_runs(&mut this, first: u32, second: u32): u32 { + return second if first == 0; + return first if second == 0; + + val mark := this.mark; + for &node in this.run_view(first) { this.push(node); } + for &node in this.run_view(second) { this.push(node); } + return this.make_run(mark); +} + +#! How many nodes the run holds. +#! @param this The parser. +#! @param run Where the run begins. +#! @returns How many nodes it holds. +def parser::run_length(&this, run: u32): u32 { + return this.syntax.run_length(run); +} + +#! The node at the index of the run. +#! @param this The parser. +#! @param run Where the run begins. +#! @param index The position, below its length. +#! @returns The node. +def parser::run_at(&this, run: u32, index: u32): u32 { + return this.syntax.run_at(run, index); +} + +#! The nodes of the run, where they are. +#! @param this The parser. +#! @param run Where the run begins. +#! @returns The nodes, a view only good until another run or record is made. +def parser::run_view(&this, run: u32): span { + return this.syntax.run_view(run); +} + +#! The ID of the name the node's token is. +#! @param this The parser. +#! @param node The node. +#! @returns The name's ID. +def parser::name_of(&this, node: u32): u32 { + return this.syntax.token_names[this.syntax.node_tokens[node]]; +} + +#! The bit of a flag when it is on, to be or'd with others into a mask, as a +#! `flags` slot. +#! @tparam T The enum of flags. +#! @param on Whether the flag is on. +#! @param flag The flag. +#! @returns The flag's bit, or 0 where it is off. +def parser::bit(on: bool, flag: T): u32 where T: ordinal { + return on ? flag as u32 : 0; +} + + +# Declarations + +#! What comes before a declaration: its attributes, `pub`, and the token it +#! begins at, which its documentation is written before. +struct parser::lead { + var attrs: u32; #! The run of its attributes. + var exported: bool; #! `pub`. + var start: u32; #! The token it begins at. +} + +#! Where a declaration is written, which says what it may be. +enum parser::place { + top, #! At the top level of a file, or within a `when` there. + local, #! Within a function. + field, #! Within a struct or union. + member, #! Within a trait. +} + +#! The lead of a declaration beginning at the current token, with nothing before +#! it. +#! @param this The parser. +#! @returns The lead. +def parser::bare_lead(&this): parser::lead { + return parser::lead { start = this.index }; +} + +#! Records where a declaration began, which says what documents it. +#! @param this The parser. +#! @param made The declaration's node. +#! @param lead What came before it: where it began, and its documentation. +#! @returns The declaration. +def parser::declared_at(&mut this, made: u32, lead: &parser::lead): u32 { + if made != 0 && this.syntax.node_kinds[made] != nk::error { + this.syntax.starts.set(made as u64, lead.start); + } + return made; +} + + +# Notes + +#! Reports an error at the current token, then panics, which silences notes +#! until the parser resynchronizes so that one mistake is one note. +#! @param this The parser. +#! @param code What kind of error it is. +#! @param detail What the note says. +def parser::fail(&mut this, code: ec, detail: strview): void { + this.fail_at(this.index, code, detail); +} + +def parser::fail_at(&mut this, token: u32, code: ec, detail: strview): void { + # Failing at a limit short of the end of the tokens says a reparse cut what it + # parsed short, which a whole parse would have read on past. + if this.kind == tk::eof && this.limit + 1 < this.syntax.token_count as u32 { + this.cut = true; + } + + return if this.panic; + this.report_at(token, code, detail); + this.panic = true; +} + +#! Reports an error at the current token without panicking, for mistakes the +#! parser reads past knowing what was meant. +#! @param this The parser. +#! @param code What kind of error it is. +#! @param detail What the note says. +def parser::report(&mut this, code: ec, detail: strview): void { + this.report_at(this.index, code, detail); +} + +#! Reports an error at the token. A note saying what was expected says what was +#! found instead, the token it is at, which `note::message` spells. +#! @param this The parser. +#! @param token The token the error is at. +#! @param code What kind of error it is. +#! @param detail What the note says. +def parser::report_at(&mut this, token: u32, code: ec, detail: strview): void { + return if this.panic || this.halted || !this.sink.admits(); + var made := note { + file = this.file, + offset = this.syntax.token_offsets[token], + length = this.syntax.token_length(token, this.names), + code = code, + detail = string::from(detail, nothing {}), + found = detail.starts_with("Expected") + }; + this.sink.give(&mut made); +} + + +# Nesting + +#! Goes one level deeper, unless that is past `max_depth`, where the rest of the +#! declaration is given up on: the tokens seem to end where it does, so that +#! everything parsing it returns, and the top level resumes after it. +#! @param this The parser. +#! @returns Whether the parser went deeper, and must `leave` again. +def parser::enter(&mut this): bool { + if this.depth < parser::max_depth { + this.depth++; + return true; + } + + if !this.halted { + this.panic = false; + this.fail(ec::syntax, "Nesting exceeds the maximum depth."); + + val end := this.declaration_end(); + this.index = end; + this.limit = end; + this.halted = true; + this.sync(); + } + return false; +} + +def parser::leave(&mut this): void { + this.depth--; +} + +#! Where the top-level declaration the parser is within ends, from where it +#! began: past the `}` closing the braces it opens, or the `;` ending it outside +#! any, whichever comes past the current token. +#! @param this The parser. +#! @returns The token after the declaration. +def parser::declaration_end(&this): u32 { + val last := this.syntax.token_count as u32 - 1; + var braces: u32 = 0; + for at in this.begun..last { + val kind := this.syntax.token_kinds[at]; + if kind == tk::lbrace { + braces++; + } else if kind == tk::rbrace { + return at + 1 if braces <= 1 && at >= this.index; + braces = braces > 0 ? braces - 1 : 0; + } else if kind == tk::semicolon && braces == 0 && at >= this.index { + return at + 1; + } + } + + return last; +} + +#! Takes up the tokens after a declaration given up on, through the limit. +#! @param this The parser. +#! @param limit The last token to take up. +def parser::resume(&mut this, limit: u32): void { + this.limit = limit; + this.halted = false; + this.panic = false; + this.sync(); +} + + +# Recovery + +#! Where the parser resumes after an error, which decides the tokens it stops +#! at. +enum parser::scope { + document, #! The top level of a file. + declarations, #! Within a `when` at the top level. + block, #! Statements. + fields, #! The members of a struct or union. + members, #! The members of a trait. +} + +#! Whether the current token begins the next item of the scope. +#! @param this The parser. +#! @param scope What the parser is within. +#! @returns Whether the token begins an item of it. +def parser::resumes(&this, scope: parser::scope): bool { + return match scope { + parser::scope::document => this.at(tt::declares) || this.at(tt::imports), + parser::scope::declarations => this.at(tt::declares), + parser::scope::block => this.at(tt::states), + parser::scope::fields => this.at(tt::fields), + parser::scope::members => this.at(tt::members), + else => false + }; +} + +#! Skips tokens until one that can begin the next item of the scope, stepping +#! over balanced braces, then stops panicking. Every token it stops on is +#! consumed by the item parser, or ends the enclosing loop, so parsing always +#! makes progress. +#! @param this The parser. +#! @param scope What the parser is within. +def parser::synchronize(&mut this, scope: parser::scope): void { + var braces: u32 = 0; + while !this.check(tk::eof) { + if braces == 0 { + break if this.resumes(scope); + if this.check(tk::semicolon) { + this.advance(); + break; + } + + if this.check(tk::rbrace) { + if scope == parser::scope::document { + this.advance(); + } + break; + } + } + + if this.check(tk::lbrace) { + braces++; + } else if this.check(tk::rbrace) { + braces--; + if braces == 0 { + this.advance(); + break; + } + } + this.advance(); + } + + this.panic = false; +} + +#! Skips to the `}` closing the braces the parser is within, without moving +#! past it, then stops panicking. +#! @param this The parser. +def parser::skip_to_close(&mut this): void { + var braces: u32 = 0; + while !this.check(tk::eof) { + if this.check(tk::lbrace) { + braces++; + } else if this.check(tk::rbrace) { + break if braces == 0; + braces--; + } + this.advance(); + } + + this.panic = false; +} + + +# Lists + +#! What a list holds, which `list_item` parses one of. +enum parser::item { + argument, #! Of a call. + element, #! Of an array. + field, #! Of a struct literal or an attribute. + param_type, #! Of a function type. + rename, #! Of a spread field. + enumerator, #! Of an enum. + value_arm, #! Of a match used as a value. +} + +def parser::list_item(&mut this, kind: parser::item): u32 { + return match kind { + parser::item::argument => this.argument(), + parser::item::element => this.expression(), + parser::item::field => this.field_init(), + parser::item::param_type => this.spread_type(), + parser::item::rename => this.rename(), + parser::item::enumerator => this.enumerator(), + parser::item::value_arm => this.arm(true), + else => this.error_here() + }; +} + +#! The items of a list separated by commas, which may end with one, through the +#! token closing it. An item that fails is skipped to the comma or closing token +#! after it, so one mistake leaves the rest of the list parsed. +#! @param this The parser. +#! @param kind What the items are. +#! @param close The kind of token closing the list. +#! @param detail What the note says where the closing token is missing. +#! @returns The run of items. +def parser::list(&mut this, kind: parser::item, close: tk, detail: strview): u32 { + val angled := this.angled; + this.angled = false; + val mark := this.mark; + while !this.check(close) && !this.check(tk::eof) { + this.push(this.list_item(kind)); + break if this.panic && !this.skip_item(close); + break if !this.accept(tk::comma); + } + + val items := this.make_run(mark); + this.expect(close, detail); + this.angled = angled; + return items; +} + +#! Skips what is left of an item that failed, stepping over what is nested in +#! it, to the comma or closing token after it, then stops panicking. It gives up +#! at a `;`, or at a closing token of something outside the list, which the +#! enclosing parser recovers at instead. +#! @param this The parser. +#! @param close The kind of token closing the list. +#! @returns Whether the list goes on. +def parser::skip_item(&mut this, close: tk): bool { + var depth: u32 = 0; + while !this.check(tk::eof) { + if depth == 0 && (this.check(tk::comma) || this.check(close)) { + this.panic = false; + return true; + } + + val closes := this.at(tt::closes); + return false if depth == 0 && (closes || this.check(tk::semicolon) || this.check(tk::istring_mid)); + + if this.at(tt::opens) { depth++; } + if closes { depth--; } + this.advance(); + } + + return false; +} diff --git a/analyzer/parser/primary.sakura b/analyzer/parser/primary.sakura new file mode 100644 index 00000000..1b880c7b --- /dev/null +++ b/analyzer/parser/primary.sakura @@ -0,0 +1,200 @@ +#! @file primary.sakura +#! @author John Christman (sorakatadzuma@gmail.com) +#! @copyright Malunal Studios, LLC. +#! @license MIT +#! +#! Contains the parsing of primaries, which operators are applied to: literals, +#! interpolated strings, names and paths with their struct literals, arrays, +#! lambdas, `type_of`, and expressions in parentheses. + +module sakura::analyzer; + + +#! What an expression is built from: a literal, a name or path, a struct +#! literal, an expression in parentheses, a lambda, an array, a match used as a +#! value, or `type_of(d)`, a type named to test it with `is`. +#! @param this The parser. +#! @param structs Whether a name followed by `{` is a struct literal. +#! @returns The node, or an `error` node. +def parser::primary(&mut this, structs: bool): u32 { + # `type_of(d)` is a type, which an expression names only to test it, as + # `type_of(d) is copyable`. + if this.check_word(names::type_of_id) && this.peek(1) == tk::lparen { + return this.type_primary(); + } + # Within an `ensures`, `old(e)` is what `e` was where it was reached. + if this.in_ensures && this.check_word(names::old_id) && this.peek(1) == tk::lparen { + return this.old_value(); + } + + val token := this.index; + match this.kind { + tk::signed, tk::unsigned, tk::float => return this.literal(nk::number); + tk::char => return this.literal(nk::character); + tk::string => return this.literal(nk::string); + tk::kw_true, tk::kw_false => return this.literal(nk::boolean); + tk::kw_null => return this.literal(nk::null_lit); + tk::istring, tk::istring_beg => return this.istring(); + tk::kw_match => return this.match_expr(true); + tk::kw_def => return this.lambda(); + tk::lbracket => return this.array(); + tk::name => return this.named(structs); + + # What is between parentheses may be a struct literal. + tk::lparen => { + val angled := this.angled; + this.angled = false; + this.advance(); + val inner := this.expression(); + this.expect(tk::rparen, "Expected `)` to close the expression."); + this.angled = angled; + return inner; + } + + # The lexer reported what is wrong with a malformed literal, so it stands as + # an error with nothing more said. + tk::bad_number, tk::bad_quote => {} + else => { + this.fail(ec::expr, "Expected an expression."); + return this.error_here(); + } + } + + this.advance(); + return this.error(token); +} + +#! `old(e)` within an `ensures`: what `e` was where the `ensures` was reached. +#! @param this The parser. +#! @returns The `old_value` node. +def parser::old_value(&mut this): u32 { + val token := this.index; + this.advance(); + this.advance(); + val inner := this.expression(); + this.expect(tk::rparen, "Expected `)` to close `old`, which takes one expression."); + return this.make_node(nk::old_value, token, inner); +} + +#! A literal of the kind, which its token alone describes. +#! @param this The parser. +#! @param kind The node's kind. +#! @returns The node. +def parser::literal(&mut this, kind: nk): u32 { + this.advance(); + return this.make_node(kind, this.index - 1); +} + +#! An interpolated string, whose run holds its text as `string` nodes, the token +#! of each a piece of it, between which come the expressions of its holes: the +#! `istring_beg` before the first hole, an `istring_mid` between two holes, and +#! the `istring_end` after the last. One with no holes is one `istring` piece. +#! @param this The parser. +#! @returns The `istring` node. +def parser::istring(&mut this): u32 { + val token := this.index; + val mark := this.mark; + this.push(this.literal(nk::string)); + val angled := this.angled; + this.angled = false; + if this.syntax.token_kinds[token] == tk::istring_beg { + while true { + this.push(this.expression()); + if this.check(tk::istring_mid) { + this.push(this.literal(nk::string)); + continue; + } + + if this.check(tk::istring_end) { + this.push(this.literal(nk::string)); + break; + } + + this.fail(ec::token, "Expected `}` after the interpolated expression."); + this.skip_hole(); + break; + } + } + this.angled = angled; + + return this.make_node(nk::istring, token, this.make_run(mark)); +} + +#! Skips past the end of the interpolated string whose hole the parser is +#! within, stepping over the strings within it. +#! @param this The parser. +def parser::skip_hole(&mut this): void { + var depth: u32 = 0; + while !this.check(tk::eof) { + if this.check(tk::istring_beg) { + depth++; + } else if this.check(tk::istring_end) { + if depth == 0 { + this.advance(); + break; + } + depth--; + } + this.advance(); + } +} + +#! A name, a path, as `math::max::`, or a struct literal of either, where +#! they are allowed. +#! @param this The parser. +#! @param structs Whether a struct literal may follow. +#! @returns The `name`, `path`, or `construct` node. +def parser::named(&mut this, structs: bool): u32 { + val token := this.index; + var made: u32 = 0; + if this.peek(1) == tk::scope { + made = this.make_node(nk::path, token, this.segments(parser::args::values)); + } else { + this.advance(); + made = this.make_node(nk::name, token); + } + + return made if !structs || !this.check(tk::lbrace); + + # The literal's type is the name read as a type: a path's segments are a type + # name's, and a name is a type name of one segment, which holds no run. + this.syntax.node_kinds[made] = nk::type_name; + + val brace := this.index; + return this.make_node(nk::construct, brace, made, this.field_list()); +} + +#! `[a, b, c]`. +#! @param this The parser. +#! @returns The `array` node. +def parser::array(&mut this): u32 { + val token := this.index; + this.advance(); + + val elements := this.list(parser::item::element, tk::rbracket, "Expected `]` to close the array."); + return this.make_node(nk::array, token, elements); +} + +#! `def(params): result { body }`, or `def(params) => value`, which returns the +#! value, or evaluates it for `void`. Its parameter types and result may be left +#! out. +#! @param this The parser. +#! @returns The `lambda` node. +def parser::lambda(&mut this): u32 { + val token := this.index; + val angled := this.angled; + this.angled = false; + # A lambda's body is checked where it is called, which no `old` reaches back + # from. + val ensures := this.in_ensures; + this.in_ensures = false; + this.advance(); + + val signature := this.params(true, false); + val body := this.accept(tk::arrow) + ? this.expression() + : this.block(); + this.angled = angled; + this.in_ensures = ensures; + return this.make_node(nk::lambda, token, signature.params, this.make_record(signature.result, body)); +} diff --git a/analyzer/parser/reparse.sakura b/analyzer/parser/reparse.sakura new file mode 100644 index 00000000..1072d7c3 --- /dev/null +++ b/analyzer/parser/reparse.sakura @@ -0,0 +1,229 @@ +#! @file reparse.sakura +#! @author John Christman (sorakatadzuma@gmail.com) +#! @copyright Malunal Studios, LLC. +#! @license MIT +#! +#! Contains `syntax::reparse`, which parses only the top-level declarations an +#! edit touched, and keeps the trees of the rest. + +module sakura::analyzer; + + +#! Reparses a file after an edit, keeping the trees of the top-level +#! declarations the edit did not touch, and parsing again only those it did. +#! +#! The edited text is lexed whole into `fresh`, which is cheap, and its tokens +#! are compared with the old ones from each end to find what changed. The +#! declarations around the change are parsed again from the fresh tokens, and +#! those after it keep their nodes, whose tokens move by how many the edit added +#! or took away. Where a declaration parsed again runs into where the change +#! ends, as one that lost its closing `}` does, the file is parsed whole +#! instead, so the tree is always the one a whole parse makes. +#! +#! The nodes of the declarations parsed again are left behind, unreachable. Once +#! there are as many nodes or extras again as the last whole parse made, the +#! file is parsed whole, which lets go of them, so a file edited for a long +#! while does not keep growing. The indexes of every node change when it does. +#! @param this The syntax tree. +#! @param fresh The edited text, lexed: its tokens, documentation, and +#! comments. +#! @param names The names `fresh` was lexed with. +#! @param document The `document` node of this syntax. +#! @param notes The notes of this file, both the lexer's and the +#! parser's. +#! @param fresh_notes What the lexer noted of the edited text, which are moved +#! into `notes`. +#! @param file The index of the file. +#! @returns The `document` node. +pub def syntax::reparse( + &mut this, + fresh: &mut syntax, + names: &names, + document: u32, + notes: &mut vector, + fresh_notes: &mut vector, + file: u32 +): u32 { + val old_count := this.token_count as u32; + val new_count := fresh.token_count as u32; + val bytes := fresh.token_offsets[new_count - 1] as i64 - this.token_offsets[old_count - 1] as i64; + val shift := new_count as i64 - old_count as i64; + + # What is the same before the change, and after it, where it has moved. + var same_before: u32 = 0; + while same_before < old_count - 1 && same_before < new_count - 1 + && this.same_token(fresh, same_before, same_before, 0) { + same_before++; + } + + var same_after: u32 = 0; + while same_after < old_count - 1 - same_before && same_after < new_count - 1 - same_before + && this.same_token(fresh, old_count - 2 - same_after, new_count - 2 - same_after, bytes) { + same_after++; + } + + val changed_end := old_count - 1 - same_after; + + # The declarations the change touches, from `first` through `last`, and the + # tokens they and the change span. + val decls: u32 = this.node_lefts[document]; + val count := this.run_length(decls); + var first := count; + for i in 0..count { + if this.node_end(this.run_at(decls, i as u32)) >= same_before { + first = i as u32; + break; + } + } + + var last := first; + for i in first..count { + break if this.start_of(this.run_at(decls, i as u32)) >= changed_end && i > first; + last = i as u32; + } + + var from := same_before; + var to := changed_end; + if first < count { + val start := this.start_of(this.run_at(decls, first)); + val end := this.node_end(this.run_at(decls, last)) + 1; + from = start < from ? start : from; + to = end > to ? end : to; + } + + # The notes of what is parsed again, and all of the lexer's, are made again. + # They are put back in the order a whole parse makes them: the lexer's, then + # the parser's along the text, those after the change moving with it. + val from_byte := this.token_offsets[from]; + val to_byte := this.token_offsets[to < old_count - 1 ? to : old_count - 1]; + var before := vector::::new(); + var after := vector::::new(); + for &mut each in notes { + continue if each.lexed; + if each.offset < from_byte { + before.append(move(each)); + continue; + } + + continue if each.offset < to_byte; + each.offset = (each.offset as i64 + bytes) as u32; + after.append(move(each)); + } + + notes.clear(); + for &mut each in fresh_notes { notes.append(move(each)); } + val kept := before.length + after.length; + for &mut each in before { notes.append(move(each)); } + + # The nodes after the change move with their tokens, and their ends with + # them, which are held as how far past their tokens they are. + for at in 1..this.node_count { + if this.node_tokens[at] >= to { + this.node_tokens[at] = (this.node_tokens[at] as i64 + shift) as u32; + } + } + + var moved := vector::::new(); + for at in 0..this.starts.capacity { + if this.starts.key_at(at) != keymap::free && this.starts.value_at(at) >= to { + moved.append(this.starts.key_at(at)); + } + } + for key in moved { + this.starts.set(key, (this.starts.get_or(&key, 0) as i64 + shift) as u32); + } + + this.take_tokens(fresh); + + # The declarations around the change are parsed again, and their run takes + # the place of theirs among the rest. + val limit := (to as i64 + shift) as u32; + var parsing := parser::new(this, names, notes, file); + parsing.index = from; + parsing.limit = limit; + parsing.sink.count = kept as u32; + parsing.sync(); + + val mark := parsing.mark; + for i in 0..first { parsing.push(this.run_at(decls, i as u32)); } + + # Where the parser reached as many notes as it makes, a whole parse would have + # stopped somewhere else, so it is what tells which are made. + val made := parsing.declarations(limit); + if parsing.cut || parsing.sink.full { + return this.parse_again(document, names, notes, file); + } + + for &mut each in after { notes.append(move(each)); } + + for &node in this.run_view(made) { parsing.push(node); } + for i in (last + 1)..count { parsing.push(this.run_at(decls, i as u32)); } + + val declared := parsing.make_run(mark); + this.node_lefts[document] = declared; + this.set_node_end(document, this.token_count as u32 - 1); + + if this.node_count > this.whole_nodes * 2 || this.extras.length > this.whole_extras * 2 { + return this.parse_again(document, names, notes, file); + } + return document; +} + +#! Whether the old token and the fresh one are the same, the fresh one having +#! moved `bytes` along the text. +#! @param this The syntax tree. +#! @param fresh The syntax lexed again. +#! @param old The old token. +#! @param now The fresh token. +#! @param bytes How far the edit moved the fresh one, which is negative where +#! text was taken out. +#! @returns Whether they are. +def syntax::same_token(&this, fresh: &syntax, old: u32, now: u32, bytes: i64): bool { + val kind := this.token_kinds[old]; + return kind == fresh.token_kinds[now] + && this.token_names[old] == fresh.token_names[now] + && this.token_offsets[old] as i64 + bytes == fresh.token_offsets[now] as i64 + && (kind == tk::name || kind.width != 0 || this.literal_length(old) == fresh.literal_length(now)); +} + +#! Takes the tokens, documentation, and comments of `fresh` for its own. +#! @param this The syntax tree. +#! @param fresh The syntax lexed again, which is left without them. +def syntax::take_tokens(&mut this, fresh: &mut syntax): void { + this.token_kinds = move(&mut fresh.token_kinds); + this.token_offsets = move(&mut fresh.token_offsets); + this.token_names = move(&mut fresh.token_names); + this.literal_tokens = move(&mut fresh.literal_tokens); + this.literal_lengths = move(&mut fresh.literal_lengths); + this.docs = move(&mut fresh.docs); + this.comments = move(&mut fresh.comments); +} + +#! Parses the whole file again, from the tokens it already took. +#! @param this The syntax tree. +#! @param document The `document` node to parse into. +#! @param names The names its tokens were lexed with. +#! @param notes The file's notes, the lexer's first, which are kept, and +#! then the parser's, which are made again. +#! @param file The file's index. +#! @returns The `document` node. +def syntax::parse_again( + &mut this, + document: u32, + names: &names, + notes: &mut vector, + file: u32 +): u32 { + this.reset(); + this.parses++; + var lexed: u64 = 0; + while lexed < notes.length && notes[lexed].lexed { + lexed++; + } + while notes.length > lexed { + notes.truncate(); + } + + var parsing := parser::new(this, names, notes, file); + return parsing.parse(); +} diff --git a/analyzer/parser/statements.sakura b/analyzer/parser/statements.sakura new file mode 100644 index 00000000..24896de7 --- /dev/null +++ b/analyzer/parser/statements.sakura @@ -0,0 +1,352 @@ +#! @file statements.sakura +#! @author John Christman (sorakatadzuma@gmail.com) +#! @copyright Malunal Studios, LLC. +#! @license MIT +#! +#! Contains the parsing of blocks and the statements within them: `if`, `while`, +#! `for`, `match`, jumps, contracts, local functions, local variables, and the +#! expressions and assignments written as statements. + +module sakura::analyzer; + + +#! `{ statements }`. +#! @param this The parser. +#! @returns The `block` node. +def parser::block(&mut this): u32 { + if !this.check(tk::lbrace) { + this.fail(ec::token, "Expected `{` to begin a block."); + return this.error_here(); + } + + val token := this.index; + val angled := this.angled; + this.angled = false; + this.advance(); + + val mark := this.mark; + while !this.check(tk::rbrace) && !this.check(tk::eof) { + this.push(this.statement()); + if this.panic { + this.synchronize(parser::scope::block); + } + } + + val statements := this.make_run(mark); + this.expect(tk::rbrace, "Expected `}` to close the block."); + this.angled = angled; + return this.make_node(nk::block, token, statements); +} + +def parser::statement(&mut this): u32 { + return this.error_here() if !this.enter(); + + var made: u32 = 0; + match this.kind { + tk::kw_pub => { + this.report(ec::token, + "Only a declaration outside a function is `pub`, since nothing within one is reached by name from elsewhere."); + this.advance(); + made = this.statement(); + } + # The statement is kept with the attributes, within an `error` node. + tk::attr => { + val token := this.index; + this.report(ec::token, + "Attributes describe declarations outside a function, since nothing within one is reached by name from elsewhere."); + val attrs := this.attributes(); + val held := this.panic ? 0 : this.statement(); + made = this.error(token, this.join_runs(attrs, this.run_of(held))); + } + tk::kw_val, tk::kw_var => { + val lead := this.bare_lead(); + made = this.variable(&lead, parser::place::local); + } + tk::kw_const => { + # A function within a block lives in its frame, which no constant can reach. + if this.peek(1) == tk::kw_def { + this.report(ec::token, "A `const def` is declared outside any function, where constants can call it."); + this.advance(); + made = this.peek(1) == tk::name ? this.local_function() : this.simple(); + } else { + val lead := this.bare_lead(); + made = this.variable(&lead, parser::place::local); + } + } + tk::kw_if => made = this.if_stmt(); + tk::kw_when => made = this.when_block(false); + tk::kw_while => made = this.while_stmt(); + tk::kw_for => made = this.for_stmt(); + tk::kw_match => made = this.match_expr(false); + tk::kw_ret => made = this.jump(nk::return_stmt); + tk::kw_break => made = this.jump(nk::break_stmt); + tk::kw_cont => made = this.jump(nk::continue_stmt); + tk::lbrace => made = this.block(); + tk::kw_def => made = this.peek(1) == tk::name ? this.local_function() : this.simple(); + else => made = this.contract_word() ? this.contract() : this.simple(); + } + + this.leave(); + return made; +} + +#! Whether the statement is a contract: `expects`, `asserts`, or `ensures` +#! before `(`. Anywhere else, each is a name, as `t.expects(x)` calls a method. +#! @param this The parser. +#! @returns Whether it is. +def parser::contract_word(&this): bool { + return false if this.kind != tk::name || this.peek(1) != tk::lparen; + val word := this.syntax.token_names[this.index]; + return word == names::expects_id || word == names::asserts_id || word == names::ensures_id; +} + +#! A contract, `expects(cond)`, `asserts(cond)`, or `ensures(cond)`, each of +#! which may say what failed in place of the condition, as +#! `expects(n != 0, "A count is not zero.")`, and an `ensures` may name what the +#! function returns, as `ensures(r: r > 0)`, within which `old(e)` is what `e` +#! was where it was reached. +#! @param this The parser. +#! @returns The `contract` node. +def parser::contract(&mut this): u32 { + val token := this.index; + val ensures := this.syntax.token_names[token] == names::ensures_id; + this.advance(); + this.advance(); + + var bound: u32 = 0; + if ensures && this.check(tk::name) && this.peek(1) == tk::colon { + bound = this.name_node("Expected the name of what the function returns."); + this.advance(); + } + val within := this.in_ensures; + this.in_ensures = ensures; + val condition := this.expression(); + this.in_ensures = within; + var text: u32 = 0; + if this.accept(tk::comma) { + text = this.expression(); + } + this.expect(tk::rparen, "Expected `)` to close the contract, which takes its condition and what it says failed."); + this.expect(tk::semicolon, "Expected `;` after the statement."); + return this.make_node(nk::contract, token, condition, this.make_record(bound, text)); +} + +#! An expression followed by `;`. +#! @param this The parser. +#! @returns The `expr_stmt` node. +def parser::simple(&mut this): u32 { + val token := this.index; + val made := this.expression(); + this.expect(tk::semicolon, "Expected `;` after the statement."); + return this.make_node(nk::expr_stmt, token, made); +} + +#! `if cond { } else if cond { } else { }`, and `if const`. +#! @param this The parser. +#! @returns The `if_stmt` or `if_const` node. +def parser::if_stmt(&mut this): u32 { + return this.error_here() if !this.enter(); + + val token := this.index; + this.advance(); + + val constant := this.accept(tk::kw_const); + val condition := this.condition_expr(); + val then := this.block(); + var other: u32 = 0; + if this.accept(tk::kw_else) { + other = this.check(tk::kw_if) + ? this.if_stmt() + : this.block(); + } + + this.leave(); + return this.branch(constant ? nk::if_const : nk::if_stmt, token, condition, then, other); +} + +def parser::while_stmt(&mut this): u32 { + val token := this.index; + this.advance(); + + val condition := this.condition_expr(); + return this.make_node(nk::while_stmt, token, condition, this.block()); +} + +#! `for x in xs`, `for i, x in xs`, `for &x in xs`, `for &mut x in xs`, +#! `for i in a..b`, and `for const x in args`, which is unrolled over a pack +#! while compiling. +#! @param this The parser. +#! @returns The `for_stmt` node. +def parser::for_stmt(&mut this): u32 { + val token := this.index; + this.advance(); + + val constant := this.accept(tk::kw_const); + var index: u32 = 0; + if this.check(tk::name) && this.peek(1) == tk::comma { + index = this.name_node("Expected a name for the index."); + this.advance(); + } + + val reference := this.accept(tk::bitand); + val mutable := reference && this.accept(tk::kw_mut); + val variable := this.name_node("Expected a name for the loop variable."); + this.expect(tk::kw_in, "Expected `in` after the loop variable."); + + # A range is the loop's own, so `for i in 0..n` counts, rather than walking a + # range made as a value. + var iterated := this.condition_expr(); + var end: u32 = 0; + var inclusive := false; + if this.syntax.node_kinds[iterated] == nk::range { + inclusive = this.syntax.token_kinds[this.syntax.node_tokens[iterated]] == tk::cascadeeq; + end = this.syntax.node_rights[iterated]; + iterated = this.syntax.node_lefts[iterated]; + } + val flags := parser::bit(constant, nf::constant) + | parser::bit(reference, nf::reference) + | parser::bit(mutable, nf::mutable) + | parser::bit(inclusive, nf::inclusive); + val record := this.make_record(index, variable, iterated, end, flags); + return this.make_node(nk::for_stmt, token, record, this.block()); +} + +#! A match statement, or a match used as a value, whose arms are separated by +#! commas. +#! @param this The parser. +#! @param value Whether it is used as a value. +#! @returns The `match_stmt` or `match_value` node. +def parser::match_expr(&mut this, value: bool): u32 { + return this.error_here() if !this.enter(); + + val kind := value ? nk::match_value : nk::match_stmt; + val token := this.index; + this.advance(); + + val subject := this.condition_expr(); + if !this.accept(tk::lbrace) { + this.fail(ec::token, "Expected `{` to begin the arms of the match."); + this.leave(); + return this.make_node(kind, token, subject); + } + + # A match used as a value separates its arms with commas, and one as a + # statement ends each with the block or statement it does. + val arms := value + ? this.list(parser::item::value_arm, tk::rbrace, "Expected `,` between the arms, or `}` to close the match.") + : this.arms(); + this.leave(); + return this.make_node(kind, token, subject, arms); +} + +#! The arms of a match statement, through its `}`. +#! @param this The parser. +#! @returns The run of `match_arm` nodes. +def parser::arms(&mut this): u32 { + val mark := this.mark; + while !this.check(tk::rbrace) && !this.check(tk::eof) { + this.push(this.arm(false)); + if this.panic { + this.synchronize(parser::scope::block); + } + } + + val arms := this.make_run(mark); + this.expect(tk::rbrace, "Expected `}` to close the match."); + return arms; +} + +#! An arm of a match: its patterns, or `else`, then what it does, which is a +#! block or a statement, or in a match used as a value, an expression. A pattern +#! is an expression: a value compared with the subject, or the name of the field +#! of a union the subject holds, as `error` or `error(code)`. +#! @param this The parser. +#! @param value Whether the match is used as a value. +#! @returns The `match_arm` node, or an `error` node. +def parser::arm(&mut this, value: bool): u32 { + val token := this.index; + var patterns: u32 = 0; + if !this.accept(tk::kw_else) { + if this.check(tk::name) && this.peek(1) == tk::colon { + this.fail(ec::token, + "An arm names the field of a union it matches, as `field =>`, or `field(value) =>` to use its value."); + } else { + val mark := this.mark; + while true { + this.push(this.condition_expr()); + break if !this.accept(tk::comma); + } + patterns = this.make_run(mark); + } + } + + this.expect(tk::arrow, "Expected `=>` followed by what the arm does."); + var body: u32 = 0; + if value && this.check(tk::kw_ret) { + this.fail(ec::token, + "Each arm of a match used as a value is the expression it gives, as `2 => x,`, so leave out `return` and `;`."); + } else if value { + body = this.expression(); + } else if this.check(tk::lbrace) { + body = this.block(); + } else { + # A single statement is the body, as a block of its own. + val first := this.index; + body = this.make_node(nk::block, first, this.run_of(this.statement())); + } + + return this.make_node(nk::match_arm, token, patterns, body); +} + +#! `return`, `break`, or `continue`, each of which may be followed by `if`. +#! `return value if cond;` is the `if` it reads as, built here so that nothing +#! below the parser tells the two apart. +#! @param this The parser. +#! @param kind `return_stmt`, `break_stmt`, or `continue_stmt`. +#! @returns The node, or the `if_stmt` holding it. +def parser::jump(&mut this, kind: nk): u32 { + val token := this.index; + this.advance(); + + var value: u32 = 0; + if kind == nk::return_stmt && !this.check(tk::semicolon) && !this.check(tk::kw_if) { + value = this.expression(); + } + + var made := this.make_node(kind, token, value); + if this.check(tk::kw_if) { + val guard := this.index; + this.advance(); + + val constant := this.accept(tk::kw_const); + val condition := this.condition_expr(); + val then := this.make_node(nk::block, token, this.run_of(made)); + made = this.branch(constant ? nk::if_const : nk::if_stmt, guard, condition, then, 0); + } + + this.expect(tk::semicolon, "Expected `;` after the statement."); + return made; +} + +#! A function declared within a block, `def name(params): type { body }`, which +#! is a local holding the function as a `lambda`, named before its body so it +#! can call itself. It gives the types of its parameters and its result, as any +#! other named function does. +#! @param this The parser. +#! @returns The `variable` node, or an `error` node. +def parser::local_function(&mut this): u32 { + val token := this.index; + this.advance(); + + val name := this.index; + this.advance(); + if this.check(tk::less) { + this.fail(ec::token, "Functions declared within a block cannot be generic."); + return this.error_here(); + } + + val signature := this.params(false, false); + val body := this.block(); + val lambda := this.make_node(nk::lambda, token, signature.params, this.make_record(signature.result, body)); + return this.make_node(nk::variable, name, this.make_record(0, 0, 0, lambda), nf::function as u32); +} diff --git a/analyzer/parser/tables.sakura b/analyzer/parser/tables.sakura new file mode 100644 index 00000000..baa4c49e --- /dev/null +++ b/analyzer/parser/tables.sakura @@ -0,0 +1,119 @@ +#! @file tables.sakura +#! @author John Christman (sorakatadzuma@gmail.com) +#! @copyright Malunal Studios, LLC. +#! @license MIT +#! +#! Contains the tables the parser reads tokens by, built while compiling: the +#! traits of each kind of token, as whether it begins a declaration or closes a +#! list, and the binding power of each operator. + +module sakura::analyzer; + + +#! What the parser asks of a kind of token, as bits of `tk::traits`. Each kind's +#! answers are worked out once, while compiling, so asking is one load. +enum tt : u32 { + assigns = 0x0001, #! `=`, `+=`, and the rest. + declares = 0x0002, #! Begins a declaration at the top level of a file. + imports = 0x0004, #! `import` or `module`. + states = 0x0008, #! Begins a statement a block resumes at after an error. + fields = 0x0010, #! Begins a member a struct or union resumes at. + members = 0x0020, #! Begins a member a trait resumes at. + opens = 0x0040, #! Opens what a later token closes. + closes = 0x0080, #! Closes what an earlier token opened. + text = 0x0100, #! Its text says something its node's kind does not: a name, a literal, or an operator. + piece = 0x0200, #! May be part of a type before its `<`, as `&mut a::b`. + angle = 0x0400, #! Begins with a `>` that may close type arguments: `>`, `>>`, `>=`, or `>>=`. +} + +#! What the parser asks of each kind of token. +const token_traits: u32[tk::count as u64] = make_token_traits(); + +#! How tightly each kind of token binds as an operator, `none` where it is not +#! one. +const token_powers: parser::bp[tk::count as u64] = make_token_powers(); + +#! The answers of a kind of token, as bits of `tt`. +#! @param this The kind of token. +#! @returns The bits. +val tk::traits: u32 { get => token_traits[this as u64]; } + +#! Whether a kind of token has the trait. +#! @param this The kind of token. +#! @param which The trait. +#! @returns Whether it has. +def tk::has(&this, which: tt): bool { + return (this.traits & which as u32) != 0; +} + +const def make_token_traits(): u32[tk::count as u64] { + var made: u32[tk::count as u64]; + for each in [ + tk::assign, tk::pluseq, tk::minuseq, tk::stareq, tk::slasheq, tk::moduloeq, + tk::bitandeq, tk::bitoreq, tk::bitxoreq, tk::lshifteq, tk::rshifteq + ] { made[each as u64] |= tt::assigns as u32; } + + for each in [ + tk::kw_pub, tk::attr, tk::kw_when, tk::kw_enum, tk::kw_def, tk::kw_const, + tk::kw_struct, tk::kw_union, tk::kw_trait, tk::kw_type, tk::kw_val, tk::kw_var + ] { made[each as u64] |= tt::declares as u32; } + + for each in [tk::kw_imp, tk::kw_mod, tk::kw_extern] { made[each as u64] |= tt::imports as u32; } + + for each in [ + tk::kw_val, tk::kw_var, tk::kw_const, tk::kw_if, tk::kw_while, tk::kw_for, + tk::kw_match, tk::kw_when, tk::kw_ret, tk::kw_break, tk::kw_cont + ] { made[each as u64] |= tt::states as u32; } + + for each in [tk::kw_val, tk::kw_var, tk::attr, tk::kw_pub] { made[each as u64] |= tt::fields as u32; } + for each in [tk::kw_def, tk::kw_const, tk::attr] { made[each as u64] |= tt::members as u32; } + for each in [tk::lparen, tk::lbracket, tk::lbrace, tk::istring_beg] { made[each as u64] |= tt::opens as u32; } + for each in [tk::rparen, tk::rbracket, tk::rbrace, tk::istring_end] { made[each as u64] |= tt::closes as u32; } + + for each in [ + tk::name, tk::unknown, tk::signed, tk::unsigned, tk::float, tk::char, tk::string, + tk::istring, tk::istring_beg, tk::istring_mid, tk::istring_end, + tk::kw_true, tk::kw_false, tk::kw_null, + tk::assign, tk::equals, tk::negate, tk::noteq, tk::less, tk::lesseq, tk::more, + tk::moreeq, tk::plus, tk::minus, tk::star, tk::slash, tk::modulo, tk::logand, + tk::logor, tk::bitand, tk::bitor, tk::bitxor, tk::bitnot, tk::lshift, tk::rshift, + tk::pluseq, tk::minuseq, tk::stareq, tk::slasheq, tk::moduloeq, tk::bitandeq, + tk::bitoreq, tk::bitxoreq, tk::lshifteq, tk::rshifteq, tk::increment, tk::decrement, + tk::cascade, tk::cascadeeq + ] { made[each as u64] |= tt::text as u32; } + + for each in [tk::name, tk::scope, tk::kw_mut, tk::bitand, tk::star, tk::kw_not] { + made[each as u64] |= tt::piece as u32; + } + + for each in [tk::more, tk::rshift, tk::moreeq, tk::rshifteq] { made[each as u64] |= tt::angle as u32; } + return made; +} + +const def make_token_powers(): parser::bp[tk::count as u64] { + var made: parser::bp[tk::count as u64]; + for each in [ + tk::assign, tk::pluseq, tk::minuseq, tk::stareq, tk::slasheq, tk::moduloeq, + tk::bitandeq, tk::bitoreq, tk::bitxoreq, tk::lshifteq, tk::rshifteq + ] { made[each as u64] = parser::bp::assign; } + + made[tk::kw_else as u64] = parser::bp::fallback; + made[tk::quest as u64] = parser::bp::ternary; + made[tk::cascade as u64] = parser::bp::range; + made[tk::cascadeeq as u64] = parser::bp::range; + made[tk::logor as u64] = parser::bp::logor; + made[tk::logand as u64] = parser::bp::logand; + made[tk::bitor as u64] = parser::bp::bitor; + made[tk::bitxor as u64] = parser::bp::bitxor; + made[tk::bitand as u64] = parser::bp::bitand; + for each in [tk::equals, tk::noteq] { made[each as u64] = parser::bp::equality; } + for each in [tk::less, tk::lesseq, tk::more, tk::moreeq] { made[each as u64] = parser::bp::compare; } + for each in [tk::lshift, tk::rshift] { made[each as u64] = parser::bp::shift; } + for each in [tk::plus, tk::minus] { made[each as u64] = parser::bp::sum; } + for each in [tk::star, tk::slash, tk::modulo] { made[each as u64] = parser::bp::product; } + for each in [tk::kw_as, tk::kw_is] { made[each as u64] = parser::bp::cast; } + for each in [tk::lparen, tk::lbracket, tk::dot, tk::increment, tk::decrement, tk::scope] { + made[each as u64] = parser::bp::postfix; + } + return made; +} diff --git a/analyzer/parser/types.sakura b/analyzer/parser/types.sakura new file mode 100644 index 00000000..56f102fe --- /dev/null +++ b/analyzer/parser/types.sakura @@ -0,0 +1,382 @@ +#! @file types.sakura +#! @author John Christman (sorakatadzuma@gmail.com) +#! @copyright Malunal Studios, LLC. +#! @license MIT +#! +#! Contains the parsing of types: names and paths with their type arguments, +#! references, arrays, `type_of`, and the type parameters of declarations. + +module sakura::analyzer; + + +#! What may follow the segments of a path as type arguments. +enum parser::args { + plain, #! Nothing, as in imports. + types, #! Type arguments after `<`, as in `box`. + values, #! Type arguments after `::<`, as in `box::`. +} + +#! A type, as `&mut T`, `*u8`, `T[4]`, `def(T): U`, or `std::list`, which +#! is also what follows `as` and `is`, so `x as i32 | y` remains a bitwise or. +#! @param this The parser. +#! @returns The type's node, or an `error` node. +def parser::type_expr(&mut this): u32 { + return this.error_here() if !this.enter(); + + var made: u32 = 0; + if this.check(tk::star) || this.check(tk::bitand) { + val kind := this.check(tk::star) ? nk::type_ptr : nk::type_ref; + val token := this.index; + this.advance(); + val mutable := this.accept(tk::kw_mut); + made = this.make_node(kind, token, this.type_expr(), parser::bit(mutable, nf::mutable)); + } else { + made = this.type_postfix(); + } + + this.leave(); + return made; +} + +#! A type followed by the lengths of fixed arrays of it, as `T[4][2]`. +#! @param this The parser. +#! @returns The type's node, a `type_fixed` node where lengths follow. +def parser::type_postfix(&mut this): u32 { + var made := this.type_primary(); + while this.check(tk::lbracket) { + val token := this.index; + this.advance(); + if this.check(tk::rbracket) { + this.report(ec::token, + "Expected the number of elements, as `T[4]`: a run of elements whose number is not known is a `std::list`, and a view of one a `slice`."); + } + + val length := this.expression(); + this.expect(tk::rbracket, "Expected `]` after the number of elements."); + made = this.make_node(nk::type_fixed, token, made, length); + } + + return made; +} + +#! A type that `...` may follow: a function type's last parameter, which takes +#! any number of arguments, as `def(i64...): i64`, or is a pack, as `def(Ts...): +#! R`, and a pack passed on among type arguments, as `box`. +#! @param this The parser. +#! @returns The type's node, or a `type_spread` of it. +def parser::spread_type(&mut this): u32 { + val made := this.type_expr(); + return made if !this.check(tk::spread); + val token := this.index; + this.advance(); + return this.make_node(nk::type_spread, token, made); +} + +def parser::type_primary(&mut this): u32 { + # A function type, as `def(int, str): bool`, whose result takes everything + # after it. + if this.check(tk::kw_def) { + val token := this.index; + this.advance(); + this.expect(tk::lparen, "Expected `(` to begin the parameter types."); + + val params := this.list(parser::item::param_type, tk::rparen, "Expected `)` to close the parameter types."); + this.expect(tk::colon, "Expected `:` followed by the return type."); + return this.make_node(nk::type_func, token, params, this.type_expr()); + } + + if this.accept(tk::lparen) { + val made := this.type_expr(); + this.expect(tk::rparen, "Expected `)` to close the type."); + return made; + } + + # `type_of(d)` is the type of what a declaration known while compiling declares. + if this.check_word(names::type_of_id) && this.peek(1) == tk::lparen { + val token := this.index; + this.advance(); + this.advance(); + + val declaration := this.expression(); + this.expect(tk::rparen, "Expected `)` after the declaration whose type it is."); + return this.make_node(nk::type_of, token, declaration); + } + + return this.type_name(); +} + +#! A named type, as `std::list`, made of its segments. One of a single +#! segment without type arguments, as `u8`, holds no run: its token names it. +#! @param this The parser. +#! @returns The `type_name` node. +def parser::type_name(&mut this): u32 { + if !this.check(tk::name) { + this.fail(ec::kind, "Expected a type name."); + return this.error_here(); + } + + val token := this.index; + if this.peek(1) != tk::less && this.peek(1) != tk::scope { + this.advance(); + return this.make_node(nk::type_name, token); + } + return this.make_node(nk::type_name, token, this.segments(parser::args::types)); +} + +#! A path, as `std::io`, of segments without type arguments. One of a single +#! segment holds no run: its token names it. +#! @param this The parser. +#! @returns The `path` node. +def parser::path(&mut this): u32 { + val token := this.index; + if this.check(tk::name) && this.peek(1) != tk::scope { + this.advance(); + return this.make_node(nk::path, token); + } + return this.make_node(nk::path, token, this.segments(parser::args::plain)); +} + +#! The segments of a path, as `a::b::c`, each of which may take type arguments, +#! as `res::ok` in a type, or `res::::ok` in an expression. +#! @param this The parser. +#! @param args How type arguments are written after each segment, if at all. +#! @returns The run of `segment` nodes. +def parser::segments(&mut this, args: parser::args): u32 { + val mark := this.mark; + while true { + if !this.check(tk::name) { + this.fail(ec::ident, "Expected an identifier in the path."); + break; + } + + val token := this.index; + var types: u32 = 0; + this.advance(); + if args == parser::args::types && this.check(tk::less) { + types = this.type_args(); + } else if args == parser::args::values && this.at_value_args() { + this.advance(); + types = this.type_args(); + } + + this.push(this.make_node(nk::segment, token, types)); + break if !this.accept(tk::scope); + } + + return this.make_run(mark); +} + +#! Whether type arguments follow a name in an expression, written `::<` so that +#! a `<` alone always compares. +#! @param this The parser. +#! @returns Whether they do. +def parser::at_value_args(&this): bool { + return this.check(tk::scope) && this.peek(1) == tk::less; +} + +#! The type arguments ``, from the current `<`. After `as` and `is`, a `<` +#! always begins type arguments, so a comparison there needs parentheses. +#! @param this The parser. +#! @returns The run of types. +def parser::type_args(&mut this): u32 { + val open := this.index; + val angled := this.angled; + this.angled = false; + this.advance(); + + val mark := this.mark; + while true { + this.push(this.type_arg()); + break if !this.accept(tk::comma); + } + this.angled = angled; + + val types := this.make_run(mark); + this.close_angle(this.follows_cast(open) + ? "Expected `>` to close the type arguments. A `<` after the type of `as` or `is` begins type arguments, so put a comparison in parentheses, as `(n as i64) < limit`." + : "Expected `>` to close the type arguments."); + return types; +} + +#! A type argument: a type, or the value a constant parameter is given, a +#! literal, a name, or an expression of them, as `buffer` or +#! `grid`. A name alone is read as a type, which the checker takes as the +#! constant it names where the parameter is one. `(` begins a value, unless a +#! type that needs one does. +#! @param this The parser. +#! @returns The type's or the value's node. +def parser::type_arg(&mut this): u32 { + val next := this.peek(1); + val value := match this.kind { + tk::signed, tk::unsigned, tk::float, tk::char, tk::string, tk::istring, tk::istring_beg, + tk::kw_true, tk::kw_false, tk::kw_null, tk::minus, tk::negate, tk::bitnot, tk::lbracket => true, + tk::lparen => next != tk::star && next != tk::bitand && next != tk::kw_def, + else => false + }; + return this.constant_arg(0) if value; + + val made := this.spread_type(); + return made if this.syntax.node_kinds[made] != nk::type_name || !this.continues_value(); + + # The name is the expression's first operand: a name of one segment, or a path. + this.syntax.node_kinds[made] = this.syntax.node_lefts[made] == 0 ? nk::name : nk::path; + return this.constant_arg(made); +} + +#! Whether what follows a name read as a type goes on with an expression, so the +#! name began a constant argument, as `N` does in `grid`. `>` closes the +#! arguments, so a comparison is put in parentheses. +#! @param this The parser. +#! @returns Whether it does. +def parser::continues_value(&this): bool { + return match this.kind { + tk::lparen, tk::lbrace, tk::dot, tk::quest, tk::kw_as, tk::kw_is => true, + tk::more, tk::moreeq, tk::rshift, tk::rshifteq, tk::comma => false, + else => token_powers[this.kind as u64] as u32 > parser::bp::assign as u32 + }; +} + +#! A constant argument, which is an expression, going on from the name already +#! read as a type where one was. +#! @param this The parser. +#! @param primed The `name` or `path` the expression begins with, or 0. +#! @returns The expression's node. +def parser::constant_arg(&mut this, primed: u32): u32 { + val angled := this.angled; + this.angled = true; + var made: u32 = 0; + if primed == 0 { + made = this.expression(); + } else { + made = primed; + # A struct literal of the name, as `point { x = 1 }`. + if this.check(tk::lbrace) { + this.syntax.node_kinds[made] = nk::type_name; + made = this.make_node(nk::construct, this.index, made, this.field_list()); + } + while true { + val power := this.power(made); + break if power == parser::bp::none; + made = this.infix(made, power, true); + } + } + this.angled = angled; + return made; +} + +#! A pattern parameter, `def(A, Ts...): R`, from the current `def`: a type +#! parameter for each of the parameter types it names, the last of which may be +#! a pack, and one for its result. +#! @param this The parser. +#! @returns The `type_pattern` node. +def parser::type_pattern(&mut this): u32 { + val token := this.index; + this.advance(); + this.expect(tk::lparen, "Expected `(` to begin the pattern's parameter types, as `def(Ts...): R`."); + + val mark := this.mark; + while !this.check(tk::rparen) && !this.check(tk::eof) { + if !this.check(tk::name) { + this.fail(ec::ident, "Expected the name of a type parameter the pattern's parameter type is, as `T` of `def(T): R`."); + break; + } + val name := this.index; + this.advance(); + val packed := this.accept(tk::spread); + if packed && !this.check(tk::rparen) { + this.report_at(name, ec::token, "A pack takes every parameter type after those before it, so it is the last."); + } + this.push(this.make_node(nk::type_param, name, 0, parser::bit(packed, nf::packed))); + break if !this.accept(tk::comma); + } + val params := this.make_run(mark); + this.expect(tk::rparen, "Expected `)` to close the pattern's parameter types."); + this.expect(tk::colon, "Expected `:` followed by the name of the type parameter the result is, as `R` of `def(Ts...): R`."); + + var result: u32 = 0; + if this.check(tk::name) { + result = this.make_node(nk::type_param, this.index, 0, 0); + this.advance(); + } else { + this.fail(ec::ident, "Expected the name of the type parameter the result is, as `R` of `def(Ts...): R`."); + } + return this.make_node(nk::type_pattern, token, params, result); +} + +#! A pattern parameter, `L[N]`, from the current `[` after the name of its +#! element's type parameter: that, and a constant parameter for its length. +#! @param this The parser. +#! @param token The name of the element's type parameter. +#! @returns The `array_pattern` node. +def parser::array_pattern(&mut this, token: u32): u32 { + val element := this.make_node(nk::type_param, token, 0, 0); + this.advance(); + var length: u32 = 0; + if this.check(tk::name) { + length = this.make_node(nk::const_param, this.index, 0, 0); + this.advance(); + } else { + this.fail(ec::ident, "Expected the name of the constant parameter the length is, as `N` of `L[N]`."); + } + this.expect(tk::rbracket, "Expected `]` to close the pattern, as `L[N]`."); + return this.make_node(nk::array_pattern, token, element, length); +} + +#! The type parameters `` of a declaration, from the current `<`, +#! whose bounds are given in a `where` clause after its signature, which gives +#! them to the `type_param` nodes. +#! @param this The parser. +#! @returns The run of `type_param` nodes. +def parser::type_params(&mut this): u32 { + this.advance(); + + val mark := this.mark; + while true { + # `def(Ts...): R` is given a function type, and names its parameters' types + # and its result's. + if this.check(tk::kw_def) { + this.push(this.type_pattern()); + break if !this.accept(tk::comma); + continue; + } + + # `const N: u64` stands for a value each instance is given, of the type written. + val valued := this.accept(tk::kw_const); + if !this.check(tk::name) { + this.fail(ec::ident, valued ? "Expected the name of a constant parameter, as `const N: u64`." : "Expected the name of a type parameter."); + break; + } + + val token := this.index; + this.advance(); + # `L[N]` is given a fixed array, and names its element's type and its length. + if !valued && this.check(tk::lbracket) { + this.push(this.array_pattern(token)); + break if !this.accept(tk::comma); + continue; + } + if valued { + if this.accept(tk::spread) { + this.report_at(token, ec::token, "A constant parameter stands for one value, so it is not a pack."); + } + this.expect(tk::colon, "Expected `:` followed by the type of the constant, as `const N: u64`."); + this.push(this.make_node(nk::const_param, token, 0, this.type_expr())); + break if !this.accept(tk::comma); + continue; + } + + # `Ts...` is a pack, standing for any number of types, which comes last. + val packed := this.accept(tk::spread); + if packed && !this.at(tt::angle) { + this.report_at(token, ec::token, + "A pack takes every type argument after the type parameters before it, so it is the last."); + } + + this.push(this.make_node(nk::type_param, token, 0, parser::bit(packed, nf::packed))); + break if !this.accept(tk::comma); + } + + val params := this.make_run(mark); + this.close_angle("Expected `>` to close the type parameters."); + return params; +} diff --git a/analyzer/parser/when.sakura b/analyzer/parser/when.sakura new file mode 100644 index 00000000..069f2dac --- /dev/null +++ b/analyzer/parser/when.sakura @@ -0,0 +1,133 @@ +#! @file when.sakura +#! @author John Christman (sorakatadzuma@gmail.com) +#! @copyright Malunal Studios, LLC. +#! @license MIT +#! +#! Contains the parsing of `when` blocks, which choose the declarations or +#! statements a program has while compiling, and of the conditions they test. + +module sakura::analyzer; + + +#! `when condition { ... }`, holding declarations at the top level of a file and +#! statements within a function, followed by `else when` and `else`. +#! @param this The parser. +#! @param declarations Whether it holds declarations, at the top level of a +#! file, rather than statements. +#! @returns The `when_block` node. +def parser::when_block(&mut this, declarations: bool): u32 { + return this.error_here() if !this.enter(); + + val token := this.index; + this.advance(); + + val condition := this.condition(); + val then := declarations ? this.decl_block() : this.block(); + var other: u32 = 0; + if this.accept(tk::kw_else) { + other = this.check(tk::kw_when) + ? this.when_block(declarations) + : declarations ? this.decl_block() : this.block(); + } + + this.leave(); + return this.branch(nk::when_block, token, condition, then, other); +} + +#! The declarations of a `when` at the top level, as a `block`, which cannot +#! import or begin a module. +#! @param this The parser. +#! @returns The `block` node. +def parser::decl_block(&mut this): u32 { + if !this.check(tk::lbrace) { + this.fail(ec::token, "Expected `{` to begin the declarations."); + return this.error_here(); + } + + val token := this.index; + this.advance(); + + val mark := this.mark; + while !this.check(tk::rbrace) && !this.check(tk::eof) { + if this.check(tk::kw_imp) || this.check(tk::kw_mod) || this.check(tk::kw_extern) { + this.fail(ec::decl, + "Imports and modules cannot be within `when`; a whole section of a file can be declared `module path when condition;`."); + } else { + this.push(this.declaration()); + } + + if this.panic { + this.synchronize(parser::scope::declarations); + } + } + + val declarations := this.make_run(mark); + this.expect(tk::rbrace, "Expected `}` to close the declarations."); + return this.make_node(nk::block, token, declarations); +} + +#! A condition on the target, where `&&` binds tighter than `||`. +#! @param this The parser. +#! @returns The condition's node. +def parser::condition(&mut this): u32 { + var left := this.condition_and(); + while this.check(tk::logor) { + val token := this.index; + this.advance(); + left = this.make_node(nk::binary, token, left, this.condition_and()); + } + + return left; +} + +def parser::condition_and(&mut this): u32 { + var left := this.condition_operand(); + while this.check(tk::logand) { + val token := this.index; + this.advance(); + left = this.make_node(nk::binary, token, left, this.condition_operand()); + } + + return left; +} + +#! A target key compared with a value, as `os == linux`, a negation, or a +#! condition in parentheses. +#! @param this The parser. +#! @returns The operand's node, or an `error` node. +def parser::condition_operand(&mut this): u32 { + return this.error_here() if !this.enter(); + + val token := this.index; + var made: u32 = 0; + if this.accept(tk::negate) { + made = this.make_node(nk::unary, token, this.condition_operand()); + } else if this.accept(tk::lparen) { + made = this.condition(); + this.expect(tk::rparen, "Expected `)` to close the condition."); + } else if !this.check(tk::name) { + this.fail(ec::ident, "Expected a target key: `os`, `arch`, or `backend`."); + made = this.error_here(); + } else { + made = this.comparison(); + } + + this.leave(); + return made; +} + +#! `key == value` or `key != value`, from the key. +#! @param this The parser. +#! @returns The `binary` node. +def parser::comparison(&mut this): u32 { + val key := this.name_node("Expected a target key: `os`, `arch`, or `backend`."); + if !this.check(tk::equals) && !this.check(tk::noteq) { + this.fail(ec::token, "Expected `==` or `!=` after the target key."); + return this.error_here(); + } + + val token := this.index; + this.advance(); + val value := this.name_node("Expected the value the key is compared with, as `linux`."); + return this.make_node(nk::binary, token, key, value); +} diff --git a/analyzer/printer.sakura b/analyzer/printer.sakura new file mode 100644 index 00000000..6917c182 --- /dev/null +++ b/analyzer/printer.sakura @@ -0,0 +1,161 @@ +#! @file printer.sakura +#! @author John Christman (sorakatadzuma@gmail.com) +#! @copyright Malunal Studios, LLC. +#! @license MIT +#! +#! Contains the printer, which writes a syntax tree as text, the way the +#! parser's tests say what tree they expect. + +module sakura::analyzer; + + +#! Prints the tree under a node, which is how the parser's tests say what tree +#! they expect, and how one is read while debugging. +#! +#! A node is printed as `(kind:text ...)`, its slots following in the order its +#! shape lists them, and one whose slots all hold nothing, being absent nodes, +#! empty runs, or no flags, is printed as `kind:text` alone. The text is that of +#! its token where it says something, as a name, a literal, or an operator, and +#! left out where it is punctuation or a keyword the kind already says. An +#! absent node is `_`, a run is `[...]`, and flags are `{mutable,constant}`, +#! printed only where any are set. +#! @param this The syntax tree. +#! @param at The node to print. +#! @param source The source the tokens are of, for their text. +#! @param names The names the tokens were lexed with, for the length of each +#! name. +#! @returns The tree printed. +pub def syntax::print(&this, at: u32, source: &source, names: &names): string { + var out := string::new(nothing {}); + this.print_into(at, source, names, &mut out); + return out; +} + +def syntax::print_into(&this, at: u32, source: &source, names: &names, out: &mut string): void { + if at == 0 { + out.append("_"); + return; + } + + val held := this.node(at); + val shape := held.shape; + val bare := this.slot_empty(shape.left, held.left, shape.record) + && this.slot_empty(shape.right, held.right, shape.record); + if !bare { + out.append("("); + } + + out.append(kind_names[held.kind as u64]); + val token := this.token(held.token, names); + if token.kind.has(tt::text) { + out.append(":"); + val text := source.make_lexeme(token.offset, token.length); + # A parameter an accessor implies has the `get` or `set` for its token. + val flags := held.kind == nk::param ? this.flags_at(at) : 0; + if (flags & nf::implied as u32) != 0 { + out.append(text == "set" && (flags & nf::mutable as u32) == 0 ? "value" : "this"); + } else { + out.append(text); + } + } + + return if bare; + + this.print_slot(shape.left, held.left, shape.record, source, names, out); + this.print_slot(shape.right, held.right, shape.record, source, names, out); + out.append(")"); +} + +def syntax::print_slot( + &this, + kind: slot, + value: u32, + record: span, + source: &source, + names: &names, + out: &mut string +): void { + match kind { + slot::node => { + out.append(" "); + this.print_into(value, source, names, out); + } + slot::run, slot::bounds => { + return if kind == slot::bounds && this.run_length(value) == 0; + out.append(" ["); + for i in 0..this.run_length(value) { + if i != 0 { + out.append(" "); + } + this.print_into(this.run_at(value, i as u32), source, names, out); + } + out.append("]"); + } + slot::flags => { + return if value == 0; + out.append(" {"); + var first := true; + for i in 0..flag_names.length { + if (value & (1 << i as u32)) != 0 { + if !first { + out.append(","); + } + out.append(flag_names[i]); + first = false; + } + } + out.append("}"); + } + slot::extra => { + for i in 0..record.length { + this.print_slot(record[i], this.extras[value as u64 + i], no_record, source, names, out); + } + } + else => {} + } +} + +#! Whether the slot holds nothing where it holds `value`. +#! @param this The syntax tree. +#! @param kind What the slot holds. +#! @param value The slot's value. +#! @param record The shape of the node's record, where the slot holds one. +#! @returns Whether it holds nothing. +def syntax::slot_empty(&this, kind: slot, value: u32, record: span): bool { + return match kind { + slot::node, slot::flags => value == 0, + slot::run, slot::bounds => this.run_length(value) == 0, + slot::extra => this.record_empty(value, record), + else => true + }; +} + +def syntax::record_empty(&this, at: u32, record: span): bool { + for i in 0..record.length { + return false if !this.slot_empty(record[i], this.extras[at as u64 + i], no_record); + } + return true; +} + +#! The names of the kinds of node, in the order `nk` declares them. +const kind_names: strview[nk::count as u64] = [ + "error", "document", "block", + "import_decl", "module_decl", "extern_import", "extern_module", "when_block", "function", "param", "variable", + "field", "spread", "rename", "property", "accessor", "struct_decl", "union_decl", + "trait_decl", "assoc_type", "enumeration", "enumerator", "alias", "attribute", + "type_param", "const_param", "type_pattern", "array_pattern", + "segment", "type_name", "type_ref", "type_ptr", "type_fixed", "type_func", "type_spread", "type_of", + "if_stmt", "if_const", "while_stmt", "for_stmt", "match_stmt", "match_arm", + "return_stmt", "break_stmt", "continue_stmt", "expr_stmt", "contract", + "name", "path", "number", "character", "string", "istring", "boolean", "null_lit", + "unary", "postfix", "reference", "binary", "assign", "ternary", "fallback", "call", + "type_args", "index", "slice", "member", "member_of", "cast", "is_test", + "construct", "field_init", "array", "lambda", "match_value", "range", "old_value", + "undefined", +]; + +#! The names of the bits of `nf`, from its lowest. +const flag_names: span = [ + "exported", "mutable", "constant", "reference", "variadic", "packed", + "negated", "computed", "function", "named", "inclusive", "implied", +]; diff --git a/analyzer/queries/calling.sakura b/analyzer/queries/calling.sakura new file mode 100644 index 00000000..c92d8b04 --- /dev/null +++ b/analyzer/queries/calling.sakura @@ -0,0 +1,270 @@ +#! @file calling.sakura +#! @author John Christman (sorakatadzuma@gmail.com) +#! @copyright Malunal Studios, LLC. +#! @license MIT +#! +#! Contains what is being called at a position, for an editor to show while the +#! arguments are written: every overload of what is called, and the parameter +#! the position writes. + +import std::containers; +module sakura::analyzer; + + +#! An overload of what is being called. +pub struct overload { + pub var signature: string; #! How it is declared, as `hover` shows it. + pub var documentation: string; #! Its documentation comment, or empty. + pub var contract: string; #! The `expects` and `ensures` its body begins with, a line each, or empty. + pub var arity: u32; #! How many parameters its signature declares. + pub var variadic: bool; #! Whether its last parameter takes every argument after the others. +} + +#! What is being called at a position. +pub struct calls { + pub var overloads: vector; #! Each overload, the one the arguments written so far fit first. + pub var parameter: u32; #! The parameter the position writes, counting the receiver of a method called through a value. +} + +#! The call whose parentheses are open at a position: the token naming what it +#! calls, and the argument being written. +struct open_call { + var name: u32; #! The token naming what is called. + var argument: u32; #! The argument being written, from 0. +} + +#! A bracket open before a position, as `open_calls` reads them. +struct open_bracket { + var closes: tk; #! The token that closes it. + var call: bool; #! Whether it is a call's parentheses. + var name: u32; #! The token naming what a call calls. + var argument: u32; #! The argument of a call being written, from 0. +} + +#! What is being called at the offset of the file: the innermost call whose +#! parentheses are open there, whose overloads are given, the one a call of the +#! arguments written so far would choose first. +#! @param this The checker. +#! @param file The file. +#! @param offset The byte of its text. +#! @returns What is called, or nothing where no call is open there. +pub def checker::calls_at(&mut this, file: u32, offset: u32): maybe { + var opens := this.open_calls(file, offset); + return nothing {} if opens.length == 0; + + # The innermost call whose callee is a function, or a value of a type with an + # `invoke`, as a call of it is a call of that. + val asked := this.begin_query(file); + var member := false; + var decl: u32 = 0; + var argument: u32 = 0; + var i := opens.length; + while i > 0 && decl == 0 { + i--; + member = false; + decl = this.called_decl(file, offset, &opens[i], &asked.walked, &asked.decls, &mut member); + argument = opens[i].argument; + } + # A method called through a value is given its receiver, which its signature + # names first, so the argument written is the one after it. + if member && decl != 0 && this.decls.has(decl, df::method) { + argument++; + } + return nothing {} if decl == 0 || this.decls.kinds.p[decl] != dk::function; + + var made := calls { overloads = vector::::new(), parameter = argument }; + var walk := this.decls.walk_overloads(this.first_overload(decl), 32); + while true { + val at := walk.next(); + break if at == 0; + if !this.decls.has(at, df::failed) { + this.resolve(at); + val kind: u32 = this.decls.types.p[at]; + made.overloads.append(overload { + signature = this.signature_of(at), + documentation = this.documentation_of(this.decls.files.p[at], this.decls.nodes.p[at]), + contract = this.contract_of(at), + arity = kind != 0 ? this.types.part_count(kind) : 0, + variadic = this.decls.has(at, df::variadic) + }); + } + } + + # The overload the arguments written so far fit comes first. + for i in 0..made.overloads.length { + continue if made.overloads[i].arity <= argument && !made.overloads[i].variadic; + var fitting := move(&mut made.overloads[i]); + made.overloads.remove_at(i); + made.overloads.insert_at(0, move(&mut fitting)); + break; + } + return move(&mut made); +} + +#! The first of the overloads of a function: the first member of its name of +#! the type it is declared through, or the first declaration of its name of its +#! module. +#! @param this The checker. +#! @param decl The function. +#! @returns The first overload. +def checker::first_overload(&this, decl: u32): u32 { + val owner: u32 = this.decls.owners.p[decl]; + val first := owner != 0 + ? this.first_member(decl) + : this.modules.decl(this.decls.modules.p[decl], this.decls.names.p[decl]); + return first != 0 ? first : decl; +} + +#! Finds the calls whose parentheses are open at the offset: the name each +#! calls, and the argument being written. The tokens are read rather than the +#! tree, since a call is rarely whole while its arguments are written. +#! @param this The checker. +#! @param file The file. +#! @param offset The byte of its text. +#! @returns The calls, the innermost last. +def checker::open_calls(&this, file: u32, offset: u32): vector { + val syntax := &this.units[file].syntax; + var open := vector::::new(); + var called: u32 = 0; + var has_called := false; + var scope := false; + for at in 0..syntax.token_count { + val token := at as u32; + break if syntax.token_offsets[token] >= offset; + val kind := syntax.token_kinds[token]; + break if kind == tk::eof; + if kind == tk::lparen || kind == tk::lbracket || kind == tk::lbrace { + open.append(open_bracket { + closes = kind == tk::lparen ? tk::rparen : kind == tk::lbracket ? tk::rbracket : tk::rbrace, + call = kind == tk::lparen && has_called, name = called + }); + } else if kind == tk::less && scope { + # Type arguments follow `::`, as `f::(x)`, and their commas are not the + # call's, so they take a frame of their own. + open.append(open_bracket { closes = tk::more }); + } else if kind == tk::rparen || kind == tk::rbracket || kind == tk::rbrace || kind == tk::more { + if open.length != 0 && open.last().closes == kind { + open.truncate(); + } + } else if kind == tk::comma { + if open.length != 0 && open.last().call { + open.last().argument++; + } + } + + # The name a `(` follows is the last one written before it. + if kind == tk::name { + called = token; + has_called = true; + } else if kind != tk::scope && kind != tk::less && kind != tk::more && kind != tk::dot { + has_called = false; + } + scope = kind == tk::scope; + } + + # The calls still open, which the position is writing an argument of, the + # innermost last. + var made := vector::::new(); + for &each in open { + if each.call { + made.append(open_call { name = each.name, argument = each.argument }); + } + } + return made; +} + +#! The function a call open at a position calls: what the node naming it +#! refers to, and otherwise a function of the name the position can name. +#! @param this The checker. +#! @param file The file. +#! @param offset The byte of its text. +#! @param open The call. +#! @param walked The file's tree. +#! @param decls The declarations of the file's nodes. +#! @param member Where whether it is called through a value is written. +#! @returns The function, or 0. +def checker::called_decl( + &mut this, + file: u32, + offset: u32, + open: &open_call, + walked: &tree_walk, + decls: &dict, + member: &mut bool +): u32 { + for &node in walked.order { + continue if this.token_of(node) != open.name; + val kind := this.kind_of(node); + continue if kind != nk::name && kind != nk::member && kind != nk::segment && kind != nk::path; + member = kind == nk::member; + val meant := this.meaning_of(node, walked, decls); + if meant.decl != 0 && this.decls.kinds.p[meant.decl] == dk::function { + return meant.decl; + } + if kind == nk::member { + val found := this.member_meaning(this.type_at(this.left_of(node)), this.name_of(node)); + return found.decl if found.decl != 0 && this.decls.kinds.p[found.decl] == dk::function; + } + + # A value of a type with an `invoke` is called through it, which is given + # the value as its receiver. + val held := this.type_at(node); + if held != 0 && held != bt::error { + val found := this.find_member(this.reached(held), word::invoke); + if found.decl != 0 && this.decls.kinds.p[found.decl] == dk::function { + member = true; + return found.decl; + } + } + return 0; + } + + # A call being written rarely parses, so where the tree has no node for the + # name, or the checker made nothing of the one it has, the name is looked up + # as the checker would: a function of the module, of an import, or one built + # in. + this.at.home = this.home_at(file, offset); + val found := this.lookup_global(this.units[file].syntax.token_names[open.name], 0); + this.at.home = 0; + return found; +} + +#! The type of the argument being written at the offset of the file, of the +#! call whose parentheses are open there, or 0 where none is. +#! @param this The checker. +#! @param file The file. +#! @param offset The byte of its text. +#! @param walked The file's tree. +#! @param decls The declarations of the file's nodes. +#! @returns The type, or 0. +def checker::argument_type(&mut this, file: u32, offset: u32, walked: &tree_walk, decls: &dict): u32 { + var opens := this.open_calls(file, offset); + return 0 if opens.length == 0; + var member := false; + val open := opens.last(); + val decl := this.called_decl(file, offset, open, walked, decls, &mut member); + return 0 if decl == 0 || this.decls.kinds.p[decl] != dk::function; + var argument := open.argument; + if member && this.decls.has(decl, df::method) { + argument++; + } + + # The first overload with a parameter for the argument, as the call is read + # so far. Every argument after a variadic parameter's first is of it too. + var walk := this.decls.walk_overloads(this.first_overload(decl), 32); + while true { + val at := walk.next(); + break if at == 0; + this.resolve(at); + val kind: u32 = this.decls.types.p[at]; + val count := kind != 0 ? this.types.part_count(kind) : 0; + val variadic := this.decls.has(at, df::variadic); + if argument < count { + return this.types.part_at(kind, argument); + } + if variadic && count != 0 { + return this.types.part_at(kind, count - 1); + } + } + return 0; +} diff --git a/analyzer/queries/completion.sakura b/analyzer/queries/completion.sakura new file mode 100644 index 00000000..2ca31aae --- /dev/null +++ b/analyzer/queries/completion.sakura @@ -0,0 +1,1223 @@ +#! @file completion.sakura +#! @author John Christman (sorakatadzuma@gmail.com) +#! @copyright Malunal Studios, LLC. +#! @license MIT +#! +#! Contains completion: the names that may be written at a position. After +#! `value.` they are the members of the value, after `path::` what the module +#! or type the path names declares, and otherwise what the place takes, then +#! the locals, declarations, modules, and keywords in scope there. + +import std::containers; +module sakura::analyzer; + + +#! A name that may be written at a position. +pub struct completion { + pub var name: string; #! The name to write. + pub var kind: symbol; #! What it is. + pub var signature: string; #! How it is declared, as `hover` shows it, or empty. + pub var documentation: string; #! Its documentation comment, or empty. + pub var insert: string; #! What to write where it is more than the name, as `w = ` for a field of a struct literal or `red => ` for an arm of a match, or empty. +} + +#! The kind of place a name is written in, which says what is offered there. +enum place_kind : u8 { + anywhere, + type_only, #! A type: after the `:` of a declaration or bound, `as`, the `&` of a type, or `::<`. + imported, #! A module, after `import`. + field, #! A field a struct literal gives, after its `{` or a `,`. + arm, #! The pattern an arm of a match begins with. + test, #! What `is` tests for: a field of a union, or a trait. +} + +#! Where a name is completed: the kind of place, and what says more of it. +struct completing { + var kind: place_kind; + var opening: u32; #! Of a field, the `{` of the literal; of an arm, the `match`; of a test, the `is`. A token. + var written: vector; #! The names of the fields the literal gives, or of the patterns the match has, already. +} + +#! What a completion gathers as it goes. +struct offering { + var items: vector; #! The names offered, in order. + var fits: vector; #! Of each, whether its value is of the type expected. + var seen: hashset; #! The names offered already, each once. + var types: bool; #! Whether only what names a type is offered. + var expected: u32; #! The type of the argument being written, or 0. +} + +#! The keywords offered where a name may be written. +const completion_keywords: strview[34] = [ + "var", "val", "mut", "def", "return", "if", "else", "for", "in", "while", "break", + "continue", "match", "when", "where", "as", "is", "not", "true", "false", "null", "type", "struct", + "union", "trait", "enum", "const", "pub", "import", "module", "extern", "expects", "asserts", "ensures" +]; + +#! The names that may be written at the offset of the file, in the order they +#! are found, so locals come before what is declared further away. They are not +#! filtered by what is already written of the name being completed. A member +#! name must follow `.` for the value before it to parse, so an editor completing +#! right after `.` checks the text with a name written there. +#! @param this The checker. +#! @param file The file. +#! @param offset The byte of its text. +#! @returns The names. +pub def checker::complete(&mut this, file: u32, offset: u32): vector { + var offer := offering { + items = vector::::new(), + fits = vector::::new(), + seen = hashset::::new() + }; + val text := this.units[file].source.make_lexeme(0, this.units[file].source.length); + return move(&mut offer.items) if offset as u64 > text.length || this.in_text(text, offset); + + var start := offset; + while start > 0 && is_word_byte(text[(start - 1) as u64]) { + start--; + } + + val asked := this.begin_query(file); + this.at.home = this.home_at(file, start); + + # After `value.`, the members of the value's type, but not after `..` of a range. + if start >= 1 && text[(start - 1) as u64] == '.' && (start < 2 || text[(start - 2) as u64] != '.') { + for &node in asked.walked.order { + continue if this.kind_of(node) != nk::member; + continue if this.units[file].syntax.token_offsets[this.token_of(node)] != start; + this.offer_value(&mut offer, this.type_at(this.left_of(node))); + break; + } + return move(&mut offer.items); + } + + # After `path::`, what the module or type the path names declares. + if start >= 2 && text[(start - 1) as u64] == ':' && text[(start - 2) as u64] == ':' { + this.offer_path(&mut offer, file, start, text); + return move(&mut offer.items); + } + + # Otherwise what the place the name is written in takes: a module after + # `import`, a type where one is written, the fields a struct literal has yet to + # give, the members of an enum or fields of a union an arm of a match has yet + # to handle, and after `is`, the fields of the union tested or a trait. + var site := this.place_of_completion(file, start); + match site.kind { + place_kind::imported => { + this.offer_modules(&mut offer, 0); + return move(&mut offer.items); + } + place_kind::field => { + val made := this.literal_type(file, site.opening, &asked.walked); + if made != 0 { + val run: u32 = this.decls.children.p[made]; + for i in 0..this.decls.list_length(run) { + val field := this.decls.list_at(run, i as u32); + continue if this.decls.kinds.p[field] != dk::field || this.is_written(&site, this.decls.names.p[field]); + continue if !this.visible(field); + val index := offer.items.length; + this.offer_decl(&mut offer, field); + this.give_insert(&mut offer, index, " = "); + } + } + } + place_kind::arm => { + val subject := this.subject_type(file, site.opening, &asked.walked); + if subject != 0 { + val decl := this.types.first_of(subject); + val run: u32 = this.decls.children.p[decl]; + for i in 0..this.decls.list_length(run) { + val member := this.decls.list_at(run, i as u32); + val kind: dk = this.decls.kinds.p[member]; + continue if (kind != dk::field && kind != dk::enum_member) || this.is_written(&site, this.decls.names.p[member]); + val index := offer.items.length; + this.offer_decl(&mut offer, member); + this.give_insert(&mut offer, index, " => "); + } + val index := offer.items.length; + this.offer_name(&mut offer, "else", symbol::keyword, "", ""); + this.give_insert(&mut offer, index, " => "); + return move(&mut offer.items); + } + } + place_kind::test => { + val tested := this.tested_union(file, site.opening, &asked.walked); + if tested != 0 { + val run: u32 = this.decls.children.p[this.types.first_of(tested)]; + for i in 0..this.decls.list_length(run) { + val field := this.decls.list_at(run, i as u32); + continue if this.decls.kinds.p[field] != dk::field; + this.offer_decl(&mut offer, field); + } + } + offer.types = true; + } + place_kind::type_only => offer.types = true; + place_kind::anywhere => { + # Within a call, the names whose values are of the argument's type come first. + offer.expected = this.argument_type(file, start, &asked.walked, &asked.decls); + } + } + + # Then the names in scope: locals first, then what the types around the place + # give, what is declared in the module, imported, and built in, then modules + # and keywords. + this.offer_locals(&mut offer, file, start, &asked.walked); + this.offer_scope(&mut offer, file, start, &asked.walked, &asked.decls); + this.offer_module_decls(&mut offer, this.at.home, true); + + # The program's own modules come before the standard library, and the built-in + # types between them, since they are what a type is most often written as. + val imports: u32 = this.units[file].imports; + for pass in 0..2 { + for i in 0..this.decls.list_length(imports) { + val imported := this.decls.list_at(imports, i as u32); + continue if this.in_library(imported) != (pass == 1); + this.offer_module_decls(&mut offer, imported, false); + } + # Each name of a built-in type is offered, as `int` and `i64` of one type, + # each name and type copied out first, since offering one changes the + # checker a loop over its built-in types would lock. + if pass == 0 { + var built := vector::::new(); + for &each in this.builtins { + built.append(pair_key(each.key, each.value)); + } + for &each in built { + val signature := this.signature_of(pair_low(each)); + this.offer_name(&mut offer, this.names.text(pair_high(each)), symbol::type_name, signature.view(), ""); + } + } + } + # Then `core`'s root, which every file sees, after what the file imports. + val core := this.modules.find(0, word::core); + if core != 0 { + this.offer_module_decls(&mut offer, core, this.modules.within(this.at.home, core)); + } + this.offer_modules(&mut offer, 0); + for &each in this.decls.list_view(imports) { + this.offer_module(&mut offer, each); + } + + # Where a type is written, `def` begins a function type and `mut` follows `&`. + val types := offer.types; + offer.types = false; + for &keyword in completion_keywords { + continue if types && keyword != "def" && keyword != "mut"; + this.offer_name(&mut offer, keyword, symbol::keyword, "", ""); + } + + # The names of the argument's type are put first, each kind keeping its order. + if offer.expected != 0 { + var ordered := vector::::new(); + for i in 0..offer.items.length { + if offer.fits[i] { + ordered.append(move(&mut offer.items[i])); + } + } + for i in 0..offer.items.length { + if !offer.fits[i] { + ordered.append(move(&mut offer.items[i])); + } + } + return ordered; + } + return move(&mut offer.items); +} + +#! Whether the offset is within a comment or text on its line, where no names +#! are completed. +#! @param this The checker. +#! @param text The file's text. +#! @param offset The byte of the text. +#! @returns Whether it is. +def checker::in_text(&this, text: strview, offset: u32): bool { + var line := offset; + while line > 0 && text[(line - 1) as u64] != '\n' { + line--; + } + var quote: u8 = 0; + var at := line; + while at < offset { + val byte: u8 = text[at as u64]; + if quote != 0 { + if byte == '\\' { + at++; + } else if byte == quote { + quote = 0; + } + } else if byte == '"' || byte == '\'' { + quote = byte; + } else if byte == '#' { + return true; + } + at++; + } + return quote != 0; +} + +#! Offers a name, once, where the place takes it. +#! @param this The checker. +#! @param offer What is offered so far. +#! @param name The name. +#! @param kind What it is. +#! @param signature How it is declared. +#! @param documentation Its documentation. +def checker::offer_name(&this, offer: &mut offering, name: strview, kind: symbol, signature: strview, documentation: strview): void { + return if name.length == 0 || name == "_"; + + # Where a type is written, only what names one is offered. + if offer.types && kind != symbol::struct_type && kind != symbol::trait_type && kind != symbol::enum_type + && kind != symbol::type_name && kind != symbol::type_param && kind != symbol::namespace { + return; + } + var key := string::from(name, nothing {}); + return if !offer.seen.insert(move(&mut key)); + offer.items.append(completion { + name = string::from(name, nothing {}), + kind = kind, + signature = string::from(signature, nothing {}), + documentation = string::from(documentation, nothing {}), + insert = string::new(nothing {}) + }); + offer.fits.append(false); +} + +#! Offers a declaration, and says whether its value is of the type of the +#! argument being written: a variable, constant, or member of an enum of the +#! type, or a function giving one. +#! @param this The checker. +#! @param offer What is offered so far. +#! @param decl The declaration. +def checker::offer_decl(&mut this, offer: &mut offering, decl: u32): void { + return if decl == 0 || this.decls.kinds.p[decl] == dk::none || this.decls.has(decl, df::failed); + val shown := this.standing_for(decl); + val index := offer.items.length; + val file: u32 = this.decls.files.p[shown]; + val signature := this.signature_of(shown); + val documentation := this.documentation_of(file, this.decls.nodes.p[shown]); + this.offer_name(offer, this.decl_text(shown), this.symbol_of(shown), signature.view(), documentation.view()); + return if offer.expected == 0 || offer.items.length == index; + + var have: u32 = 0; + match this.decls.kinds.p[shown] { + dk::variable, dk::enum_member, dk::field => have = this.decls.types.p[shown]; + dk::function => { + val kind: u32 = this.decls.types.p[shown]; + have = kind != 0 && this.types.kind_of(kind) == ty::function ? this.types.first_of(kind) : 0; + } + else => {} + } + var want := offer.expected; + have = have == 0 ? 0 : this.reached(have); + want = this.reached(want); + offer.fits[index] = have != 0 && have != bt::error + && (have == want || (this.type_decl(have) != 0 && this.type_decl(have) == this.type_decl(want) + && this.types.kind_of(have) == this.types.kind_of(want))); +} + +#! Offers a local, by the node declaring it. +#! @param this The checker. +#! @param offer What is offered so far. +#! @param file The file. +#! @param node The node declaring it. +def checker::offer_local(&mut this, offer: &mut offering, file: u32, node: u32): void { + val syntax := &this.units[file].syntax; + val kind := syntax.node_kinds[node] == nk::param ? symbol::parameter : symbol::variable; + val index := offer.items.length; + val signature := this.local_signature(file, node); + val documentation := this.documentation_of(file, node); + this.offer_name(offer, this.local_text(file, node), kind, signature.view(), documentation.view()); + this.query_file(file); + return if offer.expected == 0 || offer.items.length == index; + val have := this.reached(this.type_at(node)); + val want := this.reached(offer.expected); + offer.fits[index] = have != 0 && have != bt::error + && (have == want || (this.type_decl(have) != 0 && this.type_decl(have) == this.type_decl(want))); +} + +#! Gives the item offered at the index a text to write of its own, its name and +#! then `suffix`, as `w = `. +#! @param this The checker. +#! @param offer What is offered so far. +#! @param index The item. +#! @param suffix What follows its name. +def checker::give_insert(&this, offer: &mut offering, index: u64, suffix: strview): void { + return if index >= offer.items.length; + var made := string::copy_of(&offer.items[index].name); + made.append(suffix); + offer.items[index].insert = move(&mut made); +} + +#! Offers a module, by the last segment of its path. +#! @param this The checker. +#! @param offer What is offered so far. +#! @param id The module. +def checker::offer_module(&this, offer: &mut offering, id: u32): void { + return if id == 0; + val signature := this.module_signature(id); + this.offer_name(offer, this.names.text(this.modules.names[id]), symbol::namespace, signature.view(), ""); +} + +#! Offers the modules within a module. +#! @param this The checker. +#! @param offer What is offered so far. +#! @param parent The module. +def checker::offer_modules(&this, offer: &mut offering, parent: u32): void { + for id in 1..this.modules.names.length { + if this.modules.parents[id] == parent && this.declares_any(id as u32) { + this.offer_module(offer, id as u32); + } + } +} + +#! Whether a module, or one within it, declares anything for the target, as +#! the runtime of executables does not for the machine. +#! @param this The checker. +#! @param id The module. +#! @returns Whether it does. +def checker::declares_any(&this, id: u32): bool { + for decl in 1..this.decls.count { + continue if this.decls.kinds.p[decl] == dk::none; + return true if this.modules.within(this.decls.modules.p[decl], id); + } + return false; +} + +#! Offers what a module declares that the place can name: all of it within the +#! module or one it holds, and else only what it declares `pub`. +#! @param this The checker. +#! @param offer What is offered so far. +#! @param id The module. +#! @param own Whether it is the module the place is in. +def checker::offer_module_decls(&mut this, offer: &mut offering, id: u32, own: bool): void { + # Offering may make declarations, as of attributes, which the module may list, + # so what it lists is copied first. + var listed := vector::::new(); + listed.extend(this.decls.by_module.of(id)); + for &decl in listed { + continue if this.decls.modules.p[decl] != id || this.decls.owners.p[decl] != 0; + match this.decls.kinds.p[decl] { + dk::function, dk::variable, dk::struct_type, dk::union_type, dk::enum_type, dk::trait_type, dk::alias_type => {} + else => continue; + } + continue if this.modules.decl(id, this.decls.names.p[decl]) == 0; + continue if !own && !this.visible(decl); + this.offer_decl(offer, decl); + } +} + +#! Offers what the types around the place give its names, as `kind` within +#! `token` is `token::kind`: their nested types and associated variables, and +#! an enum's members. +#! @param this The checker. +#! @param offer What is offered so far. +#! @param file The file. +#! @param offset The byte of its text. +#! @param walked The file's tree. +#! @param decls The declarations of the file's nodes. +def checker::offer_scope(&mut this, offer: &mut offering, file: u32, offset: u32, walked: &tree_walk, decls: &dict): void { + # The top-level declaration holding the place. + var top: u32 = 0; + val syntax := &this.units[file].syntax; + val run := syntax.node_lefts[this.units[file].root]; + for &node in syntax.run_view(run) { + break if syntax.token_offsets[syntax.start_of(node)] > offset; + top = node; + } + return if top == 0; + var held: u32 = 0; + if decls.get(&top) is some(found) { + held = found; + } + return if held == 0; + var kind := this.scope_of(held, 0); + var steps := 0; + while kind != 0 && steps < 16 { + steps++; + val holder := this.type_decl(kind); + break if holder == 0; + var given := vector::::new(); + val nested := &this.decls.nested; + for at in 0..nested.capacity { + val key := nested.key_at(at); + if key != keymap::free && pair_high(key) == holder { + given.append(nested.value_at(at)); + } + } + val members := &this.decls.members; + for at in 0..members.capacity { + val key := members.key_at(at); + continue if key == keymap::free || pair_high(key) != holder; + val member := members.value_at(at); + val member_kind: dk = this.decls.kinds.p[member]; + if member_kind == dk::variable || member_kind == dk::enum_member { + given.append(member); + } + } + for &each in given { + if this.visible(each) { + this.offer_decl(offer, each); + } + } + val outer: u32 = this.decls.owners.p[holder]; + break if outer == 0 || !this.gives_scope(outer); + kind = this.decls.types.p[outer]; + } +} + +#! Offers what may follow `value.`: fields, properties, and methods, through +#! references and aliases, and the methods a type parameter's bounds give. +#! @param this The checker. +#! @param offer What is offered so far. +#! @param kind The value's type. +def checker::offer_value(&mut this, offer: &mut offering, kind: u32): void { + return if kind == 0 || kind == bt::error; + var at := this.reached(kind); + if this.types.kind_of(at) == ty::pointer { + at = this.types.first_of(at); + } + var steps := 0; + while steps < 16 { + steps++; + if this.types.kind_of(at) == ty::param { + # What its bounds ask for, and within a trait, `self` has the trait's. + val param := this.types.first_of(at); + val run: u32 = this.decls.children.p[param]; + for i in 0..this.decls.list_length(run) { + this.offer_trait(offer, this.types.first_of(this.decls.list_at(run, i as u32)), 0); + } + val holder: u32 = this.decls.owners.p[param]; + if this.decls.names.p[param] == names::self_id && holder != 0 && this.decls.kinds.p[holder] == dk::trait_type { + this.offer_trait(offer, holder, 0); + } + return; + } + val decl := this.type_decl(at); + if decl != 0 { + if this.decls.kinds.p[decl] == dk::struct_type || this.decls.kinds.p[decl] == dk::union_type { + this.offer_fields(offer, decl, 0); + } + this.offer_members(offer, decl, true); + # The methods the traits it implements write for it. + if this.decls.kinds.p[decl] == dk::struct_type || this.decls.kinds.p[decl] == dk::union_type { + val traits := this.composed_of(decl); + for i in 0..this.decls.list_length(traits) { + this.offer_trait(offer, this.types.first_of(this.decls.list_at(traits, i as u32)), 0); + } + } + if this.decls.kinds.p[decl] == dk::trait_type { + this.offer_trait(offer, decl, 0); + } + } + break if !this.is_alias(at); + at = this.alias_target(at); + } +} + +#! Offers the methods a trait asks for, with those of the traits it composes. +#! @param this The checker. +#! @param offer What is offered so far. +#! @param trait_decl The trait. +#! @param depth How deeply composition has been followed. +def checker::offer_trait(&mut this, offer: &mut offering, trait_decl: u32, depth: u32): void { + return if trait_decl == 0 || depth > 16 || this.decls.kinds.p[trait_decl] != dk::trait_type; + this.offer_members(offer, trait_decl, true); + val run := this.composed_of(trait_decl); + for i in 0..this.decls.list_length(run) { + this.offer_trait(offer, this.types.first_of(this.decls.list_at(run, i as u32)), depth + 1); + } +} + +#! Offers the fields of a struct or union, with those its spread fields bring in +#! by the names they are reached by. +#! @param this The checker. +#! @param offer What is offered so far. +#! @param decl The struct or union. +#! @param depth How deeply spreads have been followed. +def checker::offer_fields(&mut this, offer: &mut offering, decl: u32, depth: u32): void { + return if depth > 16; + val run: u32 = this.decls.children.p[decl]; + for i in 0..this.decls.list_length(run) { + val field := this.decls.list_at(run, i as u32); + continue if this.decls.kinds.p[field] != dk::field || !this.visible(field); + this.offer_decl(offer, field); + if this.is_spread(field) { + this.resolve(field); + val spread := this.type_decl(this.reached(this.decls.types.p[field])); + if spread != 0 && this.decls.kinds.p[spread] == dk::struct_type { + this.offer_fields(offer, spread, depth + 1); + } + } + } +} + +#! Offers the members a type declares: only its methods and properties, where +#! they follow a value, or everything `::` reaches, as its functions, associated +#! variables, members of an enum, and nested types. +#! @param this The checker. +#! @param offer What is offered so far. +#! @param decl The type. +#! @param values Whether they follow a value. +def checker::offer_members(&mut this, offer: &mut offering, decl: u32, values: bool): void { + var firsts := vector::::new(); + val members := &this.decls.members; + for at in 0..members.capacity { + val key := members.key_at(at); + if key != keymap::free && pair_high(key) == decl { + firsts.append(members.value_at(at)); + } + } + var nested := vector::::new(); + val types := &this.decls.nested; + for at in 0..types.capacity { + val key := types.key_at(at); + if key != keymap::free && pair_high(key) == decl { + nested.append(types.value_at(at)); + } + } + for &first in firsts { + var walk := this.decls.walk_overloads(first, 64); + while true { + val at := walk.next(); + break if at == 0; + val kind: dk = this.decls.kinds.p[at]; + val wanted := values + ? (kind == dk::function && (this.decls.has(at, df::method) || this.decls.has(at, df::accessor))) || kind == dk::property + : kind != dk::field; + if wanted && this.visible(at) && this.member_seen(at) { + this.offer_decl(offer, at); + break; + } + } + } + if !values { + for &each in nested { + if this.visible(each) { + this.offer_decl(offer, each); + } + } + } +} + +#! Offers what may follow `path::`: what the module the path names declares and +#! the modules within it, or the members of the type it names, with those of +#! the types it aliases. +#! @param this The checker. +#! @param offer What is offered so far. +#! @param file The file. +#! @param start Where the name completed begins. +#! @param text The file's text. +def checker::offer_path(&mut this, offer: &mut offering, file: u32, start: u32, text: strview): void { + # The segments before `::`, last first. Type arguments before `::`, as in + # `stack::`, are passed over. + var names := vector::::new(); + var at := start - 2; + while names.length < 16 { + if at > 0 && text[(at - 1) as u64] == '>' { + var angles := 0; + while at > 0 { + at--; + if text[at as u64] == '>' { + angles++; + } else if text[at as u64] == '<' { + angles--; + break if angles == 0; + } + } + if at >= 2 && text[(at - 1) as u64] == ':' && text[(at - 2) as u64] == ':' { + at -= 2; + } + } + val end := at; + while at > 0 && is_word_byte(text[(at - 1) as u64]) { + at--; + } + break if at == end; + val word := text.substr(at as u64, (end - at) as u64); + names.append(this.names.intern(&word)); + break if at < 2 || text[(at - 1) as u64] != ':' || text[(at - 2) as u64] != ':'; + at -= 2; + } + return if names.length == 0; + + # The first segment is a module, a type, or a type parameter, as the place + # names it; the rest are what the one before declares. + var home: u32 = 0; + var decl: u32 = 0; + var in_module := false; + val first: u32 = names.last(); + return if first == 0; + val bound := this.bound(first); + if (bound & ref_type) != 0 { + decl = this.type_decl(bound & ref_mask); + } else { + home = this.lookup_module(first); + in_module = home != 0; + if !in_module { + decl = this.lookup_type(first, 0); + } + } + var i := names.length - 1; + while i > 0 { + i--; + val name: u32 = names[i]; + return if name == 0; + if in_module { + decl = this.modules.decl(home, name); + if decl == 0 { + home = this.modules.find(home, name); + return if home == 0; + } else { + in_module = false; + } + } else { + return if decl == 0; + decl = this.decls.path_member(decl, name); + } + } + + if in_module { + this.offer_module_decls(offer, home, this.modules.within(this.at.home, home)); + this.offer_modules(offer, home); + # A library's modules no file read refers to yet are found by their folders. + var path := vector::::new(); + this.module_segments(home, &mut path); + for &each in modules_within(this.shelves.view(), path.view()) { + this.offer_name(offer, each.view(), symbol::namespace, "", ""); + } + return; + } + return if decl == 0 || !this.is_type_decl(decl); + var kind: u32 = this.decls.types.p[decl]; + var steps := 0; + while steps < 16 { + steps++; + val holder := this.type_decl(kind); + if holder != 0 { + this.offer_members(offer, holder, false); + } + break if !this.is_alias(kind); + kind = this.alias_target(kind); + } +} + +#! Offers the locals in scope at the offset: the parameters and type parameters +#! of the function holding it, and the variables of each block holding it +#! declared before it, with those its loops, arms, and tests bind there. +#! @param this The checker. +#! @param offer What is offered so far. +#! @param file The file. +#! @param offset The byte of its text. +#! @param walked The file's tree. +def checker::offer_locals(&mut this, offer: &mut offering, file: u32, offset: u32, walked: &tree_walk): void { + val syntax := &this.units[file].syntax; + # The nodes holding the place, innermost first, found from the innermost node + # whose tokens hold it. + var holders := vector::::new(); + for &node in walked.order { + continue if !this.node_holds(file, node, offset); + holders.append(node); + } + # The walk meets what holds a node before it, so the last is the innermost. + var i := holders.length; + while i > 0 { + i--; + val node: u32 = holders[i]; + match syntax.node_kinds[node] { + nk::block => { + val run: u32 = syntax.node_lefts[node]; + for &statement in syntax.run_view(run) { + break if syntax.token_offsets[syntax.start_of(statement)] >= offset; + # A variable is in scope after its declaration, not within its value. + if syntax.node_kinds[statement] == nk::variable && this.node_end(file, statement) <= offset + && this.has_flag(statement, rf::local) { + this.offer_local(offer, file, statement); + } + } + } + nk::function => { + val params := syntax.record_at(node, function_slot::params); + for ¶m in syntax.run_view(params) { + this.offer_local(offer, file, param); + } + this.offer_type_params(offer, file, syntax.record_at(node, function_slot::type_params)); + # Type parameters named before `::` belong to the method, as `T` in `box::get`. + val receiver := syntax.record_at(node, function_slot::receiver); + if receiver != 0 && syntax.node_lefts[receiver] != 0 { + val segments: u32 = syntax.node_lefts[receiver]; + val last := syntax.run_at(segments, syntax.run_length(segments) - 1); + this.offer_type_params(offer, file, syntax.node_lefts[last]); + } + } + nk::lambda => { + val params: u32 = syntax.node_lefts[node]; + for ¶m in syntax.run_view(params) { + this.offer_local(offer, file, param); + } + } + nk::for_stmt => { + if this.node_holds(file, syntax.node_rights[node], offset) { + # Its index and variable, `for_slot::index` and `for_slot::variable`. + for j in 0u..2u { + val bound := syntax.record_at(node, j as u32); + if bound != 0 && this.has_flag(bound, rf::local) { + this.offer_local(offer, file, bound); + } + } + } + } + nk::match_arm => { + val patterns: u32 = syntax.node_lefts[node]; + for &pattern in syntax.run_view(patterns) { + this.offer_bindings(offer, file, pattern); + } + } + nk::if_stmt => { + if this.node_holds(file, syntax.record_at(node, if_slot::then), offset) { + this.offer_tests(offer, file, syntax.node_lefts[node]); + } + } + nk::fallback => { + val error := syntax.record_at(node, fallback_slot::error); + if error != 0 && this.node_holds(file, syntax.record_at(node, fallback_slot::other), offset) && this.has_flag(error, rf::local) { + this.offer_local(offer, file, error); + } + } + else => {} + } + } +} + +#! Offers the names a pattern binds, as `n` of `number(n)` or `number(&mut n)`. +#! @param this The checker. +#! @param offer What is offered so far. +#! @param file The file. +#! @param pattern The pattern. +def checker::offer_bindings(&mut this, offer: &mut offering, file: u32, pattern: u32): void { + val syntax := &this.units[file].syntax; + return if pattern == 0 || syntax.node_kinds[pattern] != nk::call; + val run: u32 = syntax.node_rights[pattern]; + for &each in syntax.run_view(run) { + var bound := each; + if syntax.node_kinds[bound] == nk::reference { + bound = syntax.node_lefts[bound]; + } + if syntax.node_kinds[bound] == nk::name && this.has_flag(bound, rf::local) { + this.offer_local(offer, file, bound); + } + } +} + +#! Offers the names the `is` tests of a condition bind, as `v` of +#! `x is some(v)`, in the branch they guard. +#! @param this The checker. +#! @param offer What is offered so far. +#! @param file The file. +#! @param condition The condition. +def checker::offer_tests(&mut this, offer: &mut offering, file: u32, condition: u32): void { + val syntax := &this.units[file].syntax; + return if condition == 0; + match syntax.node_kinds[condition] { + nk::is_test => { + var bound := syntax.record_at(condition, is_slot::binding); + if bound != 0 && syntax.node_kinds[bound] == nk::reference { + bound = syntax.node_lefts[bound]; + } + if bound != 0 && this.has_flag(bound, rf::local) { + this.offer_local(offer, file, bound); + } + } + nk::binary => { + this.offer_tests(offer, file, syntax.node_lefts[condition]); + this.offer_tests(offer, file, syntax.node_rights[condition]); + } + else => {} + } +} + +#! Offers the type parameters of a run. +#! @param this The checker. +#! @param offer What is offered so far. +#! @param file The file. +#! @param run The run of `type_param` nodes. +def checker::offer_type_params(&mut this, offer: &mut offering, file: u32, run: u32): void { + val syntax := &this.units[file].syntax; + return if run == 0; + for ¶m in syntax.run_view(run) { + # A pattern offers the type parameters it names. + if syntax.node_kinds[param] == nk::type_pattern { + this.offer_type_params(offer, file, syntax.node_lefts[param]); + if syntax.node_rights[param] != 0 { + this.offer_type_param(offer, file, syntax.node_rights[param]); + } + continue; + } + if syntax.node_kinds[param] == nk::array_pattern { + this.offer_type_param(offer, file, syntax.node_lefts[param]); + if syntax.node_rights[param] != 0 { + this.offer_type_param(offer, file, syntax.node_rights[param]); + } + continue; + } + this.offer_type_param(offer, file, param); + } +} + +#! Offers a type parameter, or a constant one. +#! @param this The checker. +#! @param offer What is offered so far. +#! @param file The file. +#! @param param The `type_param` or `const_param` node. +def checker::offer_type_param(&mut this, offer: &mut offering, file: u32, param: u32): void { + val syntax := &this.units[file].syntax; + var text := string::from(syntax.node_kinds[param] == nk::const_param ? "constant parameter " : "type parameter ", nothing {}); + this.param_text(file, param, &mut text); + this.offer_name(offer, this.token_text(file, syntax.node_tokens[param]), + syntax.node_kinds[param] == nk::const_param ? symbol::constant : symbol::type_param, text.view(), ""); +} + +#! Whether a node's tokens hold the offset: from where it begins to where its +#! last token ends. A block holds what is after its `{` through its `}`. +#! @param this The checker. +#! @param file The file. +#! @param node The node. +#! @param offset The byte of its text. +#! @returns Whether they do. +def checker::node_holds(&this, file: u32, node: u32, offset: u32): bool { + return false if node == 0; + val syntax := &this.units[file].syntax; + val first: u32 = syntax.token_offsets[syntax.node_tokens[node]]; + val brace := syntax.node_kinds[node] == nk::block && syntax.token_kinds[syntax.node_tokens[node]] == tk::lbrace; + return false if brace ? offset <= first : offset < first; + val last: u32 = syntax.node_end(node); + if brace { + # A block whose `}` is missing, as one being written, holds the rest. + return syntax.token_kinds[last] != tk::rbrace || offset <= syntax.token_offsets[last]; + } + return offset <= this.node_end(file, node); +} + +#! Where a node's last token ends. +#! @param this The checker. +#! @param file The file. +#! @param node The node. +#! @returns The byte its last token ends at. +def checker::node_end(&this, file: u32, node: u32): u32 { + val syntax := &this.units[file].syntax; + val last: u32 = syntax.node_end(node); + return syntax.token_offsets[last] + syntax.token_length(last, this.names); +} + +#! Whether the name of a field or pattern is one the literal or match has +#! already. +#! @param this The checker. +#! @param site Where the name is completed. +#! @param name The ID of the name. +#! @returns Whether it is. +def checker::is_written(&this, site: &completing, name: u32): bool { + for &each in site.written { + return true if each == name; + } + return false; +} + +#! The segments of a module's path, its outermost first. +#! @param this The checker. +#! @param id The module. +#! @param into Where they are added. +def checker::module_segments(&this, id: u32, into: &mut vector): void { + return if id == 0; + this.module_segments(this.modules.parents[id], into); + into.append(string::from(this.names.text(this.modules.names[id]), nothing {})); +} + +#! Whether a module is `core`'s, the standard library's, or `system`'s, or one +#! within them. +#! @param this The checker. +#! @param id The module. +#! @returns Whether it is. +def checker::in_library(&this, id: u32): bool { + var at := id; + var steps := 0; + while at != 0 && steps < 64 { + return this.modules.names[at] == word::std || this.modules.names[at] == word::core + || this.modules.names[at] == word::system + if this.modules.parents[at] == 0; + at = this.modules.parents[at]; + steps++; + } + return false; +} + +#! Whether a token opens a group, as `(`. +#! @param kind The token's kind. +#! @returns Whether it does. +def opens_group(kind: tk): bool { + return kind == tk::lparen || kind == tk::lbracket || kind == tk::lbrace; +} + +#! Whether a token closes a group, as `)`. +#! @param kind The token's kind. +#! @returns Whether it does. +def closes_group(kind: tk): bool { + return kind == tk::rparen || kind == tk::rbracket || kind == tk::rbrace; +} + +#! What stands for no token, where completion looks for one before a place and +#! finds none. +const no_token: u32 = 0xFFFFFFFF; + +#! The token before another at the same depth of groups, passing over whole +#! groups, or `no_token` where there is none. +#! @param kinds The kinds of the tokens. +#! @param at The token. +#! @returns The token before it, or `no_token`. +def token_before(kinds: &vector, at: u32): u32 { + var depth := 0; + var k := at; + while k > 0 { + k--; + if closes_group(kinds[k]) { + depth++; + } else if opens_group(kinds[k]) { + return no_token if depth == 0; + depth--; + } + return k if depth == 0; + } + return no_token; +} + +#! Whether a name written after the first `count` tokens names a type: after +#! `as`, after the `:` of a declaration, parameter, result, or bound, rather than +#! of a ternary or a slice, after `&`, `*`, or `mut` of a type, and among type +#! arguments. +#! @param kinds The kinds of the tokens. +#! @param count How many come before the name. +#! @param depth How deeply type arguments have been followed. +#! @returns Whether it does. +def typed_place(kinds: &vector, count: u32, depth: u32): bool { + var at := count; + while at > 0 && (kinds[at - 1] == tk::bitand || kinds[at - 1] == tk::star || kinds[at - 1] == tk::kw_mut) { + at--; + } + return false if at == 0 || depth > 16; + val before := kinds[at - 1]; + return true if before == tk::kw_as; + + if before == tk::colon { + # Within the statement, a `?` before the `:` makes it a ternary's, and a `[` + # holding it a slice's. + var k := token_before(kinds, at - 1); + while k != no_token { + return false if kinds[k] == tk::quest; + break if kinds[k] == tk::semicolon || kinds[k] == tk::lbrace || kinds[k] == tk::rbrace; + k = token_before(kinds, k); + } + var open := 0; + var j := at - 1; + while j > 0 { + j--; + if closes_group(kinds[j]) { + open++; + } else if opens_group(kinds[j]) { + return kinds[j] != tk::lbracket if open == 0; + open--; + } + } + return true; + } + + # Type arguments: after the `<` of `::<`, or of a name that is itself a type. + if before == tk::less || before == tk::comma { + var angles := 0; + var j := at; + while j > 0 { + j--; + val kind := kinds[j]; + if kind == tk::more { + angles++; + } else if kind == tk::rshift { + angles += 2; + } else if kind == tk::less && angles > 0 { + angles--; + } else if kind == tk::less { + return (j > 0 && kinds[j - 1] == tk::scope) + || (j > 0 && kinds[j - 1] == tk::name && typed_place(kinds, j - 1, depth + 1)); + } else if opens_group(kind) || closes_group(kind) || kind == tk::semicolon { + return false; + } + } + } + return false; +} + +#! Works out what kind of place a name beginning at `start` is written in, from +#! the tokens of the top-level declaration holding it, up to it. +#! @param this The checker. +#! @param file The file. +#! @param start Where the name begins. +#! @returns The place. +def checker::place_of_completion(&mut this, file: u32, start: u32): completing { + var found := completing { kind = place_kind::anywhere, written = vector::::new() }; + val syntax := &this.units[file].syntax; + + # The tokens from the top-level declaration holding the place. + var first: u32 = 0; + val run := syntax.node_lefts[this.units[file].root]; + for &node in syntax.run_view(run) { + val begins := syntax.start_of(node); + break if syntax.token_offsets[begins] >= start; + first = begins; + } + var kinds := vector::::new(); + var tokens := vector::::new(); + var at := first; + while (at as u64) < syntax.token_count && syntax.token_offsets[at] < start && syntax.token_kinds[at] != tk::eof { + kinds.append(syntax.token_kinds[at]); + tokens.append(at); + at++; + } + val count := kinds.length as u32; + return found if count == 0; + + val last := kinds[count - 1]; + if last == tk::kw_imp && !(count >= 2 && kinds[count - 2] == tk::kw_extern) { + found.kind = place_kind::imported; + return found; + } + if last == tk::kw_is || (last == tk::kw_not && count >= 2 && kinds[count - 2] == tk::kw_is) { + found.kind = place_kind::test; + found.opening = tokens[last == tk::kw_is ? count - 1 : count - 2]; + return found; + } + if typed_place(&kinds, count, 0) { + found.kind = place_kind::type_only; + return found; + } + + # Within braces, where a field is named or an arm begins: right after the `{`, + # or after a `,`, or after a `;` or `}` ending an arm. + var brace: u32 = no_token; + var open := 0; + var k := count; + while k > 0 { + k--; + if closes_group(kinds[k]) { + open++; + } else if opens_group(kinds[k]) { + if open == 0 { + if kinds[k] == tk::lbrace { + brace = k; + } + break; + } + open--; + } + } + return found if brace == no_token + || (last != tk::lbrace && last != tk::comma && last != tk::semicolon && last != tk::rbrace); + + # A match: `match` begins the statement the brace follows. + var j := token_before(&kinds, brace); + while j != no_token { + val kind := kinds[j]; + if kind == tk::kw_match { + found.kind = place_kind::arm; + found.opening = tokens[j]; + break; + } + break if kind == tk::semicolon || kind == tk::lbrace || kind == tk::rbrace || kind == tk::arrow + || kind == tk::assign || kind == tk::kw_ret || kind == tk::comma; + j = token_before(&kinds, j); + } + + # A struct literal, which parsed as one, of a type named before the brace. + if found.kind == place_kind::anywhere && (last == tk::lbrace || last == tk::comma) && brace > 0 { + found.kind = place_kind::field; + found.opening = tokens[brace]; + } + + # The fields a literal gives, as `name =`, and the patterns a match has, each a + # name beginning an arm, directly within the braces. + var depth := 0; + for m in (brace + 1)..count { + val index := m as u32; + val kind := kinds[index]; + if depth == 0 && kind == tk::name { + val prior := kinds[index - 1]; + val next := index + 1 < count ? kinds[index + 1] : tk::eof; + val given := found.kind == place_kind::field + ? next == tk::assign && (prior == tk::lbrace || prior == tk::comma) + : prior == tk::lbrace || prior == tk::comma || prior == tk::semicolon || prior == tk::rbrace; + if given { + found.written.append(syntax.token_names[tokens[index]]); + } + } + if opens_group(kind) { + depth++; + } else if closes_group(kind) && depth > 0 { + depth--; + } + } + return found; +} + +#! The struct or union a literal makes, by the `{` beginning its fields, or 0 +#! where the brace begins none. +#! @param this The checker. +#! @param file The file. +#! @param brace The `{` token. +#! @param walked The file's tree. +#! @returns The struct's or union's declaration, or 0. +def checker::literal_type(&mut this, file: u32, brace: u32, walked: &tree_walk): u32 { + for &node in walked.order { + continue if this.kind_of(node) != nk::construct || this.token_of(node) != brace; + var made := this.type_at(node); + if made == 0 || made == bt::error { + val named := this.type_name_meaning(this.left_of(node)); + return 0 if named.decl == 0; + made = this.decls.types.p[named.decl]; + } + val decl := this.type_decl(this.unalias(made)); + return decl if decl != 0 && (this.decls.kinds.p[decl] == dk::struct_type || this.decls.kinds.p[decl] == dk::union_type); + return 0; + } + return 0; +} + +#! The enum or union a match tests, through references and aliases, by its +#! `match`, or 0 where it tests neither. +#! @param this The checker. +#! @param file The file. +#! @param token The `match` token. +#! @param walked The file's tree. +#! @returns The enum's or union's type, or 0. +def checker::subject_type(&mut this, file: u32, token: u32, walked: &tree_walk): u32 { + for &node in walked.order { + val kind := this.kind_of(node); + continue if (kind != nk::match_stmt && kind != nk::match_value) || this.token_of(node) != token; + val held := this.unalias(this.reached(this.type_at(this.left_of(node)))); + val named := this.named_kind(held); + return held if named == dk::enum_type || named == dk::union_type; + return 0; + } + return 0; +} + +#! The union an `is` tests, by its `is`, or 0 where it tests none. +#! @param this The checker. +#! @param file The file. +#! @param token The `is` token. +#! @param walked The file's tree. +#! @returns The union's type, or 0. +def checker::tested_union(&mut this, file: u32, token: u32, walked: &tree_walk): u32 { + for &node in walked.order { + continue if this.kind_of(node) != nk::is_test || this.token_of(node) != token; + val held := this.unalias(this.reached(this.type_at(this.left_of(node)))); + return held if this.named_kind(held) == dk::union_type; + return 0; + } + return 0; +} diff --git a/analyzer/queries/highlights.sakura b/analyzer/queries/highlights.sakura new file mode 100644 index 00000000..df893f37 --- /dev/null +++ b/analyzer/queries/highlights.sakura @@ -0,0 +1,81 @@ +#! @file highlights.sakura +#! @author John Christman (sorakatadzuma@gmail.com) +#! @copyright Malunal Studios, LLC. +#! @license MIT +#! +#! Contains the names of a file as what the checker made of each, for an editor +#! to colour them by that rather than by how they are written. + +module sakura::analyzer; + + +#! A name of a file, as what the checker made of it. +pub struct highlight { + pub var offset: u32; #! Where the name begins in the file's text. + pub var length: u32; #! How many bytes it covers. + pub var kind: symbol; #! What it is. + pub var declared: bool; #! Whether this is where it is declared. + pub var readonly: bool; #! Whether what it names is never written, as a `val` or a `const`. +} + +#! The names of the file the checker resolved, in the order they are written, +#! each with what it is, so an editor colours the rest as it otherwise would. A +#! file whose syntax has mistakes gives the names of what parsed. +#! @param this The checker. +#! @param file The file. +#! @returns The names. +pub def checker::highlights(&mut this, file: u32): vector { + var made := vector::::new(); + val syntax := &this.units[file].syntax; + val asked := this.begin_query(file); + val walked := &asked.walked; + for &node in walked.order { + val token: u32 = syntax.node_tokens[node]; + # A contract's word, `old` within an `ensures`, and `undefined` as a + # variable's value are the language's own words there, though names + # everywhere else. + val held := syntax.node_kinds[node]; + if held == nk::contract || held == nk::old_value || held == nk::undefined { + made.append(highlight { + offset = syntax.token_offsets[token], length = syntax.token_length(token, this.names), kind = symbol::keyword + }); + continue; + } + continue if syntax.token_kinds[token] != tk::name; + val meant := this.meaning_of(node, walked, &asked.decls); + continue if !meant.found(); + var declared := meant.local == node && meant.file == file; + if meant.decl != 0 { + declared = this.decls.nodes.p[meant.decl] == node && this.decls.files.p[meant.decl] == file; + } + if meant.is_module { + val outer: u32 = walked.parents[walked.parents[node]]; + declared = outer != 0 && (syntax.node_kinds[outer] == nk::module_decl || syntax.node_kinds[outer] == nk::extern_module) + || (walked.parents[node] != 0 && (syntax.node_kinds[walked.parents[node]] == nk::module_decl + || syntax.node_kinds[walked.parents[node]] == nk::extern_module)); + } + # A type named where it is used is never written there. + val kind := this.symbol_meant(&meant); + val names_type := kind == symbol::struct_type || kind == symbol::trait_type || kind == symbol::enum_type + || kind == symbol::type_name || kind == symbol::type_param; + made.append(highlight { + offset = syntax.token_offsets[token], + length = syntax.token_length(token, this.names), + kind = kind, + declared = declared, + readonly = this.readonly_meant(&meant) || (names_type && !declared) + }); + this.query_file(file); + } + + # A receiver is written before the name of what it declares, as `rect` is in + # `def rect::area`, so the names are put in the order they are written, and a + # name the walk reached twice is one. + made.sort_by(def(a: &highlight, b: &highlight): bool { return a.offset < b.offset; }); + var kept := vector::::new(); + for &each in made { + continue if kept.length != 0 && kept.last().offset == each.offset; + kept.append(each); + } + return kept; +} diff --git a/analyzer/queries/hover.sakura b/analyzer/queries/hover.sakura new file mode 100644 index 00000000..e960ae0e --- /dev/null +++ b/analyzer/queries/hover.sakura @@ -0,0 +1,226 @@ +#! @file hover.sakura +#! @author John Christman (sorakatadzuma@gmail.com) +#! @copyright Malunal Studios, LLC. +#! @license MIT +#! +#! Contains hovering: what an editor shows of the name at a position, which is +#! how what it refers to is declared, with the types the checker gave it and +#! the contract a function's body begins with, and its documentation. + +import std::containers; +module sakura::analyzer; + + +#! What hovering a name shows. +pub struct hover { + pub var signature: string; #! How what it refers to is declared, as `def str::trim(this: &str): str` or `val count: int`, after the attributes written on it, and of a function, a line for each `expects` and `ensures` its body begins with. + pub var documentation: string; #! The documentation comment of what it refers to, without its `#!`, or empty. + pub var offset: u32; #! Where the name begins in the file's text. + pub var length: u32; #! How many bytes it covers. +} + +#! What hovering the name at the offset of the file shows: a variable, +#! parameter, function, method, field, type, member of an enum, or module, +#! used or declared there. +#! @param this The checker. +#! @param file The file. +#! @param offset The byte of its text. +#! @returns What it shows, or nothing where no name is there, or checking left +#! it unresolved. +pub def checker::hover(&mut this, file: u32, offset: u32): maybe { + val token := this.token_at(file, offset); + return nothing {} if token as u64 >= this.units[file].syntax.token_count; + + val asked := this.begin_query(file); + var found := hover { + signature = string::new(nothing {}), + documentation = string::new(nothing {}) + }; + var shown := false; + for &node in asked.walked.order { + continue if this.token_of(node) != token; + shown = this.shown_at(node, &asked.walked, &asked.decls, &mut found); + break if shown; + } + return nothing {} if !shown; + return move(&mut found); +} + +#! What hovering a node of the file being queried shows, or nothing where it +#! names nothing the checker resolved. +#! @param this The checker. +#! @param node The node. +#! @param walked The file's tree. +#! @param decls The declarations of the file's nodes. +#! @param out Where what it shows is written. +#! @returns Whether it shows anything. +def checker::shown_at(&mut this, node: u32, walked: &tree_walk, decls: &dict, out: &mut hover): bool { + val file := this.at.file; + val spot := this.spot_of(file, this.token_of(node)); + val meant := this.meaning_of(node, walked, decls); + var signature := string::new(nothing {}); + var documentation := string::new(nothing {}); + + if meant.is_module { + signature = this.module_signature(meant.named_module); + } else if meant.decl != 0 { + val decl := meant.decl; + val home: u32 = this.decls.files.p[decl]; + val declared: u32 = this.decls.nodes.p[decl]; + if declared != 0 { + this.attributes_text(home, declared, &mut signature); + } + var written := this.signature_seen(decl, node, walked.parents[node]); + signature.append(written.view()); + val contract := this.contract_of(decl); + if contract.length != 0 { + signature.append("\n"); + signature.append(contract.view()); + } + documentation = this.documentation_of(home, declared); + this.query_file(file); + } else if meant.local != 0 { + signature = this.local_signature(meant.file, meant.local); + documentation = this.documentation_of(meant.file, meant.local); + } else if this.kind_of(node) == nk::member && this.type_at(node) != 0 && this.type_at(node) != bt::error { + # What the compiler gives a value, as the length of a fixed array. + signature.append("val "); + signature.append(this.text_of(node)); + signature.append(": "); + this.type_text(this.type_at(node), &mut signature); + } else { + return false; + } + + out.signature = move(&mut signature); + out.documentation = move(&mut documentation); + out.offset = spot.offset; + out.length = spot.length; + return true; +} + +#! The contract a function's body begins with, which is what callers are +#! promised: each `expects` and `ensures` before its first other statement, as +#! it is written, with its spaces and line breaks run together, a line each, +#! as `expects(b != 0)`. +#! @param this The checker. +#! @param decl The function. +#! @returns The lines, or empty text where it begins with none. +pub def checker::contract_of(&mut this, decl: u32): string { + var made := string::new(nothing {}); + return made if this.decls.kinds.p[decl] != dk::function || this.decls.has(decl, df::accessor); + val file: u32 = this.decls.files.p[decl]; + val syntax := &this.units[file].syntax; + val source := &this.units[file].source; + val node: u32 = this.decls.nodes.p[decl]; + return made if node == 0 || syntax.node_kinds[node] != nk::function; + val body := syntax.extras[syntax.node_lefts[node] as u64 + function_slot::body as u64]; + return made if body == 0 || syntax.node_kinds[body] != nk::block; + + val run := syntax.node_lefts[body]; + for i in 0..syntax.run_length(run) { + val each := syntax.run_at(run, i as u32); + break if syntax.node_kinds[each] != nk::contract; + val first: u32 = syntax.node_tokens[each]; + continue if syntax.token_names[first] == names::asserts_id; + # What it was parsed from ends at its `;`, which is left out. + var last: u32 = syntax.node_end(each); + if last > first && syntax.token_kinds[last] == tk::semicolon { + last--; + } + val begin: u64 = syntax.token_offsets[first]; + val end: u64 = syntax.token_offsets[last] + syntax.token_length(last, this.names); + continue if end <= begin; + if made.length != 0 { + made.append("\n"); + } + var spaced := false; + for &byte in source.make_lexeme(begin, end - begin) { + if byte == ' ' || byte == '\n' || byte == '\t' || byte == '\r' { + spaced = true; + continue; + } + if spaced && byte != ')' && made.length != 0 && made[made.length - 1] != '(' && made[made.length - 1] != '\n' { + made.push(' '); + } + spaced = false; + made.push(byte); + } + } + return made; +} + +#! The instance a call of a node uses, where the node is what a call calls. +#! @param this The checker. +#! @param callee The node. +#! @returns One more than the instance, or nothing. +def checker::called_by(&mut this, callee: u32): maybe { + # The call is found by its callee, which its node holds. + val syntax := &this.syn(); + for at in 1..syntax.node_count { + val node := at as u32; + continue if syntax.node_kinds[node] != nk::call || this.left_of(node) != callee; + if this.called.get(&this.result_key(node)) is some(found) { + return found; + } + return nothing {}; + } + return nothing {}; +} + +#! How a declaration is written where a node names it: a field reached through +#! a value of a generic type, as `p.x` of a `box`, is of the type the value +#! gives it, and a method called through one is of the types it is given. +#! @param this The checker. +#! @param decl The declaration. +#! @param node The node naming it, of the file being queried. +#! @param parent The node holding it. +#! @returns The signature. +def checker::signature_seen(&mut this, decl: u32, node: u32, parent: u32): string { + val kind := this.kind_of(node); + val seen := this.type_at(node); + + # A generic function a call uses is shown as the instance the call uses. + if this.decls.kinds.p[decl] == dk::function && !this.decls.has(decl, df::accessor) { + # The call is of the node, or of the path whose last segment it is. + var made: u32 = 0; + var callee := node; + if parent != 0 && kind == nk::segment && (this.kind_of(parent) == nk::path || this.kind_of(parent) == nk::type_name) { + callee = parent; + } + if this.called.get(&this.result_key(callee)) is some(found) { + made = found; + } + if made == 0 && callee != node { + if this.called.get(&this.result_key(node)) is some(found) { + made = found; + } + } + if made == 0 { + if this.called_by(callee) is some(found) { + made = found; + } + } + if made != 0 && made <= this.instances.length as u32 && this.instances[made - 1].decl == decl { + var out := string::new(nothing {}); + if this.decls.has(decl, df::exported) { + out.append("pub "); + } + this.instance_text_of(decl, true, made, &mut out); + return out; + } + } + if (kind == nk::member || kind == nk::field_init) && seen != 0 && seen != bt::error + && this.decls.kinds.p[decl] == dk::field && this.decls.types.p[decl] != seen { + var out := string::new(nothing {}); + if this.decls.has(decl, df::exported) { + out.append("pub "); + } + out.append(this.decls.has(decl, df::mutable) ? "var " : "val "); + out.append(this.decl_text(decl)); + out.append(": "); + this.type_text(seen, &mut out); + return out; + } + return this.signature_of(decl); +} diff --git a/analyzer/queries/names.sakura b/analyzer/queries/names.sakura new file mode 100644 index 00000000..ca5d70ac --- /dev/null +++ b/analyzer/queries/names.sakura @@ -0,0 +1,540 @@ +#! @file names.sakura +#! @author John Christman (sorakatadzuma@gmail.com) +#! @copyright Malunal Studios, LLC. +#! @license MIT +#! +#! Contains what the name at a position refers to, for an editor to go to where +#! that is declared, and everywhere it is written, for an editor to find its +#! references and rename it, with why some names cannot be renamed. + +module sakura::analyzer; + + +#! What the name at a position refers to. +pub struct referent { + pub var at: spot; #! The name at the position. + pub var declaration: spot; #! Where what it refers to is declared, where `declared` says it is. + pub var declared: bool; #! Whether it has a declaration to go to, which a built-in type has not. + pub var refusal: strview; #! Why it cannot be renamed, as that it is built into the language, or empty where it can. + pub var local: bool; #! Whether it is a local, a parameter, a type parameter, or a name a pattern binds, which is only written within the declaration holding it. + pub var member: bool; #! Whether it is a member of a type, as a field, method, property, member of an enum, or associated variable, which is written after `.` or `::` wherever it is not declared. +} + +#! What the name at the offset of the file refers to, used or declared there. A +#! name the offset is just past is the one asked about, as an editor puts the +#! cursor after the name it asks about. +#! @param this The checker. +#! @param file The file. +#! @param offset The byte of its text. +#! @returns What it refers to, or nothing where no name the checker resolved is +#! there. +pub def checker::name_at(&mut this, file: u32, offset: u32): maybe { + var meant := checker::meant {}; + val node := this.seek_name(file, offset, &mut meant); + return nothing {} if node == 0; + + var made := referent { + at = this.spot_of(file, this.units[file].syntax.node_tokens[node]), + refusal = "" + }; + + var declared := spot {}; + made.declared = this.declared_at(&meant, &mut declared); + made.declaration = declared; + made.refusal = this.refusal_of(&meant); + made.local = meant.local != 0 || (meant.decl != 0 && this.decls.kinds.p[meant.decl] == dk::type_param); + made.member = meant.decl != 0 && this.decls.owners.p[meant.decl] != 0 + && this.decls.kinds.p[meant.decl] != dk::type_param; + return made; +} + +#! Finds the node naming something at the offset of the file, or at the byte +#! before it. +#! @param this The checker. +#! @param file The file. +#! @param offset The byte of its text. +#! @param meant Where what it refers to is written. +#! @returns The node, or 0. +def checker::seek_name(&mut this, file: u32, offset: u32, meant: &mut checker::meant): u32 { + val syntax := &this.units[file].syntax; + val asked := this.begin_query(file); + var found: u32 = 0; + for back in 0..2 { + break if found != 0 || back as u32 > offset; + val token := this.token_at(file, offset - back as u32); + continue if token as u64 >= syntax.token_count || syntax.token_kinds[token] != tk::name; + for &node in asked.walked.order { + continue if this.token_of(node) != token; + val each := this.meaning_of(node, &asked.walked, &asked.decls); + if each.found() { + meant = each; + found = node; + break; + } + } + } + return found; +} + +#! Where what a name refers to is declared: the name of its declaration, of the +#! node declaring a local, or of the first module declaration naming a module. +#! @param this The checker. +#! @param meant What the name refers to. +#! @param out Where it is written. +#! @returns Whether it has a declaration to go to. +def checker::declared_at(&mut this, meant: &checker::meant, out: &mut spot): bool { + if meant.local != 0 { + out = this.spot_of(meant.file, this.units[meant.file].syntax.node_tokens[meant.local]); + return true; + } + if meant.is_module { + return this.module_declared(meant.named_module, out); + } + val decl := meant.decl; + return false if decl == 0 || this.decls.kinds.p[decl] == dk::builtin; + val file: u32 = this.decls.files.p[decl]; + val node: u32 = this.decls.nodes.p[decl]; + return false if node == 0; + val syntax := &this.units[file].syntax; + val token: u32 = syntax.node_tokens[node]; + return false if syntax.token_names[token] != this.decls.names.p[decl]; + out = this.spot_of(file, token); + return true; +} + +#! Where a module is declared: the last segment of the first `module` naming it, +#! in the order the files were given. +#! @param this The checker. +#! @param id The module. +#! @param out Where it is written. +#! @returns Whether a file declares it. +def checker::module_declared(&mut this, id: u32, out: &mut spot): bool { + for file in 0..this.units.length { + val syntax := &this.units[file].syntax; + val decls := syntax.node_lefts[this.units[file].root]; + for &node in syntax.run_view(decls) { + continue if syntax.node_kinds[node] != nk::module_decl && syntax.node_kinds[node] != nk::extern_module; + val path: u32 = syntax.node_lefts[node]; + continue if this.module_named(file as u32, path, 0xFFFFFFFF) != id; + val run: u32 = syntax.node_lefts[path]; + val last := run == 0 ? path : syntax.run_at(run, syntax.run_length(run) - 1); + out = this.spot_of(file as u32, syntax.node_tokens[last]); + return true; + } + } + return false; +} + +#! Why renaming what a name refers to would lose it, or empty text where it +#! would not: what is built in, a module, `this`, and what the compiler finds by +#! its name. +#! @param this The checker. +#! @param meant What the name refers to. +#! @returns Why it cannot be renamed, or empty text. +def checker::refusal_of(&mut this, meant: &checker::meant): strview { + if meant.is_module { + return "A module is named by every file that declares or imports it, which renaming does not change."; + } + if meant.local != 0 { + val name := this.local_text(meant.file, meant.local); + if name == "this" { + return "`this` is what every method calls its receiver."; + } + val syntax := &this.units[meant.file].syntax; + if syntax.node_kinds[meant.local] == nk::param && (syntax.flags_at(meant.local) & nf::implied as u32) != 0 { + return "`value` is what every `set` calls what it is given."; + } + return ""; + } + + val decl := meant.decl; + return "" if decl == 0; + if this.decls.kinds.p[decl] == dk::builtin || this.decls.nodes.p[decl] == 0 { + return "It is built into the language."; + } + if this.decls.kinds.p[decl] == dk::type_param && this.decls.names.p[decl] == names::self_id { + return "`self` is what implements the trait it is written within."; + } + if this.decls.kinds.p[decl] == dk::function && this.decls.has(decl, df::intrinsic) { + return "An `@intrinsic` function is bound to what implements it by its name."; + } + if this.decls.kinds.p[decl] == dk::function && this.decls.has(decl, df::foreign) && !this.has_body(decl) { + return "A function without a body in an `extern module` is the C function of its name."; + } + if (this.decls.kinds.p[decl] == dk::struct_type || this.decls.kinds.p[decl] == dk::union_type) && this.decls.has(decl, df::foreign) { + return this.decls.kinds.p[decl] == dk::union_type + ? "A union of an `extern module` is C's: every field begins where it does, and nothing says which it holds." + : "A struct of an `extern module` is laid out as C lays it out."; + } + return this.compiler_names(decl); +} + +#! Why renaming a declaration would lose it to the compiler, which finds some by +#! their names: the declarations of std it knows, as the types it makes values +#! of and the traits whose methods it calls, the methods those traits ask for, +#! the methods its arithmetic operators call, where a program begins, and the +#! runtime an executable calls into. +#! @param this The checker. +#! @param decl The declaration. +#! @returns Why it cannot be renamed, or empty text. +def checker::compiler_names(&mut this, decl: u32): strview { + for &each in this.known { + if each.value == decl && decl != 0 { + return match this.decls.kinds.p[decl] { + dk::trait_type => "The compiler finds it by its name, as a trait whose methods it calls or whose meaning it decides.", + dk::struct_type, dk::union_type, dk::enum_type, dk::alias_type => "The compiler finds it by its name, as a type it makes values of.", + else => "The compiler finds it by its name." + }; + } + } + if this.in_runtime(decl) && this.decls.kinds.p[decl] != dk::field { + return "The compiler calls into `runtime` by name."; + } + if this.decls.kinds.p[decl] == dk::function && this.decls.owners.p[decl] == 0 && this.decls.modules.p[decl] == 0 + && this.decls.names.p[decl] == word::main { + return "A program begins at the function named `main`."; + } + + # A method the compiler calls for every type implementing one of its traits. + if this.decls.kinds.p[decl] == dk::function && this.decls.owners.p[decl] != 0 { + var traits := this.traits_asking(decl); + for &trait_decl in traits { + for &each in this.known { + if each.value == trait_decl { + return "The compiler calls it by its name, for every type implementing the trait asking for it."; + } + } + } + } + + # A method an operator calls, which a type has the operator by declaring: `add` + # for `+`, and the rest, taking the other operand, and `negate` for `-x` and + # `bit_not` for `~x`. + if this.decls.kinds.p[decl] == dk::function && this.decls.has(decl, df::method) { + val name: u32 = this.decls.names.p[decl]; + val taken := this.types.part_count(this.decls.types.p[decl]); + if name == word::negate && taken == 1 { + return "The compiler calls it by its name, as the method `-x` is."; + } + if name == word::bit_not && taken == 1 { + return "The compiler calls it by its name, as the method `~x` is."; + } + if taken == 2 && (name == word::add || name == word::sub || name == word::mul + || name == word::div || name == word::rem || name == word::bit_and + || name == word::bit_or || name == word::bit_xor || name == word::shift_left + || name == word::shift_right) { + return "The compiler calls it by its name, as the method an operator is, as `+` is `add`."; + } + } + return ""; +} + +#! Whether a declaration is of the module `runtime`, which only an executable +#! holds. +#! @param this The checker. +#! @param decl The declaration. +#! @returns Whether it is. +def checker::in_runtime(&this, decl: u32): bool { + val home: u32 = this.decls.modules.p[decl]; + return home != 0 && this.modules.parents[home] == 0 && this.names.text(this.modules.names[home]) == "runtime"; +} + +#! The traits that ask for a method: its own type's, where that is a trait, and +#! those its type implements, or those compose, with a member of its name. +#! @param this The checker. +#! @param method The method. +#! @returns The traits' declarations. +def checker::traits_asking(&mut this, method: u32): vector { + var made := vector::::new(); + val owner: u32 = this.decls.owners.p[method]; + return made if owner == 0; + if this.decls.kinds.p[owner] == dk::trait_type { + made.append(owner); + } + this.add_asking(owner, this.decls.names.p[method], &mut made, 0); + return made; +} + +#! Adds the traits a type implements, or a trait composes, and those they +#! compose, that have a member of the name. +#! @param this The checker. +#! @param decl The type or trait. +#! @param name The ID of the name. +#! @param into The traits found so far. +#! @param depth How deeply composition has been followed. +def checker::add_asking(&mut this, decl: u32, name: u32, into: &mut vector, depth: u32): void { + return if depth > 16; + val kind: dk = this.decls.kinds.p[decl]; + return if kind != dk::struct_type && kind != dk::union_type && kind != dk::trait_type; + val run := this.composed_of(decl); + for i in 0..this.decls.list_length(run) { + val trait_decl := this.types.first_of(this.decls.list_at(run, i as u32)); + continue if trait_decl == 0 || this.decls.kinds.p[trait_decl] != dk::trait_type; + if this.decls.member(trait_decl, name) != 0 { + var known := false; + for &each in into { + known = known || each == trait_decl; + } + if !known { + into.append(trait_decl); + } + } + this.add_asking(trait_decl, name, into, depth + 1); + } +} + +#! Whether a trait is another, or composes it. +#! @param this The checker. +#! @param trait_decl The trait. +#! @param target The trait it may compose. +#! @param depth How deeply composition has been followed. +#! @returns Whether it does. +def checker::trait_composes(&mut this, trait_decl: u32, target: u32, depth: u32): bool { + return true if trait_decl == target; + return false if depth > 16 || this.decls.kinds.p[trait_decl] != dk::trait_type; + val run := this.composed_of(trait_decl); + for i in 0..this.decls.list_length(run) { + return true if this.trait_composes(this.types.first_of(this.decls.list_at(run, i as u32)), target, depth + 1); + } + return false; +} + +#! Everywhere the name at the offset of the file refers to is written, its +#! declaration among them, in every file of the program, ordered by file and +#! then by where in it they are. Each place is written with the very text of +#! the name, so an editor renames it by replacing each. +#! @param this The checker. +#! @param file The file. +#! @param offset The byte of its text. +#! @returns The places, which are none where no name the checker resolved is +#! there. +pub def checker::references(&mut this, file: u32, offset: u32): vector { + var found := vector::::new(); + var strays := vector::::new(); + this.refer_all(file, offset, &mut found, &mut strays); + return found; +} + +#! The places the name at the offset of the file is written but the checker left +#! unresolved, as in a branch of `when` for another target, which may refer to +#! the same thing. A local is sought only within the declaration holding it. +#! @param this The checker. +#! @param file The file. +#! @param offset The byte of its text. +#! @returns The places, ordered as `references` orders them. +pub def checker::unresolved(&mut this, file: u32, offset: u32): vector { + var found := vector::::new(); + var strays := vector::::new(); + this.refer_all(file, offset, &mut found, &mut strays); + return strays; +} + +#! Everywhere what the name at a place refers to is written, and where its text +#! is written but unresolved, as `references` and `unresolved` give them. +#! @param this The checker. +#! @param file The file. +#! @param offset The byte of its text. +#! @param found Where the places it is written are put. +#! @param strays Where the places it is written unresolved are put. +pub def checker::refer_all(&mut this, file: u32, offset: u32, found: &mut vector, strays: &mut vector): void { + var meant := checker::meant {}; + val named := this.seek_name(file, offset, &mut meant); + return if named == 0; + var declared := spot {}; + return if !this.declared_at(&meant, &mut declared); + + val name: u32 = this.units[declared.file].syntax.token_names[this.token_at(declared.file, declared.offset)]; + var sought := vector::::new(); + sought.append(meant); + this.widen(&meant, &mut sought); + + # The top-level declaration holding a local, which alone may name it. + var home_top: u32 = 0; + if meant.local != 0 { + home_top = this.top_holding(meant.file, meant.local); + } + + for each in 0..this.units.length { + val at := each as u32; + continue if meant.local != 0 && at != meant.file; + val syntax := &this.units[at].syntax; + val asked := this.begin_query(at); + val walked := &asked.walked; + for &node in walked.order { + val token: u32 = syntax.node_tokens[node]; + continue if syntax.token_names[token] != name || syntax.token_kinds[token] != tk::name; + continue if home_top != 0 && this.top_of(walked, node) != home_top; + val held := this.meaning_of(node, walked, &asked.decls); + var hit := false; + for &want in sought { + hit = hit || held.same(&want); + } + if hit { + this.add_place(found, this.spot_of(at, token)); + if syntax.node_kinds[node] == nk::type_param || syntax.node_kinds[node] == nk::const_param { + this.refer_bounds(at, node, found); + } + } else if !held.found() { + val kind := syntax.node_kinds[node]; + val unnamed_type := (kind == nk::type_name && syntax.node_lefts[node] == 0) || kind == nk::segment; + if kind == nk::name || kind == nk::member || unnamed_type + || (kind == nk::field_init && (syntax.flags_at(node) & nf::named as u32) != 0) { + this.add_place(strays, this.spot_of(at, token)); + } + } + } + } + this.sort_places(found); + this.sort_places(strays); +} + +#! Adds a place, once. +#! @param this The checker. +#! @param into The places. +#! @param place The place. +def checker::add_place(&this, into: &mut vector, place: spot): void { + for &each in into { + return if each.file == place.file && each.offset == place.offset; + } + into.append(place); +} + +#! Orders places by the path of their file, then where in it they are, so the +#! places of a name come in the same order however the files were given. +#! @param this The checker. +#! @param places The places. +def checker::sort_places(&this, places: &mut vector): void { + places.sort_by(def(a: &spot, b: &spot): bool { return this.place_before(a, b); }); +} + +#! Whether one place comes before another. +#! @param this The checker. +#! @param a The one place. +#! @param b The other. +#! @returns Whether `a` comes first. +def checker::place_before(&this, a: &spot, b: &spot): bool { + if a.file != b.file { + return this.units[a.file].source.path.compare(this.units[b.file].source.path) < 0; + } + return a.offset < b.offset; +} + +#! The top-level declaration holding a node of a file. +#! @param this The checker. +#! @param file The file. +#! @param node The node. +#! @returns The top-level declaration's node. +def checker::top_holding(&this, file: u32, node: u32): u32 { + val walked := this.tree_of(file); + return this.top_of(&walked, node); +} + +#! The top-level node holding a node, which is the node itself where the +#! document holds it. +#! @param this The checker. +#! @param walked The file's tree. +#! @param node The node. +#! @returns The top-level node. +def checker::top_of(&this, walked: &tree_walk, node: u32): u32 { + var at := node; + var steps := 0; + while steps < 4096 { + val parent: u32 = walked.parents[at]; + return at if parent == 0 || walked.parents[parent] == 0; + at = parent; + steps++; + } + return at; +} + +#! A `where` clause names the type parameters it bounds, as `T` of +#! `where T: show`, though no node holds the name there, since the bounds are +#! given to the parameter. So the tokens after the parameter are read up to the +#! body, or the `;` ending the declaration, for each name that follows `where` +#! or `,` and is followed by `:`. +#! @param this The checker. +#! @param file The file. +#! @param param The `type_param` node. +#! @param into Where the places are put. +def checker::refer_bounds(&this, file: u32, param: u32, into: &mut vector): void { + val syntax := &this.units[file].syntax; + val name: u32 = syntax.token_names[syntax.node_tokens[param]]; + var depth := 0; + var clause := false; + var at: u32 = syntax.node_tokens[param] + 1; + while at as u64 + 1 < syntax.token_count { + val kind := syntax.token_kinds[at]; + if kind == tk::lparen || kind == tk::lbracket || kind == tk::less { + depth++; + } else if (kind == tk::rparen || kind == tk::rbracket || kind == tk::more) && depth > 0 { + depth--; + } + break if depth == 0 && (kind == tk::lbrace || kind == tk::semicolon); + if depth == 0 && kind == tk::kw_where { + clause = true; + } else if clause && kind == tk::name && syntax.token_names[at] == name && syntax.token_kinds[at + 1] == tk::colon { + val prior := syntax.token_kinds[at - 1]; + if prior == tk::kw_where || prior == tk::comma { + this.add_place(into, this.spot_of(file, at)); + } + } + at++; + } +} + +#! A method a trait asks for is one name with each method implementing it, since +#! a type implements a trait by the names of its methods: renaming one alone +#! would leave a type no longer implementing a trait it declares. So a trait's +#! method is sought with the method of the name of every type declaring the +#! trait, directly or through one composing it, and a method of a type with the +#! members of the traits its type declares that ask for it, and so with theirs. +#! @param this The checker. +#! @param meant What the name refers to. +#! @param sought What is sought, which the rest are added to. +def checker::widen(&mut this, meant: &checker::meant, sought: &mut vector): void { + val decl := meant.decl; + return if decl == 0 || this.decls.kinds.p[decl] != dk::function || this.decls.owners.p[decl] == 0; + var traits := this.traits_asking(decl); + return if traits.length == 0; + + val name: u32 = this.decls.names.p[decl]; + this.add_family(this.decls.owners.p[decl], name, sought); + for &trait_decl in traits { + this.add_family(trait_decl, name, sought); + for id in 1..this.decls.count { + val type_decl := id as u32; + val kind: dk = this.decls.kinds.p[type_decl]; + continue if kind != dk::struct_type && kind != dk::union_type && kind != dk::trait_type; + val run := this.composed_of(type_decl); + for i in 0..this.decls.list_length(run) { + val named := this.types.first_of(this.decls.list_at(run, i as u32)); + if this.trait_composes(named, trait_decl, 0) { + this.add_family(type_decl, name, sought); + break; + } + } + } + } +} + +#! Adds each member of the name a type has, which overloads of a trait's method +#! are renamed together, as `at(&this)` and `at(&mut this)`. +#! @param this The checker. +#! @param owner The type. +#! @param name The ID of the name. +#! @param sought What is sought. +def checker::add_family(&mut this, owner: u32, name: u32, sought: &mut vector): void { + var walk := this.decls.walk_overloads(this.decls.member(owner, name), 256); + while true { + val at := walk.next(); + break if at == 0; + val each := checker::meant { decl = this.standing_for(at) }; + var known := false; + for &held in sought { + known = known || held.same(&each); + } + if !known { + sought.append(each); + } + } +} diff --git a/analyzer/queries/programs.sakura b/analyzer/queries/programs.sakura new file mode 100644 index 00000000..6bffde56 --- /dev/null +++ b/analyzer/queries/programs.sakura @@ -0,0 +1,80 @@ +#! @file programs.sakura +#! @author John Christman (sorakatadzuma@gmail.com) +#! @copyright Malunal Studios, LLC. +#! @license MIT +#! +#! Contains what says which program a file belongs to. A file declaring `main` +#! begins a program, which holds it and every file declaring none, so an +#! editor whose workspace holds several, as a program and the program testing +#! it, checks one of them at a time. + +module sakura::analyzer; + + +#! Whether a parsed file declares `main` outside any module, beginning a +#! program. A `main` in any branch of a `when` counts, whatever the target, and +#! one after a `module` is that module's and does not. A file whose syntax has +#! mistakes counts by what parsed. +#! @param this The file's syntax. +#! @param root Its `document` node. +#! @param main The ID of the name `main`. +#! @returns Whether it does. +pub def syntax::declares_main(&this, root: u32, main: u32): bool { + var found := false; + this.main_within(this.node_lefts[root], main, &mut found); + return found; +} + +#! Whether a run of top-level declarations declares `main` before a `module`. +#! @param this The file's syntax. +#! @param run The run. +#! @param main The ID of the name `main`. +#! @param found Where whether one does is written. +#! @returns Whether a `module` ended the run, so nothing after it counts. +def syntax::main_within(&this, run: u32, main: u32, found: &mut bool): bool { + for &node in this.run_view(run) { + match this.node_kinds[node] { + nk::module_decl, nk::extern_module => return true; + nk::function => { + if this.token_names[this.node_tokens[node]] == main && this.record_at(node, function_slot::receiver) == 0 { + found = true; + } + } + nk::when_block => { + # Each branch is a block of declarations, or another `when`. + var branch := this.record_at(node, if_slot::then); + var other := this.record_at(node, if_slot::other); + var steps := 0; + while steps < 64 { + steps++; + if branch != 0 && this.node_kinds[branch] == nk::block { + return true if this.main_within(this.node_lefts[branch], main, found); + } + break if other == 0; + if this.node_kinds[other] == nk::when_block { + branch = this.record_at(other, if_slot::then); + other = this.record_at(other, if_slot::other); + } else { + branch = other; + other = 0; + } + } + } + else => {} + } + } + return false; +} + +#! Whether any note made of a file is a mistake of its syntax, which the lexer +#! or the parser made, so what the checker says of it would mislead. +#! @param this The note. +#! @returns Whether it is. +pub val note::is_syntax: bool { + get { + return match this.code { + ec::syntax, ec::token, ec::expr, ec::ident, ec::kind, ec::decl, ec::escape, ec::char, ec::block => true, + else => false + }; + } +} diff --git a/analyzer/queries/signatures.sakura b/analyzer/queries/signatures.sakura new file mode 100644 index 00000000..30724d16 --- /dev/null +++ b/analyzer/queries/signatures.sakura @@ -0,0 +1,829 @@ +#! @file signatures.sakura +#! @author John Christman (sorakatadzuma@gmail.com) +#! @copyright Malunal Studios, LLC. +#! @license MIT +#! +#! Contains how an editor is shown what a name is: the signature it is declared +#! with, with the types the checker gave it, as `def str::trim(this: &str): str` +#! or `val count: int`, and the documentation comment written for it. + +module sakura::analyzer; + + +#! The most members a type's signature lists. +const checker::listed: u32 = 48; + +#! How a declaration is written, with the types the checker gave it, as +#! `pub def vec2::length(this: &vec2): float`. A struct, union, trait, or enum +#! lists its members. +#! @param this The checker. +#! @param decl The declaration. +#! @returns The signature. +pub def checker::signature_of(&mut this, decl: u32): string { + var out := string::new(nothing {}); + this.resolve(decl); + val kind: dk = this.decls.kinds.p[decl]; + + # What another module reaches is written as it was declared, `pub` and all. + if this.decls.has(decl, df::exported) && kind != dk::enum_member && kind != dk::type_param && kind != dk::builtin { + out.append("pub "); + } + + match kind { + dk::function => { + if this.decls.has(decl, df::accessor) { + this.property_text(this.decls.owners.p[decl], &mut out); + } else { + this.function_text(decl, true, &mut out); + } + } + dk::property => this.property_text(decl, &mut out); + dk::field => this.field_text(decl, this.decls.names.p[decl], &mut out); + dk::enum_member => { + this.owner_prefix(decl, &mut out); + out.append(this.decl_text(decl)); + out.append(" = "); + this.value_text(decl, &mut out); + } + dk::variable, dk::attribute => { + out.append(this.decls.has(decl, df::constant) ? "const " : this.decls.has(decl, df::mutable) ? "var " : "val "); + this.owner_prefix(decl, &mut out); + out.append(this.decl_text(decl)); + out.append(": "); + this.type_text(this.decls.types.p[decl], &mut out); + } + dk::struct_type, dk::union_type => this.aggregate_text(decl, &mut out); + dk::trait_type => this.trait_text(decl, &mut out); + dk::enum_type => this.enum_text(decl, &mut out); + dk::alias_type => { + val syntax := &this.units[this.decls.files.p[decl]].syntax; + val node: u32 = this.decls.nodes.p[decl]; + out.append("type "); + this.type_name_text(decl, &mut out); + this.generics_text(this.decls.files.p[decl], syntax.record_at(node, alias_slot::type_params), &mut out); + out.append(" = "); + this.type_text(this.decls.targets.p[decl], &mut out); + this.where_text(this.decls.files.p[decl], syntax.record_at(node, alias_slot::type_params), &mut out); + } + dk::type_param => this.type_param_text(decl, &mut out); + dk::assoc_type => { + out.append("type "); + out.append(this.decl_text(decl)); + val bounds: u32 = this.decls.children.p[decl]; + for i in 0..this.decls.list_length(bounds) { + out.append(i == 0 ? ": " : " + "); + this.type_text(this.decls.list_at(bounds, i as u32), &mut out); + } + } + dk::builtin => { + # A built-in type is written as notes spell it, as `int` for `i64`. + out.append("type "); + this.type_text(this.decls.types.p[decl], &mut out); + } + else => { + out.append("type "); + out.append(this.decl_text(decl)); + } + } + return out; +} + +#! The name a local is known by, as its declaration writes it, or of a parameter +#! an accessor implies, whose token is the `get` or `set`, `this` or `value`. +#! @param this The checker. +#! @param file The file. +#! @param node The node declaring it. +#! @returns The name. +pub def checker::local_text(&mut this, file: u32, node: u32): strview { + val syntax := &this.units[file].syntax; + val text := this.token_text(file, syntax.node_tokens[node]); + return text if syntax.node_kinds[node] != nk::param || (syntax.flags_at(node) & nf::implied as u32) == 0; + return text == "set" && (syntax.flags_at(node) & nf::mutable as u32) == 0 ? "value" : "this"; +} + +#! How a local is written, with the type the checker gave it, as `val n: int`, +#! or `n: int` for a parameter. +#! @param this The checker. +#! @param file The file. +#! @param node The node declaring it. +#! @returns The signature. +pub def checker::local_signature(&mut this, file: u32, node: u32): string { + var out := string::new(nothing {}); + val syntax := &this.units[file].syntax; + val saved := this.at; + this.use_table(this.units[file].table); + var kind := this.type_at(node); + val kind_of := syntax.node_kinds[node]; + val name := this.local_text(file, node); + + if kind_of == nk::param { + val flags := syntax.flags_at(node); + # A parameter of a function without a body is no local, so its type is the + # function's. + if !this.has_flag(node, rf::local) { + kind = this.param_type(file, node); + } + out.append(name); + out.append(": "); + if (flags & nf::variadic as u32) != 0 && this.types.kind_of(kind) == ty::named && this.types.part_count(kind) == 1 { + this.type_text(this.types.part_at(kind, 0), &mut out); + out.append("..."); + } else { + this.type_text(kind, &mut out); + } + this.at = saved; + return out; + } + + val flags := kind_of == nk::variable ? syntax.flags_at(node) : 0; + if (flags & nf::constant as u32) != 0 { + out.append("const "); + } else { + out.append(this.has_flag(node, rf::mutable) || (flags & nf::mutable as u32) != 0 ? "var " : "val "); + } + out.append(name); + out.append(": "); + this.type_text(kind, &mut out); + this.at = saved; + return out; +} + +#! The type of a parameter of a function, as its function's type gives it. +#! @param this The checker. +#! @param file The file. +#! @param node The `param` node. +#! @returns Its type, or the error type. +def checker::param_type(&mut this, file: u32, node: u32): u32 { + # Resolving a function may make more declarations of the file, but nothing is + # read of those it lists once one is resolved. + for &id in this.decls.by_file.of(file) { + continue if this.decls.kinds.p[id] != dk::function; + val syntax := &this.units[file].syntax; + val owner: u32 = this.decls.nodes.p[id]; + val run := this.decls.has(id, df::accessor) ? syntax.node_lefts[owner] : syntax.record_at(owner, function_slot::params); + for i in 0..syntax.run_length(run) { + continue if syntax.run_at(run, i as u32) != node; + this.resolve(id); + val kind: u32 = this.decls.types.p[id]; + return i < this.types.part_count(kind) ? this.types.part_at(kind, i as u32) : bt::error; + } + } + return bt::error; +} + +#! How a module is written, as `module std::io`. +#! @param this The checker. +#! @param id The module. +#! @returns The signature. +pub def checker::module_signature(&this, id: u32): string { + var out := string::from("module ", nothing {}); + this.module_text(id, &mut out); + return out; +} + +#! Writes the path of a module, as `std::io`. +#! @param this The checker. +#! @param id The module. +#! @param out Where it is written. +pub def checker::module_text(&this, id: u32, out: &mut string): void { + return if id == 0; + val parent: u32 = this.modules.parents[id]; + if parent != 0 { + this.module_text(parent, out); + out.append("::"); + } + out.append(this.names.text(this.modules.names[id])); +} + +#! Writes a type as notes spell it, as `&mut list`. +#! @param this The checker. +#! @param kind The type. +#! @param out Where it is written. +def checker::type_text(&this, kind: u32, out: &mut string): void { + if kind == 0 { + out.append("?"); + return; + } + val described := this.describe(kind); + out.append(described.view()); +} + +#! Writes the type a member is declared through, as `rect::` of `rect::area`. +#! @param this The checker. +#! @param decl The member. +#! @param out Where it is written. +def checker::owner_prefix(&this, decl: u32, out: &mut string): void { + val owner: u32 = this.decls.owners.p[decl]; + return if owner == 0; + out.append(this.decl_text(owner)); + out.append("::"); +} + +#! Writes the value of a member of an enum. +#! @param this The checker. +#! @param decl The member. +#! @param out Where it is written. +def checker::value_text(&this, decl: u32, out: &mut string): void { + var held := constant {}; + if !this.decl_value(decl, &mut held) { + out.append("?"); + return; + } + if held.negative { + out.append("-"); + } + val text := $"{held.magnitude}"; + out.append(text.view()); +} + +#! Writes a function as it is declared: `def`, its name, after the type it is +#! declared through where `owner` says, its own type parameters, its +#! parameters with the types the checker gave them, and what it gives. +#! @param this The checker. +#! @param decl The function. +#! @param owner Whether the type it is declared through is written. +#! @param out Where it is written. +def checker::function_text(&mut this, decl: u32, owner: bool, out: &mut string): void { + this.instance_text_of(decl, owner, 0, out); +} + +#! Writes a function as `function_text` does, or where it is given an instance +#! of it, as the instance is: its type arguments in place of its own type +#! parameters, and its parameters and result of the types they give, as +#! `def max(a: int, b: int): int`. +#! @param this The checker. +#! @param decl The function. +#! @param owner Whether the type it is declared through is written. +#! @param made One more than the instance, or 0. +#! @param out Where it is written. +def checker::instance_text_of(&mut this, decl: u32, owner: bool, made: u32, out: &mut string): void { + val file: u32 = this.decls.files.p[decl]; + val syntax := &this.units[file].syntax; + val node: u32 = this.decls.nodes.p[decl]; + if this.decls.has(decl, df::optional) { + out.append("@optional "); + } + if this.decls.has(decl, df::intrinsic) { + out.append("@intrinsic "); + } else if this.decls.has(decl, df::constant) { + out.append("const "); + } + out.append("def "); + if owner { + this.owner_prefix(decl, out); + } + out.append(this.decl_text(decl)); + var kind: u32 = this.decls.types.p[decl]; + if made != 0 { + # The arguments of its own type parameters, which follow those of the type + # it is declared through, written as notes write them. + val held: instance = this.instances[made - 1]; + kind = held.kind; + val own := this.own_param_count(decl); + val count := this.types.part_count(held.args); + if own != 0 && own <= count { + val parts := this.types.parts_view(held.args); + out.append("<"); + this.describe_args(span::::over(parts.data + (count - own), own as u64), out); + out.append(">"); + } + } else { + this.generics_text(file, syntax.record_at(node, function_slot::type_params), out); + } + + out.append("("); + val params := syntax.record_at(node, function_slot::params); + val count := syntax.run_length(params); + for i in 0..count { + if i != 0 { + out.append(", "); + } + val param := syntax.run_at(params, i as u32); + out.append(this.token_text(file, syntax.node_tokens[param])); + out.append(": "); + val held: u32 = kind != 0 && i < this.types.part_count(kind) ? this.types.part_at(kind, i as u32) : 0; + this.type_text(held, out); + # A pack's type is already written as spread, as `Ts...`. + if i as u32 + 1 == count && this.decls.has(decl, df::variadic) && held != 0 && !this.types.is_open_pack(held) { + out.append("..."); + } + } + out.append("): "); + this.type_text(kind != 0 ? this.types.first_of(kind) : 0, out); + if made == 0 { + this.where_text(file, syntax.record_at(node, function_slot::type_params), out); + } +} + +#! Writes a property as it is declared rather than as either of its accessors: +#! `val` where it only reads, `var` where it also writes, and its type. +#! @param this The checker. +#! @param property The property. +#! @param out Where it is written. +def checker::property_text(&mut this, property: u32, out: &mut string): void { + this.resolve(property); + var intrinsic := this.decls.has(property, df::intrinsic); + val run: u32 = this.decls.children.p[property]; + for &each in this.decls.list_view(run) { + intrinsic = intrinsic || this.decls.has(each, df::intrinsic); + } + if intrinsic { + out.append("@intrinsic "); + } + out.append(this.property_setter(property) != 0 ? "var " : "val "); + this.owner_prefix(property, out); + out.append(this.decl_text(property)); + out.append(": "); + this.type_text(this.decls.types.p[property], out); +} + +#! Writes a field as it is declared, by the name it is reached by, as `var x: int` +#! or `val base: ...pair`. +#! @param this The checker. +#! @param field The field. +#! @param name The ID of the name it is reached by. +#! @param out Where it is written. +def checker::field_text(&mut this, field: u32, name: u32, out: &mut string): void { + this.resolve(field); + out.append(this.decls.has(field, df::mutable) ? "var " : "val "); + out.append(this.names.text(name)); + out.append(": "); + if this.is_spread(field) { + out.append("..."); + } + this.type_text(this.decls.types.p[field], out); +} + +#! Writes the name a type is declared with, after the type it is declared +#! through as that is written, as `list::iter`. +#! @param this The checker. +#! @param decl The type. +#! @param out Where it is written. +def checker::type_name_text(&this, decl: u32, out: &mut string): void { + val file: u32 = this.decls.files.p[decl]; + val node: u32 = this.decls.nodes.p[decl]; + val syntax := &this.units[file].syntax; + val receiver := node == 0 ? 0 : syntax.record_at(node, decl_slot::receiver); + if receiver != 0 { + val run: u32 = syntax.node_lefts[receiver]; + val count := run == 0 ? 1 : syntax.run_length(run); + for i in 0..count { + val segment := run == 0 ? receiver : syntax.run_at(run, i as u32); + out.append(this.token_text(file, syntax.node_tokens[segment])); + this.generics_text(file, run == 0 ? 0 : syntax.node_lefts[segment], out); + out.append("::"); + } + } + out.append(this.decl_text(decl)); +} + +#! Writes the names of a run of type parameters, as ``, or nothing where +#! the run is empty. +#! @param this The checker. +#! @param file The file. +#! @param run The run of `type_param` nodes. +#! @param out Where it is written. +def checker::generics_text(&this, file: u32, run: u32, out: &mut string): void { + val syntax := &this.units[file].syntax; + return if run == 0 || syntax.run_length(run) == 0; + out.append("<"); + for i in 0..syntax.run_length(run) { + if i != 0 { + out.append(", "); + } + # A pattern parameter is written whole, as `def(Ts...): R` or `L[N]`. + val param := syntax.run_at(run, i as u32); + if syntax.node_kinds[param] == nk::type_pattern || syntax.node_kinds[param] == nk::array_pattern { + var held := this.written(file, param); + out.append(held.view()); + } else { + out.append(this.token_text(file, syntax.node_tokens[param])); + } + } + out.append(">"); +} + +#! Writes the `where` clause bounding a run of type parameters, as +#! ` where T: show + equatable`, or nothing where none is bounded. +#! @param this The checker. +#! @param file The file. +#! @param run The run of `type_param` nodes. +#! @param out Where it is written. +def checker::where_text(&this, file: u32, run: u32, out: &mut string): void { + val syntax := &this.units[file].syntax; + return if run == 0; + var first := true; + for &each in syntax.run_view(run) { + var param := each; + continue if syntax.node_kinds[param] == nk::type_pattern; + # An array pattern's element is bounded as a type parameter is. + if syntax.node_kinds[param] == nk::array_pattern { + param = syntax.node_lefts[param]; + } + val bounds: u32 = syntax.node_lefts[param]; + continue if bounds == 0 || syntax.run_length(bounds) == 0; + out.append(first ? " where " : ", "); + this.param_text(file, param, out); + first = false; + } +} + +#! Writes a type parameter as it is declared, with its bounds, as +#! `T: show + equatable`, `Ts...`, or `N: u64`. +#! @param this The checker. +#! @param file The file. +#! @param param The `type_param` or `const_param` node. +#! @param out Where it is written. +def checker::param_text(&this, file: u32, param: u32, out: &mut string): void { + val syntax := &this.units[file].syntax; + out.append(this.token_text(file, syntax.node_tokens[param])); + if syntax.node_kinds[param] == nk::type_param && (syntax.node_rights[param] & nf::packed as u32) != 0 { + out.append("..."); + } + var joined := ": "; + if syntax.node_kinds[param] == nk::const_param && syntax.node_rights[param] != 0 { + out.append(": "); + var held := this.written(file, syntax.node_rights[param]); + out.append(held.view()); + joined = " + "; + } else if syntax.node_kinds[param] == nk::const_param { + # The length an array pattern names, as `N` of `L[N]`. + out.append(": u64"); + joined = " + "; + } + val bounds: u32 = syntax.node_lefts[param]; + for i in 0..(bounds == 0 ? 0 : syntax.run_length(bounds)) { + out.append(i == 0 ? joined : " + "); + var held := this.written(file, syntax.run_at(bounds, i as u32)); + out.append(held.view()); + } +} + +#! Writes a type parameter, as `type parameter T: show`, or a constant one, as +#! `constant parameter N: u64`. +#! @param this The checker. +#! @param decl The type parameter. +#! @param out Where it is written. +def checker::type_param_text(&this, decl: u32, out: &mut string): void { + val file: u32 = this.decls.files.p[decl]; + val node: u32 = this.decls.nodes.p[decl]; + val syntax := &this.units[file].syntax; + out.append(this.decls.has(decl, df::valued) ? "constant parameter " : "type parameter "); + if node != 0 && (syntax.node_kinds[node] == nk::type_param || syntax.node_kinds[node] == nk::const_param) { + this.param_text(file, node, out); + } else { + out.append(this.decl_text(decl)); + } +} + +#! Writes the traits a type implements, or a trait composes, as they are +#! written, as `: show, equatable`. +#! @param this The checker. +#! @param decl The type. +#! @param out Where it is written. +def checker::traits_text(&this, decl: u32, out: &mut string): void { + val file: u32 = this.decls.files.p[decl]; + val node: u32 = this.decls.nodes.p[decl]; + val syntax := &this.units[file].syntax; + val run := node == 0 ? 0 : syntax.record_at(node, aggregate_slot::traits); + for i in 0..(run == 0 ? 0 : syntax.run_length(run)) { + out.append(i == 0 ? ": " : ", "); + var held := this.written(file, syntax.run_at(run, i as u32)); + out.append(held.view()); + } +} + +#! Writes a struct or union with its fields. +#! @param this The checker. +#! @param decl The type. +#! @param out Where it is written. +def checker::aggregate_text(&mut this, decl: u32, out: &mut string): void { + val file: u32 = this.decls.files.p[decl]; + val node: u32 = this.decls.nodes.p[decl]; + val syntax := &this.units[file].syntax; + val union_type := this.decls.kinds.p[decl] == dk::union_type; + out.append(union_type ? "union " : "struct "); + this.type_name_text(decl, out); + this.generics_text(file, syntax.record_at(node, aggregate_slot::type_params), out); + this.traits_text(decl, out); + this.where_text(file, syntax.record_at(node, aggregate_slot::type_params), out); + + out.append(" {"); + var listed: u32 = 0; + val run: u32 = this.decls.children.p[decl]; + for i in 0..this.decls.list_length(run) { + val field := this.decls.list_at(run, i as u32); + continue if this.decls.kinds.p[field] != dk::field; + break if listed == checker::listed; + out.append("\n "); + if this.decls.has(field, df::exported) { + out.append("pub "); + } + this.field_text(field, this.decls.names.p[field], out); + out.append(";"); + listed++; + } + out.append(listed != 0 ? "\n}" : "}"); +} + +#! Writes a trait with the methods it asks for. +#! @param this The checker. +#! @param decl The trait. +#! @param out Where it is written. +def checker::trait_text(&mut this, decl: u32, out: &mut string): void { + out.append("trait "); + this.type_name_text(decl, out); + val file: u32 = this.decls.files.p[decl]; + val node: u32 = this.decls.nodes.p[decl]; + this.generics_text(file, this.units[file].syntax.record_at(node, aggregate_slot::type_params), out); + this.traits_text(decl, out); + + out.append(" {"); + var listed: u32 = 0; + val run: u32 = this.decls.children.p[decl]; + for i in 0..this.decls.list_length(run) { + val member := this.decls.list_at(run, i as u32); + continue if this.decls.kinds.p[member] != dk::function; + break if listed == checker::listed; + this.resolve(member); + out.append("\n "); + this.function_text(member, false, out); + out.append(";"); + listed++; + } + out.append(listed != 0 ? "\n}" : "}"); +} + +#! Writes an enum with its members and their values. +#! @param this The checker. +#! @param decl The enum. +#! @param out Where it is written. +def checker::enum_text(&mut this, decl: u32, out: &mut string): void { + out.append("enum "); + this.type_name_text(decl, out); + out.append(": "); + this.type_text(this.decls.targets.p[decl], out); + + out.append(" {"); + var listed: u32 = 0; + val run: u32 = this.decls.children.p[decl]; + for i in 0..this.decls.list_length(run) { + val member := this.decls.list_at(run, i as u32); + continue if this.decls.kinds.p[member] != dk::enum_member; + break if listed == checker::listed; + this.resolve(member); + out.append("\n "); + out.append(this.decl_text(member)); + out.append(" = "); + this.value_text(member, out); + out.append(","); + listed++; + } + out.append(listed != 0 ? "\n}" : "}"); +} + +#! Writes the attributes written on a declaration, each on a line of its own as +#! it is written, as `@test`. +#! @param this The checker. +#! @param file The file. +#! @param node The declaration's node. +#! @param out Where they are written. +def checker::attributes_text(&this, file: u32, node: u32, out: &mut string): void { + val syntax := &this.units[file].syntax; + val run := match syntax.node_kinds[node] { + nk::function, nk::variable, nk::field, nk::property, nk::struct_decl, nk::union_decl, + nk::trait_decl, nk::assoc_type, nk::enumeration, nk::alias => syntax.record_at(node, decl_slot::attributes), + nk::enumerator => syntax.node_lefts[node], + else => 0 + }; + for i in 0..(run == 0 ? 0 : syntax.run_length(run)) { + var held := this.written(file, syntax.run_at(run, i as u32)); + out.append(held.view()); + out.append("\n"); + } +} + +#! The documentation comment of a declaration: the `#!` lines written on lines +#! of their own right above it, and a `#!` after it on its own line, without +#! their markers. A parameter or type parameter is described by its line of +#! its declaration's comment, `@param` or `@tparam`. +#! @param this The checker. +#! @param file The file. +#! @param node The node declaring it. +#! @param walked The file's tree, where it is at hand, which says what holds a +#! parameter. +#! @returns The comment, or empty text. +pub def checker::documentation_of(&this, file: u32, node: u32): string { + var made := string::new(nothing {}); + return made if node == 0; + val syntax := &this.units[file].syntax; + val kind := syntax.node_kinds[node]; + if kind == nk::param || kind == nk::type_param || kind == nk::const_param { + val owner := this.owner_of_param(file, node); + return made if owner == 0; + var whole := this.documentation_of(file, owner); + return this.tagged(whole.view(), kind == nk::param ? "param" : "tparam", this.token_text(file, syntax.node_tokens[node])); + } + + val text := this.units[file].source.make_lexeme(0, this.units[file].source.length); + val start: u32 = syntax.token_offsets[syntax.start_of(node)]; + var line := start; + while line > 0 && text[(line - 1) as u64] != '\n' { + line--; + } + + # The comment above a line is of the declaration it begins, as `def str::trim`, + # and not of the names declared after it on the line. + var leading := true; + for at in line..start { + val byte: u8 = text[at as u64]; + leading = leading && (byte == ' ' || byte == '\t' || byte == ':' || byte == '<' || byte == '>' || byte == ',' + || byte == '&' || byte == '_' || (byte >= 'a' && byte <= 'z') || (byte >= 'A' && byte <= 'Z') || (byte >= '0' && byte <= '9')); + } + + var lines := vector::::new(); + var above := line; + while leading && above > 0 && lines.length < 64 { + var previous := above - 1; + while previous > 0 && text[(previous - 1) as u64] != '\n' { + previous--; + } + var at := previous; + while at < above && (text[at as u64] == ' ' || text[at as u64] == '\t') { + at++; + } + break if above - at < 3 || text[at as u64] != '#' || text[(at + 1) as u64] != '!' || text[(at + 2) as u64] == '<'; + lines.append(this.comment_text(text, at + 2)); + above = previous; + } + var i := lines.length; + while i > 0 { + i--; + made.append(lines[i]); + made.append("\n"); + } + + # A `#!` after the declaration on its own line, outside any string there. + var quote: u8 = 0; + var at: u32 = syntax.token_offsets[syntax.node_tokens[node]] + syntax.token_length(syntax.node_tokens[node], this.names); + while (at as u64) < text.length && text[at as u64] != '\n' { + val byte: u8 = text[at as u64]; + if quote != 0 { + if byte == '\\' { + at++; + } else if byte == quote { + quote = 0; + } + } else if byte == '"' || byte == '\'' { + quote = byte; + } else if byte == '#' { + if at as u64 + 1 < text.length && text[(at + 1) as u64] == '!' { + val after := at as u64 + 2 < text.length && text[(at + 2) as u64] == '<' ? at + 3 : at + 2; + made.append(this.comment_text(text, after)); + made.append("\n"); + } + break; + } + at++; + } + + while made.length != 0 && made[made.length - 1] == '\n' { + made = string::from(made.substr(0, made.length - 1), nothing {}); + } + return made; +} + +#! The text of a comment from after its marker to the end of its line, with one +#! space after the marker and the spacing ending the line left out. +#! @param this The checker. +#! @param text The file's text. +#! @param from Where the text after the marker begins. +#! @returns The text. +def checker::comment_text(&this, text: strview, from: u32): strview { + var start := from as u64; + var stop := start; + while stop < text.length && text[stop] != '\n' { + stop++; + } + if start < stop && text[start] == ' ' { + start++; + } + while stop > start && (text[stop - 1] == '\r' || text[stop - 1] == ' ') { + stop--; + } + return text.substr(start, stop - start); +} + +#! What a documentation comment says of one of its parameters: the text after +#! `@param name`, or `@tparam name`, through the lines continuing it. +#! @param this The checker. +#! @param text The comment. +#! @param tag `param` or `tparam`. +#! @param name The parameter's name. +#! @returns The text, or empty text. +def checker::tagged(&this, text: strview, tag: strview, name: strview): string { + var made := string::new(nothing {}); + var within := false; + var line: u64 = 0; + while line < text.length { + var stop := line; + while stop < text.length && text[stop] != '\n' { + stop++; + } + var at := line; + while at < stop && (text[at] == ' ' || text[at] == '\t') { + at++; + } + if at < stop && (text[at] == '@' || text[at] == '\\') { + within = false; + if stop - at > tag.length && text.substr(at + 1, tag.length) == tag { + at += 1 + tag.length; + if at < stop && text[at] == '[' { + while at < stop && text[at] != ']' { + at++; + } + at++; + } + while at < stop && (text[at] == ' ' || text[at] == '\t') { + at++; + } + val word := at; + while at < stop && is_word_byte(text[at]) { + at++; + } + if text.substr(word, at - word) == name { + while at < stop && (text[at] == ' ' || text[at] == '\t') { + at++; + } + made.append(text.substr(at, stop - at)); + within = true; + } + } + } else if within && at < stop { + made.append(" "); + made.append(text.substr(at, stop - at)); + } + line = stop + 1; + } + return made; +} + +#! The node of the declaration a parameter or type parameter belongs to, whose +#! documentation describes it, or 0. +#! @param this The checker. +#! @param file The file. +#! @param node The `param`, `type_param`, or `const_param` node. +#! @returns The declaration's node, or 0. +def checker::owner_of_param(&this, file: u32, node: u32): u32 { + val syntax := &this.units[file].syntax; + for &id in this.decls.by_file.of(file) { + val owner: u32 = this.decls.nodes.p[id]; + continue if owner == 0; + match syntax.node_kinds[owner] { + nk::function => { + return owner if this.run_holds(syntax, syntax.record_at(owner, function_slot::params), node) + || this.run_holds(syntax, syntax.record_at(owner, function_slot::type_params), node) + || this.receiver_holds(syntax, syntax.record_at(owner, function_slot::receiver), node); + } + nk::struct_decl, nk::union_decl, nk::trait_decl, nk::alias => { + return owner if this.run_holds(syntax, syntax.record_at(owner, decl_slot::type_params), node); + } + nk::variable, nk::property => { + return owner if this.receiver_holds(syntax, syntax.record_at(owner, decl_slot::receiver), node); + } + else => {} + } + } + return 0; +} + +#! Whether a run of a syntax holds a node. +#! @param this The checker. +#! @param syntax The syntax. +#! @param run The run. +#! @param node The node. +#! @returns Whether it does. +def checker::run_holds(&this, syntax: &syntax, run: u32, node: u32): bool { + return false if run == 0; + for &each in syntax.run_view(run) { + return true if each == node; + } + return false; +} + +#! Whether the last segment of a receiver declares a type parameter, as `T` of +#! `def box::get`. +#! @param this The checker. +#! @param syntax The syntax. +#! @param receiver The receiver's `type_name` node, or 0. +#! @param node The type parameter's node. +#! @returns Whether it does. +def checker::receiver_holds(&this, syntax: &syntax, receiver: u32, node: u32): bool { + return false if receiver == 0; + val run: u32 = syntax.node_lefts[receiver]; + return false if run == 0; + for &each in syntax.run_view(run) { + return true if this.run_holds(syntax, syntax.node_lefts[each], node); + } + return false; +} diff --git a/analyzer/queries/symbols.sakura b/analyzer/queries/symbols.sakura new file mode 100644 index 00000000..0ae29060 --- /dev/null +++ b/analyzer/queries/symbols.sakura @@ -0,0 +1,628 @@ +#! @file symbols.sakura +#! @author John Christman (sorakatadzuma@gmail.com) +#! @copyright Malunal Studios, LLC. +#! @license MIT +#! +#! Contains what the queries an editor asks of a checked program share: what a +#! name is, as `symbol` says, where one is written, as a `spot`, the walk of a +#! file that finds what holds each node, and what the name a node writes +#! refers to. +#! +#! The queries read what checking recorded of each node, as the declaration a +#! name refers to and the type of each expression, together with the tables the +#! check built. They ask the checker nothing that reports, so a query never +#! adds a note. + +import std::containers; +module sakura::analyzer; + + +#! What a name is, as an editor offers it to complete and colours it. +pub enum symbol : u8 { + keyword, #! A keyword, as `def`. + namespace, #! A module. + function, #! A function, or a function declared through a type. + method, #! A method, which takes `this`. + variable, #! A variable, or a local. + constant, #! A constant, or a variable that is never written, declared outside any function. + parameter, #! A parameter. + field, #! A field, or a property. + struct_type, #! A struct or union. + trait_type, #! A trait. + enum_type, #! An enum. + enum_member, #! A member of an enum. + type_name, #! Any other type, as a built-in one or an alias. + type_param, #! A type parameter. +} + +#! Where a name is written: its file, and the bytes of its text it covers. +pub struct spot { + pub var file: u32; #! The index of the file. + pub var offset: u32; #! Where the name begins in the file's text. + pub var length: u32; #! How many bytes it covers. +} + +#! What a name refers to: a declaration, a local, or a module. +struct checker::meant { + var decl: u32; #! The declaration, or 0. + var file: u32; #! The file of the local. + var local: u32; #! The node declaring the local, as a `variable` or `param`, or 0. + var named_module: u32; #! The module, where `is_module` says it is one. + var is_module: bool; #! Whether it is a module. +} + +#! Whether a name refers to anything. +#! @param this What it refers to. +#! @returns Whether it does. +def checker::meant::found(&this): bool { + return this.decl != 0 || this.local != 0 || this.is_module; +} + +#! Whether two names refer to the same thing. +#! @param this What one refers to. +#! @param other What the other refers to. +#! @returns Whether they do. +def checker::meant::same(&this, other: &checker::meant): bool { + return this.decl == other.decl && this.local == other.local && this.file == other.file + && this.is_module == other.is_module && this.named_module == other.named_module; +} + +#! The nodes of a file a walk from its `document` meets, each before the nodes +#! it holds, and the node holding each. The nodes a reparse left behind are no +#! longer in the tree, and the walk never meets them. +struct tree_walk { + var order: vector; #! The nodes, in the order the walk meets them. + var parents: vector; #! The node holding each, by its index, or 0. +} + +#! The tree of the file, walked from its `document`. +#! @param this The checker. +#! @param file The file. +#! @returns The tree. +def checker::tree_of(&this, file: u32): tree_walk { + val syntax := &this.units[file].syntax; + var made := tree_walk { order = vector::::new(), parents = vector::::new() }; + made.parents.resize(syntax.node_count); + var todo := vector::::new(); + var held := vector::::new(); + todo.append(this.units[file].root); + while todo.length != 0 { + val at: u32 = todo.last(); + todo.truncate(); + made.order.append(at); + held.clear(); + syntax.children(at, &mut held); + var i := held.length; + while i > 0 { + i--; + val child: u32 = held[i]; + continue if child as u64 >= syntax.node_count || made.parents[child] != 0; + made.parents[child] = at; + todo.append(child); + } + } + return made; +} + +#! The token of the file whose text holds the offset, or the count of its +#! tokens where none does, as between two. +#! @param this The checker. +#! @param file The file. +#! @param offset The byte of its text. +#! @returns The token. +def checker::token_at(&this, file: u32, offset: u32): u32 { + val syntax := &this.units[file].syntax; + val count := syntax.token_count as u32; + # The token before the first beginning past the offset is the one that may + # hold it. + val after := syntax.token_offsets.view().upper_bound(&offset) as u32; + return count if after == 0; + val token := after - 1; + val start: u32 = syntax.token_offsets[token]; + return token if offset < start + syntax.token_length(token, this.names); + return count; +} + +#! Where the token is written. +#! @param this The checker. +#! @param file The file. +#! @param token The token. +#! @returns Its spot. +def checker::spot_of(&this, file: u32, token: u32): spot { + val syntax := &this.units[file].syntax; + return spot { file = file, offset = syntax.token_offsets[token], length = syntax.token_length(token, this.names) }; +} + +#! The text of a token of a file. +#! @param this The checker. +#! @param file The file. +#! @param token The token. +#! @returns The text, which views the file's source. +def checker::token_text(&this, file: u32, token: u32): strview { + val syntax := &this.units[file].syntax; + return this.units[file].source.make_lexeme(syntax.token_offsets[token], syntax.token_length(token, this.names)); +} + +#! The text a node of a file is written as, from its first token through its +#! last, with each run of spacing made one space, as `std::list`. +#! @param this The checker. +#! @param file The file. +#! @param node The node. +#! @returns The text. +def checker::written(&this, file: u32, node: u32): string { + val syntax := &this.units[file].syntax; + var made := string::new(nothing {}); + return made if node == 0; + val first: u32 = syntax.node_tokens[node]; + var last: u32 = syntax.node_end(node); + last = last < first ? first : last; + val start: u32 = syntax.token_offsets[first]; + val end: u32 = syntax.token_offsets[last] + syntax.token_length(last, this.names); + val text := this.units[file].source.make_lexeme(start, end - start); + var spaced := false; + for i in 0..text.length { + val byte: u8 = text[i]; + if byte == ' ' || byte == '\t' || byte == '\n' || byte == '\r' { + spaced = true; + continue; + } + if spaced && made.length != 0 { + made.push(' '); + } + spaced = false; + made.push(byte); + } + return made; +} + +#! A slot of a node's record, in whichever slot its shape keeps the record. +#! @param this The syntax tree. +#! @param node The node. +#! @param index The slot's position in the record. +#! @returns The slot, or 0 where the node has no record. +def syntax::record_at(&this, node: u32, index: u32): u32 { + val kind := this.node_kinds[node]; + val at: u32 = kind.shape.left == slot::extra ? this.node_lefts[node] : this.node_rights[node]; + return this.extras[at as u64 + index as u64]; +} + +#! The flags of a node, wherever its shape keeps them. +#! @param this The syntax tree. +#! @param node The node. +#! @returns The flags, as `nf` says, or 0. +def syntax::flags_at(&this, node: u32): u32 { + val shape := this.node_kinds[node].shape; + return this.node_rights[node] if shape.right == slot::flags; + return this.node_lefts[node] if shape.left == slot::flags; + for i in 0..shape.record.length { + return this.record_at(node, i as u32) if shape.record[i] == slot::flags; + } + return 0; +} + +#! A query of a file under way: where checking was before it began, the walk +#! of the file's tree, and the declarations of the file's nodes. It closes +#! where its scope ends, however the query returns, which puts back where +#! checking was. +struct checker::query : owning { + var checker: &mut checker; #! The checker queried. + var saved: checker::frame; #! Where checking was, which closing puts back. + var walked: tree_walk; #! The file's tree. + var decls: dict; #! The declarations each node of the file declares, by the node. + var open: bool; #! Whether it is yet to close. +} + +#! Begins a query of the file: its results are what is read, nothing the +#! checker works out depends on the query, and nothing it reports is noted, +#! until the query closes. +#! @param this The checker. +#! @param file The file. +#! @returns The query, holding the file's tree and the declarations of its +#! nodes. +def checker::begin_query(&mut this, file: u32): checker::query { + val saved := this.at; + this.use_table(this.units[file].table); + this.at.decl = 0; + this.at.instance = 0; + this.at.scope = 0; + this.at.home = 0; + this.mute++; + this.owned_names = true; + return checker::query { + checker = this, + saved = saved, + walked = this.tree_of(file), + decls = this.decls_in(file), + open = true + }; +} + +#! Ends the query, putting back where checking was, once. +#! @param this The query. +def checker::query::close(&mut this): void { + return if !this.open; + this.open = false; + this.checker.mute--; + this.checker.owned_names = this.checker.mute != 0 && this.checker.owned_names; + this.checker.at = this.saved; + close(&mut this.walked); + close(&mut this.decls); +} + +#! Moves the query to another file, whose results are read from then on. +#! @param this The checker. +#! @param file The file. +def checker::query_file(&mut this, file: u32): void { + this.use_table(this.units[file].table); + this.at.decl = 0; + this.at.instance = 0; +} + +#! The module the declarations a file makes before the offset are in: that of +#! the last `module` before it, or the program's own. +#! @param this The checker. +#! @param file The file. +#! @param offset The byte of its text. +#! @returns The module. +def checker::home_at(&mut this, file: u32, offset: u32): u32 { + val syntax := &this.units[file].syntax; + val decls := syntax.node_lefts[this.units[file].root]; + var home: u32 = 0; + for &node in syntax.run_view(decls) { + break if syntax.token_offsets[syntax.node_tokens[node]] > offset; + continue if syntax.node_kinds[node] != nk::module_decl && syntax.node_kinds[node] != nk::extern_module; + val found := this.module_named(file, syntax.node_lefts[node], 0xFFFFFFFF); + if found != 0 { + home = found; + } + } + return home; +} + +#! The module a `path` of a file names from the program's own, through its +#! segment at `last`, or 0 where it names none. +#! @param this The checker. +#! @param file The file. +#! @param path The `path` node. +#! @param last The position of the last segment read, or more for all. +#! @returns The module, or 0. +def checker::module_named(&this, file: u32, path: u32, last: u32): u32 { + val syntax := &this.units[file].syntax; + val run: u32 = syntax.node_lefts[path]; + if run == 0 { + return this.modules.find(0, syntax.token_names[syntax.node_tokens[path]]); + } + var at: u32 = 0; + for i in 0..syntax.run_length(run) { + break if i as u32 > last; + val segment := syntax.run_at(run, i as u32); + at = this.modules.find(at, syntax.token_names[syntax.node_tokens[segment]]); + return 0 if at == 0; + } + return at; +} + +#! The declarations each node of a file declares, by the node. +#! @param this The checker. +#! @param file The file. +#! @returns The declarations, by their nodes. +def checker::decls_in(&this, file: u32): dict { + var made := dict::::new(); + for &id in this.decls.by_file.of(file) { + continue if this.decls.kinds.p[id] == dk::none || this.decls.kinds.p[id] == dk::builtin; + made.insert(this.decls.nodes.p[id], id); + } + return made; +} + +#! What a declaration a name refers to stands for: a property for its accessors, +#! which are renamed and shown as one. +#! @param this The checker. +#! @param decl The declaration. +#! @returns What it stands for. +def checker::standing_for(&this, decl: u32): u32 { + if decl != 0 && this.decls.kinds.p[decl] == dk::function && this.decls.has(decl, df::accessor) { + return this.decls.owners.p[decl]; + } + return decl; +} + +#! What a reference a node records refers to. +#! @param this The checker. +#! @param ref The reference, as `ref_at` gives it. +#! @returns What it refers to. +def checker::meant_by(&this, ref: u32): checker::meant { + return checker::meant {} if ref == 0; + if (ref & ref_local) != 0 { + return checker::meant { file = this.at.file, local = ref & ref_mask }; + } + if (ref & ref_type) != 0 { + # A pack whose types are not known is of the pack parameter it is. + val kind := ref & ref_mask; + val decl := this.type_decl(kind); + if decl == 0 && this.types.kind_of(kind) == ty::pack && this.types.part_count(kind) == 0 { + return checker::meant { decl = this.types.first_of(kind) }; + } + return checker::meant { decl = decl }; + } + return checker::meant {} if ref >= this.decls.count as u32; + return checker::meant { decl = this.standing_for(ref) }; +} + +#! What the name a node of the file being queried writes refers to, or nothing +#! where it writes none, or one checking left unresolved. +#! @param this The checker. +#! @param node The node. +#! @param walked The file's tree. +#! @param decls The declarations of the file's nodes. +#! @returns What it refers to. +def checker::meaning_of(&mut this, node: u32, walked: &tree_walk, decls: &dict): checker::meant { + val parent: u32 = walked.parents[node]; + match this.kind_of(node) { + nk::name => { + val ref := this.ref_at(node); + return this.meant_by(ref) if ref != 0; + + # A name a pattern binds, or a loop or `else` names, declares it. + if this.has_flag(node, rf::local) { + return checker::meant { file = this.at.file, local = node }; + } + + # A field a pattern names, as `number` of `number(n)`, which the pattern's + # call refers to. + if parent != 0 && this.kind_of(parent) == nk::call && this.left_of(parent) == node { + val held := this.ref_at(parent); + if held != 0 && (held & (ref_local | ref_type)) == 0 && held < this.decls.count as u32 + && this.decls.kinds.p[held] == dk::field { + return checker::meant { decl = held }; + } + } + return checker::meant {}; + } + nk::segment => return this.segment_meaning(parent, node, walked, decls); + nk::type_name, nk::path => { + # A name of one segment is its own segment, and one of more is its + # segments', which the walk meets after it. + return checker::meant {} if this.left_of(node) != 0; + return this.segment_meaning(node, node, walked, decls); + } + nk::member, nk::member_of => { + val ref := this.ref_at(node); + return this.meant_by(ref) if ref != 0; + return checker::meant {} if this.kind_of(node) == nk::member_of; + return this.member_meaning(this.type_at(this.left_of(node)), this.name_of(node)); + } + nk::field_init => { + return checker::meant {} if !this.node_has(node, nf::named); + return this.meant_by(this.ref_at(node)); + } + nk::rename => { + # The name a spread renames is a field of the struct spread. + return checker::meant {} if parent == 0 || this.kind_of(parent) != nk::spread; + val spread := this.type_name_meaning(this.left_of(parent)); + return checker::meant {} if spread.decl == 0; + return this.member_meaning(this.decls.types.p[spread.decl], this.name_of(node)); + } + nk::function, nk::struct_decl, nk::union_decl, nk::trait_decl, nk::alias, nk::enumeration, + nk::enumerator, nk::field, nk::property, nk::assoc_type, nk::type_param, nk::const_param => { + if decls.get(&node) is some(found) { + return checker::meant { decl = this.standing_for(found) }; + } + return checker::meant {}; + } + nk::variable => { + if decls.get(&node) is some(found) { + return checker::meant { decl = found }; + } + return checker::meant { file = this.at.file, local = node } if this.has_flag(node, rf::local); + return checker::meant {}; + } + nk::param => { + # A parameter an accessor implies has no name of its own written, and its + # token is the `get` or `set`. + return checker::meant {} if this.node_has(node, nf::implied); + # A parameter of a function without a body is no local, but is still + # the function's. + return checker::meant { file = this.at.file, local = node }; + } + else => return checker::meant {}; + } + return checker::meant {}; +} + +#! What a segment of a `type_name`, `path`, `import`, or `module` names: the +#! last what the whole names, and those before it the modules and types it is +#! within. +#! @param this The checker. +#! @param holder The `type_name` or `path` node holding the segment. +#! @param segment The segment, which is the holder itself where it has one. +#! @param walked The file's tree. +#! @param decls The declarations of the file's nodes. +#! @returns What it names. +def checker::segment_meaning(&mut this, holder: u32, segment: u32, walked: &tree_walk, decls: &dict): checker::meant { + return checker::meant {} if holder == 0; + val ref := this.ref_at(segment); + if ref != 0 { + return this.meant_by(ref); + } + + # The position of the segment in the holder. + val run := this.left_of(holder); + var index: u32 = 0; + for i in 0..(run == 0 ? 0 : this.run_length(run)) { + if this.run_at(run, i as u32) == segment { + index = i as u32; + } + } + val last := run == 0 || index + 1 == this.run_length(run); + + # A path an `import` or `module` names is of modules alone. + val outer: u32 = walked.parents[holder]; + if outer != 0 && (this.kind_of(outer) == nk::import_decl || this.kind_of(outer) == nk::module_decl + || this.kind_of(outer) == nk::extern_module) { + val found := this.module_named(this.at.file, holder, index); + return checker::meant { named_module = found, is_module = true } if found != 0; + return checker::meant {}; + } + + # The type a declaration is made through, as `rect` of `def rect::area`, is + # what it is a member of, and a segment before the last, what that is + # declared through in turn. + if outer != 0 && this.is_receiving(outer) && this.record(outer, decl_slot::receiver) == holder { + if decls.get(&outer) is some(found) { + var at: u32 = this.decls.owners.p[found]; + if this.decls.kinds.p[at] == dk::property { + at = this.decls.owners.p[at]; + } + val count := run == 0 ? 1 : this.run_length(run); + var steps := count - 1 - index; + while steps > 0 && at != 0 { + at = this.decls.owners.p[at]; + steps--; + } + return checker::meant { decl = at } if at != 0; + } + } + + # A whole path refers to what its node says, and its last segment with it. + if last && segment != holder { + val whole := this.ref_at(holder); + if whole != 0 { + return this.meant_by(whole); + } + } + + # After `is`, a name that is no type is the field of the union tested, which + # the test refers to. + if outer != 0 && this.kind_of(outer) == nk::is_test && this.record(outer, is_slot::target) == holder && index == 0 { + val held := this.ref_at(outer); + if held != 0 && (held & (ref_local | ref_type)) == 0 && held < this.decls.count as u32 { + return checker::meant { decl = held }; + } + } + + # A segment naming no declaration may name a module, from where the file is. + if !last || run != 0 { + val name := this.name_of(segment); + var home := this.home_at(this.at.file, this.units[this.at.file].syntax.token_offsets[this.token_of(segment)]); + if index == 0 { + val saved := this.at.home; + this.at.home = home; + val found := this.lookup_module(name); + this.at.home = saved; + return checker::meant { named_module = found, is_module = true } if found != 0; + return checker::meant {}; + } + val before := this.segment_meaning(holder, this.run_at(run, index - 1), walked, decls); + if before.is_module { + val found := this.modules.find(before.named_module, name); + return checker::meant { named_module = found, is_module = true } if found != 0; + } + } + return checker::meant {}; +} + +#! What a `type_name` names, as its last segment refers to it. +#! @param this The checker. +#! @param node The `type_name` node. +#! @returns What it names. +def checker::type_name_meaning(&mut this, node: u32): checker::meant { + return checker::meant {} if node == 0 || this.kind_of(node) != nk::type_name; + val run := this.left_of(node); + val last := run == 0 ? node : this.run_at(run, this.run_length(run) - 1); + return this.meant_by(this.ref_at(last)); +} + +#! Whether a node declares what may be made through a type, as `rect` of +#! `def rect::area`, which its record's second slot names. +#! @param this The checker. +#! @param node The node. +#! @returns Whether it does. +def checker::is_receiving(&this, node: u32): bool { + return match this.kind_of(node) { + nk::function, nk::variable, nk::property, nk::struct_decl, nk::union_decl, nk::trait_decl, + nk::enumeration, nk::alias => true, + else => false + }; +} + +#! The member of a type a name reaches after `.`, as a field, a property, or a +#! method, or nothing where the type has none of the name. +#! @param this The checker. +#! @param kind The type of the value. +#! @param name The ID of the name. +#! @returns What the name refers to. +def checker::member_meaning(&mut this, kind: u32, name: u32): checker::meant { + return checker::meant {} if kind == 0 || kind == bt::error; + val found := this.find_member(this.reached(kind), name); + return checker::meant {} if found.decl == 0; + return checker::meant { decl = this.standing_for(found.decl) }; +} + +#! What a declaration is, as `symbol` says. +#! @param this The checker. +#! @param decl The declaration. +#! @returns What it is. +def checker::symbol_of(&mut this, decl: u32): symbol { + val kind: dk = this.decls.kinds.p[decl]; + if kind == dk::function { + # A property is read and written by its name alone, so it is offered and + # coloured as a field is rather than as the methods its accessors are. + return symbol::field if this.decls.has(decl, df::accessor); + return this.decls.owners.p[decl] != 0 && this.decls.has(decl, df::method) ? symbol::method : symbol::function; + } + if kind == dk::type_param { + return this.decls.has(decl, df::valued) ? symbol::constant : symbol::type_param; + } + if kind == dk::variable { + return this.decls.has(decl, df::mutable) ? symbol::variable : symbol::constant; + } + return match kind { + dk::property => symbol::field, + dk::field => symbol::field, + dk::attribute => symbol::constant, + dk::enum_member => symbol::enum_member, + dk::struct_type, dk::union_type => symbol::struct_type, + dk::trait_type => symbol::trait_type, + dk::enum_type => symbol::enum_type, + else => symbol::type_name + }; +} + +#! What a name refers to is, as `symbol` says. +#! @param this The checker. +#! @param meant What it refers to. +#! @returns What it is. +def checker::symbol_meant(&mut this, meant: &checker::meant): symbol { + return symbol::namespace if meant.is_module; + return this.symbol_of(meant.decl) if meant.decl != 0; + val kind := this.units[meant.file].syntax.node_kinds[meant.local]; + return kind == nk::param ? symbol::parameter : symbol::variable; +} + +#! Whether what a name refers to is never written, as a `val`, a `const`, or a +#! member of an enum. +#! @param this The checker. +#! @param meant What it refers to. +#! @returns Whether it is. +def checker::readonly_meant(&mut this, meant: &checker::meant): bool { + return true if meant.is_module; + if meant.decl != 0 { + return match this.decls.kinds.p[meant.decl] { + dk::variable, dk::field, dk::attribute => !this.decls.has(meant.decl, df::mutable), + dk::enum_member => true, + dk::property => this.property_setter(meant.decl) == 0, + dk::type_param => true, + else => false + }; + } + + # A parameter is a binding the body writes, so it is not marked read-only. + val syntax := &this.units[meant.file].syntax; + return false if syntax.node_kinds[meant.local] == nk::param; + val saved := this.at; + this.use_table(this.units[meant.file].table); + val writes := this.has_flag(meant.local, rf::mutable); + this.at = saved; + return !writes; +} diff --git a/analyzer/reading.sakura b/analyzer/reading.sakura new file mode 100644 index 00000000..db3f613f --- /dev/null +++ b/analyzer/reading.sakura @@ -0,0 +1,170 @@ +#! @file reading.sakura +#! @author John Christman (sorakatadzuma@gmail.com) +#! @copyright Malunal Studios, LLC. +#! @license MIT +#! +#! Contains how the files of a program are read: each lexed, then parsed, as +#! many at once as there are threads asked for. Each thread reading files lexes +#! them with names of its own, which it keeps from file to file. The names a +#! file uses join the program's in the order the file first uses them, and the +#! files' in the order of the files, each once those of the files before it +#! have, so every word is given the ID it would have were the files read one +#! after another, and what is read is the same however many threads read it. +#! What reading notes is heard as it is noted, on the thread noting it, rather +#! than kept. + +import std::thread; +module sakura::analyzer; + + +#! What hears what reading files notes, as it is noted. +pub struct listener { + pub var noted: def(&mut note): void; #! Hears each note as it is made, on the thread reading its file, which it may move. + pub var read: def(u32): void; #! Hears that the file of the index was read whole, after which nothing more is noted of reading it. +} + +#! Lexes and parses some of the files of a program, those from one index up to +#! another, as many at once as there are threads asked for, each taking the +#! next file none has taken. A program read by reference reads its files so, a +#! round at a time, each round's after those before it. +#! @param sources The source of each file, which stays where it is, as what +#! is read refers to it. +#! @param syntaxes Where each file is read into: one, empty, for each source. +#! @param roots Where the `document` node of each file is written. +#! @param names The program's names, which the words of each file join. +#! @param threads How many threads read files, the one calling among them; +#! where it is one, none starts, and the files are read one +#! after another, with the program's names. +#! @param heard What hears what reading notes. +#! @param from The index of the first file read, whose names join the +#! program's after those of every file before it. +#! @param to The index past the last. +pub def read_files( + sources: &vector, + syntaxes: &mut vector, + roots: &mut vector, + names: &mut names, + threads: u32, + heard: &listener, + from: u64, + to: u64 +): void { + return if to <= from; + val count := to - from; + if roots.length < to { + roots.resize(to); + } + var helpers: u64 = threads <= 1 || count <= 1 ? 0 : (threads - 1) as u64; + if helpers > count - 1 { + helpers = count - 1; + } + # The lexer and parser are given a vector to keep notes in, which stays + # empty, as they hear each note instead. + if helpers == 0 { + var kept := vector::::new(); + for j in from..to { + var lexing := lexer::new(sources.at(j), names, &mut kept, j as u32); + lexing.sink.heard = heard.noted; + lexing.tokenize_all(syntaxes.at(j)); + roots[j] = parse_heard(syntaxes.at(j), names, j as u32, heard); + heard.read(j as u32); + } + return; + } + + # The names of each file join the program's in its turn: `turn` holds the + # index of the file whose names join next. + var next := atomic::::new(from); + var turn := thread::mutex::::new(from); + var turned := thread::condition::new(); + val reader := def(): void { + var kept := vector::::new(); + # The names this thread lexes with; of each, one more than the index of the + # last file seen to use it, and its ID in the program's names, there; and + # the names the file being read uses, in the order it first uses them. + var own := names::new(); + var seen := vector::::new(); + var ids := vector::::new(); + var used := vector::::new(); + while true { + val j := next.fetch_add(1); + return if j >= to; + var lexing := lexer::new(sources.at(j), &mut own, &mut kept, j as u32); + lexing.sink.heard = heard.noted; + lexing.tokenize_all(syntaxes.at(j)); + + # The file is parsed with the names it was lexed with, before its turn to + # join them to the program's, which other threads write meanwhile. The + # parser knows its words by the IDs every table gives them, and the tree + # holds no ID of its own. + roots[j] = parse_heard(syntaxes.at(j), &own, j as u32, heard); + + # Every word lexed is a token, so the order the file first uses each name + # in is that of its tokens. + seen.resize(own.count); + ids.resize(own.count); + used.clear(); + for &id in syntaxes.at(j).token_names { + if seen[id as u64] != j + 1 { + seen[id as u64] = j + 1; + used.append(id); + } + } + join_names(&mut turn, &mut turned, j, names, &own, used.view(), &mut ids); + syntaxes.at(j).rename(ids.view()); + heard.read(j as u32); + } + }; + var started := vector::>::new(); + for _ in 0..helpers { + var made := thread::spawn(reader) else (_) { break; }; + started.append(move(&mut made)); + } + reader(); + for &mut handle in started { + handle.join(); + } +} + +#! Parses a file lexed, the notes heard as they are made. +#! @param syntax The file's tokens, which its nodes join. +#! @param names The names the file was lexed with. +#! @param file The index of the file. +#! @param heard What hears the notes. +#! @returns The file's `document` node. +def parse_heard(syntax: &mut syntax, names: &names, file: u32, heard: &listener): u32 { + var kept := vector::::new(); + var parsing := parser::new(syntax, names, &mut kept, file); + parsing.sink.heard = heard.noted; + return parsing.parse(); +} + +#! Waits for a file's turn, which comes once the names of the files before it +#! have joined the program's, then adds those it uses. +#! @param turn The index of the file whose names join next. +#! @param turned What is notified where the turn passes. +#! @param file The index of the file. +#! @param names The program's names. +#! @param own The names the file was lexed with. +#! @param used Those the file uses, in the order it first uses them. +#! @param ids Where the ID in the program's names of each it uses is +#! written, by its ID in its own. +def join_names( + turn: &mut thread::mutex, + turned: &mut thread::condition, + file: u64, + names: &mut names, + own: &names, + used: span, + ids: &mut vector +): void { + var held := turn.lock(); + while held.value() != file { + turned.wait(&mut held); + } + for &id in used { + ids[id as u64] = names.intern(&own.text(id)); + } + held.value() = file + 1; + turned.notify_all(); +} diff --git a/analyzer/shapes.sakura b/analyzer/shapes.sakura new file mode 100644 index 00000000..f653e002 --- /dev/null +++ b/analyzer/shapes.sakura @@ -0,0 +1,455 @@ +#! @file shapes.sakura +#! @author John Christman (sorakatadzuma@gmail.com) +#! @copyright Malunal Studios, LLC. +#! @license MIT +#! +#! Contains the shapes of the nodes, which say what the slots and records of +#! each kind of node hold, so the tree can be walked and printed without knowing +#! each kind, and the positions of the slots of each record, by name. + +module sakura::analyzer; + +#! Describes the shape of any given syntax node within the language. +#! +#! All nodes have a distinct `left` and `right`, but they may mean something +#! different. They can point to another node by index, an extra piece of data +#! by index, a run of nodes whose indices are proceeding the length in the +#! extras vector, or simply the flags associated with the node. +#! +#! When the slot, `left` or `right`, is populated by `slot::extra` then the +#! record variable is guaranteed to be populated, as this will describe the +#! full structure of the node. For example, a function node has many additional +#! features to it: receiver, generics, params, return type, body, attributes. +#! All of those cannot be described in simply the `left` and `right` slots. It +#! can be described in `right` if `slot::extra` indicates that `record` further +#! describes it shape and the record tells you how many additional pieces there +#! are and what they represent. +pub struct shape { + #! What a node's first slot holds. + val left: slot; + #! What its second slot holds. + val right: slot; + #! What its record holds, slot by slot, where a slot holds one. + val record: span; +} + +#! Describes what a left hand or right hand side of a node contains. +#! +#! This works in conjunction with the `shape` structure to describe the exact +#! layout of a given node for the purposes of traversing the abstract syntax +#! tree of the language. +pub enum slot : u8 { + none, #! Unused. + node, #! An index into `nodes`. + extra, #! An index into `extras` of one node. + run, #! An index into `extras` where a count is followed by that many nodes. + flags, #! Bits the kind defines, as `mut` or `const`. + bounds #! A run, which only shows where it holds nodes: those a trait's method bounds beside its own. +} + + +#! The slots the records of declarations share, by their positions, as `record` +#! takes them: each begins with its attributes, then its receiver, where it can +#! be declared through a type, then its type parameters, where it takes them. So +#! what reads one of these of any declaration reads the same slot. +pub enum decl_slot : u32 { + attributes, #! Attributes, of every declaration's record. + receiver, #! Receiver, of all but a type a trait asks for. + type_params, #! Type parameters, of a function's, a struct's, union's, or trait's, and an alias's. +} + +#! Describes how the extras of an `if` statement is laid out. +#! +#! An if statement is described by a `left` containing the condition, and +#! `right` containing the `then` and `else` branch of the statement. Thus, this +#! record describes two nodes slots. +pub const if_record: span = [ + slot::node, #! Then body, a `block`. + slot::node #! Else body, a `block` or `no_record`. +]; + +#! The slots of the record of an `if`, a `when`, `if const`, or `?:`, by their +#! positions, as `record` takes them. +pub enum if_slot : u32 { + then, #! What is taken where the condition holds. + other, #! What is taken where it does not, or 0. +} + +#! Describes how the extras of a function are laid out. +#! +#! `left` is this record and `right` its flags. The receiver is the type a +#! method or nested function is declared through, as `box` of `box::get`, +#! and the result and body are 0 where they are left out: a lambda's result, or +#! the body of a function ending at its signature. +pub const function_record: span = [ + slot::run, #! Attributes. + slot::node, #! Receiver, a `type_name`. + slot::run, #! Type parameters, each a `type_param`. + slot::run, #! Parameters, each a `param`. + slot::node, #! Result type. + slot::node, #! Body, a `block`. + slot::bounds, #! Bounds a trait's method puts on the trait's type parameters and `self`, each a `type_param`. +]; + +#! The slots of a function's record, by their positions, as `record` takes them. +pub enum function_slot : u32 { + attributes, #! Attributes. + receiver, #! Receiver. + type_params, #! Type parameters. + params, #! Parameters. + result, #! Result type. + body, #! Body. + outer, #! Bounds on the trait's type parameters and `self`. +} + +#! Describes how the extras of a parameter are laid out: `left` is its type, +#! which a lambda may leave out, and `right` this record. +pub const param_record: span = [ + slot::node, #! Default value. + slot::flags, #! `variadic`, and `mutable` for `&mut this`. +]; + +#! The slots of a parameter's record, by their positions, as `record` takes +#! them. +pub enum parameter_slot : u32 { + value, #! Default value. + flags, #! Flags. +} + +#! Describes how the extras of a variable, constant, or field are laid out: +#! `left` is this record and `right` its flags. A spread field's type is a +#! `spread`. +pub const variable_record: span = [ + slot::run, #! Attributes. + slot::node, #! Receiver, a `type_name`, as `rect` of `val rect::unit`. + slot::node, #! Type. + slot::node, #! Value. +]; + +#! The slots of the record of a variable, constant, or field, by their +#! positions, as `record` takes them. +pub enum variable_slot : u32 { + attributes, #! Attributes. + receiver, #! Receiver. + type_expr, #! Type. + value, #! Value. +} + +#! Describes how the extras of a property are laid out: `left` is this record +#! and `right` the run of its accessors. +pub const property_record: span = [ + slot::run, #! Attributes. + slot::node, #! Receiver, a `type_name`. + slot::node, #! Type. + slot::flags, #! `mutable` for `var`, and `exported`. +]; + +#! The slots of a property's record, by their positions, as `record` takes them. +pub enum property_slot : u32 { + attributes, #! Attributes. + receiver, #! Receiver. + type_expr, #! Type. + flags, #! Flags. +} + +#! Describes how the extras of an accessor are laid out: `left` is the run of +#! its parameters, `&this` first, and `right` this record. Its token says `get` +#! or `set`. +pub const accessor_record: span = [ + slot::node, #! Body, 0 where it ends at its signature. + slot::flags, #! `exported`, where the accessor is `pub` of its own. +]; + +#! The slots of an accessor's record, by their positions, as `record` takes +#! them. +pub enum accessor_slot : u32 { + body, #! Body. + flags, #! Flags. +} + +#! Describes how the extras of a struct, union, or trait are laid out: `left` is +#! this record and `right` the run of its members. Which it is, is its kind. +pub const aggregate_record: span = [ + slot::run, #! Attributes. + slot::node, #! Receiver, a `type_name`. + slot::run, #! Type parameters, each a `type_param`. + slot::run, #! Traits it implements, or composes, each a `type_name`. + slot::flags, #! `exported`. +]; + +#! The slots of the record of a struct, union, or trait, by their positions, as +#! `record` takes them. +pub enum aggregate_slot : u32 { + attributes, #! Attributes. + receiver, #! Receiver. + type_params, #! Type parameters. + traits, #! Traits it implements, or composes. + flags, #! Flags. +} + +#! Describes how the extras of a type a trait asks for are laid out: `left` is +#! this record and `right` the type standing in where the implementer gives +#! none. +pub const assoc_record: span = [ + slot::run, #! Attributes. + slot::run, #! Bounds, each a `type_name`. + slot::flags, #! `packed`, of a pack, as `type params...;`. +]; + +#! The slots of the record of a type a trait asks for, by their positions, as +#! `record` takes them. +pub enum assoc_slot : u32 { + attributes, #! Attributes. + bounds, #! Bounds. + flags, #! Flags. +} + +#! Describes how the extras of an enum are laid out: `left` is this record and +#! `right` the run of its members. +pub const enumeration_record: span = [ + slot::run, #! Attributes. + slot::node, #! Receiver, a `type_name`. + slot::node, #! The integer type holding it. + slot::flags, #! `exported`. +]; + +#! The slots of an enum's record, by their positions, as `record` takes them. +pub enum enumeration_slot : u32 { + attributes, #! Attributes. + receiver, #! Receiver. + integer, #! The integer type holding it. + flags, #! Flags. +} + +#! Describes how the extras of a type alias are laid out: `left` is this record +#! and `right` the aliased type. +pub const alias_record: span = [ + slot::run, #! Attributes. + slot::node, #! Receiver, a `type_name`. + slot::run, #! Type parameters, each a `type_param`. + slot::flags, #! `exported`. +]; + +#! The slots of a type alias's record, by their positions, as `record` takes +#! them. +pub enum alias_slot : u32 { + attributes, #! Attributes. + receiver, #! Receiver. + type_params, #! Type parameters. + flags, #! Flags. +} + +#! Describes how the extras of a `for` loop are laid out: `left` is this record +#! and `right` the body. +pub const for_record: span = [ + slot::node, #! The index, a `name`, as `i` of `for i, x in xs`. + slot::node, #! The variable, a `name`. + slot::node, #! What is iterated, or where a range begins. + slot::node, #! Where a range ends, as `n` of `0..n`. + slot::flags, #! `reference` for `&x`, with `mutable` for `&mut x`, `constant`, and `inclusive` for `0..=n`. +]; + +#! The slots of a `for` loop's record, by their positions, as `record` takes +#! them. +pub enum for_slot : u32 { + index, #! The index. + variable, #! The variable. + iterated, #! What is iterated, or where a range begins. + end, #! Where a range ends. + flags, #! Flags. +} + +#! Describes how the extras of an `else` fallback are laid out: `left` is the +#! result or maybe it takes from, and `right` this record. +pub const fallback_record: span = [ + slot::node, #! The error it names, a `name`, as `e` of `else (e)`. + slot::node, #! What stands in: a `block` that leaves, or an expression. +]; + +#! The slots of the record of an `else` fallback, by their positions, as +#! `record` takes them. +pub enum fallback_slot : u32 { + error, #! The error it names. + other, #! What stands in. +} + +#! Describes how the extras of a slice are laid out: `left` is what is sliced, +#! and `right` this record, either of whose bounds may be left out, as in +#! `xs[a:]`. +pub const slice_record: span = [ + slot::node, #! Start. + slot::node, #! Count. +]; + +#! The slots of a slice's record, by their positions, as `record` takes them. +pub enum slice_slot : u32 { + start, #! Start. + count, #! Count. +} + +#! Describes how the extras of an `is` test are laid out: `left` is the value +#! tested, and `right` this record. +pub const is_record: span = [ + slot::node, #! The field or trait, a `type_name`, or what names a field, as `d` of `x is (d)`. + slot::node, #! The value the field holds, a `name`, or a `reference` to one. + slot::flags, #! `negated` for `is not`, and `computed` for `x is (d)`. +]; + +#! The slots of the record of an `is` test, by their positions, as `record` +#! takes them. +pub enum is_slot : u32 { + target, #! The field or trait. + binding, #! The value the field holds. + flags, #! Flags. +} + +#! Describes how the extras of a contract are laid out: `left` is its +#! condition, and `right` this record, which is none where it says nothing but +#! its condition. Its token is the word saying which it is. +pub const contract_record: span = [ + slot::node, #! The name an `ensures` gives what the function returns, a `name`. + slot::node, #! What it says failed, in place of the condition as written. +]; + +#! The slots of the record of a contract, by their positions, as `record` takes +#! them. +pub enum contract_slot : u32 { + bound, #! The name given what is returned. + text, #! What it says failed. +} + +#! Which contract a `contract` node is, as its token says. +pub enum clause : u8 { + expects, #! What a function needs of what it is given, checked where it is written. + asserts, #! What must hold as the work goes on, checked where it is written. + ensures, #! What holds where the block it is written in is left, checked there. +} + +#! Describes how the extras of a lambda are laid out: `left` is the run of its +#! parameters, and `right` this record. +pub const lambda_record: span = [ + slot::node, #! Result type, 0 where it is left out. + slot::node, #! Body: a `block`, or the expression after `=>`. +]; + +#! The slots of a lambda's record, by their positions, as `record` takes them. +pub enum lambda_slot : u32 { + result, #! Result type. + body, #! Body. +} + +#! No record, for the kinds whose slots hold everything they have. +pub const no_record: span = []; + + +#! The shape of each kind of node, in the order `nk` declares them. +#! +#! Index 0 stands for "absent" in both vectors: node 0 is an `error` node +#! holding nothing, a run at 0 is empty, and a record at 0 holds nothing in each +#! of its slots, which the zeros `extras` begins with make true. So a slot left +#! out holds 0 whatever it is, and a record of nothing takes no room. +#! +#! A `type_name` of one segment without type arguments, as `u8`, holds no run, +#! its token being the name, and likewise a `path` of one segment. +#! +#! Where a node's token alone says what it is, as a `name` or a `number`, both +#! of its slots are unused. An operator's token is the operator. +pub const shapes: shape[nk::count as u64] = [ + # Structure + shape { left = slot::run, right = slot::none, record = no_record }, # error: what it did parse + shape { left = slot::run, right = slot::none, record = no_record }, # document: declarations + shape { left = slot::run, right = slot::none, record = no_record }, # block: statements + + # Declarations + shape { left = slot::node, right = slot::none, record = no_record }, # import_decl: `path` + shape { left = slot::node, right = slot::node, record = no_record }, # module_decl: `path`, `when` condition + shape { left = slot::node, right = slot::node, record = no_record }, # extern_import: `string`, `when` condition + shape { left = slot::node, right = slot::node, record = no_record }, # extern_module: `path`, `when` condition + shape { left = slot::node, right = slot::extra, record = if_record }, # when_block: condition, [then, else] + shape { left = slot::extra, right = slot::flags, record = function_record }, # function + shape { left = slot::node, right = slot::extra, record = param_record }, # param: type, [default, flags] + shape { left = slot::extra, right = slot::flags, record = variable_record }, # variable + shape { left = slot::extra, right = slot::flags, record = variable_record }, # field + shape { left = slot::node, right = slot::run, record = no_record }, # spread: `type_name`, renames + shape { left = slot::node, right = slot::none, record = no_record }, # rename: new `name`; token is the old + shape { left = slot::extra, right = slot::run, record = property_record }, # property: [...], accessors + shape { left = slot::run, right = slot::extra, record = accessor_record }, # accessor: params, [body, flags] + shape { left = slot::extra, right = slot::run, record = aggregate_record }, # struct_decl: [...], fields + shape { left = slot::extra, right = slot::run, record = aggregate_record }, # union_decl: [...], fields + shape { left = slot::extra, right = slot::run, record = aggregate_record }, # trait_decl: [...], members + shape { left = slot::extra, right = slot::node, record = assoc_record }, # assoc_type: [...], default + shape { left = slot::extra, right = slot::run, record = enumeration_record }, # enumeration: [...], members + shape { left = slot::run, right = slot::node, record = no_record }, # enumerator: attributes, value + shape { left = slot::extra, right = slot::node, record = alias_record }, # alias: [...], aliased type + shape { left = slot::node, right = slot::run, record = no_record }, # attribute: `type_name`, field inits + shape { left = slot::run, right = slot::flags, record = no_record }, # type_param: bounds, `packed` + shape { left = slot::run, right = slot::node, record = no_record }, # const_param: bounds, type + shape { left = slot::run, right = slot::node, record = no_record }, # type_pattern: parameters' type parameters, result's + shape { left = slot::node, right = slot::node, record = no_record }, # array_pattern: element's type parameter, length's + + # Types + shape { left = slot::run, right = slot::none, record = no_record }, # segment: type arguments or parameters + shape { left = slot::run, right = slot::none, record = no_record }, # type_name: segments + shape { left = slot::node, right = slot::flags, record = no_record }, # type_ref: referent, `mutable` + shape { left = slot::node, right = slot::flags, record = no_record }, # type_ptr: pointee, `mutable` + shape { left = slot::node, right = slot::node, record = no_record }, # type_fixed: element, length + shape { left = slot::run, right = slot::node, record = no_record }, # type_func: parameter types, result + shape { left = slot::node, right = slot::none, record = no_record }, # type_spread: the type spread + shape { left = slot::node, right = slot::none, record = no_record }, # type_of: declaration + + # Statements + shape { left = slot::node, right = slot::extra, record = if_record }, # if_stmt: condition, [then, else] + shape { left = slot::node, right = slot::extra, record = if_record }, # if_const: condition, [then, else] + shape { left = slot::node, right = slot::node, record = no_record }, # while_stmt: condition, body + shape { left = slot::extra, right = slot::node, record = for_record }, # for_stmt: [...], body + shape { left = slot::node, right = slot::run, record = no_record }, # match_stmt: subject, arms + shape { left = slot::run, right = slot::node, record = no_record }, # arm: patterns (empty for `else`), body + shape { left = slot::node, right = slot::none, record = no_record }, # return_stmt: value + shape { left = slot::none, right = slot::none, record = no_record }, # break_stmt + shape { left = slot::none, right = slot::none, record = no_record }, # continue_stmt + shape { left = slot::node, right = slot::none, record = no_record }, # expr_stmt: expression + shape { left = slot::node, right = slot::extra, record = contract_record }, # contract: condition, [name, text]; token is the word + + # Expressions + shape { left = slot::none, right = slot::none, record = no_record }, # name + shape { left = slot::run, right = slot::none, record = no_record }, # path: segments + shape { left = slot::none, right = slot::none, record = no_record }, # number + shape { left = slot::none, right = slot::none, record = no_record }, # character + shape { left = slot::none, right = slot::none, record = no_record }, # string + shape { left = slot::run, right = slot::none, record = no_record }, # istring: text pieces and holes + shape { left = slot::none, right = slot::none, record = no_record }, # boolean + shape { left = slot::none, right = slot::none, record = no_record }, # null_lit + shape { left = slot::node, right = slot::none, record = no_record }, # unary: operand; also `*p` and `...xs` + shape { left = slot::node, right = slot::none, record = no_record }, # postfix: operand of `++` or `--` + shape { left = slot::node, right = slot::flags, record = no_record }, # reference: operand, `mutable` + shape { left = slot::node, right = slot::node, record = no_record }, # binary: left, right + shape { left = slot::node, right = slot::node, record = no_record }, # assign: target, value + shape { left = slot::node, right = slot::extra, record = if_record }, # ternary: condition, [then, else] + shape { left = slot::node, right = slot::extra, record = fallback_record }, # fallback: value, [error, fallback] + shape { left = slot::node, right = slot::run, record = no_record }, # call: callee, arguments + shape { left = slot::node, right = slot::run, record = no_record }, # type_args: callee, types, as `value_of(d)::` + shape { left = slot::node, right = slot::node, record = no_record }, # index: object, index + shape { left = slot::node, right = slot::extra, record = slice_record }, # slice: object, [start, count] + shape { left = slot::node, right = slot::run, record = no_record }, # member: object, type arguments + shape { left = slot::node, right = slot::node, record = no_record }, # member_of: object, declaration, as `x.(d)` + shape { left = slot::node, right = slot::node, record = no_record }, # cast: value, type + shape { left = slot::node, right = slot::extra, record = is_record }, # is_test: value, [target, binding, flags] + shape { left = slot::node, right = slot::run, record = no_record }, # construct: `type_name`, field inits + shape { left = slot::node, right = slot::flags, record = no_record }, # field_init: value, `named`; token is the field where named + shape { left = slot::run, right = slot::none, record = no_record }, # array: elements + shape { left = slot::run, right = slot::extra, record = lambda_record }, # lambda: params, [result, body] + shape { left = slot::node, right = slot::run, record = no_record }, # match_value: subject, arms + shape { left = slot::node, right = slot::node, record = no_record }, # range: start, end; token is `..` or `..=` + shape { left = slot::node, right = slot::none, record = no_record }, # old_value: the expression, within an `ensures` + shape { left = slot::none, right = slot::none, record = no_record }, # undefined +]; + +#! The shape of the node, which says what its `left` and `right` hold. +#! @param this The node. +#! @returns The shape. +pub val node::shape: shape { get => shapes[this.kind as u64]; } + +#! The shape of nodes of the kind. +#! @param this The kind of node. +#! @returns The shape. +pub val nk::shape: shape { get => shapes[this as u64]; } diff --git a/analyzer/source.sakura b/analyzer/source.sakura new file mode 100644 index 00000000..57a295de --- /dev/null +++ b/analyzer/source.sakura @@ -0,0 +1,227 @@ +#! @file source.sakura +#! @author John Christman (sorakatadzuma@gmail.com) +#! @copyright Malunal Studios, LLC. +#! @license MIT +#! +#! Contains the source type, which is the text of a file and where its lines +#! begin, read from disk or given from memory, along with the classes of bytes +#! the lexer reads the text by. + +import std::io; +import core::swar; +module sakura::analyzer; + +#! Represents the source information for a file. +#! +#! The source keeps the path to the file, the loaded text of the file, and a +#! `lines` vector to indicate where lines start within the source text, which +#! it finds itself as it is made, so the text is never changed after. Each line +#! break Windows writes, CR LF, is kept as the LF alone, as other systems write +#! one, so the lexer, the lines, and a literal spanning lines read the same +#! text whichever system wrote the file. +pub struct source { + pub var path: strview; #! The path the file is reported as. + var text: string; #! The file's text. + pub var lines: lines; #! Where each line of the text begins. +} + +#! Provides the length of the source text. +#! @param this The source object to get the length of its text. +#! @returns The length of the source text. +pub val source::length: u64 { + get => this.text.length; +} + +#! Creates a new source object by opening the file it points to and reading it. +#! @param path The path to the source file to open. +#! @returns The source object containing the file contents read. +pub def source::open(path: strview): source { + var result := source { + path = path, + text = without_mark(source::read(path)), + lines = lines::new(nothing {}) + }; + result.finish(); + return result; +} + +# Reads the whole of the file at a path, giving empty text where it cannot be. +def source::read(text: strview): string { + val at := path::parse(text) else (_) { return string::new(nothing {}); }; + return read_file(at, nothing {}) else string::new(nothing {}); +} + +# Finds the lines of the text, which finds whether it holds a CR, so only text +# holding one is read again, made without its CR LFs, and its lines found again. +def source::finish(&mut this): void { + return if !this.find_lines(); + val held := this.text.length; + this.text = without_returns(move(&mut this.text)); + if this.text.length != held { + this.lines.clear(); + _ = this.find_lines(); + } +} + +# The text without the byte order mark some editors begin a file of UTF-8 with, +# which is no part of the language, or the text itself where it has none. +def without_mark(text: string): string { + val bytes := text.view(); + return text if bytes.length < 3 || bytes[0] != 0xEF || bytes[1] != 0xBB || bytes[2] != 0xBF; + return string::from(bytes[3:], nothing {}); +} + +# The text with each CR LF line break made the LF alone, or the text itself +# where it has none. +def without_returns(text: string): string { + val bytes := text.view(); + var found := false; + for i in 1..bytes.length { + if bytes[i] == '\n' && bytes[i - 1] == '\r' { + found = true; + break; + } + } + return text if !found; + + var made := string::new(nothing {}); + made.reserve(bytes.length); + for i in 0..bytes.length { + if bytes[i] != '\r' || i + 1 == bytes.length || bytes[i + 1] != '\n' { + made.push(bytes[i]); + } + } + return made; +} + +#! Finds where each line of the text begins: at its start, and past each line +#! break, and whether the text holds a CR, which a CR LF line break begins +#! with. +#! @param this The source file. +#! @returns Whether the text holds a CR. +def source::find_lines(&mut this): bool { + val text := this.text.view().data; + val size := this.text.length; + this.lines.reserve(size / 24 + 2); + this.lines.append(0); + + # Where vectors are held in registers, sixteen bytes at a time: the bits of + # the bytes that are `\n`, each found from the lowest. Then eight at a time, + # as words, each `\n` found from the first of the mask of them. The bytes + # that are `\r` are gathered as they go. + var at: u64 = 0; + var returns := false; + if lanes_held() { + val newline := u8x16::splat('\n'); + val back := u8x16::splat('\r'); + var held: u32 = 0; + while at + 16 <= size { + val chunk: u8x16 = *((text + at) as *u8x16); + var marks := chunk.equal(&newline).bits(); + while marks != 0 { + this.lines.append((at + trailing_zeros(marks) as u64 + 1) as u32); + marks = marks & (marks - 1); + } + held |= chunk.equal(&back).bits(); + at += 16; + } + returns = held != 0; + } + while at + 8 <= size { + val word := swar::load(text + at); + var marks := word.equal('\n'); + while marks.any() { + this.lines.append((at + marks.first() + 1) as u32); + marks = marks.rest(); + } + returns = returns || word.equal('\r').any(); + at += 8; + } + for k in at..size { + if text[k] == '\n' { + this.lines.append((k + 1) as u32); + } + returns = returns || text[k] == '\r'; + } + return returns; +} + +#! Creates a lexeme from the given start location in the source and the count. +#! @param this The source object to create a lexeme from. +#! @param start The starting index within the source to create the lexeme. +#! @param count The number of characters for the lexeme to be created. +#! @returns A strview of the lexeme requested from the source. +pub def source::make_lexeme(&this, start: u64, count: u64): strview { + return this.text.view().substr(start, count); +} + +#! The classes a byte may be of, as bits of `char_classes`. +enum cc : u8 { + space = 0x01, #! Spacing between tokens: ` `, and `\t` through `\r`. + start = 0x02, #! What a word begins with: a letter or `_`. + word = 0x04, #! What a word goes on with: a letter, a digit, or `_`. + digit = 0x08, #! What a number begins with. +} + +#! The classes of each byte, as bits of `cc`, worked out while compiling, so the +#! lexer asks what a byte is with one load. +const char_classes: u8[256] = make_char_classes(); + +#! Whether a byte goes on a name: a letter, a digit, or `_`. +#! @param byte The byte. +#! @returns Whether it does. +pub def is_word_byte(byte: u8): bool { + return (char_classes[byte as u64] & cc::word as u8) != 0; +} + +const def make_char_classes(): u8[256] { + var made: u8[256]; + for each in 0..256 { + val byte := each as u8; + if byte == ' ' || (byte >= '\t' && byte <= '\r') { + made[each] |= cc::space as u8; + } + if (byte >= 'a' && byte <= 'z') || (byte >= 'A' && byte <= 'Z') || byte == '_' { + made[each] |= cc::start as u8 | cc::word as u8; + } + if byte >= '0' && byte <= '9' { + made[each] |= cc::digit as u8 | cc::word as u8; + } + } + return made; +} + +# A set of character boolean checks that are specific to sakura. + +val u8::is_cmnt: bool { get => this == '#'; } +val u8::is_dot: bool { get => this == '.'; } +val u8::is_zero: bool { get => this == '0'; } +val u8::is_squote: bool { get => this == '\''; } +val u8::is_dquote: bool { get => this == '\"'; } +val u8::is_format: bool { get => this == '$'; } +val u8::is_escape: bool { get => this == '\\'; } +val u8::is_lbrace: bool { get => this == '{'; } +val u8::is_rbrace: bool { get => this == '}'; } +val u8::is_brace: bool { get => this.is_lbrace || this.is_rbrace; } +val u8::is_blank: bool { get => this == ' ' || this == '\t'; } + +#! Whether the byte continues a character of more than one byte, which UTF-8 +#! writes as `10xxxxxx`. +#! @param this The byte. +#! @returns Whether it does. +val u8::is_continuation: bool { get => (this & 0xC0) == 0x80; } + +#! Creates a source object of text held in memory rather than read from a file, +#! as an editor's unsaved buffer or a test's program. +#! @param path The path to report the text as. +#! @param text The text. +#! @returns The source object holding a copy of the text. +pub def source::from(path: strview, text: strview): source { + var result := source { + path = path, + text = without_mark(string::from(text, nothing {})), + lines = lines::new(nothing {}) + }; + result.finish(); + return result; +} diff --git a/analyzer/syntax.sakura b/analyzer/syntax.sakura new file mode 100644 index 00000000..c72da486 --- /dev/null +++ b/analyzer/syntax.sakura @@ -0,0 +1,365 @@ +#! @file syntax.sakura +#! @author John Christman (sorakatadzuma@gmail.com) +#! @copyright Malunal Studios, LLC. +#! @license MIT +#! +#! Contains the syntax type, which keeps the tokens, nodes, and extras of a +#! parsed file, its comments, and the documentation and starts of its +#! declarations. + +import std::containers; +module sakura::analyzer; + +#! Represents a parsed syntax for a given file. +#! +#! As the lexer reads the source code, it stores the tokens into this +#! structure, then as the parser builds new nodes, it stores those into this +#! structure too. +#! +#! Nodes and tokens are each kept as one vector per field, indexed alike, so a +#! pass reading one field, as the kind of every node, reads only that, and no +#! padding sits between fields. `node` and `token` are values gathered from +#! them, for reading one whole. +#! +#! What a token's kind or name says is not kept again: how many bytes a keyword +#! or a punctuator covers is its kind's, as `token_widths` says, and a name's is +#! its text's. Only the lengths of the rest, the literals, a few of every +#! hundred tokens, are kept, as `token_length` reads them. +pub struct syntax { + # Nodes, by index. + pub var node_kinds: vector; #! The kind of each node. + pub var node_tokens: vector; #! The token each says what it is by. + var node_lefts: vector; #! The first slot of each, which its kind's shape says the meaning of. + var node_rights: vector; #! The second slot of each. + var node_spans: vector; #! How many tokens past its own each was parsed through, or `syntax::wide`, where `wide_spans` holds how many. + + # How many tokens past its own each node spanning more than a byte counts was + # parsed through, a few of every thousand, as a document or a function body. + var wide_spans: keymap; #! How many, by the node. + + # What nodes hold beyond their two slots: records and runs. + var extras: vector; #! The records and runs, each where a slot says it begins. + + # Tokens, by index. + var token_kinds: vector; #! The kind of each token. + pub var token_offsets: vector; #! The byte of the text each begins at. + var token_names: vector; #! The ID of the name each is, or 0 where it is no word. + + # The tokens whose kind and name do not say how many bytes they cover, the + # literals, in order, and how many each covers. + var literal_tokens: vector; #! Each literal token, in increasing order. + var literal_lengths: vector; #! How many bytes each covers. + + # The documentation comments, `#!` lines, in order, and where each + # declaration begins, its attributes and `pub` included, which says which of + # them document it. + var docs: vector; #! The documentation comments. + var starts: keymap; #! The token each declaration begins at, by its node. + + # The other comments, in order, which are no part of the tree but are kept for + # the tools that write the text back out, as a formatter. + var comments: vector; #! The other comments. + + # How many nodes and extras the last whole parse left. A reparse leaves the + # nodes it replaced behind, unreachable, and these say when they are enough + # to parse whole again and let go of them. + var whole_nodes: u64; #! The node count the last whole parse left. + var whole_extras: u64; #! The extras count the last whole parse left. + + # How many times a reparse parsed the file whole again, which makes every + # node anew, so what was kept of the old ones by their indexes is no longer of + # them. + pub var parses: u32; #! How many times the file was parsed whole again. +} + +#! A line of documentation, `#!` and what follows it on its line. +pub struct doc { + var offset: u32; #! The byte of the text it begins at. + var length: u32; #! How many bytes it covers. + var token: u32; #! The token it is written before. +} + +#! A comment that is not documentation, `#` and what follows it on its line. +pub struct comment { + var offset: u32; #! The byte of the text it begins at. + var length: u32; #! How many bytes it covers. + var token: u32; #! The token after it. +} + +#! The documentation of a declaration: `count` lines from `first` of `docs`. +pub struct doc_range { + var first: u32; #! The first line, in `docs`. + var count: u32; #! How many lines. +} + +#! How many entries at the start of `extras` are 0, which stand for both an +#! empty run and a record whose slots are all absent, as large as the largest +#! record. +pub const syntax::zeros: u32 = 6; + +#! Creates a new instance of a syntax object. +#! @returns The instantiated syntax. +pub def syntax::new(): syntax { + var made := syntax { + node_kinds = vector::::new(), + node_tokens = vector::::new(), + node_lefts = vector::::new(), + node_rights = vector::::new(), + node_spans = vector::::new(), + wide_spans = keymap::new(), + extras = vector::::new(), + token_kinds = vector::::new(), + token_offsets = vector::::new(), + token_names = vector::::new(), + literal_tokens = vector::::new(), + literal_lengths = vector::::new(), + docs = vector::::new(), + starts = keymap::new(), + comments = vector::::new() + }; + + made.reset(); + return made; +} + +#! Lets go of every node and extra, leaving only what stands for absent: node 0, +#! an `error` node holding nothing, and the zeros at the start of `extras`. +#! @param this The syntax tree. +pub def syntax::reset(&mut this): void { + this.node_kinds.clear(); + this.node_tokens.clear(); + this.node_lefts.clear(); + this.node_rights.clear(); + this.node_spans.clear(); + this.wide_spans.clear(); + this.extras.clear(); + this.starts.clear(); + + this.add_node(nk::error, 0, 0, 0, 0); + this.extras.resize(syntax::zeros as u64); +} + +#! How many nodes there are, node 0 included. +#! @param this The syntax tree. +#! @returns The count. +pub val syntax::node_count: u64 { get => this.node_kinds.length; } + +#! How many tokens there are, the `eof` ending them included. +#! @param this The syntax tree. +#! @returns The count. +pub val syntax::token_count: u64 { get => this.token_kinds.length; } + +#! Appends a node. +#! @param this The syntax tree. +#! @param kind Its kind. +#! @param token The token it says what it is by. +#! @param left Its first slot. +#! @param right Its second slot. +#! @param end The last token of what it was parsed from. +#! @returns Its index. +pub def syntax::add_node(&mut this, kind: nk, token: u32, left: u32, right: u32, end: u32): u32 { + this.node_kinds.append(kind); + this.node_tokens.append(token); + this.node_lefts.append(left); + this.node_rights.append(right); + this.node_spans.append(0); + val at := (this.node_kinds.length - 1) as u32; + this.set_node_end(at, end); + return at; +} + +#! A node's span, in a byte, that says `wide_spans` holds it. +pub const syntax::wide: u8 = 255; + +#! The last token of what the node was parsed from. +#! @param this The syntax tree. +#! @param at The node's index. +#! @returns The token. +pub def syntax::node_end(&this, at: u32): u32 { + val span := this.node_spans[at]; + return this.node_tokens[at] + (span != syntax::wide ? span as u32 : this.wide_spans.get_or(&(at as u64), 0)); +} + +#! Says the last token of what the node was parsed from, which its token is +#! set before. +#! @param this The syntax tree. +#! @param at The node's index. +#! @param end The token. +pub def syntax::set_node_end(&mut this, at: u32, end: u32): void { + # Held as a count past its token, which wraps where it ends before it, so + # adding the count back gives the end. + val span := end - this.node_tokens[at]; + if span < syntax::wide as u32 { + if this.node_spans[at] == syntax::wide { + this.wide_spans.remove(&(at as u64)); + } + this.node_spans[at] = span as u8; + return; + } + this.node_spans[at] = syntax::wide; + this.wide_spans.set(at as u64, span); +} + +#! The node at the index, gathered from its fields. +#! @param this The syntax tree. +#! @param at The node's index. +#! @returns The node. +pub def syntax::node(&this, at: u32): node { + return node { + kind = this.node_kinds[at], + token = this.node_tokens[at], + left = this.node_lefts[at], + right = this.node_rights[at], + end = this.node_end(at) + }; +} + +#! Appends a token of the kind, spanning `length` bytes from `offset`, which is +#! the word of the ID `name`, or 0 where it is no word. +#! @param this The syntax tree. +#! @param kind Its kind. +#! @param offset The byte of the text it begins at. +#! @param length How many bytes it covers. +#! @param name The ID of the word it is, or 0. +pub def syntax::add_token(&mut this, kind: tk, offset: u32, length: u32, name: u32): void { + if kind != tk::name && kind.width == 0 && length != 0 { + this.literal_tokens.append(this.token_kinds.length as u32); + this.literal_lengths.append(length); + } + this.token_kinds.append(kind); + this.token_offsets.append(offset); + this.token_names.append(name); +} + +#! How many bytes the token covers: as many as its kind says, or its name's +#! text, or as were kept of a literal. +#! @param this The syntax tree. +#! @param at The token's index. +#! @param names The names the file was lexed with, or joined. +#! @returns How many. +pub def syntax::token_length(&this, at: u32, names: &names): u32 { + val kind := this.token_kinds[at]; + val width := kind.width; + return width if width != 0; + return names.text(this.token_names[at]).length as u32 if kind == tk::name; + return this.literal_length(at); +} + +#! How many bytes a literal token covers, or 0 for a token not kept as one, as +#! `eof`. +#! @param this The syntax tree. +#! @param at The token's index. +#! @returns How many. +def syntax::literal_length(&this, at: u32): u32 { + val found := this.literal_tokens.view().lower_bound(&at); + return found < this.literal_tokens.length && this.literal_tokens[found] == at ? this.literal_lengths[found] : 0; +} + +#! Gives each token the ID of its name in another table of names, as where a +#! file lexed with names of its own joins those of the program. +#! @param this The syntax tree. +#! @param ids The ID in the other table of each name, by its ID in the one +#! the file was lexed with. +pub def syntax::rename(&mut this, ids: span): void { + for i in 0..this.token_names.length { + this.token_names[i] = ids[this.token_names[i] as u64]; + } +} + +#! The token at the index, gathered from its fields. +#! @param this The syntax tree. +#! @param at The token's index. +#! @param names The names the file was lexed with, or joined, which give a +#! name's length. +#! @returns The token. +pub def syntax::token(&this, at: u32, names: &names): token { + return token { + kind = this.token_kinds[at], + offset = this.token_offsets[at], + length = this.token_length(at, names), + name = this.token_names[at] + }; +} + +#! Makes room for the tokens lexing text of so many bytes makes, which are +#! seldom more than one for every four bytes, so lexing seldom moves them; the +#! room left is let go of once lexing ends, as `fit_tokens` does. +#! @param this The syntax tree. +#! @param bytes How many bytes the text holds. +pub def syntax::reserve_for_text(&mut this, bytes: u32): void { + val tokens := this.token_count + bytes as u64 / 4 + 16; + this.token_kinds.reserve(tokens); + this.token_offsets.reserve(tokens); + this.token_names.reserve(tokens); +} + +#! Makes room for the nodes and extras parsing the tokens makes, which are +#! seldom more than three quarters of the tokens, so parsing seldom moves them; +#! the room left is let go of once parsing ends, as `fit_nodes` does. +#! @param this The syntax tree. +pub def syntax::reserve_for_tokens(&mut this): void { + val tokens := this.token_count; + val nodes := this.node_count + tokens * 3 / 4 + 16; + this.node_kinds.reserve(nodes); + this.node_tokens.reserve(nodes); + this.node_lefts.reserve(nodes); + this.node_rights.reserve(nodes); + this.node_spans.reserve(nodes); + this.extras.reserve(this.extras.length + tokens * 3 / 4 + 16); +} + +#! Lets go of the room the tokens were given beyond those lexed, which is +#! about a third of it. +#! @param this The syntax tree. +pub def syntax::fit_tokens(&mut this): void { + fitted(&mut this.token_kinds); + fitted(&mut this.token_offsets); + fitted(&mut this.token_names); + fitted(&mut this.literal_tokens); + fitted(&mut this.literal_lengths); +} + +#! Lets go of the room the nodes and extras were given beyond those parsed. +#! @param this The syntax tree. +pub def syntax::fit_nodes(&mut this): void { + fitted(&mut this.node_kinds); + fitted(&mut this.node_tokens); + fitted(&mut this.node_lefts); + fitted(&mut this.node_rights); + fitted(&mut this.node_spans); + fitted(&mut this.extras); +} + +# Moves the items into a block of their own size, where the one they are in +# has room for more than an eighth as many again. +def fitted(items: &mut vector): void { + return if items.capacity - items.length <= items.length / 8 + 16; + var made := vector::::new(); + made.reserve(items.length); + made.extend(items.view()); + items = move(&mut made); +} + +#! The token a declaration begins at, its attributes and `pub` included, or its +#! own token where it was not recorded. +#! @param this The syntax tree. +#! @param at The declaration's node. +#! @returns The token. +pub def syntax::start_of(&this, at: u32): u32 { + return this.starts.get_or(&(at as u64), this.node_tokens[at]); +} + +#! The documentation comments written before a declaration. +#! @param this The syntax tree. +#! @param at The declaration's node. +#! @returns The lines, which are none where it has no documentation. +pub def syntax::docs_of(&this, at: u32): doc_range { + val start := this.starts.get(&(at as u64)) else { return doc_range {}; }; + val low := this.docs.view().partition_point(def(each: &doc): bool { return each.token < start; }); + + var count: u32 = 0; + while low + (count as u64) < this.docs.length && this.docs[low + count as u64].token == start { + count++; + } + return doc_range { first = low as u32, count = count }; +} diff --git a/analyzer/token.sakura b/analyzer/token.sakura new file mode 100644 index 00000000..67d34c9d --- /dev/null +++ b/analyzer/token.sakura @@ -0,0 +1,274 @@ +#! @file token.sakura +#! @author John Christman (sorakatadzuma@gmail.com) +#! @copyright Malunal Studios, LLC. +#! @license MIT +#! +#! Contains the token type, which is a kind of token and the text it was read +#! from, and `tk`, the kinds of token. + +module sakura::analyzer; + +#! Defines a source code token. +#! +#! A token is the kind and location of a piece of text within some source code. The +#! type is used in the parser to identify constructs and build them into an +#! abstract syntax tree. The offset of the token points to the index within the +#! source code that token resides. The offset can be used with the +#! `source::lines` vector to identify a place within the source code that the +#! token resides. +pub struct token { + var offset: u32; #! Where it begins in the source text. + var length: u32; #! How many bytes of the source text it spans. + var name: u32; #! The ID of the word it is, or 0 where it is no word. + var kind: tk; #! Its kind. +} + +#! The kinds of token. +#! +#! They are grouped by what they are: the keywords, then the literals, the +#! pieces of an interpolated string, and the punctuators. `true`, `false`, and +#! `null` are keywords that are also literals, and they are the last keywords, +#! so `kw_beg` to `kw_end` spans every keyword. +#! +#! `eof` marks the end of the source, and `bad_number` and `bad_quote` are what +#! the lexer gives for a number or a quote it could not make sense of, so it +#! goes on and the parser reports them where they are. The lexer almost never +#! fails otherwise. +pub enum tk : u8 { + # Keywords + kw_imp, kw_mod, kw_extern, kw_pub, kw_const, kw_var, kw_val, kw_def, + kw_mut, kw_ret, kw_if, kw_else, kw_for, kw_in, kw_while, kw_break, + kw_cont, kw_type, kw_enum, kw_struct, kw_union, kw_trait, kw_as, kw_is, + kw_not, kw_match, kw_when, kw_where, kw_true, kw_false, kw_null, + + # Literals + name, unknown, signed, unsigned, float, char, string, istring, + + # Pieces of an interpolated string with holes, between which come the tokens of + # each hole: `$"text{`, then `}text{` between two holes, then `}text"`. + istring_beg, istring_mid, istring_end, + + # Punctuators + lparen, rparen, lbrace, rbrace, lbracket, rbracket, semicolon, comma, + dot, cascade, spread, colon, quest, attr, assign, arrow, + equals, negate, noteq, less, lesseq, more, moreeq, plus, + minus, star, slash, modulo, logand, logor, bitand, bitor, + bitxor, bitnot, lshift, rshift, scope, pluseq, minuseq, stareq, + slasheq, moduloeq, logandeq, logoreq, bitandeq, bitoreq, bitxoreq, bitnoteq, + lshifteq, rshifteq, increment, decrement, cascadeeq, + + # End of file marker. + #! The end of the source. + eof, + + # Error tokens. + #! A number written wrongly. + bad_number, + #! A string or character with no closing quote. + bad_quote, + + # Not a kind: how many there are, which sizes the tables indexed by kind. + #! How many kinds there are, which sizes the tables indexed by kind; not a + #! kind itself. + count, + + # Ranges. + #! The first keyword. + kw_beg = tk::kw_imp, + #! The last keyword. + kw_end = tk::kw_null, +} + +#! How many bytes a token of the kind covers, where its kind says: those of a +#! keyword or a punctuator, or 0 for a kind of any length, as a name or a +#! literal. +#! @param this The kind of token. +#! @returns How many. +pub val tk::width: u32 { get => token_widths[this as u64] as u32; } + +#! How many bytes a token of each kind covers, where its kind says, worked out +#! while compiling: a keyword's word, and a punctuator's bytes. +const token_widths: u8[tk::count as u64] = make_token_widths(); + +const def make_token_widths(): u8[tk::count as u64] { + var made: u8[tk::count as u64]; + for &each in _keywords { made[each.kind as u64] = each.text.length as u8; } + for each in [ + tk::lparen, tk::rparen, tk::lbrace, tk::rbrace, tk::lbracket, tk::rbracket, tk::semicolon, + tk::comma, tk::dot, tk::colon, tk::quest, tk::attr, tk::assign, tk::negate, + tk::less, tk::more, tk::plus, tk::minus, tk::star, tk::slash, tk::modulo, + tk::bitand, tk::bitor, tk::bitxor, tk::bitnot + ] { made[each as u64] = 1; } + for each in [ + tk::cascade, tk::scope, tk::arrow, tk::equals, tk::noteq, tk::lesseq, + tk::moreeq, tk::logand, tk::logor, tk::lshift, tk::rshift, tk::pluseq, + tk::minuseq, tk::stareq, tk::slasheq, tk::moduloeq, tk::bitandeq, tk::bitoreq, + tk::bitxoreq, tk::bitnoteq, tk::increment, tk::decrement + ] { made[each as u64] = 2; } + for each in [tk::spread, tk::cascadeeq, tk::logandeq, tk::logoreq, tk::lshifteq, tk::rshifteq] { + made[each as u64] = 3; + } + return made; +} + +#! Whether the token compares, as `==` or `<` do. +#! @param this The token. +#! @returns Whether it does. +pub def tk::compares(&this): bool { + return this == tk::equals || this == tk::noteq || this == tk::less + || this == tk::lesseq || this == tk::more || this == tk::moreeq; +} + +#! The operator a compound assignment applies, as `+` of `+=`, or the token. +#! @param this The token. +#! @returns The operator. +pub def tk::applied(&this): tk { + return match this { + tk::pluseq => tk::plus, + tk::minuseq => tk::minus, + tk::stareq => tk::star, + tk::slasheq => tk::slash, + tk::moduloeq => tk::modulo, + tk::bitandeq => tk::bitand, + tk::bitoreq => tk::bitor, + tk::bitxoreq => tk::bitxor, + tk::lshifteq => tk::lshift, + tk::rshifteq => tk::rshift, + else => this + }; +} + +# Match based token kind extensions. +# Given the current token kind and the next character, produces the next token +# kind. This assists the lexer in matching greedily. `>>`, `>=`, and `>>=` are +# matched as well, though they may close type arguments instead, so the lexer +# follows each with tokens of what is left of it, as `lexer` says. +def tk::from(&this, char: u8): tk { + return match char { + # Single + '(' => tk::lparen, + ')' => tk::rparen, + '{' => tk::lbrace, + '}' => tk::rbrace, + '[' => tk::lbracket, + ']' => tk::rbracket, + ';' => tk::semicolon, + ',' => tk::comma, + '?' => tk::quest, + '@' => tk::attr, + + # Multi + '.' => tk::dot, + ':' => tk::colon, + '=' => tk::assign, + '!' => tk::negate, + '<' => tk::less, + '>' => tk::more, + '+' => tk::plus, + '-' => tk::minus, + '*' => tk::star, + '/' => tk::slash, + '%' => tk::modulo, + '&' => tk::bitand, + '|' => tk::bitor, + '^' => tk::bitxor, + '~' => tk::bitnot, + else => tk::unknown + } if this == tk::unknown; + + return match this { + # Doubles + tk::dot => match char { + '.' => tk::cascade, + else => tk::unknown + }, + tk::colon => match char { + ':' => tk::scope, + else => tk::unknown + }, + tk::assign => match char { + '=' => tk::equals, + '>' => tk::arrow, + else => tk::unknown + }, + tk::negate => match char { + '=' => tk::noteq, + else => tk::unknown + }, + tk::less => match char { + '=' => tk::lesseq, + '<' => tk::lshift, + else => tk::unknown + }, + tk::more => match char { + '=' => tk::moreeq, + '>' => tk::rshift, + else => tk::unknown + }, + tk::plus => match char { + '=' => tk::pluseq, + '+' => tk::increment, + else => tk::unknown + }, + tk::minus => match char { + '=' => tk::minuseq, + '-' => tk::decrement, + else => tk::unknown + }, + tk::star => match char { + '=' => tk::stareq, + else => tk::unknown + }, + tk::slash => match char { + '=' => tk::slasheq, + else => tk::unknown + }, + tk::modulo => match char { + '=' => tk::moduloeq, + else => tk::unknown + }, + tk::bitand => match char { + '=' => tk::bitandeq, + '&' => tk::logand, + else => tk::unknown + }, + tk::bitor => match char { + '=' => tk::bitoreq, + '|' => tk::logor, + else => tk::unknown + }, + tk::bitxor => match char { + '=' => tk::bitxoreq, + else => tk::unknown + }, + tk::bitnot => match char { + '=' => tk::bitnoteq, + else => tk::unknown + }, + + # Triples + tk::cascade => match char { + '.' => tk::spread, + '=' => tk::cascadeeq, + else => tk::unknown + }, + tk::lshift => match char { + '=' => tk::lshifteq, + else => tk::unknown + }, + tk::rshift => match char { + '=' => tk::rshifteq, + else => tk::unknown + }, + tk::logand => match char { + '=' => tk::logandeq, + else => tk::unknown + }, + tk::logor => match char { + '=' => tk::logoreq, + else => tk::unknown + }, + else => tk::unknown + }; +} + diff --git a/analyzer/walker.sakura b/analyzer/walker.sakura new file mode 100644 index 00000000..92876f01 --- /dev/null +++ b/analyzer/walker.sakura @@ -0,0 +1,86 @@ +#! @file walker.sakura +#! @author John Christman (sorakatadzuma@gmail.com) +#! @copyright Malunal Studios, LLC. +#! @license MIT +#! +#! Contains the walker, which finds the nodes a node holds through its shape, +#! so every pass can walk the tree without knowing each kind of node. + +module sakura::analyzer; + + +#! Appends the nodes a node holds to `into`, in the order its shape lists its +#! slots: the node of each `node` slot that is not absent, every node of each +#! `run`, and those of its record, likewise. +#! +#! This is how every pass walks the tree without knowing each kind of node, as +#! the shapes say what each kind holds. +#! @param this The syntax tree. +#! @param at The node. +#! @param into Where the nodes are appended. +pub def syntax::children(&this, at: u32, into: &mut vector): void { + return if at == 0; + + # Only the slots are read, rather than the whole node, whose end is worked + # out apart. + val shape := this.node_kinds[at].shape; + this.slot_children(shape.left, this.node_lefts[at], shape.record, into); + this.slot_children(shape.right, this.node_rights[at], shape.record, into); +} + +#! The nodes the slot holds, where it holds `value`. +#! @param this The syntax tree. +#! @param kind What the slot holds. +#! @param value The slot's value. +#! @param record The shape of the node's record, where the slot holds one. +#! @param into Where the nodes are appended. +def syntax::slot_children( + &this, + kind: slot, + value: u32, + record: span, + into: &mut vector +): void { + match kind { + slot::node => { + if value != 0 { + into.append(value); + } + } + slot::run, slot::bounds => { + into.extend(this.run_view(value)); + } + slot::extra => { + for i in 0..record.length { + val inner := this.extras[value as u64 + i]; + this.slot_children(record[i], inner, no_record, into); + } + } + else => {} + } +} + +#! How many nodes the run at `extras[run]` holds. +#! @param this The syntax tree. +#! @param run Where the run begins. +#! @returns How many nodes it holds. +pub def syntax::run_length(&this, run: u32): u32 { + return this.extras[run]; +} + +#! The node at the index of the run at `extras[run]`. +#! @param this The syntax tree. +#! @param run Where the run begins. +#! @param index The position, below its length. +#! @returns The node. +pub def syntax::run_at(&this, run: u32, index: u32): u32 { + return this.extras[run as u64 + 1 + index as u64]; +} + +#! The nodes of the run at `extras[run]`, where they are. +#! @param this The syntax tree. +#! @param run Where the run begins. +#! @returns The nodes, a view only good until the syntax grows, as by parsing. +pub def syntax::run_view(&this, run: u32): span { + return span::::over(this.extras.view().data + run as u64 + 1, this.extras[run] as u64); +} diff --git a/blossomfile b/blossomfile new file mode 100644 index 00000000..42e69fbf --- /dev/null +++ b/blossomfile @@ -0,0 +1,173 @@ +name: sakurac +gpid: malunal +semv: 1.0.0 + +options: + level: 2 + debug: false + +requires: +- https://git.malunal.studio/sakura/std@v1.0.0 +- https://git.malunal.studio/sakura/binary@v1.0.0 + +targets: +- name: sakurac + type: program + level: ${level} + petal: ${debug} + deps: + - binary.elf + - binary.dwarf + - binary.pe + - binary.pdb + - binary.amd64 + - sakura.analyzer + - sakura.compiler + - sakura.machine + - sakura.native + - sakura.server + - std.args + - std.io + - std.json + - std.process + - std.thread + srcs: + - entry.sakura + +# The compiler's parts, each a library of its own in the folder of its name. +- name: sakura.analyzer + type: library + root: ./analyzer + deps: [std.containers, std.io, std.thread] + +- name: sakura.compiler + type: library + root: ./compiler + deps: [std.allocators, std.containers, std.thread, sakura.analyzer] + +- name: sakura.machine + type: library + root: ./machine + deps: [std.containers, std.io, std.thread, std.time, sakura.analyzer, sakura.compiler] + +- name: sakura.native + type: library + root: ./native + deps: + - std.containers + - std.io + - std.thread + - sakura.analyzer + - sakura.compiler + - binary.amd64 + - binary.elf + - binary.dwarf + - binary.pe + - binary.pdb + +- name: sakura.server + type: library + root: ./server + deps: [std.io, std.json, std.net, std.process, std.serial, sakura.analyzer, sakura.machine] + +tests: +- name: sakurac.tests + type: program + deps: [sakura.analyzer, std.io, std.process, std.testing] + srcs: [tests/main.sakura, tests/libraries.sakura] + +# Each part's tests, in the folder of its name. Those of the native backend +# evaluate constants on the machine, as `sakurac build` does, and find `core`, +# `system`, and `runtime` as the language server does. +- name: sakura.analyzer.tests + type: program + deps: [sakura.analyzer, std.testing] + srcs: [tests/main.sakura, tests/analyzer/*.sakura] + +- name: sakura.compiler.tests + type: program + deps: [sakura.analyzer, sakura.compiler, std.containers, std.io, std.testing] + srcs: [tests/main.sakura, tests/compiler/*.sakura] + +- name: sakura.machine.tests + type: program + deps: [sakura.analyzer, sakura.compiler, sakura.machine, std.io, std.testing] + srcs: [tests/main.sakura, tests/machine/*.sakura] + +# The machine's tests again, built and run as an executable, where the machine +# compiles the functions it runs to the processor's code, as on Windows. +- name: sakura.machine.native + type: program + runs: native + deps: [sakura.analyzer, sakura.compiler, sakura.machine, std.io, std.testing] + srcs: [tests/main.sakura, tests/machine/*.sakura] + +- name: sakura.native.tests + type: program + deps: + - sakura.analyzer + - sakura.compiler + - sakura.machine + - sakura.server + - binary.amd64 + - binary.elf + - sakura.native + - std.io + - std.process + - std.testing + srcs: [tests/main.sakura, tests/native/*.sakura] + +- name: sakura.server.tests + type: program + deps: [sakura.analyzer, sakura.server, std.io, std.testing] + srcs: [tests/main.sakura, tests/server/*.sakura] + +# The tests of `core` and `system`, which ship with the compiler, built and run +# as executables. +- name: sakurac.core + type: program + runs: native + deps: [std.containers, std.io, std.math, std.process, std.serial, std.testing, std.thread] + srcs: [tests/core/*.sakura] + +# The corpus, each program run by the compiler just built, over the standard +# library's repository beside this one. + +- name: sakurac.corpus + type: program + checks: false + srcs: [tools/corpus.sakura] + deps: [std.io, std.process] + args: ["${bin}/sakurac", run, --lib, std=../std] + +- name: sakurac.checked + type: program + checks: false + srcs: [tools/corpus.sakura] + deps: [std.io, std.process] + args: [--dir, tests/checked, "${bin}/sakurac", run, --lib, std=../std] + +- name: sakurac.memory + type: program + checks: false + srcs: [tools/corpus.sakura] + deps: [std.io, std.process] + args: [--dir, tests/memory, "${bin}/sakurac", run, --lib, std=../std, --checks] + +exports: +- sakura.analyzer +- sakura.compiler +- sakura.machine +- sakura.native +- sakura.server + +install: +- !include ./core +- !include ./system +- !include ./runtime + +package: + lic: MIT + desc: The Sakura programming language compiler. + auth: John Christman + url: https://git.malunal.studio/sakura/sakurac diff --git a/compiler/README.md b/compiler/README.md new file mode 100644 index 00000000..214f0daa --- /dev/null +++ b/compiler/README.md @@ -0,0 +1,136 @@ +# sakura::compiler + +`sakura::compiler` is the middle of the Sakura compiler. It lowers a program +that `sakura::analyzer` has checked to intermediate code: values each assigned +once, in blocks that take parameters where control flow joins. It optimizes +that code, and assembles each function into the code `sakura::machine` runs. +The compiler's back end builds executables from the same intermediate code. + +## Using it + +Require this repository, which exports each of the compiler's libraries, and name this +one among a target's `deps` with the analyzer, which it reads itself: + +```yaml +requires: +- https://git.malunal.studio/sakura/std@v1.0.0 +- https://git.malunal.studio/sakura/sakurac@v1.0.0 + +targets: +- name: app + type: program + deps: [sakura.analyzer, sakura.compiler, std.io] +``` + +A program is lowered from the checker that checked it, as `sakura::analyzer`'s +README checks one: + +```sakura +import std::io; +import sakura::analyzer; +import sakura::compiler; + +# Checks a file importing nothing, with `core`, whose folder is given, then +# lowers it, optimizes it at a level, and prints the code of the function of a +# name. Gives whether it could. +def lower(path: strview, core: strview, level: u32, name: strview): bool { + var paths := vector::::new(); + paths.append(string::from(path, nothing {})); + paths.append(string::from(builtin_path, nothing {})); + every_file(core, &mut paths); + + var names := names::new(); + var notes := vector::::new(); + var sources := vector::::new(); + var syntaxes := vector::::new(); + var roots := vector::::new(); + sources.reserve(paths.length); + syntaxes.reserve(paths.length); + for i in 0..paths.length { + val at := paths[i].view(); + sources.append(at == builtin_path ? source::from(at, builtin_text) : source::open(at)); + syntaxes.append(syntax::new()); + var lexing := lexer::new(sources.at(i), &mut names, &mut notes, i as u32); + lexing.tokenize_all(syntaxes.at(i)); + var parsing := parser::new(syntaxes.at(i), &names, &mut notes, i as u32); + roots.append(parsing.parse()); + } + var checker := checker::new(&mut names, &mut notes); + for i in 0..paths.length { + checker.add(sources.at(i), syntaxes.at(i), roots.at(i)); + } + checker.check(); + return false if notes.length != 0; + + var lowered := lowerer::new(&mut checker, lowering { verify = true, level = level }); + lowered.compile(); + for &each in lowered.problems { + println(each); + } + return false if lowered.problems.length != 0; + lowered.drop_unreached_functions(); + for &function in lowered.program.functions { + if function.lowered && function.name.view() == name { + print(function.body.print()); + } + } + return true; +} +``` + +For `def square(x: i32): i32 { return x * x; }` at level 0, it prints: + +``` +b0(v0: i64): + v1 = mul v0, v0 + v2 = wrap v1, 32, signed + ret v2 +``` + +The values of constants are computed by running code on `sakura::machine`. +Its `evaluate` gives the `outcomes`, which are set as the lowerer's `evaluated` +before `compile`. + +## What it holds + +- **Lowering**: `lowerer` lowers each function once something that runs names + it, by `lowering`'s options. `emitter/` has a file for each part of the + language. + - `layouts` lays out types as C lays out the same fields. + - `dispatch` holds the vtables of traits. + - `globals` gives the globals their values before `main` runs. + - `escapes` and `flows` find where each reference may go, so a local whose + address is kept lives in a cell of the frame. +- **Intermediate code** (`intermediate/`): `code`, a function's blocks, + instructions and cells. `builder` makes it in one pass. `verifier` checks it + is well formed. `printer` writes it as text. +- **Optimizing** (`optimizer/`): + - `-O1` simplifies, cleans up control flow, numbers values, and removes dead + code. + - `-O2` also inlines and promotes cells to values. + - Below `-O2`, calls of `@inline` functions are inlined all the same, and at + `-O0` that is all that changes. + - At `-O1` and above, a function asking which vector instructions the + processor has, or counting a word's bits, gets a version for x86-64-v3's, + and an executable's stores filling 16 bytes of a struct are merged into one + of a vector once the rest is done. + - Each pass leaves the code well formed. +- **The machine's code**: `bytecode` assembles each function into the words + `sakura::machine` runs. +- **Constants**: the program that computes the constants and the `if const` + conditions the checker left undecided. +- **Threads**: `workers` shares functions among threads, which optimize and + assemble them into the same bytes however many there are. + +## Testing + +From the repository's root, `blossom test` runs them as `sakura.compiler.tests`, or: + +```sh +sakurac run --lib sakura::analyzer=analyzer --lib sakura::compiler=compiler \ + tests/main.sakura tests/compiler/*.sakura +``` + +The tests are declared within the module. Most check and lower a small program +and compare its printed code with what is expected, after the verifier has +found nothing wrong with it. diff --git a/compiler/atomics.sakura b/compiler/atomics.sakura new file mode 100644 index 00000000..f6da1d60 --- /dev/null +++ b/compiler/atomics.sakura @@ -0,0 +1,71 @@ +#! @file atomics.sakura +#! @author John Christman (sorakatadzuma@gmail.com) +#! @copyright Malunal Studios, LLC. +#! @license MIT +#! +#! Contains the operations of atomics, as `core::atomic` and both compilers number +#! them, and the orders they take, as `core::order` does. + +module sakura::compiler; + + +# The operations an `atomic` instruction works, its `aux`. Each takes the address +# first, but a fence, which takes none, and its orders last. +pub const atomic_load: u32 = 0; #! (address, order): what the address holds. +pub const atomic_store: u32 = 1; #! (address, value, order): writes the value, giving nothing. +pub const atomic_exchange: u32 = 2; #! (address, value, order): writes the value, giving what was there. +pub const atomic_compare_exchange: u32 = 3; #! (address, expected, desired, success, failure): writes `desired` where it holds `expected`, giving what was there. +pub const atomic_add: u32 = 4; #! (address, operand, order): adds, wrapping, giving what was there. +pub const atomic_sub: u32 = 5; #! Subtracts, wrapping. +pub const atomic_and: u32 = 6; #! Keeps the bits both have. +pub const atomic_or: u32 = 7; #! Keeps the bits either has. +pub const atomic_xor: u32 = 8; #! Keeps the bits one has. +pub const atomic_min: u32 = 9; #! Keeps the less, compared as the access is, signed or unsigned. +pub const atomic_max: u32 = 10; #! Keeps the greater. +pub const atomic_fence: u32 = 11; #! (order): orders the reads and writes around it, giving nothing. + +#! Set in an `atomic` instruction's `imm`, beside its access, where the integer +#! is unsigned, which the access alone does not say of 64 bits. +pub const atomic_unsigned: u64 = 0x100; + +#! The access an `atomic` instruction reads and writes as. +#! @param imm Its `imm`. +#! @returns The access. +pub def atomic_access(imm: u64): access { + return (imm & 0xFF) as access; +} + +#! Whether an `atomic` instruction compares as signed integers do. +#! @param imm Its `imm`. +#! @returns Whether it does. +pub def atomic_signed(imm: u64): bool { + val how := atomic_access(imm); + return (imm & atomic_unsigned) == 0 && (how == access::i8 || how == access::i16 || how == access::i32 || how == access::i64); +} + +# The orders, as `core::order` numbers them. +pub const order_relaxed: u64 = 0; +pub const order_acquire: u64 = 1; +pub const order_release: u64 = 2; +pub const order_acq_rel: u64 = 3; +pub const order_seq_cst: u64 = 4; + +#! The name of each atomic operation, as the printed code writes it. +pub const atomic_names: strview[12] = [ + "load", "store", "exchange", "compare_exchange", "add", "sub", "and", "or", "xor", "min", "max", "fence" +]; + +#! Whether an atomic operation gives what the address held. +#! @param operation The operation. +#! @returns Whether it does. +pub def atomic_gives(operation: u32): bool { + return operation != atomic_store && operation != atomic_fence; +} + +#! Whether an atomic operation is one of those `core::atomic`'s integers alone +#! have, which read, combine, and write. +#! @param operation The operation. +#! @returns Whether it is. +pub def atomic_combines(operation: u32): bool { + return operation >= atomic_add && operation <= atomic_max; +} diff --git a/compiler/bytecode.sakura b/compiler/bytecode.sakura new file mode 100644 index 00000000..4f6835a5 --- /dev/null +++ b/compiler/bytecode.sakura @@ -0,0 +1,1592 @@ +#! @file bytecode.sakura +#! @author John Christman (sorakatadzuma@gmail.com) +#! @copyright Malunal Studios, LLC. +#! @license MIT +#! +#! Contains the code the machine runs, made from each function's intermediate +#! code. Every value is held in a word of the frame, and values whose lives do +#! not overlap share one, as a linear scan over where each is held finds. What +#! a block takes is moved into its words on each edge into it. Cells follow the +#! words, and the parameters, which a call copies into the frame of the +#! function it calls, come first. +#! +#! The code is words: an operation, then its operands, most of them words of +#! the frame. Where in the source each instruction is from is kept beside it, +#! for the trace of a fault. +#! +#! Where the machine has an operation doing the work of two, the code uses it: +#! a constant fitting a word of the code is taken into the instruction reading +#! it, and a comparison only a branch or a check reads, or an addition only a +#! load or a store of a byte reads as its address, is made part of that, where +#! that is, so it reads its operands there. A constant every instruction +#! reading takes so is not made at all, nor what is made part of another. The +#! last move of an edge, or an addition of a constant just before a block's +#! jump, jumps as the jump following it would. + +import std::containers; +module sakura::compiler; + + +#! The operations of the machine's code, each with the operands it is followed +#! by. A frame word is written as its index, a label as the place in the code +#! it stands for, and a word of 64 bits as its low and then its high half. +pub enum bc : u8 { + konst, #! dst, low, high: a word. + move, #! dst, src: copies a word. + + # Operators of two words, dst, a, b, in the order `op` declares them. + add, sub, mul, divs, divu, rems, remu, band, bor, bxor, shl, shrs, shru, + eq, ne, lts, ltu, les, leu, eqsu, ltsu, lesu, ltus, leus, + fadd, fsub, fmul, fdiv, frem, feq, fne, flt, fle, + + # Operators of one word, dst, a, in the order `op` declares them. + neg, bnot, lnot, fneg, itof, utof, ftoi, ftou, fsingle, fsqrt, ones, clz, ctz, bswap, + wrap, #! dst, a, bits, signed: the word narrowed to its bits. + select, #! dst, condition, a, b: `a` where the condition is not zero, and `b` where it is. + + cell, #! dst, offset: the address that many bytes into the frame. + global, #! dst, offset: the address that many bytes into the globals. + datum, #! dst, datum, offset: the address that many bytes into a datum. + + # Reading memory, dst, address, offset, each as its access says. + load_i8, load_u8, load_i16, load_u16, load_i32, load_u32, load_i64, load_f32, + # Writing memory, address, offset, value, each as wide as it says. + store_8, store_16, store_32, store_64, store_f32, + + copy, #! to, from, size: copies bytes. + clear, #! address, size: zeroes bytes. + allocate, #! dst, size, uncleared: memory the program gives back itself, zeroed unless uncleared is 1. + release, #! address: gives memory back. + resize, #! dst, address, size: memory holding what the address's did. + + call, #! function, argc, args..., resc, results... + call_trait, #! signature, slot, argc, args..., resc, results... + call_value, #! signature, argc, args..., resc, results... + call_c, #! signature, argc, args..., resc, results... + c_address, #! dst, index: the address of a C function. + callback, #! dst, function: the address C calls a function through. + + equal, #! dst, a, b, layout: whether the values at the addresses are equal. + retrait, #! dst, vtable, map: the vtable a reference to another trait takes. + check, #! condition, fault: stops the program where the word is zero. + + syscall, #! dst, number, a, b, c, d, e, f: what the kernel gives. + frame, #! dst: the frame pointer, in an executable. + image, #! dst: the image an executable was built with. + environ, #! dst: where the system put the variables the program started with. + signals, #! dst: the signals that came since last asked. + catch, #! dst, number: has the signal noted. + safepoint, #! function: calls it where a signal the program handles came. + exit, #! code: ends the program with the status. + abort, #! Ends the program at once, reporting where it was. + fault, #! pointer, length: ends the program at once, reporting the text and where it was. + + format, #! Begins text. + format_text, #! datum: adds the datum's bytes. + format_value, #! layout, count, words...: adds a value. + format_bytes, #! pointer, length: adds the bytes. + format_owned, #! pointer, length: the text made, in memory the program gives back. + + jump, #! label. + jump_if, #! condition, label: goes there where the word is not zero. + jump_zero, #! condition, label: goes there where the word is zero. + switch, #! value, count, (low, high, label)..., label: goes where the word is the case. + ret, #! count, words...: returns the words. + ret_memory, #! address: returns the memory there. + trap, #! fault: stops the program. + trap_word, #! word: stops the program with the fault the word is. + unreachable, #! Is never reached. + + ready, #! evaluation: stops unless the constant is evaluated, while compiling. + reach, #! pointer, count, size: stops unless the elements are memory the program holds, while compiling. + same, #! a, b: stops unless the pointers are within the same memory, while compiling. + + atomic, #! dst, operation, imm, address, a, b: an atomic operation, of the access and sign `imm` gives, on the address, with the operands `a` and `b`. + start, #! dst, function, environment, context: starts a thread running the function value, given the context. + + # Operations doing the work of two of those above, where code does it often. + # A constant is a word of the code standing for the 64 bits its sign extends + # to, which no word of the frame holds. + + # Operators of a word and a constant, dst, a, constant, as their operators. + add_k, mul_k, band_k, shl_k, shrs_k, shru_k, + # Writing a constant to memory, address, offset, constant, each as wide as it + # says, of which `store_k64` takes the constant's low and then its high half. + store_k8, store_k16, store_k32, store_k64, + # Comparisons going to the label where they hold: of two words, a, b, label, + jump_eq, jump_ne, jump_lts, jump_ltu, jump_les, jump_leu, + # and of a word and a constant, a, constant, label. + jump_eq_k, jump_ne_k, jump_lts_k, jump_ltu_k, jump_les_k, jump_leu_k, jump_gts_k, jump_gtu_k, jump_ges_k, jump_geu_k, + check_ltu, #! a, b, fault: stops the program unless a < b, unsigned, as a check of an index does. + check_ltu_k, #! a, constant, fault: stops the program unless a is below the constant, unsigned. + load_u8_x, #! dst, a, b, offset: reads a byte unsigned at the sum of two words and the offset, as indexing bytes does. + store_8_x, #! a, b, offset, value: writes a byte at the sum of two words and the offset. + move_jump, #! dst, src, label: copies a word, then goes to the label, as the last move of an edge does. + add_k_jump, #! dst, a, constant, label: adds, then goes to the label, as the step of a loop does. + # Operators of two reals rounded to an `f32`, dst, a, b, as the operator of + # `f32`s an `fsingle` alone reads is, which it is made part of. + fadd_f32, fsub_f32, fmul_f32, fdiv_f32, + + # What only a run checking its memory has. + forget, #! address, size: marks bytes as never written. + watch_read, #! address, offset, size: stops the program where a byte the load after reads was never written. + watch_write, #! address, offset, size: marks the bytes the store after writes as written. + + count, #! How many operations there are; not an operation itself. +} + +#! How many words each operation of the machine's code takes, its operation +#! included. An operation followed by a count of words takes those too: a +#! call's operands and results, `format_value`'s words, `switch`'s cases, three +#! words each, and `ret`'s words. +pub const bc_widths: u64[bc::count as u64] = [ + 4, 3, # konst, move + 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, # add to shru + 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, # eq to leus + 4, 4, 4, 4, 4, 4, 4, 4, 4, # fadd to fle + 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, # neg to bswap + 5, # wrap + 5, # select + 3, 3, 4, # cell, global, datum + 4, 4, 4, 4, 4, 4, 4, 4, # load_i8 to load_f32 + 4, 4, 4, 4, 4, # store_8 to store_f32 + 4, 3, 4, 2, 4, # copy, clear, allocate, release, resize + 4, 5, 4, 4, # call, call_trait, call_value, call_c, before their counts + 3, 3, # c_address, callback + 5, 4, 3, # equal, retrait, check + 9, 2, 2, 2, 2, 3, 2, 2, 1, 3, # syscall to fault + 1, 2, 3, 3, 3, # format to format_owned, `format_value` before its count + 2, 3, 3, 4, 2, 2, 2, 2, 1, # jump to unreachable, `switch` and `ret` before their counts + 2, 4, 3, # ready, reach, same + 7, 5, # atomic, start + 4, 4, 4, 4, 4, 4, # add_k to shru_k + 4, 4, 4, 5, # store_k8 to store_k64 + 4, 4, 4, 4, 4, 4, # jump_eq to jump_leu + 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, # jump_eq_k to jump_geu_k + 4, 4, # check_ltu, check_ltu_k + 5, 5, # load_u8_x, store_8_x + 4, 5, # move_jump, add_k_jump + 4, 4, 4, 4, # fadd_f32 to fdiv_f32 + 3, 4, 4 # forget, watch_read, watch_write +]; + +#! Where an instruction of the code is from: from `pc` on, until the next mark. +pub struct line_mark { + pub var pc: u32; #! The first word of the code it holds for. + pub var at: u64; #! Where in the source: one more than the file, then the byte. + pub var site: u32; #! One more than the site of the function inlined there, or 0 for the function's own code. +} + +#! How a function takes a parameter into its frame. +pub struct param_slot { + pub var memory: bool; #! Whether it is held in memory, its own copy given by address. + pub var words: u32; #! How many words it is, where it is not held in memory. + pub var offset: u64; #! Where it begins in the frame, in bytes. + pub var size: u64; #! The bytes of one held in memory. +} + +#! A function's code for the machine. +pub struct bytecode { + pub var code: vector; #! The code. + pub var lines: vector; #! Where each run of it is from. + pub var sites: vector; #! Where the functions inlined into it were called, which its marks name. + pub var params: vector; #! How each parameter is taken. + pub var frame: u64; #! The bytes of the frame. + pub var cells: u64; #! Where the cells begin, the first of which are zeroed as it starts. + pub var zeroed: u64; #! Where the cells zeroed as it starts end, those it need not zero following. + pub var env: u64; #! Where a closure's environment is. + pub var returned: u64; #! The bytes of the memory it returns, or 0 where it returns words. + var done: bool; #! Whether it is made. +} + +#! Makes an empty function code. +#! @returns The code. +pub def bytecode::new(): bytecode { + return bytecode { + code = vector::::new(), + lines = vector::::new(), + sites = vector::::new(), + params = vector::::new() + }; +} + +#! What stands for no value, label, or position. +const none: u32 = 0xFFFFFFFF; + +#! A read of a value: the block it is in, and where. +struct value_read { + var block: u32; + var place: u32; +} + +#! What assembling one function keeps track of, which makes the moves between +#! the words of its values. +struct assembler : move_maker { + var order: vector; #! The blocks, in the order they are laid out. + var number: vector; #! Each block's place in that order. + var starts: vector; #! Where each block begins, which its parameters are held from. + var ends: vector; #! Where each block's edges leave, which their arguments are held to. + var places: vector; #! Where each instruction reads; it writes one after. + var lows: vector; #! Where each value is first held. + var highs: vector; #! Where each value is last held. + var slots: vector; #! The word of the frame holding each value. + var cells: vector; #! Where each cell begins in the frame. + var out: vector; #! The code made. + var lines: vector; #! Where each run of it is from. + var labels: vector; #! Where each label is in the code: those of the blocks, then others. + var fixups: vector; #! The words of the code naming a label, which is written there. + var scratch: u32; #! A word no value is held in, for moves going round in a cycle. + var last_at: u64; #! Where the instruction made last is from. + var last_site: u32; #! The site of the function the instruction made last was inlined from. + var left: vector; #! How many reads of each value read its word: all but those taking it as a constant, and that of what is made part of its reader. + var takes: vector; #! Which operand of each instruction it takes as a constant, or `no_take`. + var folds: vector; #! The instruction each comparison or addition is made part of, or `none`. + var prior: u32; #! The instruction before the one being made, in its block, or 0. + var watches: bool; #! Whether each load and store not of a cell is watched for memory never written, as a run checking its memory asks. + var copies: bool; #! Whether it is a function copying bytes, whose loads are not watched. +} + +#! What stands for no operand taken as a constant. +const no_take: u8 = 0xFF; + +#! Makes the machine's code of every function lowered that has none yet, each +#! freeing the scratch memory it took as it ends. Each function's code is made +#! from its own alone, so as many threads as the options say make them at once. +#! @param this The compiler. +pub def lowerer::assemble_all(&mut this): void { + val compiler := &mut this; + share_out(this.program.functions.length, this.options.threads, def(i: u64): void { + return if !compiler.program.functions[i].lowered || compiler.program.functions[i].compiled.done; + val point := mark_scratch(); + compiler.assemble(i as u32); + release_scratch(point); + }); +} + +#! Makes the machine's code of a function. +#! @param this The compiler. +#! @param index The function. +pub def lowerer::assemble(&mut this, index: u32): void { + val signature: u32 = this.program.functions[index].signature; + var made := bytecode::new(); + made.done = true; + + # The parameters come first in the frame, where the call copies them, then + # the environment of a closure. + var pinned := vector::::new(); + var copies := vector::::new(); + val count := this.program.signatures[signature].params.length; + for i in 0..count { + val shape := this.layout_at(this.program.signatures[signature].params[i]); + val offset: u64 = this.program.signatures[signature].offsets[i]; + if in_memory(&shape) { + made.params.append(param_slot { memory = true, offset = offset, size = shape.size }); + pinned.append(none); + copies.append(offset); + continue; + } + val words := word_count(&shape); + made.params.append(param_slot { words = words, offset = offset }); + for w in 0..words { + pinned.append((offset / word_size) as u32 + w as u32); + copies.append(0); + } + } + var area: u64 = this.program.signatures[signature].size; + made.env = area; + if this.program.functions[index].closure { + pinned.append((area / word_size) as u32); + copies.append(0); + area += word_size; + } + + val body := &this.program.functions[index].body; + made.returned = body.returned as u64; + + var work := assembler { + order = vector::::new(), + number = vector::::new(), + starts = vector::::new(), + ends = vector::::new(), + places = vector::::new(), + lows = vector::::new(), + highs = vector::::new(), + slots = vector::::new(), + cells = vector::::new(), + out = vector::::new(), + lines = vector::::new(), + labels = vector::::new(), + fixups = vector::::new(), + left = vector::::new(), + takes = vector::::new(), + folds = vector::::new(), + watches = this.options.checks, + copies = this.options.checks && this.copies_bytes(index) + }; + body.copy_order(&mut work.order, &mut work.number); + work.place(body); + work.fuse(body); + work.live(body); + val words := work.allocate(body, &pinned, (area / word_size) as u32); + + # The cells follow the words, each aligned as it asks: first those the frame + # zeroes, as an executable's prologue does, then those it need not: those of + # functions inlined, whose code clears them, those `undefined`, and those + # every read of which some write comes before. + val writes := this.result_writes(index); + val zeroed := zeroed_cells(body, work.order.view(), work.number.view(), writes.view()); + var at := words as u64 * word_size; + made.cells = round_up(at, 16); + at = made.cells; + work.cells.resize(body.cells.length); + for pass in 0..2u { + for i in 0..body.cells.length { + val each: cell = body.cells[i]; + val zeroes := each.kind != ck::inlined && each.kind != ck::undefined && zeroed[i]; + continue if zeroes != (pass == 0); + at = round_up(at, each.align as u64); + work.cells[i] = at; + at += each.size as u64; + } + if pass == 0 { + made.zeroed = at; + } + } + made.frame = round_up(at, 16); + + # A parameter held in memory is the address of the frame's copy of it. + val entry := &body.blocks[0]; + for i in 0..entry.params.length { + continue if i >= copies.length || pinned[i] != none; + val value: u32 = entry.params[i]; + work.emit3(bc::cell, work.slots[value], copies[i] as u32); + } + work.emit_all(body); + made.code = move(&mut work.out); + made.lines = move(&mut work.lines); + made.sites.extend(body.sites.view()); + this.program.functions[index].compiled = move(&mut made); +} + +#! Says where each block and instruction is, in the order the blocks are laid +#! out: a block's parameters are held from its start, each instruction reads +#! where it is and writes one past it, and the arguments of the edges leaving a +#! block are read at its end. +#! @param this The assembler. +#! @param body The code. +def assembler::place(&mut this, body: &code): void { + this.starts.resize(body.blocks.length); + this.ends.resize(body.blocks.length); + this.places.resize(body.insts.length); + var pos: u32 = 0; + for k in 0..this.order.length { + val block: u32 = this.order[k]; + this.starts[block] = pos; + pos += 2; + var walk := body.walk(block); + while walk.more() { + this.places[walk.next()] = pos; + pos += 2; + } + this.ends[block] = pos; + pos += 2; + } +} + +#! Works out which instructions the code makes part of others: each operand +#! that is a constant fitting a word of the code, where the machine has a form +#! of the instruction reading it taking one, each comparison only a branch or a +#! check in its block reads, where the machine has a form of the two together, +#! which takes a constant of the comparison too, each addition of words only a +#! load or a store of a byte in its block reads, as its address, and each +#! arithmetic of reals only an `fsingle` in its block reads, as an `f32`'s. +#! @param this The assembler. +#! @param body The code. +def assembler::fuse(&mut this, body: &code): void { + this.left.resize(body.origins.length); + this.takes.resize(body.insts.length, no_take); + this.folds.resize(body.insts.length, none); + var given := body.reader(); + for &block in this.order { + var walk := body.walk(block); + while walk.more() { + given.start(walk.next()); + while given.more() { + val value := given.next(); + this.left[value] = this.left[value] + 1; + } + } + } + + for k in 0..this.order.length { + var walk := body.walk(this.order[k]); + while walk.more() { + val index := walk.next(); + match body.insts[index].kind { + op::add, op::mul, op::band => { + if !this.take(body, index, 1, false) { + _ = this.take(body, index, 0, false); + } + } + op::sub => { + _ = this.take(body, index, 1, true); + } + op::shl, op::shrs, op::shru => { + _ = this.take(body, index, 1, false); + } + op::load => this.fold_address(body, index); + op::store => { + this.take_stored(body, index); + if this.takes[index] == no_take { + this.fold_address(body, index); + } + } + op::branch, op::check => this.fold(body, index); + op::fsingle => this.fold_single(body, index); + else => {} + } + } + } +} + +#! Takes an operand of an instruction as a constant, where it is one fitting a +#! word of the code. +#! @param this The assembler. +#! @param body The code. +#! @param index The instruction. +#! @param at The operand's position. +#! @param negated Whether the code takes the constant negated, as it makes a +#! subtraction an addition. +#! @returns Whether it is taken. +def assembler::take(&mut this, body: &code, index: u32, at: u32, negated: bool): bool { + val value := body.arg(index, at); + val from: origin = body.origins[value]; + return false if from.param || body.insts[from.from].kind != op::iconst; + val bits := bits_of(body, value); + return false if !fits_word(negated ? 0 - bits : bits); + this.takes[index] = at as u8; + this.left[value] = this.left[value] - 1; + return true; +} + +#! Takes the value a store writes as a constant, where it is one: the bits of +#! a word or a real, which `store_k64` takes whole, and the narrower stores the +#! low bits of, as they write them, but none `store_f32` rounds. +#! @param this The assembler. +#! @param body The code. +#! @param index The store. +def assembler::take_stored(&mut this, body: &code, index: u32): void { + val how := body.insts[index].aux as access; + return if how.value_type().lanes() || how == access::f32; + val value := body.arg(index, 1); + val from: origin = body.origins[value]; + return if from.param; + val kind := body.insts[from.from].kind; + return if kind != op::iconst && kind != op::fconst; + this.takes[index] = 1; + this.left[value] = this.left[value] - 1; +} + +#! Makes the comparison a branch or a check reads part of it, where nothing +#! else reads it, it is in the same block, and the machine has a form of the +#! two together: a branch on any comparison of words as equal or ordered, and +#! a check of an index below a count, or of a word not zero, which is a check +#! of the word itself. +#! @param this The assembler. +#! @param body The code. +#! @param index The branch or check. +def assembler::fold(&mut this, body: &code, index: u32): void { + val cond := body.arg(index, 0); + val from: origin = body.origins[cond]; + return if from.param || this.left[cond] != 1; + val compare: u32 = from.from; + val held: inst = body.insts[compare]; + return if held.block != body.insts[index].block; + if body.insts[index].kind == op::branch { + return if (held.kind as u32) < op::eq as u32 || (held.kind as u32) > op::leu as u32; + this.folds[compare] = index; + this.left[cond] = 0; + if !this.take(body, compare, 1, false) { + _ = this.take(body, compare, 0, false); + } + return; + } + if held.kind != op::ltu { + return if held.kind != op::ne; + val zero: origin = body.origins[body.arg(compare, 1)]; + return if zero.param || body.insts[zero.from].kind != op::iconst || body.insts[zero.from].imm != 0; + } + this.folds[compare] = index; + this.left[cond] = 0; + _ = this.take(body, compare, 1, false); +} + +#! Makes the arithmetic of reals an `fsingle` rounds part of it, where nothing +#! else reads it and it is in the same block, so the machine works it as one +#! operation of `f32`s. +#! @param this The assembler. +#! @param body The code. +#! @param index The `fsingle`. +def assembler::fold_single(&mut this, body: &code, index: u32): void { + val real := body.arg(index, 0); + val from: origin = body.origins[real]; + return if from.param || this.left[real] != 1; + val held: inst = body.insts[from.from]; + return if held.block != body.insts[index].block; + return if held.kind != op::fadd && held.kind != op::fsub && held.kind != op::fmul && held.kind != op::fdiv; + this.folds[from.from] = index; + this.left[real] = 0; +} + +#! The arithmetic of reals made part of an `fsingle`. +#! @param this The assembler. +#! @param body The code. +#! @param index The `fsingle`. +#! @returns The arithmetic, or `none` where none is. +def assembler::single_of(&this, body: &code, index: u32): u32 { + val from: origin = body.origins[body.arg(index, 0)]; + return none if from.param || this.folds[from.from] != index; + return from.from; +} + +#! Makes the addition giving a load's or a store's address part of it, where +#! nothing else reads it, it is in the same block, it adds two words, and the +#! machine has a form of the load or the store at a sum. +#! @param this The assembler. +#! @param body The code. +#! @param index The load or store. +def assembler::fold_address(&mut this, body: &code, index: u32): void { + return if this.watches || indexed_of(body, index) == bc::count; + val address := body.arg(index, 0); + val from: origin = body.origins[address]; + return if from.param || this.left[address] != 1; + val sum: u32 = from.from; + val held: inst = body.insts[sum]; + return if held.kind != op::add || held.block != body.insts[index].block || this.takes[sum] != no_take; + this.folds[sum] = index; + this.left[address] = 0; +} + +#! Whether a function is one of `core`'s that copy bytes, `memcpy` and those it +#! calls, whose reads a run checking its memory does not watch: copying bytes +#! never written uses none of them, as moving a block that is partly written +#! does, so the bytes copied count as written where they go. +#! @param this The compiler. +#! @param index The function. +#! @returns Whether it is. +def lowerer::copies_bytes(&mut this, index: u32): bool { + val decl := this.program.functions[index].decl; + return false if decl == 0 || !this.in_std(decl); + val name := this.checker.names.text(this.checker.decls.names.p[decl]); + return name == "memcpy" || name == "copyfwd" || name == "copybwd"; +} + +#! Watches the bytes a load reads or a store writes, running with memory +#! checked: those of a cell the frame holds are left alone, but for a cell +#! `undefined`, as each is written before it is read or was zeroed as the +#! frame began. +#! @param this The assembler. +#! @param body The code. +#! @param index The load or store. +#! @param kind `watch_read` or `watch_write`. +def assembler::watch(&mut this, body: &code, index: u32, kind: bc): void { + return if !this.watches || (this.copies && kind == bc::watch_read); + val held: inst = body.insts[index]; + val address := body.arg(index, 0); + val from: origin = body.origins[address]; + if !from.param && body.insts[from.from].kind == op::cell { + return if body.cells[body.insts[from.from].aux].kind != ck::undefined; + } + this.emit4(kind, this.arg(body, index, 0), held.imm as u32, (held.aux as access).width() as u32); +} + +#! The form of a load or a store at the sum of two words, where the machine has +#! one: reading a byte unsigned, or writing a byte. +#! @param body The code. +#! @param index The load or store. +#! @returns The operation, or `bc::count` where it has none. +def indexed_of(body: &code, index: u32): bc { + val how := body.insts[index].aux as access; + if body.insts[index].kind == op::load { + return how == access::u8 ? bc::load_u8_x : bc::count; + } + return how == access::i8 || how == access::u8 ? bc::store_8_x : bc::count; +} + +#! The addition made part of a load or a store, giving its address. +#! @param this The assembler. +#! @param body The code. +#! @param index The load or store. +#! @returns The addition, or `none` where none is. +def assembler::sum_of(&this, body: &code, index: u32): u32 { + val from: origin = body.origins[body.arg(index, 0)]; + return none if from.param || this.folds[from.from] != index; + return from.from; +} + +#! Whether an instruction makes no code of its own: a comparison or an addition +#! made part of another, or a constant no instruction reads from its word. +#! @param this The assembler. +#! @param body The code. +#! @param index The instruction. +#! @returns Whether it does not. +def assembler::omitted(&this, body: &code, index: u32): bool { + return true if this.folds[index] != none; + val held: inst = body.insts[index]; + return (held.kind == op::iconst || held.kind == op::fconst) && this.left[held.result] == 0; +} + +#! Whether an instruction's read of a value reads its word: where it neither +#! takes it as a constant, nor makes the instruction giving it part of itself. +#! @param this The assembler. +#! @param body The code. +#! @param index The instruction. +#! @param operand The position of the operand read, or `no_operand` for an +#! argument of an edge. +#! @param value The value. +#! @returns Whether it does. +def assembler::reads_word(&this, body: &code, index: u32, operand: u32, value: u32): bool { + return false if operand != no_operand && this.takes[index] != no_take && operand == this.takes[index] as u32; + val from: origin = body.origins[value]; + return from.param || this.folds[from.from] != index; +} + +#! The bits of a constant. +#! @param body The code. +#! @param value The constant. +#! @returns Its bits. +def bits_of(body: &code, value: u32): u64 { + return body.insts[body.origins[value].from].imm; +} + +#! Whether a constant is one a word of the code stands for. +#! @param bits The constant. +#! @returns Whether it is. +def fits_word(bits: u64): bool { + return bits == bc_constant((bits & 0xFFFFFFFF) as u32); +} + +#! The constant a word of the code stands for: the 64 bits its sign extends to. +#! @param word The word. +#! @returns The constant. +pub def bc_constant(word: u32): u64 { + return ((word as i32) as i64) as u64; +} + +#! Works out where each value is held, from where it is made to where it is +#! last read, and over every block it is held into along the way, as a value +#! read in a loop is held around it. +#! @param this The assembler. +#! @param body The code. +def assembler::live(&mut this, body: &code): void { + val values := body.origins.length; + this.lows.resize(values, none); + this.highs.resize(values); + for k in 0..this.order.length { + val block: u32 = this.order[k]; + for ¶m in body.blocks[block].params { + this.lows[param] = this.starts[block]; + this.highs[param] = this.starts[block]; + } + var insts := body.walk(block); + while insts.more() { + val at := insts.next(); + val held: inst = body.insts[at]; + for r in 0..held.count { + this.lows[held.result as u64 + r as u64] = this.places[at] + 1; + this.highs[held.result as u64 + r as u64] = this.places[at] + 1; + } + } + } + + # Each value's reads, gathered together: the block and position of each. + var reads := groups::::new(values); + this.each_read(body, &mut reads); + reads.seal(); + this.each_read(body, &mut reads); + + # A value read in a block other than its own is held into that block, and + # out of every block before it on the way back to its own, laid out or not. + var walk := live_walk::new(body.blocks.length, nothing {}); + for v in 1..values { + continue if this.lows[v] == none || reads.length(v) == 0; + walk.begin(v as u32, body.home_of(v as u32)); + for &read in reads.of(v) { + this.extend(v as u32, read.place); + walk.read(read.block, read.place); + } + walk.walk(body, &this.number, false); + for &block in walk.touched { + val reach: block_reach = walk.reaches[block]; + if reach.into { + this.extend(v as u32, this.starts[block]); + } + if reach.out { + this.extend(v as u32, this.ends[block]); + } + } + } +} + +#! Walks every read of a value's word, in the blocks laid out: each operand of +#! an instruction, read where the instruction it is made part of is, if any, +#! and each argument of an edge, read at the end of the block it leaves. +#! Counts the reads of each value, or, once the reads are sealed, puts where +#! each is. +#! @param this The assembler. +#! @param body The code. +#! @param reads The reads of each value. +def assembler::each_read(&this, body: &code, reads: &mut groups): void { + val fill := reads.is_sealed; + var given := body.reader(); + for &block in this.order { + var walk := body.walk(block); + while walk.more() { + val index := walk.next(); + val at: u32 = this.folds[index] != none ? this.folds[index] : index; + given.start(index); + while given.more() { + val value := given.next(); + continue if !this.reads_word(body, index, given.operand(), value); + if fill { + val place := given.operand() != no_operand ? this.places[at] : this.ends[block]; + reads.put(value, value_read { block = block, place = place }); + } else { + reads.count(value); + } + } + } + } +} + +#! Holds a value at a position too. +#! @param this The assembler. +#! @param value The value. +#! @param pos The position. +def assembler::extend(&mut this, value: u32, pos: u32): void { + if pos < this.lows[value] { + this.lows[value] = pos; + } + if pos > this.highs[value] { + this.highs[value] = pos; + } +} + +#! Gives each value a word of the frame, sharing one between values whose lives +#! do not overlap, but those of instructions making no code of their own. The +#! function's parameters are where the call copies them. +#! @param this The assembler. +#! @param body The code. +#! @param pinned The word of each parameter of the entry, or `none` for one +#! given a word as any other value is. +#! @param first The first word not taken by the parameters. +#! @returns How many words the values take, the parameters' included. +def assembler::allocate(&mut this, body: &code, pinned: &vector, first: u32): u32 { + this.slots.resize(body.origins.length, none); + val entry := &body.blocks[0]; + for i in 0..entry.params.length { + if i < pinned.length && pinned[i] != none { + this.slots[entry.params[i]] = pinned[i]; + } + } + + var next := first; + var free := vector::::new(); + var active := vector::::new(); + for k in 0..this.order.length { + val block: u32 = this.order[k]; + for ¶m in body.blocks[block].params { + this.assign(param, &mut next, &mut free, &mut active); + } + var walk := body.walk(block); + while walk.more() { + val index := walk.next(); + continue if this.omitted(body, index); + val held: inst = body.insts[index]; + for r in 0..held.count { + this.assign(held.result + r as u32, &mut next, &mut free, &mut active); + } + } + } + this.scratch = next; + return next + 1; +} + +#! Gives a value a word, once the values no longer held where it begins give +#! theirs back. +#! @param this The assembler. +#! @param value The value. +#! @param next The next word never given. +#! @param free The words given back. +#! @param active The values holding words. +def assembler::assign(&mut this, value: u32, next: &mut u32, free: &mut vector, active: &mut vector): void { + return if this.slots[value] != none; + val begins: u32 = this.lows[value]; + var i := active.length; + while i > 0 { + i--; + val held: u32 = active[i]; + continue if this.highs[held] >= begins; + free.append(this.slots[held]); + active[i] = active.last(); + active.truncate(); + } + + if free.length != 0 { + this.slots[value] = free.last(); + free.truncate(); + } else { + this.slots[value] = next; + next = next + 1; + } + active.append(value); +} + +#! Adds a word to the code. +#! @param this The assembler. +#! @param word The word. +def assembler::put(&mut this, word: u32): void { + this.out.append(word); +} + +#! Adds an operation of one operand. +#! @param this The assembler. +#! @param kind The operation. +#! @param a Its operand. +def assembler::emit1(&mut this, kind: bc, a: u32): void { + this.out.append(kind as u32); + this.out.append(a); +} + +#! Adds an operation of two operands. +#! @param this The assembler. +#! @param kind The operation. +#! @param a Its first operand. +#! @param b Its second. +def assembler::emit3(&mut this, kind: bc, a: u32, b: u32): void { + this.out.append(kind as u32); + this.out.append(a); + this.out.append(b); +} + +#! Adds an operation of three operands. +#! @param this The assembler. +#! @param kind The operation. +#! @param a Its first operand. +#! @param b Its second. +#! @param c Its third. +def assembler::emit4(&mut this, kind: bc, a: u32, b: u32, c: u32): void { + this.out.append(kind as u32); + this.out.append(a); + this.out.append(b); + this.out.append(c); +} + +#! Adds an operation of four operands. +#! @param this The assembler. +#! @param kind The operation. +#! @param a Its first operand. +#! @param b Its second. +#! @param c Its third. +#! @param d Its fourth. +def assembler::emit5(&mut this, kind: bc, a: u32, b: u32, c: u32, d: u32): void { + this.out.append(kind as u32); + this.out.append(a); + this.out.append(b); + this.out.append(c); + this.out.append(d); +} + +#! Adds a word naming a label, written once the label is placed. +#! @param this The assembler. +#! @param label The label. +def assembler::put_label(&mut this, label: u32): void { + this.fixups.append(this.out.length as u32); + this.out.append(label); +} + +#! Makes a label, not yet placed. +#! @param this The assembler. +#! @returns The label. +def assembler::new_label(&mut this): u32 { + this.labels.append(none); + return (this.labels.length - 1) as u32; +} + +#! The word holding a value. +#! @param this The assembler. +#! @param body The code. +#! @param index The instruction. +#! @param at The position of the operand. +#! @returns The word. +def assembler::arg(&this, body: &code, index: u32, at: u32): u32 { + return this.slots[body.arg(index, at)]; +} + +#! The word holding a result of an instruction. +#! @param this The assembler. +#! @param body The code. +#! @param index The instruction. +#! @param at Which result. +#! @returns The word. +def assembler::result(&this, body: &code, index: u32, at: u32): u32 { + return this.slots[body.insts[index].result + at]; +} + +#! Adds the code of every block, in the order laid out, then writes where each +#! label is. +#! @param this The assembler. +#! @param body The code. +def assembler::emit_all(&mut this, body: &code): void { + this.labels.resize(body.blocks.length, none); + this.last_at = 0xFFFFFFFFFFFFFFFF; + for k in 0..this.order.length { + val block: u32 = this.order[k]; + this.labels[block] = this.out.length as u32; + val next: u32 = k + 1 < this.order.length ? this.order[k + 1] : none; + this.prior = 0; + var walk := body.walk(block); + while walk.more() { + val index := walk.next(); + this.emit_inst(body, index, next); + this.prior = index; + } + } + for f in 0..this.fixups.length { + val word: u32 = this.fixups[f]; + this.out[word] = this.labels[this.out[word]]; + } +} + +#! Adds the code of an instruction. +#! @param this The assembler. +#! @param body The code. +#! @param index The instruction. +#! @param next The block laid out next, which a jump to needs no jump. +def assembler::emit_inst(&mut this, body: &code, index: u32, next: u32): void { + return if this.omitted(body, index); + val held: inst = body.insts[index]; + if held.at != this.last_at || held.site != this.last_site { + this.lines.append(line_mark { pc = this.out.length as u32, at = held.at, site = held.site }); + this.last_at = held.at; + this.last_site = held.site; + } + + val kind := held.kind; + val number := kind as u32; + if number >= op::add as u32 && number <= op::fle as u32 { + if this.takes[index] != no_take { + this.emit_taking(body, index); + return; + } + this.emit4((bc::add as u32 + (number - op::add as u32)) as bc, this.result(body, index, 0), + this.arg(body, index, 0), this.arg(body, index, 1)); + return; + } + if kind == op::fsingle { + val arithmetic := this.single_of(body, index); + if arithmetic != none { + val which := body.insts[arithmetic].kind as u32 - op::fadd as u32; + this.emit4((bc::fadd_f32 as u32 + which) as bc, this.result(body, index, 0), + this.arg(body, arithmetic, 0), this.arg(body, arithmetic, 1)); + return; + } + } + if number >= op::neg as u32 && number <= op::bswap as u32 { + this.emit3((bc::neg as u32 + (number - op::neg as u32)) as bc, this.result(body, index, 0), this.arg(body, index, 0)); + return; + } + + match kind { + op::iconst, op::fconst => this.emit4(bc::konst, this.result(body, index, 0), + (held.imm & 0xFFFFFFFF) as u32, (held.imm >> 32) as u32); + op::wrap => this.emit5(bc::wrap, this.result(body, index, 0), this.arg(body, index, 0), held.aux, held.imm as u32); + op::select => this.emit5(bc::select, this.result(body, index, 0), this.arg(body, index, 0), this.arg(body, index, 1), this.arg(body, index, 2)); + op::cell => this.emit3(bc::cell, this.result(body, index, 0), this.cells[held.aux] as u32); + op::global => this.emit3(bc::global, this.result(body, index, 0), held.imm as u32); + op::datum => this.emit4(bc::datum, this.result(body, index, 0), held.aux, held.imm as u32); + op::load => { + val sum := this.sum_of(body, index); + this.watch(body, index, bc::watch_read); + if (held.aux as access).value_type().lanes() { + this.emit1(bc::trap, 3); + } else if sum != none { + this.emit5(indexed_of(body, index), this.result(body, index, 0), this.arg(body, sum, 0), this.arg(body, sum, 1), held.imm as u32); + } else { + this.emit4(load_of(held.aux as access), this.result(body, index, 0), this.arg(body, index, 0), held.imm as u32); + } + } + op::store => { + val sum := this.sum_of(body, index); + this.watch(body, index, bc::watch_write); + if (held.aux as access).value_type().lanes() { + this.emit1(bc::trap, 3); + } else if this.takes[index] != no_take { + this.emit_stored(body, index); + } else if sum != none { + this.emit5(indexed_of(body, index), this.arg(body, sum, 0), this.arg(body, sum, 1), held.imm as u32, this.arg(body, index, 1)); + } else { + this.emit4(store_of(held.aux as access), this.arg(body, index, 0), held.imm as u32, this.arg(body, index, 1)); + } + } + op::copy => this.emit4(bc::copy, this.arg(body, index, 0), this.arg(body, index, 1), held.imm as u32); + op::clear => this.emit3(bc::clear, this.arg(body, index, 0), held.imm as u32); + op::forget => this.emit3(bc::forget, this.arg(body, index, 0), held.imm as u32); + op::allocate => this.emit4(bc::allocate, this.result(body, index, 0), this.arg(body, index, 0), body.insts[index].aux); + op::release => this.emit1(bc::release, this.arg(body, index, 0)); + op::resize => this.emit4(bc::resize, this.result(body, index, 0), this.arg(body, index, 0), this.arg(body, index, 1)); + op::call, op::call_trait, op::call_value, op::call_c => this.emit_call(body, index); + op::c_address => this.emit3(bc::c_address, this.result(body, index, 0), held.aux); + op::callback => this.emit3(bc::callback, this.result(body, index, 0), held.aux); + op::equal => this.emit5(bc::equal, this.result(body, index, 0), this.arg(body, index, 0), this.arg(body, index, 1), held.aux); + op::retrait => this.emit4(bc::retrait, this.result(body, index, 0), this.arg(body, index, 0), held.aux); + op::check => this.emit_check(body, index); + op::syscall => { + this.put(bc::syscall as u32); + this.put(this.result(body, index, 0)); + for a in 0..7 { + this.put(a < held.argc ? this.arg(body, index, a as u32) : this.scratch); + } + } + op::frame => this.emit1(bc::frame, this.result(body, index, 0)); + op::image => this.emit1(bc::image, this.result(body, index, 0)); + op::environ => this.emit1(bc::environ, this.result(body, index, 0)); + op::signals => this.emit1(bc::signals, this.result(body, index, 0)); + op::catch => this.emit3(bc::catch, this.result(body, index, 0), this.arg(body, index, 0)); + op::safepoint => this.emit1(bc::safepoint, held.aux); + op::exit => this.emit1(bc::exit, this.arg(body, index, 0)); + op::abort => this.put(bc::abort as u32); + op::fault => this.emit3(bc::fault, this.arg(body, index, 0), this.arg(body, index, 1)); + op::format => this.put(bc::format as u32); + op::format_text => this.emit1(bc::format_text, held.aux); + op::format_value => { + this.put(bc::format_value as u32); + this.put(held.aux); + this.put(held.argc); + for a in 0..held.argc { + this.put(this.arg(body, index, a as u32)); + } + } + op::format_bytes => this.emit3(bc::format_bytes, this.arg(body, index, 0), this.arg(body, index, 1)); + op::format_owned => this.emit3(bc::format_owned, this.result(body, index, 0), this.result(body, index, 1)); + op::jump => { + val moved := this.moves(body, held.aux); + if body.edges[held.aux].target != next { + this.put_jump(body.edges[held.aux].target, moved ? bc::move : this.joined(body, index)); + } + } + op::branch => this.emit_branch(body, index, next); + op::switch => this.emit_switch(body, index); + op::ret => { + if body.returned != 0 { + this.emit1(bc::ret_memory, this.arg(body, index, 0)); + return; + } + this.put(bc::ret as u32); + this.put(held.argc); + for a in 0..held.argc { + this.put(this.arg(body, index, a as u32)); + } + } + op::trap => { + if held.argc != 0 { + this.emit1(bc::trap_word, this.arg(body, index, 0)); + } else { + this.emit1(bc::trap, held.aux); + } + } + op::unreachable => this.put(bc::unreachable as u32); + op::ready => this.emit1(bc::ready, held.aux); + op::reach => this.emit4(bc::reach, this.arg(body, index, 0), this.arg(body, index, 1), held.imm as u32); + op::same => this.emit3(bc::same, this.arg(body, index, 0), this.arg(body, index, 1)); + # The machine has no vector instructions, so no processor's, and never works + # the lanes with them. + op::atomic => { + # The machine works one thread, so it needs none of the orders, which come + # after the operands. + val fence := held.aux == atomic_fence; + val operands: u32 = fence || held.aux == atomic_load ? 0 : held.aux == atomic_compare_exchange ? 2 : 1; + this.put(bc::atomic as u32); + this.put(atomic_gives(held.aux) ? this.result(body, index, 0) : this.scratch); + this.put(held.aux); + this.put(held.imm as u32); + this.put(fence ? this.scratch : this.arg(body, index, 0)); + this.put(operands >= 1 ? this.arg(body, index, 1) : this.scratch); + this.put(operands >= 2 ? this.arg(body, index, 2) : this.scratch); + } + op::start => { + this.put(bc::start as u32); + this.put(this.result(body, index, 0)); + for a in 0..3u { + this.put(this.arg(body, index, a as u32)); + } + } + op::current, op::clone => this.emit1(bc::trap, 3); + op::cpu => this.emit4(bc::konst, this.result(body, index, 0), 0, 0); + op::lanes, op::vzero => this.emit1(bc::trap, 3); + else => this.put(bc::unreachable as u32); + } +} + +#! The operation reading memory as an access says, of which a float's bits are +#! read as a word's are. +#! @param how The access. +#! @returns The operation. +def load_of(how: access): bc { + return match how { + access::i8 => bc::load_i8, + access::u8 => bc::load_u8, + access::i16 => bc::load_i16, + access::u16 => bc::load_u16, + access::i32 => bc::load_i32, + access::u32 => bc::load_u32, + access::f32 => bc::load_f32, + else => bc::load_i64 + }; +} + +#! The operation writing memory as an access says, which only needs its width. +#! @param how The access. +#! @returns The operation. +def store_of(how: access): bc { + return match how { + access::i8, access::u8 => bc::store_8, + access::i16, access::u16 => bc::store_16, + access::i32, access::u32 => bc::store_32, + access::f32 => bc::store_f32, + else => bc::store_64 + }; +} + +#! Adds an operator of a word and the constant it takes: an addition, which a +#! subtraction is of the constant negated, a multiplication, an `&`, or a +#! shift. +#! @param this The assembler. +#! @param body The code. +#! @param index The instruction. +def assembler::emit_taking(&mut this, body: &code, index: u32): void { + val held: inst = body.insts[index]; + val at := this.takes[index] as u32; + var bits := bits_of(body, body.arg(index, at)); + if held.kind == op::sub { + bits = 0 - bits; + } + val kind := match held.kind { + op::add, op::sub => bc::add_k, + op::mul => bc::mul_k, + op::band => bc::band_k, + op::shl => bc::shl_k, + op::shrs => bc::shrs_k, + else => bc::shru_k + }; + this.emit4(kind, this.result(body, index, 0), this.arg(body, index, 1 - at), (bits & 0xFFFFFFFF) as u32); +} + +#! Adds a store of the constant it takes, as wide as its access says. +#! @param this The assembler. +#! @param body The code. +#! @param index The store. +def assembler::emit_stored(&mut this, body: &code, index: u32): void { + val held: inst = body.insts[index]; + val bits := bits_of(body, body.arg(index, 1)); + val kind := match store_of(held.aux as access) { + bc::store_8 => bc::store_k8, + bc::store_16 => bc::store_k16, + bc::store_32 => bc::store_k32, + else => bc::store_k64 + }; + this.emit4(kind, this.arg(body, index, 0), held.imm as u32, (bits & 0xFFFFFFFF) as u32); + if kind == bc::store_k64 { + this.put((bits >> 32) as u32); + } +} + +#! Adds a check: of the word of its condition, or of the comparison made part +#! of it, an index below a count, of words or a word and a constant, or a word +#! not zero, which is a check of the word. +#! @param this The assembler. +#! @param body The code. +#! @param index The check. +def assembler::emit_check(&mut this, body: &code, index: u32): void { + val held: inst = body.insts[index]; + val cond := body.arg(index, 0); + val from: origin = body.origins[cond]; + if from.param || this.folds[from.from] != index { + this.emit3(bc::check, this.slots[cond], held.aux); + return; + } + val compare: u32 = from.from; + val word := this.arg(body, compare, 0); + if body.insts[compare].kind == op::ne { + this.emit3(bc::check, word, held.aux); + } else if this.takes[compare] != no_take { + this.emit4(bc::check_ltu_k, word, (bits_of(body, body.arg(compare, 1)) & 0xFFFFFFFF) as u32, held.aux); + } else { + this.emit4(bc::check_ltu, word, this.arg(body, compare, 1), held.aux); + } +} + +#! Adds a call: what it calls, its operands, then the words of its results. +#! @param this The assembler. +#! @param body The code. +#! @param index The instruction. +def assembler::emit_call(&mut this, body: &code, index: u32): void { + val held: inst = body.insts[index]; + val kind := match held.kind { + op::call => bc::call, + op::call_trait => bc::call_trait, + op::call_value => bc::call_value, + else => bc::call_c + }; + this.put(kind as u32); + this.put(held.aux); + # A trait's method is called through the slot of its vtable. + if held.kind == op::call_trait { + this.put(held.imm as u32); + } + this.put(held.argc); + for a in 0..held.argc { + this.put(this.arg(body, index, a as u32)); + } + this.put(held.count as u32); + for r in 0..held.count { + this.put(this.result(body, index, r as u32)); + } +} + +#! Adds a branch: to where the condition is not zero, and otherwise to the +#! other edge, each moving what its block takes, and neither jumping to the +#! block laid out next. +#! @param this The assembler. +#! @param body The code. +#! @param index The instruction. +#! @param next The block laid out next. +def assembler::emit_branch(&mut this, body: &code, index: u32, next: u32): void { + val held: inst = body.insts[index]; + val then := held.aux; + val other := held.aux + 1; + val then_target: u32 = body.edges[then].target; + val other_target: u32 = body.edges[other].target; + val then_moves := this.has_moves(body, then); + val other_moves := this.has_moves(body, other); + + if !then_moves && !other_moves { + if then_target == next { + this.put_test(body, index, false); + this.put_label(other_target); + return; + } + this.put_test(body, index, true); + this.put_label(then_target); + if other_target != next { + this.put(bc::jump as u32); + this.put_label(other_target); + } + return; + } + + # The moves of each edge are made down its own path. + val otherwise := this.new_label(); + this.put_test(body, index, false); + this.put_label(otherwise); + val moved := this.moves(body, then); + this.put_jump(then_target, moved ? bc::move : bc::count); + this.labels[otherwise] = this.out.length as u32; + val moved_other := this.moves(body, other); + if other_target != next { + this.put_jump(other_target, moved_other ? bc::move : bc::count); + } +} + +#! Adds a jump to a label, which the instruction made last takes part of, +#! where that is the last move of the edge the jump follows, or the addition +#! of a constant `joined` finds. +#! @param this The assembler. +#! @param label The label. +#! @param last The operation of the instruction made last that takes the +#! jump, `move` or `add_k`, or `count` where none does. +def assembler::put_jump(&mut this, label: u32, last: bc): void { + if last == bc::count { + this.put(bc::jump as u32); + } else { + this.out[this.out.length - bc_widths[last as u64]] = (last == bc::move ? bc::move_jump : bc::add_k_jump) as u32; + } + this.put_label(label); +} + +#! The operation of the instruction made last, which a block's jump moving +#! nothing may be made part of: the addition of a constant just before it, +#! from the same place in the source, so a trace of the two reads the same. +#! @param this The assembler. +#! @param body The code. +#! @param index The jump. +#! @returns `add_k`, or `count` where it is not that. +def assembler::joined(&this, body: &code, index: u32): bc { + return bc::count if this.prior == 0; + val before: inst = body.insts[this.prior]; + val held: inst = body.insts[index]; + return bc::count if (before.kind != op::add && before.kind != op::sub) || this.takes[this.prior] == no_take; + return before.at == held.at && before.site == held.site ? bc::add_k : bc::count; +} + +#! The relation each comparison going to a label tests, by its place from +#! `jump_eq_k` on: `==`, `!=`, `<` signed and unsigned, `<=`, `>`, and `>=`, +#! of which those of two words are the first six, as `>` and `>=` are `<` and +#! `<=` with the words the other way round. The comparisons of the code are in +#! the same order from `op::eq`. The relation holding of the operands the other +#! way round, of each: +const relation_mirrored: u8[10] = [0, 1, 6, 7, 8, 9, 2, 3, 4, 5]; +#! The relation holding where each does not. +const relation_negated: u8[10] = [1, 0, 8, 9, 6, 7, 4, 5, 2, 3]; + +#! Adds an instruction going to a label where a branch's condition is as +#! asked, but for the label, which follows: a jump on the word of the +#! condition, or the comparison made part of the branch, of two words or of a +#! word and a constant, as a jump on the word where the constant is zero and +#! the relation holds where the word is zero, or where it is not. +#! @param this The assembler. +#! @param body The code. +#! @param index The branch. +#! @param holds Whether it goes where the condition holds, or where it does not. +def assembler::put_test(&mut this, body: &code, index: u32, holds: bool): void { + val cond := body.arg(index, 0); + val from: origin = body.origins[cond]; + if from.param || this.folds[from.from] != index { + this.emit1(holds ? bc::jump_if : bc::jump_zero, this.slots[cond]); + return; + } + val compare: u32 = from.from; + val at := this.takes[compare]; + var relation := (body.insts[compare].kind as u32 - op::eq as u32) as u64; + if at == 0 { + relation = relation_mirrored[relation] as u64; + } + if !holds { + relation = relation_negated[relation] as u64; + } + if at == no_take { + var a := this.arg(body, compare, 0); + var b := this.arg(body, compare, 1); + if relation >= 6 { + relation = relation_mirrored[relation] as u64; + val first := a; + a = b; + b = first; + } + this.emit3((bc::jump_eq as u64 + relation) as bc, a, b); + return; + } + val word := this.arg(body, compare, 1 - at as u32); + val bits := bits_of(body, body.arg(compare, at as u32)); + # Of zero, `==` and `<=` unsigned hold where the word is zero, and `!=` and + # `>` unsigned where it is not. + if bits == 0 && (relation == 0 || relation == 5) { + this.emit1(bc::jump_zero, word); + } else if bits == 0 && (relation == 1 || relation == 7) { + this.emit1(bc::jump_if, word); + } else { + this.emit3((bc::jump_eq_k as u64 + relation) as bc, word, (bits & 0xFFFFFFFF) as u32); + } +} + +#! Adds a switch: the cases, each to its edge, then the default, and after them +#! the moves of the edges that move what their blocks take. +#! @param this The assembler. +#! @param body The code. +#! @param index The instruction. +def assembler::emit_switch(&mut this, body: &code, index: u32): void { + val held: inst = body.insts[index]; + val edges := held.imm as u32; + val cases := edges - 1; + var targets := vector::::new(); + for e in 0..edges { + val edge := held.aux + e as u32; + if this.has_moves(body, edge) { + targets.append(this.new_label()); + } else { + targets.append(body.edges[edge].target); + } + } + + this.put(bc::switch as u32); + this.put(this.arg(body, index, 0)); + this.put(cases); + for e in 0..cases { + val edge := held.aux + e as u32; + val case: u64 = body.edges[edge].case; + this.put((case & 0xFFFFFFFF) as u32); + this.put((case >> 32) as u32); + this.put_label(targets[e]); + } + this.put_label(targets[cases]); + + for e in 0..edges { + val edge := held.aux + e as u32; + continue if !this.has_moves(body, edge); + this.labels[targets[e]] = this.out.length as u32; + val moved := this.moves(body, edge); + this.put_jump(body.edges[edge].target, moved ? bc::move : bc::count); + } +} + +#! Whether an edge moves anything into the words of what its block takes. +#! @param this The assembler. +#! @param body The code. +#! @param edge The edge. +#! @returns Whether it does. +def assembler::has_moves(&this, body: &code, edge: u32): bool { + val target: u32 = body.edges[edge].target; + val params := &body.blocks[target].params; + for i in 0..body.edges[edge].args.length { + continue if i >= params.length; + if this.slots[params[i]] != this.slots[body.edges[edge].args[i]] { + return true; + } + } + return false; +} + +#! Adds the moves of an edge into the words of what its block takes, all as if +#! at once, each left waiting moving up in its place: a move whose word another +#! still reads waits for that one, and moves going round in a cycle save one +#! word first. +#! @param this The assembler. +#! @param body The code. +#! @param edge The edge. +#! @returns Whether it added any, the last of which is the code made last. +def assembler::moves(&mut this, body: &code, edge: u32): bool { + val target: u32 = body.edges[edge].target; + var pending := vector::::new(); + for i in 0..body.edges[edge].args.length { + break if i >= body.blocks[target].params.length; + val to := this.slots[body.blocks[target].params[i]]; + val from := this.slots[body.edges[edge].args[i]]; + continue if to == from; + pending.append(word_move { to = to, from = from }); + } + val any := pending.length != 0; + make_moves::(&mut pending, this, false); + return any; +} + +#! A move of the machine's code: a word of the frame written with another. +struct word_move { + var to: u32; #! The word written. + var from: u32; #! The word read. +} + +#! Whether a move reads the word another writes. +#! @param this The assembler. +#! @param reader The move that may read it. +#! @param writer The move writing it. +#! @returns Whether it does. +def assembler::move_reads(&this, reader: &word_move, writer: &word_move): bool { + return reader.from == writer.to; +} + +#! Adds a move. +#! @param this The assembler. +#! @param made The move. +def assembler::move_one(&mut this, made: &word_move): void { + this.emit3(bc::move, made.to, made.from); +} + +#! The move saving what a move would write over, which a cycle of moves still +#! reads, in the word no value is held in. +#! @param this The assembler. +#! @param written The move. +#! @param pending The moves waiting. +#! @returns The move saving it. +def assembler::move_saving(&mut this, written: &word_move, pending: span): word_move { + return word_move { to = this.scratch, from = written.to }; +} + +#! Has a move read what another saved from where it was saved. +#! @param this The assembler. +#! @param reader The move. +#! @param saved The move saving what it reads. +def assembler::move_reread(&this, reader: &mut word_move, saved: &word_move): void { + reader.from = saved.to; +} + +#! How many words an instruction of the code takes, its operation included. +#! @param code The code. +#! @param pc Where the instruction begins. +#! @returns How many: 1 for what is no operation. +pub def bc_width(code: span, pc: u64): u64 { + val kind := code[pc]; + return 1 if kind >= bc::count as u32; + val fixed := bc_widths[kind as u64]; + return match kind { + bc::call as u32, bc::call_trait as u32, bc::call_value as u32, bc::call_c as u32 => fixed + call_counts(code, pc + fixed - 2), + bc::format_value as u32 => fixed + code[pc + 2] as u64, + bc::switch as u32 => fixed + 3 * code[pc + 2] as u64, + bc::ret as u32 => fixed + code[pc + 1] as u64, + else => fixed + }; +} + +#! How many operands and results a call has. +#! @param code The code. +#! @param at Where the count of its operands is. +#! @returns How many. +def call_counts(code: span, at: u64): u64 { + val argc := code[at] as u64; + val resc := code[at + 1 + argc] as u64; + return argc + resc; +} + +#! The name of each operation of the machine's code, as it is printed. +const bc_names: strview[bc::count as u64] = [ + "konst", "move", + "add", "sub", "mul", "divs", "divu", "rems", "remu", "band", "bor", "bxor", "shl", "shrs", "shru", + "eq", "ne", "lts", "ltu", "les", "leu", "eqsu", "ltsu", "lesu", "ltus", "leus", + "fadd", "fsub", "fmul", "fdiv", "frem", "feq", "fne", "flt", "fle", + "neg", "bnot", "lnot", "fneg", "itof", "utof", "ftoi", "ftou", "fsingle", "fsqrt", "ones", "clz", "ctz", "bswap", "wrap", + "select", + "cell", "global", "datum", + "load_i8", "load_u8", "load_i16", "load_u16", "load_i32", "load_u32", "load_i64", "load_f32", + "store_8", "store_16", "store_32", "store_64", "store_f32", + "copy", "clear", "allocate", "release", "resize", + "call", "call_trait", "call_value", "call_c", "c_address", "callback", + "equal", "retrait", "check", + "syscall", "frame", "image", "environ", "signals", "catch", "safepoint", "exit", "abort", "fault", + "format", "format_text", "format_value", "format_bytes", "format_owned", + "jump", "jump_if", "jump_zero", "switch", "ret", "ret_memory", "trap", "trap_word", "unreachable", + "ready", "reach", "same", + "atomic", "start", + "add_k", "mul_k", "band_k", "shl_k", "shrs_k", "shru_k", + "store_k8", "store_k16", "store_k32", "store_k64", + "jump_eq", "jump_ne", "jump_lts", "jump_ltu", "jump_les", "jump_leu", + "jump_eq_k", "jump_ne_k", "jump_lts_k", "jump_ltu_k", "jump_les_k", "jump_leu_k", + "jump_gts_k", "jump_gtu_k", "jump_ges_k", "jump_geu_k", + "check_ltu", "check_ltu_k", + "load_u8_x", "store_8_x", + "move_jump", "add_k_jump", + "fadd_f32", "fsub_f32", "fmul_f32", "fdiv_f32", + "forget", "watch_read", "watch_write", +]; + +#! Writes a function's code for the machine, one instruction a line, each its +#! place, its operation, and its operand words. +#! @param this The code. +#! @returns The text. +pub def bytecode::print(&this): string { + var out := string::new(nothing {}); + out.append($"frame {this.frame}, cells from {this.cells}\n"); + val code := this.code.view(); + var pc: u64 = 0; + while pc < code.length { + val kind := code[pc]; + val width := bc_width(code, pc); + out.append($"{pc}: "); + out.append(kind < bc::count as u32 ? bc_names[kind as u64] : "?"); + for i in 1..width { + break if pc + i >= code.length; + out.append($" {code[pc + i]}"); + } + out.append("\n"); + pc += width; + } + return out; +} diff --git a/compiler/compiler.sakura b/compiler/compiler.sakura new file mode 100644 index 00000000..2719e126 --- /dev/null +++ b/compiler/compiler.sakura @@ -0,0 +1,475 @@ +#! @file compiler.sakura +#! @author John Christman (sorakatadzuma@gmail.com) +#! @copyright Malunal Studios, LLC. +#! @license MIT +#! +#! Contains the compiler, which lowers a checked program to a program of +#! intermediate code: `main`, the code initializing the globals, and every +#! function they reach, each lowered once something that runs names it. What +#! each node means comes from the checker's tables: a function's nodes from +#! its file's result table, and those of an instance of a generic from the +#! instance's. What lowering does with each part of the language is split +#! across the files of the `emitter` directory, as the checker's are. + +import std::containers; +import sakura::analyzer; +module sakura::compiler; + + +#! How the code is lowered. +pub struct lowering { + pub var keep_locals: bool; #! Whether every named local is kept in a cell of its own, as debugging information wants. + pub var describe: bool; #! Whether the variables of optimized code are noted for debugging information, which changes nothing of the code. + pub var verify: bool; #! Whether each function is verified once lowered. + pub var everything: bool; #! Whether every function that is no generic's template is lowered, not only those `main` reaches. + pub var evaluating: bool; #! Whether the program evaluates constants while compiling, rather than running. + pub var checks: bool; #! Whether what each reference and pointer reaches is checked as the program runs, as `run --checks` asks. + pub var level: u32; #! How much the code is optimized: 0 not at all, 1 within each function, 2 inlining too. + pub var inline_limit: u32; #! The most instructions a function inlined may have, but for its constants, or 0 for `inline_limit`. + pub var threads: u32; #! How many threads optimize and assemble functions at once, the compiler's own among them; 0 or 1 for it alone. +} + +#! The compiler. +pub struct lowerer { + pub var checker: &mut checker; #! The checker, whose tables say what the program means. + pub var program: program; #! What is made. + var options: lowering; #! How the code is lowered. + + var layout_ids: dict; #! The layout of each type. + var laying: u32; #! How many layouts are being made, one within another. + var referents: vector; #! References and pointers laid out, each with the type it reaches, which is laid out once the outermost is. + var signature_ids: dict; #! The signature of each function type. + var function_ids: dict; #! The function of each declaration and instance, by `pair_key(decl, instance)`, the instance one more than its index. + var builtin_ids: dict; #! The function giving each built-in type each method, by `pair_key(type, name)`. + var lambda_ids: dict; #! The function of each anonymous function, by `pair_key(table, node)`. + var adapter_ids: dict; #! The adapter of each function named as a value of another function type, by `pair_key(table, node)`. + var global_ids: dict; #! Where each global is among the globals, by its declaration. + var begun_globals: hashset; #! The globals whose initializers are lowered, or being lowered. + var vtable_ids: dict; #! The vtable of each type for each trait's type, by `pair_key(type, trait)`. + var retrait_ids: dict; #! The map of each conversion between traits' types, by `pair_key(from, to)`. + var linked_ids: dict; #! The C function each foreign declaration calls. + var texts: interner; #! Each text a datum holds. + var text_data: vector; #! The datum holding each text, by its ID in `texts`. + var dispatches: dict; #! The run of the methods of each trait in the order its vtables hold them, in `lists`. + var lists: runs; #! The runs `dispatches` names. + var queue: vector; #! The functions waiting to be lowered. + pub var problems: vector; #! What lowering could not lower, which a program the checker passes never has. + var summaries: dict; #! What each function does with what it is given, by `pair_key(decl, instance)`, once found for good. + var pending: vector; #! The functions whose summaries are being found, in the order they were reached. + var pending_ids: dict; #! The place of each in `pending`, by its key. + var reader_of: vector; #! Of each link of a pending function's readers, the reader, by its place. + var reader_next: vector; #! Of each link, one more than the next link of the same function, or 0. + var read_pairs: hashset; #! The pending functions each reader read, by `pair_key(read, reader)`. + var scanning: u32; #! The pending function whose scan is being made, or `no_scan`. + pub var dispatch: u32; #! The function safe points call, `system::dispatch`, or `no_function` where the program handles no signal. + pub var evaluations: vector; #! Of a program evaluating constants, what it evaluates. + pub var evaluation_ids: dict; #! The evaluation of each constant, condition, or text, by its key. + pub var evaluated: outcomes; #! What evaluating worked out, which the program holds as data. + var constant_data: dict; #! The datum holding each constant evaluated, by its key. +} + +#! Provides read only access to how much the code is optimized: 0 not at all, +#! 1 within each function, 2 inlining too. +#! @param this The compiler. +#! @returns How much. +pub val lowerer::level: u32 { + get => this.options.level; +} + +#! Makes a compiler of a program the checker has checked. +#! @param checker The checker. +#! @param options How the code is lowered. +#! @returns The compiler. +pub def lowerer::new(checker: &mut checker, options: lowering): lowerer { + return lowerer { + checker = checker, + program = program::new(), + options = options, + layout_ids = dict::::new(), + referents = vector::::new(), + signature_ids = dict::::new(), + function_ids = dict::::new(), + builtin_ids = dict::::new(), + lambda_ids = dict::::new(), + adapter_ids = dict::::new(), + global_ids = dict::::new(), + begun_globals = hashset::::new(), + vtable_ids = dict::::new(), + retrait_ids = dict::::new(), + linked_ids = dict::::new(), + texts = interner::::new(), + text_data = vector::::new(), + dispatches = dict::::new(), + lists = runs::::new(), + queue = vector::::new(), + problems = vector::::new(), + summaries = dict::::new(), + pending = vector::::new(), + pending_ids = dict::::new(), + reader_of = vector::::new(), + reader_next = vector::::new(), + read_pairs = hashset::::new(), + scanning = no_scan, + dispatch = no_function, + evaluations = vector::::new(), + evaluation_ids = dict::::new(), + evaluated = outcomes::new(), + constant_data = dict::::new() + }; +} + +#! Lowers the program: the code initializing the globals, `main`, and every +#! function they reach, then fills the vtables' maps between traits. +#! @param this The compiler. +#! @returns Whether everything was lowered, with nothing it could not lower. +pub def lowerer::compile(&mut this): bool { + # A program evaluating constants computes them, and runs nothing else. + if this.options.evaluating { + this.lower_evaluations(); + this.drain(); + this.fill_retraits(); + this.drain(); + return this.problems.length == 0; + } + + val main := this.checker.modules.decl(0, word::main); + if main != 0 && this.checker.decls.kinds.p[main] == dk::function { + this.program.main = this.function_of(main, 0); + } + + this.find_dispatch(); + val point := mark_scratch(); + this.program.init = this.lower_globals(); + release_scratch(point); + if this.options.everything { + this.want_everything(); + } + this.drain(); + this.fill_retraits(); + this.drain(); + this.optimize(); + return this.problems.length == 0; +} + +#! Lowers the functions waiting, and those they reach in turn, each freeing +#! the scratch memory it took as it ends. +#! @param this The compiler. +pub def lowerer::drain(&mut this): void { + var at: u64 = 0; + while at < this.queue.length { + val point := mark_scratch(); + this.lower_function(this.queue[at]); + release_scratch(point); + at++; + } + this.queue.clear(); +} + +#! Notes what lowering could not lower. +#! @param this The compiler. +#! @param file The file it is in. +#! @param node Its node. +#! @param what What it is, said in words. +pub def lowerer::problem(&mut this, file: u32, node: u32, what: strview): void { + val held := &this.checker.units[file].source; + val at := held.lines.place_of(this.node_offset(file, node)); + this.problems.append($"{held.path}:{at.line}:{at.column}: {what}"); +} + +#! The type of a function, or of an instance of it. +#! @param this The compiler. +#! @param decl The function's declaration. +#! @param instance One more than the instance, or 0. +#! @returns The type. +pub def lowerer::type_of_function(&this, decl: u32, instance: u32): u32 { + return instance != 0 ? this.checker.instances[instance - 1].kind : this.checker.decls.types.p[decl]; +} + +#! The table of nodes a function's body was checked in: its instance's, whose +#! instances are checked where they were not yet, or its file's, where it is no +#! instance or the instance's body was never checked. +#! @param this The compiler. +#! @param decl The function's declaration. +#! @param instance One more than the instance, or 0. +#! @returns The table. +pub def lowerer::body_table(&mut this, decl: u32, instance: u32): u32 { + if instance != 0 { + if this.checker.instances[instance - 1].table == 0 { + this.check_instances(); + } + val held: u32 = this.checker.instances[instance - 1].table; + return held - 1 if held != 0; + } + return this.checker.units[this.checker.decls.files.p[decl]].table; +} + +#! The function a declaration is lowered to, given the instance of a generic it +#! is, made and waiting to be lowered where it is new. +#! @param this The compiler. +#! @param decl The function's declaration. +#! @param instance One more than the instance of the checker it is, or 0. +#! @returns The function's index. +pub def lowerer::function_of(&mut this, decl: u32, instance: u32): u32 { + val key := pair_key(decl, instance); + if this.function_ids.get(&key) is some(got) { + return got; + } + + this.checker.resolve(decl); + val kind := this.type_of_function(decl, instance); + val index := this.add_function(this.function_name(decl, instance), this.signature_of(this.call_type(this.function_type(decl, kind)))); + this.function_ids.set(key, index); + val node: u32 = this.checker.decls.nodes.p[decl]; + val file: u32 = this.checker.decls.files.p[decl]; + this.program.functions[index].decl = decl; + this.program.functions[index].instance = instance; + this.program.functions[index].file = file; + this.program.functions[index].offset = this.node_offset(file, node); + this.program.functions[index].callback = this.checker.decls.has(decl, df::callback); + this.program.functions[index].inline = this.checker.decls.has(decl, df::inline); + val name: u32 = this.checker.decls.names.p[decl]; + this.program.functions[index].stepping = this.checker.decls.has(decl, df::method) + && (name == word::next || name == word::next_back || name == word::invoke); + this.want(index); + return index; +} + +#! The function type a function is lowered with: its own, where a trait's +#! default method takes `this` as a reference to the trait rather than to +#! `self`, which only what implements it knows. A default compiled for each +#! type takes its own type, as its type says. +#! @param this The compiler. +#! @param decl The function's declaration. +#! @param kind Its function type, given its type arguments. +#! @returns The function type. +pub def lowerer::function_type(&mut this, decl: u32, kind: u32): u32 { + val holder: u32 = this.checker.decls.owners.p[decl]; + val owner: u32 = holder != 0 && this.checker.decls.kinds.p[holder] == dk::property + ? this.checker.decls.owners.p[holder] + : holder; + return kind if owner == 0 || this.checker.decls.kinds.p[owner] != dk::trait_type + || !this.checker.decls.has(decl, df::method) || this.checker.typed_default(decl); + + # An instance of a generic trait's default already takes the trait, given + # its arguments. + var params := this.checker.types.parts_of(kind); + return kind if params.length == 0; + val taken := this.checker.unalias(this.checker.types.first_of(params[0])); + return kind if this.checker.named_kind(taken) == dk::trait_type; + val writes := this.checker.decls.has(decl, df::mut_this); + params[0] = this.checker.types.reference(this.checker.decls.types.p[owner], writes); + return this.checker.types.function(params.view(), this.checker.types.first_of(kind), this.checker.types.second_of(kind) != 0); +} + +#! Adds a function of the program, lowered later. +#! @param this The compiler. +#! @param name Its name, as a trace writes it. +#! @param signature How it is called. +#! @returns Its index. +pub def lowerer::add_function(&mut this, name: string, signature: u32): u32 { + this.program.functions.append(function { + name = move(&mut name), + signature = signature, + body = code::new(), + compiled = bytecode::new(), + order = vector::::new(), + named = vector::::new() + }); + return (this.program.functions.length - 1) as u32; +} + +#! Notes that a function's code names another as a value, each once. +#! @param this The compiler. +#! @param function The function naming it. +#! @param named The function named. +pub def lowerer::names(&mut this, function: u32, named: u32): void { + for &each in this.program.functions[function].named.view() { + return if each == named; + } + this.program.functions[function].named.append(named); +} + +#! Marks a function as named by code that runs, so it is lowered. +#! @param this The compiler. +#! @param index The function. +pub def lowerer::want(&mut this, index: u32): void { + return if this.program.functions[index].queued; + this.program.functions[index].queued = true; + this.queue.append(index); +} + +#! The name of a function as a trace writes it, as the C compiler names it: a +#! method's names its type, as `vec2::normalize`, and an instance of a generic +#! names its type arguments, as `max` and `list::push`. +#! @param this The compiler. +#! @param decl The function's declaration. +#! @param instance One more than the instance of a generic it is, or 0. +#! @returns The name. +pub def lowerer::function_name(&mut this, decl: u32, instance: u32): string { + var holder: u32 = this.checker.decls.owners.p[decl]; + if holder != 0 && this.checker.decls.kinds.p[holder] == dk::property { + holder = this.checker.decls.owners.p[holder]; + } + + # The type arguments of an instance are its owner's, then its own. + val args := instance != 0 ? this.checker.types.parts_view(this.checker.instances[instance - 1].args) : span::::empty(); + val own := this.checker.own_param_count(decl) as u64; + val outer := args.length > own ? args.length - own : 0; + + var made := string::new(nothing {}); + if holder != 0 { + made.append(this.checker.names.text(this.checker.decls.names.p[holder])); + if outer != 0 { + this.type_args(args, 0, outer, &mut made); + } + made.append("::"); + } + made.append(this.checker.names.text(this.checker.decls.names.p[decl])); + if own != 0 && args.length > outer { + this.type_args(args, outer, args.length, &mut made); + } + return made; +} + +#! Writes type arguments as a name shows them, ``, a pack's types as +#! the arguments they are, and an empty pack as none, as the checker writes them. +#! @param this The compiler. +#! @param args The type arguments. +#! @param from The first written. +#! @param to The one past the last written. +#! @param out Where they are written. +def lowerer::type_args(&this, args: span, from: u64, to: u64, out: &mut string): void { + out.append("<"); + this.checker.describe_args(span::::over(args.data + from, to - from), out); + out.append(">"); +} + +#! The byte of a file a node begins at. +#! @param this The compiler. +#! @param file The file. +#! @param node The node. +#! @returns The byte. +pub def lowerer::node_offset(&this, file: u32, node: u32): u32 { + val syntax := &this.checker.units[file].syntax; + return syntax.token_offsets[syntax.node_tokens[node]]; +} + +#! Lowers a function waiting to be lowered. +#! @param this The compiler. +#! @param index The function. +def lowerer::lower_function(&mut this, index: u32): void { + return if this.program.functions[index].lowered; + this.program.functions[index].lowered = true; + + var made := emitter::new(this, index); + made.lower(); + made.finish(); +} + +#! The datum holding text, made where it is new: its bytes, followed by a zero +#! the length does not count. +#! @param this The compiler. +#! @param text The text. +#! @returns The datum's index. +pub def lowerer::text_datum(&mut this, text: strview): u32 { + # A text new to `texts` is given the next ID, which has no datum yet. + val id := this.texts.intern_view(text); + if id < this.text_data.length { + return this.text_data[id]; + } + + var bytes := vector::::new(); + bytes.extend(text); + bytes.append(0); + val index := this.program.data.length as u32; + this.program.data.append(datum { + bytes = move(&mut bytes), + align = 1, + relocations = vector::::new() + }); + this.text_data.append(index); + return index; +} + +#! Places a global after those placed before it, where it is not yet placed. +#! @param this The compiler. +#! @param decl The global's declaration. +#! @returns Where it is among the globals. +pub def lowerer::global_of(&mut this, decl: u32): u64 { + if this.global_ids.get(&decl) is some(got) { + return got; + } + + this.checker.resolve(decl); + val held := this.shape_of(this.checker.decls.types.p[decl]); + this.program.globals = round_up(this.program.globals, held.align); + val offset := this.program.globals; + this.global_ids.set(decl, offset); + this.program.globals += held.size; + + # Evaluating, a byte between globals keeps an address just past one from being + # where the next begins, so an empty view at the end of a constant's array is + # still that constant's. + if this.options.evaluating { + this.program.globals += 1; + } + return offset; +} + +#! Places a global no declaration names after those placed before it, as what +#! a global refers to that was made for it is. +#! @param this The compiler. +#! @param kind Its type. +#! @returns Where it is among the globals. +pub def lowerer::unnamed_global(&mut this, kind: u32): u64 { + val held := this.shape_of(kind); + this.program.globals = round_up(this.program.globals, held.align); + val offset := this.program.globals; + this.program.globals += held.size == 0 ? 1 : held.size; + return offset; +} + +#! Asks for every function that is no generic's template, and has a body, as a +#! library's tests want, rather than only those `main` reaches. +#! @param this The lowerer. +def lowerer::want_everything(&mut this): void { + for id in 1..this.checker.decls.count { + val decl := id as u32; + continue if this.checker.decls.kinds.p[decl] != dk::function || this.checker.decls.has(decl, df::generic); + continue if this.checker.decls.has(decl, df::intrinsic) || this.checker.decls.has(decl, df::failed); + continue if !this.checker.has_body(decl) || this.trait_of_method(decl) != 0; + this.function_of(decl, 0); + } +} + +#! Gives the program safe points where it handles a signal, which is where +#! anything calls `system::handle`: each calls `system::dispatch`, which runs +#! the handlers of the signals that have come. +#! @param this The lowerer. +def lowerer::find_dispatch(&mut this): void { + val sys := this.checker.modules.find(0, word::system); + return if sys == 0; + val handle := this.checker.modules.decl(sys, this.checker.names.intern(&"handle")); + val dispatch := this.checker.modules.decl(sys, this.checker.names.intern(&"dispatch")); + return if handle == 0 || dispatch == 0 || this.checker.decls.kinds.p[dispatch] != dk::function; + + return if !this.checker.is_depended(handle); + this.dispatch = this.function_of(dispatch, 0); +} + +#! Whether a declaration is `core`'s, std's, or `system`'s, whose code has no +#! safe points. +#! @param this The lowerer. +#! @param decl The declaration. +#! @returns Whether it is. +pub def lowerer::in_std(&this, decl: u32): bool { + var at: u32 = this.checker.decls.modules.p[decl]; + var steps := 0; + while at != 0 && this.checker.modules.parents[at] != 0 && steps < 64 { + at = this.checker.modules.parents[at]; + steps++; + } + return at != 0 && (this.checker.modules.names[at] == word::std + || this.checker.modules.names[at] == word::core + || this.checker.modules.names[at] == word::system); +} diff --git a/compiler/constants.sakura b/compiler/constants.sakura new file mode 100644 index 00000000..a31516a8 --- /dev/null +++ b/compiler/constants.sakura @@ -0,0 +1,358 @@ +#! @file constants.sakura +#! @author John Christman (sorakatadzuma@gmail.com) +#! @copyright Malunal Studios, LLC. +#! @license MIT +#! +#! Contains the values computed while compiling: the constants, the +#! conditions of the `if const` statements the checker left undecided, and the +#! text of each `compile_error` it was given text it could not read. +#! +#! A program evaluating them is lowered first, with a function of its own for +#! each, which computes the value into a global. Reading a constant stops that +#! program unless the constant is evaluated, so the machine evaluates the one it +#! needs first; and it stops reading what only a running program has, such as +#! a variable given its value once it runs. +#! +#! The value each computes is kept as bytes laid out as its type, with the +#! memory it points into, each address within them noted rather than written, +#! since the memory it was computed in is the compiler's. The program then +#! holds each as data, whose addresses are written where it is placed: a +#! constant is read where its data is, and a condition decides its branch. + +import sakura::analyzer; +import std::containers; +module sakura::compiler; + + +#! What stands for no block, where an address a value holds names a function. +pub const no_block: u32 = 0xFFFFFFFF; + +#! What stands for a block, where an address a value holds points into another +#! constant's value, which `decl`, or `table` and `node`, name as for a function. +pub const in_constant: u32 = 0xFFFFFFFE; + +#! Where a value computed while compiling holds an address: of memory it points +#! into, kept as a block, of another constant's value, or of a function, as a +#! function value holds it. +pub struct kept_address { + pub var at: u64; #! The byte of the value or block the address is written at. + pub var block: u32; #! The block it points into, `in_constant`, or `no_block` for a function. + pub var addend: u64; #! How far into the block or the constant's value it points. + pub var decl: u32; #! The function's or the global constant's declaration, or 0 for an anonymous function or a local constant. + pub var instance: u32; #! One more than the instance of a generic it is, or 0. + pub var table: u32; #! Of an anonymous function or a local constant, the result table of its nodes. + pub var node: u32; #! Of an anonymous function, its `lambda` node, and of a local constant, its `variable` node. + pub var file: u32; #! Of an anonymous function, its file. +} + +#! Memory a value computed while compiling points into. +pub struct kept_block { + pub var bytes: vector; #! What it holds. + pub var addresses: vector; #! Where it holds addresses. +} + +#! A value computed while compiling: its bytes, laid out as its type is, and +#! the memory it reaches. +pub struct evaluated { + pub var bytes: vector; #! The value. + pub var addresses: vector; #! Where it holds addresses. + pub var blocks: vector; #! The memory it points into, which addresses name by index. +} + +#! What evaluating worked out, by the key of each constant, condition, or text. +pub struct outcomes { + pub var values: dict; #! The value of each constant. + pub var decisions: dict; #! Whether the condition of each `if const` holds. + pub var texts: dict; #! What each `compile_error` evaluating reports says. +} + +#! Makes outcomes holding nothing. +#! @returns The outcomes. +pub def outcomes::new(): outcomes { + return outcomes { + values = dict::::new(), + decisions = dict::::new(), + texts = dict::::new() + }; +} + +#! The key of a global constant. +#! @param decl Its declaration. +#! @returns The key. +pub def decl_key(decl: u32): u64 { + return decl as u64; +} + +#! The key of a local constant, the condition of an `if const`, or the text of +#! a `compile_error`: the result table it was checked in, and its node. +#! @param table The table. +#! @param node The `variable`, `if_const`, or `call` node. +#! @returns The key. +pub def node_key(table: u32, node: u32): u64 { + return (1u << 63) | pair_key(table, node); +} + +#! A value computed while compiling, in the program evaluating them. +pub struct evaluation { + pub var key: u64; #! Its key. + pub var decl: u32; #! The global constant, or 0. + pub var table: u32; #! The result table a local constant, condition, or text was checked in. + pub var node: u32; #! Its `variable`, `if_const`, or `call` node. + pub var condition: bool; #! Whether it is the condition of an `if const`. + pub var text: bool; #! Whether it is the text of a `compile_error`, its first argument. + pub var kind: u32; #! The type of its value. + pub var offset: u64; #! The global holding its value. + pub var function: u32; #! The function computing it. +} + +#! Lowers the program evaluating what the checker left to evaluating: every +#! global constant whose value is not a number it worked out, and the local +#! constants, conditions of `if const`, and text of `compile_error` it noted. +#! @param this The compiler. +pub def lowerer::lower_evaluations(&mut this): void { + for id in 1..this.checker.decls.count { + val decl := id as u32; + continue if !this.needs_evaluation(decl); + this.evaluation_of(decl_key(decl), decl, 0, 0, false); + } + for i in 0..this.checker.to_evaluate.length { + val each: u64 = this.checker.to_evaluate[i]; + val table := pair_high(each); + val node := pair_low(each); + val syntax := &this.checker.units[this.checker.tables.p[table].file].syntax; + val condition := syntax.node_kinds[node] == nk::if_const; + this.evaluation_of(node_key(table, node), 0, table, node, condition); + } +} + +#! Whether a declaration is a global constant whose value is evaluated: one the +#! checker did not work out as a number, or one of a struct, a union, or an +#! array. +#! @param this The compiler. +#! @param decl The declaration. +#! @returns Whether it is. +pub def lowerer::needs_evaluation(&mut this, decl: u32): bool { + return false if this.checker.decls.kinds.p[decl] != dk::variable || !this.checker.decls.has(decl, df::constant); + return false if this.checker.decls.has(decl, df::failed) || this.checker.decls.nodes.p[decl] == 0; + val owner: u32 = this.checker.decls.owners.p[decl]; + return false if owner != 0 && this.checker.own_param_count(owner) != 0; + + val saved := this.checker.at; + this.checker.use_table(this.checker.units[this.checker.decls.files.p[decl]].table); + val value := this.checker.record(this.checker.decls.nodes.p[decl], variable_slot::value); + val known := value != 0 && this.checker.is_known(value) && this.is_scalar_type(this.checker.decls.types.p[decl]); + this.checker.at = saved; + return value != 0 && !known; +} + +#! Whether values of a type are one word, as a number, `bool`, enum, or pointer. +#! @param this The compiler. +#! @param kind The type. +#! @returns Whether they are. +pub def lowerer::is_scalar_type(&mut this, kind: u32): bool { + return false if kind == bt::error || kind == bt::void_type || kind == 0; + val plain := this.layout_type(kind); + return this.checker.types.is_numeric(plain) || this.checker.types.is_boolean(plain) + || this.checker.named_kind(plain) == dk::enum_type || this.checker.types.kind_of(plain) == ty::pointer; +} + +#! The evaluation computing a constant, condition, or text, made where it is +#! new: a global holding its value, and a function computing it there. +#! @param this The compiler. +#! @param key Its key. +#! @param decl The global constant, or 0. +#! @param table The result table of a local constant, condition, or text. +#! @param node Its node: of text, the `compile_error` call. +#! @param condition Whether it is the condition of an `if const`. +#! @returns Its index. +pub def lowerer::evaluation_of(&mut this, key: u64, decl: u32, table: u32, node: u32, condition: bool): u32 { + if this.evaluation_ids.get(&key) is some(got) { + return got; + } + + val saved := this.checker.at; + var kind: u32 = bt::boolean; + var offset: u64 = 0; + var text := false; + var name := string::new(nothing {}); + if decl != 0 { + this.checker.resolve(decl); + kind = this.checker.decls.types.p[decl]; + offset = this.global_of(decl); + name.append(this.checker.names.text(this.checker.decls.names.p[decl])); + } else { + this.checker.use_table(table); + text = !condition && this.checker.kind_of(node) == nk::call; + if text { + # Text is evaluated as the type it is given as, as a `string` that owns + # its bytes, rather than the view `compile_error` takes of them. + kind = this.checker.type_at(this.checker.run_at(this.checker.right_of(node), 0)); + name.append(""); + } else if !condition { + kind = this.checker.type_at(node); + name.append(this.checker.names.text(this.checker.name_of(node))); + } else { + name.append(""); + } + val held := this.shape_of(kind); + this.program.globals = round_up(this.program.globals, held.align); + offset = this.program.globals; + this.program.globals += (held.size == 0 ? word_size : held.size) + 1; + } + this.checker.at = saved; + + val void_type := this.checker.types.function(span::::empty(), bt::void_type, false); + val function := this.add_function(move(&mut name), this.signature_of(void_type)); + val index := this.evaluations.length as u32; + this.evaluations.append(evaluation { + key = key, + decl = decl, + table = table, + node = node, + condition = condition, + text = text, + kind = kind, + offset = offset, + function = function + }); + this.evaluation_ids.set(key, index); + this.program.functions[function].evaluation = index + 1; + this.want(function); + return index; +} + +#! Lowers the function computing an evaluation's value into its global. +#! @param this The emitter. +#! @param index The evaluation. +pub def emitter::lower_evaluation(&mut this, index: u32): void { + val held: evaluation = this.c.evaluations[index]; + var value: u32 = 0; + if held.decl != 0 { + this.table = this.c.checker.units[this.c.checker.decls.files.p[held.decl]].table; + this.use_own_table(); + value = this.c.checker.record(this.c.checker.decls.nodes.p[held.decl], variable_slot::value); + this.at_node(this.c.checker.decls.nodes.p[held.decl]); + } else { + this.table = held.table; + this.use_own_table(); + if held.condition { + value = this.c.checker.left_of(held.node); + } else if held.text { + value = this.c.checker.run_at(this.c.checker.right_of(held.node), 0); + } else { + value = this.c.checker.record(held.node, variable_slot::value); + } + this.at_node(held.node); + } + this.result = bt::void_type; + this.plan_storage(value); + + val mark := this.begin_statement(); + val address := this.build.value(op::global, span::::empty(), vt::word, 0, held.offset); + val place := location { kind = held.kind, address = address }; + val made := this.value_as(value, held.kind); + this.adopt(&made); + this.store(&place, &made); + this.end_statement(mark); + this.build.ret(span::::empty()); +} + +#! The data holding a value computed while compiling, made where it is new: +#! the memory it points into first, then the value, each address within them +#! written where the data is placed, and each function as it is numbered here. +#! @param this The compiler. +#! @param key The constant's key. +#! @param kind Its type. +#! @returns The datum, or `no_block` where nothing was evaluated for it. +pub def lowerer::evaluated_datum(&mut this, key: u64, kind: u32): u32 { + if this.constant_data.get(&key) is some(got) { + return got; + } + return no_block if !this.evaluated.values.contains(&key); + + # Each block is placed before any is written, since one may point into another. + val count := this.evaluated.values[key].blocks.length; + val first := this.program.data.length as u32; + for _ in 0..count { + this.program.data.append(datum { bytes = vector::::new(), align = 16, relocations = vector::::new() }); + } + for b in 0..count { + var bytes := vector::::copy_of(&this.evaluated.values[key].blocks[b].bytes); + var moved := vector::::new(); + var addresses := vector::::copy_of(&this.evaluated.values[key].blocks[b].addresses); + this.place_addresses(&mut bytes, &mut moved, addresses.view(), first); + bytes.append(0); + this.program.data[first as u64 + b].bytes = move(&mut bytes); + this.program.data[first as u64 + b].relocations = move(&mut moved); + } + + var bytes := vector::::copy_of(&this.evaluated.values[key].bytes); + var moved := vector::::new(); + var addresses := vector::::copy_of(&this.evaluated.values[key].addresses); + this.place_addresses(&mut bytes, &mut moved, addresses.view(), first); + bytes.append(0); + val shape := this.shape_of(kind); + val index := this.program.data.length as u32; + this.program.data.append(datum { + bytes = move(&mut bytes), + align = shape.align < word_size ? word_size : shape.align, + relocations = move(&mut moved) + }); + this.constant_data.set(key, index); + return index; +} + +#! Writes the addresses a value computed while compiling holds: each of a +#! block as a relocation into the data the block became, each into another +#! constant as one into the data that constant's value is, and each function +#! as its index here plus one. +#! @param this The compiler. +#! @param bytes The bytes holding them. +#! @param moved Where the relocations are written. +#! @param addresses The addresses. +#! @param first The datum the first block became. +def lowerer::place_addresses(&mut this, bytes: &mut vector, moved: &mut vector, addresses: span, first: u32): void { + for &each in addresses { + if each.block == in_constant { + # The constant was evaluated before the one pointing into it, so its data + # never waits on this. + moved.append(relocation { at = each.at, target = this.constant_datum(each.decl, each.table, each.node), addend = each.addend }); + continue; + } + if each.block != no_block { + moved.append(relocation { at = each.at, target = first + each.block, addend = each.addend }); + continue; + } + var function: u32 = 0; + if each.decl != 0 { + function = this.function_of(each.decl, each.instance); + } else { + val saved := this.checker.at; + this.checker.use_table(each.table); + val kind := this.checker.type_at(each.node); + this.checker.at = saved; + function = this.lambda_of(each.table, each.node, each.file, kind, false); + } + this.program.functions[function].taken = true; + val word := function as u64 + 1; + write_number(bytes, each.at, word_size, word); + } +} + +#! The data holding another constant's value, which an address a value holds +#! points into, made where it is new. +#! @param this The compiler. +#! @param decl The global constant, or 0 for a local one. +#! @param table Of a local constant, the result table it was checked in. +#! @param node Of a local constant, its `variable` node. +#! @returns The datum. +def lowerer::constant_datum(&mut this, decl: u32, table: u32, node: u32): u32 { + if decl != 0 { + return this.evaluated_datum(decl_key(decl), this.checker.decls.types.p[decl]); + } + val saved := this.checker.at; + this.checker.use_table(table); + val kind := this.checker.type_at(node); + this.checker.at = saved; + return this.evaluated_datum(node_key(table, node), kind); +} diff --git a/compiler/conventions.sakura b/compiler/conventions.sakura new file mode 100644 index 00000000..0664d91b --- /dev/null +++ b/compiler/conventions.sakura @@ -0,0 +1,31 @@ +#! @file conventions.sakura +#! @author John Christman (sorakatadzuma@gmail.com) +#! @copyright Malunal Studios, LLC. +#! @license MIT +#! +#! Contains what the machine and the native backend both know of how calls +#! cross to C: how many words of a frame a value passed to a function of the +#! program takes, and which aggregates Microsoft's ABI passes by value. The +#! machine calls C through code of its own on Windows, and the native backend +#! writes the code of each call, so both cross by these rules. + +module sakura::compiler; + + +#! How many words of a frame a value of a layout takes as an argument of a +#! function of the program: the address of one held in memory, or its words. +#! @param shape The layout. +#! @returns How many. +pub def argument_words(shape: &layout): u64 { + return in_memory(shape) ? 1 : word_count(shape) as u64; +} + +#! Whether Microsoft's ABI passes an aggregate of a size by value, as an integer +#! of as many bytes, which it does for one of 1, 2, 4, or 8 bytes. It passes any +#! other by the address of a copy, and returns it through memory whose address +#! the caller passes. +#! @param size The aggregate's bytes. +#! @returns Whether it does. +pub def micro_by_value(size: u64): bool { + return size == 1 || size == 2 || size == 4 || size == 8; +} diff --git a/compiler/dispatch.sakura b/compiler/dispatch.sakura new file mode 100644 index 00000000..0b1e2937 --- /dev/null +++ b/compiler/dispatch.sakura @@ -0,0 +1,427 @@ +#! @file dispatch.sakura +#! @author John Christman (sorakatadzuma@gmail.com) +#! @copyright Malunal Studios, LLC. +#! @license MIT +#! +#! Contains how calls reach the functions they call: the instance of a method +#! a value of a generic type is given, the order a trait's vtables hold its +#! methods in, each type's vtable for each trait it is referred to through, the +#! maps a reference to one trait becomes one to another by, and the C functions +#! the program calls by name. + +import sakura::analyzer; +module sakura::compiler; + + +#! What a method called on a value of a type reaches: a function of the +#! program, or a trait's method, called through a vtable. +pub struct target { + var function: u32; #! The function called directly, or `no_function`. + var holder: u32; #! The trait whose vtable is called through, or 0. + var kind: u32; #! The method's function type, given the type's arguments. +} + +#! What a method called on a value of a type reaches: the instance of a generic +#! type's method, given the type's arguments, a function of its own, or a +#! trait's method, which a value of a type parameter or a reference to a trait +#! calls through a vtable. +#! @param this The compiler. +#! @param decl The method's declaration. +#! @param owner The type it is called on, read through its references. +#! @returns What it reaches. +pub def lowerer::method_target(&mut this, decl: u32, owner: u32): target { + this.checker.resolve(decl); + var holder: u32 = this.checker.decls.owners.p[decl]; + if holder != 0 && this.checker.decls.kinds.p[holder] == dk::property { + holder = this.checker.decls.owners.p[holder]; + } + val plain := this.checker.unalias(owner); + if this.checker.trait_asks(decl) { + val kind := this.checker.trait_method_type(decl, plain); + val dynamic := this.checker.named_kind(plain) == dk::trait_type || this.checker.types.kind_of(plain) == ty::param; + if dynamic || !this.checker.has_body(decl) { + return target { function = no_function, holder = holder, kind = kind }; + } + val own := span::::empty(); + return target { function = this.default_of(decl, this.checker.implemented(plain, holder), plain, own), kind = kind }; + } + + if !this.checker.decls.has(decl, df::generic) { + return target { function = this.function_of(decl, 0), kind = this.checker.decls.types.p[decl] }; + } + + # A generic type's method is the instance its arguments give. + var args := vector::::new(); + if this.checker.types.kind_of(plain) == ty::named { + for i in 0..this.checker.types.part_count(plain) { + args.append(this.checker.types.part_at(plain, i as u32)); + } + } + val instance := this.checker.instance_of(decl, args.view(), 0); + if instance == 0 { + return target { function = this.function_of(decl, 0), kind = this.checker.method_type(decl, plain) }; + } + return target { + function = this.function_of(decl, instance), + kind = this.checker.instances[instance - 1].kind + }; +} + +#! Checks the bodies of the instances asked for since the checker last did, +#! which lowering asks for where it calls a method the checker only looked up, +#! as a loop's `next` or a value's `close`. +#! @param this The compiler. +pub def lowerer::check_instances(&mut this): void { + val notes := this.checker.notes_made; + this.checker.check_wanted(); + if this.checker.notes_made != notes { + this.problems.append("Checking an instance lowering asked for made notes."); + } +} + +#! The methods of a trait in the order its vtables hold them: what it takes on +#! from the traits it composes, in order, and then what it declares itself, the +#! accessors of a property among them. A member taken on is numbered by each +#! trait taking it in its own order. +#! @param this The compiler. +#! @param holder The trait's declaration. +#! @returns The run of the methods in `lists`. +pub def lowerer::dispatch_of(&mut this, holder: u32): u32 { + if this.dispatches.get(&holder) is some(got) { + return got; + } + + var methods := vector::::new(); + this.collect_dispatch(holder, &mut methods, 0); + val run := this.lists.add(methods.view()); + this.dispatches.set(holder, run); + return run; +} + +#! Collects the methods a trait's vtables hold, those of the traits it composes +#! first, each once. +#! @param this The compiler. +#! @param holder The trait's declaration. +#! @param methods Where they are collected. +#! @param depth How deeply composition has been followed. +def lowerer::collect_dispatch(&mut this, holder: u32, methods: &mut vector, depth: u32): void { + return if depth > 16; + val composed := this.checker.composed_of(holder); + for i in 0..this.checker.decls.list_length(composed) { + val inner := this.checker.types.first_of(this.checker.decls.list_at(composed, i as u32)); + this.collect_dispatch(inner, methods, depth + 1); + } + + val run: u32 = this.checker.decls.children.p[holder]; + for i in 0..this.checker.decls.list_length(run) { + val member := this.checker.decls.list_at(run, i as u32); + match this.checker.decls.kinds.p[member] { + dk::function => this.add_method(member, methods); + dk::property => { + val accessors: u32 = this.checker.decls.children.p[member]; + for j in 0..this.checker.decls.list_length(accessors) { + this.add_method(this.checker.decls.list_at(accessors, j as u32), methods); + } + } + else => {} + } + } +} + +#! Adds a method to those a vtable holds, where it is not there already. +#! @param this The compiler. +#! @param method The method's declaration. +#! @param methods The methods so far. +def lowerer::add_method(&mut this, method: u32, methods: &mut vector): void { + return if methods.view().contains(&method); + methods.append(method); +} + +#! The slot of a method among those a trait's vtables hold. +#! @param this The compiler. +#! @param holder The trait's declaration. +#! @param method The method's declaration. +#! @returns The slot. +pub def lowerer::dispatch_index(&mut this, holder: u32, method: u32): u32 { + val run := this.dispatch_of(holder); + if this.lists.view(run).index_of(&method) is some(slot) { + return slot as u32; + } + return 0; +} + +#! The signature a call through a trait's vtable passes arguments by: the +#! method's, taking `this` as a reference to the trait, and giving the type the +#! call gives, which a generic trait's method gives in terms of the trait's +#! arguments. +#! @param this The compiler. +#! @param method The method's declaration. +#! @param holder The trait referred to. +#! @param result The type the call gives. +#! @returns The signature's index. +pub def lowerer::trait_signature(&mut this, method: u32, holder: u32, result: u32, trait_kind: u32 = 0): u32 { + this.checker.resolve(method); + # A trait's method in terms of the arguments of the trait referred to, as a + # pack it takes is the parameters of its types. + val kind: u32 = trait_kind != 0 + ? this.checker.requirement_type(method, this.checker.bound_for(trait_kind, this.trait_of_method(method)), trait_kind) + : this.checker.decls.types.p[method]; + var params := this.checker.types.parts_of(kind); + if params.length != 0 { + params[0] = this.checker.types.reference(this.checker.decls.types.p[holder], this.checker.decls.has(method, df::mut_this)); + } + val made := this.checker.types.function(params.view(), result, this.checker.types.second_of(kind) != 0); + return this.signature_of(this.call_type(made)); +} + +#! The vtable of a type for a trait it implements, made where it is new, which +#! names the function giving each of the trait's methods, or the trait's default +#! where the type gives none. +#! @param this The compiler. +#! @param kind The type referred to. +#! @param trait_kind The trait's type, given its arguments. +#! @returns The vtable's index. +pub def lowerer::vtable_of(&mut this, kind: u32, trait_kind: u32): u32 { + # An alias's methods come before those of what it stands for, so its vtable + # is its own. + val plain := this.checker.unalias(kind); + val key := pair_key(kind, trait_kind); + if this.vtable_ids.get(&key) is some(got) { + return got; + } + + # Placed before its slots are filled, which may make more vtables. + val holder := this.checker.types.first_of(trait_kind); + val index := this.program.vtables.length as u32; + this.program.vtables.append(vtable { + type_id = kind, + trait_id = trait_kind, + layout = this.layout_of(plain), + functions = vector::::new(), + owners = vector::::new() + }); + this.vtable_ids.set(key, index); + + # Read by place, since making the vtables its slots name may add runs. + val run := this.dispatch_of(holder); + for i in 0..this.lists.length(run) { + val method: u32 = this.lists.at(run, i); + var function := no_function; + var owner := index; + val found := this.implementation(kind, method, trait_kind); + if found != 0 && this.trait_of_method(found) == 0 { + function = this.method_target(found, kind).function; + } else if this.checker.has_body(method) { + # The default addresses the slots of the trait declaring it. + val declarer := this.trait_of_method(method); + val declaring := this.checker.bound_for(trait_kind, declarer); + function = this.default_of(method, declaring, plain, span::::empty()); + if declarer != holder { + owner = this.vtable_of(kind, declaring); + } + } else if found != 0 && this.checker.has_body(found) { + function = this.default_of(found, this.checker.bound_for(trait_kind, this.trait_of_method(found)), plain, span::::empty()); + } else if found == 0 { + # A built-in type's method is a function the compiler makes. + function = this.builtin_function(plain, this.checker.decls.names.p[method]); + } + this.program.vtables[index].functions.append(function); + this.program.vtables[index].owners.append(owner); + } + return index; +} + +#! The function a trait's default method is, for the trait given its +#! arguments: an instance of it where the trait is generic, so its body is +#! lowered with the types the arguments give, or for the type taking it, where +#! the trait is only a bound. +#! @param this The compiler. +#! @param method The default's declaration. +#! @param trait_kind The trait declaring it, given its arguments. +#! @param self_kind The type taking it. +#! @param own The default's own type arguments. +#! @returns The function's index. +pub def lowerer::default_of(&mut this, method: u32, trait_kind: u32, self_kind: u32, own: span): u32 { + return this.function_of(method, this.checker.default_instance(method, trait_kind, self_kind, own)); +} + +#! The trait a method is a member of, directly or as a property's accessor, or +#! 0. +#! @param this The compiler. +#! @param method The method's declaration. +#! @returns The trait's declaration, or 0. +pub def lowerer::trait_of_method(&this, method: u32): u32 { + var owner: u32 = this.checker.decls.owners.p[method]; + if owner != 0 && this.checker.decls.kinds.p[owner] == dk::property { + owner = this.checker.decls.owners.p[owner]; + } + return this.checker.trait_asks(method) ? owner : 0; +} + +#! The method of a type implementing a trait's: of its overloads, the one taking +#! what the trait's does, or the trait's default where the type has none. +#! @param this The compiler. +#! @param kind The type. +#! @param method The trait's method. +#! @returns The type's method, or 0. +def lowerer::implementation(&mut this, kind: u32, method: u32, trait_kind: u32): u32 { + # A property's accessor is found through the property of its name. + var name: u32 = this.checker.decls.names.p[method]; + val setter := this.checker.decls.has(method, df::setter); + val accessor := this.checker.decls.has(method, df::accessor); + val found := this.checker.find_member(kind, name); + return 0 if found.decl == 0; + + if accessor { + return 0 if this.checker.decls.kinds.p[found.decl] != dk::property; + val run: u32 = this.checker.decls.children.p[found.decl]; + for i in 0..this.checker.decls.list_length(run) { + val each := this.checker.decls.list_at(run, i as u32); + return each if this.checker.decls.has(each, df::setter) == setter; + } + return 0; + } + + # Of overloads, the one with the method's shape, in terms of the trait's + # arguments, as a pack it takes is the parameters of its types: as many + # parameters, and `&mut this` where it takes it, or else `&this`, which meets + # it too. + this.checker.resolve(method); + val asked := this.checker.requirement_type(method, this.checker.bound_for(trait_kind, this.trait_of_method(method)), kind); + val wanted := this.checker.types.part_count(asked); + var first: u32 = 0; + var counted: u32 = 0; + var walk := this.checker.decls.walk_overloads(found.decl); + while true { + val at := walk.next(); + break if at == 0; + if this.checker.decls.kinds.p[at] == dk::function && this.checker.decls.has(at, df::method) { + this.checker.resolve(at); + val count := this.checker.types.part_count(this.checker.decls.types.p[at]); + if first == 0 { + first = at; + } + if count == wanted && counted == 0 { + counted = at; + } + if count == wanted && this.checker.decls.has(at, df::mut_this) == this.checker.decls.has(method, df::mut_this) { + return at; + } + } + } + return counted != 0 ? counted : first; +} + +#! The map a reference to one trait becomes one to another by, made where it is +#! new, and filled once every vtable is made. +#! @param this The compiler. +#! @param from The trait's type converted from. +#! @param to The trait's type converted to. +#! @returns The map's index. +pub def lowerer::retrait_of(&mut this, from: u32, to: u32): u32 { + val key := pair_key(from, to); + if this.retrait_ids.get(&key) is some(got) { + return got; + } + val index := this.program.retraits.length as u32; + this.program.retraits.append(retrait { from = from, to = to, vtables = vector::::new() }); + this.retrait_ids.set(key, index); + return index; +} + +#! Fills each map between traits with the vtable each vtable of its trait +#! becomes, once the code is lowered. Making a vtable of a trait converted to +#! may make more, so every map is settled before any is filled. +#! @param this The compiler. +pub def lowerer::fill_retraits(&mut this): void { + return if this.program.retraits.length == 0; + var done: u64 = 0; + while done < this.program.vtables.length { + val count := this.program.vtables.length; + for v in done..count { + for i in 0..this.program.retraits.length { + val from: u32 = this.program.retraits[i].from; + val to: u32 = this.program.retraits[i].to; + if this.program.vtables[v].trait_id == from { + this.vtable_of(this.program.vtables[v].type_id, to); + } + } + } + done = count; + } + + for i in 0..this.program.retraits.length { + var map := vector::::new(); + for v in 0..this.program.vtables.length { + val held_trait: u32 = this.program.vtables[v].trait_id; + if held_trait == this.program.retraits[i].from { + map.append(this.vtable_of(this.program.vtables[v].type_id, this.program.retraits[i].to)); + } else { + map.append(0); + } + } + this.program.retraits[i].vtables = move(&mut map); + } +} + +#! The C function a declaration of an `extern module` without a body calls, +#! among those the program links, found by its name in its file's libraries. +#! @param this The compiler. +#! @param decl The declaration. +#! @returns The C function's index. +pub def lowerer::linked_of(&mut this, decl: u32): u32 { + if this.linked_ids.get(&decl) is some(got) { + return got; + } + val index := this.program.linked.length as u32; + var libraries := this.libraries_of(decl); + var first := libraries.length != 0 ? string::copy_of(&libraries[0]) : string::new(nothing {}); + this.program.linked.append(linked { + name = this.checker.decls.names.p[decl], + library = move(&mut first), + libraries = move(&mut libraries), + decl = decl + }); + this.linked_ids.set(decl, index); + return index; +} + +#! The libraries a C function may be found in: those its file's `extern import`s +#! name for the target, or none for one the running program has. +#! @param this The lowerer. +#! @param decl The function's declaration. +#! @returns The libraries. +def lowerer::libraries_of(&mut this, decl: u32): vector { + var libraries := vector::::new(); + val file: u32 = this.checker.decls.files.p[decl]; + val saved := this.checker.at; + this.checker.use_table(this.checker.units[file].table); + for &each in this.checker.libraries { + continue if (each >> 32) as u32 != file; + val written := this.checker.text_of(this.checker.left_of(each as u32)); + var text := string::new(nothing {}); + this.checker.decode_text(written.substr(1, written.length < 2 ? 0 : written.length - 2), &mut text); + libraries.append(move(&mut text)); + } + + this.checker.at = saved; + return libraries; +} + +#! The function type as the code of a function takes its parameters: a variadic +#! one's last as a view of what it is given. +#! @param this The compiler. +#! @param kind The function type. +#! @returns The type. +pub def lowerer::call_type(&mut this, kind: u32): u32 { + val plain := this.checker.unalias(kind); + val count := this.checker.types.part_count(plain); + return plain if this.checker.types.kind_of(plain) != ty::function || this.checker.types.second_of(plain) == 0 || count == 0; + + var params := this.checker.types.parts_of(plain); + val last: u32 = params.last(); + if this.checker.types.kind_of(last) != ty::pack { + params.last() = this.checker.span_of(last); + } + return this.checker.types.function(params.view(), this.checker.types.first_of(plain), false); +} diff --git a/compiler/emitter.sakura b/compiler/emitter.sakura new file mode 100644 index 00000000..d3602d64 --- /dev/null +++ b/compiler/emitter.sakura @@ -0,0 +1,699 @@ +#! @file emitter.sakura +#! @author John Christman (sorakatadzuma@gmail.com) +#! @copyright Malunal Studios, LLC. +#! @license MIT +#! +#! Contains the emitter, which lowers one function's body to intermediate code: +#! where each local is held, the scopes that close them, the values a +#! statement makes that close and no place owns yet, and the cells of the +#! frame what is held in memory lives in. What it does with each part of the +#! language is split across the files of the `emitter` directory. + +import sakura::analyzer; +import std::containers; +module sakura::compiler; + + +#! A value as lowering holds it: the words it is, or the address of the memory +#! holding it, which a struct, union, or fixed array is held in. +pub struct operand { + var kind: u32; #! Its type. + var count: u32; #! How many words it is, where it is held as words. + var words: u32[2]; #! Its words. + var address: u32; #! The address of its memory, where it is held there, or 0. +} + +#! Where a value is: in variables of the builder, or in memory. +pub struct location { + var kind: u32; #! The type of what is there. + var held: bool; #! Whether it is in variables rather than memory. + var vars: u32[2]; #! The variable of each word, where it is in variables. + var address: u32; #! The address its memory is reached from. + var offset: u64; #! How many bytes past the address it is. + var framed: bool; #! Whether the memory is in the frame, which a reference to it refers to while the frame lasts. +} + +#! How a local is held. +pub enum held_as : u8 { + words, #! As the values of variables, where it is a word or a few. + cell, #! In a cell of the frame, where it is in memory or referred to. +} + +#! A local the emitter knows: a variable, a parameter, or a name a test or a +#! loop gives. +pub struct local_info { + var node: u32; #! The node declaring it. + var place: location; #! Where it is. + var closes: bool; #! Whether it is closed where its scope ends. + var pack: u32; #! Of a pack, the first of its values in `packs`, and `count` how many. + var count: u32; #! Of a pack, how many values it holds. + var record: u32; #! One more than its variable among the code's, or 0. + var checks: bool; #! Whether it is an `ensures`, which is checked where its scope ends rather than closed. +} + +#! A value a statement made that closes and no place owns, which the statement +#! closes where it ends, where the flag says it was made. +pub struct kept_value { + var address: u32; #! The address of its memory. + var cell: u32; #! One more than the cell holding it, whose address is taken again where it closes, or 0. + var kind: u32; #! Its type. + var flag: u32; #! The variable saying whether it was made, 1, or not, 0. +} + +#! A loop being lowered, which `break` and `continue` leave. +pub struct loop_info { + var exit: u32; #! The block `break` goes to. + var next: u32; #! The block `continue` goes to. + var locals: u64; #! How many locals there were before its body, which a jump out of it closes past. + var kept: u64; #! How many kept values there were before its body, which a jump out of it closes past. +} + +#! The call whose defaults are being made, which a default asks where it is, +#! or the text of what it was given. +pub struct default_site { + var node: u32; #! The call, or 0 where no default is being made. + var file: u32; #! The file the call is in. + var table: u32; #! The result table its nodes' results are in. + var args: u32; #! The run of the arguments it writes. + var params: u32; #! The run of the parameters of the function it calls. + var skip: u32; #! How many parameters come before the first argument, as `this`. +} + +#! The emitter. +pub struct emitter { + var c: &mut lowerer; #! The compiler. + var build: builder; #! What builds the code. + var function: u32; #! The function being lowered. + var table: u32; #! The result table its nodes' results are in. + var result: u32; #! The type its `return` gives. + var locals: vector;#! The locals in scope, the innermost last. + var local_ids: scoped_dict; #! One more than the local each node declares, by its file and node, a change for each local in scope. + var packs: vector; #! The values packs hold. + var kept: vector;#! The values made that close, which no place owns yet. + var loops: vector; #! The loops around what is lowered, the innermost last. + var storage: dict;#! How each local is held, by the node declaring it, where it is not in variables. + var free: vector; #! The temporary cells free to be taken again. + var lanes_cells: vector; #! Whether each cell is a temporary holding a vector, which only another vector takes again, so the cell is promoted to a vector, not words. + var taken: vector; #! The temporary cells taken by the statements being lowered. + var held: vector; #! The temporary cells holding kept values, freed once the values are closed or taken. + var named: dict; #! Of each variable of the builder holding a word of a named local, the local's variable among the code's, then which word, as `variable << 8 | word`. + var defaulting: default_site; #! The call whose defaults are being made. + var returned: operand; #! What a `return` gives, while the `ensures` it leaves are checked. + var returning: bool; #! Whether a `return` giving a value is closing what it leaves. +} + +#! Makes an emitter of a function. +#! @param c The compiler. +#! @param function The function. +#! @returns The emitter, whose builder takes the function's parameters. +pub def emitter::new(c: &mut lowerer, function: u32): emitter { + val signature: u32 = c.program.functions[function].signature; + var params := c.param_types(signature); + val result := c.layout_at(c.program.signatures[signature].result); + # A closure is given its environment, a reference to what it captures. + if c.program.functions[function].closure { + params.append(vt::word); + } + + var made := emitter { + c = c, + build = builder::new(params.view()), + function = function, + locals = vector::::new(scratch()), + local_ids = scoped_dict::::new(scratch()), + packs = vector::::new(scratch()), + kept = vector::::new(scratch()), + loops = vector::::new(scratch()), + storage = dict::::new(scratch()), + free = vector::::new(scratch()), + lanes_cells = vector::::new(scratch()), + taken = vector::::new(scratch()), + held = vector::::new(scratch()), + named = dict::::new(scratch()) + }; + if !in_memory(&result) { + for _ in 0..word_count(&result) { + made.build.code.results.append(word_type(&result)); + } + } else { + made.build.code.returned = result.size as u32; + } + return made; +} + +#! Finishes the code lowered and gives it to the function, verifying it where +#! the options ask. +#! @param this The emitter. +pub def emitter::finish(&mut this): void { + var body := this.build.finish(); + body.vectors = !this.c.options.evaluating && this.c.checker.names.text(this.c.checker.target.backend) == "native"; + if this.c.options.verify { + val verdict := body.verify(); + for &each in verdict.problems { + this.c.problems.append($"{this.c.program.functions[this.function].name}: {each}"); + } + } + this.c.program.functions[this.function].body = move(&mut body); +} + +#! Makes the function's result table the one the checker reads results from. +#! @param this The emitter. +pub def emitter::use_own_table(&mut this): void { + this.c.checker.use_table(this.table); +} + +#! Notes what lowering could not lower, at a node. +#! @param this The emitter. +#! @param node The node. +#! @param what What it is, said in words. +pub def emitter::problem(&mut this, node: u32, what: strview): void { + if node == 0 { + this.c.problems.append($"{this.c.program.functions[this.function].name}: {what}"); + return; + } + this.c.problem(this.c.checker.at.file, node, what); +} + +#! Says where in the source the instructions added next are from. +#! @param this The emitter. +#! @param node The node they are lowered from. +pub def emitter::at_node(&mut this, node: u32): void { + return if node == 0; + this.build.pos = this.place_at(node); +} + +#! Where in the source a node is, as instructions and variables say: one more +#! than its file above its byte. +#! @param this The emitter. +#! @param node The node. +#! @returns Where. +def emitter::place_at(&this, node: u32): u64 { + val file := this.c.checker.at.file; + return pair_key(file + 1, this.c.node_offset(file, node)); +} + +# Operands. + +#! A value of no words, as `void` is. +#! @param kind The type. +#! @returns The operand. +pub def operand::none(kind: u32): operand { + return operand { kind = kind }; +} + +#! A value of one word. +#! @param kind The type. +#! @param word The word. +#! @returns The operand. +pub def operand::one(kind: u32, word: u32): operand { + var made := operand { kind = kind, count = 1 }; + made.words[0] = word; + return made; +} + +#! A value of two words, as a reference to a trait or a function is. +#! @param kind The type. +#! @param a The first word. +#! @param b The second. +#! @returns The operand. +pub def operand::two(kind: u32, a: u32, b: u32): operand { + var made := operand { kind = kind, count = 2 }; + made.words[0] = a; + made.words[1] = b; + return made; +} + +#! A value held in memory. +#! @param kind The type. +#! @param address The address of its memory. +#! @returns The operand. +pub def operand::at(kind: u32, address: u32): operand { + return operand { kind = kind, address = address }; +} + +#! The values of the code an operand gives where it is passed: its words, or +#! the address of its memory. +#! @param this The operand. +#! @param into Where they are appended. +pub def operand::args(&this, into: &mut vector): void { + if this.address != 0 { + into.append(this.address); + return; + } + for i in 0..this.count { + into.append(this.words[i]); + } +} + +# Cells. + +#! A temporary cell of a size, which the statement taking it holds until it +#! ends: one taken before and freed since where one fits. +#! @param this The emitter. +#! @param size How many bytes it holds. +#! @param align What its address is a multiple of. +#! @returns The cell. +pub def emitter::temporary(&mut this, size: u64, align: u64): u32 { + return this.temporary_for(size, align, false); +} + +#! A temporary cell, as `temporary` gives, holding a vector or not: a cell is +#! taken again only for what it held before, a vector or not. +#! @param this The emitter. +#! @param size How many bytes it holds. +#! @param align What its address is a multiple of. +#! @param lanes Whether it holds a vector. +#! @returns The cell. +def emitter::temporary_for(&mut this, size: u64, align: u64, lanes: bool): u32 { + val wanted := round_up(size == 0 ? word_size : size, word_size) as u32; + val aligned := (align < word_size ? word_size : align) as u32; + for i in 0..this.free.length { + val cell: u32 = this.free[i]; + val held: cell = this.build.code.cells[cell]; + val vector := (cell as u64) < this.lanes_cells.length && this.lanes_cells[cell]; + if held.size == wanted && held.align >= aligned && vector == lanes { + this.free.remove_at(i); + this.taken.append(cell); + return cell; + } + } + val made := this.build.code.add_cell(wanted, aligned, ck::temporary, 0); + if lanes { + this.lanes_cells.resize(made as u64 + 1); + this.lanes_cells[made] = true; + } + this.taken.append(made); + return made; +} + +#! A temporary cell holding a value of a type, and its address. +#! @param this The emitter. +#! @param kind The type. +#! @returns The address of the cell. +pub def emitter::temporary_of(&mut this, kind: u32): u32 { + val held := this.c.shape_of(kind); + return this.build.cell_address(this.temporary_for(held.size, held.align, this.c.checker.is_lanes_type(kind))); +} + +#! How many temporary cells the statements being lowered have taken, which +#! `release` frees those taken since. +#! @param this The emitter. +#! @returns The mark. +pub def emitter::cell_mark(&this): u64 { + return this.taken.length; +} + +#! Frees the temporary cells taken since a mark, to be taken again. +#! @param this The emitter. +#! @param mark How many were taken before. +pub def emitter::release(&mut this, mark: u64): void { + while this.taken.length > mark { + val cell: u32 = this.taken.last(); + this.taken.truncate(); + # A cell holding a value the statement still closes is held until it does. + var kept := false; + for &each in this.kept { + kept = kept || each.cell == cell + 1; + } + if kept { + this.held.append(cell); + } else { + this.free.append(cell); + } + } +} + +#! Frees the cell a kept value was held in, once it is closed or a place took +#! it, where the statement's cells were released before. +#! @param this The emitter. +#! @param cell One more than the cell, or 0. +def emitter::unhold(&mut this, cell: u32): void { + return if cell == 0; + for i in 0..this.held.length { + if this.held[i] == cell - 1 { + this.held.remove_at(i); + this.free.append(cell - 1); + return; + } + } +} + +# Locals. + +#! The local a node of the file being read declares, or none. A local is +#! known by its file as well as its node, since the defaults of a call name the +#! parameters of a function of another file, whose nodes are counted apart, as +#! the arguments written for them name the caller's locals. +#! @param this The emitter. +#! @param node The node. +#! @returns One more than the local's index, or 0. +pub def emitter::local_of(&this, node: u32): u32 { + return this.local_ids.get_or(&pair_key(this.c.checker.at.file, node), 0); +} + +#! Declares a local where it is. +#! @param this The emitter. +#! @param node The node declaring it. +#! @param place Where it is. +#! @param closes Whether it is closed where its scope ends. +#! @returns The local's index. +pub def emitter::declare(&mut this, node: u32, place: location, closes: bool): u32 { + val index := this.locals.length as u32; + this.locals.append(local_info { + node = node, + place = place, + closes = closes, + record = this.describe(node, &place) + }); + this.local_ids.set(pair_key(this.c.checker.at.file, node), index + 1); + return index; +} + +#! Notes a local as a variable debugging information shows, where it is named +#! and held in memory: in a cell, or the copy of a parameter given as memory. +#! Where locals are kept for debugging information, one in an object of the +#! heap is too, whose address a cell is given to hold. +#! @param this The emitter. +#! @param node The node declaring it. +#! @param place Where it is. +#! @returns One more than the variable among the code's, or 0. +def emitter::describe(&mut this, node: u32, place: &location): u32 { + return 0 if node == 0 || place.held || place.address == 0 || place.offset != 0; + val name := this.c.checker.param_name(node); + return 0 if name == 0; + val at := this.place_at(node); + val param := this.c.checker.kind_of(node) == nk::param; + val held: origin = this.build.code.origins[place.address]; + var cell: u32 = 0; + var given: u32 = 0; + if held.param { + return 0 if held.from != 0 || !place.framed; + given = held.index + 1; + } else if this.build.code.insts[held.from].kind == op::cell { + cell = this.build.code.insts[held.from].aux + 1; + } else { + return 0; + } + # Optimized code notes them only for debugging information. + return 0 if !this.c.options.keep_locals && !this.c.options.describe; + this.build.code.variables.append(variable_info { + name = name, at = at, kind = place.kind, cell = cell, given = given, param = param, + first = this.build.code.insts.length as u32 + }); + return this.build.code.variables.length as u32; +} + +#! Notes a local held in values as a variable debugging information shows, +#! where it is named: one in variables of the builder, which each value they +#! are given binds. +#! @param this The emitter. +#! @param node The node declaring it. +#! @param place Where it is. +#! @param words How many words it is. +def emitter::describe_held(&mut this, node: u32, place: &location, words: u64): void { + return if !this.c.options.describe; + val name := this.c.checker.param_name(node); + return if name == 0; + val at := this.place_at(node); + val param := this.c.checker.kind_of(node) == nk::param; + val index := this.build.code.variables.length as u32; + this.build.code.variables.append(variable_info { + name = name, at = at, kind = place.kind, param = param, held = true + }); + for i in 0..words { + this.named.set(place.vars[i], (index as u64 << 8) | i); + } +} + +#! Binds a named local to a value given a variable of the builder holding one +#! of its words, where it is one. +#! @param this The emitter. +#! @param held The variable of the builder. +#! @param value The value. +pub def emitter::bind(&mut this, held: u32, value: u32): void { + if this.named.get(&held) is some(found) { + this.bind_word((found >> 8) as u32, (found & 0xFF) as u32, value); + } +} + +#! Binds a word of a variable held in values to a value, where the code being +#! built is. +#! @param this The emitter. +#! @param variable The variable, among the code's. +#! @param word Which of its words. +#! @param value The value. +def emitter::bind_word(&mut this, variable: u32, word: u32, value: u32): void { + val block := this.build.at; + this.build.code.bindings.append(binding { + variable = variable, word = word, value = value, after = this.build.code.blocks[block].last, block = block + }); +} + +#! Makes a place for a local of a type declared by a node, held as the storage +#! worked out for it says: in variables, or a cell. +#! @param this The emitter. +#! @param node The node declaring it. +#! @param kind Its type. +#! @param cells The kind of cell it takes where it takes one: `undefined` for +#! one the frame leaves as it is. +#! @returns Where it is. +pub def emitter::new_place(&mut this, node: u32, kind: u32, cells: ck = ck::local): location { + val held := this.c.shape_of(kind); + var how := this.storage.get_or(&node, held_as::words); + if in_memory(&held) && how == held_as::words { + how = held_as::cell; + } + if this.c.options.keep_locals && how == held_as::words && word_count(&held) != 0 { + how = held_as::cell; + } + + match how { + held_as::cell => { + val name := this.c.checker.name_of(node); + val made := this.build.code.add_cell(round_up(held.size == 0 ? word_size : held.size, word_size) as u32, + held.align < word_size ? word_size as u32 : held.align as u32, cells, name); + return location { kind = kind, address = this.build.cell_address(made), framed = true }; + } + else => { + var place := location { kind = kind, held = true }; + for i in 0..word_count(&held) { + place.vars[i] = this.build.variable(word_type(&held)); + } + if !this.c.options.keep_locals { + this.describe_held(node, &place, word_count(&held)); + } + return place; + } + } + return location { kind = kind }; +} + +#! How many locals are in scope, which `end_scope` closes those declared since. +#! @param this The emitter. +#! @returns The mark. +pub def emitter::scope_mark(&this): u64 { + return this.locals.length; +} + +#! Closes the locals declared since a mark, in the reverse of the order they +#! were declared, but the one given back by name, and ends their scope. +#! @param this The emitter. +#! @param mark How many were in scope before. +#! @param given The node of a local given back by name, which is not closed, or +#! 0. +pub def emitter::end_scope(&mut this, mark: u64, given: u32): void { + this.close_locals(mark, given); + this.forget_locals(mark); +} + +#! Ends the scope of the locals declared since a mark, without closing them. +#! @param this The emitter. +#! @param mark How many were in scope before. +pub def emitter::forget_locals(&mut this, mark: u64): void { + # Each local set the node declaring it once, so taking back the changes + # since the mark gives each node the local it named before. + while this.locals.length > mark { + val record: u32 = this.locals.last().record; + if record != 0 { + this.build.code.variables[record as u64 - 1].end = this.build.code.insts.length as u32; + } + this.locals.truncate(); + } + this.local_ids.rewind(mark); +} + +#! Closes the locals declared since a mark that close, in the reverse of the +#! order they were declared, so each is closed while everything it was built +#! from still stands, but the one given back by name. +#! @param this The emitter. +#! @param mark How many were in scope before. +#! @param given The node of a local given back by name, or 0. +pub def emitter::close_locals(&mut this, mark: u64, given: u32): void { + var at := this.locals.length; + while at > mark { + at--; + val held: local_info = this.locals[at]; + continue if !held.closes || held.node == given; + if held.checks { + this.check_ensures(held.node); + continue; + } + # A pack closes each of its values, the last first. + if held.count != 0 { + var k := held.count; + while k > 0 { + k--; + val each: location = this.packs[held.pack as u64 + k as u64]; + this.close(&each); + } + continue; + } + this.close(&held.place); + } +} + +# Kept values. + +#! Keeps a value a statement made that closes, which no place owns yet, so the +#! statement closes it where it ends unless a place takes it first. +#! @param this The emitter. +#! @param value The value, held in memory. +pub def emitter::keep(&mut this, value: &operand): void { + return if value.address == 0 || !this.c.checker.closes(value.kind); + for &each in this.kept { + return if each.address == value.address; + } + val flag := this.build.variable(vt::word); + this.build.assign(flag, this.build.word(1)); + + # It may be made down one branch of the statement, and closed where they join, + # so the address of the cell holding it is taken again there. + var cell: u32 = 0; + val held: origin = this.build.code.origins[value.address]; + if !held.param && this.build.code.insts[held.from].kind == op::cell { + cell = this.build.code.insts[held.from].aux + 1; + } + this.kept.append(kept_value { address = value.address, cell = cell, kind = value.kind, flag = flag }); +} + +#! Says a place took a kept value, so the statement no longer closes it. +#! @param this The emitter. +#! @param value The value. +pub def emitter::adopt(&mut this, value: &operand): void { + return if value.address == 0; + var at := this.kept.length; + while at > 0 { + at--; + if this.kept[at].address == value.address { + val cell: u32 = this.kept[at].cell; + this.kept.remove_at(at); + this.unhold(cell); + return; + } + } +} + +#! Closes the values kept since a mark, in the reverse of the order they were +#! made, each where it was made on the way here, and forgets them. +#! @param this The emitter. +#! @param mark How many were kept before. +pub def emitter::close_kept(&mut this, mark: u64): void { + this.leave_kept(mark); + while this.kept.length > mark { + val cell: u32 = this.kept.last().cell; + this.kept.truncate(); + this.unhold(cell); + } +} + +#! Forgets the values kept since a mark without closing them, where the program +#! stops before they would be. +#! @param this The emitter. +#! @param mark How many were kept before. +pub def emitter::drop_kept(&mut this, mark: u64): void { + while this.kept.length > mark { + val cell: u32 = this.kept.last().cell; + this.kept.truncate(); + this.unhold(cell); + } +} + +#! Closes the values kept since a mark, each where it was made on the way here, +#! without forgetting them, as a jump out of the statements keeping them does. +#! @param this The emitter. +#! @param mark How many were kept before. +pub def emitter::leave_kept(&mut this, mark: u64): void { + var at := this.kept.length; + while at > mark { + at--; + val held: kept_value = this.kept[at]; + val made := this.build.read(held.flag); + # Each close forgets it was made, so a jump in a later pass of a loop, taken + # before it is made again, does not close it twice. + if this.is_one(made) { + val place := location { kind = held.kind, address = held.address, framed = true }; + this.close(&place); + this.build.assign(held.flag, this.build.word(0)); + continue; + } + val closing := this.build.new_block(); + val after := this.build.new_block(); + this.build.branch(made, closing, after); + this.build.seal(closing); + this.build.switch_to(closing); + val address := held.cell != 0 ? this.build.cell_address(held.cell - 1) : held.address; + val place := location { kind = held.kind, address = address, framed = true }; + this.close(&place); + this.build.assign(held.flag, this.build.word(0)); + this.build.jump(after); + this.build.seal(after); + this.build.switch_to(after); + } +} + +#! Whether a value is the word 1, made where it is known to be. +#! @param this The emitter. +#! @param value The value. +#! @returns Whether it is. +pub def emitter::is_one(&this, value: u32): bool { + val held: origin = this.build.code.origins[value]; + return false if held.param; + val made: inst = this.build.code.insts[held.from]; + return made.kind == op::iconst && made.imm == 1; +} + +# Statements. + +#! What a statement holds while it is lowered, which it lets go of once it ends. +pub struct statement_mark { + var cells: u64; #! The temporary cells taken before it. + var kept: u64; #! The values kept before it. +} + +#! Begins a statement. +#! @param this The emitter. +#! @returns What it holds, as `end_statement` takes it. +pub def emitter::begin_statement(&this): statement_mark { + return statement_mark { cells = this.taken.length, kept = this.kept.length }; +} + +#! Ends a statement: closes what it kept, and frees the cells it took. +#! @param this The emitter. +#! @param mark What it held, as `begin_statement` gave it. +pub def emitter::end_statement(&mut this, mark: statement_mark): void { + this.close_kept(mark.kept); + this.release(mark.cells); +} + +#! A safe point, where the handlers of the signals that have come run. Only a +#! program handling a signal has them, and only in its own functions, at the +#! start of each and of each pass of each loop, so a handler never finds a +#! container of std in the middle of a change. +#! @param this The emitter. +pub def emitter::safepoint(&mut this): void { + return if this.c.dispatch == no_function; + val held := &this.c.program.functions[this.function]; + val decl: u32 = held.decl != 0 ? held.decl : held.outer; + return if decl == 0 || held.builtin != 0 || this.c.in_std(decl); + this.build.effect(op::safepoint, span::::empty(), this.c.dispatch, 0); +} diff --git a/compiler/emitter/bodies.sakura b/compiler/emitter/bodies.sakura new file mode 100644 index 00000000..79a1faec --- /dev/null +++ b/compiler/emitter/bodies.sakura @@ -0,0 +1,253 @@ +#! @file bodies.sakura +#! @author John Christman (sorakatadzuma@gmail.com) +#! @copyright Malunal Studios, LLC. +#! @license MIT +#! +#! Contains the lowering of a function's body: where its parameters are, its +#! statements, and how it returns, closing its parameters as it does. + +import sakura::analyzer; +module sakura::compiler; + + +#! Lowers the function the emitter is of. +#! @param this The emitter. +pub def emitter::lower(&mut this): void { + val decl: u32 = this.c.program.functions[this.function].decl; + val instance: u32 = this.c.program.functions[this.function].instance; + val lambda: u32 = this.c.program.functions[this.function].node; + if this.c.program.functions[this.function].adapted != 0 { + this.lower_adapter(); + return; + } + if lambda != 0 { + this.lower_lambda(lambda); + return; + } + if this.c.program.functions[this.function].builtin != 0 { + this.lower_builtin(); + return; + } + val evaluation: u32 = this.c.program.functions[this.function].evaluation; + if evaluation != 0 { + this.lower_evaluation(evaluation - 1); + return; + } + if decl == 0 { + this.build.unreachable(); + return; + } + + val table := this.c.body_table(decl, instance); + if instance != 0 && this.c.checker.instances[instance - 1].table == 0 { + this.c.checker.use_table(table); + this.problem(this.c.checker.decls.nodes.p[decl], "The instance's body was never checked."); + this.build.unreachable(); + return; + } + this.table = table; + this.use_own_table(); + + val node: u32 = this.c.checker.decls.nodes.p[decl]; + val accessor := this.c.checker.decls.has(decl, df::accessor); + val body := accessor ? this.c.checker.record(node, accessor_slot::body) : this.c.checker.record(node, function_slot::body); + val params := accessor ? this.c.checker.left_of(node) : this.c.checker.record(node, function_slot::params); + val kind := this.c.type_of_function(decl, instance); + this.at_node(node); + this.result = this.c.checker.types.first_of(kind); + + this.plan_function(decl, params, kind, body); + this.take_params(decl, params, kind); + this.safepoint(); + this.lower_body(body); +} + +#! Lowers a body: a block, which ends returning nothing where control falls off +#! its end, or an expression, whose value is returned. +#! @param this The emitter. +#! @param body The body's node. +pub def emitter::lower_body(&mut this, body: u32): void { + if this.c.checker.kind_of(body) != nk::block { + val mark := this.begin_statement(); + this.at_node(body); + if this.c.checker.types.kind_of(this.c.layout_type(this.result)) == ty::void_type { + this.value(body); + this.end_statement(mark); + this.close_locals(0, 0); + this.build.ret(span::::empty()); + return; + } + this.return_value(body, mark); + return; + } + + this.lower_block(body); + return if this.build.ended(); + + # Running off the end returns, which a function giving a value never does. + if this.c.checker.types.kind_of(this.c.layout_type(this.result)) == ty::void_type { + this.close_locals(0, 0); + this.build.ret(span::::empty()); + return; + } + this.build.trap(fault::unreachable as u32); +} + +#! Takes the function's parameters where its code is given them: each as a +#! local, held as its storage says, and a pack's as one local holding each. +#! @param this The emitter. +#! @param decl The function's declaration. +#! @param params The run of its parameters' nodes. +#! @param kind Its function type, given its type arguments. +def emitter::take_params(&mut this, decl: u32, params: u32, kind: u32): void { + val signature: u32 = this.c.program.functions[this.function].signature; + val count := this.c.checker.run_length(params); + var next: u32 = 0; + + # A pack parameter takes every parameter from its own on, one value of each. + val written: u32 = this.c.checker.decls.types.p[decl]; + val wcount := this.c.checker.types.part_count(written); + val packed := this.c.checker.decls.has(decl, df::variadic) && wcount != 0 + && this.c.checker.types.is_open_pack(this.c.checker.types.part_at(written, wcount - 1)); + val total := this.c.program.signatures[signature].params.length as u32; + + for i in 0..count { + val node := this.c.checker.run_at(params, i as u32); + if packed && i as u32 + 1 == count { + val first := this.packs.length as u32; + for p in i as u32..total { + val held := this.take_param(signature, p, &mut next); + val place := this.param_place(0, held); + this.packs.append(place); + } + val index := this.declare(node, location { kind = this.c.checker.type_at(node) }, true); + this.locals[index].pack = first; + this.locals[index].count = this.packs.length as u32 - first; + continue; + } + break if i as u32 >= total; + + val held := this.take_param(signature, i as u32, &mut next); + val place := this.param_place(node, held); + this.declare(node, place, this.c.checker.closes(held.kind)); + } +} + +#! A parameter as the code is given it: its words, or the address of the +#! function's own copy of it. +#! @param this The emitter. +#! @param signature The function's signature. +#! @param index The parameter's position. +#! @param next The first of the code's parameters not yet taken, moved +#! past those of this one. +#! @returns The parameter's value. +def emitter::take_param(&mut this, signature: u32, index: u32, next: &mut u32): operand { + val layout_index: u32 = this.c.program.signatures[signature].params[index]; + val shape := this.c.layout_at(layout_index); + val kind := shape.type_id; + if in_memory(&shape) { + val address := this.build.param(next); + next++; + return operand::at(kind, address); + } + + var made := operand { kind = kind, count = word_count(&shape) }; + for i in 0..made.count { + made.words[i] = this.build.param(next); + next++; + } + return made; +} + +#! Where a parameter is held: in memory it was given, or its own copy, as its +#! storage says where it is referred to. +#! @param this The emitter. +#! @param node The parameter's node, or 0 for a value of a pack. +#! @param held Its value. +#! @returns Where it is. +def emitter::param_place(&mut this, node: u32, held: operand): location { + if held.address != 0 { + return location { kind = held.kind, address = held.address, framed = true }; + } + + val place := node != 0 ? this.new_place(node, held.kind) : this.fresh_place(held.kind); + this.store(&place, &held); + return place; +} + +#! A place for a value of a type that no node declares, as each value of a +#! pack: in variables, or a cell where it is in memory. +#! @param this The emitter. +#! @param kind The type. +#! @returns Where it is. +pub def emitter::fresh_place(&mut this, kind: u32): location { + val held := this.c.shape_of(kind); + if in_memory(&held) { + val made := this.build.code.add_cell(round_up(held.size == 0 ? word_size : held.size, word_size) as u32, + held.align < word_size ? word_size as u32 : held.align as u32, ck::local, 0); + return location { kind = kind, address = this.build.cell_address(made), framed = true }; + } + var place := location { kind = kind, held = true }; + for i in 0..word_count(&held) { + place.vars[i] = this.build.variable(word_type(&held)); + } + return place; +} + +#! Lowers `return value;`: the value is made, or the local it names handed +#! over, everything the statements and scopes around it hold is closed, and the +#! function returns. +#! @param this The emitter. +#! @param node The value's node. +#! @param mark What the statement held before the value. +pub def emitter::return_value(&mut this, node: u32, mark: statement_mark): void { + var made := this.value_as(node, this.result); + + # Returning a local by name hands it over, so it is not closed. + var given: u32 = 0; + if this.c.checker.kind_of(node) == nk::name { + val ref := this.c.checker.ref_at(node); + if (ref & ref_local) != 0 { + given = ref & ref_mask; + } + } + this.return_made(&mut made, given, mark); +} + +#! Ends the function returning a value made, closing what the statement made and +#! what the function's locals hold, all but the local handed over. +#! @param this The emitter. +#! @param made The value returned. +#! @param given The local the value is, handed over rather than closed, or 0. +#! @param mark Where the statement began. +pub def emitter::return_made(&mut this, made: &mut operand, given: u32, mark: statement_mark): void { + this.adopt(made); + + # What the statement made closes, and what the statements around it made too, + # which they still close down the paths that do not return. The cells it took + # are freed only once the closing is lowered, which might take them otherwise. + var args := vector::::new(); + made.args(&mut args); + this.close_kept(mark.kept); + this.leave_kept(0); + # An `ensures` naming what is returned reads it as the locals close. + this.returned = made; + this.returning = true; + this.close_locals(0, given); + this.returning = false; + this.release(mark.cells); + this.give_back(args.view()); +} + +#! Ends the block returning what the function gives: its words, or the address +#! of what it gives in memory, and nothing where that has no bytes, as a struct +#! of no fields. +#! @param this The emitter. +#! @param args The words, or the address. +pub def emitter::give_back(&mut this, args: span): void { + if this.build.code.results.length == 0 && this.build.code.returned == 0 { + this.build.ret(span::::empty()); + return; + } + this.build.ret(args); +} diff --git a/compiler/emitter/builtins.sakura b/compiler/emitter/builtins.sakura new file mode 100644 index 00000000..dcf6a097 --- /dev/null +++ b/compiler/emitter/builtins.sakura @@ -0,0 +1,310 @@ +#! @file builtins.sakura +#! @author John Christman (sorakatadzuma@gmail.com) +#! @copyright Malunal Studios, LLC. +#! @license MIT +#! +#! Contains the methods the compiler gives the built-in types, which make +#! numbers, `bool`, enums, and pointers `equatable`, `hashable`, `ordered`, and +#! `numeric` as far as each allows: written where they are called, and made +#! functions of their own where a vtable names them. + +import sakura::analyzer; +module sakura::compiler; + + +#! A call of a method the compiler gives a built-in type, on the value it is +#! called on and the other operand. +#! @param this The emitter. +#! @param node The `call` node. +#! @returns What it gives. +pub def emitter::builtin_call(&mut this, node: u32): operand { + val callee := this.c.checker.left_of(node); + val object := this.c.checker.left_of(callee); + val name := this.c.checker.name_of(callee); + + # `f.invoke(args)` calls the function, or the C function, the value is. + if name == word::invoke { + val made := this.value_of_type(object); + val function := this.through_references(&made); + var given := gathered { values = vector::::new() }; + this.gather(node, 0, 0, this.called_type(function.kind), 0, &mut given); + return this.call_function_value(&function, &given); + } + + # A fixed array is compared and hashed element by element, where it is. + val reached := this.c.checker.unalias(this.c.checker.reached(this.c.checker.type_at(object))); + if this.c.checker.types.kind_of(reached) == ty::fixed { + val whole := this.object(object); + val first := this.address_of(&whole); + val result := this.c.checker.type_at(node); + if name == word::hash { + return operand::one(result, this.hash_elements(first, reached)); + } + val run := this.c.checker.right_of(node); + val other := this.object(this.c.checker.run_at(run, 0)); + return operand::one(result, this.equal_elements(first, this.address_of(&other), reached)); + } + + val made := this.value_of_type(object); + val subject := this.through_references(&made); + var other := operand {}; + val run := this.c.checker.right_of(node); + if this.c.checker.run_length(run) != 0 { + val given := this.value_of_type(this.c.checker.run_at(run, 0)); + other = this.through_references(&given); + other = this.convert(&other, subject.kind); + } + return this.builtin_method(name, &subject, &other, this.c.checker.type_at(node)); +} + +#! What a method the compiler gives a built-in type gives: `equals` compares, +#! `hash` gives the bits, as 0 for both zeros of a float, `compare` gives -1, 0, +#! or 1, and the methods of `numeric` operate. +#! @param this The emitter. +#! @param name The ID of the method's name. +#! @param a The value it is called on. +#! @param b The other operand, where it takes one. +#! @param result The type it gives. +#! @returns What it gives. +pub def emitter::builtin_method(&mut this, name: u32, a: &operand, b: &operand, result: u32): operand { + val kind := a.kind; + val floating := this.is_float(kind); + val signed := this.is_signed(kind); + if name == word::equals { + return operand::one(result, this.build.binary(floating ? op::feq : op::eq, a.words[0], b.words[0])); + } + if name == word::compare { + val less := floating ? op::flt : (signed ? op::lts : op::ltu); + val below := this.build.binary(less, a.words[0], b.words[0]); + val above := this.build.binary(less, b.words[0], a.words[0]); + return operand::one(result, this.build.binary(op::sub, above, below)); + } + if name == word::hash { + if !floating { + return operand::one(result, a.words[0]); + } + # Both zeros hash as 0, and anything else as its bits, an `f32`'s as one. + val shape := this.c.shape_of(kind); + val cell := this.temporary(word_size, word_size); + val address := this.build.cell_address(cell); + this.build.store(shape.bits <= 32 ? access::f32 : access::f64, address, 0, a.words[0]); + val bits := this.build.load(shape.bits <= 32 ? access::u32 : access::i64, address, 0); + val zero := this.build.binary(op::feq, a.words[0], this.build.real(0)); + val nonzero := this.build.binary(op::eq, zero, this.build.word(0)); + val mask := this.build.unary(op::neg, nonzero); + return operand::one(result, this.build.binary(op::band, bits, mask)); + } + if name == word::negate { + val made := this.build.unary(floating ? op::fneg : op::neg, a.words[0]); + return operand::one(result, this.normalize(made, kind)); + } + if name == word::bit_not { + return operand::one(result, this.normalize(this.build.unary(op::bnot, a.words[0]), kind)); + } + + var chosen := op::add; + if name == word::add { + chosen = floating ? op::fadd : op::add; + } else if name == word::sub { + chosen = floating ? op::fsub : op::sub; + } else if name == word::mul { + chosen = floating ? op::fmul : op::mul; + } else if name == word::div { + chosen = floating ? op::fdiv : (signed ? op::divs : op::divu); + } else if name == word::rem { + chosen = floating ? op::frem : (signed ? op::rems : op::remu); + } else if name == word::bit_and { + chosen = op::band; + } else if name == word::bit_or { + chosen = op::bor; + } else if name == word::bit_xor { + chosen = op::bxor; + } else if name == word::shift_left { + chosen = op::shl; + } else if name == word::shift_right { + chosen = signed ? op::shrs : op::shru; + } + return operand::one(result, this.normalize(this.build.binary(chosen, a.words[0], b.words[0]), kind)); +} + +#! The function giving a built-in type a method, as a vtable names it, made +#! where it is new: it takes `this` and the other operand by reference, as the +#! method's type says. +#! @param this The compiler. +#! @param kind The built-in type. +#! @param name The ID of the method's name. +#! @returns The function's index, or `no_function` where the type has no such +#! method. +pub def lowerer::builtin_function(&mut this, kind: u32, name: u32): u32 { + val type_of := this.checker.builtin_method(kind, name); + return no_function if type_of == 0; + val key := pair_key(kind, name); + if this.builtin_ids.get(&key) is some(got) { + return got; + } + var text := string::from(this.checker.names.text(name), nothing {}); + val index := this.add_function(move(&mut text), this.signature_of(this.call_type(type_of))); + this.builtin_ids.set(key, index); + this.program.functions[index].builtin = name; + this.program.functions[index].owner_type = kind; + this.want(index); + return index; +} + +#! Lowers a function giving a built-in type a method. +#! @param this The emitter. +pub def emitter::lower_builtin(&mut this): void { + val name: u32 = this.c.program.functions[this.function].builtin; + val kind: u32 = this.c.program.functions[this.function].owner_type; + + # `invoke` calls the function, or the C function, its `this` refers to, with + # the arguments it is given, as they are. + if name == word::invoke { + val signature: u32 = this.c.program.functions[this.function].signature; + val total := this.c.program.signatures[signature].params.length as u32; + var next: u32 = 0; + val taken := this.take_param(signature, 0, &mut next); + val place := location { kind = kind, address = taken.words[0] }; + val function := this.load(&place); + var given := gathered { values = vector::::new() }; + for p in 1..total { + given.values.append(this.take_param(signature, p as u32, &mut next)); + } + val made := this.call_function_value(&function, &given); + var args := vector::::new(); + made.args(&mut args); + this.give_back(args.view()); + return; + } + if this.c.checker.types.kind_of(this.c.checker.unalias(kind)) == ty::fixed { + val plain := this.c.checker.unalias(kind); + var words: u32[1] = [0]; + if name == word::hash { + words[0] = this.hash_elements(this.build.param(0), plain); + } else { + words[0] = this.equal_elements(this.build.param(0), this.build.param(2), plain); + } + this.build.ret(words[0:1]); + return; + } + val first := location { kind = kind, address = this.build.param(0) }; + val a := this.load(&first); + var b := operand {}; + if this.c.program.signatures[this.c.program.functions[this.function].signature].params.length > 1 { + val second := location { kind = kind, address = this.build.param(2) }; + b = this.load(&second); + } + val result := this.c.checker.types.first_of(this.c.checker.builtin_method(kind, name)); + val made := this.builtin_method(name, &a, &b, result); + var args := vector::::new(); + made.args(&mut args); + this.give_back(args.view()); +} + +#! Whether the elements of two fixed arrays are equal, one by one, as each +#! says it is equal: a number by its value, and a struct by its `equals`. +#! @param this The emitter. +#! @param a The address of one array. +#! @param b The address of the other. +#! @param kind The arrays' type. +#! @returns A word of 1 where they are, and 0 where not. +pub def emitter::equal_elements(&mut this, a: u32, b: u32, kind: u32): u32 { + val element := this.c.checker.types.first_of(kind); + val count := this.c.checker.types.second_of(kind) as u64; + val size := this.c.shape_of(element).size; + val same := this.build.variable(vt::word); + val index := this.build.variable(vt::word); + this.build.assign(same, this.build.word(1)); + this.build.assign(index, this.build.word(0)); + + val head := this.build.new_block(); + val body := this.build.new_block(); + val differs := this.build.new_block(); + val next := this.build.new_block(); + val done := this.build.new_block(); + val at := this.count_up(index, count, head, body, done); + val offset := this.scaled(at, size); + val equal := this.element_equals(this.build.binary(op::add, a, offset), this.build.binary(op::add, b, offset), element); + this.build.branch(equal, next, differs); + this.build.seal(differs); + this.build.switch_to(differs); + this.build.assign(same, this.build.word(0)); + this.build.jump(done); + this.build.seal(next); + this.build.switch_to(next); + this.count_on(index, head, done); + return this.build.read(same); +} + +#! Whether two values of a type, at their addresses, are equal, as the type +#! says it is. +#! @param this The emitter. +#! @param a The address of one. +#! @param b The address of the other. +#! @param kind The type. +#! @returns A word of 1 where they are, and 0 where not. +def emitter::element_equals(&mut this, a: u32, b: u32, kind: u32): u32 { + val plain := this.c.checker.unalias(kind); + if this.c.checker.types.kind_of(plain) == ty::fixed { + return this.equal_elements(a, b, plain); + } + val first := location { kind = kind, address = a }; + val second := location { kind = kind, address = b }; + if this.c.checker.find_member(kind, word::equals).decl == 0 { + val x := this.load(&first); + val y := this.load(&second); + return this.builtin_method(word::equals, &x, &y, bt::boolean).words[0]; + } + val method := this.c.checker.find_member(kind, word::equals).decl; + val reference := this.c.checker.types.reference(kind, false); + val subject := this.reference_to(&first, reference); + var others := vector::::new(); + others.append(this.reference_to(&second, reference)); + return this.method_call(method, kind, &subject, others.view()).words[0]; +} + +#! The hash of a fixed array: of its length, then each element's in turn, +#! mixed as the C compiler mixes them. +#! @param this The emitter. +#! @param a The array's address. +#! @param kind Its type. +#! @returns The hash. +pub def emitter::hash_elements(&mut this, a: u32, kind: u32): u32 { + val element := this.c.checker.types.first_of(kind); + val count := this.c.checker.types.second_of(kind) as u64; + val size := this.c.shape_of(element).size; + val code := this.build.variable(vt::word); + val index := this.build.variable(vt::word); + this.build.assign(code, this.build.word(count)); + this.build.assign(index, this.build.word(0)); + + val head := this.build.new_block(); + val body := this.build.new_block(); + val done := this.build.new_block(); + val at := this.count_up(index, count, head, body, done); + val each := this.element_hash(this.build.binary(op::add, a, this.scaled(at, size)), element); + val mixed := this.build.binary(op::mul, this.build.binary(op::bxor, this.build.read(code), each), this.build.word(0x9E3779B97F4A7C15)); + this.build.assign(code, this.build.binary(op::bxor, mixed, this.build.binary(op::shru, mixed, this.build.word(29)))); + this.count_on(index, head, done); + return this.build.read(code); +} + +#! The hash of a value of a type, at its address, as the type gives it. +#! @param this The emitter. +#! @param a The value's address. +#! @param kind The type. +#! @returns The hash. +def emitter::element_hash(&mut this, a: u32, kind: u32): u32 { + val plain := this.c.checker.unalias(kind); + if this.c.checker.types.kind_of(plain) == ty::fixed { + return this.hash_elements(a, plain); + } + val place := location { kind = kind, address = a }; + val method := this.c.checker.find_member(kind, word::hash).decl; + if method == 0 { + val x := this.load(&place); + return this.builtin_method(word::hash, &x, &operand {}, bt::uint64).words[0]; + } + val subject := this.reference_to(&place, this.c.checker.types.reference(kind, false)); + return this.method_call(method, kind, &subject, span::::empty()).words[0]; +} diff --git a/compiler/emitter/calls.sakura b/compiler/emitter/calls.sakura new file mode 100644 index 00000000..d5ba15c9 --- /dev/null +++ b/compiler/emitter/calls.sakura @@ -0,0 +1,702 @@ +#! @file calls.sakura +#! @author John Christman (sorakatadzuma@gmail.com) +#! @copyright Malunal Studios, LLC. +#! @license MIT +#! +#! Contains the lowering of calls: of functions and the instances of generics, +#! of methods given the value they are called on, of traits' methods through a +#! vtable, of function values, and of C functions, with the arguments a call +#! leaves to defaults, those a variadic parameter gathers, and those a pack +#! spreads. Also contains the calls the compiler makes itself, for reading and +#! writing a property and indexing what implements `indexable`, and the +#! intrinsics, which are code of their own rather than calls. + +import sakura::analyzer; +module sakura::compiler; + + +#! The arguments of a call as lowering gathers them, each the value of a +#! parameter, in order. +pub struct gathered { + var values: vector; #! The value given each parameter. +} + +#! The instance of a generic a node calls, as the checker recorded it. +#! @param this The emitter. +#! @param node The node. +#! @returns One more than the instance, or 0. +pub def emitter::called(&mut this, node: u32): u32 { + return this.c.called(node); +} + +#! Lowers a call. +#! @param this The emitter. +#! @param node The `call` node. +#! @returns What it gives. +pub def emitter::call(&mut this, node: u32): operand { + val callee := this.c.checker.left_of(node); + var decl := this.c.checker.ref_at(node); + # A value of no function type is called through its `invoke`, given the value + # as `this`, which the callee is however it is reached, as `obj.f` of `obj.f(x)`. + if this.c.checker.has_flag(node, rf::invokes) && decl != 0 { + return this.call_decl(node, decl, callee); + } + # `x.(d)()` calls the method a description names, which the callee names. + if decl == 0 && this.c.checker.kind_of(callee) == nk::member_of { + decl = this.c.checker.ref_at(callee); + } + + # An intrinsic of reflection records what it reaches as the call's own, as + # `value_of(d)` does the function `d` describes, so its callee says what it is. + val named := this.c.checker.kind_of(callee) == nk::name || this.c.checker.kind_of(callee) == nk::path + ? this.c.checker.ref_at(callee) : 0; + if named != 0 && (named & (ref_local | ref_type)) == 0 && this.c.checker.decls.kinds.p[named] == dk::function + && this.c.checker.decls.has(named, df::intrinsic) { + return this.intrinsic(node, named); + } + if decl != 0 && (decl & (ref_local | ref_type)) == 0 && this.c.checker.decls.kinds.p[decl] == dk::function { + if this.c.checker.decls.has(decl, df::intrinsic) { + return this.intrinsic(node, decl); + } + var object: u32 = 0; + val callee_kind := this.c.checker.kind_of(callee); + if (callee_kind == nk::member || callee_kind == nk::member_of) && this.c.checker.decls.has(decl, df::method) { + object = this.c.checker.left_of(callee); + } + return this.call_decl(node, decl, object); + } + + # A method the compiler gives a built-in type, as `equals` of a number, but + # not a field holding a function. + if this.c.checker.kind_of(callee) == nk::member && decl == 0 { + val field := this.c.checker.ref_at(callee); + val is_field := field != 0 && (field & (ref_local | ref_type)) == 0 && this.c.checker.decls.kinds.p[field] == dk::field; + if !is_field { + return this.builtin_call(node); + } + } + return this.call_value(node); +} + +#! Lowers a call of a declared function, given the value a method is called on. +#! @param this The emitter. +#! @param node The `call` node. +#! @param decl The function's declaration. +#! @param object The node of the value a method is called on, or 0. +#! @returns What it gives. +def emitter::call_decl(&mut this, node: u32, decl: u32, object: u32): operand { + val instance := this.called(node); + val holder := this.c.trait_of_method(decl); + var kind := this.c.type_of_function(decl, instance); + if holder != 0 && object != 0 && instance == 0 { + kind = this.c.checker.trait_method_type(decl, this.c.checker.reached(this.c.checker.type_at(object))); + } + + var given := gathered { values = vector::::new() }; + if object != 0 { + given.values.append(this.receiver(object, this.c.checker.types.part_at(kind, 0), decl)); + } + this.gather(node, decl, instance, kind, object != 0 ? 1 : 0, &mut given); + return this.call_gathered(decl, instance, holder, kind, object, &given); +} + +#! Calls a declared function with its arguments gathered: through a vtable, as +#! a trait's default, through its address where it is C's, or as it is. +#! @param this The emitter. +#! @param decl The function's declaration. +#! @param instance One more than the instance called, or 0. +#! @param holder The trait it is a member of, or 0. +#! @param kind The function type called. +#! @param object The node of the value a method is called on, or 0. +#! @param given The arguments. +#! @returns What it gives. +pub def emitter::call_gathered( + &mut this, + decl: u32, + instance: u32, + holder: u32, + kind: u32, + object: u32, + given: &gathered +): operand { + # A trait's method is called through the vtable of the value's trait + # reference, but a default it writes a body for, called on a value of a type + # that takes it, is that body: the type's own instance of it, which the + # checker made where the call gives the default's type arguments, or one + # given the value as a reference to the trait. + if holder != 0 { + val receiver_type := object != 0 ? this.c.checker.unalias(this.c.checker.reached(this.c.checker.type_at(object))) : 0; + val dynamic := object != 0 && (this.c.checker.named_kind(receiver_type) == dk::trait_type + || this.c.checker.types.kind_of(receiver_type) == ty::param); + if dynamic || !this.c.checker.has_body(decl) { + return this.call_trait(decl, holder, given, this.c.checker.types.first_of(kind)); + } + if instance != 0 { + return this.call_function(this.c.function_of(decl, instance), given, this.c.checker.types.first_of(kind)); + } + val implemented := this.c.checker.implemented(receiver_type, this.c.checker.enclosing_trait(decl)); + val own := span::::empty(); + return this.call_function(this.c.default_of(decl, implemented, receiver_type, own), given, this.c.checker.types.first_of(kind)); + } + + # A C function without a body is called through its address. + if this.c.checker.decls.has(decl, df::foreign) && !this.c.checker.has_body(decl) { + val address := this.build.value(op::c_address, span::::empty(), vt::word, this.c.linked_of(decl), 0); + return this.call_address(address, this.c.call_type(kind), given, this.c.checker.types.first_of(kind)); + } + return this.call_function(this.c.function_of(decl, instance), given, this.c.checker.types.first_of(kind)); +} + +#! The reference a method's `this` takes to the value it is called on: the +#! reference the value already is, read through to the one `this` takes, or one +#! to the place it is, or to a copy of it where it is no place. A trait's +#! default method takes it as a reference to the trait. +#! @param this The emitter. +#! @param object The node of the value. +#! @param param The type of `this`. +#! @param decl The method's declaration. +#! @returns The reference. +pub def emitter::receiver(&mut this, object: u32, param: u32, decl: u32): operand { + var made := this.receiver_of(object, this.c.checker.decls.has(decl, df::mut_this)); + + # A default takes the value as a reference to its trait, unless it is compiled + # for each type. + val holder := this.c.trait_of_method(decl); + if holder != 0 && made.count == 1 && !this.c.checker.typed_default(decl) { + val given := this.c.checker.types.first_of(this.c.checker.unalias(made.kind)); + val referent := this.c.checker.unalias(given); + if this.c.checker.named_kind(referent) != dk::trait_type { + val implemented := this.c.checker.implemented(referent, this.c.checker.enclosing_trait(decl)); + val vtable := this.c.vtable_of(given, implemented); + return operand::two(this.c.checker.types.reference(implemented, false), + made.words[0], this.build.word(vtable as u64)); + } + } + return this.convert(&made, param); +} + +#! A reference to what a node gives, which a parameter taking a reference is +#! given where the value given is no reference: one to its place, or to a copy +#! of it the statement holds until it ends. +#! @param this The emitter. +#! @param node The node. +#! @param kind The reference's type. +#! @returns The reference. +pub def emitter::reference_arg(&mut this, node: u32, kind: u32): operand { + if this.c.checker.is_place(node) { + val place := this.place_of(node); + return this.reference_to(&place, kind) if this.lends_as_is(place.kind, kind); + } + + # A value is referred to where the statement holds it, which closes it where + # the statement ends. A value referred to as a trait it implements is held as + # its own type. + val referent := this.c.checker.types.first_of(this.c.checker.unalias(kind)); + var value := this.value_of_type(node); + if this.c.checker.named_kind(this.c.checker.unalias(referent)) != dk::trait_type { + value = this.convert(&value, referent); + } + val place := this.hold(&value); + return this.reference_to(&place, kind); +} + +#! A reference to an operand an operator's method is given, which never keeps +#! it: to the place it names, or to where the statement holds its value, which +#! the statement closes where it ends. +#! @param this The emitter. +#! @param node The operand's node. +#! @param kind The reference's type. +#! @returns The reference. +pub def emitter::lent_arg(&mut this, node: u32, kind: u32): operand { + if this.c.checker.is_place(node) { + val place := this.place_of(node); + return this.reference_to(&place, kind) if this.lends_as_is(place.kind, kind); + } + val referent := this.c.checker.types.first_of(this.c.checker.unalias(kind)); + var value := this.value(node); + value = this.convert(&value, referent); + val place := this.hold(&value); + if value.address == 0 { + var held := operand::at(value.kind, place.address); + this.keep(&held); + } + return this.reference_to(&place, kind); +} + +#! Whether a place is referred to as it is where a reference is wanted: one of +#! its own type, of a trait it implements, of a reference it holds, or one +#! written through. A place of another type is converted first, as a view where +#! a `string` is wanted is copied into one, and the copy referred to. +#! @param this The emitter. +#! @param held The place's type. +#! @param kind The reference's type. +#! @returns Whether it is. +def emitter::lends_as_is(&mut this, held: u32, kind: u32): bool { + val wanted := this.c.checker.unalias(kind); + return true if this.c.checker.types.kind_of(wanted) != ty::reference || this.c.checker.types.second_of(wanted) != 0; + val referent := this.c.checker.unalias(this.c.checker.types.first_of(wanted)); + val own := this.c.checker.unalias(held); + return referent == own || this.c.checker.named_kind(referent) == dk::trait_type + || this.c.checker.types.kind_of(own) == ty::reference; +} + +#! Gathers the arguments of a call: those written, each converted to its +#! parameter or referred to where the parameter takes a reference, those a +#! variadic parameter takes as a view of them, those a pack spreads, and the +#! defaults of the parameters the call leaves out. +#! @param this The emitter. +#! @param node The `call` node. +#! @param decl The function's declaration. +#! @param instance One more than the instance called, or 0. +#! @param kind The function type called. +#! @param skip How many parameters come before the first argument, as +#! `this`. +#! @param into Where the arguments are gathered, after any already there. +pub def emitter::gather( + &mut this, + node: u32, + decl: u32, + instance: u32, + kind: u32, + skip: u32, + into: &mut gathered +): void { + val run := this.c.checker.right_of(node); + val count := this.c.checker.types.part_count(kind); + val variadic := this.c.checker.types.second_of(kind) != 0; + val stop: u32 = variadic ? count - 1 : count; + var p := skip; + var rest_given := false; + + for i in 0..this.c.checker.run_length(run) { + val arg := this.c.checker.run_at(run, i as u32); + val packs := this.is_spread(arg) + && this.c.checker.types.kind_of(this.c.checker.unalias(this.c.checker.reached(this.c.checker.type_at(this.c.checker.left_of(arg))))) == ty::pack; + # A variadic function's pack ends in a view of the rest, which is the view a + # variadic parameter takes as it is. + val ends_in_rest := packs && this.c.checker.types.second_of(this.c.checker.reached(this.c.checker.type_at(this.c.checker.left_of(arg)))) != 0; + break if p >= stop && variadic && !ends_in_rest; + break if p >= count; + + # `...args` spreads the values of a pack, one to a parameter. + if packs { + val pack := this.c.checker.left_of(arg); + val ref := this.c.checker.ref_at(pack); + val local := (ref & ref_local) != 0 ? this.local_of(ref & ref_mask) : 0; + if local != 0 { + val held: local_info = this.locals[local - 1]; + for j in 0..held.count { + val place: location = this.packs[held.pack as u64 + j as u64]; + val value := this.load(&place); + if ends_in_rest && variadic && j + 1 == held.count && p + 1 == count { + into.values.append(value); + p = count; + rest_given = true; + break; + } + # A value that closes is moved to the parameter taking it, as the + # function then owns it: the pack is left empty, so it isn't closed + # twice. The value was copied out of the pack's place as it was read. + val param := this.c.checker.types.part_at(kind, p); + if this.c.checker.closes(place.kind) + && this.c.checker.types.kind_of(this.c.checker.unalias(param)) != ty::reference { + this.zero(&place); + } + into.values.append(this.convert(&value, param)); + p++; + } + } + continue; + } + into.values.append(this.argument(arg, this.c.checker.types.part_at(kind, p))); + p++; + } + + # A variadic parameter takes a view of the rest, which `...xs` gives as it is, + # after the defaults of those before it the call leaves out. + if variadic && !rest_given { + if p < stop { + this.defaults_of(decl, instance, kind, p, stop, into, node, skip); + p = stop; + } + val element := this.c.checker.types.part_at(kind, count - 1); + val view := this.c.checker.span_of(element); + var rest := vector::::new(); + for i in (p - skip) as u64..this.c.checker.run_length(run) as u64 { + rest.append(this.c.checker.run_at(run, i as u32)); + } + if rest.length == 1 && this.is_spread(rest[0]) { + into.values.append(this.spread_view(this.c.checker.left_of(rest[0]), view)); + } else { + into.values.append(this.gathered_view(rest.view(), element, view)); + } + p = count; + } + + # The parameters left out take their defaults, made where the function is. + if p < count { + this.defaults_of(decl, instance, kind, p, count, into, node, skip); + } +} + +#! Whether a node is `...xs`. +#! @param this The emitter. +#! @param node The node. +#! @returns Whether it is. +pub def emitter::is_spread(&mut this, node: u32): bool { + return this.c.checker.kind_of(node) == nk::unary && this.c.checker.token_kind(node) == tk::spread; +} + +#! An argument as its parameter takes it: converted to its type, or referred to +#! where it takes a reference and the argument is none. +#! @param this The emitter. +#! @param node The argument's node. +#! @param param The parameter's type. +#! @returns The value. +pub def emitter::argument(&mut this, node: u32, param: u32) : operand { + if this.c.checker.has_flag(node, rf::borrowed) { + val made := this.reference_arg(node, param); + return this.convert(&made, param); + } + return this.value_as(node, param); +} + +#! A view of the arguments a variadic parameter gathers, held in an array the +#! statement holds. +#! @param this The emitter. +#! @param args The arguments' nodes. +#! @param element The type of each. +#! @param view The view's type. +#! @returns The view. +def emitter::gathered_view(&mut this, args: span, element: u32, view: u32): operand { + val address := this.temporary_of(view); + if args.length == 0 { + this.build.clear(address, 2 * word_size); + return operand::at(view, address); + } + + val array := this.c.checker.types.fixed(element, args.length as u32); + val held := this.c.shape_of(element); + val first := this.temporary_of(array); + for i in 0..args.length { + val value := this.value_as(args[i], element); + this.adopt(&value); + val place := location { kind = element, address = first, offset = i as u64 * held.size, framed = true }; + this.store(&place, &value); + } + this.build.store(access::i64, address, 0, first); + this.build.store(access::i64, address, word_size, this.build.word(args.length)); + # What the array holds closes where the statement ends, as an array literal's does. + var whole := operand::at(array, first); + this.keep(&whole); + return operand::at(view, address); +} + +#! The view `...xs` gives a variadic parameter: a view as it is, or one of every +#! element of a fixed array. +#! @param this The emitter. +#! @param node The node of what is spread. +#! @param view The view's type. +#! @returns The view. +def emitter::spread_view(&mut this, node: u32, view: u32): operand { + val through := this.c.checker.unalias(this.c.checker.reached(this.c.checker.type_at(node))); + if this.c.checker.types.kind_of(through) == ty::fixed { + val whole := this.object(node); + val shape := this.c.shape_of(through); + val address := this.temporary_of(view); + this.build.store(access::i64, address, 0, this.address_of(&whole)); + this.build.store(access::i64, address, word_size, this.build.word(shape.count as u64)); + return operand::at(view, address); + } + val made := this.value(node); + val read := this.through_references(&made); + return this.convert(&read, view); +} + +#! The defaults of the parameters a call leaves out, each made where the +#! function is declared, with the parameters before it named as the arguments +#! the call gave them. +#! @param this The emitter. +#! @param decl The function's declaration. +#! @param instance One more than the instance called, or 0. +#! @param kind The function type called. +#! @param from The first parameter left out. +#! @param to One past the last. +#! @param into The arguments gathered so far, which the defaults follow. +def emitter::defaults_of( + &mut this, + decl: u32, + instance: u32, + kind: u32, + from: u32, + to: u32, + into: &mut gathered, + call: u32, + skip: u32 +): void { + # What a default asks of its call, as where it is or the text of an argument, + # is of the call written, not of a call a default makes. + val outer := this.defaulting; + if outer.node == 0 { + this.defaulting = default_site { + node = call, + file = this.c.checker.at.file, + table = this.c.checker.at.table, + args = this.c.checker.right_of(call), + skip = skip + }; + } + val table := this.c.body_table(decl, instance); + val saved := this.c.checker.at; + this.c.checker.use_table(table); + val node: u32 = this.c.checker.decls.nodes.p[decl]; + val params := this.c.checker.record(node, function_slot::params); + val mark := this.scope_mark(); + if outer.node == 0 { + this.defaulting.params = params; + } + + # The parameters given are named as what they were given. + for i in 0..from { + break if i as u64 >= into.values.length || i >= this.c.checker.run_length(params); + val param := this.c.checker.run_at(params, i as u32); + val place := this.hold(&into.values[i]); + this.declare(param, place, false); + } + for i in from..to { + break if i >= this.c.checker.run_length(params); + val param := this.c.checker.run_at(params, i as u32); + val value := this.c.checker.record(param, parameter_slot::value); + val wanted := this.c.checker.types.part_at(kind, i as u32); + if value == 0 { + this.problem(param, "The parameter is left out and has no default."); + into.values.append(this.zero_value(wanted)); + continue; + } + val made := this.value_as(value, wanted); + into.values.append(made); + val place := this.hold(&made); + this.declare(param, place, false); + } + + this.forget_locals(mark); + this.c.checker.at = saved; + this.defaulting = outer; +} + +#! The argument a call wrote for a parameter a default names, where the default +#! being made names one: the node, in the call's own table. +#! @param this The emitter. +#! @param node The node naming the parameter, in the default. +#! @returns The argument's node, or 0. +pub def emitter::written_argument(&mut this, node: u32): u32 { + return 0 if this.defaulting.node == 0 || this.c.checker.kind_of(node) != nk::name; + val ref := this.c.checker.ref_at(node); + return 0 if (ref & ref_local) == 0; + val param := ref & ref_mask; + val params := this.defaulting.params; + for i in 0..this.c.checker.run_length(params) { + continue if this.c.checker.run_at(params, i as u32) != param; + return 0 if (i as u32) < this.defaulting.skip; + val at := i as u32 - this.defaulting.skip; + val saved := this.c.checker.at; + this.c.checker.use_table(this.defaulting.table); + val arg := at < this.c.checker.run_length(this.defaulting.args) ? this.c.checker.run_at(this.defaulting.args, at) : 0; + this.c.checker.at = saved; + return arg; + } + return 0; +} + +#! Calls a function of the program with the arguments gathered. +#! @param this The emitter. +#! @param index The function. +#! @param given The arguments. +#! @param result The type it gives. +#! @returns What it gives. +pub def emitter::call_function(&mut this, index: u32, given: &gathered, result: u32): operand { + var args := vector::::new(); + this.pass_args(given, &mut args); + return this.call_with(op::call, index, 0, &mut args, result); +} + +#! Adds the words of the arguments gathered to a call's operands, which the call +#! takes as its own. +#! @param this The emitter. +#! @param given The arguments. +#! @param args The operands. +def emitter::pass_args(&mut this, given: &gathered, args: &mut vector): void { + for &each in given.values { + this.adopt(&each); + each.args(args); + } +} + +#! Adds a call, writing what it gives to a cell the statement holds where it is +#! held in memory, whose address the call is given last. +#! @param this The emitter. +#! @param kind The kind of call. +#! @param aux The function or signature called. +#! @param imm The slot of a vtable called through, or 0. +#! @param args The operands. +#! @param result The type it gives. +#! @returns What it gives. +pub def emitter::call_with(&mut this, kind: op, aux: u32, imm: u64, args: &mut vector, result: u32): operand { + val held := this.c.shape_of(result); + if in_memory(&held) { + # A value of no bytes, as a struct of no fields, is returned as nothing, so + # the call is given nowhere to write it. + val address := this.temporary_of(result); + if returned_in_memory(&held) { + args.append(address); + } + this.build.effect(kind, args.view(), aux, imm); + return operand::at(result, address); + } + + var gives := vector::::new(); + for _ in 0..word_count(&held) { + gives.append(word_type(&held)); + } + val index := this.build.emit(kind, args.view(), gives.view(), aux, imm); + var made := operand { kind = result, count = word_count(&held) }; + val first: u32 = this.build.code.insts[index].result; + for i in 0..made.count { + made.words[i] = first + i as u32; + } + return made; +} + +#! Calls a trait's method through the vtable of the reference it is given. +#! @param this The emitter. +#! @param decl The method's declaration. +#! @param holder The trait's declaration. +#! @param given The arguments, the trait reference first. +#! @param result The type it gives. +#! @returns What it gives. +pub def emitter::call_trait(&mut this, decl: u32, holder: u32, given: &gathered, result: u32): operand { + var args := vector::::new(); + this.pass_args(given, &mut args); + # The reference's own trait numbers the slots its vtables hold; within a + # default, `this` holds the vtable of the trait declaring it. + val reached := given.values.length != 0 ? this.c.checker.types.first_of(this.c.checker.unalias(given.values[0].kind)) : 0; + val plain := this.c.checker.unalias(reached); + var owner := this.c.checker.named_kind(plain) == dk::trait_type ? this.c.checker.types.first_of(plain) : holder; + if this.c.checker.types.kind_of(plain) == ty::param { + val param := this.c.checker.types.first_of(plain); + val declarer: u32 = this.c.checker.decls.owners.p[param]; + if this.c.checker.decls.names.p[param] == names::self_id && declarer != 0 + && this.c.checker.decls.kinds.p[declarer] == dk::trait_type { + owner = declarer; + } + } + val slot := this.c.dispatch_index(owner, decl); + val signature := this.c.trait_signature(decl, owner, result, + this.c.checker.named_kind(plain) == dk::trait_type ? plain : 0); + return this.call_with(op::call_trait, signature, slot as u64, &mut args, result); +} + +#! Calls a C function through its address. +#! @param this The emitter. +#! @param address The function's address. +#! @param kind Its function type. +#! @param given The arguments. +#! @param result The type it gives. +#! @returns What it gives. +pub def emitter::call_address(&mut this, address: u32, kind: u32, given: &gathered, result: u32): operand { + var args := vector::::new(); + args.append(address); + this.pass_args(given, &mut args); + return this.call_with(op::call_c, this.c.signature_of(kind), 0, &mut args, result); +} + +#! Lowers a call of a function value: a local, a field, or anything giving a +#! function, or the address of a C function. +#! @param this The emitter. +#! @param node The `call` node. +#! @returns What it gives. +def emitter::call_value(&mut this, node: u32): operand { + val callee := this.c.checker.left_of(node); + val made := this.value_of_type(callee); + val function := this.through_references(&made); + + # A function value has no defaults, but takes a view of the rest where its last + # parameter is variadic, and a value of each type of a pack spread into it. + var given := gathered { values = vector::::new() }; + this.gather(node, 0, 0, this.called_type(function.kind), 0, &mut given); + return this.call_function_value(&function, &given); +} + +#! The function type a function value, or the address of a C function, is called +#! as. +#! @param this The emitter. +#! @param kind The value's type. +#! @returns The function type. +pub def emitter::called_type(&mut this, kind: u32): u32 { + val plain := this.c.checker.unalias(kind); + return this.c.checker.is_std(plain, word::cfn) + ? this.c.checker.unalias(this.c.checker.types.part_at(plain, 0)) + : plain; +} + +#! Calls a function value, or the address of a C function, given its arguments. +#! @param this The emitter. +#! @param function The value. +#! @param given The arguments, as its parameters take them. +#! @returns What it gives. +pub def emitter::call_function_value(&mut this, function: &operand, given: &gathered): operand { + val plain := this.called_type(function.kind); + val result := this.c.checker.types.first_of(plain); + if this.c.checker.is_std(this.c.checker.unalias(function.kind), word::cfn) { + return this.call_address(function.words[0], plain, given, result); + } + + var args := vector::::new(); + function.args(&mut args); + this.pass_args(given, &mut args); + return this.call_with(op::call_value, this.c.signature_of(this.c.call_type(plain)), 0, &mut args, result); +} + +#! Calls an accessor the compiler calls itself, as `at` indexing what implements +#! `indexable`, given the value it is called on and its other argument. +#! @param this The emitter. +#! @param node The node the call stands for. +#! @param decl The accessor's declaration. +#! @param object The node of the value it is called on. +#! @param arg The node of its other argument, or 0. +#! @returns What it gives. +pub def emitter::accessor_call(&mut this, node: u32, decl: u32, object: u32, arg: u32): operand { + val owner := this.c.checker.reached(this.object_type(object)); + val target := this.c.method_target(decl, owner); + var given := gathered { values = vector::::new() }; + given.values.append(this.receiver(object, this.c.checker.types.part_at(target.kind, 0), decl)); + if arg != 0 && this.c.checker.types.part_count(target.kind) > 1 { + given.values.append(this.value_as(arg, this.c.checker.types.part_at(target.kind, 1))); + } + val result := this.c.checker.types.first_of(target.kind); + if target.holder != 0 { + return this.call_trait(decl, target.holder, &given, result); + } + return this.call_function(target.function, &given, result); +} + +#! Calls a method on a value already lowered, as the compiler does where a loop +#! asks an iterator for its next element, or a value is closed: given a +#! reference to it, and the other arguments. +#! @param this The emitter. +#! @param decl The method's declaration. +#! @param owner The type it is called on. +#! @param receiver The reference `this` takes. +#! @param others The other arguments. +#! @returns What it gives. +pub def emitter::method_call(&mut this, decl: u32, owner: u32, receiver: &operand, others: span): operand { + val target := this.c.method_target(decl, owner); + var given := gathered { values = vector::::new() }; + given.values.append(this.convert(receiver, this.c.checker.types.part_at(target.kind, 0))); + given.values.extend(others); + val result := this.c.checker.types.first_of(target.kind); + if target.holder != 0 { + return this.call_trait(decl, target.holder, &given, result); + } + return this.call_function(target.function, &given, result); +} diff --git a/compiler/emitter/closures.sakura b/compiler/emitter/closures.sakura new file mode 100644 index 00000000..df2ee888 --- /dev/null +++ b/compiler/emitter/closures.sakura @@ -0,0 +1,303 @@ +#! @file closures.sakura +#! @author John Christman (sorakatadzuma@gmail.com) +#! @copyright Malunal Studios, LLC. +#! @license MIT +#! +#! Contains functions as values: a function named, the instance of a generic +#! one, the address of a C function, and anonymous functions, which refer to +#! the locals of the function around them they name. An anonymous function +#! naming any is a closure, given an environment of references to them after +#! its parameters, which is a cell of the frame making it, as the locals are. +#! So a closure is good while the locals it refers to are, and one outliving +#! them is the program's mistake, as a reference outliving what it refers to +#! is. + +import sakura::analyzer; +module sakura::compiler; + + +#! A function named as a value: its index plus one, with no environment, a C +#! function's address, or the address of the entry C calls one of the program +#! back through, where it is given as a `cfn`. +#! @param this The emitter. +#! @param node The node naming it. +#! @param decl The function's declaration. +#! @returns The value. +pub def emitter::function_value(&mut this, node: u32, decl: u32): operand { + val kind := this.c.checker.type_at(node); + if this.c.checker.decls.has(decl, df::foreign) { + return operand::one(kind, this.build.value(op::c_address, span::::empty(), vt::word, this.c.linked_of(decl), 0)); + } + if this.c.checker.decls.has(decl, df::callback) && this.c.checker.is_std(this.c.checker.unalias(kind), word::cfn) { + val function := this.c.function_of(decl, 0); + return operand::one(kind, this.build.value(op::callback, span::::empty(), vt::word, function, 0)); + } + + var instance := this.called(node); + # A generic type's function named through it is the instance its arguments give. + if instance == 0 && this.c.checker.decls.has(decl, df::generic) && this.c.checker.kind_of(node) == nk::path { + val target := this.c.checker.path_target(node); + if target.owner != bt::error && this.c.checker.types.kind_of(target.owner) == ty::named { + var args := this.c.checker.types.parts_of(target.owner); + instance = this.c.checker.instance_of(decl, args.view(), node); + } + } + val index := this.c.function_of(decl, instance); + + # Named where another function type is expected, it is called through a + # function of that type made for it. + if this.c.checker.has_flag(node, rf::adapted) { + val wanted := this.c.checker.converted(node); + val adapter := this.c.adapter_of(this.c.checker.at.table, node, this.c.checker.at.file, wanted, index); + this.c.names(this.function, adapter); + return operand::two(wanted, this.build.word(adapter as u64 + 1), this.build.word(0)); + } + this.c.program.functions[index].taken = true; + this.c.names(this.function, index); + return operand::two(kind, this.build.word(index as u64 + 1), this.build.word(0)); +} + +#! An anonymous function as a value: its index plus one, and where it names +#! locals of the functions around it, the environment holding a reference to +#! each, in a cell of the frame. +#! @param this The emitter. +#! @param node The `lambda` node. +#! @returns The value. +pub def emitter::lambda_value(&mut this, node: u32): operand { + val kind := this.c.checker.type_at(node); + var captures := this.captures_of(node); + val index := this.c.lambda_of(this.c.checker.at.table, node, this.c.checker.at.file, kind, captures.length != 0); + val outer: u32 = this.c.program.functions[this.function].decl != 0 + ? this.c.program.functions[this.function].decl + : this.c.program.functions[this.function].outer; + this.c.program.functions[index].outer = outer; + this.c.program.functions[index].taken = true; + this.c.names(this.function, index); + val function := this.build.word(index as u64 + 1); + if captures.length == 0 { + return operand::two(kind, function, this.build.word(0)); + } + + # The environment is a fixed array of references, one to each local captured. + val reference := this.c.checker.types.reference(bt::int64, false); + val holder := this.c.checker.types.fixed(reference, captures.length as u32); + val shape := this.c.shape_of(holder); + val cell := this.build.code.add_cell(round_up(shape.size, word_size) as u32, word_size as u32, ck::local, 0); + val environment := this.build.cell_address(cell); + for i in 0..captures.length { + val local := this.local_of(captures[i]); + if local == 0 { + this.problem(node, "A local the function captures is not where it is named."); + continue; + } + val held: local_info = this.locals[local - 1]; + val made := this.reference_to(&held.place, reference); + val at := location { kind = reference, address = environment, offset = i as u64 * word_size }; + this.store(&at, &made); + } + return operand::two(kind, function, environment); +} + +#! The locals of the functions around an anonymous function that it names, or +#! that one within it names, in the order it first names them. +#! @param this The emitter. +#! @param node The `lambda` node. +#! @returns The nodes declaring them. +pub def emitter::captures_of(&mut this, node: u32): vector { + var made := vector::::new(); + val first := this.lowest_node(node); + var walk := node_walk::new(node); + while walk.more() { + val at := walk.next(); + # A contract left out captures nothing. + continue if this.c.checker.contracts_off && this.c.checker.kind_of(at) == nk::contract; + if this.c.checker.kind_of(at) == nk::name { + val ref := this.c.checker.ref_at(at); + if (ref & ref_local) != 0 { + val local := ref & ref_mask; + if (local < first || local > node) && !made.view().contains(&local) { + made.append(local); + } + } + } + walk.enter(this.c.checker.syn(), at); + } + return made; +} + +#! The first node of what a node was parsed from, which the parser made before +#! the node itself, one after another. +#! @param this The emitter. +#! @param node The node. +#! @returns The lowest node under it. +pub def emitter::lowest_node(&mut this, node: u32): u32 { + var lowest := node; + var walk := node_walk::new(node); + while walk.more() { + val at := walk.next(); + lowest = at < lowest ? at : lowest; + walk.enter(this.c.checker.syn(), at); + } + return lowest; +} + +#! The function an anonymous function is lowered to, made where it is new. +#! @param this The compiler. +#! @param table The result table its nodes' results are in. +#! @param node Its `lambda` node. +#! @param file The file it is in. +#! @param kind Its function type. +#! @param closure Whether it captures locals. +#! @returns The function's index. +pub def lowerer::lambda_of(&mut this, table: u32, node: u32, file: u32, kind: u32, closure: bool): u32 { + val key := pair_key(table, node); + if this.lambda_ids.get(&key) is some(got) { + return got; + } + val index := this.add_function(string::from("", nothing {}), this.signature_of(kind)); + this.lambda_ids.set(key, index); + this.program.functions[index].node = node; + this.program.functions[index].table = table; + this.program.functions[index].file = file; + this.program.functions[index].offset = this.node_offset(file, node); + this.program.functions[index].closure = closure; + this.want(index); + return index; +} + +#! The adapter of a function named as a value of another function type: a +#! function of that type, made where it is first named, which calls it as a call +#! would, with the defaults of the parameters the type leaves out. +#! @param this The compiler. +#! @param table The result table holding the node. +#! @param node The node naming the function. +#! @param file The file the node is in. +#! @param kind The function type the adapter is of. +#! @param callee The function it calls. +#! @returns The adapter. +pub def lowerer::adapter_of(&mut this, table: u32, node: u32, file: u32, kind: u32, callee: u32): u32 { + val key := pair_key(table, node); + if this.adapter_ids.get(&key) is some(got) { + return got; + } + var name := string::from(this.program.functions[callee].name.view(), nothing {}); + name.append(" (adapted)"); + val index := this.add_function(move(&mut name), this.signature_of(kind)); + this.adapter_ids.set(key, index); + this.program.functions[index].adapted = callee + 1; + this.program.functions[index].node = node; + this.program.functions[index].table = table; + this.program.functions[index].file = file; + this.program.functions[index].offset = this.node_offset(file, node); + this.program.functions[index].taken = true; + this.want(index); + return index; +} + +#! Lowers an adapter: each parameter of the type it is of is given to the +#! function it calls as a call gives an argument: a value lent where it takes a +#! reference, closed once the call returns, a reference read through where it +#! takes what it reaches, and a value converted or moved where it takes a value. +#! The parameters the type leaves out take their defaults, and what the function +#! gives is converted to what the type gives. +#! @param this The emitter. +pub def emitter::lower_adapter(&mut this): void { + val entry := this.function; + val callee: u32 = this.c.program.functions[entry].adapted - 1; + val node: u32 = this.c.program.functions[entry].node; + this.table = this.c.program.functions[entry].table; + this.use_own_table(); + this.at_node(node); + val wanted := this.c.checker.unalias(this.c.checker.converted(node)); + val kind := this.c.checker.unalias(this.c.checker.type_at(node)); + this.result = this.c.checker.types.first_of(wanted); + val signature: u32 = this.c.program.functions[entry].signature; + val count := this.c.checker.types.part_count(wanted); + + var next: u32 = 0; + var given := gathered { values = vector::::new() }; + var lent := vector::::new(); + for i in 0..count { + val held := this.take_param(signature, i as u32, &mut next); + val param := this.c.checker.types.part_at(kind, i as u32); + val place := this.param_place(0, held); + val takes_reference := this.c.is_reference_type(this.c.checker.unalias(param)); + if takes_reference && !this.c.is_reference_type(this.c.checker.unalias(held.kind)) { + given.values.append(this.reference_to(&place, param)); + if this.c.checker.closes(held.kind) { + lent.append(place); + } + continue; + } + val value := this.load(&place); + given.values.append(this.convert(&value, param)); + # What converts lends from what the adapter holds, as a string a view of its + # text, and what doesn't is moved into the call. + if !takes_reference && this.c.checker.closes(held.kind) + && this.c.checker.unalias(held.kind) != this.c.checker.unalias(param) { + lent.append(place); + } + } + + val decl: u32 = this.c.program.functions[callee].decl; + val instance: u32 = this.c.program.functions[callee].instance; + val total := this.c.checker.types.part_count(kind); + if count < total { + this.defaults_of(decl, instance, kind, count as u32, total, &mut given, node, 0); + } + val made := this.call_function(callee, &given, this.c.checker.types.first_of(kind)); + val result := this.convert(&made, this.result); + for &each in lent.view() { + this.close(&each); + } + var args := vector::::new(); + result.args(&mut args); + this.give_back(args.view()); +} + +#! Lowers an anonymous function: the locals it captures are reached through the +#! references its environment holds, which it never closes, since the function +#! declaring them owns them. +#! @param this The emitter. +#! @param node The `lambda` node. +pub def emitter::lower_lambda(&mut this, node: u32): void { + this.table = this.c.program.functions[this.function].table; + this.use_own_table(); + this.at_node(node); + val kind := this.c.checker.type_at(node); + this.result = this.c.checker.types.first_of(kind); + val params := this.c.checker.left_of(node); + val body := this.c.checker.record(node, lambda_slot::body); + val signature: u32 = this.c.program.functions[this.function].signature; + val total := this.c.program.signatures[signature].params.length as u32; + + var next: u32 = 0; + var taken := vector::::new(); + for i in 0..total { + taken.append(this.take_param(signature, i as u32, &mut next)); + } + + # The environment follows the parameters. + if this.c.program.functions[this.function].closure { + val environment := this.build.param(next); + var captures := this.captures_of(node); + val reference := this.c.checker.types.reference(bt::int64, false); + for i in 0..captures.length { + val at := location { kind = reference, address = environment, offset = i as u64 * word_size }; + val made := this.load(&at); + val captured := captures[i]; + val place := location { kind = this.c.checker.type_at(captured), address = made.words[0] }; + this.declare(captured, place, false); + } + } + + this.plan_lambda(node); + for i in 0..this.c.checker.run_length(params) { + break if i as u64 >= taken.length; + val param := this.c.checker.run_at(params, i as u32); + val place := this.param_place(param, taken[i]); + this.declare(param, place, this.c.checker.closes(taken[i].kind)); + } + this.safepoint(); + this.lower_body(body); +} diff --git a/compiler/emitter/composite.sakura b/compiler/emitter/composite.sakura new file mode 100644 index 00000000..44727328 --- /dev/null +++ b/compiler/emitter/composite.sakura @@ -0,0 +1,553 @@ +#! @file composite.sakura +#! @author John Christman (sorakatadzuma@gmail.com) +#! @copyright Malunal Studios, LLC. +#! @license MIT +#! +#! Contains the lowering of values built from others, and of what reads into +#! them: struct and union literals, with the defaults of the fields they leave +#! out, array literals, the members of a value, its properties through their +#! accessors, and slices. + +import sakura::analyzer; +module sakura::compiler; + + +#! A struct or union literal, built in a cell the statement holds. +#! @param this The emitter. +#! @param node The `construct` node. +#! @returns The value. +pub def emitter::construct(&mut this, node: u32): operand { + return this.construct_of(this.c.checker.type_at(node), this.c.checker.right_of(node)); +} + +#! A struct or union literal of a type, given its field inits, built in a cell +#! the statement holds, as an attribute's value is too. +#! @param this The emitter. +#! @param kind The type. +#! @param inits The run of `field_init` nodes. +#! @returns The value. +pub def emitter::construct_of(&mut this, kind: u32, inits: u32): operand { + val plain := this.c.checker.unalias(kind); + return operand::none(kind) if plain == bt::void_type; + val index := this.c.layout_of(plain); + val shape := this.c.layout_at(index); + val address := this.temporary_of(kind); + val decl := this.c.checker.types.first_of(plain); + # A struct's fields given write themselves, so what is cleared is the rest: + # the padding, and the fields left out, which take their defaults over zero. + if shape.kind != lk::variant && this.c.checker.decls.kinds.p[decl] != dk::union_type { + this.clear_unwritten(address, index, inits); + } else { + this.build.clear(address, shape.size); + } + val whole := location { kind = kind, address = address, framed = true }; + + # A union holds the one field it is given, whose index is its tag. A C union + # holds it over the others, without a tag. + if shape.kind == lk::variant { + if this.c.checker.run_length(inits) == 0 { + this.defaults(&whole); + return operand::at(kind, address); + } + val init := this.c.checker.run_at(inits, 0); + val field := this.c.checker.ref_at(init); + for i in 0..shape.count { + val each := this.c.field_at(index, i as u32); + continue if each.decl != field; + if shape.niche == 0 { + this.build.store(access::i64, address, 0, this.build.word(i)); + } + val value := this.value_as(this.c.checker.left_of(init), each.type_id); + this.adopt(&value); + val at := this.within(&whole, each.offset, each.type_id); + this.store(&at, &value); + } + return operand::at(kind, address); + } + + var given := vector::::new(); + for i in 0..this.c.checker.run_length(inits) { + val init := this.c.checker.run_at(inits, i as u32); + val field := this.c.checker.ref_at(init); + given.append(field); + val at := this.field_in(&whole, plain, field, 0); + val value := this.value_as(this.c.checker.left_of(init), at.kind); + this.adopt(&value); + this.store(&at, &value); + } + if this.c.checker.decls.kinds.p[decl] == dk::union_type { + if given.length == 0 { + this.defaults(&whole); + } + return operand::at(kind, address); + } + + # The fields left out take their defaults, or the defaults of what they hold. + for i in 0..shape.count { + val each := this.c.field_at(index, i as u32); + var was_given := false; + for &field in given { + was_given = was_given || field == each.decl; + } + continue if was_given; + val at := this.within(&whole, each.offset, each.type_id); + this.default_of(&at, each.decl, each.spread); + } + return operand::at(kind, address); +} + +#! Clears the bytes of a struct literal's memory that none of the fields it +#! gives writes, where each is written whole: those of its own fields, and not +#! those a spread brings in, whose spread field is cleared whole. +#! @param this The emitter. +#! @param address Where the struct is built. +#! @param index Its layout. +#! @param inits The run of `field_init` nodes. +def emitter::clear_unwritten(&mut this, address: u32, index: u32, inits: u32): void { + val shape := this.c.layout_at(index); + var written := vector::::new(); + written.resize(shape.size); + for i in 0..this.c.checker.run_length(inits) { + val field := this.c.checker.ref_at(this.c.checker.run_at(inits, i as u32)); + for k in 0..shape.count { + val each := this.c.field_at(index, k as u32); + continue if each.decl != field || each.spread; + val end := each.offset + this.c.shape_of(each.type_id).size; + for at in each.offset..end { + written[at] = true; + } + } + } + var at: u64 = 0; + while at < shape.size { + if written[at] { + at++; + continue; + } + var end := at; + while end < shape.size && !written[end] { + end++; + } + this.clear_bytes(address, at, end); + at = end; + } +} + +#! Clears a run of bytes at an address: as stores of zero where it is a few +#! words, as padding is, and otherwise at once. +#! @param this The emitter. +#! @param address The address. +#! @param from The first byte. +#! @param to Past the last. +def emitter::clear_bytes(&mut this, address: u32, from: u64, to: u64): void { + if to - from > 4 * word_size { + val first := from == 0 ? address : this.build.binary(op::add, address, this.build.word(from)); + this.build.clear(first, to - from); + return; + } + val zero := this.build.word(0); + var at := from; + while at < to { + val left := to - at; + val how := left >= 8 && at % 8 == 0 ? access::i64 + : left >= 4 && at % 4 == 0 ? access::u32 + : left >= 2 && at % 2 == 0 ? access::u16 : access::u8; + this.build.store(how, address, at, zero); + at += how.width(); + } +} + +#! `a..b`, or `a..=b`, as a value: std's `range`, built in a cell the +#! statement holds from its fields in the order std declares them, its start, +#! its end, and whether it is still to give its end. +#! @param this The emitter. +#! @param node The `range` node. +#! @returns The value. +pub def emitter::range_value(&mut this, node: u32): operand { + val kind := this.c.checker.type_at(node); + val plain := this.c.checker.unalias(kind); + val index := this.c.layout_of(plain); + val shape := this.c.layout_at(index); + val address := this.temporary_of(kind); + this.build.clear(address, shape.size); + val whole := location { kind = kind, address = address, framed = true }; + + val start := this.c.field_at(index, 0); + val first := this.value_as(this.c.checker.left_of(node), start.type_id); + val at_start := this.within(&whole, start.offset, start.type_id); + this.store(&at_start, &first); + + val end := this.c.field_at(index, 1); + val last := this.value_as(this.c.checker.right_of(node), end.type_id); + val at_end := this.within(&whole, end.offset, end.type_id); + this.store(&at_end, &last); + + if this.c.checker.token_kind(node) == tk::cascadeeq { + val held := this.c.field_at(index, 2); + this.build.store(access::u8, address, held.offset, this.build.word(1)); + } + return operand::at(kind, address); +} + +#! Sets the defaults of the fields of a zeroed struct, and of the first field a +#! zeroed union holds, as a variable without a value is given them. +#! @param this The emitter. +#! @param place The place, zeroed. +pub def emitter::defaults(&mut this, place: &location): void { + val plain := this.c.checker.unalias(place.kind); + return if this.c.checker.types.kind_of(plain) != ty::named; + val index := this.c.layout_of(plain); + val shape := this.c.layout_at(index); + val decl := this.c.checker.types.first_of(plain); + val named := this.c.checker.decls.kinds.p[decl]; + return if named != dk::struct_type && named != dk::union_type; + + # A union is zeroed as its first field, and so is a C union. + if named == dk::union_type { + if shape.count != 0 { + val first := this.c.field_at(index, 0); + val inner := this.c.layout_at(first.layout); + if inner.kind == lk::record { + val at := this.within(place, first.offset, first.type_id); + this.defaults(&at); + } + } + return; + } + for i in 0..shape.count { + val each := this.c.field_at(index, i as u32); + val at := this.within(place, each.offset, each.type_id); + this.default_of(&at, each.decl, each.spread); + } +} + +#! Gives a field of a zeroed struct its default: the value it is declared with, +#! made where the struct is declared, or the defaults of a struct it holds. +#! @param this The emitter. +#! @param place The field's place, zeroed. +#! @param field The field's declaration. +#! @param spread Whether it spreads another struct's fields. +def emitter::default_of(&mut this, place: &location, field: u32, spread: bool): void { + val value := spread ? 0 : this.c.checker.field_default(field); + if value == 0 { + val inner := this.c.shape_of(place.kind); + if inner.kind == lk::record { + this.defaults(place); + } + return; + } + + val file: u32 = this.c.checker.decls.files.p[field]; + val saved := this.c.checker.at; + this.c.checker.use_table(this.c.checker.units[file].table); + val made := this.value_as(value, place.kind); + this.c.checker.at = saved; + this.adopt(&made); + this.store(place, &made); +} + +#! An array literal: a fixed array holding its elements, or, where a view is +#! wanted, a view of such an array, which lives as long as the function does, +#! since the view may outlive the statement. +#! @param this The emitter. +#! @param node The `array` node. +#! @param kind The type it is used as. +#! @returns The value. +pub def emitter::array_literal(&mut this, node: u32, kind: u32): operand { + val run := this.c.checker.left_of(node); + val count := this.c.checker.run_length(run); + val plain := this.c.checker.unalias(kind); + val viewed := this.c.viewed(plain); + val element := viewed != 0 ? viewed : this.c.checker.types.first_of(plain); + val inner := this.c.shape_of(element); + + if viewed != 0 { + val view := this.temporary_of(kind); + if count == 0 { + this.build.clear(view, 2 * word_size); + return operand::at(kind, view); + } + + # A read-only view of what is known while compiling views data the program + # holds, made once. + if this.c.checker.is_std(plain, word::span) { + val held := this.static_datum(node, element); + if held != no_block { + val data := this.build.value(op::datum, span::::empty(), vt::word, held, 0); + this.build.store(access::i64, view, 0, data); + this.build.store(access::i64, view, word_size, this.build.word(count as u64)); + return operand::at(kind, view); + } + } + val array := this.c.checker.types.fixed(element, count); + val held := this.c.shape_of(array); + val cell := this.build.code.add_cell(round_up(held.size, word_size) as u32, + held.align < word_size ? word_size as u32 : held.align as u32, ck::local, 0); + val first := this.build.cell_address(cell); + this.fill_array(run, element, inner.size, first); + this.build.store(access::i64, view, 0, first); + this.build.store(access::i64, view, word_size, this.build.word(count as u64)); + # What the array holds closes where the statement ends, since a view owns + # nothing. + var whole := operand::at(array, first); + this.keep(&whole); + return operand::at(kind, view); + } + + val address := this.temporary_of(kind); + this.fill_array(run, element, inner.size, address); + return operand::at(kind, address); +} + +#! The datum holding the elements of an array literal, where each is known +#! while compiling: a number, text, or an array literal viewed of the same. +#! @param this The emitter. +#! @param node The `array` node. +#! @param element The elements' type. +#! @returns The datum, or `no_block` where an element is not known. +def emitter::static_datum(&mut this, node: u32, element: u32): u32 { + val run := this.c.checker.left_of(node); + val count := this.c.checker.run_length(run); + val inner := this.c.shape_of(element); + var bytes := vector::::new(); + bytes.resize(count as u64 * inner.size + 1); + var moved := vector::::new(); + for i in 0..count { + val each := this.c.checker.run_at(run, i as u32); + return no_block if !this.write_static(each, element, &mut bytes, i as u64 * inner.size, &mut moved); + } + val index := this.c.program.data.length as u32; + this.c.program.data.append(datum { + bytes = move(&mut bytes), + align = inner.align < word_size ? word_size : inner.align, + relocations = move(&mut moved) + }); + return index; +} + +#! Writes a value known while compiling into the bytes of a datum, laid out as +#! its type is. +#! @param this The emitter. +#! @param node The value's node. +#! @param kind Its type. +#! @param bytes The datum's bytes. +#! @param at Where it is written. +#! @param moved Where the addresses it holds are noted. +#! @returns Whether it is known. +def emitter::write_static(&mut this, node: u32, kind: u32, bytes: &mut vector, at: u64, moved: &mut vector): bool { + val shape := this.c.shape_of(kind); + if this.c.is_scalar_type(kind) && this.c.checker.is_known(node) { + val value := this.c.checker.value_at(node); + var word: u64 = 0; + if shape.kind == lk::floating { + val real := value.as_real(); + word = shape.bits <= 32 ? bits_of_single(real as f32) as u64 : bits_of_real(real); + } else { + word = value.floating ? (value.real as i64) as u64 : value.bits(); + } + write_number(bytes, at, shape.size, word); + return true; + } + + val viewed := this.c.viewed(kind); + return false if viewed == 0 || !this.c.checker.is_std(this.c.checker.unalias(kind), word::span); + var target: u32 = no_block; + var length: u64 = 0; + if this.c.checker.kind_of(node) == nk::string { + var text := string::new(nothing {}); + this.decode_literal(this.c.checker.text_of(node), &mut text); + target = this.c.text_datum(text.view()); + length = text.length; + } else if this.c.checker.kind_of(node) == nk::array { + length = this.c.checker.run_length(this.c.checker.left_of(node)) as u64; + target = length == 0 ? no_block : this.static_datum(node, viewed); + return false if length != 0 && target == no_block; + } else { + return false; + } + if length != 0 { + moved.append(relocation { at = at, target = target, addend = 0 }); + } + write_number(bytes, at + word_size, word_size, length); + return true; +} + +#! The bits of an `f32`. +#! @param value The value. +#! @returns Its bits. +def bits_of_single(value: f32): u32 { + var held := value; + return ((&mut held) as *mut u32)[0]; +} + +#! Writes the elements of an array literal one after another from an address. +#! @param this The emitter. +#! @param run The run of the elements' nodes. +#! @param element Their type. +#! @param size The size of each. +#! @param first Where the first goes. +def emitter::fill_array(&mut this, run: u32, element: u32, size: u64, first: u32): void { + for i in 0..this.c.checker.run_length(run) { + val value := this.value_as(this.c.checker.run_at(run, i as u32), element); + this.adopt(&value); + val at := location { kind = element, address = first, offset = i as u64 * size, framed = true }; + this.store(&at, &value); + } +} + +#! `x.name`: a field, read where it is, or a property, read through its `get`. +#! The length of a fixed array is known while compiling, which its value gives. +#! @param this The emitter. +#! @param node The `member` node. +#! @returns The value. +pub def emitter::member_value(&mut this, node: u32): operand { + val property := this.property_of(node); + if property != 0 { + val object := this.c.checker.left_of(node); + val receiver := this.receiver_of(object, false); + return this.property_get(property, &receiver, node); + } + val place := this.place_of(node); + return this.load(&place); +} + +#! The property a member names, or 0. +#! @param this The emitter. +#! @param node The node. +#! @returns The property's declaration, or 0. +pub def emitter::property_of(&mut this, node: u32): u32 { + val kind := this.c.checker.kind_of(node); + return 0 if kind != nk::member && kind != nk::member_of; + val ref := this.c.checker.ref_at(node); + return 0 if ref == 0 || (ref & (ref_local | ref_type)) != 0; + # `x.(d)` may name the accessor of the property. + if this.c.checker.decls.kinds.p[ref] == dk::function && this.c.checker.decls.has(ref, df::accessor) { + return this.c.checker.decls.owners.p[ref]; + } + return this.c.checker.decls.kinds.p[ref] == dk::property ? ref : 0; +} + +#! The reference a method or a property's accessors take to the value they are +#! of: the reference the value already is, read through to the last, or one to +#! the place it is, or to a copy of it where it is no place. +#! @param this The emitter. +#! @param object The node of the value. +#! @param writes Whether it is written. +#! @returns The reference. +pub def emitter::receiver_of(&mut this, object: u32, writes: bool): operand { + val kind := this.c.checker.type_at(object); + return this.through_one(object) if this.c.is_reference_type(kind); + return this.reference_arg(object, this.c.checker.types.reference(kind, writes)); +} + +#! The accessor of a property: its `set`, or its `get`. +#! @param this The emitter. +#! @param property The property's declaration. +#! @param setter Whether the `set` is wanted. +#! @returns The accessor's declaration, or 0. +pub def emitter::accessor_of(&mut this, property: u32, setter: bool): u32 { + val run: u32 = this.c.checker.decls.children.p[property]; + for i in 0..this.c.checker.decls.list_length(run) { + val each := this.c.checker.decls.list_at(run, i as u32); + return each if this.c.checker.decls.has(each, df::setter) == setter; + } + return 0; +} + +#! Reads a property through its `get`. +#! @param this The emitter. +#! @param property The property's declaration. +#! @param receiver The reference to the value it is of. +#! @param node The node reading it. +#! @returns What its `get` gives. +pub def emitter::property_get(&mut this, property: u32, receiver: &operand, node: u32): operand { + val getter := this.accessor_of(property, false); + if getter == 0 { + this.problem(node, "The property has no `get`."); + return this.zero_value(this.c.checker.type_at(node)); + } + val owner := this.c.checker.types.first_of(this.c.checker.unalias(receiver.kind)); + val made := this.method_call(getter, owner, receiver, span::::empty()); + this.keep(&made); + return made; +} + +#! Writes a property through its `set`. +#! @param this The emitter. +#! @param property The property's declaration. +#! @param receiver The reference to the value it is of. +#! @param value The value written. +#! @param node The node writing it. +pub def emitter::property_set(&mut this, property: u32, receiver: &operand, value: &operand, node: u32): void { + val setter := this.accessor_of(property, true); + if setter == 0 { + this.problem(node, "The property has no `set`."); + return; + } + val owner := this.c.checker.types.first_of(this.c.checker.unalias(receiver.kind)); + var others: operand[1] = [value]; + this.method_call(setter, owner, receiver, others[0:1]); +} + +#! `x[start:count]`: a view of the elements of a fixed array, of what a pointer +#! points at, or of another view, checked against how many there are where that +#! is known. Either bound may be left out but a pointer's count. +#! @param this The emitter. +#! @param node The `slice` node. +#! @returns The view. +pub def emitter::slice(&mut this, node: u32): operand { + val object := this.c.checker.left_of(node); + val start := this.c.checker.record(node, slice_slot::start); + val count := this.c.checker.record(node, slice_slot::count); + val kind := this.c.checker.type_at(node); + val through := this.c.checker.unalias(this.c.checker.reached(this.c.checker.type_at(object))); + var data: u32 = 0; + var held: u32 = 0; + var element: u32 = 0; + + match this.c.checker.types.kind_of(through) { + ty::fixed => { + val whole := this.object(object); + val shape := this.c.shape_of(through); + data = this.address_of(&whole); + held = this.build.word(shape.count as u64); + element = this.c.checker.types.first_of(through); + } + ty::pointer => { + val pointer := this.value_of_type(object); + data = this.through_references(&pointer).words[0]; + element = this.c.checker.types.first_of(through); + } + else => { + val whole := this.object(object); + data = this.build.load(access::i64, whole.address, whole.offset); + held = this.build.load(access::i64, whole.address, whole.offset + word_size); + element = this.c.viewed(through); + } + } + + val size := this.c.shape_of(element).size; + var from := this.build.word(0); + if start != 0 { + from = this.value_as(start, bt::uint64).words[0]; + if held != 0 && this.checking() { + this.build.check(this.build.binary(op::leu, from, held), fault::out_of_bounds as u32); + } + } + var many: u32 = 0; + if count != 0 { + many = this.value_as(count, bt::uint64).words[0]; + if held != 0 && this.checking() { + val rest := this.build.binary(op::sub, held, from); + this.build.check(this.build.binary(op::leu, many, rest), fault::out_of_bounds as u32); + } + } else { + many = held != 0 ? this.build.binary(op::sub, held, from) : this.build.word(0); + } + + val first := this.build.binary(op::add, data, this.scaled(from, size)); + val view := this.temporary_of(kind); + this.build.store(access::i64, view, 0, first); + this.build.store(access::i64, view, word_size, many); + return operand::at(kind, view); +} diff --git a/compiler/emitter/formatting.sakura b/compiler/emitter/formatting.sakura new file mode 100644 index 00000000..7c5319ae --- /dev/null +++ b/compiler/emitter/formatting.sakura @@ -0,0 +1,238 @@ +#! @file formatting.sakura +#! @author John Christman (sorakatadzuma@gmail.com) +#! @copyright Malunal Studios, LLC. +#! @license MIT +#! +#! Contains the lowering of text a program writes while it runs: interpolated +#! strings, whose holes are written as the values they hold, and the text of +#! literals, decoded from how they are written. + +import sakura::analyzer; +module sakura::compiler; + + +#! An interpolated string: its text and the values of its holes, written in +#! order into text a `string` then owns. A view of bytes, and a string, are +#! written as the text they hold. +#! @param this The emitter. +#! @param node The `istring` node. +#! @returns The string. +pub def emitter::interpolated(&mut this, node: u32): operand { + this.build.effect(op::format, span::::empty(), 0, 0); + val run := this.c.checker.left_of(node); + val count := this.c.checker.run_length(run); + + # The lines of a block are written without the indentation its closing + # delimiter stands at, as a block of plain text is. + var indent: u64 = 0; + var block := false; + if count != 0 && this.c.checker.kind_of(this.c.checker.run_at(run, 0)) == nk::string { + val opened := this.c.checker.text_of(this.c.checker.run_at(run, 0)); + block = opened.length >= 4 && opened.substr(0, 4) == "$\"\"\""; + } + if block && this.c.checker.kind_of(this.c.checker.run_at(run, count - 1)) == nk::string { + val closed := this.c.checker.text_of(this.c.checker.run_at(run, count - 1)); + var line := closed.length; + while line > 0 && closed[line - 1] != '\n' { + line--; + } + if line != 0 && closed.length >= 3 { + indent = closed.length - 3 - line; + } + } + + for i in 0..count { + val piece := this.c.checker.run_at(run, i as u32); + if this.c.checker.kind_of(piece) == nk::string { + var text := string::new(nothing {}); + if block { + this.block_piece(piece, i == 0, indent, &mut text); + } else { + this.piece_text(piece, &mut text); + } + if text.length != 0 { + this.build.effect(op::format_text, span::::empty(), this.c.text_datum(text.view()), 0); + } + continue; + } + val mark := this.cell_mark(); + val value := this.value(piece); + this.format_value(&value); + this.release(mark); + } + + # Text written where a view is wanted is made as a string all the same, which + # the statement closes, so the view is only good while it runs. + val made := this.c.checker.type_at(node); + val text := this.owned_text(made); + val wanted := this.c.checker.converted(node); + return text if wanted == made; + return this.convert(&text, wanted); +} + +#! Writes a value into the text being made: the bytes a view of them or a +#! string holds, or the value as its layout says it is written. +#! @param this The emitter. +#! @param value The value. +pub def emitter::format_value(&mut this, value: &operand): void { + val kind := this.c.checker.unalias(value.kind); + val viewed := this.c.is_reference_type(kind) ? 0 : this.c.viewed(kind); + if viewed != 0 { + val element := this.c.shape_of(viewed); + if element.size == 1 && element.kind != lk::record { + var args: u32[2] = [this.build.load(access::i64, value.address, 0), this.build.load(access::i64, value.address, word_size)]; + this.build.effect(op::format_bytes, args[0:2], 0, 0); + return; + } + } + if !this.c.is_reference_type(kind) && this.c.is_string(kind) { + val index := this.c.layout_of(kind); + val data := this.c.field_at(index, 1); + val count := this.c.field_at(index, 2); + var args: u32[2] = [this.build.load(access::i64, value.address, data.offset), this.build.load(access::i64, value.address, count.offset)]; + this.build.effect(op::format_bytes, args[0:2], 0, 0); + return; + } + + var args := vector::::new(); + value.args(&mut args); + this.build.effect(op::format_value, args.view(), this.c.layout_of(kind), 0); +} + +#! The text of a piece of an interpolated block, decoded: each of its lines +#! without the spaces trailing it and followed by a line break, and each line +#! after one without the indentation the block's closing delimiter stands at. +#! The first piece begins below the line the block opens. +#! @param this The emitter. +#! @param piece The `string` node of the piece. +#! @param first Whether it is the first piece. +#! @param indent How far the block's lines are indented. +#! @param out Where the bytes are written. +def emitter::block_piece(&mut this, piece: u32, first: bool, indent: u64, out: &mut string): void { + val written := this.c.checker.text_of(piece); + var from := 0u; + var to := written.length; + if written.length >= 4 && written.substr(0, 4) == "$\"\"\"" { + from = 4; + } else if written.length >= 1 && written[0] == '}' { + from = 1; + } + if to >= from + 3 && written.substr(to - 3, 3) == "\"\"\"" { + to -= 3; + } else if to > from && written[to - 1] == '{' { + to -= 1; + } + + var at := from; + if first { + while at < to && written[at] != '\n' { + at++; + } + return if at >= to; + at = past_indent(written, at + 1, to, indent); + } + var start := at; + while at < to { + if written[at] != '\n' { + at++; + continue; + } + var stop := at; + while stop > start && (written[stop - 1] == ' ' || written[stop - 1] == '\t') { + stop--; + } + this.c.checker.decode_text(written.substr(start, stop - start), out); + out.push('\n'); + at = past_indent(written, at + 1, to, indent); + start = at; + } + this.c.checker.decode_text(written.substr(start, to - start), out); +} + +#! Where a line begins past the indentation of a block. +#! @param text The text. +#! @param at Where the line begins. +#! @param end Where the text ends. +#! @param indent How far the block's lines are indented. +#! @returns Where the line begins past it. +def past_indent(text: strview, at: u64, end: u64, indent: u64): u64 { + var made := at; + var skipped: u64 = 0; + while skipped < indent && made < end && (text[made] == ' ' || text[made] == '\t') { + made++; + skipped++; + } + return made; +} + +#! The text of a piece of an interpolated string, without what opens and +#! closes it, decoded. +#! @param this The emitter. +#! @param piece The `string` node of the piece. +#! @param out Where the bytes are written. +def emitter::piece_text(&mut this, piece: u32, out: &mut string): void { + val written := this.c.checker.text_of(piece); + var from := 0u; + var to := written.length; + if written.length >= 4 && written.substr(0, 4) == "$\"\"\"" { + from = 4; + } else if written.length >= 2 && written.substr(0, 2) == "$\"" { + from = 2; + } else if written.length >= 1 && written[0] == '}' { + from = 1; + } + if to >= from + 3 && written.substr(to - 3, 3) == "\"\"\"" { + to -= 3; + } else if to > from && (written[to - 1] == '"' || written[to - 1] == '{') { + to -= 1; + } + this.c.checker.decode_text(written.substr(from, to - from), out); +} + +#! Decodes the text a literal is written as: between its quotes, with its +#! escapes, or of text spanning lines, each of its lines without the +#! indentation the closing quotes stand at, and each followed by a line break. +#! @param this The emitter. +#! @param written The literal, with its quotes. +#! @param out Where the bytes are written. +pub def emitter::decode_literal(&mut this, written: strview, out: &mut string): void { + if written.length < 6 || written.substr(0, 3) != "\"\"\"" { + this.c.checker.decode_text(written.substr(1, written.length < 2 ? 0 : written.length - 2), out); + return; + } + + # The text begins below the line the block opens, and the closing quotes' own + # line says how far every line of it is indented. + val inner := written.substr(3, written.length - 6); + var first := 0u; + while first < inner.length && inner[first] != '\n' { + first++; + } + var last := inner.length; + while last > 0 && inner[last - 1] != '\n' { + last--; + } + return if first >= inner.length || last <= first; + + val indent := inner.length - last; + var line := first + 1; + while line < last { + var stop := line; + while stop < last && inner[stop] != '\n' { + stop++; + } + var at := line; + var skipped := 0u; + while skipped < indent && at < stop && (inner[at] == ' ' || inner[at] == '\t') { + at++; + skipped++; + } + var text := stop; + while text > at && (inner[text - 1] == ' ' || inner[text - 1] == '\t') { + text--; + } + this.c.checker.decode_text(inner.substr(at, text - at), out); + out.push('\n'); + line = stop + 1; + } +} diff --git a/compiler/emitter/intrinsics.sakura b/compiler/emitter/intrinsics.sakura new file mode 100644 index 00000000..026af852 --- /dev/null +++ b/compiler/emitter/intrinsics.sakura @@ -0,0 +1,546 @@ +#! @file intrinsics.sakura +#! @author John Christman (sorakatadzuma@gmail.com) +#! @copyright Malunal Studios, LLC. +#! @license MIT +#! +#! Contains the intrinsics, the functions std declares `@intrinsic` that the +#! compiler gives: an operation of their own, or a value worked out while +#! compiling, rather than a call. + +import sakura::analyzer; +module sakura::compiler; + + +#! Lowers a call of an intrinsic. +#! @param this The emitter. +#! @param node The `call` node. +#! @param decl The intrinsic's declaration. +#! @returns What it gives. +pub def emitter::intrinsic(&mut this, node: u32, decl: u32): operand { + val name := this.c.checker.names.text(this.c.checker.decls.names.p[decl]); + val kind := this.c.checker.type_at(node); + val run := this.c.checker.right_of(node); + + # A type's layout is known while compiling. + if name == "size_of" || name == "align_of" { + val instance := this.called(node); + var size: u64 = 0; + if instance != 0 { + val args: u32 = this.c.checker.instances[instance - 1].args; + val held := this.c.shape_of(this.c.checker.types.part_at(args, 0)); + size = name == "size_of" ? held.size : held.align; + } + return operand::one(kind, this.build.word(size)); + } + if name == "os" || name == "arch" || name == "backend" { + val value := name == "os" ? this.c.checker.target.os : name == "arch" ? this.c.checker.target.arch : this.c.checker.target.backend; + return this.text_value(this.c.checker.names.text(value), kind); + } + if name == "call_site" { + return this.call_site(node, kind); + } + if name == "contracts" || name == "checking" { + val off := name == "contracts" ? this.c.checker.contracts_off : this.c.checker.checks_off; + return operand::one(kind, this.build.word(off ? 0 : 1)); + } + # These read the argument as it is written: in a default, the argument the + # call wrote for the parameter it names. + if name == "source_of" || name == "values_of" { + val arg := this.c.checker.run_length(run) != 0 ? this.c.checker.run_at(run, 0) : 0; + val written := arg != 0 ? this.written_argument(arg) : 0; + val saved := this.c.checker.at; + if written != 0 { + this.c.checker.use_table(this.defaulting.table); + } + val chosen := written != 0 ? written : arg; + var made := operand {}; + if name == "source_of" { + var text := string::new(nothing {}); + if chosen != 0 { + this.source_text(chosen, &mut text); + } + this.c.checker.at = saved; + made = this.text_value(text.view(), kind); + } else { + val outer := this.defaulting; + this.defaulting = default_site {}; + made = this.values_of(chosen, kind); + this.defaulting = outer; + this.c.checker.at = saved; + } + return made; + } + if name == "name_of" || name == "path_of" { + # The checker keeps the type named as the callee's. + val named := this.c.checker.type_at(this.c.checker.left_of(node)); + var text := string::new(nothing {}); + if named != 0 && named != bt::error { + text = name == "path_of" ? this.c.checker.describe_path(named) : this.c.checker.describe(named); + } + return this.text_value(text.view(), kind); + } + if name == "value_of" { + if this.c.checker.is_known(node) && this.c.is_scalar_type(kind) { + return this.known(&this.c.checker.value_at(node), kind); + } + val ref := this.c.checker.ref_at(node); + if ref != 0 && (ref & (ref_local | ref_type)) == 0 && this.c.checker.decls.kinds.p[ref] == dk::enum_member { + var value := constant {}; + this.c.checker.decl_value(ref, &mut value); + return this.known(&value, kind); + } + if ref != 0 && (ref & (ref_local | ref_type)) == 0 && this.c.checker.decls.kinds.p[ref] == dk::variable { + val place := this.global_place(ref); + return this.load(&place); + } + if ref != 0 && (ref & (ref_local | ref_type)) == 0 && this.c.checker.decls.kinds.p[ref] == dk::function { + return this.function_value(node, ref); + } + # An attribute is the value it writes, made where it is read. + if ref != 0 && (ref & (ref_local | ref_type)) == 0 && this.c.checker.decls.kinds.p[ref] == dk::attribute { + val saved := this.c.checker.at; + this.c.checker.use_table(this.c.checker.units[this.c.checker.decls.files.p[ref]].table); + val made := this.construct_of(this.c.checker.decls.types.p[ref], this.c.checker.right_of(this.c.checker.decls.nodes.p[ref])); + this.c.checker.at = saved; + return made; + } + this.problem(node, "`value_of` reaches nothing lowering knows."); + return this.zero_value(kind); + } + if name == "attached" { + return this.attached(node, kind); + } + if name == "compile_error" { + this.build.unreachable(); + return operand::none(kind); + } + if name == "lanes_have" || name == "lanes_apply" { + return this.lanes(node, name == "lanes_have", kind); + } + # Vectors are values held in registers between operations in an executable + # optimized with inlining and promotion, and nowhere else. + if name == "lanes_held" { + val native := !this.c.options.evaluating && this.c.checker.names.text(this.c.checker.target.backend) == "native"; + return operand::one(kind, this.build.word(native && this.c.options.level >= 2 ? 1 : 0)); + } + + if name.starts_with("atomic_") { + return this.atomic(node, name, kind); + } + + # `fault` takes its text's two words, wherever the view is. + if name == "fault" { + val text := this.value(this.c.checker.run_at(run, 0)); + var words: u32[2] = [0, 0]; + if text.address != 0 { + words[0] = this.build.load(access::i64, text.address, 0); + words[1] = this.build.load(access::i64, text.address, word_size); + } else { + words[0] = text.words[0]; + words[1] = text.words[1]; + } + this.build.effect(op::fault, words[0:2], 0, 0); + return operand::none(kind); + } + + # The rest are operations, given their arguments' values. + var args := vector::::new(); + for i in 0..this.c.checker.run_length(run) { + val made := this.value(this.c.checker.run_at(run, i as u32)); + made.args(&mut args); + } + # A member of an enum's place among the values of its members, and the member + # at a place, by which a range of its members counts. + if name == "rank_of" || name == "member_at" { + val instance := this.called(node); + val members := instance != 0 ? this.c.checker.types.part_at(this.c.checker.instances[instance - 1].args, 0) : bt::error; + if members == bt::error || this.c.checker.named_kind(this.c.checker.unalias(members)) != dk::enum_type { + this.problem(node, "`rank_of` and `member_at` count the members of an enum."); + return this.zero_value(kind); + } + val made := name == "rank_of" ? this.member_rank(args[0], members) : this.member_of_rank(args[0], members); + return operand::one(kind, made); + } + if name == "raw_allocate" || name == "raw_allocate_zeroed" { + val uncleared: u32 = name == "raw_allocate" ? 1 : 0; + return operand::one(kind, this.build.value(op::allocate, args.view(), vt::word, uncleared, 0)); + } + if name == "raw_release" { + this.build.effect(op::release, args.view(), 0, 0); + return operand::none(kind); + } + # `core::close` closes a value where it is, as its scope ending would: its own + # `close`, then what it holds that closes. + if name == "close_where_it_is" { + val instance := this.called(node); + if instance != 0 && args.length > 0 { + val closed := this.c.checker.types.part_at(this.c.checker.instances[instance - 1].args, 0); + val place := location { kind = closed, address = args[0] }; + this.close(&place); + } + return operand::none(kind); + } + if name == "raw_resize" { + return operand::one(kind, this.build.value(op::resize, args.view(), vt::word, 0, 0)); + } + if name == "syscall" { + return operand::one(kind, this.build.value(op::syscall, args.view(), vt::word, 0, 0)); + } + if name == "frame" || name == "executable" || name == "environ" || name == "take_signals" || name == "current" { + val chosen := name == "frame" ? op::frame : name == "executable" ? op::image : name == "environ" ? op::environ + : name == "current" ? op::current : op::signals; + return operand::one(kind, this.build.value(chosen, span::::empty(), vt::word, 0, 0)); + } + # A thread runs the function value, of two words, given the context, a word; + # the runtime starts one of the system on a record's stacks. + if name == "start" || name == "clone_thread" { + return operand::one(kind, this.build.value(name == "start" ? op::start : op::clone, args.view(), vt::word, 0, 0)); + } + if name == "catch_signal" { + return operand::one(kind, this.build.value(op::catch, args.view(), vt::word, 0, 0)); + } + if name == "exit" { + this.build.effect(op::exit, args.view(), 0, 0); + return operand::none(kind); + } + if name == "abort" { + this.build.effect(op::abort, span::::empty(), 0, 0); + return operand::none(kind); + } + if name == "trap" { + this.build.effect(op::trap, args.view(), 0, 0); + return operand::none(kind); + } + # Operations of the machine on a whole real or word, which `std::math` narrows + # for the other types. + if name == "square_root" { + return operand::one(kind, this.build.unary(op::fsqrt, args[0])); + } + if name == "ones_in" || name == "zeros_leading" || name == "zeros_trailing" || name == "bytes_reversed" { + val chosen := name == "ones_in" ? op::ones : name == "zeros_leading" ? op::clz : name == "zeros_trailing" ? op::ctz : op::bswap; + return operand::one(kind, this.build.unary(chosen, args[0])); + } + this.problem(node, "The intrinsic is not lowered."); + return this.zero_value(kind); +} + +#! `lanes_have` and `lanes_apply`, of an operation on lanes: in an executable, +#! whether the processor it runs on has the vector instructions working it, as +#! it found when it started, and the lanes worked with them. The virtual machine +#! and constants have none, so never reach the second. +#! @param this The emitter. +#! @param node The `call` node. +#! @param have Whether it is `lanes_have`. +#! @param kind What it gives. +#! @returns What it gives. +def emitter::lanes(&mut this, node: u32, have: bool, kind: u32): operand { + # Its type arguments are the type of lane, the operation, and how many lanes. + var lane := lane_none; + var operation: u32 = 0; + var count: u64 = 0; + val instance := this.called(node); + if instance != 0 { + val args: u32 = this.c.checker.instances[instance - 1].args; + lane = this.lane_of(this.c.checker.types.part_at(args, 0)); + operation = this.constant_argument(this.c.checker.types.part_at(args, 1)) as u32; + count = this.constant_argument(this.c.checker.types.part_at(args, 2)); + } + val native := !this.c.options.evaluating && this.c.checker.names.text(this.c.checker.target.backend) == "native"; + val need := native && lane != lane_none ? lanes_needs(operation, lane, count * lane_bits(lane) / 8) : cpu_never; + + if have { + return operand::one(kind, this.build.word(0)) if need == cpu_never; + return operand::one(kind, this.build.word(1)) if need == cpu_sse2; + val found := this.build.value(op::cpu, span::::empty(), vt::word, 0, 0); + val held := this.build.binary(op::band, found, this.build.word(need)); + return operand::one(kind, this.build.binary(op::eq, held, this.build.word(need))); + } + if need == cpu_never { + this.build.unreachable(); + return operand::none(kind); + } + # The pointers: where the result goes, then the operands. + var pointers := vector::::new(); + val run := this.c.checker.right_of(node); + for i in 0..this.c.checker.run_length(run) { + val made := this.value(this.c.checker.run_at(run, i as u32)); + made.args(&mut pointers); + } + + # The operands are read, worked as values, and the result written, so a + # vector a cell holds is a value wherever the cell is promoted. + val bytes := count * lane_bits(lane) / 8; + var args := vector::::new(); + for k in 0..lanes_operands(operation) { + val how := lanes_operand_access(operation, lane, bytes, k); + args.append(this.build.load(how, pointers[1 + k as u64], 0)); + } + val result := lanes_result_access(operation, lane, bytes); + val made := operation == lanes_copy ? args[0] + : this.build.value(op::lanes, args.view(), result.value_type(), operation, lane as u64 | bytes << 8); + this.build.store(result, pointers[0], 0, made); + return operand::none(kind); +} + +#! The atomics of `core::atomic`: an operation on the `T` at an address, in one +#! step, which is the first type argument, and of `atomic_fetch` the operation +#! the second. A compare-exchange gives whether it wrote, and writes what it +#! found where a pointer it is given points. +#! @param this The emitter. +#! @param node The `call` node. +#! @param name The intrinsic's name. +#! @param kind What it gives. +#! @returns What it gives. +def emitter::atomic(&mut this, node: u32, name: strview, kind: u32): operand { + var operation := name == "atomic_load" ? atomic_load : name == "atomic_store" ? atomic_store + : name == "atomic_exchange" ? atomic_exchange : name == "atomic_compare_exchange" ? atomic_compare_exchange + : name == "atomic_fence" ? atomic_fence : atomic_add; + var how := access::i64; + var unsigned: u64 = 0; + val instance := this.called(node); + if instance != 0 && operation != atomic_fence { + val args: u32 = this.c.checker.instances[instance - 1].args; + val held := this.c.checker.types.part_at(args, 0); + how = this.c.shape_of(held).how; + if this.c.checker.types.kind_of(this.c.checker.unalias(held)) == ty::unsigned { + unsigned = atomic_unsigned; + } + if name == "atomic_fetch" { + operation = this.constant_argument(this.c.checker.types.part_at(args, 1)) as u32; + } + } + + var values := vector::::new(); + val run := this.c.checker.right_of(node); + for i in 0..this.c.checker.run_length(run) { + val made := this.value(this.c.checker.run_at(run, i as u32)); + made.args(&mut values); + } + if operation == atomic_fence { + this.build.effect(op::atomic, values.view(), operation, 0); + return operand::none(kind); + } + + # While compiling, what it reaches is checked as a read through a pointer is. + this.reaches(values[0], this.build.word(1), how.width()); + if operation == atomic_compare_exchange { + this.reaches(values[3], this.build.word(1), how.width()); + var args: u32[5] = [values[0], values[1], values[2], values[4], values[5]]; + val found := this.build.value(op::atomic, args[0:5], vt::word, operation, how as u64 | unsigned); + this.build.store(how, values[3], 0, found); + return operand::one(kind, this.build.binary(op::eq, found, values[1])); + } + if atomic_gives(operation) { + return operand::one(kind, this.build.value(op::atomic, values.view(), vt::word, operation, how as u64 | unsigned)); + } + this.build.effect(op::atomic, values.view(), operation, how as u64 | unsigned); + return operand::none(kind); +} + +#! The type of lane a number is, as vector instructions take it. +#! @param this The emitter. +#! @param kind The type. +#! @returns The type of lane, or `lane_none` where it is no number. +def emitter::lane_of(&mut this, kind: u32): u32 { + val plain := this.c.checker.unalias(kind); + val of := this.c.checker.types.kind_of(plain); + val bits := this.c.checker.types.first_of(plain); + if of == ty::floating { + return bits == 32 ? lane_f32 : lane_f64; + } + return lane_none if of != ty::signed && of != ty::unsigned; + val width: u32 = bits == 8 ? 0 : bits == 16 ? 2 : bits == 32 ? 4 : 6; + return width + (of == ty::unsigned ? 1 : 0); +} + +#! The number a constant type argument is. +#! @param this The emitter. +#! @param arg The type argument. +#! @returns The number, or 0 where it is none. +def emitter::constant_argument(&mut this, arg: u32): u64 { + return 0 if this.c.checker.types.kind_of(arg) != ty::value; + return this.c.checker.known_at(this.c.checker.types.second_of(arg)).value.magnitude; +} + +#! Where a call is written, as `core::site`: its file, line, and column, and the +#! signature of the function holding it. +#! @param this The emitter. +#! @param node The `call` node. +#! @param kind The `site` type. +#! @returns The value. +def emitter::call_site(&mut this, node: u32, kind: u32): operand { + # In a default, it is where the call leaving the parameter out is. + val file := this.defaulting.node != 0 ? this.defaulting.file : this.c.checker.at.file; + val site := this.defaulting.node != 0 ? this.defaulting.node : node; + val held := &this.c.checker.units[file].source; + val offset := this.c.node_offset(file, site); + val at := held.lines.place_of(offset); + val plain := this.c.checker.unalias(kind); + val index := this.c.layout_of(plain); + val shape := this.c.layout_at(index); + val address := this.temporary_of(kind); + this.build.clear(address, shape.size); + val whole := location { kind = kind, address = address, framed = true }; + + var signature := string::new(nothing {}); + val decl: u32 = this.c.program.functions[this.function].decl; + if decl != 0 { + this.c.signature_text(decl, &mut signature); + } + for i in 0..shape.count { + val field := this.c.field_at(index, i as u32); + val name := this.c.checker.names.text(field.name); + val place := this.within(&whole, field.offset, field.type_id); + var value := operand {}; + if name == "path" { + value = this.text_value(held.path, field.type_id); + } else if name == "line" { + value = operand::one(field.type_id, this.build.word(at.line as u64)); + } else if name == "column" { + value = operand::one(field.type_id, this.build.word(at.column as u64)); + } else if name == "signature" { + value = this.text_value(signature.view(), field.type_id); + } else { + continue; + } + this.store(&place, &value); + } + return operand::at(kind, address); +} + +#! The text an expression is written as, without the spaces around it. +#! @param this The emitter. +#! @param node The expression. +#! @param out Where the text is written. +pub def emitter::source_text(&mut this, node: u32, out: &mut string): void { + val file := this.c.checker.at.file; + val syntax := &this.c.checker.units[file].syntax; + val held := &this.c.checker.units[file].source; + # A node's own token may come after those of what it was parsed from, as an + # operator's comes after its left operand, so the first is the least of all. + var first: u32 = syntax.node_tokens[node]; + var walk := node_walk::new(node); + while walk.more() { + val at := walk.next(); + val token := syntax.node_tokens[at]; + first = token < first ? token : first; + walk.enter(&syntax, at); + } + val last := syntax.node_end(node); + val begin := syntax.token_offsets[first]; + val end := syntax.token_offsets[last] + syntax.token_length(last, this.c.checker.names); + return if end <= begin; + out.append(held.make_lexeme(begin, end - begin)); +} + +#! What the operands of an expression held, as `values_of` gives it: both +#! operands of a comparison, or the expression itself, each as `text = value`, +#! but for literals, which say what they hold already. +#! @param this The emitter. +#! @param node The expression, or 0. +#! @param kind The `string` type. +#! @returns The text. +def emitter::values_of(&mut this, node: u32, kind: u32): operand { + this.build.effect(op::format, span::::empty(), 0, 0); + if node != 0 { + this.write_values(node, ""); + } + return this.owned_text(kind); +} + +#! Writes what the operands of an expression held into the text being made, as +#! `values_of` gives it, after a lead where there are any. +#! @param this The emitter. +#! @param node The expression. +#! @param lead What comes before the first, as `, with `, or nothing. +pub def emitter::write_values(&mut this, node: u32, lead: strview): void { + var named := vector::::new(); + val shape := this.c.checker.kind_of(node); + if shape == nk::binary { + val operator := this.c.checker.token_kind(node); + if operator.compares() { + named.append(this.c.checker.left_of(node)); + named.append(this.c.checker.right_of(node)); + } + } else if shape != nk::unary { + named.append(node); + } + + var first := true; + for &each in named { + val literal := this.c.checker.kind_of(each); + continue if literal == nk::number || literal == nk::string || literal == nk::character || literal == nk::boolean + || literal == nk::null_lit; + if !first { + this.build.effect(op::format_text, span::::empty(), this.c.text_datum(", "), 0); + } else if lead.length != 0 { + this.build.effect(op::format_text, span::::empty(), this.c.text_datum(lead), 0); + } + first = false; + var text := string::new(nothing {}); + this.source_text(each, &mut text); + this.build.effect(op::format_text, span::::empty(), this.c.text_datum(text.view()), 0); + this.build.effect(op::format_text, span::::empty(), this.c.text_datum(" = "), 0); + val mark := this.cell_mark(); + val value := this.value(each); + this.format_value(&value); + this.release(mark); + } +} + +#! `attached::(d)`: a view of the values of the attributes of the type `A` +#! written on the declaration `d` describes, in the order they are written, each +#! made as the struct literal it is, where the declaration is. They are held as +#! long as the function runs, since the view may outlive the statement. +#! @param this The emitter. +#! @param node The `call` node. +#! @param kind The view's type. +#! @returns The view. +def emitter::attached(&mut this, node: u32, kind: u32): operand { + val view := this.temporary_of(kind); + this.build.clear(view, 2 * word_size); + val run := this.c.checker.right_of(node); + val wanted := this.c.viewed(kind); + return operand::at(kind, view) if wanted == 0 || this.c.checker.run_length(run) == 0; + val one := this.c.checker.reflected_one(this.c.checker.run_at(run, 0)); + return operand::at(kind, view) if one == checker::no_reflection; + val held: desc = this.c.checker.descs[one]; + return operand::at(kind, view) if held.param != 0; + + # The attributes of the type, in the order they are written. + val decl := held.decl; + var types := this.c.checker.attribute_types(decl); + val saved := this.c.checker.at; + this.c.checker.use_table(this.c.checker.units[this.c.checker.decls.files.p[decl]].table); + val attrs := this.c.checker.attributes_of(this.c.checker.decls.nodes.p[decl]); + var chosen := vector::::new(); + var at: u64 = 0; + for i in 0..this.c.checker.run_length(attrs) { + val attr := this.c.checker.run_at(attrs, i as u32); + continue if this.c.checker.kind_of(attr) != nk::attribute; + if at < types.length && this.c.checker.strip(types[at], 0) == this.c.checker.strip(wanted, 0) { + chosen.append(attr); + } + at++; + } + if chosen.length == 0 { + this.c.checker.at = saved; + return operand::at(kind, view); + } + + val shape := this.c.shape_of(wanted); + val array := this.c.checker.types.fixed(wanted, chosen.length as u32); + val whole := this.c.shape_of(array); + val cell := this.build.code.add_cell(round_up(whole.size, word_size) as u32, + whole.align < word_size ? word_size as u32 : whole.align as u32, ck::local, 0); + val first := this.build.cell_address(cell); + for i in 0..chosen.length { + val made := this.construct_of(wanted, this.c.checker.right_of(chosen[i])); + val place := location { kind = wanted, address = first, offset = i * shape.size, framed = true }; + this.store(&place, &made); + } + this.c.checker.at = saved; + this.build.store(access::i64, view, 0, first); + this.build.store(access::i64, view, word_size, this.build.word(chosen.length)); + return operand::at(kind, view); +} diff --git a/compiler/emitter/loops.sakura b/compiler/emitter/loops.sakura new file mode 100644 index 00000000..35410344 --- /dev/null +++ b/compiler/emitter/loops.sakura @@ -0,0 +1,410 @@ +#! @file loops.sakura +#! @author John Christman (sorakatadzuma@gmail.com) +#! @copyright Malunal Studios, LLC. +#! @license MIT +#! +#! Contains the lowering of `for`: counting through a range, walking the +#! elements of a fixed array or a view, each bound by reference, asking an +#! iterator for each element until it gives none, and `for const`, whose body +#! the checker checked once for each value of a pack. + +import sakura::analyzer; +module sakura::compiler; + + +#! Lowers `for`. +#! @param this The emitter. +#! @param node The `for_stmt` node. +pub def emitter::for_statement(&mut this, node: u32): void { + val iterated := this.c.checker.record(node, for_slot::iterated); + val end := this.c.checker.record(node, for_slot::end); + if this.c.checker.node_has(node, nf::constant) { + this.unrolled(node); + return; + } + if end != 0 { + this.for_range(node); + return; + } + + # What's walked is of the type it's converted to, as a literal of text is a + # `strview`. + val through := this.c.checker.unalias(this.c.checker.reached(this.c.checker.converted(iterated))); + if this.c.checker.types.kind_of(through) == ty::fixed || this.c.viewed(through) != 0 { + this.for_elements(node, through); + return; + } + this.for_iterator(node, through); +} + +#! A loop's blocks: where each pass begins, its body, where `continue` goes, and +#! where it ends. +struct loop_blocks { + var head: u32; #! Where each pass asks whether there is another. + var body: u32; #! The body. + var next: u32; #! Where `continue` goes, which steps to the next pass. + var exit: u32; #! Where it ends. +} + +#! Makes the blocks of a loop, and goes to its head. +#! @param this The emitter. +#! @returns The blocks. +def emitter::begin_loop(&mut this): loop_blocks { + val made := loop_blocks { + head = this.build.new_block(), + body = this.build.new_block(), + next = this.build.new_block(), + exit = this.build.new_block() + }; + this.build.jump(made.head); + this.build.switch_to(made.head); + return made; +} + +#! Lowers a loop's body, with `break` and `continue` going where the loop says, +#! then goes to the step to the next pass. +#! @param this The emitter. +#! @param blocks The loop's blocks. +#! @param body The body's node. +#! @param locals How many locals there were before the loop's variables, +#! which each pass closes past. +def emitter::loop_body(&mut this, blocks: &loop_blocks, body: u32, locals: u64): void { + this.safepoint(); + this.loops.append(loop_info { exit = blocks.exit, next = blocks.next, locals = locals, kept = this.kept.length }); + this.lower_block(body); + this.loops.truncate(); + this.close_locals(locals, 0); + this.build.jump(blocks.next); + this.build.seal(blocks.next); + this.build.switch_to(blocks.next); +} + +#! Goes into a loop's body where there is another pass, and leaves it where not. +#! @param this The emitter. +#! @param blocks The loop's blocks. +#! @param more Whether there is another pass. +#! @returns How many locals there were before the pass's own. +def emitter::enter_pass(&mut this, blocks: &loop_blocks, more: u32): u64 { + this.build.branch(more, blocks.body, blocks.exit); + this.build.seal(blocks.body); + this.build.switch_to(blocks.body); + return this.scope_mark(); +} + +#! Lowers the body of a counted pass, then counts it and ends the loop. +#! @param this The emitter. +#! @param blocks The loop's blocks. +#! @param node The `for_stmt` node. +#! @param locals How many locals there were before the pass's own. +#! @param counter The variable counting the passes. +def emitter::end_pass(&mut this, blocks: &loop_blocks, node: u32, locals: u64, counter: u32): void { + this.loop_body(blocks, this.c.checker.right_of(node), locals); + this.forget_locals(locals); + this.count_on(counter, blocks.head, blocks.exit); +} + +#! Ends a loop: the step jumps back to its head, and what follows goes on from +#! its exit. +#! @param this The emitter. +#! @param blocks The loop's blocks. +def emitter::end_loop(&mut this, blocks: &loop_blocks): void { + this.close_loop(blocks.head, blocks.exit); +} + +#! Ends a loop of the blocks given: where the code is jumps back to its head, +#! every way into which is known then, and what follows goes on from its exit. +#! @param this The emitter. +#! @param head The loop's head. +#! @param exit The block after it. +def emitter::close_loop(&mut this, head: u32, exit: u32): void { + this.build.jump(head); + this.build.seal(head); + this.build.seal(exit); + this.build.switch_to(exit); +} + +#! Goes into a loop counting a variable up to a count, as one over the elements +#! of a fixed array does: its head goes into its body while the variable is +#! below the count, and out of the loop otherwise, and what follows is the body. +#! @param this The emitter. +#! @param index The variable, which holds where the count begins. +#! @param count The count, which the variable stays below. +#! @param head The loop's head. +#! @param body Its body. +#! @param exit The block after it. +#! @returns What the variable holds in the body. +def emitter::count_up(&mut this, index: u32, count: u64, head: u32, body: u32, exit: u32): u32 { + this.build.jump(head); + this.build.switch_to(head); + val at := this.build.read(index); + this.build.branch(this.build.binary(op::ltu, at, this.build.word(count)), body, exit); + this.build.seal(body); + this.build.switch_to(body); + return at; +} + +#! Ends the pass of a loop counting a variable up: counts it, and ends the loop. +#! @param this The emitter. +#! @param index The variable. +#! @param head The loop's head. +#! @param exit The block after it. +def emitter::count_on(&mut this, index: u32, head: u32, exit: u32): void { + this.build.assign(index, this.build.binary(op::add, this.build.read(index), this.build.word(1))); + this.close_loop(head, exit); +} + +#! Declares the variable of a loop's pass, and its index, where it has one. +#! @param this The emitter. +#! @param node The `for_stmt` node. +#! @param value The value the variable is given. +#! @param counter The index of the pass, a word. +#! @param closes Whether the variable is the loop's own, closed where each +#! pass ends. +def emitter::bind_pass(&mut this, node: u32, value: &operand, counter: u32, closes: bool): void { + val variable := this.c.checker.record(node, for_slot::variable); + val index := this.c.checker.record(node, for_slot::index); + if variable != 0 { + val kind := this.c.checker.type_at(variable); + val place := this.new_place(variable, kind); + val made := this.convert(value, kind); + this.store(&place, &made); + this.declare(variable, place, closes); + } + if index != 0 { + val place := this.new_place(index, bt::uint64); + val made := operand::one(bt::uint64, counter); + this.store(&place, &made); + this.declare(index, place, false); + } +} + +#! `for i in a..b`: counts from the start to just before the end, or through it +#! where the loop is `a..=b`, each count a variable of the body's own. A range +#! of an enum's members counts their places among the values of its members, +#! each pass's variable the member at its place. +#! @param this The emitter. +#! @param node The `for_stmt` node. +def emitter::for_range(&mut this, node: u32): void { + val mark := this.begin_statement(); + val variable := this.c.checker.record(node, for_slot::variable); + val kind := variable != 0 ? this.c.checker.type_at(variable) : this.c.checker.converted(this.c.checker.record(node, for_slot::iterated)); + val start := this.value_as(this.c.checker.record(node, for_slot::iterated), kind); + val limit := this.value_as(this.c.checker.record(node, for_slot::end), kind); + val members := this.c.checker.named_kind(this.c.checker.unalias(kind)) == dk::enum_type; + val first := members ? this.member_rank(start.words[0], kind) : start.words[0]; + val last := members ? this.member_rank(limit.words[0], kind) : limit.words[0]; + val count := this.build.variable(vt::word); + this.build.assign(count, first); + + # `a..=b` gives `b` too, so whether another pass follows is kept apart from the + # count, which may pass the end of its type after `b`. + val inclusive := this.c.checker.node_has(node, nf::inclusive); + val signed := !members && this.is_signed(kind); + var keep: u32 = 0; + if inclusive { + keep = this.build.variable(vt::word); + this.build.assign(keep, this.build.binary(signed ? op::les : op::leu, first, last)); + } + + val blocks := this.begin_loop(); + val more := inclusive + ? this.build.read(keep) + : this.build.binary(signed ? op::lts : op::ltu, this.build.read(count), last); + val locals := this.enter_pass(&blocks, more); + if variable != 0 { + val place := this.new_place(variable, kind); + val counted := this.build.read(count); + val made := operand::one(kind, members ? this.member_of_rank(counted, kind) : counted); + this.store(&place, &made); + this.declare(variable, place, false); + } + if inclusive { + this.loop_body(&blocks, this.c.checker.right_of(node), locals); + this.forget_locals(locals); + this.build.assign(keep, this.build.binary(op::ne, this.build.read(count), last)); + this.count_on(count, blocks.head, blocks.exit); + } else { + this.end_pass(&blocks, node, locals, count); + } + this.end_statement(mark); +} + +#! Walks the elements of a fixed array or a view, which lie one after another, +#! binding a reference to each. +#! @param this The emitter. +#! @param node The `for_stmt` node. +#! @param through The type walked, read through its references. +def emitter::for_elements(&mut this, node: u32, through: u32): void { + val mark := this.begin_statement(); + val whole := this.object(this.c.checker.record(node, for_slot::iterated)); + var first: u32 = 0; + var limit: u32 = 0; + var element: u32 = 0; + if this.c.checker.types.kind_of(through) == ty::fixed { + val shape := this.c.shape_of(through); + first = this.address_of(&whole); + limit = this.build.word(shape.count as u64); + element = this.c.checker.types.first_of(through); + } else { + first = this.build.load(access::i64, whole.address, whole.offset); + limit = this.build.load(access::i64, whole.address, whole.offset + word_size); + element = this.c.viewed(through); + } + val size := this.c.shape_of(element).size; + val counter := this.build.variable(vt::word); + this.build.assign(counter, this.build.word(0)); + + val blocks := this.begin_loop(); + val locals := this.enter_pass(&blocks, this.build.binary(op::ltu, this.build.read(counter), limit)); + val address := this.build.binary(op::add, first, this.scaled(this.build.read(counter), size)); + val reference := operand::one(this.c.checker.types.reference(element, true), address); + this.bind_pass(node, &reference, this.build.read(counter), false); + this.end_pass(&blocks, node, locals, counter); + this.end_statement(mark); +} + +#! Asks an iterator for each element until it gives `none`. The iterator is the +#! one the loop is given, advanced where it is, or the one what it walks lends +#! through `iter`, which the loop holds and closes where it ends. An element +#! given by value is the loop's own, closed where each pass ends. +#! @param this The emitter. +#! @param node The `for_stmt` node. +#! @param through The type walked, read through its references. +def emitter::for_iterator(&mut this, node: u32, through: u32): void { + val mark := this.begin_statement(); + val iterated := this.c.checker.record(node, for_slot::iterated); + val mutable := this.c.checker.node_has(node, nf::mutable); + val locals := this.scope_mark(); + + # The iterator, where it is: what the loop is given, or what `iter` lends. + var cursor_place := location {}; + var cursor_type := through; + if !this.c.checker.has_method(through, word::next) { + val lends := this.c.checker.pick_iter(through, mutable); + val receiver := this.c.is_reference_type(this.c.checker.type_at(iterated)) + ? this.through_one(iterated) + : this.reference_arg(iterated, this.c.checker.types.reference(through, mutable)); + val made := this.method_call(lends, through, &receiver, span::::empty()); + this.adopt(&made); + cursor_type = this.c.checker.unalias(made.kind); + cursor_place = this.fresh_place(made.kind); + this.store(&cursor_place, &made); + this.declare(this.c.checker.right_of(node), cursor_place, this.c.checker.closes(made.kind)); + } else if this.c.is_reference_type(this.c.checker.type_at(iterated)) { + val made := this.through_one(iterated); + cursor_place = this.referent(&made); + } else if this.c.checker.is_place(iterated) { + cursor_place = this.place_of(iterated); + } else { + val made := this.value_of_type(iterated); + this.adopt(&made); + cursor_place = this.fresh_place(made.kind); + this.store(&cursor_place, &made); + this.declare(this.c.checker.right_of(node), cursor_place, this.c.checker.closes(made.kind)); + } + + val next := this.c.checker.find_member(cursor_type, word::next); + val counter := this.build.variable(vt::word); + this.build.assign(counter, this.build.word(0)); + val blocks := this.begin_loop(); + + # `next` gives `some` of the element while there are more, and `none` after. + val receiver := this.reference_to(&cursor_place, this.c.checker.types.reference(cursor_type, true)); + val given := this.method_call(next.decl, cursor_type, &receiver, span::::empty()); + val maybe := this.hold(&given); + val plain := this.c.checker.unalias(given.kind); + val index := this.c.layout_of(plain); + var some: u32 = 0; + for i in 0..this.c.layout_at(index).count { + if this.c.field_at(index, i as u32).name == word::some { + some = i as u32; + } + } + val passes := this.enter_pass(&blocks, this.tag_is(&maybe, some)); + val field := this.c.field_at(index, some); + val payload := this.within(&maybe, field.offset, field.type_id); + val element := this.load(&payload); + this.bind_pass(node, &element, this.build.read(counter), !this.c.is_reference_type(field.type_id) && this.c.checker.closes(field.type_id)); + this.end_pass(&blocks, node, passes, counter); + + # Leaving the loop, by its end or a `break`, closes the iterator it holds. + this.end_scope(locals, 0); + this.end_statement(mark); +} + +#! The reference a node is, read through the references it refers to until one +#! refers to what is no reference. +#! @param this The emitter. +#! @param node The node, of a reference type. +#! @returns The reference. +def emitter::through_one(&mut this, node: u32): operand { + var made := this.value_of_type(node); + while this.c.is_reference_type(this.c.checker.types.first_of(this.c.checker.unalias(made.kind))) { + val place := this.referent(&made); + made = this.load(&place); + } + return made; +} + +#! `for const`: the body the checker checked once for each value of a pack, or +#! each declaration reflection gives, each with a result table of its own, run +#! one after another. `continue` goes on to the next, and `break` past the last. +#! @param this The emitter. +#! @param node The `for_stmt` node. +def emitter::unrolled(&mut this, node: u32): void { + val variable := this.c.checker.record(node, for_slot::variable); + val iterated := this.c.checker.record(node, for_slot::iterated); + val body := this.c.checker.right_of(node); + val outer := this.c.checker.at.table; + val pack := this.c.checker.unalias(this.c.checker.reached(this.c.checker.type_at(iterated))); + val is_pack := this.c.checker.types.kind_of(pack) == ty::pack; + + # The tables the checker made for each pass, in order. + var tables := vector::::new(); + for t in 0..this.c.checker.tables.length { + val held: rtable = this.c.checker.tables.p[t]; + if held.parent == outer + 1 && held.base == variable && held.count == body - variable + 1 { + tables.append(t as u32); + } + } + + # The pack is named in the table around the passes, which theirs do not hold. + var values := vector::::new(); + if is_pack { + for i in 0..this.c.checker.types.part_count(pack) { + values.append(this.pack_place(iterated, i as u32)); + } + } + + val exit := this.build.new_block(); + for i in 0..tables.length { + val next := this.build.new_block(); + this.c.checker.use_table(tables[i]); + val locals := this.scope_mark(); + if is_pack { + # The variable is the pack's value itself, so writing it writes the pack. + val place: location = i < values.length ? values[i] : location { kind = bt::error }; + this.declare(variable, place, false); + } else if this.c.checker.record(node, for_slot::end) != 0 { + # The variable is the number this pass counts. + val kind := this.c.checker.type_at(variable); + val made := this.known(&this.c.checker.value_at(variable), kind); + val place := this.new_place(variable, kind); + this.store(&place, &made); + this.declare(variable, place, false); + } else { + this.reflected_pass(variable); + } + this.loops.append(loop_info { exit = exit, next = next, locals = locals, kept = this.kept.length }); + this.lower_block(body); + this.loops.truncate(); + this.end_scope(locals, 0); + this.build.jump(next); + this.build.seal(next); + this.build.switch_to(next); + this.c.checker.use_table(outer); + } + this.build.jump(exit); + this.build.seal(exit); + this.build.switch_to(exit); +} diff --git a/compiler/emitter/match.sakura b/compiler/emitter/match.sakura new file mode 100644 index 00000000..e16021db --- /dev/null +++ b/compiler/emitter/match.sakura @@ -0,0 +1,238 @@ +#! @file match.sakura +#! @author John Christman (sorakatadzuma@gmail.com) +#! @copyright Malunal Studios, LLC. +#! @license MIT +#! +#! Contains the lowering of `match`: the first arm naming the field a union +#! holds, or the member an enum is, or a value equal to the subject, runs, or +#! else the `else` arm. A union's arm may name the value its field holds, a +#! copy of it, taken out where it closes, or with `&` or `&mut` a reference to +#! it. A match used as a value gives what its arm gives. + +import sakura::analyzer; +module sakura::compiler; + + +#! A `match` used as a value. +#! @param this The emitter. +#! @param node The `match_value` node. +#! @returns What the arm taken gives. +pub def emitter::match_value(&mut this, node: u32): operand { + return this.lower_match(node, true); +} + +#! Lowers a match, as a statement or as a value. +#! @param this The emitter. +#! @param node The `match_stmt` or `match_value` node. +#! @param value Whether it is used as a value. +#! @returns What the arm taken gives, where it is used as a value. +pub def emitter::lower_match(&mut this, node: u32, value: bool): operand { + val subject := this.c.checker.left_of(node); + val arms := this.c.checker.right_of(node); + val kind := value ? this.c.checker.type_at(node) : bt::void_type; + val whole := this.object(subject); + val plain := this.c.checker.unalias(whole.kind); + val union_like := this.c.checker.named_kind(plain) == dk::union_type; + + # Values are compared with the subject as read once, before any arm runs. + var held := operand {}; + if !union_like { + held = this.load(&whole); + } + + val result := value ? this.result_place(kind) : location {}; + val join := this.build.new_block(); + var otherwise := false; + for i in 0..this.c.checker.run_length(arms) { + val arm := this.c.checker.run_at(arms, i as u32); + val patterns := this.c.checker.left_of(arm); + val body := this.c.checker.right_of(arm); + if patterns == 0 { + this.lower_arm(arm, body, value, kind, &result, &whole, 0, 0); + this.build.jump(join); + otherwise = true; + break; + } + + # The arm runs where any of its patterns does. + val taken := this.build.new_block(); + val next := this.build.new_block(); + var field: u32 = 0; + var binding: u32 = 0; + for j in 0..this.c.checker.run_length(patterns) { + val pattern := this.c.checker.run_at(patterns, j as u32); + val failed := j + 1 == this.c.checker.run_length(patterns) as u64 ? next : this.build.new_block(); + var test: u32 = 0; + if union_like { + field = this.c.checker.ref_at(pattern); + if this.c.checker.kind_of(pattern) == nk::call { + val given := this.c.checker.right_of(pattern); + if this.c.checker.run_length(given) == 1 { + binding = this.c.checker.named_binding(this.c.checker.run_at(given, 0)); + } + } + test = this.tag_is(&whole, this.field_index(plain, field)); + } else { + test = this.equals_value(&held, pattern, plain); + } + this.build.branch(test, taken, failed); + if failed != next { + this.build.seal(failed); + this.build.switch_to(failed); + } + } + this.build.seal(taken); + this.build.seal(next); + + this.build.switch_to(taken); + this.lower_arm(arm, body, value, kind, &result, &whole, field, binding); + this.build.jump(join); + this.build.switch_to(next); + } + + # A match used as a value with no `else` finds no arm only for a value no enum + # member has, which only memory written through pointers can hold, and which + # only code that checks looks for. + if !otherwise { + if value && this.checking() { + this.build.trap(fault::not_member as u32); + } else if value { + this.build.unreachable(); + } else { + this.build.jump(join); + } + } + this.build.seal(join); + this.build.switch_to(join); + return operand::none(bt::void_type) if !value; + val made := this.load_result(&result); + this.keep(&made); + return made; +} + +#! The index of a union's field among its fields. +#! @param this The emitter. +#! @param kind The union's type, without aliases. +#! @param field The field's declaration. +#! @returns Its index. +pub def emitter::field_index(&mut this, kind: u32, field: u32): u32 { + val index := this.c.layout_of(kind); + for i in 0..this.c.layout_at(index).count { + return i as u32 if this.c.field_at(index, i as u32).decl == field; + } + return 0; +} + +#! Whether a value equals a pattern's: as words, or through `equals`, or part by +#! part for what the language compares that way. +#! @param this The emitter. +#! @param held The value. +#! @param pattern The pattern's node. +#! @param kind The type compared, without aliases. +#! @returns A word of 1 where they are equal. +def emitter::equals_value(&mut this, held: &operand, pattern: u32, kind: u32): u32 { + val given := this.value_as(pattern, kind); + val shape := this.c.shape_of(kind); + if !in_memory(&shape) { + if this.c.checker.has_method(kind, word::equals) && this.c.checker.named_kind(kind) != dk::enum_type + && !this.c.checker.types.is_numeric(kind) && this.c.checker.types.kind_of(kind) != ty::pointer + && !this.c.checker.types.is_boolean(kind) { + return this.equals_call(held, &given, kind); + } + val floating := shape.kind == lk::floating; + return this.build.binary(floating ? op::feq : op::eq, held.words[0], given.words[0]); + } + if this.c.checker.has_method(kind, word::equals) { + return this.equals_call(held, &given, kind); + } + var args: u32[2] = [held.address, given.address]; + return this.build.value(op::equal, args[0:2], vt::word, this.c.layout_of(kind), 0); +} + +#! Calls a type's `equals` on two values, given references to each. +#! @param this The emitter. +#! @param a One value. +#! @param b The other. +#! @param kind Their type, without aliases. +#! @returns A word of 1 where they are equal. +def emitter::equals_call(&mut this, a: &operand, b: &operand, kind: u32): u32 { + val method := this.pick_method(kind, word::equals, true); + val reference := this.c.checker.types.reference(kind, false); + val left := this.hold(a); + val right := this.hold(b); + val subject := this.reference_to(&left, reference); + var others: operand[1] = [this.reference_to(&right, reference)]; + val made := this.method_call(method, kind, &subject, others[0:1]); + return made.words[0]; +} + +#! Lowers an arm: the value its pattern names, where it names one, and its body, +#! whose value the match gives where it is used as one. +#! @param this The emitter. +#! @param arm The arm's node. +#! @param body Its body's node. +#! @param value Whether the match is used as a value. +#! @param kind The match's type. +#! @param result Where its value goes. +#! @param whole The place of the subject. +#! @param field The field the arm names of a union, or 0. +#! @param binding The node naming the field's value, or 0. +def emitter::lower_arm( + &mut this, + arm: u32, + body: u32, + value: bool, + kind: u32, + result: &location, + whole: &location, + field: u32, + binding: u32 +): void { + val locals := this.scope_mark(); + var named: u32 = 0; + if binding != 0 && field != 0 { + val refers := this.c.checker.kind_of(binding) == nk::reference; + named = refers ? this.c.checker.left_of(binding) : binding; + val plain := this.c.checker.unalias(whole.kind); + val held := this.c.field_at(this.c.layout_of(plain), this.field_index(plain, field)); + val payload := this.within(whole, held.offset, held.type_id); + val bound := this.c.checker.type_at(named); + val place := this.new_place(named, bound); + if refers { + # A field holding a reference gives that reference, since references + # never stack. + var made := operand {}; + if this.c.checker.has_flag(binding, rf::relent) { + val inner := this.load(&payload); + made = this.convert(&inner, bound); + } else { + made = this.reference_to(&payload, bound); + } + this.store(&place, &made); + this.declare(named, place, false); + } else { + val made := this.load(&payload); + val converted := this.convert(&made, bound); + this.store(&place, &converted); + val closes := this.c.checker.closes(held.type_id); + if closes { + this.zero(&payload); + } + this.declare(named, place, closes); + } + } + + # An arm giving the value its name took hands it over to the match. + var given: u32 = 0; + if value { + if this.c.checker.kind_of(body) == nk::name && named != 0 && (this.c.checker.ref_at(body) & ref_mask) == named { + given = named; + } + val made := this.value_as(body, kind); + this.adopt(&made); + this.store(result, &made); + } else { + this.lower_block(body); + } + this.end_scope(locals, given); +} diff --git a/compiler/emitter/operators.sakura b/compiler/emitter/operators.sakura new file mode 100644 index 00000000..814b18b8 --- /dev/null +++ b/compiler/emitter/operators.sakura @@ -0,0 +1,1163 @@ +#! @file operators.sakura +#! @author John Christman (sorakatadzuma@gmail.com) +#! @copyright Malunal Studios, LLC. +#! @license MIT +#! +#! Contains the lowering of operators: prefix and postfix operators, taking a +#! reference, the binary operators, assignment, ternaries, `else`, casts with +#! `as`, and tests with `is`. Arithmetic on words wraps at 64 bits, so a result +#! narrower than a word is narrowed again to its type, as the machine keeps it. + +import sakura::analyzer; +module sakura::compiler; + + +#! Narrows the result of arithmetic to its type: an integer to its bits, and a +#! real to the precision of an `f32`. +#! @param this The emitter. +#! @param value The result. +#! @param kind Its type. +#! @returns The result narrowed. +pub def emitter::normalize(&mut this, value: u32, kind: u32): u32 { + val held := this.c.shape_of(kind); + if held.kind == lk::floating && held.bits <= 32 { + return this.build.unary(op::fsingle, value); + } + if (held.kind == lk::signed || held.kind == lk::unsigned) && held.bits < 64 { + return this.build.wrap(value, held.bits, held.kind == lk::signed); + } + return value; +} + +#! Whether a type is a signed integer, read as the machine reads it. +#! @param this The emitter. +#! @param kind The type. +#! @returns Whether it is. +pub def emitter::is_signed(&mut this, kind: u32): bool { + val held := this.c.shape_of(kind); + return held.kind == lk::signed; +} + +#! Whether a type is a float. +#! @param this The emitter. +#! @param kind The type. +#! @returns Whether it is. +pub def emitter::is_float(&mut this, kind: u32): bool { + val held := this.c.shape_of(kind); + return held.kind == lk::floating; +} + +#! A prefix operator: `-x`, `!x`, `~x`, `++x`, `--x`, or `*p`. +#! @param this The emitter. +#! @param node The operator's node. +#! @returns Its value. +pub def emitter::unary(&mut this, node: u32): operand { + val operand_node := this.c.checker.left_of(node); + val kind := this.c.checker.type_at(node); + match this.c.checker.token_kind(node) { + tk::minus => { + val method := this.operator_decl(node); + if method != 0 { + return this.method_operator(node, method, operand_node, 0); + } + val value := this.value_as(operand_node, kind); + val made := this.is_float(kind) ? this.build.unary(op::fneg, value.words[0]) : this.build.unary(op::neg, value.words[0]); + return operand::one(kind, this.normalize(made, kind)); + } + tk::negate => { + val value := this.value_as(operand_node, kind); + return operand::one(kind, this.build.unary(op::lnot, value.words[0])); + } + tk::bitnot => { + val method := this.operator_decl(node); + if method != 0 { + return this.method_operator(node, method, operand_node, 0); + } + val value := this.value_as(operand_node, kind); + return operand::one(kind, this.normalize(this.build.unary(op::bnot, value.words[0]), kind)); + } + tk::increment, tk::decrement => return this.step(node, operand_node, true); + tk::star => { + val place := this.place_of(node); + return this.load(&place); + } + else => {} + } + this.problem(node, "The operator is not lowered."); + return this.zero_value(kind); +} + +#! The method an arithmetic operator calls, as `+` calls `add`, which the +#! checker chose by its operands, or 0 where the language operates on them +#! itself, as it does on numbers. +#! @param this The emitter. +#! @param node The operator's node: a `binary`, a prefix `-`, or a compound +#! assignment. +#! @returns The method's declaration, or 0. +pub def emitter::operator_decl(&mut this, node: u32): u32 { + val ref := this.c.checker.ref_at(node); + return 0 if ref == 0 || (ref & (ref_local | ref_type)) != 0 || this.c.checker.decls.kinds.p[ref] != dk::function; + return ref; +} + +#! Calls the method an arithmetic operator is, given the operand it is called +#! on as its `this` and the other as its argument, each as a call gives them: +#! referred to where the method takes a reference, and converted to what it +#! takes otherwise. What it gives is the statement's, as what a call gives is. +#! @param this The emitter. +#! @param node The operator's node, which the checker recorded the call at. +#! @param decl The method's declaration. +#! @param left The node of the operand it is called on. +#! @param right The node of the other operand, or 0. +#! @returns What the method gives. +pub def emitter::method_operator(&mut this, node: u32, decl: u32, left: u32, right: u32): operand { + val instance := this.called(node); + val holder := this.c.trait_of_method(decl); + var kind := this.c.type_of_function(decl, instance); + if holder != 0 && instance == 0 { + kind = this.c.checker.trait_method_type(decl, this.c.checker.reached(this.c.checker.type_at(left))); + } + + var given := gathered { values = vector::::new() }; + given.values.append(this.receiver(left, this.c.checker.types.part_at(kind, 0), decl)); + if right != 0 && this.c.checker.types.part_count(kind) > 1 { + given.values.append(this.argument(right, this.c.checker.types.part_at(kind, 1))); + } + val made := this.call_gathered(decl, instance, holder, kind, left, &given); + this.keep(&made); + return made; +} + +#! Whether the method a compound assignment calls changes its target in place, +#! as `add_assign` does, giving nothing, rather than giving what is written over +#! it, as `add` does. +#! @param this The emitter. +#! @param decl The method's declaration. +#! @returns Whether it does. +def emitter::in_place(&mut this, decl: u32): bool { + val kind := this.c.checker.decls.types.p[decl]; + return this.c.checker.types.kind_of(kind) == ty::function + && this.c.checker.unalias(this.c.checker.types.first_of(kind)) == bt::void_type; +} + +#! Calls the method a compound assignment's operator is, as `+=` calls `add`, +#! on what its target holds, given the value as its argument. What it gives is +#! the caller's to store. +#! @param this The emitter. +#! @param node The `assign` node, which the checker recorded the call at. +#! @param decl The method's declaration. +#! @param place Where what the target holds is. +#! @param value The node of the value. +#! @returns What the method gives. +def emitter::method_applied(&mut this, node: u32, decl: u32, place: &location, value: u32): operand { + val instance := this.called(node); + val holder := this.c.trait_of_method(decl); + val target := this.c.checker.left_of(node); + var kind := this.c.type_of_function(decl, instance); + if holder != 0 { + kind = this.c.checker.trait_method_type(decl, this.c.checker.reached(this.c.checker.type_at(target))); + } + + var given := gathered { values = vector::::new() }; + val subject := this.reference_to(place, this.c.checker.types.reference(place.kind, this.c.checker.decls.has(decl, df::mut_this))); + given.values.append(this.convert(&subject, this.c.checker.types.part_at(kind, 0))); + if this.c.checker.types.part_count(kind) > 1 { + given.values.append(this.argument(value, this.c.checker.types.part_at(kind, 1))); + } + return this.call_gathered(decl, instance, holder, kind, target, &given); +} + +#! Calls the method of a comparison, as `==` calls `equals`, given references to +#! its operands. +#! @param this The emitter. +#! @param node The operator's node. +#! @param kind The type of the operand the method is called on. +#! @param word The ID of the method's name. +#! @param left The node of that operand. +#! @param right The node of the other operand, or 0. +#! @returns What the method gives. +pub def emitter::operator_call(&mut this, node: u32, kind: u32, word: u32, left: u32, right: u32): operand { + val plain := this.c.checker.unalias(this.c.checker.read_type(kind)); + val method := this.pick_method(plain, word, right != 0); + if method == 0 { + this.problem(node, "The operator's method is not found."); + return this.zero_value(kind); + } + val target := this.c.method_target(method, plain); + var others := vector::::new(); + if right != 0 && this.c.checker.types.part_count(target.kind) > 1 { + val param := this.c.checker.types.part_at(target.kind, 1); + if this.c.is_reference_type(this.c.checker.type_at(right)) { + val given := this.value_of_type(right); + others.append(this.convert(&given, param)); + } else { + others.append(this.lent_arg(right, param)); + } + } + val subject := this.c.is_reference_type(this.c.checker.type_at(left)) + ? this.value_of_type(left) + : this.lent_arg(left, this.c.checker.types.reference(plain, false)); + val made := this.method_call(method, plain, &subject, others.view()); + this.keep(&made); + return made; +} + +#! The method of a name a type has, of the overloads the one taking `this` and, +#! where `binary` says, another reference to the type. +#! @param this The emitter. +#! @param kind The type. +#! @param word The ID of the method's name. +#! @param binary Whether it takes another operand. +#! @returns The method's declaration, or 0. +pub def emitter::pick_method(&mut this, kind: u32, word: u32, binary: bool): u32 { + val found := this.c.checker.find_member(kind, word); + return 0 if found.decl == 0; + var first: u32 = 0; + var walk := this.c.checker.decls.walk_overloads(found.decl); + while true { + val at := walk.next(); + break if at == 0; + this.c.checker.resolve(at); + if this.c.checker.decls.kinds.p[at] == dk::function && this.c.checker.decls.has(at, df::method) { + val held := this.c.checker.method_type(at, kind); + val count := this.c.checker.types.part_count(held); + if (binary && count == 2) || (!binary && count == 1) { + if first == 0 { + first = at; + } + if !binary { + return at; + } + val other := this.c.checker.types.part_at(held, 1); + if this.c.is_reference_type(other) + && this.c.checker.strip(this.c.checker.types.first_of(this.c.checker.unalias(other)), 0) == this.c.checker.strip(kind, 0) { + return at; + } + } + } + } + return first; +} + +#! `x++`, `x--`, `++x`, or `--x`, which change a number or pointer in place, or a +#! property through its accessors. +#! @param this The emitter. +#! @param node The operator's node. +#! @param target The node of what it changes. +#! @param prefix Whether it gives the value after the change rather than before. +#! @returns The value it gives. +pub def emitter::step(&mut this, node: u32, target: u32, prefix: bool): operand { + val kind := this.c.checker.type_at(node); + val increments := this.c.checker.token_kind(node) == tk::increment; + + # A property is read by its `get` and written by its `set`, on one receiver. + val property := this.property_of(target); + if property != 0 { + val object := this.c.checker.left_of(target); + val receiver := this.receiver_of(object, true); + val before := this.property_get(property, &receiver, target); + val after := this.stepped(&before, kind, increments); + this.property_set(property, &receiver, &after, target); + return prefix ? after : before; + } + + val place := this.writable_place(target); + val before := this.load(&place); + val after := this.stepped(&before, place.kind, increments); + this.store(&place, &after); + var made := prefix ? after : before; + made.kind = kind; + return made; +} + +#! A number or pointer one more or one less. +#! @param this The emitter. +#! @param value The number or pointer. +#! @param kind Its type. +#! @param increments Whether it is one more. +#! @returns The value. +def emitter::stepped(&mut this, value: &operand, kind: u32, increments: bool): operand { + val plain := this.c.layout_type(kind); + if this.c.checker.types.kind_of(plain) == ty::pointer { + val element := this.c.shape_of(this.c.checker.types.first_of(plain)); + val made := this.build.binary(increments ? op::add : op::sub, value.words[0], this.build.word(element.size)); + return operand::one(kind, made); + } + if this.is_float(kind) { + val one := this.build.real(bits_of_real(1.0)); + val made := this.build.binary(increments ? op::fadd : op::fsub, value.words[0], one); + return operand::one(kind, this.normalize(made, kind)); + } + val made := this.build.binary(increments ? op::add : op::sub, value.words[0], this.build.word(1)); + return operand::one(kind, this.normalize(made, kind)); +} + +#! The place an assignment or step writes: a place, read through references +#! where the node is a reference whose referent is written. +#! @param this The emitter. +#! @param node The node written. +#! @returns The place. +def emitter::writable_place(&mut this, node: u32): location { + return this.c.is_reference_type(this.c.checker.type_at(node)) ? this.object(node) : this.place_of(node); +} + +#! Whether a place whose value is known while compiling is still in memory: an +#! element or field of a variable or constant whose whole value is not known, as +#! one of a constant's array, which the program holds as data. A reference to it +#! is to the place, as one to the whole is. +#! @param this The emitter. +#! @param node The place's node. +#! @returns Whether it is. +def emitter::stored(&mut this, node: u32): bool { + var at := node; + while this.c.checker.kind_of(at) == nk::index || this.c.checker.kind_of(at) == nk::member { + at = this.c.checker.left_of(at); + } + val named := this.c.checker.kind_of(at) == nk::name || this.c.checker.kind_of(at) == nk::path; + return named && at != node && !this.c.checker.is_known(at); +} + +#! `&x` or `&mut x`: a reference to a place, or to a value that is no place, +#! held where the statement holds it, which closes it where the statement ends. +#! One bound to a name lives as long as the name, as `local_statement` holds +#! it. +#! @param this The emitter. +#! @param node The `reference` node. +#! @returns The reference. +pub def emitter::reference(&mut this, node: u32): operand { + val inner := this.c.checker.left_of(node); + val kind := this.c.checker.type_at(node); + + # A reference, as a variable or a call gives one, is lent as it is, since + # references never stack. + if this.c.checker.has_flag(node, rf::relent) { + val same := this.value(inner); + return this.convert(&same, kind); + } + if this.c.checker.is_place(inner) && (!this.c.checker.is_known(inner) || this.stored(inner)) { + val place := this.place_of(inner); + return this.reference_to(&place, kind); + } + + val referent := this.c.checker.types.first_of(this.c.checker.unalias(kind)); + + val value := this.value_as(inner, referent); + val place := this.hold(&value); + return this.reference_to(&place, kind); +} + +#! A binary operator. +#! @param this The emitter. +#! @param node The operator's node. +#! @returns Its value. +pub def emitter::binary(&mut this, node: u32): operand { + val operator := this.c.checker.token_kind(node); + val left := this.c.checker.left_of(node); + val right := this.c.checker.right_of(node); + val kind := this.c.checker.type_at(node); + + if operator == tk::logand || operator == tk::logor { + return this.logical(node); + } + + if operator.compares() { + return this.comparison(node); + } + + # Pointers move by elements, and two count the elements between them. + val left_type := this.c.layout_type(this.c.checker.read_type(this.c.checker.type_at(left))); + if (operator == tk::plus || operator == tk::minus) && this.c.checker.types.kind_of(left_type) == ty::pointer { + val a := this.value_of_type(left); + val pointer := this.through_references(&a); + val element := this.c.shape_of(this.c.checker.types.first_of(left_type)); + val right_type := this.c.layout_type(this.c.checker.read_type(this.c.checker.type_at(right))); + if this.c.checker.types.kind_of(right_type) == ty::pointer { + val b := this.value_of_type(right); + val other := this.through_references(&b); + if this.c.options.evaluating { + this.same_memory(pointer.words[0], other.words[0]); + } + var bytes := this.build.binary(op::sub, pointer.words[0], other.words[0]); + if element.size > 1 { + bytes = this.build.binary(op::divs, bytes, this.build.word(element.size)); + } + return operand::one(kind, bytes); + } + val count := this.value_as(right, bt::int64); + val step := this.scaled(count.words[0], element.size); + return operand::one(kind, this.build.binary(operator == tk::plus ? op::add : op::sub, pointer.words[0], step)); + } + + # Arithmetic on what is no number calls the method the checker chose. + val method := this.operator_decl(node); + if method != 0 { + return this.method_operator(node, method, left, right); + } + + # A shift's amount is of its own type, read through a reference. + val a := this.value_as(left, kind); + val b := operator == tk::lshift || operator == tk::rshift ? this.value_as(right, this.read_kind(right)) : this.value_as(right, kind); + return this.arithmetic(operator, a.words[0], b.words[0], kind); +} + +#! The type of a node's value, read through the references it is. +#! @param this The emitter. +#! @param node The node. +#! @returns The type. +def emitter::read_kind(&mut this, node: u32): u32 { + return this.c.checker.read_type(this.c.checker.type_at(node)); +} + +#! Arithmetic the language does itself, on numbers or bits. +#! @param this The emitter. +#! @param operator The operator, as `+`. +#! @param a The left operand's word. +#! @param b The right operand's word. +#! @param kind The type of the result. +#! @returns Its value. +def emitter::arithmetic(&mut this, operator: tk, a: u32, b: u32, kind: u32): operand { + val floating := this.is_float(kind); + val signed := this.is_signed(kind); + val made := match operator { + tk::plus => floating ? op::fadd : op::add, + tk::minus => floating ? op::fsub : op::sub, + tk::star => floating ? op::fmul : op::mul, + tk::slash => floating ? op::fdiv : (signed ? op::divs : op::divu), + tk::modulo => floating ? op::frem : (signed ? op::rems : op::remu), + tk::bitand => op::band, + tk::bitor => op::bor, + tk::bitxor => op::bxor, + tk::lshift => op::shl, + tk::rshift => signed ? op::shrs : op::shru, + else => op::add + }; + return operand::one(kind, this.normalize(this.build.binary(made, a, b), kind)); +} + +#! `&&` or `||` as a value: the right is only evaluated where the left does not +#! decide. +#! @param this The emitter. +#! @param node The operator's node. +#! @returns Its value. +def emitter::logical(&mut this, node: u32): operand { + val locals := this.scope_mark(); + this.declare_tests(node); + val result := this.build.variable(vt::word); + val yes := this.build.new_block(); + val no := this.build.new_block(); + val join := this.build.new_block(); + this.branch_on(node, yes, no); + this.build.seal(yes); + this.build.seal(no); + this.build.switch_to(yes); + this.build.assign(result, this.build.word(1)); + this.build.jump(join); + this.build.switch_to(no); + this.build.assign(result, this.build.word(0)); + this.build.jump(join); + this.build.seal(join); + this.build.switch_to(join); + val made := operand::one(this.c.checker.type_at(node), this.build.read(result)); + this.end_scope(locals, 0); + return made; +} + +#! A comparison: of numbers, enums, `bool`, and pointers as words, of integers +#! of different signs exactly, of floats as floats, of what says how it compares +#! through its `equals` or `compare`, and of fixed arrays, structs, and unions +#! the language compares part by part. +#! @param this The emitter. +#! @param node The comparison's node. +#! @returns Its value, a `bool`. +def emitter::comparison(&mut this, node: u32): operand { + val operator := this.c.checker.token_kind(node); + val left := this.c.checker.left_of(node); + val right := this.c.checker.right_of(node); + val kind := this.c.checker.type_at(node); + val shared := this.c.checker.converted(left); + val plain := this.c.layout_type(this.c.checker.read_type(shared)); + val equal := operator == tk::equals || operator == tk::noteq; + val swap := operator == tk::more || operator == tk::moreeq; + + # Integers of different signs compare as the numbers they are. + val ra := this.c.checker.unalias(this.c.checker.read_type(this.c.checker.type_at(left))); + val rb := this.c.checker.unalias(this.c.checker.read_type(this.c.checker.type_at(right))); + if this.c.checker.types.is_integer(ra) && this.c.checker.types.is_integer(rb) + && !this.c.checker.types.is_untyped(ra) && !this.c.checker.types.is_untyped(rb) + && this.c.checker.types.is_signed(ra) != this.c.checker.types.is_signed(rb) { + return this.mixed(node, ra); + } + + # What says how it compares is compared by its method. + # A fixed array compares element by element, which the runtime does by its + # layout, as the machine does. + val named := this.c.checker.named_kind(plain); + if named == dk::struct_type || named == dk::union_type { + if !equal || this.c.checker.has_method(plain, word::equals) { + return this.method_comparison(node, plain); + } + } + if this.c.checker.types.kind_of(plain) == ty::fixed { + val a := this.value_as(left, plain); + val b := this.value_as(right, plain); + var args: u32[2] = [a.address, b.address]; + var made := this.build.value(op::equal, args[0:2], vt::word, this.c.layout_of(plain), 0); + if operator == tk::noteq { + made = this.build.unary(op::lnot, made); + } + return operand::one(kind, made); + } + + val a := this.value_as(left, plain); + val b := this.value_as(right, plain); + val x := swap ? b.words[0] : a.words[0]; + val y := swap ? a.words[0] : b.words[0]; + # While compiling, pointers are ordered only within one memory, since where + # different memory is changes from one build to the next. + if !equal && this.c.options.evaluating && this.c.checker.types.kind_of(plain) == ty::pointer { + this.same_memory(x, y); + } + val floating := this.is_float(plain); + val signed := this.is_signed(plain); + val compared := match operator { + tk::equals => floating ? op::feq : op::eq, + tk::noteq => floating ? op::fne : op::ne, + tk::less, tk::more => floating ? op::flt : (signed ? op::lts : op::ltu), + else => floating ? op::fle : (signed ? op::les : op::leu) + }; + return operand::one(kind, this.build.binary(compared, x, y)); +} + +#! A comparison through `equals` or `compare`, given references to both sides: +#! `!=` turns `equals` around, and `<` and the others test the sign of what +#! `compare` gives. +#! @param this The emitter. +#! @param node The comparison's node. +#! @param kind The type compared. +#! @returns Its value. +def emitter::method_comparison(&mut this, node: u32, kind: u32): operand { + val operator := this.c.checker.token_kind(node); + val equal := operator == tk::equals || operator == tk::noteq; + val word := equal ? word::equals : word::compare; + val left := this.c.checker.left_of(node); + val right := this.c.checker.right_of(node); + val result := this.operator_call(node, kind, word, left, right); + val bool_type := this.c.checker.type_at(node); + if equal { + return operand::one(bool_type, operator == tk::noteq ? this.build.unary(op::lnot, result.words[0]) : result.words[0]); + } + + val zero := this.build.word(0); + val made := match operator { + tk::less => this.build.binary(op::lts, result.words[0], zero), + tk::lesseq => this.build.binary(op::les, result.words[0], zero), + tk::more => this.build.binary(op::lts, zero, result.words[0]), + else => this.build.binary(op::les, zero, result.words[0]) + }; + return operand::one(bool_type, made); +} + +#! Compares a signed and an unsigned integer exactly, as the numbers they are. +#! @param this The emitter. +#! @param node The comparison's node. +#! @param ra The left operand's type, read through. +#! @returns Its value. +def emitter::mixed(&mut this, node: u32, ra: u32): operand { + val operator := this.c.checker.token_kind(node); + val a := this.value(this.c.checker.left_of(node)); + val b := this.value(this.c.checker.right_of(node)); + var x := this.through_references(&a).words[0]; + var y := this.through_references(&b).words[0]; + var signed_left := this.c.checker.types.is_signed(ra); + + # `a > b` is `b < a`, and `a >= b` is `b <= a`. + if operator == tk::more || operator == tk::moreeq { + val held := x; + x = y; + y = held; + signed_left = !signed_left; + } + + var made: u32 = 0; + if operator == tk::equals || operator == tk::noteq { + made = signed_left ? this.build.binary(op::eqsu, x, y) : this.build.binary(op::eqsu, y, x); + if operator == tk::noteq { + made = this.build.unary(op::lnot, made); + } + } else if operator == tk::less || operator == tk::more { + made = this.build.binary(signed_left ? op::ltsu : op::ltus, x, y); + } else { + made = this.build.binary(signed_left ? op::lesu : op::leus, x, y); + } + return operand::one(this.c.checker.type_at(node), made); +} + +#! An assignment, `=` or a compound one as `+=`, which gives the value assigned. +#! @param this The emitter. +#! @param node The `assign` node. +#! @returns The value assigned. +pub def emitter::assign(&mut this, node: u32): operand { + val operator := this.c.checker.token_kind(node); + val target := this.c.checker.left_of(node); + val value := this.c.checker.right_of(node); + val kind := this.c.checker.type_at(node); + + # `_ = x` evaluates `x` and lets go of it, which the statement closes. + if operator == tk::assign && this.c.checker.kind_of(target) == nk::name + && this.c.checker.name_of(target) == names::underscore_id { + return this.value(value); + } + + # A property is written by its `set`, on the receiver its `get` reads. + val property := this.property_of(target); + if property != 0 { + val object := this.c.checker.left_of(target); + val receiver := this.receiver_of(object, true); + val held := this.c.checker.decls.types.p[property]; + var stored := operand {}; + if operator == tk::assign { + stored = this.value_as(value, kind); + } else { + val current := this.property_get(property, &receiver, target); + stored = this.compound(node, ¤t, value, kind); + # Changed in place, what `get` gave is what `set` takes, so the statement + # no longer closes it. + val method := this.operator_decl(node); + if method != 0 && this.in_place(method) { + this.adopt(¤t); + } + } + this.property_set(property, &receiver, &stored, target); + return stored; + } + + # A variable holding a reference is pointed elsewhere by a reference written + # as one, and anything else writes what it refers to. + val target_type := this.c.checker.type_at(target); + if operator == tk::assign && this.c.is_reference_type(target_type) { + if !this.c.checker.has_flag(node, rf::valued) { + val place := this.place_of(target); + val made := this.value_as(value, target_type); + this.store(&place, &made); + return made; + } + val place := this.object_by(target, 1); + val made := this.value_as(value, place.kind); + this.adopt(&made); + this.replace(&place, &made); + return made; + } + + # Writing a union's field makes the union hold it, as `u.(d)` names one too. + val target_kind := this.c.checker.kind_of(target); + if target_kind == nk::member || target_kind == nk::member_of { + val ref := this.c.checker.ref_at(target); + if ref != 0 && (ref & (ref_local | ref_type)) == 0 && this.c.checker.decls.kinds.p[ref] == dk::field + && this.c.checker.decls.kinds.p[this.c.checker.decls.owners.p[ref]] == dk::union_type + && !this.c.checker.decls.has(this.c.checker.decls.owners.p[ref], df::foreign) && operator == tk::assign { + val whole := this.object(this.c.checker.left_of(target)); + val made := this.value_as(value, this.c.checker.type_at(target)); + val united := this.unite(&made, this.c.checker.unalias(whole.kind), whole.kind); + this.replace(&whole, &united); + return made; + } + } + + val place := this.writable_place(target); + if operator == tk::assign { + val made := this.value_as(value, place.kind); + this.adopt(&made); + this.replace(&place, &made); + return made; + } + + # A compound assignment reads the target after the value, so it holds whatever + # the value made of it. Where its operator is a method's call, what the method + # gives is written over what the target held, which is closed, and one that + # changes the target in place, as `add_assign`, is given it to change. + val method := this.operator_decl(node); + if method != 0 { + val made := this.method_applied(node, method, &place, value); + if this.in_place(method) { + return this.load(&place); + } + this.replace(&place, &made); + return made; + } + val current := this.load(&place); + val made := this.compound(node, ¤t, value, place.kind); + this.store(&place, &made); + return made; +} + +#! Writes a value over what a place holds, closing what it held first, since +#! nothing holds it afterwards. The value is made before, in case it reads the +#! old one. +#! @param this The emitter. +#! @param place The place. +#! @param value The value. +pub def emitter::replace(&mut this, place: &location, value: &operand): void { + if this.c.checker.closes(place.kind) { + this.close(place); + } + this.store(place, value); +} + +#! The value a compound assignment stores: the operator applied to what the +#! target held and the value. +#! @param this The emitter. +#! @param node The `assign` node. +#! @param current What the target held. +#! @param value The node of the value. +#! @param kind The target's type. +#! @returns The value to store. +def emitter::compound(&mut this, node: u32, current: &operand, value: u32, kind: u32): operand { + val operator := this.c.checker.token_kind(node); + # Where the operator is a method's call, it is called on what the target held, + # and one changing it in place, as `add_assign`, changes that. + val method := this.operator_decl(node); + if method != 0 { + val place := this.hold(current); + val made := this.method_applied(node, method, &place, value); + return this.in_place(method) ? this.load(&place) : made; + } + val plain := this.c.layout_type(kind); + if this.c.checker.types.kind_of(plain) == ty::pointer { + val count := this.value_as(value, bt::int64); + val element := this.c.shape_of(this.c.checker.types.first_of(plain)); + val step := this.scaled(count.words[0], element.size); + return operand::one(kind, this.build.binary(operator == tk::pluseq ? op::add : op::sub, current.words[0], step)); + } + + val shifting := operator == tk::lshifteq || operator == tk::rshifteq; + val right := shifting ? this.value_as(value, this.read_kind(value)) : this.value_as(value, kind); + return this.arithmetic(operator.applied(), current.words[0], right.words[0], kind); +} + +#! `cond ? a : b`, whose branches give the ternary's type. +#! @param this The emitter. +#! @param node The `ternary` node. +#! @returns Its value. +pub def emitter::ternary(&mut this, node: u32): operand { + val kind := this.c.checker.type_at(node); + val then := this.c.checker.record(node, if_slot::then); + val other := this.c.checker.record(node, if_slot::other); + val yes := this.build.new_block(); + val no := this.build.new_block(); + val join := this.build.new_block(); + val result := this.result_place(kind); + + # The names the condition's tests give are declared before it runs, as an + # `if`'s are, and close once the branches join. + val condition := this.c.checker.left_of(node); + val locals := this.scope_mark(); + this.declare_tests(condition); + this.branch_on(condition, yes, no); + this.build.seal(yes); + this.build.seal(no); + this.build.switch_to(yes); + val a := this.value_as(then, kind); + this.adopt(&a); + this.store(&result, &a); + this.build.jump(join); + this.build.switch_to(no); + val b := this.value_as(other, kind); + this.adopt(&b); + this.store(&result, &b); + this.build.jump(join); + this.build.seal(join); + this.build.switch_to(join); + this.end_scope(locals, 0); + + val made := this.load_result(&result); + this.keep(&made); + return made; +} + +#! A place branches each give their value to, which the value is read from where +#! they join: variables, or a cell the statement holds. +#! @param this The emitter. +#! @param kind The value's type. +#! @returns The place. +pub def emitter::result_place(&mut this, kind: u32): location { + val held := this.c.shape_of(kind); + if in_memory(&held) { + return location { kind = kind, address = this.temporary_of(kind), framed = true }; + } + var place := location { kind = kind, held = true }; + for i in 0..word_count(&held) { + place.vars[i] = this.build.variable(word_type(&held)); + } + return place; +} + +#! The value a place branches gave their values to holds, as its own memory +#! where it is in memory, rather than a copy. +#! @param this The emitter. +#! @param place The place. +#! @returns The value. +pub def emitter::load_result(&mut this, place: &location): operand { + return operand::at(place.kind, place.address) if !place.held; + return this.load(place); +} + +#! `value else fallback`: what a `result` or `maybe` holds, or else what stands +#! in for it, a value, or a block that leaves, with the error a result holds +#! named for it. +#! @param this The emitter. +#! @param node The `fallback` node. +#! @returns The value held. +pub def emitter::fallback(&mut this, node: u32): operand { + val kind := this.c.checker.type_at(node); + val error := this.c.checker.record(node, fallback_slot::error); + val other := this.c.checker.record(node, fallback_slot::other); + val whole := this.object(this.c.checker.left_of(node)); + val plain := this.c.checker.unalias(whole.kind); + val index := this.c.layout_of(plain); + + # A result holds its value as `value`, and a maybe as `some`, the other field + # being what holds otherwise. + val wanted := this.c.checker.is_std(plain, word::maybe) ? word::some : names::value_id; + var held: u32 = 0; + var fault: u32 = 0xFFFFFFFF; + val shape := this.c.layout_at(index); + for i in 0..shape.count { + val each := this.c.field_at(index, i as u32); + if each.name == wanted { + held = i as u32; + } else if each.name == word::error { + fault = i as u32; + } + } + val value_field := this.c.field_at(index, held); + + val result := this.result_place(kind); + val yes := this.build.new_block(); + val no := this.build.new_block(); + val join := this.build.new_block(); + this.build.branch(this.tag_is(&whole, held), yes, no); + this.build.seal(yes); + this.build.seal(no); + + # The value is taken out, which a value that closes leaves zeroed, as `move` + # does, so closing what holds it closes nothing twice. + this.build.switch_to(yes); + val payload := this.within(&whole, value_field.offset, value_field.type_id); + val taken := this.load(&payload); + val converted := this.convert(&taken, kind); + this.store(&result, &converted); + if this.c.checker.closes(value_field.type_id) { + this.zero(&payload); + } + this.build.jump(join); + + this.build.switch_to(no); + val mark := this.scope_mark(); + if error != 0 && fault != 0xFFFFFFFF { + val error_field := this.c.field_at(index, fault); + val reason := this.within(&whole, error_field.offset, error_field.type_id); + val copied := this.load(&reason); + val place := this.new_place(error, this.c.checker.type_at(error)); + this.store(&place, &copied); + this.declare(error, place, false); + } + if this.c.checker.kind_of(other) == nk::block { + this.lower_block(other); + } else { + val given := this.value_as(other, kind); + this.adopt(&given); + this.store(&result, &given); + } + this.end_scope(mark, 0); + this.build.jump(join); + this.build.seal(join); + this.build.switch_to(join); + + val made := this.load_result(&result); + this.keep(&made); + return made; +} + +#! `x as T`: between numbers, between integers and enums, which checks an +#! integer is a member's value, between pointers and integers, a reference to +#! the address it holds, and whatever converts without `as`. +#! @param this The emitter. +#! @param node The `cast` node. +#! @returns The value converted. +pub def emitter::cast(&mut this, node: u32): operand { + val inner := this.c.checker.left_of(node); + val to := this.c.checker.type_at(node); + val target := this.c.layout_type(to); + val value := this.value(inner); + val from_type := this.c.layout_type(this.c.checker.read_type(value.kind)); + val reads_through := this.c.is_reference_type(value.kind) && this.c.checker.types.kind_of(target) != ty::pointer + && !this.c.checker.is_std(target, word::cfn) && !this.c.is_reference_type(to); + val source := reads_through ? this.through_references(&value) : value; + val from := this.c.layout_type(source.kind); + val fk := this.c.checker.types.kind_of(from); + val tok := this.c.checker.types.kind_of(target); + + # An integer, or another enum, becomes an enum only as the value of a member. + if this.c.checker.named_kind(target) == dk::enum_type && this.c.checker.named_kind(from) != dk::enum_type + || this.c.checker.named_kind(target) == dk::enum_type && from != target { + val wide := this.numeric(source.words[0], from, this.is_signed(from) ? bt::int64 : bt::uint64); + this.check_member(wide, this.is_signed(from), target); + return operand::one(to, this.numeric(source.words[0], from, to)); + } + + # A reference is the address it holds. + if (tok == ty::pointer || this.c.checker.is_std(target, word::cfn)) && fk == ty::reference { + return operand::one(to, source.words[0]); + } + if tok == ty::pointer || this.c.checker.is_std(target, word::cfn) + || fk == ty::pointer || this.c.checker.is_std(from, word::cfn) { + # While compiling, an address is no number, since where memory is changes from + # one build to the next, so what turns one into a number does not run then. + if this.c.options.evaluating && tok != ty::pointer && !this.c.checker.is_std(target, word::cfn) { + this.build.trap(fault::not_constant as u32); + } + var made := source; + made.count = 1; + made.kind = to; + return made; + } + + if (this.c.checker.types.is_numeric(from) || this.c.checker.types.is_boolean(from) || this.c.checker.named_kind(from) == dk::enum_type) + && (this.c.checker.types.is_numeric(target) || this.c.checker.types.is_boolean(target)) { + if this.c.checker.types.is_boolean(target) && !this.c.checker.types.is_boolean(from) { + if this.is_float(from) { + return operand::one(to, this.build.binary(op::fne, source.words[0], this.build.real(0))); + } + return operand::one(to, this.build.binary(op::ne, source.words[0], this.build.word(0))); + } + return operand::one(to, this.numeric(source.words[0], from, to)); + } + return this.convert(&source, to); +} + +#! A number converted to another numeric type, as the machine converts it: +#! integers wrap to their bits, floats round toward zero and saturate to +#! integers, and an `f32` is rounded to its precision. +#! @param this The emitter. +#! @param value The number. +#! @param from Its type. +#! @param to The type converted to. +#! @returns The number converted. +pub def emitter::numeric(&mut this, value: u32, from: u32, to: u32): u32 { + val source := this.c.shape_of(from); + val target := this.c.shape_of(to); + val floating := source.kind == lk::floating; + if target.kind == lk::floating { + var made := floating ? value : this.build.unary(source.kind == lk::signed ? op::itof : op::utof, value); + if target.bits <= 32 { + made = this.build.unary(op::fsingle, made); + } + return made; + } + var made := floating ? this.build.unary(target.kind == lk::signed ? op::ftoi : op::ftou, value) : value; + if (target.kind == lk::signed || target.kind == lk::unsigned) && target.bits < 64 { + made = this.build.wrap(made, target.bits, target.kind == lk::signed); + } + if target.kind == lk::boolean { + made = this.build.binary(op::ne, made, this.build.word(0)); + } + return made; +} + +#! Stops the program unless an integer is the value of a member of the enum, +#! where the code checks: it is where it lies within one of the runs of +#! consecutive values the members have, which `value - first <= last - first` +#! asks of each without its sign. +#! @param this The emitter. +#! @param value The integer, widened to 64 bits. +#! @param signed Whether it is signed. +#! @param kind The enum's type. +def emitter::check_member(&mut this, value: u32, signed: bool, kind: u32): void { + return if !this.checking(); + val decl := this.c.checker.types.first_of(this.c.checker.unalias(kind)); + var values := vector::::new(); + val flip: u64 = signed ? 0x8000000000000000u : 0; + val run: u32 = this.c.checker.decls.children.p[decl]; + for i in 0..this.c.checker.decls.list_length(run) { + var held := constant {}; + continue if !this.c.checker.decl_value(this.c.checker.decls.list_at(run, i as u32), &mut held); + continue if held.negative && !signed; + continue if !held.negative && signed && held.magnitude > 0x7FFFFFFFFFFFFFFFu; + values.append(held.bits() ^ flip); + } + values.sort(); + + var member: u32 = this.build.word(0); + var i: u64 = 0; + while i < values.length { + var end := i + 1; + while end < values.length && values[end] - values[end - 1] <= 1 { + end++; + } + val offset := this.build.binary(op::sub, value, this.build.word(values[i] ^ flip)); + val within := this.build.binary(op::leu, offset, this.build.word(values[end - 1] - values[i])); + member = this.build.binary(op::bor, member, within); + i = end; + } + this.build.check(member, fault::not_member as u32); +} + +#! The runs of consecutive values an enum's members have, from the least, as +#! the first and last value of each, flipped as `checker::member_order` gives +#! them. +#! @param this The emitter. +#! @param kind The enum's type. +#! @returns The first and last of each run, one after the other. +def emitter::member_runs(&mut this, kind: u32): vector { + val values := this.c.checker.member_order(kind); + var made := vector::::new(); + var i: u64 = 0; + while i < values.length { + var end := i + 1; + while end < values.length && values[end] - values[end - 1] == 1 { + end++; + } + made.append(values[i]); + made.append(values[end - 1]); + i = end; + } + return made; +} + +#! The place of a member of an enum among the values of its members, from 0 +#! for the least, as a range of its members counts: how far it is past the +#! least, less the values missing between the runs before it. +#! @param this The emitter. +#! @param value The member's value, a word. +#! @param kind The enum's type. +#! @returns Its place, a word. +pub def emitter::member_rank(&mut this, value: u32, kind: u32): u32 { + val runs := this.member_runs(kind); + return this.build.word(0) if runs.length == 0; + val flip := this.c.checker.member_flip(kind); + val key := flip == 0 ? value : this.build.binary(op::bxor, value, this.build.word(flip)); + var made := this.build.binary(op::sub, key, this.build.word(runs[0])); + var k: u64 = 2; + while k < runs.length { + val past := this.build.binary(op::leu, this.build.word(runs[k]), key); + val missing := this.build.binary(op::mul, past, this.build.word(runs[k] - runs[k - 1] - 1)); + made = this.build.binary(op::sub, made, missing); + k += 2; + } + return made; +} + +#! The member of an enum at a place among the values of its members, which +#! `member_rank` gives: the least, past it by the place, and past the values +#! missing between the runs before it. +#! @param this The emitter. +#! @param rank The place, a word, before the count of the members' values. +#! @param kind The enum's type. +#! @returns The member's value, a word. +pub def emitter::member_of_rank(&mut this, rank: u32, kind: u32): u32 { + val runs := this.member_runs(kind); + return this.build.word(0) if runs.length == 0; + var made := this.build.binary(op::add, rank, this.build.word(runs[0])); + var before: u64 = runs[1] - runs[0] + 1; + var k: u64 = 2; + while k < runs.length { + val past := this.build.binary(op::leu, this.build.word(before), rank); + val missing := this.build.binary(op::mul, past, this.build.word(runs[k] - runs[k - 1] - 1)); + made = this.build.binary(op::add, made, missing); + before += runs[k + 1] - runs[k] + 1; + k += 2; + } + val flip := this.c.checker.member_flip(kind); + return flip == 0 ? made : this.build.binary(op::bxor, made, this.build.word(flip)); +} + +#! `x is field`, `x is field(v)`, or `x is (d)`: whether a union holds a field, +#! with the value it holds named where it does, a copy of it, or with `&` or +#! `&mut` a reference to it. A test of what a type satisfies was decided while +#! checking, which its value gives. +#! @param this The emitter. +#! @param node The `is_test` node. +#! @returns Whether it holds, a `bool`. +pub def emitter::is_test(&mut this, node: u32): operand { + val kind := this.c.checker.type_at(node); + val field := this.c.checker.ref_at(node); + if field == 0 || (field & (ref_local | ref_type)) != 0 || this.c.checker.decls.kinds.p[field] != dk::field { + this.problem(node, "The test is not decided."); + return operand::one(kind, this.build.word(0)); + } + + val whole := this.object(this.c.checker.left_of(node)); + val plain := this.c.checker.unalias(whole.kind); + val index := this.c.layout_of(plain); + val shape := this.c.layout_at(index); + var at: u32 = 0; + for i in 0..shape.count { + if this.c.field_at(index, i as u32).decl == field { + at = i as u32; + } + } + val held := this.c.field_at(index, at); + val holds := this.tag_is(&whole, at); + val negated := this.c.checker.node_has(node, nf::negated); + + # The value it holds is named only where it holds it, and taken out where it + # closes, as a value a call made is; `_` names nothing, so takes nothing. + val binding := this.c.checker.named_binding(this.c.checker.record(node, is_slot::binding)); + if binding != 0 { + val refers := this.c.checker.kind_of(binding) == nk::reference; + val named := refers ? this.c.checker.left_of(binding) : binding; + if this.local_of(named) == 0 { + val place := this.new_place(named, this.c.checker.type_at(named)); + val closes := this.c.checker.closes(this.c.checker.type_at(named)); + if closes { + this.zero(&place); + } + this.declare(named, place, closes); + } + val local: local_info = this.locals[this.local_of(named) - 1]; + val taking := this.build.new_block(); + val after := this.build.new_block(); + this.build.branch(holds, taking, after); + this.build.seal(taking); + this.build.switch_to(taking); + val payload := this.within(&whole, held.offset, held.type_id); + val bound := this.c.checker.type_at(named); + if refers && !this.c.checker.has_flag(binding, rf::relent) { + val made := this.reference_to(&payload, bound); + this.store(&local.place, &made); + } else { + # A field holding a reference gives that reference, or what it reaches. + val loaded := this.load(&payload); + val made := this.convert(&loaded, bound); + this.store(&local.place, &made); + if this.c.checker.closes(held.type_id) { + this.zero(&payload); + } + } + this.build.jump(after); + this.build.seal(after); + this.build.switch_to(after); + } + return operand::one(kind, negated ? this.build.binary(op::eq, holds, this.build.word(0)) : holds); +} + +#! While compiling, stops unless two pointers are within the same memory. +#! @param this The emitter. +#! @param a One pointer. +#! @param b The other. +pub def emitter::same_memory(&mut this, a: u32, b: u32): void { + var args: u32[2] = [a, b]; + this.build.effect(op::same, args[0:2], 0, 0); +} + +#! While compiling, or running with its memory checked, stops unless elements of +#! a type from a pointer lie in memory the program holds. +#! @param this The emitter. +#! @param pointer The first element. +#! @param count How many there are. +#! @param size The bytes of each. +pub def emitter::reaches(&mut this, pointer: u32, count: u32, size: u64): void { + return if !this.c.options.evaluating && !this.c.options.checks; + var args: u32[2] = [pointer, count]; + this.build.effect(op::reach, args[0:2], 0, size); +} diff --git a/compiler/emitter/ownership.sakura b/compiler/emitter/ownership.sakura new file mode 100644 index 00000000..2111f4a9 --- /dev/null +++ b/compiler/emitter/ownership.sakura @@ -0,0 +1,146 @@ +#! @file ownership.sakura +#! @author John Christman (sorakatadzuma@gmail.com) +#! @copyright Malunal Studios, LLC. +#! @license MIT +#! +#! Contains closing values: a value of a type naming `owning` is closed by its +#! own `close`, and then what it holds is closed, in the reverse of the order +#! it was written, as a scope closes its locals. Also contains the text a +#! format made, which a `string` holding no allocator owns. + +import sakura::analyzer; +module sakura::compiler; + + +#! Closes a value where it is: its own `close` first, then the fields it holds +#! that close, the last first, or of a union the one it holds, or of a fixed +#! array each element, the last first. Closing a zeroed value closes nothing. +#! @param this The emitter. +#! @param place The value's place. +pub def emitter::close(&mut this, place: &location): void { + return if place.held || !this.c.checker.closes(place.kind); + val plain := this.c.checker.unalias(place.kind); + val index := this.c.layout_of(plain); + val shape := this.c.layout_at(index); + + if shape.kind == lk::fixed { + this.close_elements(place, plain, &shape); + return; + } + + # Its own `close`, where it names `owning`. + val owning := this.c.checker.std_decl(word::owning); + if owning != 0 && this.c.checker.satisfies(plain, this.c.checker.decls.types.p[owning]) { + val closer := this.closer_of(plain); + if closer != 0 { + val receiver := this.reference_to(place, this.c.checker.types.reference(plain, true)); + this.method_call(closer, plain, &receiver, span::::empty()); + } + } + + # A union holds one of its fields, so only that one is closed. + if shape.kind == lk::variant { + var at := shape.count; + while at > 0 { + at--; + val each := this.c.field_at(index, at as u32); + continue if !this.c.checker.closes(each.type_id); + val holding := this.build.new_block(); + val after := this.build.new_block(); + this.build.branch(this.tag_is(place, at as u32), holding, after); + this.build.seal(holding); + this.build.switch_to(holding); + val inner := this.within(place, each.offset, each.type_id); + this.close(&inner); + this.build.jump(after); + this.build.seal(after); + this.build.switch_to(after); + } + return; + } + + var at := shape.count; + while at > 0 { + at--; + val each := this.c.field_at(index, at as u32); + continue if !this.c.checker.closes(each.type_id); + val inner := this.within(place, each.offset, each.type_id); + this.close(&inner); + } +} + +#! The `close(&mut this): void` of `owning` a type gives, or 0. +#! @param this The emitter. +#! @param kind The type. +#! @returns The method's declaration, or 0. +pub def emitter::closer_of(&mut this, kind: u32): u32 { + val found := this.c.checker.find_member(kind, word::close); + return 0 if found.decl == 0; + var walk := this.c.checker.decls.walk_overloads(found.decl); + while true { + val at := walk.next(); + break if at == 0; + this.c.checker.resolve(at); + if this.c.checker.decls.kinds.p[at] == dk::function && this.c.checker.decls.has(at, df::mut_this) + && this.c.checker.types.part_count(this.c.checker.decls.types.p[at]) == 1 { + return at; + } + } + return 0; +} + +#! Closes the elements of a fixed array, the last first, by a loop. +#! @param this The emitter. +#! @param place The array's place. +#! @param kind Its type, without aliases. +#! @param shape Its layout. +def emitter::close_elements(&mut this, place: &location, kind: u32, shape: &layout): void { + return if shape.count == 0; + val element := this.c.checker.types.first_of(kind); + val size := this.c.layout_at(shape.element - 1).size; + val first := this.address_of(place); + val left := this.build.variable(vt::word); + this.build.assign(left, this.build.word(shape.count as u64)); + + val head := this.build.new_block(); + val body := this.build.new_block(); + val exit := this.build.new_block(); + this.build.jump(head); + this.build.switch_to(head); + val count := this.build.read(left); + this.build.branch(this.build.binary(op::ne, count, this.build.word(0)), body, exit); + this.build.seal(body); + this.build.switch_to(body); + val index := this.build.binary(op::sub, this.build.read(left), this.build.word(1)); + this.build.assign(left, index); + val address := this.build.binary(op::add, first, this.scaled(index, size)); + val inner := location { kind = element, address = address, framed = place.framed }; + this.close(&inner); + this.close_loop(head, exit); +} + +#! The text a format made, taken from what the program manages itself and +#! handed to a `string` holding no allocator, which gives it back with +#! `raw_release` where it closes. The statement keeps it until a place takes it. +#! @param this The emitter. +#! @param kind The `string` type. +#! @returns The string. +pub def emitter::owned_text(&mut this, kind: u32): operand { + var gives: vt[2] = [vt::word, vt::word]; + val made := this.build.emit(op::format_owned, span::::empty(), gives[0:2], 0, 0); + val pointer: u32 = this.build.code.insts[made].result; + val length := pointer + 1; + + val index := this.c.layout_of(this.c.checker.unalias(kind)); + val shape := this.c.layout_at(index); + val address := this.temporary_of(kind); + this.build.clear(address, shape.size); + for i in 1..shape.count { + break if i >= 4; + val field := this.c.field_at(index, i as u32); + this.build.store(access::i64, address, field.offset, i == 1 ? pointer : length); + } + var text := operand::at(kind, address); + this.keep(&text); + return text; +} diff --git a/compiler/emitter/places.sakura b/compiler/emitter/places.sakura new file mode 100644 index 00000000..b2ab694d --- /dev/null +++ b/compiler/emitter/places.sakura @@ -0,0 +1,617 @@ +#! @file places.sakura +#! @author John Christman (sorakatadzuma@gmail.com) +#! @copyright Malunal Studios, LLC. +#! @license MIT +#! +#! Contains places: where what a name, a field, an element, or what a pointer +#! or reference reaches is, how what is there is read and written, and the +#! references made to it. A reference is read through to what it refers to, +#! as many as it takes, wherever a place is reached through it. + +import sakura::analyzer; +module sakura::compiler; + + +#! The address a place's memory begins at. +#! @param this The emitter. +#! @param place The place, in memory. +#! @returns The address. +pub def emitter::address_of(&mut this, place: &location): u32 { + return place.address if place.offset == 0; + return this.build.binary(op::add, place.address, this.build.word(place.offset)); +} + +#! Reads what a place holds. What is held in memory is copied to a cell of the +#! statement's own, so writing the place afterwards leaves the value as it was. +#! @param this The emitter. +#! @param place The place. +#! @returns The value. +pub def emitter::load(&mut this, place: &location): operand { + val held := this.c.shape_of(place.kind); + var made := operand { kind = place.kind, count = word_count(&held) }; + if place.held { + for i in 0..made.count { + made.words[i] = this.build.read(place.vars[i]); + } + return made; + } + + if in_memory(&held) { + val copy := this.temporary_of(place.kind); + this.build.copy(copy, this.address_of(place), held.size); + return operand::at(place.kind, copy); + } + if made.count == 1 { + made.words[0] = this.build.load(held.how, place.address, place.offset); + return made; + } + for i in 0..made.count { + made.words[i] = this.build.load(access::i64, place.address, place.offset + i as u64 * word_size); + } + return made; +} + +#! Writes a value to a place, which is of the value's type. +#! @param this The emitter. +#! @param place The place. +#! @param value The value. +pub def emitter::store(&mut this, place: &location, value: &operand): void { + val held := this.c.shape_of(place.kind); + if place.held { + for i in 0..word_count(&held) { + this.build.assign(place.vars[i], value.words[i]); + this.bind(place.vars[i], value.words[i]); + } + return; + } + + if in_memory(&held) { + return if value.address == 0; + this.build.copy(this.address_of(place), value.address, held.size); + return; + } + if word_count(&held) == 1 { + this.build.store(held.how, place.address, place.offset, value.words[0]); + return; + } + for i in 0..word_count(&held) { + this.build.store(access::i64, place.address, place.offset + i as u64 * word_size, value.words[i]); + } +} + +#! Zeroes what a place holds. +#! @param this The emitter. +#! @param place The place. +pub def emitter::zero(&mut this, place: &location): void { + val held := this.c.shape_of(place.kind); + if place.held { + for i in 0..word_count(&held) { + val zero := word_type(&held) == vt::real ? this.build.real(0) : this.build.word(0); + this.build.assign(place.vars[i], zero); + this.bind(place.vars[i], zero); + } + return; + } + this.build.clear(this.address_of(place), held.size); +} + +#! A reference to a place, as the word a reference is: where the value is. A +#! place held in variables has no address, so a copy of its value is referred +#! to instead, which the storage worked out before lowering avoids for what a +#! reference must reach. +#! @param this The emitter. +#! @param place The place. +#! @param kind The reference's type. +#! @returns The reference. +pub def emitter::reference_to(&mut this, place: &location, kind: u32): operand { + if place.held { + val value := this.load(place); + val copy := location { kind = place.kind, address = this.temporary_of(place.kind), framed = true }; + this.store(©, &value); + return this.reference_to(©, kind); + } + + # A reference to a trait the value implements is given its type's vtable. + val wanted := this.c.checker.unalias(kind); + if this.c.checker.types.kind_of(wanted) == ty::reference { + val referent := this.c.checker.unalias(this.c.checker.types.first_of(wanted)); + if this.c.checker.named_kind(referent) == dk::trait_type && this.c.checker.named_kind(this.c.checker.unalias(place.kind)) != dk::trait_type { + val own := this.c.checker.types.reference(place.kind, this.c.checker.types.second_of(wanted) != 0); + val made := operand::one(own, this.address_of(place)); + return this.convert(&made, kind); + } + } + return operand::one(kind, this.address_of(place)); +} + +#! The place a reference refers to. +#! @param this The emitter. +#! @param value The reference. +#! @returns The place. +pub def emitter::referent(&mut this, value: &operand): location { + val kind := this.c.checker.types.first_of(this.c.checker.unalias(value.kind)); + # Running with its memory checked, what a reference refers to is where the + # program holds memory, as what a pointer points at is. + if this.c.options.checks && this.c.checker.named_kind(this.c.checker.unalias(kind)) != dk::trait_type { + this.reaches(value.words[0], this.build.word(1), this.c.shape_of(kind).size); + } + return location { kind = kind, address = value.words[0] }; +} + +#! A place within another, at an offset, as a field is. +#! @param this The emitter. +#! @param place The place holding it. +#! @param offset How many bytes in it is. +#! @param kind Its type. +#! @returns The place. +pub def emitter::within(&mut this, place: &location, offset: u64, kind: u32): location { + var made: location = place; + if place.held { + # A value held in variables is no struct, so this is never reached; it is + # copied to memory where it is. + val value := this.load(place); + made = location { kind = place.kind, address = this.temporary_of(place.kind), framed = true }; + this.store(&made, &value); + } + made.kind = kind; + made.offset = made.offset + offset; + return made; +} + +#! The place a node's value is at, read through as many references as it holds +#! until what they refer to is no reference, or as many as `levels` says. +#! @param this The emitter. +#! @param node The node. +#! @param levels How many references to read through at most. +#! @returns The place. +pub def emitter::object_by(&mut this, node: u32, levels: u32): location { + var kind := this.c.checker.type_at(node); + if !this.c.is_reference_type(kind) || levels == 0 { + return this.place_of(node); + } + + var value := this.value_of_type(node); + var place := this.referent(&value); + var steps: u32 = 1; + while steps < levels && this.c.is_reference_type(place.kind) && steps < 16 { + value = this.load(&place); + place = this.referent(&value); + steps++; + } + return place; +} + +#! The place a node's value is at, read through every reference it holds. +#! @param this The emitter. +#! @param node The node. +#! @returns The place. +pub def emitter::object(&mut this, node: u32): location { + return this.object_by(node, 16); +} + +#! The place a node names: a local, a global, a field, an element, or what a +#! pointer points at; or else a cell of the statement's own holding its value. +#! @param this The emitter. +#! @param node The node. +#! @returns The place. +pub def emitter::place_of(&mut this, node: u32): location { + val saved := this.build.pos; + this.at_node(node); + val made := this.place_node(node); + this.build.pos = saved; + return made; +} + +#! The place a node names, by the kind of the node. +#! @param this The emitter. +#! @param node The node. +#! @returns The place. +def emitter::place_node(&mut this, node: u32): location { + match this.c.checker.kind_of(node) { + nk::name, nk::path => { + val ref := this.c.checker.ref_at(node); + if (ref & ref_local) != 0 { + val index := this.local_of(ref & ref_mask); + if index != 0 { + val held: local_info = this.locals[index - 1]; + return held.place; + } + if this.pass_variable(ref & ref_mask) { + val held: local_info = this.locals[this.local_of(ref & ref_mask) - 1]; + return held.place; + } + this.problem(node, "The local is not where it is named."); + } else if ref != 0 && (ref & ref_type) == 0 && this.c.checker.decls.kinds.p[ref] == dk::variable + && !this.c.checker.is_known(node) { + return this.global_place(ref); + } + } + nk::member => { + val ref := this.c.checker.ref_at(node); + if ref != 0 && (ref & (ref_local | ref_type)) == 0 && this.c.checker.decls.kinds.p[ref] == dk::field { + return this.field_place(node, ref); + } + } + nk::member_of => { + val ref := this.c.checker.ref_at(node); + if ref != 0 && (ref & (ref_local | ref_type)) == 0 && this.c.checker.decls.kinds.p[ref] == dk::field { + return this.field_place(node, ref); + } + # What else a description names is no place. + if this.property_of(node) == 0 { + this.problem(node, "The member a description names is not lowered."); + return location { kind = this.c.checker.type_at(node), address = this.build.word(0) }; + } + } + nk::index => { + # Through `at`, it is the reference `at` gives, held as any value is. + if !this.indexes_through_at(node) { + return this.element_place(node); + } + } + nk::call => { + # `value_of(d)` of a variable is the variable. + val ref := this.c.checker.ref_at(node); + if ref != 0 && (ref & (ref_local | ref_type)) == 0 && this.c.checker.decls.kinds.p[ref] == dk::variable + && !this.c.checker.is_known(node) { + return this.global_place(ref); + } + } + nk::unary => { + if this.c.checker.token_kind(node) == tk::star { + # A reference to a pointer is read through to the pointer. + val given := this.value_of_type(this.c.checker.left_of(node)); + val pointer := this.through_references(&given); + val kind := this.c.checker.type_at(node); + this.reaches(pointer.words[0], this.build.word(1), this.c.shape_of(kind).size); + return location { kind = kind, address = pointer.words[0] }; + } + } + else => {} + } + + # Anything else is a value, held where the statement holds what it makes. + val value := this.value_of_type(node); + return this.hold(&value); +} + +#! A place holding a value: its own memory, where it is in memory, or a cell of +#! the statement's own the value is written to. +#! @param this The emitter. +#! @param value The value. +#! @returns The place. +pub def emitter::hold(&mut this, value: &operand): location { + if value.address != 0 { + return location { kind = value.kind, address = value.address, framed = true }; + } + val place := location { kind = value.kind, address = this.temporary_of(value.kind), framed = true }; + this.store(&place, value); + return place; +} + +#! The place of a global, where it is placed among the globals. +#! @param this The emitter. +#! @param decl The global's declaration. +#! @returns The place. +pub def emitter::global_place(&mut this, decl: u32): location { + val kind: u32 = this.c.checker.decls.types.p[decl]; + val constant := this.c.checker.decls.has(decl, df::constant); + + # While compiling, a constant is read once it is evaluated, and a variable + # given its value once the program runs is not read at all. + if this.c.options.evaluating { + if !constant { + this.build.trap(fault::not_constant as u32); + val nowhere := this.build.word(0); + return location { kind = kind, address = nowhere }; + } + val index := this.c.evaluation_of(decl_key(decl), decl, 0, 0, false); + this.build.effect(op::ready, span::::empty(), index, 0); + val offset: u64 = this.c.evaluations[index].offset; + val address := this.build.value(op::global, span::::empty(), vt::word, 0, offset); + return location { kind = kind, address = address }; + } + + # A constant evaluated is read where the program holds its value as data. + if constant { + val datum := this.c.evaluated_datum(decl_key(decl), kind); + if datum != no_block { + val address := this.build.value(op::datum, span::::empty(), vt::word, datum, 0); + return location { kind = kind, address = address }; + } + } + + val offset := this.c.global_of(decl); + val address := this.build.value(op::global, span::::empty(), vt::word, 0, offset); + return location { kind = kind, address = address }; +} + +#! Whether the code checks what only a checked build does: indexes and slices, +#! the field a union holds, an integer converted to an enum, and a `match` +#! finding no arm. A constant is evaluated checked in every build. +#! @param this The emitter. +#! @returns Whether it does. +pub def emitter::checking(&this): bool { + return !this.c.checker.checks_off || this.c.options.evaluating; +} + +#! Stops the program where a pointer is null, which only the code of a checked +#! program reaching an element past the first page asks. Elsewhere reading or +#! writing through null stops the program where it does, in every build: the +#! machine compares each address it reads or writes through with the first +#! page, and an executable faults there, which its runtime reports as the same. +#! @param this The emitter. +#! @param pointer The pointer. +def emitter::compare_null(&mut this, pointer: u32): void { + val zero := this.build.word(0); + this.build.check(this.build.binary(op::ne, pointer, zero), fault::null_reference as u32); +} + +#! The place of a field of a struct or union, read through the references the +#! object is reached by. A field a struct's spread brings in is reached through +#! the spread field holding it, and a field of a union only where the union +#! holds it. +#! @param this The emitter. +#! @param node The `member` node. +#! @param field The field's declaration. +#! @returns The place. +pub def emitter::field_place(&mut this, node: u32, field: u32): location { + val object := this.c.checker.left_of(node); + val whole := this.object(object); + val kind := this.c.checker.type_at(node); + val owner := this.c.checker.unalias(whole.kind); + return this.field_in(&whole, owner, field, kind); +} + +#! The place of a field within a place holding a struct or union of a type. +#! @param this The emitter. +#! @param whole The place of the struct or union. +#! @param owner Its type, without aliases. +#! @param field The field's declaration. +#! @param kind The field's type, as checked. +#! @returns The place. +pub def emitter::field_in(&mut this, whole: &location, owner: u32, field: u32, kind: u32): location { + val index := this.c.layout_of(owner); + val shape := this.c.layout_at(index); + for i in 0..shape.count { + val each := this.c.field_at(index, i as u32); + if each.decl == field { + if shape.kind == lk::variant { + this.check_held(whole, i as u32); + } + return this.within(whole, each.offset, each.type_id); + } + } + + # Reached through a spread field, which holds the struct declaring it. + for i in 0..shape.count { + val each := this.c.field_at(index, i as u32); + continue if !each.spread; + val inner := this.within(whole, each.offset, each.type_id); + val plain := this.c.checker.unalias(each.type_id); + if this.holds_field(plain, field, 0) { + return this.field_in(&inner, plain, field, kind); + } + } + this.problem(0, "A field is not in the layout of what holds it."); + return this.within(whole, 0, kind); +} + +#! Whether a struct holds a field, its own or one a spread brings in. +#! @param this The emitter. +#! @param kind The struct's type. +#! @param field The field's declaration. +#! @param depth How deeply spreads have been followed. +#! @returns Whether it holds it. +def emitter::holds_field(&mut this, kind: u32, field: u32, depth: u32): bool { + return false if depth > 16; + val index := this.c.layout_of(kind); + val shape := this.c.layout_at(index); + for i in 0..shape.count { + val each := this.c.field_at(index, i as u32); + return true if each.decl == field; + if each.spread && this.holds_field(this.c.checker.unalias(each.type_id), field, depth + 1) { + return true; + } + } + return false; +} + +#! Stops the program unless a union holds its field of an index, where the code +#! checks. +#! @param this The emitter. +#! @param whole The place of the union. +#! @param index The field's index. +pub def emitter::check_held(&mut this, whole: &location, index: u32): void { + return if !this.checking(); + val holds := this.tag_is(whole, index); + this.build.check(holds, fault::not_held as u32); +} + +#! Whether a union holds its field of an index, as a word of 0 or 1. +#! @param this The emitter. +#! @param whole The place of the union. +#! @param index The field's index. +#! @returns The word. +pub def emitter::tag_is(&mut this, whole: &location, index: u32): u32 { + var tag: u32 = 0; + if whole.held { + tag = this.build.read(whole.vars[0]); + } else { + tag = this.build.load(access::i64, whole.address, whole.offset); + } + # A union without a tag holds the field it is laid out for where its first word + # is not null, and the empty one where it is. + val shape := this.c.shape_of(whole.kind); + if shape.niche != 0 { + return this.build.binary(index + 1 == shape.niche ? op::ne : op::eq, tag, this.build.word(0)); + } + return this.build.binary(op::eq, tag, this.build.word(index as u64)); +} + +#! The place of an element: of a fixed array, at an index checked against its +#! length; of what a pointer points at, which is not checked; of a view, checked +#! against how many it views; of a pack, at an index known while compiling; or +#! of what implements `indexable`, the place its `at` refers to. +#! @param this The emitter. +#! @param node The `index` node. +#! @returns The place. +pub def emitter::element_place(&mut this, node: u32): location { + val object := this.c.checker.left_of(node); + val at := this.c.checker.right_of(node); + val kind := this.c.checker.type_at(node); + val whole_type := this.object_type(object); + val through := this.c.checker.unalias(this.c.checker.reached(whole_type)); + + match this.c.checker.types.kind_of(through) { + ty::fixed => { + val whole := this.object(object); + val shape := this.c.shape_of(through); + val element := this.c.layout_at(shape.element - 1); + if this.c.checker.is_known(at) { + val index := this.c.checker.value_at(at).magnitude; + if index < shape.count as u64 { + return this.within(&whole, index * element.size, this.c.checker.types.first_of(through)); + } + } + val index := this.value_as(at, bt::uint64); + if this.checking() { + val within := this.build.binary(op::ltu, index.words[0], this.build.word(shape.count as u64)); + this.build.check(within, fault::out_of_bounds as u32); + } + val first := this.address_of(&whole); + val address := this.build.binary(op::add, first, this.scaled(index.words[0], element.size)); + return location { kind = this.c.checker.types.first_of(through), address = address, framed = whole.framed }; + } + ty::pointer => { + val pointer := this.value_of_type(object); + val reached := this.through_references(&pointer); + val element := this.c.shape_of(this.c.checker.types.first_of(through)); + # An element past the first page is no fault there, so a checked program + # compares the pointer with null first, unless the index is known to + # stay within it. + val near := this.c.checker.is_known(at) && (element.size == 0 || this.c.checker.value_at(at).magnitude < null_page / element.size); + if this.checking() && !near { + this.compare_null(reached.words[0]); + } + val index := this.value_as(at, bt::uint64); + val address := this.build.binary(op::add, reached.words[0], this.scaled(index.words[0], element.size)); + this.reaches(address, this.build.word(1), element.size); + return location { kind = this.c.checker.types.first_of(through), address = address }; + } + ty::pack => { + val index := this.c.checker.value_at(at).magnitude; + return this.pack_place(object, index as u32); + } + else => {} + } + + # A view holds where its elements are and how many, so an element of one is the + # place that many along, once the index is checked against the count. A view + # holding any element is never over null, as std makes every view, so the + # index's check is all it needs. + val viewed := this.c.viewed(through); + if viewed != 0 { + val whole := this.object(object); + val data := this.build.load(access::i64, whole.address, whole.offset); + val count := this.build.load(access::i64, whole.address, whole.offset + word_size); + val index := this.value_as(at, bt::uint64); + if this.checking() { + this.build.check(this.build.binary(op::ltu, index.words[0], count), fault::out_of_bounds as u32); + } + val element := this.c.shape_of(viewed); + val address := this.build.binary(op::add, data, this.scaled(index.words[0], element.size)); + return location { kind = viewed, address = address }; + } + + # What implements `indexable` gives a reference to the element through `at`. + val method := this.c.checker.ref_at(node); + if method != 0 && (method & (ref_local | ref_type)) == 0 && this.c.checker.decls.kinds.p[method] == dk::function { + val made := this.accessor_call(node, method, object, at); + if this.c.is_reference_type(made.kind) { + return this.referent(&made); + } + return this.hold(&made); + } + this.problem(node, "Nothing is indexed here."); + return location { kind = kind, address = this.temporary_of(kind) }; +} + +#! The type of what an element or a member is reached through: its own, or, +#! for a constant, the one it settles as, so `"text"[0]` is a `strview`'s. +#! @param this The emitter. +#! @param object The node of the value reached through. +#! @returns The type. +pub def emitter::object_type(&mut this, object: u32): u32 { + val own := this.c.checker.type_at(object); + return this.c.checker.types.is_untyped(own) ? this.c.checker.converted(object) : own; +} + +#! Whether `x[k]` is indexed through `at`, and so is the reference it gives +#! rather than a place of its own. +#! @param this The emitter. +#! @param node The `index` node. +#! @returns Whether it is. +pub def emitter::indexes_through_at(&mut this, node: u32): bool { + val method := this.c.checker.ref_at(node); + return method != 0 && (method & (ref_local | ref_type)) == 0 && this.c.checker.decls.kinds.p[method] == dk::function + && this.c.is_reference_type(this.c.checker.type_at(node)); +} + +#! The reference `x[k]` gives through `at`: the one `at` gives, or, for a view, +#! which is indexed without calling it, one to the element it covers. +#! @param this The emitter. +#! @param node The `index` node. +#! @returns The reference. +pub def emitter::indexed_reference(&mut this, node: u32): operand { + val object := this.c.checker.left_of(node); + val through := this.c.checker.unalias(this.c.checker.reached(this.object_type(object))); + if this.c.viewed(through) != 0 { + val place := this.element_place(node); + return this.reference_to(&place, this.c.checker.type_at(node)); + } + return this.accessor_call(node, this.c.checker.ref_at(node), object, this.c.checker.right_of(node)); +} + +#! A count of elements of a size, in bytes. +#! @param this The emitter. +#! @param count The count, a word. +#! @param size The size of each. +#! @returns The bytes. +pub def emitter::scaled(&mut this, count: u32, size: u64): u32 { + return count if size == 1; + return this.build.binary(op::mul, count, this.build.word(size)); +} + +#! A value read through every reference it is, until it is no reference. +#! @param this The emitter. +#! @param value The value. +#! @returns What it reaches. +pub def emitter::through_references(&mut this, value: &operand): operand { + var at: operand = value; + var steps := 0; + while this.c.is_reference_type(at.kind) && steps < 16 { + val place := this.referent(&at); + at = this.load(&place); + steps++; + } + return at; +} + +#! The place of a value of a pack, by its index. +#! @param this The emitter. +#! @param object The node naming the pack. +#! @param index The value's index. +#! @returns The place. +pub def emitter::pack_place(&mut this, object: u32, index: u32): location { + val ref := this.c.checker.ref_at(object); + val local := (ref & ref_local) != 0 ? this.local_of(ref & ref_mask) : 0; + if local != 0 { + val held: local_info = this.locals[local - 1]; + if index < held.count { + return this.packs[held.pack as u64 + index as u64]; + } + } + this.problem(object, "The pack holds no value at the index."); + return location { kind = bt::error }; +} diff --git a/compiler/emitter/reflection.sakura b/compiler/emitter/reflection.sakura new file mode 100644 index 00000000..3fca69c4 --- /dev/null +++ b/compiler/emitter/reflection.sakura @@ -0,0 +1,253 @@ +#! @file reflection.sakura +#! @author John Christman (sorakatadzuma@gmail.com) +#! @copyright Malunal Studios, LLC. +#! @license MIT +#! +#! Contains what reflection gives a program: descriptions of its declarations, +#! as `core::decl`s, which the checker found while compiling. They are written +#! as data the program holds as long as it runs, the text they name among it, +#! and read where the program stands. + +import sakura::analyzer; +module sakura::compiler; + + +#! What reflection gives an expression: one description, read from the data +#! holding it, or a view of a list of them. +#! @param this The emitter. +#! @param node The expression. +#! @returns The value. +pub def emitter::reflected_value(&mut this, node: u32): operand { + val kind := this.c.checker.type_at(node); + val at := this.c.checker.reflected_at(node); + if at == checker::no_reflection { + this.problem(node, "Reflection gives nothing here."); + return this.zero_value(kind); + } + + var items := vector::::new(); + for i in 0..this.c.checker.reflected_count(at) { + items.append(this.c.checker.reflected_item(at, i as u32)); + } + if this.c.checker.reflected_kind(at) == rk::one as u32 { + val datum := this.c.descriptions(items.view(), kind); + val address := this.build.value(op::datum, span::::empty(), vt::word, datum, 0); + val place := location { kind = kind, address = address }; + return this.load(&place); + } + + val view := this.temporary_of(kind); + if items.length == 0 { + this.build.clear(view, 2 * word_size); + return operand::at(kind, view); + } + val element := this.c.viewed(kind); + val datum := this.c.descriptions(items.view(), element); + val first := this.build.value(op::datum, span::::empty(), vt::word, datum, 0); + this.build.store(access::i64, view, 0, first); + this.build.store(access::i64, view, word_size, this.build.word(items.length)); + return operand::at(kind, view); +} + +#! Declares the variable of a pass of `for const` over a list reflection gives: +#! the description the pass is of. +#! @param this The emitter. +#! @param variable The node of the loop's variable. +pub def emitter::reflected_pass(&mut this, variable: u32): void { + val kind := this.c.checker.type_at(variable); + val made := this.reflected_value(variable); + val place := this.new_place(variable, kind); + this.store(&place, &made); + this.declare(variable, place, false); +} + +#! Declares the variable of a pass of `for const` over a list reflection gives +#! where a function the pass doesn't run in names it, as the one evaluating the +#! condition of an `if const` within the pass does: the description the pass is +#! of, as it is in the pass. +#! @param this The emitter. +#! @param variable The node of the loop's variable. +#! @returns Whether it is such a variable, and was declared. +pub def emitter::pass_variable(&mut this, variable: u32): bool { + val at := this.c.checker.reflected_at(variable); + return false if at == checker::no_reflection || this.c.checker.reflected_kind(at) != rk::one as u32; + this.reflected_pass(variable); + return true; +} + +#! The datum holding descriptions as `core::decl`s one after another, made where +#! it is new, with the text each names among the program's data. +#! @param this The compiler. +#! @param items The descriptions' indices among the checker's. +#! @param kind The type of each, `core::decl`. +#! @returns The datum's index. +pub def lowerer::descriptions(&mut this, items: span, kind: u32): u32 { + val plain := this.checker.unalias(kind); + val index := this.layout_of(plain); + val shape := this.layout_at(index); + var bytes := vector::::new(); + bytes.resize(shape.size * items.length); + var relocations := vector::::new(); + + for i in 0..items.length { + val held: desc = this.checker.descs[items[i]]; + val base := i * shape.size; + var name := string::new(nothing {}); + var path := string::new(nothing {}); + var signature := string::new(nothing {}); + val decl := held.decl; + if held.param != 0 { + this.param_name(decl, held.param - 1, &mut name); + } else { + name.append(this.checker.names.text(this.checker.decls.names.p[decl])); + } + this.qualified_name(decl, &mut path); + this.signature_text(decl, &mut signature); + + val file: u32 = this.checker.decls.files.p[decl]; + val source := &this.checker.units[file].source; + val place := source.lines.place_of(this.node_offset(file, this.checker.decls.nodes.p[decl])); + for f in 0..shape.count { + val field := this.field_at(index, f as u32); + val field_name := this.checker.names.text(field.name); + val at := base + field.offset; + if field_name == "id" { + write_number(&mut bytes, at, this.layout_at(field.layout).size, decl as u64); + } else if field_name == "kind" { + val bit := held.param != 0 ? 0x2000u : this.checker.target_bit(decl); + write_number(&mut bytes, at, this.layout_at(field.layout).size, bit); + } else if field_name == "exported" { + write_number(&mut bytes, at, 1, held.param == 0 && this.checker.decls.has(decl, df::exported) ? 1 : 0); + } else if field_name == "generic" { + write_number(&mut bytes, at, 1, held.param == 0 && this.checker.own_param_count(decl) != 0 ? 1 : 0); + } else if field_name == "name" { + this.write_text(&mut bytes, &mut relocations, at, name.view()); + } else if field_name == "path" { + this.write_text(&mut bytes, &mut relocations, at, path.view()); + } else if field_name == "at" { + val inner := this.layout_at(field.layout); + for s in 0..inner.count { + val part := this.field_at(field.layout, s as u32); + val part_name := this.checker.names.text(part.name); + val within := at + part.offset; + if part_name == "path" { + this.write_text(&mut bytes, &mut relocations, within, source.path); + } else if part_name == "line" { + write_number(&mut bytes, within, this.layout_at(part.layout).size, place.line as u64); + } else if part_name == "column" { + write_number(&mut bytes, within, this.layout_at(part.layout).size, place.column as u64); + } else if part_name == "signature" { + this.write_text(&mut bytes, &mut relocations, within, signature.view()); + } + } + } + } + } + + val datum := this.program.data.length as u32; + bytes.append(0); + this.program.data.append(datum { + bytes = move(&mut bytes), + align = shape.align < word_size ? word_size : shape.align, + relocations = move(&mut relocations) + }); + return datum; +} + +#! Writes a number into bytes, as wide as it says, least significant first. +#! @param bytes Where it is written. +#! @param at The first byte. +#! @param size How many bytes it takes. +#! @param value The number. +pub def write_number(bytes: &mut vector, at: u64, size: u64, value: u64): void { + for i in 0..size { + bytes[at + i] = ((value >> (i * 8)) & 0xFF) as u8; + } +} + +#! Writes a view of text into bytes: where the text is, as the address of a +#! datum holding it, and how many bytes it holds. Empty text points nowhere. +#! @param this The compiler. +#! @param bytes Where the view is written. +#! @param relocations Where the address is noted. +#! @param at The first byte of the view. +#! @param text The text. +def lowerer::write_text(&mut this, bytes: &mut vector, relocations: &mut vector, at: u64, text: strview): void { + if text.length != 0 { + relocations.append(relocation { at = at, target = this.text_datum(text), addend = 0 }); + } + write_number(bytes, at + word_size, word_size, text.length); +} + +#! The name a function's parameter is declared with. +#! @param this The compiler. +#! @param decl The function's declaration. +#! @param index The parameter's position. +#! @param out Where the name is written. +def lowerer::param_name(&mut this, decl: u32, index: u32, out: &mut string): void { + val saved := this.checker.at; + this.checker.use_table(this.checker.units[this.checker.decls.files.p[decl]].table); + val node: u32 = this.checker.decls.nodes.p[decl]; + val params := this.checker.decls.has(decl, df::accessor) ? this.checker.left_of(node) : this.checker.record(node, function_slot::params); + if index < this.checker.run_length(params) { + out.append(this.checker.names.text(this.checker.param_name(this.checker.run_at(params, index)))); + } + this.checker.at = saved; +} + +#! The name a declaration is reached by from outside its module, as +#! `sakura::analyzer::interns_keywords`. +#! @param this The compiler. +#! @param decl The declaration. +#! @param out Where the name is written. +pub def lowerer::qualified_name(&mut this, decl: u32, out: &mut string): void { + var modules := vector::::new(); + var at: u32 = this.checker.decls.modules.p[decl]; + var steps := 0; + while at != 0 && steps < 64 { + modules.append(at); + at = this.checker.modules.parents[at]; + steps++; + } + var i := modules.length; + while i > 0 { + i--; + out.append(this.checker.names.text(this.checker.modules.names[modules[i]])); + out.append("::"); + } + var holder: u32 = this.checker.decls.owners.p[decl]; + if holder != 0 && this.checker.decls.kinds.p[holder] == dk::property { + holder = this.checker.decls.owners.p[holder]; + } + if holder != 0 && this.checker.decls.kinds.p[holder] != dk::type_param { + out.append(this.checker.names.text(this.checker.decls.names.p[holder])); + out.append("::"); + } + out.append(this.checker.names.text(this.checker.decls.names.p[decl])); +} + +#! The signature a declaration is written with: its text from where it begins +#! to its body, or its first line. +#! @param this The compiler. +#! @param decl The declaration. +#! @param out Where the text is written. +pub def lowerer::signature_text(&mut this, decl: u32, out: &mut string): void { + val file: u32 = this.checker.decls.files.p[decl]; + val node: u32 = this.checker.decls.nodes.p[decl]; + return if node == 0; + val syntax := &this.checker.units[file].syntax; + val source := &this.checker.units[file].source; + val begin := syntax.token_offsets[syntax.start_of(node)]; + val end_token := syntax.node_end(node); + val end := syntax.token_offsets[end_token] + syntax.token_length(end_token, this.checker.names); + return if end <= begin; + val whole := source.make_lexeme(begin, end - begin); + var stop := 0u; + while stop < whole.length && whole[stop] != '{' && whole[stop] != '\n' { + stop++; + } + while stop > 0 && (whole[stop - 1] == ' ' || whole[stop - 1] == '\t') { + stop--; + } + out.append(whole.substr(0, stop)); +} diff --git a/compiler/emitter/statements.sakura b/compiler/emitter/statements.sakura new file mode 100644 index 00000000..13a73d66 --- /dev/null +++ b/compiler/emitter/statements.sakura @@ -0,0 +1,653 @@ +#! @file statements.sakura +#! @author John Christman (sorakatadzuma@gmail.com) +#! @copyright Malunal Studios, LLC. +#! @license MIT +#! +#! Contains the lowering of statements: blocks and the locals declared in +#! them, branches, `if const` and `when`, loops, contracts, and leaving by +#! `return`, `break`, and `continue`, each closing what it leaves behind. + +import sakura::analyzer; +module sakura::compiler; + + +#! Lowers a block, whose locals close where it ends. Statements after one the +#! checker found always leaves, as decided while checking, were never checked, +#! so they are not lowered either. +#! @param this The emitter. +#! @param node The block, or a statement standing for one. +pub def emitter::lower_block(&mut this, node: u32): void { + return if node == 0; + if this.c.checker.kind_of(node) != nk::block { + this.lower_statement(node); + return; + } + + val mark := this.scope_mark(); + val run := this.c.checker.left_of(node); + for i in 0..this.c.checker.run_length(run) { + val each := this.c.checker.run_at(run, i as u32); + this.lower_statement(each); + break if this.skips(each); + } + this.end_scope(mark, 0); +} + +#! Whether a statement leaves where it was decided while checking, so the +#! checker checked nothing after it: an `if const` whose branch taken leaves, +#! with no `else`, or a block or `when` holding one. +#! @param this The emitter. +#! @param node The statement. +#! @returns Whether it does. +pub def emitter::skips(&mut this, node: u32): bool { + match this.c.checker.kind_of(node) { + nk::block => { + val run := this.c.checker.left_of(node); + for i in 0..this.c.checker.run_length(run) { + return true if this.skips(this.c.checker.run_at(run, i as u32)); + } + } + nk::when_block => return this.skips(this.c.checker.when_branch(node)); + nk::if_const => { + val condition := this.c.checker.left_of(node); + return false if !this.c.checker.is_known(condition); + val then := this.c.checker.record(node, if_slot::then); + val other := this.c.checker.record(node, if_slot::other); + if this.c.checker.value_at(condition).magnitude != 0 { + return this.skips(then) || (other == 0 && this.c.checker.has_flag(then, rf::leaves)); + } + return other != 0 && this.skips(other); + } + else => {} + } + return false; +} + +#! Lowers a statement. +#! @param this The emitter. +#! @param node The statement. +pub def emitter::lower_statement(&mut this, node: u32): void { + # A contract left out is no statement at all, so what follows takes no + # place of it. + return if this.c.checker.contracts_off && this.c.checker.kind_of(node) == nk::contract; + this.at_node(node); + match this.c.checker.kind_of(node) { + nk::block => this.lower_block(node); + nk::variable => this.local_statement(node); + nk::if_stmt => this.if_statement(node); + nk::if_const => this.if_const(node); + nk::when_block => this.lower_block(this.c.checker.when_branch(node)); + nk::while_stmt => this.while_statement(node); + nk::for_stmt => this.for_statement(node); + nk::match_stmt => { + val mark := this.begin_statement(); + this.lower_match(node, false); + this.end_statement(mark); + } + nk::return_stmt => { + val mark := this.begin_statement(); + val value := this.c.checker.left_of(node); + if value != 0 && this.result != bt::void_type { + this.return_value(value, mark); + return; + } + # `return;` from a function giving more than nothing gives `void`, as a + # `result` holds it. + if value == 0 && this.c.checker.unalias(this.result) != bt::void_type { + val none := operand::none(bt::void_type); + var made := this.convert(&none, this.result); + this.return_made(&mut made, 0, mark); + return; + } + # What gives nothing, returned from a function giving nothing, is done first. + if value != 0 { + this.value(value); + } + this.close_kept(mark.kept); + this.leave_kept(0); + this.close_locals(0, 0); + this.build.ret(span::::empty()); + } + nk::break_stmt, nk::continue_stmt => this.leave_loop(this.c.checker.kind_of(node) == nk::break_stmt); + nk::contract => this.contract_statement(node); + nk::expr_stmt => { + val mark := this.begin_statement(); + val inner := this.c.checker.left_of(node); + this.value(inner); + this.end_statement(mark); + # A call that ends the program, as `exit`, is never returned from. + if this.ends_program(inner) { + this.build.unreachable(); + } + } + else => {} + } +} + +#! Lowers a contract, as only a program checking contracts does: `expects` and +#! `asserts` are checked where they are, and an `ensures` is an entry among the +#! locals, which closing checks on each way out of its block, once what each +#! `old` within it reads is kept. +#! @param this The emitter. +#! @param node The `contract` node. +def emitter::contract_statement(&mut this, node: u32): void { + if this.c.checker.clause_of(node) != clause::ensures { + val mark := this.begin_statement(); + this.check_contract(node); + this.end_statement(mark); + return; + } + this.keep_earlier(this.c.checker.left_of(node)); + val index := this.declare(node, location {}, true); + this.locals[index].checks = true; +} + +#! Keeps what each `old(e)` in an `ensures`'s condition reads, where the +#! `ensures` is reached, as a local the `old_value` node declares. +#! @param this The emitter. +#! @param condition The condition. +def emitter::keep_earlier(&mut this, condition: u32): void { + var walk := node_walk::new(condition); + while walk.more() { + val at := walk.next(); + if this.c.checker.kind_of(at) == nk::old_value { + val held := this.c.checker.type_at(at); + val mark := this.begin_statement(); + val made := this.value_as(this.c.checker.left_of(at), held); + val place := this.fresh_place(held); + this.store(&place, &made); + this.end_statement(mark); + this.declare(at, place, false); + continue; + } + this.c.scan_children(at, &mut walk); + } +} + +#! Checks an `ensures` where its block is left, the name it gives what the +#! function returns standing for that. Where the way out returns nothing, as +#! where every way through the block returned before its end, it is never +#! reached. +#! @param this The emitter. +#! @param node The `contract` node. +pub def emitter::check_ensures(&mut this, node: u32): void { + return if this.build.ended(); + val bound := this.c.checker.record(node, contract_slot::bound); + return if bound != 0 && !this.returning; + val locals := this.scope_mark(); + if bound != 0 { + val place := this.new_place(bound, this.returned.kind); + this.store(&place, &this.returned); + this.declare(bound, place, false); + } + val mark := this.begin_statement(); + this.check_contract(node); + this.end_statement(mark); + this.forget_locals(locals); +} + +#! Lowers a contract's check: where its condition holds, the program goes on, +#! and where it does not, a block of its own, which nothing comes back from, +#! makes the report and stops the program with it, so a contract that holds +#! costs its condition and a branch. +#! @param this The emitter. +#! @param node The `contract` node. +def emitter::check_contract(&mut this, node: u32): void { + val saved := this.build.pos; + this.at_node(node); + val fine := this.build.new_block(); + val failing := this.build.new_block(); + this.branch_on(this.c.checker.left_of(node), fine, failing); + this.build.seal(failing); + this.build.switch_to(failing); + this.report_contract(node); + this.build.seal(fine); + this.build.switch_to(fine); + this.build.pos = saved; +} + +#! Stops the program where a contract failed, saying which kind failed, what it +#! checked, as written or as its text says, and what the condition's operands +#! held, as `A pre-condition failed: b != 0, with b = 0.` +#! @param this The emitter. +#! @param node The `contract` node. +def emitter::report_contract(&mut this, node: u32): void { + val mark := this.begin_statement(); + val condition := this.c.checker.left_of(node); + val text := this.c.checker.record(node, contract_slot::text); + val lead := match this.c.checker.clause_of(node) { + expects => "A pre-condition failed: ", + asserts => "An assertion failed: ", + ensures => "A post-condition failed: " + }; + this.build.effect(op::format, span::::empty(), 0, 0); + this.build.effect(op::format_text, span::::empty(), this.c.text_datum(lead), 0); + + # Text written as a literal ends where the report's own full stop does. + if text != 0 && this.c.checker.kind_of(text) == nk::string { + var said := string::new(nothing {}); + this.decode_literal(this.c.checker.text_of(text), &mut said); + if said.length != 0 && said[said.length - 1] == '.' { + said.resize(said.length - 1); + } + this.build.effect(op::format_text, span::::empty(), this.c.text_datum(said.view()), 0); + } else if text != 0 { + val said := this.value(text); + this.format_sentence(&said); + } else { + var written := string::new(nothing {}); + this.source_text(condition, &mut written); + this.build.effect(op::format_text, span::::empty(), this.c.text_datum(written.view()), 0); + } + this.write_values(condition, ", with "); + this.build.effect(op::format_text, span::::empty(), this.c.text_datum("."), 0); + + # The program stops with the report, so nothing made here is closed. + var report := this.owned_text(this.c.checker.type_at(node)); + this.adopt(&report); + val index := this.c.layout_of(this.c.checker.unalias(report.kind)); + val data := this.c.field_at(index, 1); + val count := this.c.field_at(index, 2); + var words: u32[2] = [this.build.load(access::i64, report.address, data.offset), this.build.load(access::i64, report.address, count.offset)]; + this.build.effect(op::fault, words[0:2], 0, 0); + this.build.unreachable(); + this.drop_kept(mark.kept); + this.release(mark.cells); +} + +#! Writes a view of text into the text being made without a full stop it ends +#! with, where the report's own ends it. +#! @param this The emitter. +#! @param text The view. +def emitter::format_sentence(&mut this, text: &operand): void { + var data := text.words[0]; + var length := text.words[1]; + if text.address != 0 { + data = this.build.load(access::i64, text.address, 0); + length = this.build.load(access::i64, text.address, word_size); + } + val held := this.build.variable(vt::word); + this.build.assign(held, length); + val looking := this.build.new_block(); + val dropping := this.build.new_block(); + val after := this.build.new_block(); + this.build.branch(this.build.binary(op::ne, length, this.build.word(0)), looking, after); + this.build.seal(looking); + this.build.switch_to(looking); + val last := this.build.load(access::u8, this.build.binary(op::add, data, this.build.binary(op::sub, length, this.build.word(1))), 0); + this.build.branch(this.build.binary(op::eq, last, this.build.word('.' as u64)), dropping, after); + this.build.seal(dropping); + this.build.switch_to(dropping); + this.build.assign(held, this.build.binary(op::sub, length, this.build.word(1))); + this.build.jump(after); + this.build.seal(after); + this.build.switch_to(after); + var args: u32[2] = [data, this.build.read(held)]; + this.build.effect(op::format_bytes, args[0:2], 0, 0); +} + +#! Whether an expression ends the program: a call of `exit` or `abort`, which +#! the checker treats as leaving. +#! @param this The emitter. +#! @param node The expression. +#! @returns Whether it does. +def emitter::ends_program(&mut this, node: u32): bool { + return false if this.c.checker.kind_of(node) != nk::call; + val decl := this.c.checker.ref_at(node); + return false if decl == 0 || (decl & (ref_local | ref_type)) != 0; + return false if !this.c.checker.decls.has(decl, df::intrinsic); + val name := this.c.checker.names.text(this.c.checker.decls.names.p[decl]); + return name == "exit" || name == "abort" || name == "fault"; +} + +#! Lowers a local variable or constant. A constant known while compiling is no +#! local at all, being written wherever it is named. +#! @param this The emitter. +#! @param node The `variable` node. +def emitter::local_statement(&mut this, node: u32): void { + val value := this.c.checker.record(node, variable_slot::value); + val kind := this.c.checker.type_at(node); + if this.c.checker.node_has(node, nf::constant) && this.c.checker.is_known(node) { + return; + } + + # A constant the checker did not work out is evaluated: read where it is + # once it is, while compiling, and where the program holds it as data after. + if this.c.checker.node_has(node, nf::constant) { + val key := node_key(this.table, node); + if this.c.options.evaluating { + val index := this.c.evaluation_of(key, 0, this.table, node, false); + this.build.effect(op::ready, span::::empty(), index, 0); + val offset: u64 = this.c.evaluations[index].offset; + val address := this.build.value(op::global, span::::empty(), vt::word, 0, offset); + this.declare(node, location { kind = kind, address = address }, false); + return; + } + val datum := this.c.evaluated_datum(key, kind); + if datum != no_block { + val address := this.build.value(op::datum, span::::empty(), vt::word, datum, 0); + this.declare(node, location { kind = kind, address = address }, false); + return; + } + } + + # A function declared within a block is named in its own body, so its local + # is declared before its value is made. + if this.c.checker.node_has(node, nf::function) { + val place := this.new_place(node, kind); + this.declare(node, place, false); + val mark := this.begin_statement(); + val made := this.value(value); + this.store(&place, &made); + this.end_statement(mark); + return; + } + + val mark := this.begin_statement(); + if value != 0 && this.refers_to_temporary(value) { + this.bound_temporary(node, value, kind, mark); + return; + } + # `undefined` leaves a cell as it is, and words, which cost nothing to give + # a value, are zero. Running with its memory checked, the cell is marked as + # never written, so reading it first stops the program. + if value != 0 && this.c.checker.kind_of(value) == nk::undefined { + val left := this.new_place(node, kind, ck::undefined); + if left.held { + this.zero(&left); + } else if this.c.options.checks { + this.build.forget(left.address, this.c.shape_of(kind).size); + } + this.end_statement(mark); + this.declare(node, left, false); + return; + } + val place := this.new_place(node, kind); + if value == 0 { + this.zero(&place); + this.defaults(&place); + } else { + val made := this.value_as(value, kind); + this.adopt(&made); + this.store(&place, &made); + } + this.end_statement(mark); + this.declare(node, place, this.c.checker.closes(kind)); +} + +#! Whether a value is a reference to a value that is no place, as +#! `&point { x = 1 }` or `&make()`, which the statement would hold. +#! @param this The emitter. +#! @param node The value's node. +#! @returns Whether it is. +def emitter::refers_to_temporary(&mut this, node: u32): bool { + return false if this.c.checker.kind_of(node) != nk::reference; + val inner := this.c.checker.left_of(node); + return false if this.c.checker.has_flag(node, rf::relent); + return !(this.c.checker.is_place(inner) && (!this.c.checker.is_known(inner) || this.stored(inner))); +} + +#! Lowers a local whose value is a reference to a value that is no place, which +#! lives as long as the name does, as C++ has a temporary bound to a reference: +#! held in a cell of its own, as a local declared just before the name is, and +#! closed just after the name is. +#! @param this The emitter. +#! @param node The `variable` node. +#! @param value The `reference` node. +#! @param kind The local's type. +#! @param mark What the statement held before. +def emitter::bound_temporary(&mut this, node: u32, value: u32, kind: u32, mark: statement_mark): void { + val taken := this.c.checker.type_at(value); + val referent := this.c.checker.types.first_of(this.c.checker.unalias(taken)); + val made := this.value_as(this.c.checker.left_of(value), referent); + this.adopt(&made); + val shape := this.c.shape_of(referent); + val cell := this.build.code.add_cell(round_up(shape.size == 0 ? word_size : shape.size, word_size) as u32, + shape.align < word_size ? word_size as u32 : shape.align as u32, ck::local, 0); + val held := location { kind = referent, address = this.build.cell_address(cell), framed = true }; + this.store(&held, &made); + val referred := this.reference_to(&held, taken); + val converted := this.convert(&referred, kind); + val place := this.new_place(node, kind); + this.store(&place, &converted); + this.end_statement(mark); + this.declare(value, held, this.c.checker.closes(referent)); + this.declare(node, place, this.c.checker.closes(kind)); +} + +#! Lowers `if`: the names its condition's tests give are declared before it runs, +#! and close where it ends, but those an `is not` test gives the rest of the +#! block where its branch always leaves. +#! @param this The emitter. +#! @param node The `if_stmt` node. +def emitter::if_statement(&mut this, node: u32): void { + val condition := this.c.checker.left_of(node); + val then := this.c.checker.record(node, if_slot::then); + val other := this.c.checker.record(node, if_slot::other); + val mark := this.begin_statement(); + val locals := this.scope_mark(); + this.declare_tests(condition); + + val then_block := this.build.new_block(); + val join := this.build.new_block(); + val else_block := other != 0 ? this.build.new_block() : join; + this.branch_on(condition, then_block, else_block); + this.lower_branches(then, other, then_block, else_block, join); + + # The names an `is not` test gives stay for the rest of the block, where the + # branch it guards always leaves. + val gives_rest := other == 0 && this.c.checker.has_flag(then, rf::leaves) && this.binds_where(condition, false); + if !gives_rest { + this.end_scope(locals, 0); + } + this.end_statement(mark); +} + +#! Lowers `if const`: the branch the checker decided it takes, or where only the +#! program running decides it, as in a generic's instance whose condition the +#! checker left unknown, both, by the condition's value. +#! @param this The emitter. +#! @param node The `if_const` node. +def emitter::if_const(&mut this, node: u32): void { + val condition := this.c.checker.left_of(node); + val then := this.c.checker.record(node, if_slot::then); + val other := this.c.checker.record(node, if_slot::other); + if this.c.checker.is_known(condition) { + val taken := this.c.checker.value_at(condition).magnitude != 0 ? then : other; + this.lower_block(taken); + return; + } + + # A condition evaluated decides the branch as one the checker decided does. + if this.c.evaluated.decisions.get(&node_key(this.table, node)) is some(holds) { + val taken := holds ? then : other; + this.lower_block(taken); + return; + } + + val mark := this.begin_statement(); + val then_block := this.build.new_block(); + val join := this.build.new_block(); + val else_block := other != 0 ? this.build.new_block() : join; + val cond := this.value_as(condition, bt::boolean); + this.build.branch(cond.words[0], then_block, else_block); + this.lower_branches(then, other, then_block, else_block, join); + this.end_statement(mark); +} + +#! Lowers the branches of an `if` its condition branched to, each going on +#! where they join, and goes on there. +#! @param this The emitter. +#! @param then The block taken where the condition holds. +#! @param other The one taken where it does not, or 0. +#! @param then_block Where the first begins. +#! @param else_block Where the second begins, or `join`. +#! @param join Where they join. +def emitter::lower_branches(&mut this, then: u32, other: u32, then_block: u32, else_block: u32, join: u32): void { + this.build.seal(then_block); + if other != 0 { + this.build.seal(else_block); + } + this.build.switch_to(then_block); + this.lower_block(then); + this.build.jump(join); + if other != 0 { + this.build.switch_to(else_block); + this.lower_block(other); + this.build.jump(join); + } + this.build.seal(join); + this.build.switch_to(join); +} + +#! Lowers `while`. Each pass, and each `continue`, closes what the condition +#! made, and the names its tests gave, before making them again. +#! @param this The emitter. +#! @param node The `while_stmt` node. +def emitter::while_statement(&mut this, node: u32): void { + val condition := this.c.checker.left_of(node); + val body := this.c.checker.right_of(node); + val head := this.build.new_block(); + val exit := this.build.new_block(); + val next := this.build.new_block(); + this.build.jump(head); + this.build.switch_to(head); + + val mark := this.begin_statement(); + val locals := this.scope_mark(); + this.declare_tests(condition); + val inside := this.build.new_block(); + this.branch_on(condition, inside, exit); + this.build.seal(inside); + + this.build.switch_to(inside); + this.safepoint(); + this.loops.append(loop_info { exit = exit, next = next, locals = this.locals.length, kept = this.kept.length }); + this.lower_block(body); + this.loops.truncate(); + this.build.jump(next); + this.build.seal(next); + + this.build.switch_to(next); + this.close_locals(locals, 0); + this.leave_kept(mark.kept); + + # A `break` leaves with the names the test gave, which close here, and what the + # condition made closes where the statement ends. + this.close_loop(head, exit); + this.end_scope(locals, 0); + this.end_statement(mark); +} + +#! Lowers `break` or `continue`: what the statements and scopes of the loop's +#! body hold is closed, and control goes to the loop's exit or its next pass. +#! @param this The emitter. +#! @param leaves Whether it is `break`. +def emitter::leave_loop(&mut this, leaves: bool): void { + return if this.loops.length == 0; + val held: loop_info = this.loops.last(); + this.leave_kept(held.kept); + this.close_locals(held.locals, 0); + this.build.jump(leaves ? held.exit : held.next); +} + +#! Lowers a condition as a branch: where it holds, to one block, and to another +#! where it does not. `&&` and `||` go to the second only where the first does +#! not decide. +#! @param this The emitter. +#! @param node The condition. +#! @param then Where it goes where the condition holds. +#! @param other Where it goes where it does not. +pub def emitter::branch_on(&mut this, node: u32, then: u32, other: u32): void { + if this.c.checker.is_known(node) { + this.build.jump(this.c.checker.value_at(node).magnitude != 0 ? then : other); + return; + } + if this.c.checker.kind_of(node) == nk::binary { + val operator := this.c.checker.token_kind(node); + if operator == tk::logand || operator == tk::logor { + val middle := this.build.new_block(); + if operator == tk::logand { + this.branch_on(this.c.checker.left_of(node), middle, other); + } else { + this.branch_on(this.c.checker.left_of(node), then, middle); + } + this.build.seal(middle); + this.build.switch_to(middle); + this.branch_on(this.c.checker.right_of(node), then, other); + return; + } + } + if this.c.checker.kind_of(node) == nk::unary && this.c.checker.token_kind(node) == tk::negate { + this.branch_on(this.c.checker.left_of(node), other, then); + return; + } + + val made := this.value_as(node, bt::boolean); + this.build.branch(made.words[0], then, other); +} + +#! Declares the locals the tests of a condition name their values in, before +#! any of it runs, since `&&` and `||` may leave a test that would set one +#! unrun. One that closes starts zeroed, so closing it where it was never given +#! closes nothing. +#! @param this The emitter. +#! @param node The condition. +pub def emitter::declare_tests(&mut this, node: u32): void { + return if node == 0; + match this.c.checker.kind_of(node) { + nk::is_test => { + val binding := this.c.checker.named_binding(this.c.checker.record(node, is_slot::binding)); + return if binding == 0; + val named := this.c.checker.kind_of(binding) == nk::reference ? this.c.checker.left_of(binding) : binding; + return if !this.c.checker.has_flag(named, rf::narrowed) || this.local_of(named) != 0; + val kind := this.c.checker.type_at(named); + val place := this.new_place(named, kind); + val closes := this.c.checker.closes(kind); + if closes { + this.zero(&place); + } + this.declare(named, place, closes); + } + nk::binary => { + val operator := this.c.checker.token_kind(node); + if operator == tk::logand || operator == tk::logor { + this.declare_tests(this.c.checker.left_of(node)); + this.declare_tests(this.c.checker.right_of(node)); + } + } + nk::unary => { + if this.c.checker.token_kind(node) == tk::negate { + this.declare_tests(this.c.checker.left_of(node)); + } + } + else => {} + } +} + +#! Whether a condition's tests name a value where it holds as `positive` says, +#! through `&&`, `||`, and `!`. +#! @param this The emitter. +#! @param node The condition. +#! @param positive Whether the condition holds where the value is named. +#! @returns Whether they do. +pub def emitter::binds_where(&mut this, node: u32, positive: bool): bool { + return false if node == 0; + match this.c.checker.kind_of(node) { + nk::is_test => { + return this.c.checker.named_binding(this.c.checker.record(node, is_slot::binding)) != 0 + && this.c.checker.node_has(node, nf::negated) != positive; + } + nk::binary => { + val operator := this.c.checker.token_kind(node); + return false if !((operator == tk::logand && positive) || (operator == tk::logor && !positive)); + return this.binds_where(this.c.checker.left_of(node), positive) + || this.binds_where(this.c.checker.right_of(node), positive); + } + nk::unary => { + return this.c.checker.token_kind(node) == tk::negate && this.binds_where(this.c.checker.left_of(node), !positive); + } + else => {} + } + return false; +} diff --git a/compiler/emitter/storage.sakura b/compiler/emitter/storage.sakura new file mode 100644 index 00000000..c4abd049 --- /dev/null +++ b/compiler/emitter/storage.sakura @@ -0,0 +1,246 @@ +#! @file storage.sakura +#! @author John Christman (sorakatadzuma@gmail.com) +#! @copyright Malunal Studios, LLC. +#! @license MIT +#! +#! Contains where a function's locals are held, worked out before its body is +#! lowered from where its references are made, as `escapes.sakura` finds it. A +#! local is held in variables of the builder unless a reference to it is made, +#! and then in a cell of the frame, which the reference refers to while the +#! local lives. Nothing is moved to the heap: a reference that outlives what it +#! refers to is the program's mistake, which the checker warns of where it is +#! sure of it. + +import sakura::analyzer; +module sakura::compiler; + + +#! Works out where the locals of a function's body are held, given what its +#! parameters are. +#! @param this The emitter. +#! @param decl The function's declaration. +#! @param params The run of its parameters' nodes. +#! @param kind Its function type, given its type arguments. +#! @param body The body's node. +pub def emitter::plan_function(&mut this, decl: u32, params: u32, kind: u32, body: u32): void { + var s := escape_scan::new(scratch()); + s.result = this.c.checker.types.first_of(kind); + this.c.scan_params(&mut s, params, kind, this.c.packs_last(decl)); + this.c.scan_body(&mut s, body); + this.apply_plan(&mut s, body); +} + +#! Works out where the locals of an anonymous function's body are held. What it +#! captures is the function's around it, reached through its environment, as +#! what a parameter refers to is the caller's. +#! @param this The emitter. +#! @param node The `lambda` node. +pub def emitter::plan_lambda(&mut this, node: u32): void { + var s := escape_scan::new(scratch()); + val kind := this.c.checker.type_at(node); + s.result = this.c.checker.types.first_of(kind); + var captures := this.captures_of(node); + for &each in captures { + val outer := s.graph.new_spot(spot_kind::outer, each, 0); + val inner := s.graph.new_spot(spot_kind::inner, each, 0); + s.graph.add(s.graph.held_by(outer), inner); + s.graph.add(s.graph.held_by(inner), inner); + s.slots.set(each, outer); + } + this.c.scan_params(&mut s, this.c.checker.left_of(node), kind, false); + val body := this.c.checker.record(node, lambda_slot::body); + this.c.scan_body(&mut s, body); + this.apply_plan(&mut s, body); +} + +#! Works out where the locals of a value evaluated into a global are held, +#! which keeps what it holds. +#! @param this The emitter. +#! @param value The value's node. +pub def emitter::plan_storage(&mut this, value: u32): void { + var s := escape_scan::new(scratch()); + s.graph.keep(this.c.value_flow(&mut s, value)); + this.apply_plan(&mut s, value); +} + +#! Holds in a cell each local a reference is made to. What is within an +#! anonymous function is left to its own plan. +#! @param this The emitter. +#! @param s The scan. +#! @param body The body scanned. +def emitter::apply_plan(&mut this, s: &mut escape_scan, body: u32): void { + for at in 0..s.graph.spots.length { + val held: spot = s.graph.spots[at]; + continue if held.depth != 0; + if held.kind == spot_kind::local && held.taken { + this.raise(held.node, held_as::cell); + } + } + this.check_plan(s, body); +} + +#! Holds in a cell any local a reference is made to that the scan did not see +#! made, which it always sees, so no reference refers to a local held in +#! variables: the operand of `&`, what a parameter taking a reference is given, +#! a method's receiver, the operands of an operator's method, what a loop +#! walks, a union a match names a field of by `&`, and what an anonymous +#! function captures. +#! @param this The emitter. +#! @param s The scan. +#! @param body The body scanned. +def emitter::check_plan(&mut this, s: &mut escape_scan, body: u32): void { + var walk := node_walk::new(body); + while walk.more() { + val at := walk.next(); + # A contract left out refers to nothing. + continue if this.c.checker.contracts_off && this.c.checker.kind_of(at) == nk::contract; + match this.c.checker.kind_of(at) { + nk::reference => { + val inner := this.c.checker.left_of(at); + if this.c.checker.is_place(inner) && (!this.c.checker.is_known(inner) || this.stored(inner)) { + this.check_taken(s, inner); + } + } + nk::lambda => { + var captures := this.captures_of(at); + for &each in captures { + this.check_local(s, each); + } + } + nk::member => { + # A property's accessors are given a reference to the value. + if this.property_of(at) != 0 { + this.check_taken(s, this.c.checker.left_of(at)); + } + } + nk::index => { + # So is `at`, but for what the language indexes itself. + val ref := this.c.checker.ref_at(at); + val through := this.c.checker.unalias(this.c.checker.reached(this.object_type(this.c.checker.left_of(at)))); + val kind := this.c.checker.types.kind_of(through); + if ref != 0 && (ref & (ref_local | ref_type)) == 0 && this.c.checker.decls.kinds.p[ref] == dk::function + && kind != ty::fixed && kind != ty::pointer && kind != ty::pack && this.c.viewed(through) == 0 { + this.check_taken(s, this.c.checker.left_of(at)); + } + } + nk::binary, nk::assign => { + if this.operator_method(at) != 0 { + this.check_taken(s, this.c.checker.left_of(at)); + this.check_taken(s, this.c.checker.right_of(at)); + } + } + nk::unary => { + val token := this.c.checker.token_kind(at); + if (token == tk::minus || token == tk::bitnot) && this.operator_decl(at) != 0 { + this.check_taken(s, this.c.checker.left_of(at)); + } + } + nk::for_stmt => { + val iterated := this.c.checker.record(at, for_slot::iterated); + val through := this.c.checker.unalias(this.c.checker.type_at(iterated)); + if this.c.checker.record(at, for_slot::end) == 0 && !this.c.checker.node_has(at, nf::constant) + && this.c.viewed(through) == 0 && this.c.checker.types.kind_of(through) != ty::pointer { + this.check_taken(s, iterated); + } + } + nk::is_test => { + val binding := this.c.checker.record(at, is_slot::binding); + if binding != 0 && this.c.checker.kind_of(binding) == nk::reference { + this.check_taken(s, this.c.checker.left_of(at)); + } + } + nk::match_stmt, nk::match_value => { + if this.c.refers_in_arm(at) { + this.check_taken(s, this.c.checker.left_of(at)); + } + } + else => {} + } + if this.c.checker.has_flag(at, rf::borrowed) { + this.check_taken(s, at); + } + if this.c.checker.kind_of(at) != nk::lambda { + this.c.scan_children(at, &mut walk); + } + } +} + +#! Holds in a cell the local whose own storage a place is within, past fields +#! and the elements of fixed arrays, where a reference to it is made that the +#! scan did not see. +#! @param this The emitter. +#! @param s The scan. +#! @param node The place's node. +def emitter::check_taken(&mut this, s: &mut escape_scan, node: u32): void { + var at := node; + var steps := 0; + while at != 0 && steps < 64 { + steps++; + val kind := this.c.checker.kind_of(at); + if kind == nk::member { + val ref := this.c.checker.ref_at(at); + return if ref == 0 || (ref & (ref_local | ref_type)) != 0 || this.c.checker.decls.kinds.p[ref] != dk::field; + val inner := this.c.checker.left_of(at); + return if this.c.is_reference_type(this.c.checker.type_at(inner)); + at = inner; + continue; + } + if kind == nk::index { + val inner := this.c.checker.left_of(at); + return if this.c.checker.types.kind_of(this.c.checker.unalias(this.c.checker.type_at(inner))) != ty::fixed; + at = inner; + continue; + } + break; + } + return if at == 0 || this.c.checker.kind_of(at) != nk::name; + val ref := this.c.checker.ref_at(at); + return if (ref & ref_local) == 0 || this.c.is_reference_type(this.c.checker.type_at(at)); + this.check_local(s, ref & ref_mask); +} + +#! Holds a local in a cell where the scan did not see a reference to it made. +#! @param this The emitter. +#! @param s The scan. +#! @param local The node declaring the local. +def emitter::check_local(&mut this, s: &mut escape_scan, local: u32): void { + if s.slots.get(&local) is some(at) { + return if s.graph.spots[at as u64].taken || s.graph.spots[at as u64].kind != spot_kind::local; + } + this.raise(local, held_as::cell); +} + +#! Holds a local at least as the way given: a cell over variables. +#! @param this The emitter. +#! @param local The node declaring the local. +#! @param how How it must be held. +def emitter::raise(&mut this, local: u32, how: held_as): void { + val held := this.storage.get_or(&local, held_as::words); + if (how as u8) > (held as u8) { + this.storage.set(local, how); + } +} + +#! The method an operator calls, where the language does not operate on its +#! operands itself: the one the checker chose for arithmetic, or the `equals` +#! or `compare` of what implements `equatable` or `ordered`, or 0. +#! @param this The emitter. +#! @param node The `binary` or `assign` node. +#! @returns The method's declaration, or 0. +pub def emitter::operator_method(&mut this, node: u32): u32 { + return 0 if this.c.checker.kind_of(node) == nk::unary; + val operator := this.c.checker.token_kind(node); + return 0 if operator == tk::logand || operator == tk::logor || operator == tk::assign; + val chosen := this.operator_decl(node); + return chosen if chosen != 0; + val kind := this.c.checker.type_at(this.c.checker.left_of(node)); + val plain := this.c.checker.unalias(this.c.layout_type(this.c.checker.read_type(kind))); + val named := this.c.checker.named_kind(plain); + return 0 if named != dk::struct_type && named != dk::union_type; + + if operator.compares() { + val equal := operator == tk::equals || operator == tk::noteq; + return this.pick_method(plain, equal ? word::equals : word::compare, true); + } + return 0; +} diff --git a/compiler/emitter/values.sakura b/compiler/emitter/values.sakura new file mode 100644 index 00000000..4a5572ba --- /dev/null +++ b/compiler/emitter/values.sakura @@ -0,0 +1,487 @@ +#! @file values.sakura +#! @author John Christman (sorakatadzuma@gmail.com) +#! @copyright Malunal Studios, LLC. +#! @license MIT +#! +#! Contains the lowering of expressions to their values: what each kind of +#! node gives, the constants the checker worked out, and the conversions the +#! checker recorded, by which a value of one type is taken where another is +#! expected. + +import sakura::analyzer; +module sakura::compiler; + + +#! The value of an expression as the type it is used as: the type the checker +#! converts it to, or its own. +#! @param this The emitter. +#! @param node The expression. +#! @returns The value. +pub def emitter::value(&mut this, node: u32): operand { + var to := this.c.checker.converted(node); + if this.c.checker.is_known(node) && this.c.is_scalar_type(to) { + # An integer constant past what an `i64` holds is unsigned, as `1 << 63` is. + val held := this.c.checker.value_at(node); + if this.c.checker.types.kind_of(to) == ty::untyped_int && !held.floating && !held.negative + && held.magnitude > 0x7FFFFFFFFFFFFFFF { + to = bt::uint64; + } + return this.known(&held, to); + } + val own := this.raw(node); + return this.convert(&own, to); +} + +#! The value of an expression as its own type, before any conversion. +#! @param this The emitter. +#! @param node The expression. +#! @returns The value. +pub def emitter::value_of_type(&mut this, node: u32): operand { + val own := this.c.checker.type_at(node); + if this.c.checker.is_known(node) && this.c.is_scalar_type(own) { + return this.known(&this.c.checker.value_at(node), own); + } + return this.raw(node); +} + +#! The value of an expression converted to a type. +#! @param this The emitter. +#! @param node The expression. +#! @param to The type. +#! @returns The value. +pub def emitter::value_as(&mut this, node: u32, to: u32): operand { + if this.c.checker.is_known(node) && this.c.is_scalar_type(to) { + return this.known(&this.c.checker.value_at(node), to); + } + val made := this.value(node); + return this.convert(&made, to); +} + +#! A constant the checker worked out, as a value of a type. +#! @param this The emitter. +#! @param value The constant. +#! @param kind The type, a number, `bool`, enum, or pointer. +#! @returns The value. +pub def emitter::known(&mut this, value: &constant, kind: u32): operand { + val held := this.c.shape_of(kind); + if held.kind == lk::floating { + var real := value.as_real(); + if held.bits <= 32 { + real = (real as f32) as f64; + } + return operand::one(kind, this.build.real(bits_of_real(real))); + } + var bits := value.floating ? (value.real < 0.0 ? 0 - ((0.0 - value.real) as u64) : value.real as u64) : value.bits(); + return operand::one(kind, this.build.word(bits)); +} + +#! The value of an expression as its own type, of each kind of node. What it +#! lowers is from the node, as what its operands lower is from theirs, and +#! what is lowered after it is from where it was before. +#! @param this The emitter. +#! @param node The expression. +#! @returns The value. +pub def emitter::raw(&mut this, node: u32): operand { + val saved := this.build.pos; + this.at_node(node); + val made := this.raw_node(node); + this.build.pos = saved; + return made; +} + +#! The value of an expression as its own type, by the kind of its node. +#! @param this The emitter. +#! @param node The expression. +#! @returns The value. +def emitter::raw_node(&mut this, node: u32): operand { + val kind := this.c.checker.type_at(node); + if this.c.checker.has_flag(node, rf::reflected) { + return this.reflected_value(node); + } + + match this.c.checker.kind_of(node) { + nk::number, nk::character, nk::boolean => return this.known(&this.c.checker.value_at(node), kind); + nk::string => { + # Text given to what is not text, as a union holding a view, is made as the + # view it settles as, which is then converted. + val to := this.c.checker.converted(node); + val own := this.c.is_string(to) || this.c.viewed(to) != 0 ? to : this.c.checker.settle(kind); + return this.text_literal(node, own); + } + nk::istring => return this.interpolated(node); + nk::null_lit => return this.zero_value(this.c.checker.converted(node)); + nk::name, nk::path => return this.name_value(node); + nk::unary => return this.unary(node); + nk::postfix => return this.step(node, this.c.checker.left_of(node), false); + nk::reference => return this.reference(node); + nk::binary => return this.binary(node); + nk::assign => return this.assign(node); + nk::ternary => return this.ternary(node); + nk::fallback => return this.fallback(node); + nk::call => { + val made := this.call(node); + this.keep(&made); + return made; + } + nk::index => { + if this.indexes_through_at(node) { + return this.indexed_reference(node); + } + val place := this.place_of(node); + return this.load(&place); + } + # `x.(d)` reads the field or property a description names. + nk::member_of => return this.member_value(node); + # `value_of(d)::` is the instance its type arguments make. + nk::type_args => return this.function_value(node, this.c.checker.ref_at(node)); + nk::slice => return this.slice(node); + nk::member => return this.member_value(node); + nk::cast => return this.cast(node); + nk::is_test => return this.is_test(node); + nk::construct => { + val made := this.construct(node); + this.keep(&made); + return made; + } + nk::array => { + val made := this.array_literal(node, this.c.checker.converted(node)); + this.keep(&made); + return made; + } + nk::lambda => return this.lambda_value(node); + nk::match_value => return this.match_value(node); + nk::range => return this.range_value(node); + # What `e` was is kept where its `ensures` was reached. + nk::old_value => { + val local := this.local_of(node); + if local != 0 { + val held: location = this.locals[local as u64 - 1].place; + return this.load(&held); + } + } + else => {} + } + this.problem(node, "The expression is not lowered."); + return this.zero_value(kind); +} + +#! The zero value of a type: zero words, or a zeroed cell. +#! @param this The emitter. +#! @param kind The type. +#! @returns The value. +pub def emitter::zero_value(&mut this, kind: u32): operand { + val held := this.c.shape_of(kind); + if in_memory(&held) { + val address := this.temporary_of(kind); + this.build.clear(address, held.size); + return operand::at(kind, address); + } + var made := operand { kind = kind, count = word_count(&held) }; + for i in 0..made.count { + made.words[i] = word_type(&held) == vt::real ? this.build.real(0) : this.build.word(0); + } + return made; +} + +#! The value a name or path gives: a local, a global, a constant, an enum +#! member, a constant parameter, or a function. +#! @param this The emitter. +#! @param node The `name` or `path` node. +#! @returns The value. +pub def emitter::name_value(&mut this, node: u32): operand { + val ref := this.c.checker.ref_at(node); + val kind := this.c.checker.type_at(node); + if (ref & ref_local) != 0 { + val place := this.place_of(node); + return this.load(&place); + } + if (ref & ref_type) != 0 { + return this.known_argument(ref & ref_mask, kind); + } + if ref == 0 { + this.problem(node, "The name refers to nothing."); + return this.zero_value(kind); + } + + match this.c.checker.decls.kinds.p[ref] { + dk::function => return this.function_value(node, ref); + dk::variable => { + val place := this.global_place(ref); + return this.load(&place); + } + dk::enum_member => { + var value := constant {}; + this.c.checker.decl_value(ref, &mut value); + return this.known(&value, kind); + } + else => {} + } + this.problem(node, "The name is no value."); + return this.zero_value(kind); +} + +#! The value of a constant type argument a constant parameter names. +#! @param this The emitter. +#! @param arg The type argument, a constant. +#! @param kind The type of its value. +#! @returns The value. +pub def emitter::known_argument(&mut this, arg: u32, kind: u32): operand { + if this.c.checker.types.kind_of(arg) != ty::value { + this.problem(0, "A constant parameter is given no value."); + return this.zero_value(kind); + } + return this.known_object(this.c.checker.types.second_of(arg), kind); +} + +#! A value the checker worked out, as a value of a type: a number, text, a +#! struct, union, or array of them, `null`, a function, or the address of a +#! constant. +#! @param this The emitter. +#! @param id The value's ID among the checker's known values. +#! @param kind The type. +#! @returns The value. +pub def emitter::known_object(&mut this, id: u32, kind: u32): operand { + val held: known = this.c.checker.known_at(id); + val shape := this.c.shape_of(kind); + match held.kind { + kk::number, kk::real => return this.known(&held.value, kind); + kk::null_lit => return this.zero_value(kind); + kk::text => return this.text_value(this.c.checker.known_text(id), kind); + kk::function => { + val index := this.c.function_of(held.decl, 0); + this.c.program.functions[index].taken = true; + this.c.names(this.function, index); + return operand::two(kind, this.build.word(index as u64 + 1), this.build.word(0)); + } + kk::address => { + val place := this.global_place(held.decl); + return this.reference_to(&place, kind); + } + kk::fields => { + val address := this.temporary_of(kind); + this.build.clear(address, shape.size); + val whole := location { kind = kind, address = address, framed = true }; + val plain := this.c.checker.unalias(kind); + if shape.kind == lk::fixed { + val element := this.c.checker.types.first_of(plain); + val inner := this.c.shape_of(element); + for i in 0..this.c.checker.known_count(id) { + val part := this.known_object(this.c.checker.known_part(id, i as u32), element); + val at := this.within(&whole, i as u64 * inner.size, element); + this.store(&at, &part); + } + return operand::at(kind, address); + } + val index := this.c.layout_of(plain); + for i in 0..this.c.checker.known_count(id) { + break if i >= shape.count as u64; + val field := this.c.field_at(index, i as u32); + val part := this.known_object(this.c.checker.known_part(id, i as u32), field.type_id); + val at := this.within(&whole, field.offset, field.type_id); + this.store(&at, &part); + } + return operand::at(kind, address); + } + kk::held => { + val address := this.temporary_of(kind); + this.build.clear(address, shape.size); + val tag := held.value.magnitude as u32; + if shape.niche == 0 { + this.build.store(access::i64, address, 0, this.build.word(tag as u64)); + } + val index := this.c.layout_of(this.c.checker.unalias(kind)); + if tag < shape.count && this.c.checker.known_count(id) != 0 { + val field := this.c.field_at(index, tag); + val part := this.known_object(this.c.checker.known_part(id, 0), field.type_id); + val at := location { kind = field.type_id, address = address, offset = field.offset, framed = true }; + this.store(&at, &part); + } + return operand::at(kind, address); + } + else => {} + } + this.problem(0, "A constant argument is not worked out."); + return this.zero_value(kind); +} + +#! The value text written as a literal is, as the type it is used as: a view of +#! the bytes it was written with, which stand as long as the program runs, or a +#! `string` holding a copy of them it owns. +#! @param this The emitter. +#! @param node The `string` node. +#! @param kind The type it is used as. +#! @returns The value. +pub def emitter::text_literal(&mut this, node: u32, kind: u32): operand { + var text := string::new(nothing {}); + this.decode_literal(this.c.checker.text_of(node), &mut text); + return this.text_value(text.view(), kind); +} + +#! Text as a value of a type: a view of a datum holding its bytes, or a +#! `string` holding a copy of them. +#! @param this The emitter. +#! @param text The bytes. +#! @param kind The type: a view of bytes, or `string`. +#! @returns The value. +pub def emitter::text_value(&mut this, text: strview, kind: u32): operand { + val datum := this.c.text_datum(text); + if this.c.is_string(kind) { + this.build.effect(op::format, span::::empty(), 0, 0); + this.build.effect(op::format_text, span::::empty(), datum, 0); + return this.owned_text(kind); + } + + val address := this.temporary_of(kind); + val data := text.length == 0 ? this.build.word(0) : this.build.value(op::datum, span::::empty(), vt::word, datum, 0); + this.build.store(access::i64, address, 0, data); + this.build.store(access::i64, address, word_size, this.build.word(text.length)); + return operand::at(kind, address); +} + +#! A value of a type taken as another, as the checker converts it: widened, +#! read through references, given to a union, referred to as a trait, or lent +#! as a view. +#! @param this The emitter. +#! @param value The value. +#! @param to The type it is taken as. +#! @returns The value converted. +pub def emitter::convert(&mut this, value: &operand, to: u32): operand { + var made: operand = value; + return made if value.kind == to || to == bt::error || to == 0 || value.kind == bt::error; + + val from := this.c.layout_type(value.kind); + val target := this.c.layout_type(to); + made.kind = to; + return made if from == target || this.c.checker.strip(from, 0) == this.c.checker.strip(target, 0); + + val fk := this.c.checker.types.kind_of(from); + val tok := this.c.checker.types.kind_of(target); + + # Numbers widen within their kind, which their words already hold, and an + # integer operating with a float operates as the float. + if this.c.checker.types.is_numeric(from) && this.c.checker.types.is_numeric(target) { + if this.c.checker.types.is_float(target) && !this.c.checker.types.is_float(from) { + val signed := this.c.checker.types.is_signed(from); + var real := this.build.unary(signed ? op::itof : op::utof, value.words[0]); + if this.c.checker.types.first_of(target) <= 32 { + real = this.build.unary(op::fsingle, real); + } + return operand::one(to, real); + } + return made; + } + + # An enum is its integer. + if this.c.checker.named_kind(from) == dk::enum_type && this.c.checker.types.is_integer(target) { + return made; + } + + if fk == ty::reference && tok == ty::reference { + val inner_from := this.c.checker.unalias(this.c.checker.types.first_of(from)); + val inner_to := this.c.checker.unalias(this.c.checker.types.first_of(target)); + val from_trait := this.c.checker.named_kind(inner_from) == dk::trait_type; + val to_trait := this.c.checker.named_kind(inner_to) == dk::trait_type; + + # A reference to a value becomes one to a trait it implements, given the + # vtable of its type for the trait. + if to_trait && !from_trait && this.c.checker.types.kind_of(inner_from) != ty::reference { + val vtable := this.c.vtable_of(this.c.checker.types.first_of(from), inner_to); + return operand::two(to, value.words[0], this.build.word(vtable as u64)); + } + # A reference to a trait becomes one to another the value also implements. + if to_trait && from_trait { + return made if inner_from == inner_to; + var args: u32[1] = [value.words[1]]; + val map := this.c.retrait_of(inner_from, inner_to); + val vtable := this.build.value(op::retrait, args[0:1], vt::word, map, 0); + return operand::two(to, value.words[0], vtable); + } + # A reference to a reference is read through to the one it holds. + if this.c.checker.types.kind_of(inner_from) == ty::reference && this.c.checker.types.kind_of(inner_to) != ty::reference { + val place := this.referent(value); + val inner := this.load(&place); + return this.convert(&inner, to); + } + return made; + } + + # A union holds a value as the field of its type, another union's too, and + # a reference where one of its fields is one; and otherwise a reference is + # read through first. + if this.c.checker.named_kind(target) == dk::union_type && this.c.checker.united_field(value.kind, target) != 0 { + return this.unite(value, target, to); + } + + # A reference written as one becomes a pointer at what it refers to, which + # holds the same word. + if fk == ty::reference && tok == ty::pointer + && this.c.checker.unalias(this.c.checker.types.first_of(from)) == this.c.checker.unalias(this.c.checker.types.first_of(target)) { + return made; + } + + # A plain reference is read through where its value is expected. + if fk == ty::reference { + val place := this.referent(value); + val inner := this.load(&place); + return this.convert(&inner, to); + } + + # Bytes become a string by being copied, which the statement keeps, from the + # view's two words wherever they are. + if this.c.is_string(target) && this.c.checker.is_byte_view(from) && (value.address != 0 || value.count == 2) { + var args: u32[2] = [0, 0]; + if value.address != 0 { + args[0] = this.build.load(access::i64, value.address, 0); + args[1] = this.build.load(access::i64, value.address, word_size); + } else { + args[0] = value.words[0]; + args[1] = value.words[1]; + } + this.build.effect(op::format, span::::empty(), 0, 0); + this.build.effect(op::format_bytes, args[0:2], 0, 0); + return this.owned_text(to); + } + + # A string lends a view of its text: where its bytes begin, and how many. + if this.c.is_string(from) && this.c.viewed(target) != 0 { + val index := this.c.layout_of(from); + val data := this.c.field_at(index, 1); + val count := this.c.field_at(index, 2); + val address := this.temporary_of(to); + this.build.store(access::i64, address, 0, this.build.load(access::i64, value.address, data.offset)); + this.build.store(access::i64, address, word_size, this.build.load(access::i64, value.address, count.offset)); + return operand::at(to, address); + } + + # What else converts holds the same words: a writable view lending a + # read-only one, a function by another name, `null` becoming a pointer. + return made; +} + +#! A union holding a value, as the field the checker finds of its type. +#! @param this The emitter. +#! @param value The value. +#! @param target The union's type, without aliases. +#! @param to The type it is taken as. +#! @returns The union. +pub def emitter::unite(&mut this, value: &operand, target: u32, to: u32): operand { + val field := this.c.checker.united_field(value.kind, target); + val index := this.c.layout_of(target); + val shape := this.c.layout_at(index); + val address := this.temporary_of(to); + this.build.clear(address, shape.size); + for i in 0..shape.count { + val each := this.c.field_at(index, i as u32); + continue if each.decl != field; + if shape.niche == 0 { + this.build.store(access::i64, address, 0, this.build.word(i)); + } + val held := this.convert(value, each.type_id); + val at := location { kind = each.type_id, address = address, offset = each.offset, framed = true }; + this.store(&at, &held); + this.adopt(value); + return operand::at(to, address); + } + this.problem(0, "A union holds no field of the value's type."); + return operand::at(to, address); +} diff --git a/compiler/escapes.sakura b/compiler/escapes.sakura new file mode 100644 index 00000000..926a13e0 --- /dev/null +++ b/compiler/escapes.sakura @@ -0,0 +1,1949 @@ +#! @file escapes.sakura +#! @author John Christman (sorakatadzuma@gmail.com) +#! @copyright Malunal Studios, LLC. +#! @license MIT +#! +#! Contains the scan of a body for where the references it makes, and those it +#! is given, may go: the flows `flows.sakura` solves, found from the checked +#! syntax as lowering would lower it. Each local is a spot, and so is a value a +#! statement holds where a reference to it is taken, the environment of an +#! anonymous function capturing locals, and what the caller gives each +#! parameter. An expression gives the set of spots its value may hold +#! references to, or none where its type holds no reference, and a place gives +#! the set of spots it may lie within. +#! +#! A call gives each argument where the summary of the function called says, +#! as `keeps.sakura` works it out: kept, given back in what the call gives, or +#! neither; and what the argument reaches likewise. What the scan does not +#! know, as a call of a function value, keeps what it is given and gives back +#! what any code may reach. Calling a function value keeps nothing of it, since +#! its body was scanned where it was made. That body is scanned there, sharing +#! the spots of the locals it captures, with what it is given and gives back +#! being anyone's. +#! +#! Pointers are left out: one made of a reference keeps nothing alive, as it is +#! good only while what it points at is where it is, but what that holds may be +#! read through it by any code, and so is kept. + +import sakura::analyzer; +import std::containers; +module sakura::compiler; + + +#! What a scan of a body holds as it goes. +pub struct escape_scan { + var graph: flow; #! The flows found. + var slots: dict; #! The spot of each local, by the node declaring it. + var temps: dict; #! The spot of each value a statement holds that a reference refers to, by the node it is held for. + var envs: dict; #! The spot of the environment of each anonymous function capturing locals, by its node. + var outers: vector; #! Of each parameter, the spot of what it refers to, or 0 where it takes a value. + var inners: vector; #! Of each parameter, the spot of what the caller's reference or value reaches, or 0. + var returns: u32; #! The set what `return` gives flows into. + var result: u32; #! The type `return` gives. + var within: vector; #! The anonymous functions the scan is within, each as `pair_key(lowest, node)` of its nodes. +} + +#! Makes a scan, which has found nothing yet. +#! @param alloc The optional allocator its memory is taken from. +#! @returns The scan. +pub def escape_scan::new(alloc: maybe<&mut allocator>): escape_scan { + var made := escape_scan { + graph = flow::new(alloc), + slots = dict::::new(alloc), + temps = dict::::new(alloc), + envs = dict::::new(alloc), + outers = vector::::new(alloc), + inners = vector::::new(alloc), + within = vector::::new(alloc) + }; + made.returns = made.graph.given; + return made; +} + +# Spots. + +#! The spot of a local, made where it is new, as deep within anonymous +#! functions as it is declared. +#! @param this The compiler. +#! @param s The scan. +#! @param local The node declaring the local. +#! @returns The spot. +pub def lowerer::slot_of(&mut this, s: &mut escape_scan, local: u32): u32 { + if s.slots.get(&local) is some(got) { + return got; + } + var depth: u32 = 0; + for &each in s.within { + if pair_high(each) <= local && local <= pair_low(each) { + depth++; + } + } + val made := s.graph.new_spot(spot_kind::local, local, depth); + s.slots.set(local, made); + return made; +} + +#! The place of a local's storage, as a set, noting where a reference to it is +#! made. +#! @param this The compiler. +#! @param s The scan. +#! @param local The node declaring the local. +#! @param refers Whether a reference to the place is made, rather than what it +#! holds read or written. +#! @returns The set. +def lowerer::local_place(&mut this, s: &mut escape_scan, local: u32, refers: bool): u32 { + val at := this.slot_of(s, local); + if refers { + s.graph.spots[at as u64].taken = true; + } + return s.graph.alone(at); +} + +#! A reference to a value a statement holds for a node, as a set: the spot it +#! is held in, made where it is new, holding the value. +#! @param this The compiler. +#! @param s The scan. +#! @param node The node it is held for. +#! @param value The set of the value, or 0. +#! @returns The set. +def lowerer::temp_place(&mut this, s: &mut escape_scan, node: u32, value: u32): u32 { + var at: u32 = 0; + if s.temps.get(&node) is some(got) { + at = got; + } else { + at = s.graph.new_spot(spot_kind::temp, node, s.within.length as u32); + s.temps.set(node, at); + } + s.graph.into(value, s.graph.held_by(at)); + return s.graph.alone(at); +} + +#! A set of what any code may reach, or none where the type holds no reference. +#! @param this The compiler. +#! @param s The scan. +#! @param kind The type. +#! @returns The set, or 0. +def lowerer::shared_flow(&mut this, s: &mut escape_scan, kind: u32): u32 { + return 0 if !this.holds_references(kind); + return s.graph.alone(s.graph.shared); +} + +#! Whether a value of a type may hold a reference: a reference, a function +#! value, which holds its environment, or what holds one of those. A type still +#! open, as a parameter of a generic, may. +#! @param this The compiler. +#! @param kind The type. +#! @returns Whether it may. +pub def lowerer::holds_references(&mut this, kind: u32): bool { + return false if kind == 0 || kind == bt::error; + val plain := this.layout_type(kind); + val held := this.checker.types.kind_of(plain); + return true if held == ty::param || held == ty::pack; + return held != ty::void_type && this.shape_of(plain).pointers; +} + +# Parameters. + +#! Gives the scan the parameters of a function: each a local holding what the +#! caller gives, a reference to what is the caller's, or a value whose +#! references reach what is the caller's, and given its default where it has +#! one, which a call leaving it out gives it. +#! @param this The compiler. +#! @param s The scan. +#! @param params The run of the parameters' nodes. +#! @param kind The function's type. +#! @param packed Whether the last parameter is a pack, taking every parameter from its own on. +pub def lowerer::scan_params(&mut this, s: &mut escape_scan, params: u32, kind: u32, packed: bool): void { + val count := this.checker.types.part_count(kind); + val written := this.checker.run_length(params); + for i in 0..written { + val param := this.checker.run_at(params, i as u32); + val slot := this.slot_of(s, param); + # What a pack holds, and what the type leaves out, is taken as anyone's. + if i >= count as u64 || (packed && i + 1 == written as u64) { + s.graph.add(s.graph.held_by(slot), s.graph.shared); + s.outers.append(0); + s.inners.append(0); + continue; + } + val taken := this.checker.types.part_at(kind, i as u32); + val inner := s.graph.new_spot(spot_kind::inner, param, 0); + s.graph.add(s.graph.held_by(inner), inner); + if this.is_reference_type(taken) { + val outer := s.graph.new_spot(spot_kind::outer, param, 0); + s.graph.add(s.graph.held_by(outer), inner); + s.graph.add(s.graph.held_by(slot), outer); + s.outers.append(outer); + } else { + if this.holds_references(taken) { + s.graph.add(s.graph.held_by(slot), inner); + } + s.outers.append(0); + } + s.inners.append(inner); + val value := this.checker.record(param, parameter_slot::value); + if value != 0 { + s.graph.into(this.value_flow_as(s, value, taken), s.graph.held_by(slot)); + } + } +} + +# Statements. + +#! Scans a body: a block, or an expression whose value is returned. +#! @param this The compiler. +#! @param s The scan. +#! @param body The body's node. +pub def lowerer::scan_body(&mut this, s: &mut escape_scan, body: u32): void { + return if body == 0; + if this.checker.kind_of(body) == nk::block { + this.scan_block(s, body); + return; + } + s.graph.into(this.value_flow_as(s, body, s.result), s.returns); +} + +#! Scans a block, or a statement standing for one, up to a statement after +#! which the checker checked nothing. +#! @param this The compiler. +#! @param s The scan. +#! @param node The block. +pub def lowerer::scan_block(&mut this, s: &mut escape_scan, node: u32): void { + return if node == 0; + if this.checker.kind_of(node) != nk::block { + this.scan_statement(s, node); + return; + } + val run := this.checker.left_of(node); + for i in 0..this.checker.run_length(run) { + val each := this.checker.run_at(run, i as u32); + this.scan_statement(s, each); + break if this.statement_skips(each); + } +} + +#! Has a walk go under a node to what a scan walks: all but the bodies of +#! anonymous functions, which are planned as functions of their own, and of an +#! `if const` or `when` only the branch taken. +#! @param this The compiler. +#! @param node The node. +#! @param walk The walk. +pub def lowerer::scan_children(&mut this, node: u32, walk: &mut node_walk): void { + match this.checker.kind_of(node) { + nk::lambda => return; + nk::when_block => { + walk.add(this.checker.when_branch(node)); + return; + } + nk::if_const => { + val condition := this.checker.left_of(node); + if this.checker.is_known(condition) { + walk.add(this.checker.value_at(condition).magnitude != 0 ? this.checker.record(node, if_slot::then) : this.checker.record(node, if_slot::other)); + return; + } + if this.evaluated.decisions.get(&node_key(this.checker.at.table, node)) is some(holds) { + walk.add(holds ? this.checker.record(node, if_slot::then) : this.checker.record(node, if_slot::other)); + return; + } + } + else => {} + } + walk.enter(this.checker.syn(), node); +} + +#! Whether a statement leaves where it was decided while checking, so the +#! checker checked nothing after it, as `emitter::skips` says. +#! @param this The compiler. +#! @param node The statement. +#! @returns Whether it does. +def lowerer::statement_skips(&mut this, node: u32): bool { + match this.checker.kind_of(node) { + nk::block => { + val run := this.checker.left_of(node); + for i in 0..this.checker.run_length(run) { + return true if this.statement_skips(this.checker.run_at(run, i as u32)); + } + } + nk::when_block => return this.statement_skips(this.checker.when_branch(node)); + nk::if_const => { + val condition := this.checker.left_of(node); + return false if !this.checker.is_known(condition); + val then := this.checker.record(node, if_slot::then); + val other := this.checker.record(node, if_slot::other); + if this.checker.value_at(condition).magnitude != 0 { + return this.statement_skips(then) || (other == 0 && this.checker.has_flag(then, rf::leaves)); + } + return other != 0 && this.statement_skips(other); + } + else => {} + } + return false; +} + +#! Scans a statement. +#! @param this The compiler. +#! @param s The scan. +#! @param node The statement. +def lowerer::scan_statement(&mut this, s: &mut escape_scan, node: u32): void { + match this.checker.kind_of(node) { + nk::block => this.scan_block(s, node); + nk::variable => this.scan_variable(s, node); + nk::if_stmt => { + this.value_flow(s, this.checker.left_of(node)); + this.scan_block(s, this.checker.record(node, if_slot::then)); + this.scan_block(s, this.checker.record(node, if_slot::other)); + } + nk::if_const => { + val condition := this.checker.left_of(node); + val then := this.checker.record(node, if_slot::then); + val other := this.checker.record(node, if_slot::other); + if this.checker.is_known(condition) { + this.scan_block(s, this.checker.value_at(condition).magnitude != 0 ? then : other); + return; + } + if this.evaluated.decisions.get(&node_key(this.checker.at.table, node)) is some(holds) { + this.scan_block(s, holds ? then : other); + return; + } + this.value_flow(s, condition); + this.scan_block(s, then); + this.scan_block(s, other); + } + nk::when_block => this.scan_block(s, this.checker.when_branch(node)); + nk::while_stmt => { + this.value_flow(s, this.checker.left_of(node)); + this.scan_block(s, this.checker.right_of(node)); + } + nk::for_stmt => this.scan_for(s, node); + nk::match_stmt => this.match_flow(s, node, false); + nk::return_stmt => { + val value := this.checker.left_of(node); + if value != 0 { + s.graph.into(this.value_flow_as(s, value, s.result), s.returns); + } + } + nk::break_stmt, nk::continue_stmt => {} + nk::expr_stmt => this.value_flow(s, this.checker.left_of(node)); + nk::contract => this.contract_flow(s, node); + else => this.unknown_flow(s, node); + } +} + +#! Scans a contract, where contracts are checked: its condition and what it +#! says failed are values made where it is, and the name an `ensures` gives +#! what is returned may hold what any code may reach. One left out makes +#! nothing. +#! @param this The compiler. +#! @param s The scan. +#! @param node The `contract` node. +def lowerer::contract_flow(&mut this, s: &mut escape_scan, node: u32): void { + return if this.checker.contracts_off; + val bound := this.checker.record(node, contract_slot::bound); + if bound != 0 && this.holds_references(this.checker.type_at(bound)) { + s.graph.add(s.graph.held_by(this.slot_of(s, bound)), s.graph.shared); + } + this.value_flow(s, this.checker.left_of(node)); + this.value_flow(s, this.checker.record(node, contract_slot::text)); +} + +#! Scans a local variable or constant: its storage holds what it is given. A +#! constant is no local but a value known while compiling, or data evaluated +#! while compiling, which any code may reach. +#! @param this The compiler. +#! @param s The scan. +#! @param node The `variable` node. +def lowerer::scan_variable(&mut this, s: &mut escape_scan, node: u32): void { + val value := this.checker.record(node, variable_slot::value); + val kind := this.checker.type_at(node); + if this.checker.node_has(node, nf::constant) { + s.slots.set(node, s.graph.shared); + return; + } + # A function declared within a block names its own local, which is made first. + val slot := this.slot_of(s, node); + if value == 0 { + # The defaults of its fields are made where its type is declared. + if this.holds_references(kind) { + s.graph.add(s.graph.held_by(slot), s.graph.shared); + } + return; + } + s.graph.into(this.value_flow_as(s, value, kind), s.graph.held_by(slot)); +} + +#! Scans what a node holds as values that are kept, as for a node the scan does +#! not know. +#! @param this The compiler. +#! @param s The scan. +#! @param node The node. +def lowerer::unknown_flow(&mut this, s: &mut escape_scan, node: u32): void { + var held := vector::::new(); + this.checker.syn().children(node, &mut held); + for &each in held { + continue if each == 0; + if this.checker.has_flag(each, rf::borrowed) { + s.graph.keep(this.lent_flow(s, each)); + } + s.graph.keep(this.value_flow(s, each)); + } +} + +# Loops. + +#! Scans `for`: a range counts, the elements of a fixed array or a view are each +#! referred to where they are, and an iterator is asked for each, lent by what +#! is walked where that is no iterator. +#! @param this The compiler. +#! @param s The scan. +#! @param node The `for_stmt` node. +def lowerer::scan_for(&mut this, s: &mut escape_scan, node: u32): void { + val iterated := this.checker.record(node, for_slot::iterated); + val end := this.checker.record(node, for_slot::end); + val variable := this.checker.record(node, for_slot::variable); + val body := this.checker.right_of(node); + if this.checker.node_has(node, nf::constant) { + this.unrolled_flow(s, node); + return; + } + if end != 0 { + this.value_flow(s, iterated); + this.value_flow(s, end); + this.scan_block(s, body); + return; + } + + val through := this.checker.unalias(this.checker.reached(this.checker.type_at(iterated))); + if this.checker.types.kind_of(through) == ty::fixed || this.viewed(through) != 0 { + val fixed := this.checker.types.kind_of(through) == ty::fixed; + val whole := this.object_flow(s, iterated, fixed); + val element := fixed ? whole : s.graph.alone(s.graph.shared); + if variable != 0 { + val slot := this.slot_of(s, variable); + val bound := this.checker.type_at(variable); + val given := this.is_reference_type(bound) ? element : s.graph.read_of(element); + if this.holds_references(bound) { + s.graph.into(given, s.graph.held_by(slot)); + } + } + this.scan_block(s, body); + return; + } + + # The iterator, where it is: what the loop is given, or what `iter` lends, + # which the loop holds. + var cursor: u32 = 0; + var cursor_type := through; + if !this.checker.has_method(through, word::next) { + val lends := this.checker.pick_iter(through, this.checker.node_has(node, nf::mutable)); + val receiver := this.is_reference_type(this.checker.type_at(iterated)) ? this.through_one_flow(s, iterated) : this.lent_flow(s, iterated); + val instance := this.method_instance(lends, through); + val lent_kind := this.method_kind(lends, instance, through); + val made := this.method_flow(s, lends, through, receiver); + cursor_type = this.checker.unalias(this.checker.types.first_of(lent_kind)); + cursor = this.temp_place(s, node, made); + } else if this.is_reference_type(this.checker.type_at(iterated)) { + cursor = this.through_one_flow(s, iterated); + } else if this.checker.is_place(iterated) { + cursor = this.place_flow(s, iterated, true); + } else { + cursor = this.temp_place(s, node, this.raw_flow(s, iterated)); + } + + # `next` gives `some` of each element, bound as the variable's type takes it. + val next := this.checker.find_member(cursor_type, word::next).decl; + val given := this.method_flow(s, next, cursor_type, cursor); + if variable != 0 && given != 0 { + val slot := this.slot_of(s, variable); + val bound := this.checker.type_at(variable); + val element := this.payload_type(this.checker.types.first_of(this.method_kind(next, this.method_instance(next, cursor_type), cursor_type))); + s.graph.into(this.converted_flow(s, given, element, bound), s.graph.held_by(slot)); + } + this.scan_block(s, body); +} + +#! The type a `maybe` holds as `some`, or the type itself where it is none. +#! @param this The compiler. +#! @param kind The type. +#! @returns The type held. +def lowerer::payload_type(&mut this, kind: u32): u32 { + val plain := this.checker.unalias(kind); + return kind if this.checker.named_kind(plain) != dk::union_type; + val index := this.layout_of(plain); + for i in 0..this.layout_at(index).count { + val field := this.field_at(index, i as u32); + return field.type_id if field.name == word::some; + } + return kind; +} + +#! Scans `for const`: the body the checker checked once for each value of a pack, +#! or each declaration reflection gives, each in a result table of its own. The +#! variable is the pack's value itself, which is taken as anyone's, or a local +#! holding the description of the pass, which is data. +#! @param this The compiler. +#! @param s The scan. +#! @param node The `for_stmt` node. +def lowerer::unrolled_flow(&mut this, s: &mut escape_scan, node: u32): void { + val variable := this.checker.record(node, for_slot::variable); + val iterated := this.checker.record(node, for_slot::iterated); + val body := this.checker.right_of(node); + val outer := this.checker.at.table; + val pack := this.checker.unalias(this.checker.reached(this.checker.type_at(iterated))); + if variable != 0 { + if this.checker.types.kind_of(pack) == ty::pack { + s.slots.set(variable, s.graph.shared); + } else { + s.graph.add(s.graph.held_by(this.slot_of(s, variable)), s.graph.shared); + } + } + for t in 0..this.checker.tables.length { + val held: rtable = this.checker.tables.p[t]; + continue if held.parent != outer + 1 || held.base != variable || held.count != body - variable + 1; + this.checker.use_table(t as u32); + this.scan_block(s, body); + this.checker.use_table(outer); + } +} + +# Values. + +#! The value of an expression as the type it is used as. +#! @param this The compiler. +#! @param s The scan. +#! @param node The expression, or 0. +#! @returns The set of its value, or 0. +pub def lowerer::value_flow(&mut this, s: &mut escape_scan, node: u32): u32 { + return 0 if node == 0; + val own := this.raw_flow(s, node); + return this.converted_flow(s, own, this.checker.type_at(node), this.checker.converted(node)); +} + +#! The value of an expression converted to a type. +#! @param this The compiler. +#! @param s The scan. +#! @param node The expression, or 0. +#! @param to The type. +#! @returns The set of its value, or 0. +pub def lowerer::value_flow_as(&mut this, s: &mut escape_scan, node: u32, to: u32): u32 { + return 0 if node == 0; + val made := this.value_flow(s, node); + return this.converted_flow(s, made, this.checker.converted(node), to); +} + +#! What converting a value gives, as `emitter::convert` converts it: a +#! reference is read through where a value is wanted, but kept as it is by a +#! union holding it, and anything else holds what it held. +#! @param this The compiler. +#! @param s The scan. +#! @param set The value's set, or 0. +#! @param from Its type. +#! @param to The type converted to. +#! @returns The set, or 0. +def lowerer::converted_flow(&mut this, s: &mut escape_scan, set: u32, from: u32, to: u32): u32 { + return 0 if set == 0 || !this.holds_references(to); + return set if to == from || to == bt::error || from == 0 || from == bt::error; + var at := set; + var kind := from; + var steps := 0; + while steps < 16 { + steps++; + val source := this.layout_type(kind); + val target := this.layout_type(to); + return at if source == target; + val fk := this.checker.types.kind_of(source); + val tok := this.checker.types.kind_of(target); + if fk == ty::reference && tok == ty::reference { + val inner_from := this.checker.unalias(this.checker.types.first_of(source)); + val inner_to := this.checker.unalias(this.checker.types.first_of(target)); + return at if this.checker.types.kind_of(inner_from) != ty::reference || this.checker.types.kind_of(inner_to) == ty::reference; + at = s.graph.read_of(at); + kind = inner_from; + continue; + } + if this.checker.named_kind(target) == dk::union_type && this.checker.united_field(kind, target) != 0 { + return at; + } + if fk == ty::reference { + at = s.graph.read_of(at); + kind = this.checker.types.first_of(source); + continue; + } + return at; + } + return at; +} + +#! The value of an expression as its own type, by the kind of its node. +#! @param this The compiler. +#! @param s The scan. +#! @param node The expression. +#! @returns The set of its value, or 0. +pub def lowerer::raw_flow(&mut this, s: &mut escape_scan, node: u32): u32 { + return 0 if node == 0; + val kind := this.checker.type_at(node); + # What reflection gives is worked out while compiling, from what any code may reach. + if this.checker.has_flag(node, rf::reflected) { + return this.shared_flow(s, kind); + } + if this.checker.is_known(node) && this.is_scalar_type(kind) { + return 0; + } + + match this.checker.kind_of(node) { + nk::number, nk::character, nk::boolean, nk::string, nk::null_lit, nk::undefined => return 0; + nk::istring => { + # Each hole is written by its layout, which keeps nothing. + val run := this.checker.left_of(node); + for i in 0..this.checker.run_length(run) { + this.value_flow(s, this.checker.run_at(run, i as u32)); + } + return 0; + } + nk::name, nk::path => return this.name_flow(s, node); + nk::unary => return this.unary_flow(s, node); + nk::postfix => { + this.step_flow(s, this.checker.left_of(node)); + return 0; + } + nk::reference => return this.reference_flow(s, node); + nk::binary => return this.binary_flow(s, node); + nk::assign => return this.assign_flow(s, node); + nk::ternary => { + this.value_flow(s, this.checker.left_of(node)); + val a := this.value_flow_as(s, this.checker.record(node, if_slot::then), kind); + val b := this.value_flow_as(s, this.checker.record(node, if_slot::other), kind); + return s.graph.either(a, b); + } + nk::fallback => return this.fallback_flow(s, node); + nk::call => return this.call_flow(s, node); + nk::index => return this.index_flow(s, node); + nk::member, nk::member_of => return this.member_flow(s, node); + nk::type_args => return 0; + nk::slice => return this.slice_flow(s, node); + nk::cast => return this.cast_flow(s, node); + nk::is_test => { + this.test_flow(s, node); + return 0; + } + nk::construct => return this.construct_flow(s, node); + nk::range => { + # Its ends are integers, which keep nothing. + this.value_flow(s, this.checker.left_of(node)); + this.value_flow(s, this.checker.right_of(node)); + return 0; + } + nk::array => return this.array_flow(s, node); + nk::lambda => return this.lambda_flow(s, node); + nk::match_value => return this.match_flow(s, node, true); + # What `e` was is a copy of what it held. + nk::old_value => return this.value_flow(s, this.checker.left_of(node)); + else => {} + } + this.unknown_flow(s, node); + return this.shared_flow(s, kind); +} + +#! The value a name gives: what a local holds, or what a global does, which any +#! code may reach. +#! @param this The compiler. +#! @param s The scan. +#! @param node The `name` or `path` node. +#! @returns The set of its value, or 0. +def lowerer::name_flow(&mut this, s: &mut escape_scan, node: u32): u32 { + val ref := this.checker.ref_at(node); + val kind := this.checker.type_at(node); + if (ref & ref_local) != 0 { + return 0 if !this.holds_references(kind); + return s.graph.held_by(this.slot_of(s, ref & ref_mask)); + } + return 0 if ref == 0 || (ref & ref_type) != 0; + return this.shared_flow(s, kind) if this.checker.decls.kinds.p[ref] == dk::variable; + return 0; +} + +#! The place a node names, as `emitter::place_of` finds it: a local's storage, +#! a field or element within what holds it, or what a global, a pointer, a +#! view, or what implements `indexable` reaches; or else a value the statement +#! holds. +#! @param this The compiler. +#! @param s The scan. +#! @param node The node. +#! @param refers Whether a reference to the place is made. +#! @returns The set of the spots it lies within. +pub def lowerer::place_flow(&mut this, s: &mut escape_scan, node: u32, refers: bool): u32 { + match this.checker.kind_of(node) { + nk::name, nk::path => { + val ref := this.checker.ref_at(node); + if (ref & ref_local) != 0 { + return this.local_place(s, ref & ref_mask, refers); + } + if ref != 0 && (ref & ref_type) == 0 && this.checker.decls.kinds.p[ref] == dk::variable && !this.checker.is_known(node) { + return s.graph.alone(s.graph.shared); + } + } + nk::member, nk::member_of => { + val ref := this.checker.ref_at(node); + if ref != 0 && (ref & (ref_local | ref_type)) == 0 && this.checker.decls.kinds.p[ref] == dk::field { + return this.object_flow(s, this.checker.left_of(node), refers); + } + } + nk::index => { + if !this.through_at(node) { + return this.element_flow(s, node, refers); + } + } + nk::call => { + val ref := this.checker.ref_at(node); + if ref != 0 && (ref & (ref_local | ref_type)) == 0 && this.checker.decls.kinds.p[ref] == dk::variable && !this.checker.is_known(node) { + return s.graph.alone(s.graph.shared); + } + } + nk::unary => { + if this.checker.token_kind(node) == tk::star { + this.value_flow(s, this.checker.left_of(node)); + return s.graph.alone(s.graph.shared); + } + } + else => {} + } + return this.temp_place(s, node, this.raw_flow(s, node)); +} + +#! The place a node's value is at, read through every reference it holds, as +#! `emitter::object` finds it. +#! @param this The compiler. +#! @param s The scan. +#! @param node The node. +#! @param refers Whether a reference into the place is made. +#! @returns The set of the spots it lies within. +pub def lowerer::object_flow(&mut this, s: &mut escape_scan, node: u32, refers: bool): u32 { + val kind := this.checker.type_at(node); + return this.place_flow(s, node, refers) if !this.is_reference_type(kind); + var at := this.raw_flow(s, node); + var held := this.checker.types.first_of(this.checker.unalias(kind)); + var steps := 0; + while this.is_reference_type(held) && steps < 16 { + at = s.graph.read_of(at); + held = this.checker.types.first_of(this.checker.unalias(held)); + steps++; + } + return at; +} + +#! The reference a node is, read through the references it refers to until one +#! refers to what is no reference, as `emitter::through_one` reads it. +#! @param this The compiler. +#! @param s The scan. +#! @param node The node, of a reference type. +#! @returns The set of the reference. +def lowerer::through_one_flow(&mut this, s: &mut escape_scan, node: u32): u32 { + var at := this.raw_flow(s, node); + var held := this.checker.types.first_of(this.checker.unalias(this.checker.type_at(node))); + var steps := 0; + while this.is_reference_type(held) && steps < 16 { + at = s.graph.read_of(at); + held = this.checker.types.first_of(this.checker.unalias(held)); + steps++; + } + return at; +} + +#! A reference a parameter is given to what a node gives, where that is no +#! reference, as `emitter::reference_arg` makes it: to its place, or to a value +#! the statement holds. +#! @param this The compiler. +#! @param s The scan. +#! @param node The node. +#! @returns The set of the reference. +pub def lowerer::lent_flow(&mut this, s: &mut escape_scan, node: u32): u32 { + return this.place_flow(s, node, true) if this.checker.is_place(node); + return this.temp_place(s, node, this.raw_flow(s, node)); +} + +#! The reference a method's `this` is given to the value it is called on, as +#! `emitter::receiver_of` makes it: the reference the value is, read through, or +#! one to the value. +#! @param this The compiler. +#! @param s The scan. +#! @param object The node of the value. +#! @returns The set of the reference. +def lowerer::receiver_flow(&mut this, s: &mut escape_scan, object: u32): u32 { + return this.through_one_flow(s, object) if this.is_reference_type(this.checker.type_at(object)); + return this.lent_flow(s, object); +} + +#! `&x`: a reference to a place, or to a value the statement holds, or the +#! reference a value already is, as `emitter::reference` makes it. +#! @param this The compiler. +#! @param s The scan. +#! @param node The `reference` node. +#! @returns The set of the reference. +def lowerer::reference_flow(&mut this, s: &mut escape_scan, node: u32): u32 { + val inner := this.checker.left_of(node); + val kind := this.checker.type_at(node); + if this.checker.has_flag(node, rf::relent) { + return this.raw_flow(s, inner); + } + if this.checker.is_place(inner) && (!this.checker.is_known(inner) || this.stored_place(inner)) { + return this.place_flow(s, inner, true); + } + val referent := this.checker.types.first_of(this.checker.unalias(kind)); + return this.temp_place(s, node, this.value_flow_as(s, inner, referent)); +} + +#! Whether a place whose value is known while compiling is still in memory, as +#! `emitter::stored` says. +#! @param this The compiler. +#! @param node The place's node. +#! @returns Whether it is. +def lowerer::stored_place(&mut this, node: u32): bool { + var at := node; + while this.checker.kind_of(at) == nk::index || this.checker.kind_of(at) == nk::member { + at = this.checker.left_of(at); + } + val named := this.checker.kind_of(at) == nk::name || this.checker.kind_of(at) == nk::path; + return named && at != node && !this.checker.is_known(at); +} + +#! A prefix operator: a method's call where the checker chose one, the value read +#! through a pointer, or arithmetic. +#! @param this The compiler. +#! @param s The scan. +#! @param node The `unary` node. +#! @returns The set of its value, or 0. +def lowerer::unary_flow(&mut this, s: &mut escape_scan, node: u32): u32 { + val operand := this.checker.left_of(node); + val kind := this.checker.type_at(node); + match this.checker.token_kind(node) { + tk::minus, tk::bitnot => { + val method := this.operator_called(node); + if method != 0 { + return this.operator_flow(s, node, method, operand, 0); + } + this.value_flow(s, operand); + return 0; + } + tk::negate => { + this.value_flow(s, operand); + return 0; + } + tk::increment, tk::decrement => { + this.step_flow(s, operand); + return 0; + } + tk::star => { + this.value_flow(s, operand); + return this.shared_flow(s, kind); + } + else => {} + } + this.unknown_flow(s, node); + return this.shared_flow(s, kind); +} + +#! `x++` or `--x`, which change a number or pointer where it is, or a property +#! through its accessors. +#! @param this The compiler. +#! @param s The scan. +#! @param target The node of what changes. +def lowerer::step_flow(&mut this, s: &mut escape_scan, target: u32): void { + val property := this.property_named(target); + if property != 0 { + this.property_flow(s, property, target, false, 0); + this.property_flow(s, property, target, true, 0); + return; + } + this.writable_flow(s, target, false); +} + +#! The place an assignment or step writes, as `emitter::writable_place` finds it. +#! @param this The compiler. +#! @param s The scan. +#! @param node The node written. +#! @param refers Whether a reference to the place is made, as a compound +#! assignment's method is given one. +#! @returns The set of the spots it lies within. +def lowerer::writable_flow(&mut this, s: &mut escape_scan, node: u32, refers: bool): u32 { + return this.is_reference_type(this.checker.type_at(node)) ? this.object_flow(s, node, refers) : this.place_flow(s, node, refers); +} + +#! A binary operator: what `&&` and `||` test, a comparison, which may call +#! `equals` or `compare`, a method the checker chose, or arithmetic. +#! @param this The compiler. +#! @param s The scan. +#! @param node The `binary` node. +#! @returns The set of its value, or 0. +def lowerer::binary_flow(&mut this, s: &mut escape_scan, node: u32): u32 { + val operator := this.checker.token_kind(node); + val left := this.checker.left_of(node); + val right := this.checker.right_of(node); + if operator == tk::logand || operator == tk::logor { + this.value_flow(s, left); + this.value_flow(s, right); + return 0; + } + if operator.compares() { + # What says how it compares is given references to both sides, each to its + # place or to a value the statement holds. + val plain := this.layout_type(this.checker.read_type(this.checker.converted(left))); + val named := this.checker.named_kind(plain); + val equal := operator == tk::equals || operator == tk::noteq; + if (named == dk::struct_type || named == dk::union_type) && (!equal || this.checker.has_method(plain, word::equals)) { + val method := this.picked_method(plain, equal ? word::equals : word::compare, true); + val summary := this.keeps_of_method(method, plain); + val result := s.graph.new_set(); + val subject := this.is_reference_type(this.checker.type_at(left)) ? this.raw_flow(s, left) : this.operand_flow(s, left); + this.give_flow(s, &summary, 0, subject, true, result); + val other := this.is_reference_type(this.checker.type_at(right)) ? this.raw_flow(s, right) : this.operand_flow(s, right); + this.give_flow(s, &summary, 1, other, true, result); + return 0; + } + this.value_flow(s, left); + this.value_flow(s, right); + return 0; + } + val method := this.operator_called(node); + if method != 0 { + return this.operator_flow(s, node, method, left, right); + } + this.value_flow(s, left); + this.value_flow(s, right); + return 0; +} + +#! A reference to an operand an operator's method is lent, as +#! `emitter::lent_arg` makes it: to its place, or to a value the statement holds, +#! which it always does. +#! @param this The compiler. +#! @param s The scan. +#! @param node The operand's node. +#! @returns The set of the reference. +def lowerer::operand_flow(&mut this, s: &mut escape_scan, node: u32): u32 { + return this.place_flow(s, node, true) if this.checker.is_place(node); + return this.temp_place(s, node, this.value_flow(s, node)); +} + +#! The method of a name a type has, of the overloads the one taking `this` +#! and, where `binary` says, another reference to the type, as +#! `emitter::pick_method` picks it. +#! @param this The compiler. +#! @param kind The type. +#! @param word The ID of the method's name. +#! @param binary Whether it takes another operand. +#! @returns The method's declaration, or 0. +def lowerer::picked_method(&mut this, kind: u32, word: u32, binary: bool): u32 { + val found := this.checker.find_member(kind, word); + return 0 if found.decl == 0; + var first: u32 = 0; + var walk := this.checker.decls.walk_overloads(found.decl); + while true { + val at := walk.next(); + break if at == 0; + this.checker.resolve(at); + if this.checker.decls.kinds.p[at] == dk::function && this.checker.decls.has(at, df::method) { + val held := this.checker.method_type(at, kind); + val count := this.checker.types.part_count(held); + if (binary && count == 2) || (!binary && count == 1) { + if first == 0 { + first = at; + } + return at if !binary; + val other := this.checker.types.part_at(held, 1); + if this.is_reference_type(other) + && this.checker.strip(this.checker.types.first_of(this.checker.unalias(other)), 0) == this.checker.strip(kind, 0) { + return at; + } + } + } + } + return first; +} + +#! The call of the method an arithmetic operator is, given the operand it is +#! called on as `this` and the other as its argument, as a call gives them. +#! @param this The compiler. +#! @param s The scan. +#! @param node The operator's node. +#! @param method The method's declaration. +#! @param left The node of the operand it is called on. +#! @param right The node of the other operand, or 0. +#! @returns The set of what it gives, or 0. +def lowerer::operator_flow(&mut this, s: &mut escape_scan, node: u32, method: u32, left: u32, right: u32): u32 { + val instance := this.called(node); + var kind := this.type_of_function(method, instance); + if this.trait_of_method(method) != 0 { + kind = this.checker.trait_method_type(method, this.checker.reached(this.checker.type_at(left))); + } + val summary := this.keeps_of_call(method, instance, left); + val result := this.result_flow(s, this.checker.types.first_of(kind)); + this.receive_flow(s, &summary, left, this.checker.types.part_at(kind, 0), result); + if right != 0 && this.checker.types.part_count(kind) > 1 { + this.argument_flow(s, &summary, 1, right, this.checker.types.part_at(kind, 1), result); + } + return result; +} + +#! An assignment, as `emitter::assign` lowers it: `_ = x` lets go of `x`, a +#! property is written by its `set`, a variable holding a reference is pointed +#! elsewhere, and anything else written where it is, through a method's call +#! for a compound assignment the checker chose one for. +#! @param this The compiler. +#! @param s The scan. +#! @param node The `assign` node. +#! @returns The set of the value assigned, or 0. +def lowerer::assign_flow(&mut this, s: &mut escape_scan, node: u32): u32 { + val operator := this.checker.token_kind(node); + val target := this.checker.left_of(node); + val value := this.checker.right_of(node); + val kind := this.checker.type_at(node); + if operator == tk::assign && this.checker.kind_of(target) == nk::name && this.checker.name_of(target) == names::underscore_id { + return this.value_flow(s, value); + } + + val property := this.property_named(target); + if property != 0 { + var stored: u32 = 0; + if operator == tk::assign { + stored = this.value_flow_as(s, value, kind); + } else { + val current := this.property_flow(s, property, target, false, 0); + stored = this.compound_flow(s, node, current, value, kind); + } + this.property_flow(s, property, target, true, stored); + return stored; + } + + val target_type := this.checker.type_at(target); + if operator == tk::assign && this.is_reference_type(target_type) { + if !this.checker.has_flag(node, rf::valued) { + val made := this.value_flow_as(s, value, target_type); + s.graph.write(this.place_flow(s, target, false), made); + return made; + } + # Any other reference writes what it refers to. + val at := this.object_once_flow(s, target); + val made := this.value_flow_as(s, value, this.checker.types.first_of(this.checker.unalias(target_type))); + s.graph.write(at, made); + return made; + } + + # Writing a union's field makes the union hold it. + val target_kind := this.checker.kind_of(target); + if (target_kind == nk::member || target_kind == nk::member_of) && operator == tk::assign { + val ref := this.checker.ref_at(target); + if ref != 0 && (ref & (ref_local | ref_type)) == 0 && this.checker.decls.kinds.p[ref] == dk::field + && this.checker.decls.kinds.p[this.checker.decls.owners.p[ref]] == dk::union_type + && !this.checker.decls.has(this.checker.decls.owners.p[ref], df::foreign) { + val whole := this.object_flow(s, this.checker.left_of(target), false); + val made := this.value_flow_as(s, value, target_type); + s.graph.write(whole, made); + return made; + } + } + + val method := this.operator_called(node); + val at := this.writable_flow(s, target, operator != tk::assign && method != 0); + if operator == tk::assign { + val made := this.value_flow_as(s, value, this.writable_type(target)); + s.graph.write(at, made); + return made; + } + # What a compound assignment's method gives is written over what was there. + if method != 0 { + val instance := this.called(node); + var called := this.type_of_function(method, instance); + if this.trait_of_method(method) != 0 { + called = this.checker.trait_method_type(method, this.checker.reached(target_type)); + } + val summary := this.keeps_of_call(method, instance, target); + val result := this.result_flow(s, this.checker.types.first_of(called)); + this.give_flow(s, &summary, 0, at, true, result); + if this.checker.types.part_count(called) > 1 { + this.argument_flow(s, &summary, 1, value, this.checker.types.part_at(called, 1), result); + } + s.graph.write(at, result); + return result; + } + this.value_flow(s, value); + return 0; +} + +#! The type an assignment writes where its target is, read through a reference +#! as `emitter::writable_place` reads it. +#! @param this The compiler. +#! @param target The target's node. +#! @returns The type. +def lowerer::writable_type(&mut this, target: u32): u32 { + var kind := this.checker.type_at(target); + var steps := 0; + while this.is_reference_type(kind) && steps < 16 { + kind = this.checker.types.first_of(this.checker.unalias(kind)); + steps++; + } + return kind; +} + +#! The place a reference refers to, read through one reference, as +#! `emitter::object_by(node, 1)` finds it. +#! @param this The compiler. +#! @param s The scan. +#! @param node The node, of a reference type. +#! @returns The set of the spots it lies within. +def lowerer::object_once_flow(&mut this, s: &mut escape_scan, node: u32): u32 { + return this.raw_flow(s, node); +} + +#! The value a compound assignment of a property works out from what the +#! property held, through a method's call where the checker chose one, given +#! what the property held as a value the statement holds. +#! @param this The compiler. +#! @param s The scan. +#! @param node The `assign` node. +#! @param current The set of what the property held, or 0. +#! @param value The value's node. +#! @param kind The type assigned. +#! @returns The set of the value, or 0. +def lowerer::compound_flow(&mut this, s: &mut escape_scan, node: u32, current: u32, value: u32, kind: u32): u32 { + val method := this.operator_called(node); + if method == 0 { + this.value_flow(s, value); + return 0; + } + val instance := this.called(node); + val called := this.type_of_function(method, instance); + val summary := this.keeps_of_call(method, instance, 0); + val result := this.result_flow(s, this.checker.types.first_of(called)); + this.give_flow(s, &summary, 0, this.temp_place(s, node, current), true, result); + if this.checker.types.part_count(called) > 1 { + this.argument_flow(s, &summary, 1, value, this.checker.types.part_at(called, 1), result); + } + return this.converted_flow(s, result, this.checker.types.first_of(called), kind); +} + +#! `value else fallback`: what a `result` or `maybe` holds, or what stands in, a +#! value or a block that leaves, with the error a result holds named for it. +#! @param this The compiler. +#! @param s The scan. +#! @param node The `fallback` node. +#! @returns The set of the value held, or 0. +def lowerer::fallback_flow(&mut this, s: &mut escape_scan, node: u32): u32 { + val kind := this.checker.type_at(node); + val error := this.checker.record(node, fallback_slot::error); + val other := this.checker.record(node, fallback_slot::other); + val whole := this.object_flow(s, this.checker.left_of(node), false); + val held := s.graph.read_of(whole); + if error != 0 { + s.graph.into(held, s.graph.held_by(this.slot_of(s, error))); + } + var given: u32 = 0; + if this.checker.kind_of(other) == nk::block { + this.scan_block(s, other); + } else { + given = this.value_flow_as(s, other, kind); + } + return s.graph.either(this.holds_references(kind) ? held : 0, given); +} + +#! An element's place, as `emitter::element_place` finds it: within a fixed +#! array, what a pointer or a view points at, a pack's value, or what `at` +#! gives. +#! @param this The compiler. +#! @param s The scan. +#! @param node The `index` node. +#! @param refers Whether a reference to the place is made. +#! @returns The set of the spots it lies within. +def lowerer::element_flow(&mut this, s: &mut escape_scan, node: u32, refers: bool): u32 { + val object := this.checker.left_of(node); + val at := this.checker.right_of(node); + val through := this.checker.unalias(this.checker.reached(this.object_type(object))); + match this.checker.types.kind_of(through) { + ty::fixed => { + val whole := this.object_flow(s, object, refers); + this.value_flow(s, at); + return whole; + } + ty::pointer => { + this.value_flow(s, object); + this.value_flow(s, at); + return s.graph.alone(s.graph.shared); + } + ty::pack => return s.graph.alone(s.graph.shared); + else => {} + } + if this.viewed(through) != 0 { + this.object_flow(s, object, false); + this.value_flow(s, at); + return s.graph.alone(s.graph.shared); + } + val method := this.checker.ref_at(node); + if method != 0 && (method & (ref_local | ref_type)) == 0 && this.checker.decls.kinds.p[method] == dk::function { + val made := this.accessor_flow(s, node, method, object, at); + return made if this.is_reference_type(this.checker.type_at(node)); + return this.temp_place(s, node, made); + } + this.value_flow(s, object); + this.value_flow(s, at); + return s.graph.alone(s.graph.shared); +} + +#! The type of what an element or member is reached through, as +#! `emitter::object_type` gives it. +#! @param this The compiler. +#! @param object The node of the value reached through. +#! @returns The type. +def lowerer::object_type(&mut this, object: u32): u32 { + val own := this.checker.type_at(object); + return this.checker.types.is_untyped(own) ? this.checker.converted(object) : own; +} + +#! Whether `x[k]` is indexed through `at`, and so is the reference it gives. +#! @param this The compiler. +#! @param node The `index` node. +#! @returns Whether it is. +def lowerer::through_at(&mut this, node: u32): bool { + val method := this.checker.ref_at(node); + return method != 0 && (method & (ref_local | ref_type)) == 0 && this.checker.decls.kinds.p[method] == dk::function + && this.is_reference_type(this.checker.type_at(node)); +} + +#! `x[k]` as a value: the reference `at` gives, or what the element's place holds. +#! @param this The compiler. +#! @param s The scan. +#! @param node The `index` node. +#! @returns The set of its value, or 0. +def lowerer::index_flow(&mut this, s: &mut escape_scan, node: u32): u32 { + if this.through_at(node) { + val object := this.checker.left_of(node); + val through := this.checker.unalias(this.checker.reached(this.object_type(object))); + return this.element_flow(s, node, true) if this.viewed(through) != 0; + return this.accessor_flow(s, node, this.checker.ref_at(node), object, this.checker.right_of(node)); + } + val at := this.element_flow(s, node, false); + return 0 if !this.holds_references(this.checker.type_at(node)); + return s.graph.read_of(at); +} + +#! The call of an accessor the compiler makes itself, as `at`, given the value it +#! is called on and its other argument. +#! @param this The compiler. +#! @param s The scan. +#! @param node The node the call stands for. +#! @param decl The accessor's declaration. +#! @param object The node of the value it is called on. +#! @param arg The node of its other argument, or 0. +#! @returns The set of what it gives, or 0. +def lowerer::accessor_flow(&mut this, s: &mut escape_scan, node: u32, decl: u32, object: u32, arg: u32): u32 { + val owner := this.checker.reached(this.object_type(object)); + val instance := this.method_instance(decl, owner); + val kind := this.method_kind(decl, instance, owner); + val summary := this.keeps_of_method(decl, owner); + val result := this.result_flow(s, this.checker.types.first_of(kind)); + this.receive_flow(s, &summary, object, this.checker.types.part_at(kind, 0), result); + if arg != 0 && this.checker.types.part_count(kind) > 1 { + val given := this.value_flow_as(s, arg, this.checker.types.part_at(kind, 1)); + this.give_flow(s, &summary, 1, given, this.is_reference_type(this.checker.types.part_at(kind, 1)), result); + } + return result; +} + +#! `x.name` as a value: what a field holds, or what a property's `get` gives. +#! @param this The compiler. +#! @param s The scan. +#! @param node The `member` or `member_of` node. +#! @returns The set of its value, or 0. +def lowerer::member_flow(&mut this, s: &mut escape_scan, node: u32): u32 { + val property := this.property_named(node); + if property != 0 { + return this.property_flow(s, property, node, false, 0); + } + val ref := this.checker.ref_at(node); + if ref != 0 && (ref & (ref_local | ref_type)) == 0 && this.checker.decls.kinds.p[ref] == dk::field { + val at := this.object_flow(s, this.checker.left_of(node), false); + return 0 if !this.holds_references(this.checker.type_at(node)); + return s.graph.read_of(at); + } + # The length of a fixed array, or the like, is known while compiling, and what + # else a member names reads its value, which may be referred to. + if this.checker.is_known(node) { + return 0; + } + val object := this.checker.left_of(node); + if this.is_reference_type(this.checker.type_at(object)) { + s.graph.keep(this.raw_flow(s, object)); + } else { + s.graph.keep(this.lent_flow(s, object)); + } + return this.shared_flow(s, this.checker.type_at(node)); +} + +#! The property a member names, or 0. +#! @param this The compiler. +#! @param node The node. +#! @returns The property's declaration, or 0. +def lowerer::property_named(&mut this, node: u32): u32 { + val kind := this.checker.kind_of(node); + return 0 if kind != nk::member && kind != nk::member_of; + val ref := this.checker.ref_at(node); + return 0 if ref == 0 || (ref & (ref_local | ref_type)) != 0; + if this.checker.decls.kinds.p[ref] == dk::function && this.checker.decls.has(ref, df::accessor) { + return this.checker.decls.owners.p[ref]; + } + return this.checker.decls.kinds.p[ref] == dk::property ? ref : 0; +} + +#! The call of a property's accessor, on the value the member reads it of. +#! @param this The compiler. +#! @param s The scan. +#! @param property The property's declaration. +#! @param node The member's node. +#! @param setter Whether the `set` is called, rather than the `get`. +#! @param value The set of the value `set` is given, or 0. +#! @returns The set of what it gives, or 0. +def lowerer::property_flow(&mut this, s: &mut escape_scan, property: u32, node: u32, setter: bool, value: u32): u32 { + val object := this.checker.left_of(node); + val receiver := this.receiver_flow(s, object); + var accessor: u32 = 0; + val run: u32 = this.checker.decls.children.p[property]; + for i in 0..this.checker.decls.list_length(run) { + val each := this.checker.decls.list_at(run, i as u32); + if this.checker.decls.has(each, df::setter) == setter { + accessor = each; + } + } + if accessor == 0 { + s.graph.keep(receiver); + s.graph.keep(value); + return 0; + } + val owner := this.checker.reached(this.checker.type_at(object)); + val instance := this.method_instance(accessor, owner); + val kind := this.method_kind(accessor, instance, owner); + val summary := this.keeps_of_method(accessor, owner); + val result := this.result_flow(s, this.checker.types.first_of(kind)); + this.give_flow(s, &summary, 0, receiver, true, result); + if setter && this.checker.types.part_count(kind) > 1 { + this.give_flow(s, &summary, 1, value, this.is_reference_type(this.checker.types.part_at(kind, 1)), result); + } + return result; +} + +#! `x[a:b]`: a view of what is sliced, which is no reference, so what the view +#! reaches may be read through it by anyone. +#! @param this The compiler. +#! @param s The scan. +#! @param node The `slice` node. +#! @returns 0, as a view holds no reference. +def lowerer::slice_flow(&mut this, s: &mut escape_scan, node: u32): u32 { + val object := this.checker.left_of(node); + val through := this.checker.unalias(this.checker.reached(this.checker.type_at(object))); + if this.checker.types.kind_of(through) == ty::fixed { + s.graph.keep(s.graph.read_of(this.object_flow(s, object, false))); + } else if this.checker.types.kind_of(through) == ty::pointer { + this.value_flow(s, object); + } else { + this.object_flow(s, object, false); + } + this.value_flow(s, this.checker.record(node, slice_slot::start)); + this.value_flow(s, this.checker.record(node, slice_slot::count)); + return 0; +} + +#! `x as T`: a pointer made of a reference keeps nothing alive, but what it +#! reaches may be read through it by anyone; anything else converts. +#! @param this The compiler. +#! @param s The scan. +#! @param node The `cast` node. +#! @returns The set of the value, or 0. +def lowerer::cast_flow(&mut this, s: &mut escape_scan, node: u32): u32 { + val inner := this.checker.left_of(node); + val to := this.checker.type_at(node); + val target := this.layout_type(to); + val made := this.value_flow(s, inner); + val from := this.checker.converted(inner); + val pointer := this.checker.types.kind_of(target) == ty::pointer || this.checker.is_std(target, word::cfn); + if pointer { + if this.is_reference_type(from) { + s.graph.keep(s.graph.read_of(made)); + } else { + s.graph.keep(made); + } + return 0; + } + return made if this.is_reference_type(to); + val reads := this.is_reference_type(from); + var source := made; + var kind := from; + var steps := 0; + while reads && this.is_reference_type(kind) && steps < 16 { + source = s.graph.read_of(source); + kind = this.checker.types.first_of(this.checker.unalias(kind)); + steps++; + } + if !this.holds_references(to) { + # What converts to a number holds nothing; anything else is taken as kept. + if !this.checker.types.is_numeric(this.layout_type(kind)) && !this.checker.types.is_boolean(this.layout_type(kind)) + && this.checker.named_kind(this.layout_type(kind)) != dk::enum_type { + s.graph.keep(source); + } + return 0; + } + return this.converted_flow(s, source, kind, to); +} + +#! `x is field(v)`: the name given holds a copy of what the union holds, or with +#! `&` a reference to where it holds it. +#! @param this The compiler. +#! @param s The scan. +#! @param node The `is_test` node. +def lowerer::test_flow(&mut this, s: &mut escape_scan, node: u32): void { + val field := this.checker.ref_at(node); + val subject := this.checker.left_of(node); + if field == 0 || (field & (ref_local | ref_type)) != 0 || this.checker.decls.kinds.p[field] != dk::field { + return; + } + val binding := this.checker.named_binding(this.checker.record(node, is_slot::binding)); + val refers := binding != 0 && this.checker.kind_of(binding) == nk::reference; + val whole := this.object_flow(s, subject, refers); + return if binding == 0; + val named := refers ? this.checker.left_of(binding) : binding; + val slot := this.slot_of(s, named); + # `&` of a field holding a reference gives the reference it holds. + if refers { + s.graph.into(whole, s.graph.held_by(slot)); + } + if this.holds_references(this.checker.type_at(named)) { + s.graph.read(whole, s.graph.held_by(slot)); + } +} + +#! A struct or union literal: the value holds what each field is given, and +#! what the defaults of those left out hold, which any code may reach. +#! @param this The compiler. +#! @param s The scan. +#! @param node The `construct` node. +#! @returns The set of the value, or 0. +def lowerer::construct_flow(&mut this, s: &mut escape_scan, node: u32): u32 { + val kind := this.checker.type_at(node); + val inits := this.checker.right_of(node); + val holds := this.holds_references(kind); + var made: u32 = holds ? s.graph.new_set() : 0; + val plain := this.checker.unalias(kind); + for i in 0..this.checker.run_length(inits) { + val init := this.checker.run_at(inits, i as u32); + val field := this.checker.ref_at(init); + val wanted := field != 0 && (field & (ref_local | ref_type)) == 0 ? this.checker.decls.types.p[field] : 0; + val value := this.checker.left_of(init); + val given := wanted != 0 ? this.value_flow_as(s, value, this.field_type(plain, field)) : this.value_flow(s, value); + if holds { + s.graph.into(given, made); + } else { + s.graph.keep(given); + } + } + if holds && this.checker.types.kind_of(plain) == ty::named { + val index := this.layout_of(plain); + if this.layout_at(index).count as u64 > this.checker.run_length(inits) as u64 { + s.graph.add(made, s.graph.shared); + } + } + return made; +} + +#! The type of a field within a struct or union of a type, given its arguments, +#! as its layout lays it out. +#! @param this The compiler. +#! @param kind The struct's or union's type, without aliases. +#! @param field The field's declaration. +#! @returns The type, or the field's declared type where the layout has none. +def lowerer::field_type(&mut this, kind: u32, field: u32): u32 { + if this.checker.types.kind_of(kind) == ty::named { + val index := this.layout_of(kind); + for i in 0..this.layout_at(index).count { + val each := this.field_at(index, i as u32); + return each.type_id if each.decl == field; + } + } + return this.checker.decls.types.p[field]; +} + +#! An array literal: a fixed array holds what its elements do; a view of one +#! is no reference, so what its elements hold may be read through it by anyone. +#! @param this The compiler. +#! @param s The scan. +#! @param node The `array` node. +#! @returns The set of the value, or 0. +def lowerer::array_flow(&mut this, s: &mut escape_scan, node: u32): u32 { + val kind := this.checker.unalias(this.checker.converted(node)); + val viewed := this.viewed(kind); + val element := viewed != 0 ? viewed : this.checker.types.first_of(kind); + val run := this.checker.left_of(node); + val holds := viewed == 0 && this.holds_references(kind); + var made: u32 = holds ? s.graph.new_set() : 0; + for i in 0..this.checker.run_length(run) { + val given := this.value_flow_as(s, this.checker.run_at(run, i as u32), element); + if holds { + s.graph.into(given, made); + } else { + s.graph.keep(given); + } + } + return made; +} + +#! A match, as a statement or a value: a union's arm names what it holds, a copy +#! or with `&` a reference to it; values are compared with the subject, through +#! `equals` where the type has one; and a match used as a value gives what its +#! arm gives. +#! @param this The compiler. +#! @param s The scan. +#! @param node The `match_stmt` or `match_value` node. +#! @param value Whether it is used as a value. +#! @returns The set of what it gives, or 0. +def lowerer::match_flow(&mut this, s: &mut escape_scan, node: u32, value: bool): u32 { + val subject := this.checker.left_of(node); + val arms := this.checker.right_of(node); + val kind := value ? this.checker.type_at(node) : bt::void_type; + val whole := this.object_flow(s, subject, this.refers_in_arm(node)); + val plain := this.checker.unalias(this.checker.reached(this.checker.type_at(subject))); + val union_like := this.checker.named_kind(plain) == dk::union_type; + + # Values compared through `equals` are lent to it, and what it keeps of what + # they reach is kept. + var compared := keeping {}; + val calls := !union_like && this.checker.has_method(plain, word::equals) + && this.checker.named_kind(plain) != dk::enum_type && !this.checker.types.is_numeric(plain); + if calls { + compared = this.keeps_of_method(this.picked_method(plain, word::equals, true), plain); + if (compared.kept | compared.reached) != 0 { + s.graph.keep(s.graph.read_of(whole)); + } + } + + var made: u32 = 0; + for i in 0..this.checker.run_length(arms) { + val arm := this.checker.run_at(arms, i as u32); + val patterns := this.checker.left_of(arm); + val body := this.checker.right_of(arm); + for j in 0..this.checker.run_length(patterns) { + val pattern := this.checker.run_at(patterns, j as u32); + if !union_like { + val given := this.value_flow(s, pattern); + if calls && (compared.kept | compared.reached) != 0 { + s.graph.keep(given); + } + continue; + } + continue if this.checker.kind_of(pattern) != nk::call; + val bound := this.checker.right_of(pattern); + continue if this.checker.run_length(bound) != 1; + val binding := this.checker.named_binding(this.checker.run_at(bound, 0)); + continue if binding == 0; + val refers := this.checker.kind_of(binding) == nk::reference; + val named := refers ? this.checker.left_of(binding) : binding; + val slot := this.slot_of(s, named); + # `&` of a field holding a reference gives the reference it holds. + if refers { + s.graph.into(whole, s.graph.held_by(slot)); + } + if this.holds_references(this.checker.type_at(named)) { + s.graph.read(whole, s.graph.held_by(slot)); + } + } + if value { + made = s.graph.either(made, this.value_flow_as(s, body, kind)); + } else { + this.scan_block(s, body); + } + } + return made; +} + +#! Whether an arm of a match names the value a field holds by `&` or `&mut`, +#! which refers to it where the union is. +#! @param this The compiler. +#! @param node The match's node. +#! @returns Whether one does. +pub def lowerer::refers_in_arm(&mut this, node: u32): bool { + val arms := this.checker.right_of(node); + for i in 0..this.checker.run_length(arms) { + val patterns := this.checker.left_of(this.checker.run_at(arms, i as u32)); + for j in 0..this.checker.run_length(patterns) { + val pattern := this.checker.run_at(patterns, j as u32); + continue if this.checker.kind_of(pattern) != nk::call; + val given := this.checker.right_of(pattern); + if this.checker.run_length(given) == 1 && this.checker.kind_of(this.checker.run_at(given, 0)) == nk::reference { + return true; + } + } + } + return false; +} + +# Anonymous functions. + +#! An anonymous function as a value: where it captures locals, its environment, +#! which holds a reference to each. Its body is scanned where it is made, as +#! what it does with what it captures, it does with the locals themselves; what +#! it is given, and what it gives back, are anyone's. +#! @param this The compiler. +#! @param s The scan. +#! @param node The `lambda` node. +#! @returns The set of the value, or 0 where it captures nothing. +def lowerer::lambda_flow(&mut this, s: &mut escape_scan, node: u32): u32 { + var captures := this.captured_by(node); + return 0 if captures.length == 0; + var env: u32 = 0; + if s.envs.get(&node) is some(got) { + env = got; + } else { + env = s.graph.new_spot(spot_kind::env, node, s.within.length as u32); + s.envs.set(node, env); + } + for &each in captures { + s.graph.add(s.graph.held_by(env), this.slot_of(s, each)); + s.graph.spots[this.slot_of(s, each) as u64].taken = true; + } + + # The body, as a function of its own within this one. + val saved_returns := s.returns; + val saved_result := s.result; + s.within.append(pair_key(this.lowest_node(node), node)); + val kind := this.checker.type_at(node); + s.returns = s.graph.kept; + s.result = this.checker.types.first_of(kind); + val params := this.checker.left_of(node); + for i in 0..this.checker.run_length(params) { + val param := this.checker.run_at(params, i as u32); + s.graph.add(s.graph.held_by(this.slot_of(s, param)), s.graph.shared); + } + this.scan_body(s, this.checker.record(node, lambda_slot::body)); + s.within.truncate(); + s.returns = saved_returns; + s.result = saved_result; + return s.graph.alone(env); +} + +#! The locals of the functions around an anonymous function that it names, or +#! that one within it names, in the order it first names them, as +#! `emitter::captures_of` finds them. +#! @param this The compiler. +#! @param node The `lambda` node. +#! @returns The nodes declaring them. +pub def lowerer::captured_by(&mut this, node: u32): vector { + var made := vector::::new(); + val first := this.lowest_node(node); + var walk := node_walk::new(node); + while walk.more() { + val at := walk.next(); + # A contract left out captures nothing. + continue if this.checker.contracts_off && this.checker.kind_of(at) == nk::contract; + if this.checker.kind_of(at) == nk::name { + val ref := this.checker.ref_at(at); + if (ref & ref_local) != 0 { + val local := ref & ref_mask; + if (local < first || local > node) && !made.view().contains(&local) { + made.append(local); + } + } + } + walk.enter(this.checker.syn(), at); + } + return made; +} + +#! The first node of what a node was parsed from, which the parser made before +#! the node itself, one after another. +#! @param this The compiler. +#! @param node The node. +#! @returns The lowest node under it. +pub def lowerer::lowest_node(&mut this, node: u32): u32 { + var lowest := node; + var walk := node_walk::new(node); + while walk.more() { + val at := walk.next(); + lowest = at < lowest ? at : lowest; + walk.enter(this.checker.syn(), at); + } + return lowest; +} + +# Calls. + +#! A set for what a call of a result type gives, holding what any code may +#! reach, as a function gives back what it found anywhere, or 0 where the type +#! holds no reference. +#! @param this The compiler. +#! @param s The scan. +#! @param kind The result type. +#! @returns The set, or 0. +def lowerer::result_flow(&mut this, s: &mut escape_scan, kind: u32): u32 { + return 0 if !this.holds_references(kind); + val made := s.graph.new_set(); + s.graph.add(made, s.graph.shared); + return made; +} + +#! Gives what a parameter is given where a function's summary says: kept, given +#! back in what the call gives, or neither; and what it reaches likewise. +#! @param this The compiler. +#! @param s The scan. +#! @param summary The function's summary. +#! @param index The parameter's position, `this` first. +#! @param given The set of what it is given, or 0. +#! @param reference Whether the parameter takes a reference. +#! @param result The set of what the call gives, or 0. +def lowerer::give_flow(&mut this, s: &mut escape_scan, summary: &keeping, index: u32, given: u32, reference: bool, result: u32): void { + return if given == 0; + val bit := index < 62 ? 1u << index : 0; + val all := index >= 62; + if reference { + if all || (summary.kept & bit) != 0 { + s.graph.keep(given); + } else if (summary.given & bit) != 0 { + s.graph.into(given, result != 0 ? result : s.graph.kept); + } + } + if all || (summary.reached & bit) != 0 { + s.graph.keep(reference ? s.graph.read_of(given) : given); + } else if (summary.passed & bit) != 0 { + s.graph.into(reference ? s.graph.read_of(given) : given, result != 0 ? result : s.graph.kept); + } +} + +#! Gives a method the value it is called on, as `emitter::receiver` does: the +#! reference the value is, or one to it. +#! @param this The compiler. +#! @param s The scan. +#! @param summary The method's summary. +#! @param object The node of the value. +#! @param param The type of `this`. +#! @param result The set of what the call gives, or 0. +def lowerer::receive_flow(&mut this, s: &mut escape_scan, summary: &keeping, object: u32, param: u32, result: u32): void { + val made := this.receiver_flow(s, object); + if this.is_reference_type(param) { + this.give_flow(s, summary, 0, made, true, result); + } else { + this.give_flow(s, summary, 0, s.graph.read_of(made), false, result); + } +} + +#! Gives a parameter its argument, as `emitter::argument` does: a reference to +#! it where the checker says one is taken, or its value as the parameter takes +#! it. +#! @param this The compiler. +#! @param s The scan. +#! @param summary The function's summary. +#! @param index The parameter's position. +#! @param arg The argument's node. +#! @param param The parameter's type. +#! @param result The set of what the call gives, or 0. +def lowerer::argument_flow(&mut this, s: &mut escape_scan, summary: &keeping, index: u32, arg: u32, param: u32, result: u32): void { + if this.checker.has_flag(arg, rf::borrowed) { + this.give_flow(s, summary, index, this.lent_flow(s, arg), true, result); + return; + } + this.give_flow(s, summary, index, this.value_flow_as(s, arg, param), this.is_reference_type(param), result); +} + +#! A call, as `emitter::call` lowers it: of an intrinsic, of a declared function +#! or method, of a method the compiler gives a built-in type, or of a function +#! value. +#! @param this The compiler. +#! @param s The scan. +#! @param node The `call` node. +#! @returns The set of what it gives, or 0. +def lowerer::call_flow(&mut this, s: &mut escape_scan, node: u32): u32 { + val callee := this.checker.left_of(node); + var decl := this.checker.ref_at(node); + val kind := this.checker.type_at(node); + if this.checker.has_flag(node, rf::invokes) && decl != 0 { + return this.declared_flow(s, node, decl, callee); + } + if decl == 0 && this.checker.kind_of(callee) == nk::member_of { + decl = this.checker.ref_at(callee); + } + val named := this.checker.kind_of(callee) == nk::name || this.checker.kind_of(callee) == nk::path ? this.checker.ref_at(callee) : 0; + if named != 0 && (named & (ref_local | ref_type)) == 0 && this.checker.decls.kinds.p[named] == dk::function + && this.checker.decls.has(named, df::intrinsic) { + return this.intrinsic_flow(s, node, named); + } + if decl != 0 && (decl & (ref_local | ref_type)) == 0 && this.checker.decls.kinds.p[decl] == dk::function { + return this.intrinsic_flow(s, node, decl) if this.checker.decls.has(decl, df::intrinsic); + var object: u32 = 0; + val callee_kind := this.checker.kind_of(callee); + if (callee_kind == nk::member || callee_kind == nk::member_of) && this.checker.decls.has(decl, df::method) { + object = this.checker.left_of(callee); + } + return this.declared_flow(s, node, decl, object); + } + + # A method the compiler gives a built-in type keeps nothing of its operands, + # but `invoke` calls the function value it is called on. + if this.checker.kind_of(callee) == nk::member && decl == 0 { + val field := this.checker.ref_at(callee); + val is_field := field != 0 && (field & (ref_local | ref_type)) == 0 && this.checker.decls.kinds.p[field] == dk::field; + if !is_field { + val object := this.checker.left_of(callee); + if this.checker.name_of(callee) == word::invoke { + this.value_flow(s, object); + this.keep_arguments(s, node); + return this.shared_flow(s, kind); + } + val reached := this.checker.unalias(this.checker.reached(this.checker.type_at(object))); + if this.checker.types.kind_of(reached) == ty::fixed { + this.object_flow(s, object, false); + val run := this.checker.right_of(node); + for i in 0..this.checker.run_length(run) { + this.object_flow(s, this.checker.run_at(run, i as u32), false); + } + return 0; + } + this.value_flow(s, object); + val run := this.checker.right_of(node); + for i in 0..this.checker.run_length(run) { + this.value_flow(s, this.checker.run_at(run, i as u32)); + } + return this.shared_flow(s, kind); + } + } + + # A function value's body was scanned where it was made, so calling it keeps + # nothing of it, but what it is given goes where that body does not say. + this.value_flow(s, callee); + this.keep_arguments(s, node); + return this.shared_flow(s, kind); +} + +#! A call of an intrinsic. Closing a value where it is keeps nothing of it, as +#! a local's scope ending doesn't; what the scan knows nothing more of keeps +#! what it's given. +#! @param this The compiler. +#! @param s The scan. +#! @param node The `call` node. +#! @param decl The intrinsic's declaration. +#! @returns The set of what it gives, or 0. +def lowerer::intrinsic_flow(&mut this, s: &mut escape_scan, node: u32, decl: u32): u32 { + if this.checker.names.text(this.checker.decls.names.p[decl]) == "close_where_it_is" { + val run := this.checker.right_of(node); + for i in 0..this.checker.run_length(run) { + this.value_flow(s, this.checker.run_at(run, i as u32)); + } + return 0; + } + return this.unknown_call_flow(s, node); +} + +#! A call of what the scan does not know: what each argument is, or is lent, is +#! kept, and what it gives is anyone's. +#! @param this The compiler. +#! @param s The scan. +#! @param node The `call` node. +#! @returns The set of what it gives, or 0. +def lowerer::unknown_call_flow(&mut this, s: &mut escape_scan, node: u32): u32 { + this.keep_arguments(s, node); + return this.shared_flow(s, this.checker.type_at(node)); +} + +#! Keeps what each argument of a call is, or is lent. +#! @param this The compiler. +#! @param s The scan. +#! @param node The `call` node. +def lowerer::keep_arguments(&mut this, s: &mut escape_scan, node: u32): void { + val run := this.checker.right_of(node); + for i in 0..this.checker.run_length(run) { + val arg := this.checker.run_at(run, i as u32); + if this.checker.has_flag(arg, rf::borrowed) { + s.graph.keep(this.lent_flow(s, arg)); + continue; + } + if this.checker.kind_of(arg) == nk::unary && this.checker.token_kind(arg) == tk::spread { + this.spread_flow(s, arg); + continue; + } + s.graph.keep(this.value_flow(s, arg)); + } +} + +#! `...xs`, which spreads a pack's values, or gives a view of a fixed array or +#! of a view: what it reaches is kept. +#! @param this The compiler. +#! @param s The scan. +#! @param node The `unary` node. +def lowerer::spread_flow(&mut this, s: &mut escape_scan, node: u32): void { + val spread := this.checker.left_of(node); + val through := this.checker.unalias(this.checker.reached(this.checker.type_at(spread))); + if this.checker.types.kind_of(through) == ty::fixed { + s.graph.keep(s.graph.read_of(this.object_flow(s, spread, false))); + return; + } + s.graph.keep(this.value_flow(s, spread)); +} + +#! A call of a declared function or method, giving each argument where its +#! summary says: the value a method is called on, those written, those a +#! variadic parameter takes as a view of them, and those a pack spreads. +#! @param this The compiler. +#! @param s The scan. +#! @param node The `call` node. +#! @param decl The function's declaration. +#! @param object The node of the value a method is called on, or 0. +#! @returns The set of what it gives, or 0. +def lowerer::declared_flow(&mut this, s: &mut escape_scan, node: u32, decl: u32, object: u32): u32 { + val instance := this.called(node); + var kind := this.type_of_function(decl, instance); + if this.trait_of_method(decl) != 0 && object != 0 { + kind = this.checker.trait_method_type(decl, this.checker.reached(this.checker.type_at(object))); + } + val summary := this.keeps_of_call(decl, instance, object); + val result := this.result_flow(s, this.checker.types.first_of(kind)); + var p: u32 = 0; + if object != 0 { + this.receive_flow(s, &summary, object, this.checker.types.part_at(kind, 0), result); + p = 1; + } + val count := this.checker.types.part_count(kind); + val variadic := this.checker.types.second_of(kind) != 0; + val stop: u32 = variadic ? count - 1 : count; + val run := this.checker.right_of(node); + for i in 0..this.checker.run_length(run) { + val arg := this.checker.run_at(run, i as u32); + if this.checker.kind_of(arg) == nk::unary && this.checker.token_kind(arg) == tk::spread { + this.spread_flow(s, arg); + p = count; + continue; + } + # What a variadic parameter gathers is held in a view, which is no reference. + if p >= stop || p >= count { + s.graph.keep(this.value_flow(s, arg)); + continue; + } + this.argument_flow(s, &summary, p, arg, this.checker.types.part_at(kind, p), result); + p++; + } + return result; +} + +#! A call of a method the compiler makes itself on a value it has a reference +#! to, as a loop's `next` or `iter`. +#! @param this The compiler. +#! @param s The scan. +#! @param decl The method's declaration, or 0. +#! @param owner The type it is called on. +#! @param receiver The set of the reference `this` is given. +#! @returns The set of what it gives, or 0. +def lowerer::method_flow(&mut this, s: &mut escape_scan, decl: u32, owner: u32, receiver: u32): u32 { + if decl == 0 { + s.graph.keep(receiver); + return 0; + } + val instance := this.method_instance(decl, owner); + val kind := this.method_kind(decl, instance, owner); + val summary := this.keeps_of_method(decl, owner); + val result := this.result_flow(s, this.checker.types.first_of(kind)); + if this.is_reference_type(this.checker.types.part_at(kind, 0)) { + this.give_flow(s, &summary, 0, receiver, true, result); + } else { + this.give_flow(s, &summary, 0, s.graph.read_of(receiver), false, result); + } + return result; +} diff --git a/compiler/flows.sakura b/compiler/flows.sakura new file mode 100644 index 00000000..87bd9376 --- /dev/null +++ b/compiler/flows.sakura @@ -0,0 +1,357 @@ +#! @file flows.sakura +#! @author John Christman (sorakatadzuma@gmail.com) +#! @copyright Malunal Studios, LLC. +#! @license MIT +#! +#! Contains where the references of a body may go, as `escapes.sakura` finds +#! it: the spots a reference may refer to, and the sets of spots the values of +#! the body may hold references to. Each spot holds a set of its own, of what +#! is stored in it. A set flows into another as a value is copied; reading +#! through a set, what each of its spots holds flows into another; and writing +#! through one, a set flows into what each of its spots holds. Two sets stand +#! for where values leave the body: what may be kept past it, and what it gives +#! back. +#! +#! Solving carries each spot along the flows until no set grows, as Andersen's +#! analysis does, without telling the fields of a value apart. A spot then in +#! the set of what is kept is kept, one in the set given back is given back, +#! and so is every spot held by one that is, since whoever holds it may reach +#! them. A spot of the frame held by one that may outlive it is kept too: a +#! value a statement holds held by anything but another such value, or a local +#! held by a local declared before it, which may be given another value later, +#! as each pass of a loop gives one declared within it. + +import std::containers; +module sakura::compiler; + + +#! What a spot stands for. +pub enum spot_kind : u8 { + local, #! The storage of a local, a parameter, or a name a test or a loop gives. + temp, #! A value a statement holds where a reference to it is taken. + env, #! The environment of an anonymous function, which holds references to what it captures. + outer, #! What a parameter taking a reference refers to, the caller's. + inner, #! What the caller's references reach through a parameter, the caller's. + shared, #! What any code may reach: the globals, the heap, and what pointers point at. +} + +#! How far a spot may outlive the body, as solving finds. +pub enum reach : u8 { + stays, #! Not past the body. + given, #! Given back, in what the body returns. + kept, #! Kept past the body, as where it is stored. +} + +#! A spot a reference may refer to. +pub struct spot { + var kind: spot_kind; #! What it stands for. + var node: u32; #! The node declaring it, or making it. + var held: u32; #! The set of what is stored in it. + var alone: u32; #! A set of it alone, or 0 until one is asked for. + var depth: u32; #! How many anonymous functions it is declared within. + var reach: reach; #! How far it may outlive the body. + var taken: bool; #! Whether a reference to it is made. +} + +#! The spots and sets of a body, and the flows between them. +pub struct flow { + var spots: vector; #! The spots. + var heads: vector; #! Of each set, one more than its first member's link, or 0. + var member: vector; #! Of each link of a set's members, the spot. + var next: vector; #! Of each link, one more than the next link of the same list, or 0. + var copies: vector; #! Of each set, one more than the first link of the sets it flows into. + var reads: vector; #! Of each set, one more than the first link of the sets what its spots hold flows into. + var writes: vector; #! Of each set, one more than the first link of the sets that flow into what its spots hold. + var known: hashset; #! The spots each set holds, by `pair_key(set, spot)`. + var edges: hashset; #! The flows from set to set, by `pair_key(from, to)`. + var work: vector; #! The spots added to sets not yet carried on, by `pair_key(set, spot)`. + var kept: u32; #! The set of what may be kept past the body. + var given: u32; #! The set of what the body may give back. + var shared: u32; #! The spot of what any code may reach. +} + +#! Makes the flows of a body, with nothing in them but the sets of what is kept +#! and given back, and the spot any code may reach, which holds itself. +#! @param alloc The optional allocator its memory is taken from. +#! @returns The flows. +pub def flow::new(alloc: maybe<&mut allocator>): flow { + var made := flow { + spots = vector::::new(alloc), + heads = vector::::new(alloc), + member = vector::::new(alloc), + next = vector::::new(alloc), + copies = vector::::new(alloc), + reads = vector::::new(alloc), + writes = vector::::new(alloc), + known = hashset::::new(alloc), + edges = hashset::::new(alloc), + work = vector::::new(alloc) + }; + # Set 0 stands for none. + made.heads.append(0); + made.copies.append(0); + made.reads.append(0); + made.writes.append(0); + made.kept = made.new_set(); + made.given = made.new_set(); + made.shared = made.new_spot(spot_kind::shared, 0, 0); + made.add(made.spots[made.shared as u64].held, made.shared); + return made; +} + +#! Makes an empty set. +#! @param this The flows. +#! @returns The set. +pub def flow::new_set(&mut this): u32 { + val made := this.heads.length as u32; + this.heads.append(0); + this.copies.append(0); + this.reads.append(0); + this.writes.append(0); + return made; +} + +#! Makes a spot, holding nothing yet. +#! @param this The flows. +#! @param kind What it stands for. +#! @param node The node declaring or making it. +#! @param depth How many anonymous functions it is declared within. +#! @returns The spot. +pub def flow::new_spot(&mut this, kind: spot_kind, node: u32, depth: u32): u32 { + val held := this.new_set(); + val made := this.spots.length as u32; + this.spots.append(spot { kind = kind, node = node, held = held, depth = depth }); + return made; +} + +#! The set of a spot alone, as a reference to it is. +#! @param this The flows. +#! @param at The spot. +#! @returns The set. +pub def flow::alone(&mut this, at: u32): u32 { + val had: u32 = this.spots[at as u64].alone; + return had if had != 0; + val made := this.new_set(); + this.spots[at as u64].alone = made; + this.add(made, at); + return made; +} + +#! The set of what a spot holds. +#! @param this The flows. +#! @param at The spot. +#! @returns The set. +pub def flow::held_by(&this, at: u32): u32 { + return this.spots[at as u64].held; +} + +#! Whether what is written to a spot leaves the body: the caller's, or what any +#! code may reach. +#! @param this The flows. +#! @param at The spot. +#! @returns Whether it does. +pub def flow::outside(&this, at: u32): bool { + val kind: spot_kind = this.spots[at as u64].kind; + return kind == spot_kind::outer || kind == spot_kind::inner || kind == spot_kind::shared; +} + +#! Adds a spot to a set, to be carried along its flows. +#! @param this The flows. +#! @param set The set, or 0 for none. +#! @param at The spot. +pub def flow::add(&mut this, set: u32, at: u32): void { + return if set == 0; + val key := pair_key(set, at); + return if !this.known.insert(key); + this.member.append(at); + this.next.append(this.heads[set as u64]); + this.heads[set as u64] = this.member.length as u32; + this.work.append(key); +} + +#! Links a set into one of the lists a set has of where it flows. +#! @param this The flows. +#! @param head The first link of the list, which becomes the new one. +#! @param set The set linked. +def flow::link(&mut this, head: &mut u32, set: u32): void { + this.member.append(set); + this.next.append(head); + head = this.member.length as u32; +} + +#! Has a set flow into another: every spot one holds, the other does. +#! @param this The flows. +#! @param from The set flowing, or 0 for none. +#! @param to The set it flows into, or 0 for none. +pub def flow::into(&mut this, from: u32, to: u32): void { + return if from == 0 || to == 0 || from == to; + return if !this.edges.insert(pair_key(from, to)); + var head: u32 = this.copies[from as u64]; + this.link(&mut head, to); + this.copies[from as u64] = head; + var at: u32 = this.heads[from as u64]; + while at != 0 { + this.add(to, this.member[at as u64 - 1]); + at = this.next[at as u64 - 1]; + } +} + +#! Has what each spot of a set holds flow into another set, as reading through +#! the references the set stands for does. +#! @param this The flows. +#! @param from The set read through, or 0 for none. +#! @param to The set what is read flows into, or 0 for none. +pub def flow::read(&mut this, from: u32, to: u32): void { + return if from == 0 || to == 0; + var head: u32 = this.reads[from as u64]; + this.link(&mut head, to); + this.reads[from as u64] = head; + var at: u32 = this.heads[from as u64]; + while at != 0 { + this.into(this.held_by(this.member[at as u64 - 1]), to); + at = this.next[at as u64 - 1]; + } +} + +#! Has a set flow into what each spot of another holds, as writing through the +#! references that set stands for does. What is written to a spot outside the +#! body is kept. +#! @param this The flows. +#! @param at The set written through, or 0 for none. +#! @param from The set written, or 0 for none. +pub def flow::write(&mut this, at: u32, from: u32): void { + return if at == 0 || from == 0; + var head: u32 = this.writes[at as u64]; + this.link(&mut head, from); + this.writes[at as u64] = head; + var each: u32 = this.heads[at as u64]; + while each != 0 { + val target: u32 = this.member[each as u64 - 1]; + this.into(from, this.outside(target) ? this.kept : this.held_by(target)); + each = this.next[each as u64 - 1]; + } +} + +#! A set of what reading through a set gives. +#! @param this The flows. +#! @param from The set, or 0 for none. +#! @returns The set read, or 0 for none. +pub def flow::read_of(&mut this, from: u32): u32 { + return 0 if from == 0; + val made := this.new_set(); + this.read(from, made); + return made; +} + +#! A set of what either of two sets holds. +#! @param this The flows. +#! @param a One set, or 0 for none. +#! @param b The other, or 0 for none. +#! @returns The set, or 0 for none. +pub def flow::either(&mut this, a: u32, b: u32): u32 { + return b if a == 0; + return a if b == 0; + val made := this.new_set(); + this.into(a, made); + this.into(b, made); + return made; +} + +#! Has a set's spots be kept past the body. +#! @param this The flows. +#! @param set The set, or 0 for none. +pub def flow::keep(&mut this, set: u32): void { + this.into(set, this.kept); +} + +#! Carries every spot added along the flows of the sets it was added to, until +#! no set grows. +#! @param this The flows. +pub def flow::solve(&mut this): void { + while this.work.length != 0 { + val key: u64 = this.work.last(); + this.work.truncate(); + val set := pair_high(key); + val at := pair_low(key); + var link: u32 = this.copies[set as u64]; + while link != 0 { + this.add(this.member[link as u64 - 1], at); + link = this.next[link as u64 - 1]; + } + link = this.reads[set as u64]; + while link != 0 { + this.into(this.held_by(at), this.member[link as u64 - 1]); + link = this.next[link as u64 - 1]; + } + link = this.writes[set as u64]; + while link != 0 { + this.into(this.member[link as u64 - 1], this.outside(at) ? this.kept : this.held_by(at)); + link = this.next[link as u64 - 1]; + } + } +} + +#! Works out how far each spot may outlive the body, once solved: those kept or +#! given back, those held by one that is, and those of the frame held by one +#! that may outlive them. +#! @param this The flows. +pub def flow::settle(&mut this): void { + var todo := vector::::new(); + this.mark_all(this.given, reach::given, &mut todo); + this.mark_all(this.kept, reach::kept, &mut todo); + + # A value a statement holds lives only while it runs, and a local only from + # where it is declared on, so one held by what may outlive it is kept. + for h in 0..this.spots.length { + val holder: spot = this.spots[h]; + continue if holder.kind != spot_kind::local && holder.kind != spot_kind::env && holder.kind != spot_kind::temp; + var at: u32 = this.heads[holder.held as u64]; + while at != 0 { + val held: u32 = this.member[at as u64 - 1]; + at = this.next[at as u64 - 1]; + val kind: spot_kind = this.spots[held as u64].kind; + val later := (kind == spot_kind::local || kind == spot_kind::env) && holder.kind != spot_kind::temp + && this.spots[held as u64].node > holder.node; + if (kind == spot_kind::temp && holder.kind != spot_kind::temp) || later { + this.mark(held, reach::kept, &mut todo); + } + } + } + + # Whoever holds a spot reaches what it holds. + while todo.length != 0 { + val at: u32 = todo.last(); + todo.truncate(); + val how: reach = this.spots[at as u64].reach; + var link: u32 = this.heads[this.spots[at as u64].held as u64]; + while link != 0 { + this.mark(this.member[link as u64 - 1], how, &mut todo); + link = this.next[link as u64 - 1]; + } + } +} + +#! Marks each spot of a set as outliving the body at least as far as given. +#! @param this The flows. +#! @param set The set. +#! @param how How far. +#! @param todo The spots whose reach grew, whose held spots are marked next. +def flow::mark_all(&mut this, set: u32, how: reach, todo: &mut vector): void { + var at: u32 = this.heads[set as u64]; + while at != 0 { + this.mark(this.member[at as u64 - 1], how, todo); + at = this.next[at as u64 - 1]; + } +} + +#! Marks a spot as outliving the body at least as far as given. +#! @param this The flows. +#! @param at The spot. +#! @param how How far. +#! @param todo The spots whose reach grew, whose held spots are marked next. +def flow::mark(&mut this, at: u32, how: reach, todo: &mut vector): void { + val had: reach = this.spots[at as u64].reach; + return if (had as u8) >= (how as u8); + this.spots[at as u64].reach = how; + todo.append(at); +} diff --git a/compiler/globals.sakura b/compiler/globals.sakura new file mode 100644 index 00000000..cb34d968 --- /dev/null +++ b/compiler/globals.sakura @@ -0,0 +1,158 @@ +#! @file globals.sakura +#! @author John Christman (sorakatadzuma@gmail.com) +#! @copyright Malunal Studios, LLC. +#! @license MIT +#! +#! Contains the globals: where each is among them, and ``, the +#! function the program runs before `main`, which gives each its value in the +#! order they are declared, after those its value reads. A constant is given +#! the value its declaration computes, as the program starts, until constants +#! are evaluated while compiling. + +import sakura::analyzer; +module sakura::compiler; + + +#! Lowers ``, which gives every global of the program its value. +#! @param this The compiler. +#! @returns The function's index. +pub def lowerer::lower_globals(&mut this): u32 { + val void_type := this.checker.types.function(span::::empty(), bt::void_type, false); + val index := this.add_function(string::from("", nothing {}), this.signature_of(void_type)); + this.program.functions[index].lowered = true; + this.program.functions[index].queued = true; + + var made := emitter::new(this, index); + for id in 1..this.checker.decls.count { + made.lower_global(id as u32); + } + made.build.ret(span::::empty()); + made.finish(); + return index; +} + +#! Whether a declaration is a global the program holds: a variable or constant +#! outside any function, or declared through a type, that checked. +#! @param this The compiler. +#! @param decl The declaration. +#! @returns Whether it is. +pub def lowerer::is_global(&this, decl: u32): bool { + return this.checker.decls.kinds.p[decl] == dk::variable && !this.checker.decls.has(decl, df::failed) + && this.checker.decls.nodes.p[decl] != 0; +} + +#! Gives a global its value in ``, after those its value reads. +#! @param this The emitter of ``. +#! @param decl The global's declaration. +pub def emitter::lower_global(&mut this, decl: u32): void { + return if !this.c.is_global(decl); + # A constant evaluated is held as data instead. + return if this.c.checker.decls.has(decl, df::constant) && this.c.evaluated.values.contains(&decl_key(decl)); + return if !this.c.begun_globals.insert(decl); + + val file: u32 = this.c.checker.decls.files.p[decl]; + val saved := this.c.checker.at; + this.c.checker.use_table(this.c.checker.units[file].table); + this.table = this.c.checker.units[file].table; + val node: u32 = this.c.checker.decls.nodes.p[decl]; + val value := this.c.checker.record(node, variable_slot::value); + + # The globals its value reads are given theirs first. + if value != 0 { + var reads := vector::::new(); + this.globals_read(value, &mut reads); + for &each in reads { + this.lower_global(each); + this.c.checker.use_table(this.table); + } + this.c.checker.use_table(this.c.checker.units[file].table); + this.table = this.c.checker.units[file].table; + } + + this.at_node(node); + val kind: u32 = this.c.checker.decls.types.p[decl]; + val mark := this.begin_statement(); + val place := this.global_place(decl); + # The globals begin as zeros, so one without a value is only given the + # defaults of its fields, and a `val` of a value known while compiling + # begins with it, so code that runs before `` gives it, as the + # runtime's does where values are allocated, reads it. + if value == 0 { + this.defaults(&place); + } else if this.refers_to_temporary(value) { + # A value referred to where it is made lives as long as the global bound + # to it, as a global of its own. + val taken := this.c.checker.type_at(value); + val referent := this.c.checker.types.first_of(this.c.checker.unalias(taken)); + val made := this.value_as(this.c.checker.left_of(value), referent); + this.adopt(&made); + val offset := this.c.unnamed_global(referent); + val address := this.build.value(op::global, span::::empty(), vt::word, 0, offset); + val held := location { kind = referent, address = address }; + this.store(&held, &made); + val referred := this.reference_to(&held, taken); + val converted := this.convert(&referred, kind); + this.store(&place, &converted); + } else { + val made := this.value_as(value, kind); + this.adopt(&made); + val fixed := !this.c.checker.decls.has(decl, df::mutable); + if !fixed || !this.preset(&place, &made) { + this.store(&place, &made); + } + } + this.end_statement(mark); + this.c.checker.at = saved; +} + +#! Gives a global the value it begins with, where that is a number known while +#! compiling, which it then has before any code runs. +#! @param this The emitter of ``. +#! @param place The global. +#! @param made Its value. +#! @returns Whether it was given, which it is not where the value is not known, +#! or not a number. +def emitter::preset(&mut this, place: &location, made: &operand): bool { + return false if made.count != 1 || made.address != 0 || place.address == 0 || place.offset != 0; + val at: origin = this.build.code.origins[place.address]; + val value: origin = this.build.code.origins[made.words[0]]; + return false if at.param || value.param || this.build.code.insts[at.from].kind != op::global; + val kind := this.build.code.insts[value.from].kind; + return false if kind != op::iconst && kind != op::fconst; + val bits: u64 = this.build.code.insts[value.from].imm; + val offset: u64 = this.build.code.insts[at.from].imm; + + # Only an integer or an `f64` is written as its bytes: an `f32` would be + # narrowed first, so it is left to the store. + val how := this.c.shape_of(place.kind).how; + return false if how == access::bytes || how == access::f32 || how.value_type().lanes(); + return false if kind == op::fconst && how != access::f64; + val width := how.width(); + if this.c.program.preset.length < offset + width { + this.c.program.preset.resize(offset + width); + } + for i in 0..width { + this.c.program.preset[offset + i] = ((bits >> (8 * i)) & 0xFF) as u8; + } + return true; +} + +#! Collects the globals an expression reads, by name. +#! @param this The emitter. +#! @param node The expression. +#! @param reads Where they are collected. +def emitter::globals_read(&mut this, node: u32, reads: &mut vector): void { + var walk := node_walk::new(node); + while walk.more() { + val at := walk.next(); + val kind := this.c.checker.kind_of(at); + if kind == nk::name || kind == nk::path { + val ref := this.c.checker.ref_at(at); + if ref != 0 && (ref & (ref_local | ref_type)) == 0 && this.c.is_global(ref) { + reads.append(ref); + } + } + continue if kind == nk::lambda; + walk.enter(this.c.checker.syn(), at); + } +} diff --git a/compiler/intermediate/builder.sakura b/compiler/intermediate/builder.sakura new file mode 100644 index 00000000..96158460 --- /dev/null +++ b/compiler/intermediate/builder.sakura @@ -0,0 +1,581 @@ +#! @file builder.sakura +#! @author John Christman (sorakatadzuma@gmail.com) +#! @copyright Malunal Studios, LLC. +#! @license MIT +#! +#! Contains the builder, which makes the intermediate code of a function in one +#! pass, as Braun et al.'s "Simple and Efficient Construction of Static Single +#! Assignment Form" does. What lowering calls a variable is written and read +#! by the builder, which finds the value it holds in the block where it is +#! read, or else along the edges into that block, making it a parameter of a +#! block where they join. A block is sealed once every edge into it is known, +#! and a parameter made before then is given its arguments as it is sealed. +#! Parameters that turn out to stand for one value, and blocks nothing reaches, +#! are taken out once the code is finished. + +import std::containers; +module sakura::compiler; + + +#! Builds the code of one function. +pub struct builder { + var code: code; #! What is built. + var at: u32; #! The block instructions are added to. + var pos: u64; #! Where in the source what is added is from: one more than the file, then the byte. + var kinds: vector; #! The type of each variable. + var defs: dict; #! The value of each variable in each block, by `pair_key(variable, block)`. + var sealed: vector; #! Whether each block is sealed. + var waiting: vector; #! Parameters of blocks not sealed yet, which wait for their arguments. + var held_for: vector; #! The variable each waiting parameter holds. + var zeros: u32[vt::count as u64]; #! The value of each type a variable has where nothing gave it one, made once. +} + +#! Makes a builder of code whose entry takes parameters of the types. +#! @param params The types of the parameters. +#! @returns The builder, adding to the entry, which is sealed, since nothing +#! goes back into it. +pub def builder::new(params: span): builder { + var made := builder { + code = code::new(), + kinds = vector::::new(scratch()), + defs = dict::::new(scratch()), + sealed = vector::::new(scratch()), + waiting = vector::::new(scratch()), + held_for = vector::::new(scratch()) + }; + made.sealed.append(true); + for &each in params { + made.code.add_param(0, each); + } + return made; +} + +#! The value of a parameter of the entry: one the function takes. +#! @param this The builder. +#! @param index Its position. +#! @returns The value. +pub def builder::param(&this, index: u32): u32 { + return this.code.blocks[0].params[index]; +} + +#! Adds a block, which takes nothing yet and is not sealed. +#! @param this The builder. +#! @returns The block. +pub def builder::new_block(&mut this): u32 { + this.sealed.append(false); + return this.code.add_block(); +} + +#! Makes instructions be added to the end of a block. +#! @param this The builder. +#! @param block The block. +pub def builder::switch_to(&mut this, block: u32): void { + this.at = block; +} + +#! Whether the block instructions are added to has ended, as after a `return`, +#! so what is added now is never reached. +#! @param this The builder. +#! @returns Whether it has. +pub def builder::ended(&this): bool { + val last: u32 = this.code.blocks[this.at].last; + return last != 0 && this.code.insts[last].kind.ends(); +} + +#! Says every edge into a block is known, giving the parameters it waits with +#! their arguments. +#! @param this The builder. +#! @param block The block. +pub def builder::seal(&mut this, block: u32): void { + return if this.sealed[block]; + + # Giving one its arguments may make more, which are given theirs in turn, in + # the order the block takes them. + var at: u64 = 0; + while at < this.waiting.length { + val param: u32 = this.waiting[at]; + if this.code.origins[param].from == block { + this.fill(this.held_for[at], param, block); + this.waiting.remove_at(at); + this.held_for.remove_at(at); + continue; + } + at++; + } + this.sealed[block] = true; +} + +#! Makes a variable of the type, which holds nothing yet. +#! @param this The builder. +#! @param kind Its type. +#! @returns The variable. +pub def builder::variable(&mut this, kind: vt): u32 { + this.kinds.append(kind); + return (this.kinds.length - 1) as u32; +} + +#! Gives a variable a value, from where instructions are added on. +#! @param this The builder. +#! @param variable The variable. +#! @param value The value. +pub def builder::assign(&mut this, variable: u32, value: u32): void { + this.defs.set(pair_key(variable, this.at), value); +} + +#! The value a variable holds where instructions are added. +#! @param this The builder. +#! @param variable The variable. +#! @returns The value. +pub def builder::read(&mut this, variable: u32): u32 { + return this.read_in(variable, this.at); +} + +#! The value a variable holds at the end of a block. +#! @param this The builder. +#! @param variable The variable. +#! @param block The block. +#! @returns The value. +def builder::read_in(&mut this, variable: u32, block: u32): u32 { + val key := pair_key(variable, block); + if this.defs.get(&key) is some(got) { + return got; + } + + val kind: vt = this.kinds[variable]; + var value: u32 = 0; + val count := this.code.blocks[block].preds.length; + if !this.sealed[block] { + # Edges into it may yet be added, so it takes the value, given later. + value = this.code.add_param(block, kind); + this.waiting.append(value); + this.held_for.append(variable); + } else if count == 0 { + value = this.zero(kind); + } else if count == 1 { + val edge: u32 = this.code.blocks[block].preds[0]; + value = this.read_in(variable, this.code.edge_source(edge)); + } else { + # Recorded before its arguments are found, which may come back to it. + value = this.code.add_param(block, kind); + this.defs.set(key, value); + this.fill(variable, value, block); + } + this.defs.set(key, value); + return value; +} + +#! Gives a parameter of a block the value the variable holds along each edge +#! into the block. +#! @param this The builder. +#! @param variable The variable it holds. +#! @param param The parameter. +#! @param block The block. +def builder::fill(&mut this, variable: u32, param: u32, block: u32): void { + var preds := this.code.blocks[block].preds.copied(scratch()); + for &edge in preds { + val given := this.read_in(variable, this.code.edge_source(edge)); + this.code.edges[edge].args.append(given); + } +} + +#! The value of the type a variable holds where nothing gave it one: zero, made +#! first in the entry, which every block follows. +#! @param this The builder. +#! @param kind The type. +#! @returns The value. +def builder::zero(&mut this, kind: vt): u32 { + val held: u32 = this.zeros[kind as u64]; + return held if held != 0; + + # Made in the entry, then moved first, so it stands before everything there. + val saved := this.at; + this.at = 0; + val made := kind == vt::real ? op::fconst : kind.lanes() ? op::vzero : op::iconst; + val value := this.value(made, span::::empty(), kind, 0, 0); + this.at = saved; + + val index: u32 = this.code.origins[value].from; + this.unlink(index); + this.code.put_first(0, index); + this.zeros[kind as u64] = value; + return value; +} + +#! Takes an instruction out of its block's order, where it is last. +#! @param this The builder. +#! @param index The instruction. +def builder::unlink(&mut this, index: u32): void { + val block: u32 = this.code.insts[index].block; + val before := this.code.before(index); + val after: u32 = this.code.insts[index].next; + if before == 0 { + this.code.blocks[block].first = after; + } else { + this.code.insts[before].next = after; + } + if this.code.blocks[block].last == index { + this.code.blocks[block].last = before; + } + this.code.insts[index].next = 0; +} + +#! Adds an instruction, in a block of its own where the block it would be added +#! to has ended, since nothing reaches it there. +#! @param this The builder. +#! @param kind What it does. +#! @param args Its operands. +#! @param gives The types of its results. +#! @param aux What its kind says `aux` holds. +#! @param imm What its kind says `imm` holds. +#! @returns The instruction. +pub def builder::emit(&mut this, kind: op, args: span, gives: span, aux: u32, imm: u64): u32 { + if this.ended() { + val unreached := this.new_block(); + this.seal(unreached); + this.at = unreached; + } + return this.code.append(this.at, kind, args, gives, aux, imm, this.pos); +} + +#! Adds an instruction giving one value. +#! @param this The builder. +#! @param kind What it does. +#! @param args Its operands. +#! @param give The type of what it gives. +#! @param aux What its kind says `aux` holds. +#! @param imm What its kind says `imm` holds. +#! @returns The value it gives. +pub def builder::value(&mut this, kind: op, args: span, give: vt, aux: u32, imm: u64): u32 { + var gives: vt[1] = [give]; + val index := this.emit(kind, args, gives[0:1], aux, imm); + return this.code.insts[index].result; +} + +#! Adds an instruction giving nothing. +#! @param this The builder. +#! @param kind What it does. +#! @param args Its operands. +#! @param aux What its kind says `aux` holds. +#! @param imm What its kind says `imm` holds. +#! @returns The instruction. +pub def builder::effect(&mut this, kind: op, args: span, aux: u32, imm: u64): u32 { + return this.emit(kind, args, span::::empty(), aux, imm); +} + +#! A word. +#! @param this The builder. +#! @param bits Its bits. +#! @returns The value. +pub def builder::word(&mut this, bits: u64): u32 { + return this.value(op::iconst, span::::empty(), vt::word, 0, bits); +} + +#! A real. +#! @param this The builder. +#! @param bits The bits of the `f64` it is. +#! @returns The value. +pub def builder::real(&mut this, bits: u64): u32 { + return this.value(op::fconst, span::::empty(), vt::real, 0, bits); +} + +#! An operator of two values. +#! @param this The builder. +#! @param kind The operator. +#! @param a The first operand. +#! @param b The second operand. +#! @returns What it gives: a real for arithmetic of reals, and otherwise a word. +pub def builder::binary(&mut this, kind: op, a: u32, b: u32): u32 { + var args: u32[2] = [a, b]; + val gives := kind == op::fadd || kind == op::fsub || kind == op::fmul || kind == op::fdiv || kind == op::frem + ? vt::real : vt::word; + return this.value(kind, args[0:2], gives, 0, 0); +} + +#! An operator of one value. +#! @param this The builder. +#! @param kind The operator. +#! @param a The operand. +#! @returns What it gives: a real where it gives one, and otherwise a word. +pub def builder::unary(&mut this, kind: op, a: u32): u32 { + var args: u32[1] = [a]; + val gives := kind == op::fneg || kind == op::itof || kind == op::utof || kind == op::fsingle || kind == op::fsqrt + ? vt::real : vt::word; + return this.value(kind, args[0:1], gives, 0, 0); +} + +#! A word narrowed to a number of bits. +#! @param this The builder. +#! @param a The word. +#! @param bits How many bits it keeps. +#! @param signed Whether it is sign-extended rather than zero-extended. +#! @returns The word narrowed. +pub def builder::wrap(&mut this, a: u32, bits: u32, signed: bool): u32 { + var args: u32[1] = [a]; + return this.value(op::wrap, args[0:1], vt::word, bits, signed ? 1 : 0); +} + +#! The address of a cell. +#! @param this The builder. +#! @param index The cell. +#! @returns The address. +pub def builder::cell_address(&mut this, index: u32): u32 { + return this.value(op::cell, span::::empty(), vt::word, index, 0); +} + +#! Reads a value from memory. +#! @param this The builder. +#! @param how How it is read. +#! @param address The address. +#! @param offset How many bytes past the address it is. +#! @returns The value, a real for a float, a vector for lanes, and a word +#! otherwise. +pub def builder::load(&mut this, how: access, address: u32, offset: u64): u32 { + var args: u32[1] = [address]; + return this.value(op::load, args[0:1], how.value_type(), how as u32, offset); +} + +#! Writes a value to memory. +#! @param this The builder. +#! @param how How it is written. +#! @param address The address. +#! @param offset How many bytes past the address it goes. +#! @param value The value. +pub def builder::store(&mut this, how: access, address: u32, offset: u64, value: u32): void { + var args: u32[2] = [address, value]; + this.effect(op::store, args[0:2], how as u32, offset); +} + +#! Copies bytes from one address to another. +#! @param this The builder. +#! @param to Where they go. +#! @param from Where they come from. +#! @param size How many there are. +pub def builder::copy(&mut this, to: u32, from: u32, size: u64): void { + return if size == 0; + var args: u32[2] = [to, from]; + this.effect(op::copy, args[0:2], 0, size); +} + +#! Zeroes bytes from an address. +#! @param this The builder. +#! @param address The address. +#! @param size How many there are. +pub def builder::clear(&mut this, address: u32, size: u64): void { + return if size == 0; + var args: u32[1] = [address]; + this.effect(op::clear, args[0:1], 0, size); +} + +#! Marks bytes at an address as never written, running with memory checked. +#! @param this The builder. +#! @param address The address. +#! @param size How many bytes. +pub def builder::forget(&mut this, address: u32, size: u64): void { + return if size == 0; + var args: u32[1] = [address]; + this.effect(op::forget, args[0:1], 0, size); +} + +#! Stops the program with an error where a word is zero. +#! @param this The builder. +#! @param cond The word. +#! @param error The error, as the machine numbers them. +pub def builder::check(&mut this, cond: u32, error: u32): void { + var args: u32[1] = [cond]; + this.effect(op::check, args[0:1], error, 0); +} + +#! Ends the block going to another. +#! @param this The builder. +#! @param target The block. +pub def builder::jump(&mut this, target: u32): void { + return if this.ended(); + val index := this.effect(op::jump, span::::empty(), 0, 0); + this.code.insts[index].aux = this.code.add_edge(index, target, 0); +} + +#! Ends the block going to one block where a word is not zero, and another +#! where it is. +#! @param this The builder. +#! @param cond The word. +#! @param then Where it goes where the word is not zero. +#! @param other Where it goes where it is. +pub def builder::branch(&mut this, cond: u32, then: u32, other: u32): void { + return if this.ended(); + var args: u32[1] = [cond]; + val index := this.effect(op::branch, args[0:1], 0, 0); + this.code.insts[index].aux = this.code.add_edge(index, then, 0); + this.code.add_edge(index, other, 0); +} + +#! Ends the block returning words, or the memory at an address. +#! @param this The builder. +#! @param args The words, or the address. +pub def builder::ret(&mut this, args: span): void { + return if this.ended(); + this.effect(op::ret, args, 0, 0); +} + +#! Ends the block stopping the program with an error. +#! @param this The builder. +#! @param error The error, as the machine numbers them. +pub def builder::trap(&mut this, error: u32): void { + return if this.ended(); + this.effect(op::trap, span::::empty(), error, 0); +} + +#! Ends the block as one nothing goes on from, as after a call that never +#! returns. +#! @param this The builder. +pub def builder::unreachable(&mut this): void { + return if this.ended(); + this.effect(op::unreachable, span::::empty(), 0, 0); +} + +#! Finishes the code: seals what is not sealed, takes out the blocks nothing +#! reaches and the parameters standing for one value, and gives the code. +#! @param this The builder. +#! @returns The code. +pub def builder::finish(&mut this): code { + # A block left open, as one control falls off the end of, ends unreached. + for i in 0..this.code.blocks.length { + this.at = i as u32; + if !this.ended() { + this.unreachable(); + } + this.seal(i as u32); + } + + this.code.prune(); + return move(&mut this.code); +} + +#! Takes out the blocks the entry does not reach, and the parameters that stand +#! for one value, being given it, or themselves, along every edge, so each use +#! of one uses that value instead. +#! @param this The code. +pub def code::prune(&mut this): void { + this.forget_order(); + this.drop_unreached(); + this.drop_lone_params(); +} + +#! Takes out the parameters that stand for one value, being given it, or +#! themselves, along every edge, so each use of one uses that value instead. +#! @param this The code. +pub def code::drop_lone_params(&mut this): void { + return if !this.has_lone_param(); + + # What each parameter taken out stands for, followed until one that is not. + var aliases := vector::::new(scratch()); + aliases.resize(this.origins.length); + val links := aliases.view().data; + val count := aliases.length; + var changed := true; + while changed { + changed = false; + for b in 1..this.blocks.length { + continue if this.blocks[b].gone; + for p in 0..this.blocks[b].params.length { + val param: u32 = this.blocks[b].params[p]; + continue if aliases[param] != 0; + + var only: u32 = 0; + var many := false; + for &edge in this.blocks[b].preds { + val given := follow_replaced(links, count, this.edges[edge].args[p]); + continue if given == param || given == only; + if only != 0 { + many = true; + break; + } + only = given; + } + continue if many || only == 0; + aliases[param] = only; + changed = true; + } + } + } + + # Each use reads what it stands for, and each edge gives only the parameters + # left. + for i in 0..this.operands.length { + this.operands[i] = follow_replaced(links, count, this.operands[i]); + } + var keeps := vector::::new(scratch()); + for b in 0..this.blocks.length { + continue if this.blocks[b].gone; + for &edge in this.blocks[b].preds.view() { + var args := this.edges[edge].args.slice(); + for p in 0..args.length { + args[p] = follow_replaced(links, count, args[p]); + } + } + keeps.clear(); + for ¶m in this.blocks[b].params.view() { + keeps.append(aliases[param] == 0); + } + if keeps.view().contains(&false) { + this.drop_params(b as u32, keeps.view()); + } + } +} + +#! Whether a block takes a parameter every edge into it gives one value, or +#! itself, which pruning takes out. +#! @param this The code. +#! @returns Whether one does. +def code::has_lone_param(&this): bool { + for b in 1..this.blocks.length { + continue if this.blocks[b].gone; + for p in 0..this.blocks[b].params.length { + val param: u32 = this.blocks[b].params[p]; + var only: u32 = 0; + var many := false; + for &edge in this.blocks[b].preds { + val given: u32 = this.edges[edge].args[p]; + continue if given == param || given == only; + if only != 0 { + many = true; + break; + } + only = given; + } + return true if !many; + } + } + return false; +} + +#! Marks the blocks the entry does not reach as gone, and takes their edges out +#! of the blocks they went to. Those it reaches are the blocks of their order, +#! worked out where the code does not keep it, and kept, as what comes after +#! asks it. +#! @param this The code. +pub def code::drop_unreached(&mut this): void { + this.keep_order(); + + # Only the blocks a block newly gone went to lose edges. + var touched := vector::::new(scratch()); + for b in 0..this.blocks.length { + continue if this.kept_number[b] != 0xFFFFFFFF || this.blocks[b].gone; + this.blocks[b].gone = true; + val last: u32 = this.blocks[b].last; + continue if last == 0; + val first: u32 = this.insts[last].aux; + for e in 0..this.edge_count(last) { + touched.append(this.edges[first + e as u32].target); + } + } + for &b in touched { + continue if this.kept_number[b] == 0xFFFFFFFF; + var kept := ids {}; + for &edge in this.blocks[b].preds { + if this.kept_number[this.edge_source(edge)] != 0xFFFFFFFF { + kept.append(edge); + } + } + this.blocks[b].preds = move(&mut kept); + } +} diff --git a/compiler/intermediate/cells.sakura b/compiler/intermediate/cells.sakura new file mode 100644 index 00000000..c8d956f3 --- /dev/null +++ b/compiler/intermediate/cells.sakura @@ -0,0 +1,205 @@ +#! @file cells.sakura +#! @author John Christman (sorakatadzuma@gmail.com) +#! @copyright Malunal Studios, LLC. +#! @license MIT +#! +#! Contains which cells of a function's frame are zeroed as it begins, by an +#! executable's prologue and by the machine alike. The code reads a cell as +#! zeroed where nothing wrote it yet, so a cell is zeroed as the function +#! begins unless every word of it some path reads is written first on every +#! path to the read. A cell whose address is given anywhere but to reading, +#! writing, copying, and clearing it at offsets the code knows may be read +#! anywhere from there on, so where it is given is a read of every word of it: +#! a cell written whole before its address goes anywhere is not zeroed, as +#! one a statement makes before handing it to a call. A call writing what it +#! returns to a cell, at the address its last operand gives, writes it whole. + +module sakura::compiler; + + +#! The most words of a cell the analysis follows; a larger one is zeroed. +const followed_words: u64 = 64; + +#! Finds which cells a function's prologue zeroes. +#! @param body The code. +#! @param order Its blocks, in reverse postorder. +#! @param number Each block's place in that order. +#! @param writes Of each instruction, the bytes a call writes what it +#! returns to at its last operand, or 0, as `result_writes` +#! gives them. +#! @returns Whether each cell is zeroed. +pub def zeroed_cells(body: &code, order: span, number: span, writes: span): vector { + val cells := body.cells.length; + var zeroed := vector::::new(scratch()); + zeroed.resize(cells); + return zeroed if cells == 0; + + # A cell too large to follow is zeroed. + for c in 0..cells { + if (body.cells[c].size as u64 + 7) / 8 > followed_words { + zeroed[c] = true; + } + } + val addresses := body.cell_table(); + var reads := body.reader(); + + # The words written for sure where each block ends, by cell, a word a bit, + # until they no longer change; each starts as every word, but at the entry. + var outs := vector::::new(scratch()); + outs.resize(body.blocks.length * cells, 0xFFFFFFFFFFFFFFFF); + var state := vector::::new(scratch()); + state.resize(cells); + var changed := true; + var rounds := 0; + while changed && rounds < 64 { + changed = false; + rounds++; + for k in 0..order.length { + val block: u32 = order[k]; + for c in 0..cells { + state[c] = block == 0 ? 0 : 0xFFFFFFFFFFFFFFFF; + } + for p in 0..body.blocks[block].preds.length { + val from := body.edge_source(body.blocks[block].preds[p]); + continue if number[from] == 0xFFFFFFFF; + for c in 0..cells { + state[c] = state[c] & outs[from as u64 * cells + c]; + } + } + walk_block(body, block, &addresses, &mut reads, writes, &mut state, &mut zeroed); + for c in 0..cells { + val at := block as u64 * cells + c; + if outs[at] != state[c] { + outs[at] = state[c]; + changed = true; + } + } + } + } + if changed { + for c in 0..cells { + zeroed[c] = true; + } + } + return zeroed; +} + +#! The bits of the words a run of bytes covers wholly, from the first word. +#! @param offset Where the run begins. +#! @param size How many bytes it takes. +#! @returns The bits. +def cell_words_whole(offset: u64, size: u64): u64 { + val first := (offset + 7) / 8; + val end := (offset + size) / 8; + return 0 if end <= first || first >= 64; + return bits_between(first, end > 64 ? 64 : end); +} + +#! The bits of the words a run of bytes touches, from the first word. +#! @param offset Where the run begins. +#! @param size How many bytes it takes. +#! @returns The bits. +def cell_words_touched(offset: u64, size: u64): u64 { + return 0 if size == 0; + val first := offset / 8; + val end := (offset + size + 7) / 8; + return 0 if first >= 64; + return bits_between(first, end > 64 ? 64 : end); +} + +#! The bits from one up to another. +#! @param from The first bit. +#! @param to Past the last, at most 64. +#! @returns The bits. +def bits_between(from: u64, to: u64): u64 { + val high := to >= 64 ? 0xFFFFFFFFFFFFFFFF : (1u << to) - 1; + val low := (1u << from) - 1; + return high & ~low; +} + +#! Walks a block's instructions, from what is written for sure where it begins +#! to where it ends, noting each cell a read finds a word of not yet written. +#! @param body The code. +#! @param block The block. +#! @param addresses Which cell each value is the address of. +#! @param reads A walk of what the code's instructions read. +#! @param writes Of each instruction, the bytes a call writes what it +#! returns to at its last operand, or 0. +#! @param state What is written of each cell, a word a bit. +#! @param zeroed Whether each cell is zeroed. +def walk_block( + body: &code, + block: u32, + addresses: &cell_table, + reads: &mut read_walk, + writes: span, + state: &mut vector, + zeroed: &mut vector +): void { + var walk := body.walk(block); + while walk.more() { + val at := walk.next(); + val held: inst = body.insts[at]; + + # A cell's address given anywhere but to the reads and writes below, and + # to where a call writes what it returns, may be read anywhere from here, + # as an edge's argument always may be, so every word of the cell is read + # here. + val returned: u64 = (at as u64) < writes.length ? writes[at] : 0; + var written: u32 = 0; + reads.start(at); + while reads.more() { + val cell := addresses.cell(reads.next()); + continue if cell == 0; + val a := reads.operand(); + val known := a != no_operand && match held.kind { + op::load, op::clear, op::store => a == 0, + op::copy => a < 2, + else => false + }; + continue if known; + if a != no_operand && returned != 0 && a + 1 == held.argc { + written = cell; + continue; + } + if (cell_words_touched(0, body.cells[cell - 1].size as u64) & ~state[cell - 1]) != 0 { + zeroed[cell - 1] = true; + } + } + if written != 0 { + state[written - 1] = state[written - 1] | cell_words_whole(0, returned); + } + + match held.kind { + op::load => { + val cell := addresses.cell(body.operands[held.args as u64]); + continue if cell == 0; + val read := cell_words_touched(held.imm, (held.aux as access).width()); + if (read & ~state[cell - 1]) != 0 { + zeroed[cell - 1] = true; + } + } + op::store => { + val cell := addresses.cell(body.operands[held.args as u64]); + continue if cell == 0; + state[cell - 1] = state[cell - 1] | cell_words_whole(held.imm, (held.aux as access).width()); + } + op::clear => { + val cell := addresses.cell(body.operands[held.args as u64]); + continue if cell == 0; + state[cell - 1] = state[cell - 1] | cell_words_whole(0, held.imm); + } + op::copy => { + val from := addresses.cell(body.operands[held.args as u64 + 1]); + if from != 0 && (cell_words_touched(0, held.imm) & ~state[from - 1]) != 0 { + zeroed[from - 1] = true; + } + val to := addresses.cell(body.operands[held.args as u64]); + if to != 0 { + state[to - 1] = state[to - 1] | cell_words_whole(0, held.imm); + } + } + else => {} + } + } +} diff --git a/compiler/intermediate/code.sakura b/compiler/intermediate/code.sakura new file mode 100644 index 00000000..187be6bb --- /dev/null +++ b/compiler/intermediate/code.sakura @@ -0,0 +1,677 @@ +#! @file code.sakura +#! @author John Christman (sorakatadzuma@gmail.com) +#! @copyright Malunal Studios, LLC. +#! @license MIT +#! +#! Contains the intermediate code of a function: values each assigned once, +#! the instructions giving them, the blocks holding the instructions, and the +#! cells of the frame that what is too large to be a value, or whose address is +#! taken, lives in. Where control flow joins, values arrive as the parameters +#! of a block, which each jump into it gives arguments for. +#! +#! A value is a word: an integer, which every integer type, `bool`, enum, and +#! pointer is held as, widened as a frame holds it, or a float, which an `f32` +#! is held as rounded to its precision. A reference is one value, its address, +#! and a reference to a trait or a function two. Structs, +#! unions, and fixed arrays live in cells or on the heap, and are read and +#! written through their addresses. An executable also has vectors, 16 or 32 +#! bytes of lanes, which a cell holding a `simd` becomes where promoted. + +module sakura::compiler; + + +#! The type of a value. +pub enum vt : u8 { + none, #! No value. + word, #! A 64-bit integer, which every integer type, `bool`, enum, and pointer is held as. + real, #! A 64-bit float, which an `f32` is held as. + v128, #! 16 bytes of lanes, which only an executable holds. + v256, #! 32 bytes of lanes, which only code for processors with AVX holds. + v512, #! 64 bytes of lanes, which only an executable holds, in memory, working them with AVX-512 where the processor has it. + count, #! How many types there are, which sizes the tables of them; not a type itself. +} + +#! What an instruction does. Each says what its operands are, what its `aux` +#! and `imm` hold, and what it gives. Operators of integers take and give words, +#! and those of floats reals, but for comparisons, which give a word of 0 or 1. +pub enum op : u8 { + # Constants. + iconst, #! A word: `imm` is its bits. + fconst, #! A real: `imm` is its bits. + + # Operators of two words, giving a word. + add, #! `a + b`, wrapping at 64 bits. + sub, #! `a - b`. + mul, #! `a * b`. + divs, #! `a / b` of signed words, stopping where `b` is zero. + divu, #! `a / b` of unsigned words, stopping where `b` is zero. + rems, #! What is left dividing signed words, stopping where `b` is zero. + remu, #! What is left dividing unsigned words, stopping where `b` is zero. + band, #! `a & b`. + bor, #! `a | b`. + bxor, #! `a ^ b`. + shl, #! `a << b`. + shrs, #! `a >> b`, keeping the sign. + shru, #! `a >> b`, filling with zeros. + eq, #! `a == b`. + ne, #! `a != b`. + lts, #! `a < b`, signed. + ltu, #! `a < b`, unsigned. + les, #! `a <= b`, signed. + leu, #! `a <= b`, unsigned. + eqsu, #! `a == b`, where `a` is signed and `b` unsigned, compared as the numbers they are. + ltsu, #! `a < b`, where `a` is signed and `b` unsigned. + lesu, #! `a <= b`, where `a` is signed and `b` unsigned. + ltus, #! `a < b`, where `a` is unsigned and `b` signed. + leus, #! `a <= b`, where `a` is unsigned and `b` signed. + + # Operators of two reals. + fadd, #! `a + b`, giving a real. + fsub, #! `a - b`, giving a real. + fmul, #! `a * b`, giving a real. + fdiv, #! `a / b`, giving a real. + frem, #! What is left dividing, whose sign is the dividend's, giving a real. + feq, #! `a == b`, giving a word. + fne, #! `a != b`, giving a word. + flt, #! `a < b`, giving a word. + fle, #! `a <= b`, giving a word. + + # Operators of one value. + neg, #! `-a` of a word. + bnot, #! `~a` of a word. + lnot, #! 1 where the word is zero, and 0 otherwise. + fneg, #! `-a` of a real. + itof, #! The real a signed word is. + utof, #! The real an unsigned word is. + ftoi, #! The signed word a real is, toward zero, saturating. + ftou, #! The unsigned word a real is, toward zero, saturating. + fsingle, #! The real rounded to the precision of an `f32`. + fsqrt, #! The square root of a real, rounded once. + ones, #! How many bits of the word are 1. + clz, #! How many 0 bits lead the word from its top, 64 where it is zero. + ctz, #! How many 0 bits trail the word from its bottom, 64 where it is zero. + bswap, #! The word with its bytes in the reverse order. + wrap, #! The word narrowed to `aux` bits, sign-extended where `imm` is 1 and zero-extended otherwise. + + # Choosing. + select, #! (condition, a, b): `a` where the word is not zero, and `b` where it is, both words or both reals. + + # Addresses. + cell, #! The address of the cell `aux`. + global, #! The address `imm` bytes into the globals. + datum, #! The address `imm` bytes into the bytes of datum `aux`, which are never written. + + # Memory, `imm` bytes from an address. + load, #! (address): the value there, read as access `aux` says. + store, #! (address, value): writes the value there, as access `aux` says. + copy, #! (to, from): copies `imm` bytes. + clear, #! (address): zeroes `imm` bytes. + forget, #! (address): running with its memory checked, marks `imm` bytes as never written, so reading one before writing it stops the program; elsewhere nothing. + + # Memory the program holds. + allocate, #! (size): zeroed memory the program gives back itself, or with aux 1 memory not cleared. + release, #! (address): gives memory back. + resize, #! (address, size): memory holding what the address's did. + + # Calls, whose results are the words the callee returns, followed, where it + # returns memory, by an operand giving the address it is written to. + call, #! (arguments...): calls function `aux`. + call_trait, #! (pointer, vtable, arguments...): calls slot `imm` of the vtable, by signature `aux`. + call_value, #! (function, environment, arguments...): calls a function value, by signature `aux`. + call_c, #! (address, arguments...): calls a C function, by signature `aux`. + c_address, #! The address of the C function `aux` names. + callback, #! The address C calls function `aux` through. + + # Values the runtime works with. + equal, #! (a, b): 1 where the values at the addresses of layout `aux` are equal. + retrait, #! (vtable): the vtable map `aux` gives, as a trait reference becomes another. + check, #! (condition): stops the program with error `aux` where the word is zero. + + # The system. + syscall, #! (number, a, b, c, d, e, f): what the kernel gives. + frame, #! The frame pointer, in an executable. + image, #! The image an executable was built with. + environ, #! Where the system put the variables the program started with. + signals, #! The signals that came since last asked, one bit each. + catch, #! (number): has the backend note the signal, giving 0 or the negated error. + safepoint, #! Calls function `aux` where a signal the program handles has come. + exit, #! (code): ends the program with the status, having run everything asked of it. + abort, #! Ends the program at once, reporting where it was. + fault, #! (pointer, length): ends the program at once, reporting the text and where it was. + + # Formatting text, which `format` begins and `format_owned` takes. + format, #! Begins text. + format_text, #! Adds the bytes of datum `aux`. + format_value, #! (value...): adds a value of layout `aux`, its words, or the address of its memory. + format_bytes, #! (pointer, length): adds the bytes. + format_owned, #! The text made, as two words: its pointer and length, in memory the program gives back. + + # Checks only a program evaluating constants makes. + ready, #! Stops unless the constant evaluation `aux` computes is evaluated. + reach, #! (pointer, count): stops unless that many elements of `imm` bytes from the pointer are memory the program holds. + same, #! (a, b): stops unless the pointers are within the same memory. + + # Vector instructions, which only an executable works. + cpu, #! The instruction sets of the processor running the executable, one bit each, as it found them when it started; `imm` those known to be among them. + lanes, #! (a, b, c...): operation `aux` on lanes, of type `imm & 0xFF` and `imm >> 8` bytes in all, giving a vector, or the word of a mask's bits. + vzero, #! A vector of zero bytes. + + # Atomics, which several threads, or a thread and a signal handler, read and + # write without a lock. Each touches all memory, as a call does, so no load or + # store moves across one. + atomic, #! (address, operands..., orders...): operation `aux`, as `atomic_` numbers them, of access `imm`, giving what the address held. + + # Threads. + start, #! (function, environment): starts a thread running the function value, giving its number or the negated error. + current, #! The running thread's record, in an executable. + clone, #! (record): starts a thread of the system on the record's stacks, running `runtime::thread_main`, in an executable. + + # Ends of blocks. + jump, #! Goes to edge `aux`. + branch, #! (condition): goes to edge `aux` where the word is not zero, and edge `aux + 1` where it is. + switch, #! (word): goes to the edge from `aux` whose case is the word, of `imm` edges, the last being the default. + ret, #! (words..., address): returns the words, or the memory at the address. + trap, #! Stops the program with error `aux`, or with the error a word it takes says. + unreachable, #! Is never reached. + + count, #! How many operations there are, which sizes the tables of them; not an operation itself. +} + +#! How a value is read from memory or written to it, as the program's layouts +#! give it, in the order of the C machine's `access`. +pub enum access : u8 { + i8, #! A signed byte. + u8, #! An unsigned byte. + i16, #! A signed 16-bit integer. + u16, #! An unsigned 16-bit integer. + i32, #! A signed 32-bit integer. + u32, #! An unsigned 32-bit integer. + i64, #! A 64-bit integer. + f32, #! An `f32`, read as a real. + f64, #! An `f64`. + bytes, #! No word: what is copied as bytes. + v128, #! 16 bytes of lanes, read as a vector. + v256, #! 32 bytes of lanes, read as a vector. + v512, #! 64 bytes of lanes, read as a vector. +} + +#! The errors code stops a program with, numbered as the machine numbers them. +pub enum fault : u32 { + out_of_bounds = 4, #! An index past the end, or a slice outside what it slices. + null_reference = 5, #! Reaching through a null pointer. + division = 6, #! Dividing by zero. + not_held = 7, #! Reading a field of a union holding another. + unreachable = 9, #! Reaching the end of a function that returns a value. + not_member = 13, #! Converting an integer to an enum none of whose members has its value. + not_constant = 15, #! Running, while compiling, what only the program running can. +} + +#! The addresses below which a program holds no memory: the first page, which no +#! system maps. The machine stops at a read or a write there as at null, and an +#! executable faults there, whether the address is null or some way past it, as +#! an element of a null pointer is, so neither compares a pointer with null +#! before reaching through it where what it reaches stays within the page. +pub const null_page: u64 = 4096; + +#! An instruction. +pub struct inst { + pub var kind: op; #! What it does. + pub var count: u8; #! How many results it gives. + pub var aux: u32; #! What its kind says: a cell, a function, a layout, an edge. + pub var imm: u64; #! What its kind says: bits, an offset, a size. + pub var args: u32; #! Where its operands begin in `operands`. + pub var argc: u32; #! How many operands it takes. + pub var result: u32; #! Its first result, the others following it. + pub var block: u32; #! The block holding it. + pub var next: u32; #! The next instruction of its block, or 0. + pub var at: u64; #! Where in the source it is from: one more than the file, then the byte. + pub var site: u32; #! One more than the site of the function it was inlined from, or 0 for the function's own. +} + +#! Where a function's code was put within another's, which called it there. +#! A trace names it as a frame of its own, as though it were called. +pub struct inline_site { + pub var function: u32; #! The function inlined. + pub var at: u64; #! Where it was called: one more than the file, then the byte. + pub var parent: u32; #! One more than the site the call was within, or 0 for the function's own code. +} + +#! Where a value comes from: the instruction giving it, as one of its results, +#! or the block taking it, as one of its parameters. +pub struct origin { + pub var kind: vt; #! Its type. + pub var param: bool; #! Whether a block takes it. + pub var from: u32; #! The instruction or block. + pub var index: u32; #! Which of its results or parameters it is. +} + +#! A block: instructions in order, the last of which ends it. +pub struct block { + pub var first: u32; #! Its first instruction, or 0. + pub var last: u32; #! Its last instruction, or 0. + pub var params: ids; #! The values it takes. + pub var preds: ids; #! The edges into it. + pub var gone: bool; #! Whether it was removed, as unreachable. +} + +#! A way out of a block into another, with the arguments it gives the other's +#! parameters. +pub struct edge { + var from: u32; #! The instruction it leaves by. + pub var target: u32; #! The block it goes to. + pub var args: ids; #! The values it gives the block's parameters. + pub var case: u64; #! Of a `switch`, the word it goes on. +} + +#! The kinds of cell. +pub enum ck : u8 { + temporary, #! What a statement holds while it runs. + local, #! A variable, for the scope it is declared in. + param, #! A parameter taken as memory, whose address the entry block takes. + inlined, #! A cell of a function inlined, which its code clears or copies into where it begins, so the frame does not zero it. + undefined, #! A variable declared `= undefined`, which nothing zeroes, where it is declared or where its function is inlined. +} + +#! A cell of the frame. +pub struct cell { + pub var size: u32; #! How many bytes it holds. + pub var align: u32; #! What its address is a multiple of. + pub var kind: ck; #! What it holds. + var name: u32; #! The ID of the name of the variable it holds, or 0. +} + +#! A variable debugging information shows: a named local or parameter, and +#! where it is. Code lowered with its locals kept in cells holds each in +#! memory, with the instructions its scope covers. Optimized code holds a local +#! of words in values instead, which the code's bindings name. +pub struct variable_info { + pub var name: u32; #! The ID of its name. + pub var at: u64; #! Where it is declared: one more than the file, then the byte. + pub var kind: u32; #! Its type. + pub var layout: u32; #! Its layout, worked out once the program's are written, so noting it makes none. + pub var cell: u32; #! One more than the cell holding it, or 0 where it is a parameter given as memory. + pub var given: u32; #! Of a parameter given as memory, one more than which of the code's parameters is its address, or 0. + pub var param: bool; #! Whether it is a parameter. + pub var boxed: bool; #! Whether it is in an object of the heap: whose address its cell holds, or its binding names. + pub var held: bool; #! Whether it is held in values, which the code's bindings name. + pub var site: u32; #! One more than the inline site it was declared in, or 0 for the function's own. + pub var first: u32; #! How many instructions the code had where its scope begins. + pub var end: u32; #! How many it had where its scope ends, or 0 where it lasts to the end. +} + +#! A value a variable held in values takes: from where it was given the value +#! on, it is that word of the variable, until another value is. Where the value +#! was a constant whose instruction went, the binding keeps the constant in its +#! place, as a constant is known anywhere. +pub struct binding { + pub var variable: u32; #! The variable, among the code's. + pub var word: u32; #! Which of its words. + pub var value: u32; #! The value, or 0 where it keeps a constant. + pub var after: u32; #! The instruction it was given the value after, or 0 where it was where its block begins. + pub var block: u32; #! The block it was given the value in, or `no_block` where that went. + pub var known: vt; #! The type of the constant it keeps, or `none` where it names a value. + pub var bits: u64; #! The constant's bits. +} + +#! The intermediate code of one function. Instruction 0 and value 0 stand for +#! none, and block 0 is the entry, whose parameters are the function's. +pub struct code { + pub var insts: vector; #! The instructions, by index. + pub var operands: vector; #! The values the instructions take, as runs `args` and `argc` give. + pub var origins: vector; #! Where each value comes from, by index. + pub var blocks: vector; #! The blocks, by index. + pub var edges: vector; #! The ways between them, by index. + pub var cells: vector; #! The cells of the frame, by index. + var results: vector; #! The words it returns. + pub var returned: u32; #! The bytes of the memory it returns, or 0 where it returns words. + pub var sites: vector; #! Where the functions inlined into it were called, which instructions name. + pub var variables: vector; #! Its variables, which debugging information shows. + pub var bindings: vector; #! The values its variables held in values take. + pub var vectors: bool; #! Whether it is an executable's, which may hold 16 bytes of lanes as values. + pub var wide: bool; #! Whether it runs only where the processor has AVX, so 32 bytes of lanes may be held as values. + var kept_order: vector; #! The blocks in reverse postorder, as last worked out, where `order_kept` says it holds. + var kept_number: vector; #! Each block's place in `kept_order`, or `0xFFFFFFFF` for one the entry does not reach. + var kept_idom: vector; #! Each block's immediate dominator, as last worked out, where `idom_kept` says it holds. + var order_kept: bool; #! Whether `kept_order` and `kept_number` hold for the blocks as they are. + var idom_kept: bool; #! Whether `kept_idom` holds for the blocks as they are. +} + +#! Makes code of one empty block, the entry. +#! @returns The code. +pub def code::new(): code { + var made := code { + insts = vector::::new(), + operands = vector::::new(), + origins = vector::::new(), + blocks = vector::::new(), + edges = vector::::new(), + cells = vector::::new(), + results = vector::::new(), + sites = vector::::new(), + variables = vector::::new(), + bindings = vector::::new(), + kept_order = vector::::new(), + kept_number = vector::::new(), + kept_idom = vector::::new() + }; + made.insts.append(inst {}); + made.origins.append(origin {}); + made.add_block(); + return made; +} + +#! Adds a block, taking nothing yet. +#! @param this The code. +#! @returns Its index. +pub def code::add_block(&mut this): u32 { + this.blocks.append(block {}); + return (this.blocks.length - 1) as u32; +} + +#! Adds a parameter to a block. +#! @param this The code. +#! @param at The block. +#! @param kind The parameter's type. +#! @returns The value it is. +pub def code::add_param(&mut this, at: u32, kind: vt): u32 { + val value := this.origins.length as u32; + val index := this.blocks[at].params.length as u32; + this.origins.append(origin { kind = kind, param = true, from = at, index = index }); + this.blocks[at].params.append(value); + return value; +} + +#! Adds a cell to the frame. +#! @param this The code. +#! @param size How many bytes it holds. +#! @param align What its address is a multiple of. +#! @param kind What it holds. +#! @param name The ID of its variable's name, or 0. +#! @returns Its index. +pub def code::add_cell(&mut this, size: u32, align: u32, kind: ck, name: u32): u32 { + this.cells.append(cell { size = size, align = align == 0 ? 1 : align, kind = kind, name = name }); + return (this.cells.length - 1) as u32; +} + +#! Appends an instruction to the end of a block, with its operands and the +#! values it gives. +#! @param this The code. +#! @param at The block. +#! @param kind What it does. +#! @param args Its operands. +#! @param gives The types of its results, in order. +#! @param aux What its kind says `aux` holds. +#! @param imm What its kind says `imm` holds. +#! @param pos Where in the source it is from: one more than the file, then +#! the byte. +#! @returns Its index. +pub def code::append( + &mut this, + at: u32, + kind: op, + args: span, + gives: span, + aux: u32, + imm: u64, + pos: u64 +): u32 { + val index := this.insts.length as u32; + val first := this.operands.length as u32; + # Appended one by one, which is inlined, where `extend` is a call for each + # instruction. + for &each in args { + this.operands.append(each); + } + + val result := this.origins.length as u32; + for i in 0..gives.length { + this.origins.append(origin { kind = gives[i], from = index, index = i as u32 }); + } + + this.insts.append(inst { + kind = kind, + count = gives.length as u8, + aux = aux, + imm = imm, + args = first, + argc = args.length as u32, + result = gives.length == 0 ? 0 : result, + block = at, + at = pos + }); + + val last: u32 = this.blocks[at].last; + if last == 0 { + this.blocks[at].first = index; + } else { + this.insts[last].next = index; + } + this.blocks[at].last = index; + return index; +} + +#! Puts an instruction first in a block, as a value a variable has nowhere is +#! put first in the entry. +#! @param this The code. +#! @param at The block. +#! @param index The instruction, appended to no block yet. +pub def code::put_first(&mut this, at: u32, index: u32): void { + this.insts[index].block = at; + this.insts[index].next = this.blocks[at].first; + this.blocks[at].first = index; + if this.blocks[at].last == 0 { + this.blocks[at].last = index; + } +} + +#! Adds an edge from an instruction ending a block into another block, without +#! arguments yet. +#! @param this The code. +#! @param from The instruction. +#! @param target The block it goes to. +#! @param case Of a `switch`, the word it goes on. +#! @returns Its index. +pub def code::add_edge(&mut this, from: u32, target: u32, case: u64): u32 { + val index := this.edges.length as u32; + this.edges.append(edge { from = from, target = target, case = case }); + this.blocks[target].preds.append(index); + return index; +} + +#! The operand of an instruction, by its position. +#! @param this The code. +#! @param index The instruction. +#! @param at The operand's position, below its `argc`. +#! @returns The value. +pub def code::arg(&this, index: u32, at: u32): u32 { + return this.operands[this.insts[index].args as u64 + at as u64]; +} + +#! The type of a value. +#! @param this The code. +#! @param value The value. +#! @returns Its type. +pub def code::type_of(&this, value: u32): vt { + return this.origins[value].kind; +} + +#! The block an instruction ending a block leaves from: the block holding it. +#! @param this The code. +#! @param index The edge. +#! @returns The block. +pub def code::edge_source(&this, index: u32): u32 { + return this.insts[this.edges[index].from].block; +} + +#! How many edges an instruction ending a block leaves by. +#! @param this The code. +#! @param index The instruction. +#! @returns How many: none for one that returns or stops. +pub def code::edge_count(&this, index: u32): u32 { + return this.insts[index].edge_count(); +} + +#! How many edges an instruction leaves by, which follow one another from its +#! `aux`. +#! @param this The instruction. +#! @returns How many: none for one that does not end its block, or returns or +#! stops. +pub def inst::edge_count(&this): u32 { + return match this.kind { + op::jump => 1, + op::branch => 2, + op::switch => this.imm as u32, + else => 0 + }; +} + +#! Whether an operation ends its block. +#! @param this The operation. +#! @returns Whether it does. +pub def op::ends(&this): bool { + return (op_traits[this as u64] & op_ends) != 0; +} + +#! What an operation is like, as the bits `op_pure` and the others give. +#! @param this The operation. +#! @returns Its bits. +pub def op::traits(&this): u8 { + return op_traits[this as u64]; +} + +#! The name of an operation, as the printed code writes it. +#! @param this The operation. +#! @returns The name. +pub def op::name(&this): strview { + return op_names[this as u64]; +} + +# What an operation is like, which the passes over the code respect. +pub const op_pure: u8 = 0x01; #! It only computes its result from its operands, so it may move or go. +pub const op_traps: u8 = 0x02; #! It may stop the program. +pub const op_reads: u8 = 0x04; #! It reads memory. +pub const op_write: u8 = 0x08; #! It writes memory. +pub const op_calls: u8 = 0x1E; #! It calls code, which may read, write, and stop the program. +pub const op_ends: u8 = 0x20; #! It ends its block. + +#! What each operation is like, in the order `op` declares them. +const op_traits: u8[op::count as u64] = [ + op_pure, op_pure, # iconst, fconst + op_pure, op_pure, op_pure, op_traps, op_traps, op_traps, op_traps, # add .. remu + op_pure, op_pure, op_pure, op_pure, op_pure, op_pure, # band .. shru + op_pure, op_pure, op_pure, op_pure, op_pure, op_pure, # eq .. leu + op_pure, op_pure, op_pure, op_pure, op_pure, # eqsu .. leus + op_pure, op_pure, op_pure, op_pure, op_pure, # fadd .. frem + op_pure, op_pure, op_pure, op_pure, # feq .. fle + op_pure, op_pure, op_pure, op_pure, # neg, bnot, lnot, fneg + op_pure, op_pure, op_pure, op_pure, op_pure, # itof .. fsingle + op_pure, op_pure, op_pure, op_pure, op_pure, op_pure, # fsqrt .. wrap + op_pure, # select + op_pure, op_pure, op_pure, # cell, global, datum + op_reads | op_traps, op_write | op_traps, # load, store + op_reads | op_write | op_traps, op_write | op_traps, # copy, clear + op_calls, # forget + op_calls, op_calls, op_calls, # allocate .. resize + op_calls, op_calls, op_calls, op_calls, # call .. call_c + op_pure, op_pure, # c_address, callback + op_reads | op_calls, op_pure, op_traps, # equal, retrait, check + op_calls, op_reads, op_pure, op_pure, op_calls, op_calls, # syscall .. catch + op_calls, op_calls, op_calls, op_calls, # safepoint, exit, abort, fault + op_calls, op_calls, op_calls | op_reads, op_calls | op_reads, op_calls, # format .. + op_traps, op_traps, op_traps, # ready, reach, same + op_pure, op_pure, op_pure, # cpu, lanes, vzero + op_calls, # atomic + op_calls, op_pure, op_calls, # start, current, clone + op_ends, op_ends, op_ends, op_ends | op_reads, op_ends | op_traps, op_ends, # jump .. unreachable +]; + +#! The name of each operation, in the order `op` declares them. +const op_names: strview[op::count as u64] = [ + "iconst", "fconst", + "add", "sub", "mul", "divs", "divu", "rems", "remu", + "band", "bor", "bxor", "shl", "shrs", "shru", + "eq", "ne", "lts", "ltu", "les", "leu", + "eqsu", "ltsu", "lesu", "ltus", "leus", + "fadd", "fsub", "fmul", "fdiv", "frem", + "feq", "fne", "flt", "fle", + "neg", "bnot", "lnot", "fneg", + "itof", "utof", "ftoi", "ftou", "fsingle", + "fsqrt", "ones", "clz", "ctz", "bswap", "wrap", + "select", + "cell", "global", "datum", + "load", "store", "copy", "clear", "forget", + "allocate", "release", "resize", + "call", "call_trait", "call_value", "call_c", + "c_address", "callback", + "equal", "retrait", "check", + "syscall", "frame", "image", "environ", "signals", "catch", + "safepoint", "exit", "abort", "fault", + "format", "format_text", "format_value", "format_bytes", "format_owned", + "ready", "reach", "same", + "cpu", "lanes", "vzero", + "atomic", + "start", "current", "clone", + "jump", "branch", "switch", "ret", "trap", "unreachable", +]; + +#! The name of each access, as the printed code writes it. +const access_names: strview[13] = ["i8", "u8", "i16", "u16", "i32", "u32", "i64", "f32", "f64", "bytes", "v128", "v256", "v512"]; + +#! The name of an access. +#! @param this The access. +#! @returns Its name. +pub def access::name(&this): strview { + return access_names[this as u64]; +} + +#! The type of value an access reads and writes. +#! @param how The access. +#! @returns The type: a real for a float, a vector for lanes, and otherwise a +#! word. +pub def access::value_type(&this): vt { + return match this { + access::f32, access::f64 => vt::real, + access::v128 => vt::v128, + access::v256 => vt::v256, + access::v512 => vt::v512, + else => vt::word + }; +} + +#! The bytes an access reads or writes. +#! @param this The access. +#! @returns How many: 8 for `bytes`, whose size the instruction gives. +pub def access::width(&this): u64 { + return match this { + access::i8, access::u8 => 1, + access::i16, access::u16 => 2, + access::i32, access::u32, access::f32 => 4, + access::v128 => 16, + access::v256 => 32, + access::v512 => 64, + else => 8 + }; +} + +#! Whether a type of value is a vector's. +#! @param this The type. +#! @returns Whether it is. +pub def vt::lanes(&this): bool { + return this == vt::v128 || this == vt::v256 || this == vt::v512; +} + +#! The real whose bits a word holds. +#! @param bits The bits of an `f64`. +#! @returns The real. +pub def real_of(bits: u64): f64 { + var held := bits; + return ((&mut held) as *mut f64)[0]; +} + +#! The bits of a real, as a word holds them. +#! @param value The real. +#! @returns Its bits. +pub def bits_of_real(value: f64): u64 { + var held := value; + return ((&mut held) as *mut u64)[0]; +} diff --git a/compiler/intermediate/compact.sakura b/compiler/intermediate/compact.sakura new file mode 100644 index 00000000..77a3bf09 --- /dev/null +++ b/compiler/intermediate/compact.sakura @@ -0,0 +1,250 @@ +#! @file compact.sakura +#! @author John Christman (sorakatadzuma@gmail.com) +#! @copyright Malunal Studios, LLC. +#! @license MIT +#! +#! Contains the compacting of code. A pass taking out an instruction, a block, +#! or an edge leaves its slot behind, and inlining leaves about half of a +#! function's slots so, yet every pass after and both backends size their +#! tables by the slots and walk past the empty ones. Compacting numbers again +#! what is left so they cost only what the code holds. The instructions keep +#! the order they were in, which keeps what goes by it: the instructions a +#! variable's scope covers, as how many the code had where it begins and ends. +#! The blocks are numbered in reverse postorder, so the order the code keeps +#! of them is known without working it out again. + +module sakura::compiler; + + +#! What compacting gives a slot that goes. +const compacted_out: u32 = 0xFFFFFFFF; + +#! Compacts the code, as the file says. The blocks not removed are kept, with +#! the instructions in them, the edges those instructions leave by, and the +#! values they give and the blocks take, and so are the values the bindings +#! name; the rest goes. The blocks the entry reaches are numbered in reverse +#! postorder, then those it does not, and everything else in the order it was. +#! A value a binding names whose instruction went stays, given by nothing, so +#! the variable is shown as nowhere from there, as it was; but where that +#! instruction made a constant, the binding keeps the constant in its place. +#! @param this The code. +pub def code::compact(&mut this): void { + # The blocks the entry reaches, in reverse postorder, then the others not + # removed. + var order := vector::::new(scratch()); + var number := vector::::new(scratch()); + this.block_order(&mut order, &mut number); + var block_to := vector::::new(scratch()); + block_to.resize(this.blocks.length, compacted_out); + var block_from := vector::::new(scratch()); + block_from.reserve(this.blocks.length); + for &b in order { + block_to[b] = block_from.length as u32; + block_from.append(b); + } + val reached := block_from.length as u32; + for b in 0..this.blocks.length { + continue if this.blocks[b].gone || block_to[b] != compacted_out; + block_to[b] = block_from.length as u32; + block_from.append(b as u32); + } + + # The instructions in those blocks, marked, then numbered in the order they + # were, with how many are kept below each slot, as a variable's scope is + # numbered. + var inst_to := vector::::new(scratch()); + inst_to.resize(this.insts.length, compacted_out); + inst_to[0] = 0; + var live: u64 = 1; + for &b in block_from { + var walk := this.walk(b); + while walk.more() { + inst_to[walk.next()] = 0; + live++; + } + } + var kept := vector::::new(scratch()); + kept.reserve(live); + var below := vector::::new(scratch()); + below.resize(this.insts.length + 1); + for i in 0..this.insts.length { + below[i] = kept.length as u32; + continue if inst_to[i] == compacted_out; + inst_to[i] = kept.length as u32; + kept.append(i as u32); + } + below[this.insts.length] = kept.length as u32; + + # The values the instructions kept give, the blocks kept take, and the + # bindings name, marked, then numbered in the order they were, each moving + # down to its number where it is. The operands and edges kept are counted. + val values := this.origins.length; + var value_to := vector::::new(scratch()); + value_to.resize(values, compacted_out); + value_to[0] = 0; + var operand_count: u64 = 0; + var edge_count: u64 = 0; + for &i in kept { + val held := &this.insts[i]; + for r in 0..held.count { + value_to[held.result as u64 + r as u64] = 0; + } + operand_count += held.argc as u64; + edge_count += held.edge_count() as u64; + } + for &b in block_from { + for ¶m in this.blocks[b].params { + value_to[param] = 0; + } + } + # A binding naming a constant whose instruction went keeps the constant in + # the value's place. + for i in 0..this.bindings.length { + val bound := &mut this.bindings[i]; + continue if bound.value == 0 || bound.value as u64 >= values; + val held: origin = this.origins[bound.value]; + if !held.param && inst_to[held.from] == compacted_out { + bound.known = this.constant_kind(bound.value, &mut bound.bits); + if bound.known != vt::none { + bound.value = 0; + continue; + } + } + value_to[bound.value] = 0; + } + var origins_kept: u64 = 0; + val origins := this.origins.slice().data; + for v in 0..values { + continue if value_to[v] == compacted_out; + value_to[v] = origins_kept as u32; + var held: origin = origins[v]; + if v != 0 { + val home := held.param ? block_to[held.from] : inst_to[held.from]; + if home == compacted_out { + held.param = false; + held.from = 0; + held.index = 0; + } else { + held.from = home; + } + } + origins[origins_kept] = held; + origins_kept++; + } + # Copied into memory of their size, so the code holds no more than it needs. + var made_origins := vector::::new(); + made_origins.extend(span::::over(this.origins.view().data, origins_kept)); + this.origins = move(&mut made_origins); + + # What the bindings and variables name. A binding whose instruction went + # takes effect where its block begins, or where the block of that + # instruction does where its own went, as the backends read it. This reads + # the instructions where they are, before they move. + for i in 0..this.bindings.length { + val bound := &mut this.bindings[i]; + val after := bound.after; + var block := bound.block; + if block == no_block || block_to[block] == compacted_out { + block = after != 0 ? this.insts[after].block : no_block; + } + bound.block = block == no_block || block_to[block] == compacted_out ? no_block : block_to[block]; + bound.after = inst_to[after] == compacted_out ? 0 : inst_to[after]; + bound.value = bound.value as u64 >= values ? 0 : value_to[bound.value]; + } + for i in 0..this.variables.length { + val held := &mut this.variables[i]; + if held.first != 0 { + held.first = below[held.first]; + } + if held.end != 0 { + held.end = below[held.end]; + } + } + + # The instructions, each moving down to its number, their operands each in + # a run of its own, and the edges they leave by, each instruction's in a run + # as before. Read and written where the elements are, as this runs over + # every operand. + var made_operands := vector::::new(); + made_operands.resize(operand_count); + val operands_to := made_operands.slice().data; + val operands_from := this.operands.view().data; + val values_to := value_to.view().data; + var made_edges := vector::::new(); + made_edges.reserve(edge_count); + var edge_to := vector::::new(scratch()); + edge_to.resize(this.edges.length, compacted_out); + val insts := this.insts.slice().data; + var placed: u64 = 0; + for n in 0..kept.length { + val i: u32 = kept[n]; + var held: inst = insts[i]; + val args := held.args as u64; + held.args = placed as u32; + for k in 0..held.argc as u64 { + operands_to[placed] = values_to[operands_from[args + k]]; + placed++; + } + held.result = held.count == 0 ? 0 : values_to[held.result]; + if i != 0 { + held.block = block_to[held.block]; + held.next = inst_to[held.next]; + } + val count := held.edge_count(); + if count != 0 { + val first: u64 = held.aux; + held.aux = made_edges.length as u32; + for e in 0..count { + val old := first + e as u64; + edge_to[old] = made_edges.length as u32; + var args := move(&mut this.edges[old].args); + for k in 0..args.length { + args[k as u64] = values_to[args[k as u64]]; + } + made_edges.append(edge { + from = n as u32, target = block_to[this.edges[old].target], args = move(&mut args), case = this.edges[old].case + }); + } + } + insts[n] = held; + } + var made_insts := vector::::new(); + made_insts.extend(span::::over(this.insts.view().data, kept.length)); + this.insts = move(&mut made_insts); + + # The blocks, their parameters and the edges into them numbered as they are + # now. + var made_blocks := vector::::new(); + made_blocks.reserve(block_from.length); + for &b in block_from { + var params := move(&mut this.blocks[b].params); + for k in 0..params.length { + params[k as u64] = values_to[params[k as u64]]; + } + var preds := ids {}; + for &pred in this.blocks[b].preds { + if edge_to[pred] != compacted_out { + preds.append(edge_to[pred]); + } + } + made_blocks.append(block { + first = inst_to[this.blocks[b].first], last = inst_to[this.blocks[b].last], + params = move(&mut params), preds = move(&mut preds) + }); + } + + # The dominators the code kept, where it kept them, numbered as the blocks. + var idom := vector::::new(scratch()); + if this.idom_kept { + idom.resize(block_from.length, no_block); + for i in 0..block_from.length { + val dominator: u32 = this.kept_idom[block_from[i]]; + idom[i] = dominator == no_block ? no_block : block_to[dominator]; + } + } + + this.operands = move(&mut made_operands); + this.blocks = move(&mut made_blocks); + this.edges = move(&mut made_edges); + this.keep_numbered_order(reached, block_from.length as u32, idom.view()); +} diff --git a/compiler/intermediate/ids.sakura b/compiler/intermediate/ids.sakura new file mode 100644 index 00000000..1de02f40 --- /dev/null +++ b/compiler/intermediate/ids.sakura @@ -0,0 +1,160 @@ +#! @file ids.sakura +#! @author John Christman (sorakatadzuma@gmail.com) +#! @copyright Malunal Studios, LLC. +#! @license MIT +#! +#! Contains `ids`, a short list of indices, as a block's parameters, the edges +#! into it, and the arguments an edge gives. Up to four are held in the list +#! itself, so most lists take no memory of their own, and more are moved to +#! memory of the list's own. + +module sakura::compiler; + + +#! A list of indices, holding up to four itself and more in memory of its own. +pub struct ids : owning, iterable { + var _len: u32; #! How many it holds. + var _cap: u32; #! How many its memory holds, or 0 while it holds them itself. + var _own: u32[4]; #! Those it holds itself. + var _dat: *mut u32; #! Its memory, once it has any. +} + +#! How many indices the list holds. +#! @param this The list. +#! @returns How many. +pub val ids::length: u64 { + get => this._len as u64; +} + +#! Where the indices begin, in the list or in its memory. +#! @param this The list. +#! @returns The first index. +pub def ids::data(&this): *u32 { + return this._cap == 0 ? (&this._own) as *u32 : this._dat; +} + +#! Makes a list holding the same indices as another, sharing no memory with it. +#! @param other The list. +#! @returns The copy. +pub def ids::copy_of(other: &ids): ids { + var made := ids {}; + for &each in other.view() { + made.append(each); + } + return made; +} + +#! Lends a view of the indices. +#! @param this The list. +#! @returns The view, which refers into the list. +pub def ids::view(&this): span { + return span::::over(this.data(), this._len as u64); +} + +#! Lends a view of the indices that writes them where they are. +#! @param this The list. +#! @returns The view, which refers into the list. +pub def ids::slice(&mut this): slice { + val data := this._cap == 0 ? (&mut this._own) as *mut u32 : this._dat; + return slice::::over(data, this._len as u64); +} + +#! Reads the index at a place in the list. +#! @param this The list. +#! @param index The place, below `length`, which stops the program otherwise. +#! @returns The index. +pub def ids::at(&this, index: u64): &u32 { + return &span::::over(this.data(), this._len as u64)[index]; +} + +#! Writes the index at a place in the list. +#! @param this The list. +#! @param index The place, below `length`, which stops the program otherwise. +#! @returns A reference that writes it. +pub def ids::at(&mut this, index: u64): &mut u32 { + var whole := this.slice(); + return &mut whole[index]; +} + +#! What `iter(&this)` lends, which reads the indices. +pub type ids::cursor = span::cursor; + +#! Lends a cursor that reads the indices. +#! @param this The list. +#! @returns The cursor, which refers into the list. +pub def ids::iter(&this): span::cursor { + return this.view().iter(); +} + +#! Adds an index after the last. +#! @param this The list. +#! @param value The index. +pub def ids::append(&mut this, value: u32): void { + if this._cap == 0 && this._len < 4 { + this._own[this._len as u64] = value; + this._len++; + return; + } + if this._len == this._cap || this._cap == 0 { + this.spill(this._cap == 0 ? 8 : this._cap * 2); + } + this._dat[this._len as u64] = value; + this._len++; +} + +#! Removes every index, keeping the memory the list holds them in. +#! @param this The list. +pub def ids::clear(&mut this): void { + this._len = 0; +} + +#! A vector holding the same indices, which changing the list leaves as it is. +#! @param this The list. +#! @param alloc The optional allocator the vector takes its memory from. +#! @returns The vector. +pub def ids::copied(&this, alloc: maybe<&mut allocator>): vector { + var made := vector::::new(this.length, alloc); + made.extend(this.view()); + return made; +} + +#! Whether two lists hold the same indices in the same order. +#! @param this The list. +#! @param other The list to compare it with. +#! @returns Whether they do. +pub def ids::same(&this, other: &ids): bool { + return false if this._len != other._len; + val mine := this.data(); + val theirs := other.data(); + for i in 0..this._len as u64 { + return false if mine[i] != theirs[i]; + } + return true; +} + +#! Gives back the memory the list holds, leaving it empty. +#! @param this The list. +pub def ids::close(&mut this): void { + if this._cap != 0 { + raw_release(this._dat as *mut u8); + } + this._dat = null; + this._cap = 0; + this._len = 0; +} + +# Moves the indices to memory of the list's own, with room for a number of them. +def ids::spill(&mut this, size: u32): void { + if this._cap != 0 { + this._dat = raw_resize(this._dat as *mut u8, size as u64 * 4) as *mut u32; + this._cap = size; + return; + } + + val made := raw_allocate(size as u64 * 4) as *mut u32; + for i in 0..this._len as u64 { + made[i] = this._own[i]; + } + this._dat = made; + this._cap = size; +} diff --git a/compiler/intermediate/liveness.sakura b/compiler/intermediate/liveness.sakura new file mode 100644 index 00000000..c187c2fa --- /dev/null +++ b/compiler/intermediate/liveness.sakura @@ -0,0 +1,133 @@ +#! @file liveness.sakura +#! @author John Christman (sorakatadzuma@gmail.com) +#! @copyright Malunal Studios, LLC. +#! @license MIT +#! +#! Contains what the machine's assembler and the native backend's register +#! allocator share of finding where each value of a function's code is live: +#! the block a value is made in, and the walk from each block a value is read +#! in back over the edges into it, to the block making it. A value read in a +#! block other than its own is live into that block, and out of every block an +#! edge into it leaves, and so on back to its own, as a value read in a loop is +#! live around it. + +module sakura::compiler; + + +#! Where the value being found is live in a block. +pub struct block_reach { + pub var stamp: u32; #! The value it is for, or another, where it is stale. + pub var ends: u32; #! Past the last read in the block. + pub var out: bool; #! Whether it is live where the block ends. + pub var into: bool; #! Whether it is live where the block begins. +} + +#! The walk finding the blocks a value is live in, from the reads of it back to +#! the block making it. The reach of each block is kept for the value being +#! found, and is stale for any other, so the values of a function are found one +#! after another in the same memory. +pub struct live_walk { + pub var reaches: vector; #! The reach of each block. + pub var touched: vector; #! The blocks the value reaches, each once. + var todo: vector; #! The blocks it is live into whose edges in are not walked yet. + var reach: slice; #! A view of `reaches`, which never grows, indexed without a call. + var value: u32; #! The value being found. + var home: u32; #! The block making it. +} + +#! Makes a walk of the blocks of a function's code, finding no value yet. +#! @param blocks How many blocks the code has. +#! @param alloc The optional allocator for the memory backing of the walk. +#! @returns The walk. +pub def live_walk::new(blocks: u64, alloc: maybe<&mut allocator>): live_walk { + var made := live_walk { + reaches = vector::::new(alloc), + touched = vector::::new(alloc), + todo = vector::::new(alloc), + value = 0xFFFFFFFF + }; + made.reaches.resize(blocks, block_reach { stamp = 0xFFFFFFFF }); + made.reach = made.reaches.slice(); + return made; +} + +#! Begins finding where a value is live. +#! @param this The walk. +#! @param value The value, which no reach is stamped with yet. +#! @param home The block making it. +pub def live_walk::begin(&mut this, value: u32, home: u32): void { + this.touched.clear(); + this.todo.clear(); + this.value = value; + this.home = home; +} + +#! Readies a block's reach for the value being found, where it is stale. +#! @param this The walk. +#! @param block The block. +pub def live_walk::touch(&mut this, block: u32): void { + return if this.reach[block].stamp == this.value; + this.reach[block] = block_reach { stamp = this.value }; + this.touched.append(block); +} + +# Each way the value is found live in a block notes it live into the block too, +# which is then walked back from, unless the block makes the value, or it was +# noted already. + +#! Notes a read of the value in a block, at a position: the block holds it up +#! to there, and it is live into the block, unless the block makes it. +#! @param this The walk. +#! @param block The block. +#! @param position Where the read is. +pub def live_walk::read(&mut this, block: u32, position: u32): void { + this.touch(block); + if position + 1 > this.reach[block].ends { + this.reach[block].ends = position + 1; + } + if block != this.home && !this.reach[block].into { + this.reach[block].into = true; + this.todo.append(block); + } +} + +#! Notes a read of the value where a block ends, as the argument of an edge +#! leaving it: it is live out of the block, and into it, unless the block makes +#! it. +#! @param this The walk. +#! @param block The block. +pub def live_walk::read_out(&mut this, block: u32): void { + this.touch(block); + this.reach[block].out = true; + if block != this.home && !this.reach[block].into { + this.reach[block].into = true; + this.todo.append(block); + } +} + +#! Walks back from each block the value is live into, over each edge into it: +#! the value is live out of the block the edge leaves, and into that block too, +#! unless it makes the value. The block making it is reached last of all. +#! @param this The walk. +#! @param body The code. +#! @param number Each block's place in the order laid out, or `0xFFFFFFFF` +#! for one not laid out. +#! @param laid Whether the edges leaving blocks not laid out are passed +#! over, rather than walked as any other. +pub def live_walk::walk(&mut this, body: &code, number: &vector, laid: bool): void { + while this.todo.length != 0 { + val block: u32 = this.todo.last(); + this.todo.truncate(); + for &edge in body.blocks[block].preds { + val from := body.edge_source(edge); + continue if laid && number[from] == 0xFFFFFFFF; + this.touch(from); + this.reach[from].out = true; + if from != this.home && !this.reach[from].into { + this.reach[from].into = true; + this.todo.append(from); + } + } + } + this.touch(this.home); +} diff --git a/compiler/intermediate/moves.sakura b/compiler/intermediate/moves.sakura new file mode 100644 index 00000000..f65ab82b --- /dev/null +++ b/compiler/intermediate/moves.sakura @@ -0,0 +1,82 @@ +#! @file moves.sakura +#! @author John Christman (sorakatadzuma@gmail.com) +#! @copyright Malunal Studios, LLC. +#! @license MIT +#! +#! Contains the making of moves all at once, as the moves along an edge into the +#! places of what its block takes are made: a move whose place another still +#! reads waits for that one, and moves going round in a cycle save one place +#! first, which those reading it read from where it was saved. The machine's +#! assembler moves words of the frame, and the native backend's selector +#! registers, slots, and the stack, each making the moves itself. + +module sakura::compiler; + + +#! What making moves all at once needs of the moves and of what makes them. +#! @tparam M The type of a move. +pub trait move_maker { + #! Whether a move reads the place another writes. + def move_reads(&this, reader: &M, writer: &M): bool; + + #! Makes a move. + def move_one(&mut this, made: &M): void; + + #! The move saving what a move would write over, to a place no move reads or + #! writes. + def move_saving(&mut this, written: &M, pending: span): M; + + #! Has a move read what another saved from where it was saved. + def move_reread(&this, reader: &mut M, saved: &M): void; +} + +#! Makes moves all at once: the first whose place no other reads, again and +#! again, and where every place written is still read, the first move's place +#! saved first, to be read from where it was saved. +#! @param pending The moves, no two writing one place, and none reading the +#! place it writes, which are taken as they are made. +#! @param maker What makes them. +#! @param swap Whether a move made gives its place among those left to the +#! last, rather than those after it each moving up one, which +#! is the order the rest are tried in. +pub def make_moves(pending: &mut vector, maker: &mut K, swap: bool): void where K: move_maker { + # The moves are read through a view, without a call, taken again as one goes. + var moves := pending.slice(); + while moves.length != 0 { + var ready := moves.length; + for i in 0..moves.length { + var read := false; + for j in 0..moves.length { + if j != i && maker.move_reads(&moves[j], &moves[i]) { + read = true; + break; + } + } + if !read { + ready = i; + break; + } + } + if ready != moves.length { + maker.move_one(&moves[ready]); + if swap { + moves[ready] = pending.last(); + pending.truncate(); + } else { + pending.remove_at(ready); + } + moves = pending.slice(); + continue; + } + + # Every place written is still read: the first is saved, and read from + # where it was saved. + val saved := maker.move_saving(&moves[0], moves.view()); + maker.move_one(&saved); + for j in 0..moves.length { + if maker.move_reads(&moves[j], &moves[0]) { + maker.move_reread(&mut moves[j], &saved); + } + } + } +} diff --git a/compiler/intermediate/numbers.sakura b/compiler/intermediate/numbers.sakura new file mode 100644 index 00000000..86f31b85 --- /dev/null +++ b/compiler/intermediate/numbers.sakura @@ -0,0 +1,152 @@ +#! @file numbers.sakura +#! @author John Christman (sorakatadzuma@gmail.com) +#! @copyright Malunal Studios, LLC. +#! @license MIT +#! +#! Contains the operations of one value the machine gives that no operator of the +#! language writes: a square root, and counting and reversing a word's bits and +#! bytes. The machine runs them, and the optimizer folds them, through these, so +#! the two agree with each other and with an executable, whose instructions give +#! the same. `std::math` reaches them through its intrinsics, which a compiler +#! building this one need not know. +#! +#! `root_of` is musl's `sqrt`, from src/math/sqrt.c of musl 1.2.5, which is +#! Copyright © 2005-2020 Rich Felker, et al., under the MIT license. + +module sakura::compiler; + + +# The reciprocal square roots `root_of` begins from, by the lowest bit of the +# exponent and the top six of the significand: musl's `__rsqrt_tab`. +const reciprocal_roots: u16[128] = [ + 0xb451, 0xb2f0, 0xb196, 0xb044, 0xaef9, 0xadb6, 0xac79, 0xab43, + 0xaa14, 0xa8eb, 0xa7c8, 0xa6aa, 0xa592, 0xa480, 0xa373, 0xa26b, + 0xa168, 0xa06a, 0x9f70, 0x9e7b, 0x9d8a, 0x9c9d, 0x9bb5, 0x9ad1, + 0x99f0, 0x9913, 0x983a, 0x9765, 0x9693, 0x95c4, 0x94f8, 0x9430, + 0x936b, 0x92a9, 0x91ea, 0x912e, 0x9075, 0x8fbe, 0x8f0a, 0x8e59, + 0x8daa, 0x8cfe, 0x8c54, 0x8bac, 0x8b07, 0x8a64, 0x89c4, 0x8925, + 0x8889, 0x87ee, 0x8756, 0x86c0, 0x862b, 0x8599, 0x8508, 0x8479, + 0x83ec, 0x8361, 0x82d8, 0x8250, 0x81c9, 0x8145, 0x80c2, 0x8040, + 0xff02, 0xfd0e, 0xfb25, 0xf947, 0xf773, 0xf5aa, 0xf3ea, 0xf234, + 0xf087, 0xeee3, 0xed47, 0xebb3, 0xea27, 0xe8a3, 0xe727, 0xe5b2, + 0xe443, 0xe2dc, 0xe17a, 0xe020, 0xdecb, 0xdd7d, 0xdc34, 0xdaf1, + 0xd9b3, 0xd87b, 0xd748, 0xd61a, 0xd4f1, 0xd3cd, 0xd2ad, 0xd192, + 0xd07b, 0xcf69, 0xce5b, 0xcd51, 0xcc4a, 0xcb48, 0xca4a, 0xc94f, + 0xc858, 0xc764, 0xc674, 0xc587, 0xc49d, 0xc3b7, 0xc2d4, 0xc1f4, + 0xc116, 0xc03c, 0xbf65, 0xbe90, 0xbdbe, 0xbcef, 0xbc23, 0xbb59, + 0xba91, 0xb9cc, 0xb90a, 0xb84a, 0xb78c, 0xb6d0, 0xb617, 0xb560, +]; + +# `a * b / 2^32` of the low 32 bits of each, rounded down. +def high_of_32(a: u64, b: u64): u64 { + return ((a & 0xFFFFFFFF) * (b & 0xFFFFFFFF)) >> 32; +} + +# `a * b / 2^64`, short of it by less than 3. +def high_of_64(a: u64, b: u64): u64 { + val ahi := a >> 32; + val alo := a & 0xFFFFFFFF; + val bhi := b >> 32; + val blo := b & 0xFFFFFFFF; + return ahi * bhi + ((ahi * blo) >> 32) + ((alo * bhi) >> 32); +} + +#! The square root of a real, correctly rounded, as IEEE 754 defines it and +#! `sqrtsd` gives it: the root of `-0` is `-0`, of infinity infinity, and of +#! what is below zero, or not a number, not a number. +#! @param x The real. +#! @returns Its square root. +pub def root_of(x: f64): f64 { + var ix := bits_of_real(x); + var top := ix >> 52; + # Below the least normal, infinite, not a number, or below zero. + if top - 1 >= 0x7FE { + return x if ix * 2 == 0 || ix == 0x7FF0000000000000; + if ix > 0x7FF0000000000000 { + return (x - x) / (x - x); + } + # A subnormal, made normal. + ix = bits_of_real(x * 4503599627370496.0); + top = (ix >> 52) - 52; + } + + # x is 4^e times m, with m from 1 to 4 held as 2.62 bits, and 2^e is the + # exponent of the root. + val even := top & 1; + var m := (ix << 11) | 0x8000000000000000; + if even != 0 { + m >>= 1; + } + top = (top + 0x3FF) >> 1; + + # r is near 1 / sqrt(m) and s near sqrt(m): from the table, then two steps of + # Goldschmidt's iteration in 32 bits, and one in 64. + val three: u64 = 0xC0000000; + var r := (reciprocal_roots[(ix >> 46) % 128] as u64) << 16; + var s := high_of_32(m >> 32, r); + var d := high_of_32(s, r); + var u := three - d; + r = (high_of_32(r, u) << 1) & 0xFFFFFFFF; + s = (high_of_32(s, u) << 1) & 0xFFFFFFFF; + d = high_of_32(s, r); + u = three - d; + r = (high_of_32(r, u) << 1) & 0xFFFFFFFF; + r = r << 32; + s = high_of_64(m, r); + d = high_of_64(s, r); + u = (three << 32) - d; + s = high_of_64(s, u); + s = (s - 2) >> 9; + + # s is below sqrt(m) by less than 2^-52 and a little more, so the root is s or + # the next, as (2^52 s + 1/2)^2 compares with 2^104 m. + val d0 := (m << 42) - s * s; + val d1 := s - d0; + s += d1 >> 63; + s &= 0x000FFFFFFFFFFFFF; + s |= top << 52; + return real_of(s); +} + +#! How many bits of a word are 1. +#! @param word The word. +#! @returns How many. +pub def ones_of(word: u64): u64 { + var x := word - ((word >> 1) & 0x5555555555555555); + x = (x & 0x3333333333333333) + ((x >> 2) & 0x3333333333333333); + x = (x + (x >> 4)) & 0x0F0F0F0F0F0F0F0F; + return (x * 0x0101010101010101) >> 56; +} + +#! How many 0 bits lead a word, from its top. +#! @param word The word. +#! @returns How many: 64 where it is zero. +pub def leading_zeros_of(word: u64): u64 { + return 64 if word == 0; + var x := word; + var count: u64 = 0; + if (x & 0xFFFFFFFF00000000) == 0 { count += 32; x <<= 32; } + if (x & 0xFFFF000000000000) == 0 { count += 16; x <<= 16; } + if (x & 0xFF00000000000000) == 0 { count += 8; x <<= 8; } + if (x & 0xF000000000000000) == 0 { count += 4; x <<= 4; } + if (x & 0xC000000000000000) == 0 { count += 2; x <<= 2; } + if (x & 0x8000000000000000) == 0 { count += 1; } + return count; +} + +#! How many 0 bits trail a word, from its bottom. +#! @param word The word. +#! @returns How many: 64 where it is zero. +pub def trailing_zeros_of(word: u64): u64 { + return 64 if word == 0; + return ones_of((word & (0 - word)) - 1); +} + +#! A word with its bytes in the reverse order. +#! @param word The word. +#! @returns The word reversed. +pub def bytes_swapped(word: u64): u64 { + var x := ((word >> 8) & 0x00FF00FF00FF00FF) | ((word & 0x00FF00FF00FF00FF) << 8); + x = ((x >> 16) & 0x0000FFFF0000FFFF) | ((x & 0x0000FFFF0000FFFF) << 16); + return (x >> 32) | (x << 32); +} diff --git a/compiler/intermediate/orders.sakura b/compiler/intermediate/orders.sakura new file mode 100644 index 00000000..7d8cabd2 --- /dev/null +++ b/compiler/intermediate/orders.sakura @@ -0,0 +1,123 @@ +#! @file orders.sakura +#! @author John Christman (sorakatadzuma@gmail.com) +#! @copyright Malunal Studios, LLC. +#! @license MIT +#! +#! Contains the order of the blocks and their dominators, kept with the code. +#! Working them out reads the last instruction of every block, which is where +#! most of the time goes, and many passes ask for them in turn, most of which +#! leave the blocks as they were. So code keeps what was last worked out, and +#! forgets it where what leads where changes: in each edit that changes an +#! edge, and where a pass changes edges itself, as merging blocks does, or +#! where pruning works the order out anew after inlining. Finding the blocks +#! the entry reaches works it out and keeps it, as what follows asks for it. +#! The verifier checks that what is kept is what would be worked out, after +#! each pass. + +module sakura::compiler; + + +#! Writes the blocks the entry reaches in reverse postorder, and each block's +#! place in it, as `reverse_postorder` works them out, keeping them for the next +#! pass to ask. +#! @param this The code. +#! @param order Where the blocks are written, in that order. +#! @param number Where each block's place is written, by its index, or +#! `0xFFFFFFFF` for one the entry does not reach. +pub def code::block_order(&mut this, order: &mut vector, number: &mut vector): void { + this.keep_order(); + order.clear(); + order.extend(this.kept_order.view()); + number.clear(); + number.extend(this.kept_number.view()); +} + +#! Writes the blocks' order as `block_order` does, from what the code keeps +#! where it keeps it, for those that cannot keep it, as the backends. +#! @param this The code. +#! @param order Where the blocks are written. +#! @param number Where each block's place is written. +pub def code::copy_order(&this, order: &mut vector, number: &mut vector): void { + if !this.order_kept { + this.reverse_postorder(order, number); + return; + } + order.clear(); + order.extend(this.kept_order.view()); + number.clear(); + number.extend(this.kept_number.view()); +} + +#! The immediate dominator of each block, as `dominators` works them out, +#! keeping them for the next pass to ask. +#! @param this The code. +#! @returns The dominators, by block, in scratch memory. +pub def code::block_dominators(&mut this): vector { + if !this.idom_kept { + this.keep_order(); + val found := this.dominators(this.kept_order.view(), this.kept_number.view()); + this.kept_idom.clear(); + this.kept_idom.extend(found.view()); + this.idom_kept = true; + } + var made := vector::::new(scratch()); + made.extend(this.kept_idom.view()); + return made; +} + +#! Works out the blocks' order, where the code does not keep it, or keeps it +#! for fewer blocks than it has, as where blocks were added since. +#! @param this The code. +def code::keep_order(&mut this): void { + return if this.order_kept && this.kept_number.length == this.blocks.length; + this.reverse_postorder(&mut this.kept_order, &mut this.kept_number); + this.order_kept = true; +} + +#! Forgets the order and dominators the code keeps, as what changes where its +#! blocks lead does. +#! @param this The code. +pub def code::forget_order(&mut this): void { + this.order_kept = false; + this.idom_kept = false; +} + +#! Keeps an order worked out elsewhere: the blocks numbered in reverse +#! postorder, as compacting numbers them, the first `reached` of `count` being +#! those the entry reaches, with their dominators where given. +#! @param this The code. +#! @param reached How many blocks the entry reaches. +#! @param count How many blocks there are. +#! @param idom The immediate dominator of each, by its new number, or an +#! empty view where they are not known. +pub def code::keep_numbered_order(&mut this, reached: u32, count: u32, idom: span): void { + this.kept_order.clear(); + this.kept_number.clear(); + this.kept_number.resize(count as u64, 0xFFFFFFFF); + for i in 0..reached { + this.kept_order.append(i as u32); + this.kept_number[i as u64] = i as u32; + } + this.order_kept = true; + this.idom_kept = idom.length == count as u64; + if this.idom_kept { + this.kept_idom.clear(); + this.kept_idom.extend(idom); + } +} + +#! Notes where what the code keeps of its blocks' order or dominators is not +#! what would be worked out now, as where an edit changed where blocks lead +#! without forgetting them. +#! @param this The code. +#! @param order The blocks' order, worked out now. +#! @param idom Their dominators, worked out now. +#! @param found Where what is wrong is noted. +pub def code::check_kept_order(&this, order: span, idom: span, found: &mut vector): void { + if this.order_kept && this.kept_order.view() != order { + found.append("The order of the blocks kept is not theirs now."); + } + if this.idom_kept && this.kept_idom.view() != idom { + found.append("The dominators of the blocks kept are not theirs now."); + } +} diff --git a/compiler/intermediate/printer.sakura b/compiler/intermediate/printer.sakura new file mode 100644 index 00000000..76a0aea3 --- /dev/null +++ b/compiler/intermediate/printer.sakura @@ -0,0 +1,322 @@ +#! @file printer.sakura +#! @author John Christman (sorakatadzuma@gmail.com) +#! @copyright Malunal Studios, LLC. +#! @license MIT +#! +#! Contains the printing of code as text, which is how the tests say what code +#! they expect, and how code is read while debugging. + +module sakura::compiler; + + +#! Prints the code. Each block is written as its name and parameters, then its +#! instructions, one to a line: +#! +#! ``` +#! b0(v0: i64): +#! v1 = iconst 1 +#! v2 = add v0, v1 +#! branch v2, b1(v2), b2 +#! ``` +#! +#! Blocks are written in reverse postorder, and values and blocks are numbered +#! in the order they are written, so code that is the same is printed the same +#! however it was made. The cells of the frame are listed first, as `c0: 16, 8` +#! for one of 16 bytes aligned to 8. +#! @param this The code. +#! @returns The text. +pub def code::print(&this): string { + var out := string::new(nothing {}); + var names := code_names { + values = vector::::new(), + blocks = vector::::new(), + next = 0 + }; + names.values.resize(this.origins.length); + names.blocks.resize(this.blocks.length); + + # Blocks are written in reverse postorder, each before those it goes to but + # along the edges going back, as control mostly flows. + var order := vector::::new(); + var number := vector::::new(); + this.reverse_postorder(&mut order, &mut number); + for i in 0..order.length { + names.blocks[order[i]] = i as u32; + } + + for i in 0..this.cells.length { + val held: cell = this.cells[i]; + out.append($"c{i}: {held.size}, {held.align}\n"); + } + + for &b in order { + continue if this.blocks[b].gone; + out.append($"b{names.blocks[b]}"); + val params := this.blocks[b].params.length; + if params != 0 { + out.append("("); + for i in 0..params { + if i != 0 { + out.append(", "); + } + val value: u32 = this.blocks[b].params[i]; + this.print_value(value, &mut names, &mut out); + out.append(": "); + out.append(type_name(this.type_of(value))); + } + out.append(")"); + } + out.append(":\n"); + + var walk := this.walk(b); + while walk.more() { + out.append(" "); + this.print_inst(walk.next(), &mut names, &mut out); + out.append("\n"); + } + } + return out; +} + +#! How the printer numbers what it writes. +struct code_names { + var values: vector; #! One more than the number of each value, or 0 before it is written. + var blocks: vector; #! The number of each block. + var next: u32; #! The number the next value written takes. +} + +#! The name of a type, as the printed code writes it. +#! @param kind The type. +#! @returns Its name. +def type_name(kind: vt): strview { + return match kind { + vt::word => "i64", + vt::real => "f64", + vt::v128 => "v128", + vt::v256 => "v256", + vt::v512 => "v512", + else => "none" + }; +} + +#! Writes a value's name, numbering it where it is new. +#! @param this The code. +#! @param value The value. +#! @param names How the printer numbers what it writes. +#! @param out Where it is written. +def code::print_value(&this, value: u32, names: &mut code_names, out: &mut string): void { + if value == 0 || value as u64 >= names.values.length { + out.append("v?"); + return; + } + if names.values[value] == 0 { + names.next++; + names.values[value] = names.next; + } + out.append($"v{names.values[value] - 1}"); +} + +#! Writes the values of a run of operands, separated by commas. +#! @param this The code. +#! @param index The instruction. +#! @param from The first operand to write. +#! @param names How the printer numbers what it writes. +#! @param out Where it is written. +def code::print_args(&this, index: u32, from: u32, names: &mut code_names, out: &mut string): void { + val held: inst = this.insts[index]; + for i in from..held.argc { + if i != from { + out.append(", "); + } + this.print_value(this.arg(index, i as u32), names, out); + } +} + +#! Writes an edge: the block it goes to, and its arguments where it gives any. +#! @param this The code. +#! @param edge The edge. +#! @param names How the printer numbers what it writes. +#! @param out Where it is written. +def code::print_edge(&this, edge: u32, names: &mut code_names, out: &mut string): void { + val target: u32 = this.edges[edge].target; + out.append($"b{names.blocks[target]}"); + val count := this.edges[edge].args.length; + return if count == 0; + out.append("("); + for i in 0..count { + if i != 0 { + out.append(", "); + } + this.print_value(this.edges[edge].args[i], names, out); + } + out.append(")"); +} + +#! Writes an instruction. +#! @param this The code. +#! @param index The instruction. +#! @param names How the printer numbers what it writes. +#! @param out Where it is written. +def code::print_inst(&this, index: u32, names: &mut code_names, out: &mut string): void { + val held: inst = this.insts[index]; + for i in 0..held.count { + if i != 0 { + out.append(", "); + } + this.print_value(held.result + i as u32, names, out); + } + if held.count != 0 { + out.append(" = "); + } + out.append(held.kind.name()); + + match held.kind { + op::iconst => out.append($" {held.imm as i64}"); + op::fconst => out.append($" {real_of(held.imm)}"); + op::wrap => { + out.append(" "); + this.print_args(index, 0, names, out); + out.append(held.imm != 0 ? $", {held.aux}, signed" : $", {held.aux}, unsigned"); + } + op::cell => out.append($" c{held.aux}"); + op::global => out.append($" {held.imm}"); + op::datum => out.append($" d{held.aux}+{held.imm}"); + op::load => { + out.append($".{(held.aux as access).name()} "); + this.print_args(index, 0, names, out); + if held.imm != 0 { + out.append($"+{held.imm}"); + } + } + op::store => { + out.append($".{(held.aux as access).name()} "); + this.print_value(this.arg(index, 0), names, out); + if held.imm != 0 { + out.append($"+{held.imm}"); + } + out.append(", "); + this.print_value(this.arg(index, 1), names, out); + } + op::copy, op::clear, op::forget => { + out.append(" "); + this.print_args(index, 0, names, out); + out.append($", {held.imm}"); + } + op::call => { + out.append($" f{held.aux}("); + this.print_args(index, 0, names, out); + out.append(")"); + } + op::call_trait => { + out.append($" s{held.aux}[{held.imm}]("); + this.print_args(index, 0, names, out); + out.append(")"); + } + op::call_value, op::call_c => { + out.append($" s{held.aux}("); + this.print_args(index, 0, names, out); + out.append(")"); + } + op::c_address => out.append($" x{held.aux}"); + op::callback, op::safepoint => out.append($" f{held.aux}"); + op::equal => { + out.append(" "); + this.print_args(index, 0, names, out); + out.append($", l{held.aux}"); + } + op::retrait => { + out.append(" "); + this.print_args(index, 0, names, out); + out.append($", r{held.aux}"); + } + op::check => { + out.append(" "); + this.print_args(index, 0, names, out); + out.append($", {error_name(held.aux)}"); + } + op::format_text => out.append($" d{held.aux}"); + op::ready => out.append($" e{held.aux}"); + op::reach => { + out.append(" "); + this.print_args(index, 0, names, out); + out.append($", {held.imm}"); + } + op::lanes => { + out.append($".{held.aux}.{held.imm & 0xFF}.{held.imm >> 8} "); + this.print_args(index, 0, names, out); + } + op::atomic => { + out.append($".{atomic_names[held.aux as u64]}.{atomic_access(held.imm).name()}"); + if (held.imm & atomic_unsigned) != 0 { + out.append(".unsigned"); + } + out.append(" "); + this.print_args(index, 0, names, out); + } + op::format_value => { + out.append($" l{held.aux}"); + if held.argc != 0 { + out.append(", "); + this.print_args(index, 0, names, out); + } + } + op::jump => { + out.append(" "); + this.print_edge(held.aux, names, out); + } + op::branch => { + out.append(" "); + this.print_args(index, 0, names, out); + out.append(", "); + this.print_edge(held.aux, names, out); + out.append(", "); + this.print_edge(held.aux + 1, names, out); + } + op::switch => { + out.append(" "); + this.print_args(index, 0, names, out); + out.append(", ["); + val cases := held.imm as u32 - 1; + for i in 0..cases { + if i != 0 { + out.append(", "); + } + val edge := held.aux + i as u32; + out.append($"{this.edges[edge].case}: "); + this.print_edge(edge, names, out); + } + out.append("], "); + this.print_edge(held.aux + cases, names, out); + } + op::trap => { + out.append(" "); + if held.argc != 0 { + this.print_args(index, 0, names, out); + } else { + out.append(error_name(held.aux)); + } + } + else => { + if held.argc != 0 { + out.append(" "); + this.print_args(index, 0, names, out); + } + } + } +} + +#! The name of an error the machine stops a program with, as printed. +#! @param code The error, as the machine numbers them. +#! @returns Its name. +pub def error_name(code: u32): strview { + return match code { + fault::out_of_bounds as u32 => "out_of_bounds", + fault::null_reference as u32 => "null_reference", + fault::division as u32 => "division", + fault::not_held as u32 => "not_held", + fault::unreachable as u32 => "unreachable", + fault::not_member as u32 => "not_member", + fault::not_constant as u32 => "not_constant", + else => "error" + }; +} diff --git a/compiler/intermediate/verifier.sakura b/compiler/intermediate/verifier.sakura new file mode 100644 index 00000000..9a08ccf7 --- /dev/null +++ b/compiler/intermediate/verifier.sakura @@ -0,0 +1,383 @@ +#! @file verifier.sakura +#! @author John Christman (sorakatadzuma@gmail.com) +#! @copyright Malunal Studios, LLC. +#! @license MIT +#! +#! Contains the verifier, which checks that code is well formed: each block +#! ends in exactly one instruction ending it, each value is defined before +#! every use, in a block dominating the use, each edge gives the block it goes +#! to an argument of the right type for each parameter, and each instruction +#! takes operands of the types its operation does. The tests run it on what +#! lowering makes and after every pass. + +module sakura::compiler; + + +#! What verifying code found wrong. +pub struct verdict { + var problems: vector; #! Each problem, said in words. +} + +#! Whether verifying found nothing wrong. +#! @param this The verdict. +#! @returns Whether it did. +pub def verdict::ok(&this): bool { + return this.problems.length == 0; +} + +#! Verifies the code. +#! @param this The code. +#! @returns What is wrong with it, which is nothing where it is well formed. +pub def code::verify(&this): verdict { + var made := verdict { problems = vector::::new() }; + var order := vector::::new(scratch()); + var number := vector::::new(scratch()); + this.reverse_postorder(&mut order, &mut number); + var idom := this.dominators(order.view(), number.view()); + this.check_kept_order(order.view(), idom.view(), &mut made.problems); + + # Where each instruction is in its block, so a use within one is after the + # value it uses. + var place := vector::::new(scratch()); + place.resize(this.insts.length); + for b in 0..this.blocks.length { + continue if this.blocks[b].gone; + var walk := this.walk(b as u32); + var index: u32 = 1; + while walk.more() { + place[walk.next()] = index; + index++; + } + } + + for b in 0..this.blocks.length { + continue if this.blocks[b].gone; + if b != 0 && number[b] == 0xFFFFFFFF { + made.problems.append($"b{b} is not reached from the entry, but is not removed."); + } + if b == 0 && this.blocks[b].preds.length != 0 { + made.problems.append("The entry has edges into it."); + } + + if this.blocks[b].first == 0 { + made.problems.append($"b{b} is empty."); + continue; + } + var walk := this.walk(b as u32); + while walk.more() { + val at := walk.next(); + val held: inst = this.insts[at]; + if held.block != b as u32 { + made.problems.append($"Instruction {at} is in b{b} but says it is in b{held.block}."); + } + if held.kind.ends() && held.next != 0 { + made.problems.append($"b{b} goes on past `{held.kind.name()}`, which ends it."); + } + if !held.kind.ends() && held.next == 0 { + made.problems.append($"b{b} does not end with what ends a block."); + } + + for i in 0..held.argc { + val value := this.arg(at, i as u32); + this.verify_use(value, b as u32, place[at], &idom, &place, &mut made, held.kind.name()); + } + this.verify_types(at, &mut made); + if held.kind.ends() { + this.verify_edges(at, &idom, &place, &mut made); + } + } + } + return made; +} + +#! Checks that a value is defined where it is used: before the use in the same +#! block, or in a block dominating the block of the use. +#! @param this The code. +#! @param value The value used. +#! @param block The block of the use. +#! @param index Where in the block the use is, past every instruction for an +#! edge's argument. +#! @param idom The immediate dominator of each block. +#! @param place Where each instruction is in its block. +#! @param made Where problems are noted. +#! @param what What uses it, for the note. +def code::verify_use( + &this, + value: u32, + block: u32, + index: u32, + idom: &vector, + place: &vector, + made: &mut verdict, + what: strview +): void { + if value == 0 || value as u64 >= this.origins.length { + made.problems.append($"b{block}: `{what}` uses value {value}, which is none."); + return; + } + + val held: origin = this.origins[value]; + val home := this.home_of(value); + if this.blocks[home].gone { + made.problems.append($"b{block}: `{what}` uses v{value}, of b{home}, which is removed."); + return; + } + if held.param && this.blocks[home].params.length <= held.index as u64 { + made.problems.append($"b{block}: `{what}` uses v{value}, a parameter b{home} no longer takes."); + return; + } + if home == block { + if !held.param && place[held.from] >= index { + made.problems.append($"b{block}: `{what}` uses v{value} before it is defined."); + } + return; + } + if !dominates(idom, home, block) { + made.problems.append($"b{block}: `{what}` uses v{value}, defined in b{home}, which does not dominate it."); + } +} + +#! Checks that an instruction ending a block gives each block it goes to an +#! argument of the right type for each of its parameters. +#! @param this The code. +#! @param index The instruction. +#! @param idom The immediate dominator of each block. +#! @param place Where each instruction is in its block. +#! @param made Where problems are noted. +def code::verify_edges(&this, index: u32, idom: &vector, place: &vector, made: &mut verdict): void { + val held: inst = this.insts[index]; + var outs := this.edges_of(index); + while outs.more() { + val edge := outs.next(); + val target: u32 = this.edges[edge].target; + val args := this.edges[edge].args.length; + val params := this.blocks[target].params.length; + if args != params { + made.problems.append($"b{held.block}: an edge into b{target} gives {args} arguments for {params} parameters."); + continue; + } + for i in 0..args { + val given: u32 = this.edges[edge].args[i]; + this.verify_use(given, held.block, 0xFFFFFFFF, idom, place, made, "an edge"); + val want := this.type_of(this.blocks[target].params[i]); + if given != 0 && (given as u64) < this.origins.length && this.type_of(given) != want { + made.problems.append($"b{held.block}: an edge gives parameter {i} of b{target} a value of another type."); + } + } + } +} + +#! Checks that an instruction takes operands of the types its operation does. +#! @param this The code. +#! @param index The instruction. +#! @param made Where problems are noted. +def code::verify_types(&this, index: u32, made: &mut verdict): void { + val held: inst = this.insts[index]; + val name := held.kind.name(); + var wants := vector::::new(scratch()); + var exact := true; + match held.kind { + op::add, op::sub, op::mul, op::divs, op::divu, op::rems, op::remu, op::band, op::bor, op::bxor, + op::shl, op::shrs, op::shru, op::eq, op::ne, op::lts, op::ltu, op::les, op::leu, op::eqsu, + op::ltsu, op::lesu, op::ltus, op::leus, op::copy, op::equal, op::resize, op::format_bytes, op::fault, + op::reach, op::same => { + wants.append(vt::word); + wants.append(vt::word); + } + op::fadd, op::fsub, op::fmul, op::fdiv, op::frem, op::feq, op::fne, op::flt, op::fle => { + wants.append(vt::real); + wants.append(vt::real); + } + op::neg, op::bnot, op::lnot, op::itof, op::utof, op::ones, op::clz, op::ctz, op::bswap, op::wrap, op::load, + op::clear, op::forget, op::allocate, op::release, op::retrait, op::check, op::catch, op::exit, op::branch, + op::switch => wants.append(vt::word); + op::fneg, op::ftoi, op::ftou, op::fsingle, op::fsqrt => wants.append(vt::real); + op::select => { + # A word chosen by a word, between two words or two reals, of the type it + # gives. + val chosen := held.count == 1 ? this.type_of(held.result) : vt::none; + if chosen != vt::word && chosen != vt::real { + made.problems.append($"b{held.block}: `{name}` gives no word or real."); + } + wants.append(vt::word); + wants.append(chosen); + wants.append(chosen); + } + op::store => { + wants.append(vt::word); + val how: access = held.aux as access; + wants.append(how.value_type()); + } + op::syscall => { + for _ in 0..7 { wants.append(vt::word); } + } + op::call_trait, op::call_value => { + for _ in 0..2 { wants.append(vt::word); } + exact = false; + } + op::call_c => { + wants.append(vt::word); + exact = false; + } + op::call, op::format_value, op::lanes => exact = false; + op::start => { + for _ in 0..3 { wants.append(vt::word); } + } + op::clone => wants.append(vt::word); + op::atomic => { + # Words: the address but of a fence, its operands, and its orders. + val count: u32 = held.aux == atomic_fence ? 1 : held.aux == atomic_load ? 2 : held.aux == atomic_compare_exchange ? 5 : 3; + for _ in 0..count { wants.append(vt::word); } + } + op::trap => { + # The runtime stops with an error it is given, as a word. + if held.argc != 0 { + wants.append(vt::word); + } + } + op::ret => { + wants.extend(this.results.view()); + if this.returned != 0 { + wants.append(vt::word); + } + } + else => {} + } + + if exact && held.argc as u64 != wants.length { + made.problems.append($"b{held.block}: `{name}` takes {wants.length} operands, but is given {held.argc}."); + return; + } + if !exact && (held.argc as u64) < wants.length { + made.problems.append($"b{held.block}: `{name}` takes at least {wants.length} operands, but is given {held.argc}."); + return; + } + for i in 0..wants.length { + val given := this.arg(index, i as u32); + continue if given == 0 || given as u64 >= this.origins.length; + if this.type_of(given) != wants[i] { + made.problems.append($"b{held.block}: operand {i} of `{name}` is v{given}, of another type than it takes."); + } + } +} + +#! Orders the blocks the entry reaches so each comes before those it goes to, +#! but along edges going back, and numbers each by its place in that order. +#! @param this The code. +#! @param order Where the blocks are written, in that order. +#! @param number Where each block's place is written, by its index, or +#! `0xFFFFFFFF` for one the entry does not reach. +pub def code::reverse_postorder(&this, order: &mut vector, number: &mut vector): void { + # Each block's number marks it seen, from where it is put on the walk, and is + # its place once the walk is done. + number.clear(); + number.resize(this.blocks.length, 0xFFFFFFFF); + order.clear(); + + # Each block on the walk with the next of its edges to follow, as + # `pair_key(block, next)`; the blocks are written as each is left, which is + # postorder, then turned round. + var stack := vector::::new(scratch()); + stack.append(pair_key(0, 0)); + number[0] = 0; + while stack.length != 0 { + # The top is written before a block is pushed, which may move it. + val top := &mut stack.last(); + val block := pair_high(top); + val next := pair_low(top); + val last: u32 = this.blocks[block].last; + val count := last == 0 ? 0 : this.edge_count(last); + if next >= count { + order.append(block); + stack.truncate(); + continue; + } + top = pair_key(block, next + 1); + val target: u32 = this.edges[this.insts[last].aux + next].target; + if number[target] == 0xFFFFFFFF { + number[target] = 0; + stack.append(pair_key(target, 0)); + } + } + + val length := order.length; + for i in 0..length / 2 { + val other := length - 1 - i; + val held: u32 = order[i]; + order[i] = order[other]; + order[other] = held; + } + for i in 0..length { + number[order[i]] = i as u32; + } +} + +#! The immediate dominator of each block the entry reaches, as Cooper, Harvey, +#! and Kennedy's "A Simple, Fast Dominance Algorithm" finds them. +#! @param this The code. +#! @param order The blocks in reverse postorder. +#! @param number Each block's place in that order. +#! @returns The immediate dominator of each block, by its index: the entry's is +#! itself, and that of a block not reached `no_block`. +pub def code::dominators(&this, order: span, number: span): vector { + var idom := vector::::new(scratch()); + idom.resize(this.blocks.length, no_block); + return idom if order.length == 0; + idom[0] = 0; + + var changed := true; + while changed { + changed = false; + for i in 1..order.length { + val block := order[i]; + var chosen := no_block; + for &edge in this.blocks[block].preds { + val pred := this.edge_source(edge); + continue if idom[pred] == no_block; + chosen = chosen == no_block ? pred : intersect(&idom, number, pred, chosen); + } + if chosen != no_block && idom[block] != chosen { + idom[block] = chosen; + changed = true; + } + } + } + return idom; +} + +#! The nearest block dominating both blocks. +#! @param idom The immediate dominator of each block so far. +#! @param number Each block's place in reverse postorder. +#! @param a One block. +#! @param b The other. +#! @returns The block. +def intersect(idom: &vector, number: span, a: u32, b: u32): u32 { + var x := a; + var y := b; + while x != y { + while number[x] > number[y] { + x = idom[x]; + } + while number[y] > number[x] { + y = idom[y]; + } + } + return x; +} + +#! Whether a block dominates another: every path from the entry to the other +#! goes through it. +#! @param idom The immediate dominator of each block. +#! @param a The block that may dominate. +#! @param b The block it may dominate. +#! @returns Whether it does. +pub def dominates(idom: &vector, a: u32, b: u32): bool { + var at := b; + var steps := 0; + while at != a && steps < 1000000 { + return false if at == 0 || at == no_block; + at = idom[at]; + steps++; + } + return at == a; +} diff --git a/compiler/intermediate/walks.sakura b/compiler/intermediate/walks.sakura new file mode 100644 index 00000000..5cc49572 --- /dev/null +++ b/compiler/intermediate/walks.sakura @@ -0,0 +1,246 @@ +#! @file walks.sakura +#! @author John Christman (sorakatadzuma@gmail.com) +#! @copyright Malunal Studios, LLC. +#! @license MIT +#! +#! Contains the walks over code that the passes and the backends share: of the +#! instructions of a block, or of every block not removed, of the edges an +#! instruction leaves by, and of the values an instruction reads. Each is asked +#! `more` and then gives the next with `next`, so a `continue` goes on to the +#! next rather than round again, and a walk gives nothing once it is done. What +#! each is asked is small enough for the optimizer to inline, so a pass walking +#! with one costs what a loop written out by hand does. + +module sakura::compiler; + + +#! What `read_walk::operand` gives for a value an edge gives, which is no +#! operand. +pub const no_operand: u32 = 0xFFFFFFFF; + +#! A walk of the instructions of one block, in order. It reads where each +#! instruction goes on to as it gives it, so the instruction given may be +#! rewritten, moved, or taken out, and what is put after it is not given. +#! Asking it for each is small enough to be inlined, and nothing takes its +#! address, so what it holds stays in registers as it goes. +pub struct inst_walk { + var body: &code; #! The code. + var at: u32; #! The next instruction it gives, or 0 where none is left. +} + +#! Walks the instructions of a block, in order. +#! @param this The code. +#! @param block The block. +#! @returns The walk. +pub def code::walk(&this, block: u32): inst_walk { + return inst_walk { body = this, at = this.blocks[block].first }; +} + +#! Whether the walk has another instruction to give. +#! @param this The walk. +#! @returns Whether it has. +pub def inst_walk::more(&this): bool { + return this.at != 0; +} + +#! Gives the next instruction, once `more` says there is one. +#! @param this The walk. +#! @returns The instruction. +pub def inst_walk::next(&mut this): u32 { + val at := this.at; + this.at = this.body.insts[at].next; + return at; +} + +#! A walk of the instructions of every block not removed: the blocks in order, +#! and each one's instructions in order, as `inst_walk` gives them. It goes +#! into each block by a call that takes the walk's values, not its address, so +#! what it holds stays in registers too. +pub struct code_walk { + var body: &code; #! The code. + var at: u32; #! The next instruction it gives, or 0 where the block it is in has no more. + var block: u32; #! The next block it goes into once that one has no more. + var end: u32; #! The block after the last it goes into. +} + +#! Walks the instructions of every block not removed. A block is asked whether +#! it is removed as the walk goes into it, and the blocks are those the code +#! has now. +#! @param this The code. +#! @returns The walk. +pub def code::walk_all(&this): code_walk { + return code_walk { body = this, end = this.blocks.length as u32 }; +} + +#! Whether the walk has another instruction to give. +#! @param this The walk. +#! @returns Whether it has. +pub def code_walk::more(&mut this): bool { + return true if this.at != 0; + val found := this.body.next_filled(this.block, this.end); + this.block = pair_high(found); + this.at = pair_low(found); + return this.at != 0; +} + +#! Gives the next instruction, once `more` says there is one. +#! @param this The walk. +#! @returns The instruction. +pub def code_walk::next(&mut this): u32 { + val at := this.at; + this.at = this.body.insts[at].next; + return at; +} + +#! Finds the first block from one on, and before another, that is not removed +#! and holds an instruction. +#! @param this The code. +#! @param block The block to look from. +#! @param end The block to look before. +#! @returns The block after the one found, and its first instruction, as +#! `pair_key` packs them, or `end` and 0 where none is. +pub def code::next_filled(&this, block: u32, end: u32): u64 { + var at := block; + while at < end { + val held := &this.blocks[at]; + at++; + return pair_key(at, held.first) if !held.gone && held.first != 0; + } + return pair_key(end, 0); +} + +#! A walk of the edges an instruction ending a block leaves by, which follow one +#! another from its `aux`. +pub struct edge_walk { + var at: u32; #! The next edge it gives. + var end: u32; #! The edge after the last. +} + +#! Walks the edges an instruction leaves by, in order: none for one that does +#! not end its block, or returns or stops. +#! @param this The code. +#! @param index The instruction. +#! @returns The walk. +pub def code::edges_of(&this, index: u32): edge_walk { + val first: u32 = this.insts[index].aux; + return edge_walk { at = first, end = first + this.edge_count(index) }; +} + +#! Whether the walk has another edge to give. +#! @param this The walk. +#! @returns Whether it has. +pub def edge_walk::more(&this): bool { + return this.at < this.end; +} + +#! Gives the next edge, once `more` says there is one. +#! @param this The walk. +#! @returns The edge. +pub def edge_walk::next(&mut this): u32 { + val at := this.at; + this.at = at + 1; + return at; +} + +#! A walk of every value instructions read: an instruction's operands, in +#! order, then the arguments of each edge it leaves by, edge after edge. A +#! walk is made once for the code with `reader`, then started at each +#! instruction in turn, or made for one with `reads_of`. It reads the values +#! where they are held, so nothing may add instructions, operands, or edges to +#! the code while it walks. Starting it is small enough to be inlined, so a +#! pass walking what every instruction reads makes no call for each. +pub struct read_walk { + var insts: *inst; #! The code's instructions. + var values: *u32; #! The code's operands. + var edges: *edge; #! The code's edges. + var held: *inst; #! The instruction while its operands are given, or null once its edges' arguments are. + var data: *u32; #! Where the values it is giving are held: its operands, or an edge's arguments. + var at: u64; #! The place there of the next it gives. + var end: u64; #! How many are held there. + var ends: bool; #! Whether the instruction ends its block, so the arguments of its edges follow its operands. + var edge: u32; #! The next edge whose arguments it gives. + var last: u32; #! The edge after the instruction's last. +} + +#! Makes a walk of what the code's instructions read, to be started at each. +#! @param this The code. +#! @returns The walk, which gives nothing until it is started. +pub def code::reader(&this): read_walk { + return read_walk { + insts = this.insts.view().data, + values = this.operands.view().data, + edges = this.edges.view().data + }; +} + +#! Walks every value an instruction reads. +#! @param this The code. +#! @param index The instruction. +#! @returns The walk. +pub def code::reads_of(&this, index: u32): read_walk { + var made := this.reader(); + made.start(index); + return made; +} + +#! Starts the walk at an instruction, from its first operand. +#! @param this The walk. +#! @param index The instruction. +pub def read_walk::start(&mut this, index: u32): void { + val held := this.insts + index as u64; + this.held = held; + this.data = this.values + held[0].args as u64; + this.at = 0; + this.end = held[0].argc as u64; + # The operations from `jump` on are those ending a block, as `op` orders + # them, which a comparison asks more cheaply than `op::ends`. + this.ends = held[0].kind as u32 >= op::jump as u32; +} + +#! Whether the walk has another value to give. +#! @param this The walk. +#! @returns Whether it has. +pub def read_walk::more(&mut this): bool { + return true if this.at < this.end; + return this.ends && this.next_edge(); +} + +#! Gives the next value, once `more` says there is one. +#! @param this The walk. +#! @returns The value. +pub def read_walk::next(&mut this): u32 { + val value := this.data[this.at]; + this.at++; + return value; +} + +#! Which operand the value the walk gave last is. +#! @param this The walk. +#! @returns Its position among the operands, or `no_operand` where an edge +#! gives it. +pub def read_walk::operand(&this): u32 { + return this.held != null ? (this.at - 1) as u32 : no_operand; +} + +#! Goes on to the arguments of the next edge of the instruction that gives +#! any, its operands given. +#! @param this The walk. +#! @returns Whether one does. +def read_walk::next_edge(&mut this): bool { + if this.held != null { + this.edge = this.held[0].aux; + this.last = this.edge + this.held[0].edge_count(); + this.held = null; + } + while this.edge < this.last { + val args := &this.edges[this.edge as u64].args; + this.edge++; + if args.length != 0 { + this.data = args.data(); + this.at = 0; + this.end = args.length; + return true; + } + } + return false; +} diff --git a/compiler/keeps.sakura b/compiler/keeps.sakura new file mode 100644 index 00000000..a960eff7 --- /dev/null +++ b/compiler/keeps.sakura @@ -0,0 +1,410 @@ +#! @file keeps.sakura +#! @author John Christman (sorakatadzuma@gmail.com) +#! @copyright Malunal Studios, LLC. +#! @license MIT +#! +#! Contains what a function may do with what it is given past a call, its +#! summary: of each parameter, whether the reference it is given may be kept, +#! as where the function stores it, or given back in what the function returns; +#! and whether what that reference reaches, or what a value given holds, may +#! be. A local a reference is taken of lives in a cell of the frame, which +#! keeps its address for as long as the function runs, where the reference may +#! be kept past the statement taking it, and in its slots otherwise, so the +#! summaries decide where the locals of every caller are held. +#! +#! A function's summary comes from scanning its body, as `escapes.sakura` does, +#! with what each parameter is given standing as spots of the caller's. A +#! reference held in a value is followed where the value goes, so a function +#! giving back a value holding a reference to what it was given only gives the +#! reference back, which its caller follows in turn. Anything the scan does not +#! recognize keeps what it is given. +#! +#! Functions calling one another are summarized together, as Tarjan's algorithm +#! finds them: a function whose scan is not done is taken to do what was found +#! of it so far, nothing at first, and each function reading that is noted as +#! its reader. Once the first function of such a group is scanned, each of the +#! group whose summary grew after a reader read it has that reader scanned +#! again, until none grows, and each is then summarized for good. A function is +#! so scanned again only for what it read, never for what it calls being +#! scanned again. + +import sakura::analyzer; +module sakura::compiler; + + +#! What a function may do with what each parameter gives it, one bit for each +#! parameter, `this` first. A parameter at 62 or past is taken to keep all. +pub struct keeping { + var kept: u64; #! Whose reference may be kept past the call. + var given: u64; #! Whose reference may be given back, in what the call gives. + var reached: u64; #! Of whose reference what it reaches, or of whose value what it holds, may be kept. + var passed: u64; #! Of whose reference what it reaches, or of whose value what it holds, may be given back. +} + +#! The summary of a function that may do anything with what it is given. +#! @returns The summary. +pub def keeping::all(): keeping { + return keeping { kept = 0xFFFFFFFFFFFFFFFF, given = 0xFFFFFFFFFFFFFFFF, reached = 0xFFFFFFFFFFFFFFFF, passed = 0xFFFFFFFFFFFFFFFF }; +} + +#! Whether a summary does all another does. +#! @param this The summary. +#! @param other The other. +#! @returns Whether it does. +pub def keeping::covers(&this, other: &keeping): bool { + return (this.kept | other.kept) == this.kept && (this.given | other.given) == this.given + && (this.reached | other.reached) == this.reached && (this.passed | other.passed) == this.passed; +} + +#! A function whose summary is being found. +pub struct pending_scan { + var key: u64; #! The function, as `pair_key(decl, instance)`. + var decl: u32; #! Its declaration. + var instance: u32; #! One more than the instance scanned, or 0. + var found: keeping; #! What was found of it so far. + var low: u32; #! The earliest pending function it reaches, by its place. + var stale: bool; #! Whether a summary it read grew since it read it. + var readers: u32; #! One more than the first link of the functions that read its summary, or 0. +} + +#! What `scanning` holds where no summary is being scanned. +const no_scan: u32 = 0xFFFFFFFF; + +#! The summary of a function, or of an instance of a generic one, found where +#! it is new. A C function is given only an address, good until it returns, +#! and nothing is taken as kept. +#! What has no body to scan, as an intrinsic or a trait's method, may do +#! anything, but for an instance of a default compiled for each type, which is +#! scanned as the type's own method is. +#! @param this The compiler. +#! @param decl The function's declaration. +#! @param instance One more than the instance called, or 0. +#! @returns The summary. +pub def lowerer::keeps_of(&mut this, decl: u32, instance: u32): keeping { + return keeping::all() if decl == 0 || (decl & (ref_local | ref_type)) != 0 || this.checker.decls.kinds.p[decl] != dk::function; + this.checker.resolve(decl); + return keeping {} if this.checker.decls.has(decl, df::foreign) && !this.checker.has_body(decl); + return keeping::all() if this.checker.decls.has(decl, df::intrinsic) || !this.checker.has_body(decl) + || (this.trait_of_method(decl) != 0 && (instance == 0 || !this.checker.typed_default(decl))); + + val key := pair_key(decl, instance); + if this.summaries.get(&key) is some(got) { + return got; + } + if this.pending_ids.get(&key) is some(at) { + this.lean_on(at); + return this.pending[at as u64].found; + } + return this.summarize(decl, instance, key); +} + +#! The summary of the function a call calls: a trait's method without a body, +#! called on a value whose type is known, is the method of that type the +#! vtable holds. +#! @param this The compiler. +#! @param decl The function's declaration. +#! @param instance One more than the instance called, or 0. +#! @param object The node of the value a method is called on, or 0. +#! @returns The summary. +pub def lowerer::keeps_of_call(&mut this, decl: u32, instance: u32, object: u32): keeping { + if object != 0 && instance == 0 && decl != 0 && (decl & (ref_local | ref_type)) == 0 && this.checker.typed_default(decl) { + return this.keeps_of_method(decl, this.checker.reached(this.checker.type_at(object))); + } + if object != 0 && decl != 0 && (decl & (ref_local | ref_type)) == 0 && this.trait_of_method(decl) != 0 + && !this.checker.has_body(decl) { + val callee := this.trait_callee(decl, this.checker.reached(this.checker.type_at(object))); + return keeping::all() if callee == 0; + return this.keeps_of(pair_high(callee), pair_low(callee)); + } + return this.keeps_of(decl, instance); +} + +#! The summary of a method the compiler calls itself on a value of a type, as a +#! loop's `next`, the instance the type's arguments give. +#! @param this The compiler. +#! @param decl The method's declaration, or 0. +#! @param owner The type it is called on. +#! @returns The summary. +pub def lowerer::keeps_of_method(&mut this, decl: u32, owner: u32): keeping { + return keeping::all() if decl == 0; + this.checker.resolve(decl); + if this.checker.typed_default(decl) { + val plain := this.checker.unalias(owner); + val holder := this.checker.enclosing_trait(decl); + val made := this.checker.default_instance(decl, this.checker.implemented(plain, holder), plain, span::::empty()); + return made == 0 ? keeping::all() : this.keeps_of(decl, made); + } + if this.trait_of_method(decl) != 0 { + return keeping::all() if this.checker.has_body(decl); + val callee := this.trait_callee(decl, owner); + return keeping::all() if callee == 0; + return this.keeps_of(pair_high(callee), pair_low(callee)); + } + return this.keeps_of(decl, this.method_instance(decl, owner)); +} + +#! The method a trait's method without a body calls on a value of a known type, +#! as its vtable holds it. +#! @param this The compiler. +#! @param decl The trait's method. +#! @param receiver The type of the value, read through its references. +#! @returns The method and its instance, as `pair_key(decl, instance)`, or 0 +#! where the type is not known, or the method is a default. +def lowerer::trait_callee(&mut this, decl: u32, receiver: u32): u64 { + val plain := this.checker.unalias(receiver); + return 0 if this.checker.types.kind_of(plain) != ty::named || this.checker.named_kind(plain) == dk::trait_type; + val implemented := this.checker.implemented(plain, this.checker.enclosing_trait(decl)); + val found := this.implementation(plain, decl, implemented); + return 0 if found == 0 || this.trait_of_method(found) != 0; + return pair_key(found, this.method_instance(found, plain)); +} + +#! The instance of a method a type's arguments give, as `method_target` finds +#! it. +#! @param this The compiler. +#! @param decl The method's declaration. +#! @param owner The type it is called on. +#! @returns One more than the instance, or 0. +pub def lowerer::method_instance(&mut this, decl: u32, owner: u32): u32 { + return 0 if decl == 0; + this.checker.resolve(decl); + return 0 if this.trait_of_method(decl) != 0 || !this.checker.decls.has(decl, df::generic); + val plain := this.checker.unalias(owner); + var args := vector::::new(); + if this.checker.types.kind_of(plain) == ty::named { + for i in 0..this.checker.types.part_count(plain) { + args.append(this.checker.types.part_at(plain, i as u32)); + } + } + return this.checker.instance_of(decl, args.view(), 0); +} + +#! The type of a method called on a value of a type, as `method_target` gives +#! it. +#! @param this The compiler. +#! @param decl The method's declaration. +#! @param instance One more than its instance, as `method_instance` gives it. +#! @param owner The type it is called on. +#! @returns The function type. +pub def lowerer::method_kind(&mut this, decl: u32, instance: u32, owner: u32): u32 { + return bt::error if decl == 0; + val plain := this.checker.unalias(owner); + return this.checker.trait_method_type(decl, plain) if this.trait_of_method(decl) != 0; + return this.checker.instances[instance - 1].kind if instance != 0; + return this.checker.method_type(decl, plain) if this.checker.decls.has(decl, df::generic); + return this.checker.decls.types.p[decl]; +} + +#! Notes that the scan being made read the summary of a pending function, which +#! it then reaches, and must be scanned again where that summary grows. +#! @param this The compiler. +#! @param at The pending function, by its place. +def lowerer::lean_on(&mut this, at: u32): void { + # A function calling itself reads its own summary too. + val reader := this.scanning; + return if reader == no_scan; + if at < this.pending[reader as u64].low { + this.pending[reader as u64].low = at; + } + return if !this.read_pairs.insert(pair_key(at, reader)); + this.reader_of.append(reader); + this.reader_next.append(this.pending[at as u64].readers); + this.pending[at as u64].readers = this.reader_of.length as u32; +} + +#! Finds the summary of a function not yet scanned: scans it, and where it is +#! the first of a group calling back into one another, settles the group. +#! @param this The compiler. +#! @param decl The function's declaration. +#! @param instance One more than the instance, or 0. +#! @param key The function, as `pair_key(decl, instance)`. +#! @returns What was found of it, for good where its group is settled. +def lowerer::summarize(&mut this, decl: u32, instance: u32, key: u64): keeping { + val at := this.pending.length as u32; + this.pending.append(pending_scan { key = key, decl = decl, instance = instance, low = at }); + this.pending_ids.set(key, at); + val outer := this.scanning; + this.scanning = at; + val found := this.summary_scan(decl, instance); + this.scanning = outer; + this.grow(at, &found); + + if this.pending[at as u64].low == at { + this.settle_group(at); + return this.summaries.get_or(&key, keeping::all()); + } + # Still pending, as the group it is in is: the scan around it reaches what it + # reaches, and read what it found. + if outer != no_scan && this.pending[at as u64].low < this.pending[outer as u64].low { + this.pending[outer as u64].low = this.pending[at as u64].low; + } + this.lean_on(at); + return this.pending[at as u64].found; +} + +#! Adds to what was found of a pending function, and has each function that read +#! it scanned again where that grew. +#! @param this The compiler. +#! @param at The pending function, by its place. +#! @param found What a scan found of it. +def lowerer::grow(&mut this, at: u32, found: &keeping): void { + val had: keeping = this.pending[at as u64].found; + return if had.covers(found); + this.pending[at as u64].found = keeping { + kept = had.kept | found.kept, given = had.given | found.given, + reached = had.reached | found.reached, passed = had.passed | found.passed + }; + var link: u32 = this.pending[at as u64].readers; + while link != 0 { + this.pending[this.reader_of[link as u64 - 1] as u64].stale = true; + link = this.reader_next[link as u64 - 1]; + } +} + +#! Settles a group of functions calling back into one another, from its first, +#! once that is scanned: each that read a summary which grew since is scanned +#! again, until none grows, and each is then summarized for good. A group that +#! will not settle, which never happens, is taken to do anything. +#! @param this The compiler. +#! @param root The group's first function, by its place. +def lowerer::settle_group(&mut this, root: u32): void { + var rounds: u64 = 0; + var more := true; + while more { + more = false; + var m := root as u64; + while m < this.pending.length { + if this.pending[m].stale { + this.pending[m].stale = false; + more = true; + val outer := this.scanning; + this.scanning = m as u32; + val found := this.summary_scan(this.pending[m].decl, this.pending[m].instance); + this.scanning = outer; + this.grow(m as u32, &found); + rounds++; + } + m++; + } + if rounds > 64 * (this.pending.length - root as u64) + 1024 { + for k in root as u64..this.pending.length { + this.pending[k].found = keeping::all(); + } + break; + } + } + + for k in root as u64..this.pending.length { + val held: pending_scan = this.pending[k]; + this.summaries.set(held.key, held.found); + this.pending_ids.remove(&held.key); + } + this.pending.resize(root as u64); + if this.pending.length == 0 { + this.reader_of.clear(); + this.reader_next.clear(); + this.read_pairs.clear(); + } +} + +#! Scans a function's body for what it does with what it is given, each +#! parameter given spots of the caller's, and the scan's memory freed once the +#! summary is read from it. +#! @param this The compiler. +#! @param decl The function's declaration. +#! @param instance One more than the instance scanned, or 0. +#! @returns What it was found to do. +def lowerer::summary_scan(&mut this, decl: u32, instance: u32): keeping { + val saved := this.checker.at; + this.checker.use_table(this.body_table(decl, instance)); + val node: u32 = this.checker.decls.nodes.p[decl]; + val accessor := this.checker.decls.has(decl, df::accessor); + val body := accessor ? this.checker.record(node, accessor_slot::body) : this.checker.record(node, function_slot::body); + val params := accessor ? this.checker.left_of(node) : this.checker.record(node, function_slot::params); + val kind := this.type_of_function(decl, instance); + + val point := mark_scratch(); + var made := keeping {}; + { + var s := escape_scan::new(scratch()); + s.result = this.checker.types.first_of(kind); + this.scan_params(&mut s, params, kind, this.packs_last(decl)); + this.scan_body(&mut s, body); + s.graph.solve(); + s.graph.settle(); + val count := this.checker.types.part_count(kind) as u64; + for i in 0..(count < 62 ? count : 62) { + val bit := 1u << i; + val outer: u32 = i < s.outers.length ? s.outers[i] : 0; + val inner: u32 = i < s.inners.length ? s.inners[i] : 0; + # What a pack takes, or what no parameter names, may be anything. + if inner == 0 { + made.kept |= bit; + made.given |= bit; + made.reached |= bit; + made.passed |= bit; + continue; + } + if outer != 0 { + val went: reach = s.graph.spots[outer as u64].reach; + if went == reach::kept { + made.kept |= bit; + } else if went == reach::given { + made.given |= bit; + } + } + val within: reach = s.graph.spots[inner as u64].reach; + if within == reach::kept { + made.reached |= bit; + } else if within == reach::given { + made.passed |= bit; + } + } + } + release_scratch(point); + this.checker.at = saved; + return made; +} + +#! Whether a function's last parameter is a pack, which takes every parameter +#! from its own on. +#! @param this The compiler. +#! @param decl The function's declaration. +#! @returns Whether it is. +pub def lowerer::packs_last(&mut this, decl: u32): bool { + val written: u32 = this.checker.decls.types.p[decl]; + val count := this.checker.types.part_count(written); + return this.checker.decls.has(decl, df::variadic) && count != 0 + && this.checker.types.is_open_pack(this.checker.types.part_at(written, count - 1)); +} + +#! The method an arithmetic operator calls, as the checker chose it, or 0 where +#! the language operates on its operands itself. +#! @param this The compiler. +#! @param node The operator's node. +#! @returns The method's declaration, or 0. +def lowerer::operator_called(&mut this, node: u32): u32 { + val kind := this.checker.kind_of(node); + return 0 if kind == nk::unary && this.checker.token_kind(node) != tk::minus && this.checker.token_kind(node) != tk::bitnot; + val ref := this.checker.ref_at(node); + return 0 if ref == 0 || (ref & (ref_local | ref_type)) != 0 || this.checker.decls.kinds.p[ref] != dk::function; + return ref; +} + +#! The instance of a generic a call or an operator's method uses, as the +#! checker chose it. +#! @param this The compiler. +#! @param node The call's node. +#! @returns One more than the instance, or 0. +pub def lowerer::called(&mut this, node: u32): u32 { + val key := this.checker.result_key(node); + return this.checker.called.get_or(&key, 0); +} + +#! Whether a type is a reference. +#! @param this The compiler. +#! @param kind The type. +#! @returns Whether it is. +pub def lowerer::is_reference_type(&mut this, kind: u32): bool { + return kind != 0 && this.checker.types.kind_of(this.checker.unalias(kind)) == ty::reference; +} diff --git a/compiler/lanes.sakura b/compiler/lanes.sakura new file mode 100644 index 00000000..7dd221c3 --- /dev/null +++ b/compiler/lanes.sakura @@ -0,0 +1,381 @@ +#! @file lanes.sakura +#! @author John Christman (sorakatadzuma@gmail.com) +#! @copyright Malunal Studios, LLC. +#! @license MIT +#! +#! Contains which vector instructions each operation on the lanes of a `simd` +#! needs: what `core::lanes_have` asks the processor running an executable for, +#! as it found it when it started, and what `core::lanes_apply` then works the +#! lanes with. SSE2 is every x86-64 processor's, and the rest only some have, so +#! an operation needing them is worked as std writes it, a lane at a time, where +#! the processor lacks them. + +module sakura::compiler; + + +#! The instruction sets an executable asks its processor for as it starts, one +#! bit each of the word it keeps them in. +pub const cpu_sse2: u64 = 0x01; +pub const cpu_ssse3: u64 = 0x02; +pub const cpu_sse41: u64 = 0x04; +pub const cpu_sse42: u64 = 0x08; +#! AVX, where the system also keeps the registers' upper halves. +pub const cpu_avx: u64 = 0x10; +pub const cpu_avx2: u64 = 0x20; +pub const cpu_fma: u64 = 0x40; +#! Counting a word's ones, `popcnt`, and its leading zeros, `lzcnt`. +pub const cpu_popcnt: u64 = 0x80; +pub const cpu_lzcnt: u64 = 0x100; +#! BMI1, which has `tzcnt`, counting trailing zeros. +pub const cpu_bmi1: u64 = 0x200; +#! AVX-512's foundation with its instructions of 16-bit lanes (BW), of 64-bit +#! integers (DQ), and of 16 and 32 bytes (VL), where the system also keeps the +#! mask registers and the registers' upper 384 bits, as x86-64-v4 has them. +pub const cpu_avx512: u64 = 0x400; +#! What no processor has, for an operation no instructions work. +pub const cpu_never: u64 = 0x8000000000000000; + +#! The operations on lanes, as std numbers them. +pub const lanes_add: u32 = 1; +pub const lanes_sub: u32 = 2; +pub const lanes_mul: u32 = 3; +pub const lanes_div: u32 = 4; +pub const lanes_and: u32 = 5; +pub const lanes_or: u32 = 6; +pub const lanes_xor: u32 = 7; +pub const lanes_negate: u32 = 8; +pub const lanes_not: u32 = 9; +pub const lanes_min: u32 = 10; +pub const lanes_max: u32 = 11; +pub const lanes_abs: u32 = 12; +pub const lanes_sqrt: u32 = 13; +pub const lanes_floor: u32 = 14; +pub const lanes_ceil: u32 = 15; +pub const lanes_trunc: u32 = 16; +pub const lanes_round_even: u32 = 17; +pub const lanes_equal: u32 = 18; +pub const lanes_not_equal: u32 = 19; +pub const lanes_less: u32 = 20; +pub const lanes_less_equal: u32 = 21; +pub const lanes_greater: u32 = 22; +pub const lanes_greater_equal: u32 = 23; +pub const lanes_select: u32 = 24; #! `a` the mask, `b` taken where it is set, `c` where not. +pub const lanes_fma: u32 = 25; #! `a * b + c`. +pub const lanes_shift_left: u32 = 26; #! `b` the `u32` count. +pub const lanes_shift_right: u32 = 27; +pub const lanes_bits: u32 = 28; #! The `u32` of the lanes the mask `a` has set. +pub const lanes_splat: u32 = 29; #! The lane `a` points at, in every lane. +pub const lanes_copy: u32 = 30; #! The lanes `a` points at, as they are, which moves them whole. +pub const lanes_pack: u32 = 31; #! (a, b, ...): the vector of these lanes, lane 0 first, as merging stores makes it. +pub const lanes_sum: u32 = 32; #! The lanes added together, lane 0 first, as one of the lane's type. +pub const lanes_product: u32 = 33; #! The lanes multiplied together, lane 0 first. +pub const lanes_smallest: u32 = 34; #! The least lane. +pub const lanes_largest: u32 = 35; #! The greatest lane. +pub const lanes_round: u32 = 36; #! Each real lane rounded to the nearest integer, halves away from zero. +pub const lanes_shuffle: u32 = 37; #! (a, b): `a`'s lanes in the order the bytes of `b` name, read as 16 bytes, one past the last stopping the program. +pub const lanes_convert: u32 = 38; #! `a`'s lanes, each as the type of lane above the operation's number converts it, as many. +pub const lanes_low: u32 = 39; #! The first half of `a`'s 32 bytes. +pub const lanes_high: u32 = 40; #! The second half. +pub const lanes_join: u32 = 41; #! (a, b): `a`'s 16 bytes, then `b`'s. +pub const lanes_widen: u32 = 42; #! The first half of `a`'s lanes, each as the type above the number, twice as wide. +pub const lanes_widen_high: u32 = 43; #! The second half so. +pub const lanes_narrow: u32 = 44; #! (a, b): `a`'s lanes, then `b`'s, each as the type above the number, half as wide, saturated. +pub const lanes_gather: u32 = 45; #! (a, b): the lanes the address `a` is, at the 32-bit places `b`'s lanes name. + +#! The bytes the type of lane above an operation's number takes, which the +#! operations giving lanes of another type are numbered with. +#! @param operation The operation, as `lanes_apply` is given it. +#! @returns The type of lane. +pub def lanes_target(operation: u32): u32 { + return (operation >> 8) & 0xFF; +} + +#! The types of lane, as the instructions take them: signed and unsigned +#! integers of each width, then the reals. +pub const lane_i8: u32 = 0; +pub const lane_u8: u32 = 1; +pub const lane_i16: u32 = 2; +pub const lane_u16: u32 = 3; +pub const lane_i32: u32 = 4; +pub const lane_u32: u32 = 5; +pub const lane_i64: u32 = 6; +pub const lane_u64: u32 = 7; +pub const lane_f32: u32 = 8; +pub const lane_f64: u32 = 9; +#! What no instruction takes. +pub const lane_none: u32 = 10; + +#! The bits of a lane of a type. +#! @param lane The type of lane. +#! @returns Its bits. +pub def lane_bits(lane: u32): u64 { + return lane == lane_f32 ? 32 : lane == lane_f64 ? 64 : 8u << (lane / 2) as u64; +} + +#! Whether a type of lane is a signed integer. +#! @param lane The type of lane. +#! @returns Whether it is. +pub def lane_signed(lane: u32): bool { + return lane < lane_f32 && lane % 2 == 0; +} + +#! The instruction sets an operation on lanes needs, of 16, 32, or 64 bytes, or +#! of one real alone, one bit each as the executable keeps them, or `cpu_never` +#! where none work it. +#! +#! Of 16 bytes, SSE2 has most: arithmetic but integer division, bitwise +#! operations of any lanes, comparisons, square roots, splatting a lane, and the +#! least and greatest of reals, made IEEE 754's with more instructions; products +#! of 32 and 64 bits, from `pmuludq`'s of 32 bits into 64; shifts of bytes, +#! through those of 16 bits and a mask; and the absolute values and `>>` of +#! 64-bit integers, through their signs. SSSE3 adds integers' absolute values, +#! SSE4.1 rounding reals and the least and greatest of more integers, and SSE4.2 +#! comparing 64-bit integers, so their least and greatest. FMA fuses multiplying +#! and adding. 32 bytes take AVX's forms: of reals, and what only moves bits, AVX's, +#! and of integers AVX2's. One real alone, as `std::math` works its rounding and +#! `fma` of one number, takes the instruction of one number, which needs the same, +#! and splats nothing. 64 bytes take AVX-512's, as `avx512_needs` says. +#! @param operation The operation, as std numbers them. +#! @param lane The type of lane. +#! @param bytes The bytes of the vector. +#! @returns The sets. +pub def lanes_needs(operation: u32, lane: u32, bytes: u64): u64 { + return cpu_never if lane >= lane_none; + if (operation & 0xFF) >= lanes_convert { + return reshape_needs(operation & 0xFF, lane, lanes_target(operation), bytes); + } + val real := lane >= lane_f32; + val bits := lane_bits(lane); + val signed := lane_signed(lane); + if bytes == bits / 8 { + return cpu_never if !real; + return cpu_fma if operation == lanes_fma; + return cpu_sse41 if operation >= lanes_floor && operation <= lanes_round_even; + return cpu_sse2 if operation == lanes_sqrt; + return cpu_never; + } + return avx512_needs(operation, lane) if bytes == 64; + return cpu_never if bytes != 16 && bytes != 32; + + var need := cpu_never; + if operation == lanes_add || operation == lanes_sub || operation == lanes_negate || operation == lanes_select { + need = cpu_sse2; + } else if operation == lanes_mul { + need = cpu_sse2; + } else if operation == lanes_div || operation == lanes_sqrt { + need = real ? cpu_sse2 : cpu_never; + } else if operation == lanes_and || operation == lanes_or || operation == lanes_xor || operation == lanes_not { + # Of any lanes, as a mask's are combined. + need = cpu_sse2; + } else if operation == lanes_min || operation == lanes_max { + need = real || lane == lane_i16 || lane == lane_u8 ? cpu_sse2 : bits == 64 ? cpu_sse42 : cpu_sse41; + } else if operation == lanes_abs { + need = real || !signed || bits == 64 ? cpu_sse2 : cpu_ssse3; + } else if operation == lanes_floor || operation == lanes_ceil || operation == lanes_trunc || operation == lanes_round_even { + need = real ? cpu_sse41 : cpu_never; + } else if operation == lanes_equal || operation == lanes_not_equal { + need = real || bits < 64 ? cpu_sse2 : cpu_sse41; + } else if operation == lanes_less || operation == lanes_less_equal || operation == lanes_greater + || operation == lanes_greater_equal { + need = real || bits < 64 ? cpu_sse2 : cpu_sse42; + } else if operation == lanes_fma { + need = real ? cpu_fma : cpu_never; + } else if operation == lanes_shift_left || operation == lanes_shift_right { + need = real ? cpu_never : cpu_sse2; + } else if operation == lanes_bits { + # A mask of 16-bit lanes is packed into bytes first, which 32 bytes would do + # within each half of the register, so those are taken a half at a time. + need = bits == 16 && bytes == 32 ? cpu_never : cpu_sse2; + } else if operation == lanes_splat || operation == lanes_copy { + need = cpu_sse2; + } else if operation == lanes_sum { + # Integers added in any order, and reals a lane at a time, lane 0 first. + need = cpu_sse2; + } else if operation == lanes_product { + need = real ? cpu_sse2 : cpu_never; + } else if operation == lanes_smallest || operation == lanes_largest { + # Of integers, as their least and greatest; reals' order is kept, which the + # registers left do not hold. + need = real ? cpu_never : lane == lane_i16 || lane == lane_u8 ? cpu_sse2 : bits == 64 ? cpu_sse42 : cpu_sse41; + } else if operation == lanes_round { + need = real ? cpu_sse41 : cpu_never; + } else if operation == lanes_shuffle { + # Bytes chosen by SSSE3's `pshufb`, and 32 bytes of 32- and 64-bit lanes by + # AVX2's `vpermd`, which crosses the halves `vpshufb` keeps apart. + need = bytes == 16 ? cpu_ssse3 : bits >= 32 ? cpu_sse41 : cpu_never; + } + return need if need == cpu_never || bytes == 16; + + val moves_bits := operation == lanes_select || (operation == lanes_abs && !signed) + || (operation == lanes_bits && bits != 8) || operation == lanes_splat || operation == lanes_copy; + return need | (real || moves_bits ? cpu_avx : cpu_avx2); +} + +#! The instruction sets an operation on 64 bytes of lanes needs: AVX-512's, +#! for arithmetic but integer division, bitwise operations, comparisons, choosing +#! lanes, splatting one, a mask's bits, and of reals square roots, rounding, and +#! `fma`; of integers their least, greatest, and absolute values, and shifts. +#! Moving them is SSE2's. The rest, and every operation of bytes, whose mask's +#! bits would not fit a `u32`, `simd` works a half or a quarter at a time. +#! @param operation The operation, as std numbers them. +#! @param lane The type of lane. +#! @returns The sets. +def avx512_needs(operation: u32, lane: u32): u64 { + return cpu_sse2 if operation == lanes_copy; + return cpu_never if lane_bits(lane) == 8; + val real := lane >= lane_f32; + if operation <= lanes_not || (operation >= lanes_equal && operation <= lanes_select) || operation == lanes_bits + || operation == lanes_splat { + return operation == lanes_div && !real ? cpu_never : cpu_avx512; + } + if operation == lanes_min || operation == lanes_max || operation == lanes_shift_left || operation == lanes_shift_right { + return real ? cpu_never : cpu_avx512; + } + if operation == lanes_sqrt || (operation >= lanes_floor && operation <= lanes_round_even) || operation == lanes_fma { + return real ? cpu_avx512 : cpu_never; + } + return operation == lanes_abs ? cpu_avx512 : cpu_never; +} + +#! The instruction sets the operations giving lanes of another type or size +#! need: `lanes_needs` of those, of `lane` lanes in `bytes` making `target` lanes. +#! Halves of 32 bytes are AVX's to take apart and join, as are reals' widening +#! and narrowing between `f32` and `f64`, of 32 bytes. Integers widen by +#! SSE4.1's `pmovsx` and `pmovzx`, narrow by its `pack`s, and of 32 bytes by +#! AVX2's; `i32` becomes `f32` by SSE2's `cvtdq2ps`, and `u32` by two halves of +#! 16 bits; and a real becomes a 32-bit integer by `cvttps2dq` or `cvttpd2dq`, +#! which `simd`'s `convert` asks only of lanes within `i32`'s range, where it is +#! exact. Gathering 32 and 64-bit lanes at 32-bit places is AVX2's. +def reshape_needs(operation: u32, lane: u32, target: u32, bytes: u64): u64 { + val real := lane >= lane_f32; + val bits := lane_bits(lane); + if operation == lanes_low || operation == lanes_high { + return bytes == 32 ? cpu_sse2 | cpu_avx : cpu_never; + } + if operation == lanes_join { + return bytes == 16 ? cpu_sse2 | cpu_avx : cpu_never; + } + if operation == lanes_gather { + return lane_bits(lane) >= 32 && (bytes / (bits / 8) == 4 || (bits == 32 && bytes == 32)) ? cpu_sse2 | cpu_avx | cpu_avx2 : cpu_never; + } + return cpu_never if target >= lane_none || (bytes != 16 && bytes != 32); + val into_real := target >= lane_f32; + val into_bits := lane_bits(target); + val wide: u64 = bytes == 32 ? cpu_avx | cpu_avx2 : 0; + if operation == lanes_widen || operation == lanes_widen_high { + return cpu_never if into_bits != 2 * bits; + return cpu_sse2 | (bytes == 32 ? cpu_avx : 0) if real && into_real; + return cpu_sse41 | wide if !real && !into_real; + return cpu_never; + } + if operation == lanes_narrow { + return cpu_never if 2 * into_bits != bits || real != into_real || bits == 64 && !real; + return cpu_sse2 | (bytes == 32 ? cpu_avx : 0) if real; + # Signed lanes pack by SSE2's but into `u16`, and unsigned ones are held at + # the type's greatest by SSE4.1's least of unsigned lanes first. + val plain := lane_signed(lane) && (bits == 16 || lane_signed(target)); + return (plain ? cpu_sse2 : cpu_sse41) | wide; + } + # Converting each lane, as many. + val into_bytes := bytes / (bits / 8) * (into_bits / 8); + return cpu_never if into_bytes != 16 && into_bytes != 32; + if !real && !into_real { + return cpu_sse2 | (bytes == 32 ? cpu_avx : 0) if into_bits == bits; + return cpu_sse41 | (into_bytes == 32 ? cpu_avx | cpu_avx2 : 0) if into_bits > bits; + return cpu_ssse3 | cpu_avx | cpu_avx2 if bytes == 32 && 2 * into_bits == bits; + return cpu_never; + } + if !real && into_real { + return cpu_never if bits == 64 || (target == lane_f64 && bits != 32); + return cpu_sse2 | cpu_avx if target == lane_f64; + return cpu_never if bits != 32 && into_bytes == 16; + return cpu_sse41 | cpu_avx | cpu_avx2 if bits < 32; + return cpu_sse2 | (bytes == 32 ? cpu_avx | (lane == lane_u32 ? cpu_avx2 : 0) : 0); + } + if real && !into_real { + # Toward zero, of lanes `simd`'s `convert` finds within `i32`'s range. + return cpu_never if into_bits != 32; + return cpu_sse2 | (bytes == 32 ? cpu_avx : 0) if lane == lane_f32; + return cpu_sse2 | cpu_avx; + } + return cpu_sse2 | (bytes == 32 || into_bytes == 32 ? cpu_avx : 0); +} + +#! How many operands an operation on lanes takes: the vectors, and for a shift +#! the count, and for `lanes_splat` the lane. +#! @param operation The operation. +#! @returns How many. +pub def lanes_operands(operation: u32): u32 { + return 3 if operation == lanes_select || operation == lanes_fma; + val base := operation & 0xFF; + return 2 if base == lanes_join || base == lanes_narrow || base == lanes_gather; + return 1 if operation == lanes_negate || operation == lanes_not || operation == lanes_bits || operation == lanes_splat + || operation == lanes_copy || (operation >= lanes_abs && operation <= lanes_round_even) + || (operation >= lanes_sum && operation <= lanes_round) || base >= lanes_convert; + return 2; +} + +#! How the result of an operation on lanes is written where `lanes_apply` is +#! given it: as the vector, as a `u32` of a mask's bits, or as the lane's type, +#! of one lane alone or of the lanes worked together. +#! @param operation The operation. +#! @param lane The type of lane. +#! @param bytes The bytes of the vector. +#! @returns The access. +pub def lanes_result_access(operation: u32, lane: u32, bytes: u64): access { + return access::u32 if operation == lanes_bits; + val base := operation & 0xFF; + if base == lanes_low || base == lanes_high { + return access::v128; + } + if base == lanes_join { + return access::v256; + } + if base == lanes_convert { + val made := bytes / (lane_bits(lane) / 8) * (lane_bits(lanes_target(operation)) / 8); + return made == 32 ? access::v256 : access::v128; + } + if bytes < 16 || (operation >= lanes_sum && operation <= lanes_largest) { + return lanes_operand_access(lanes_splat, lane, bytes, 0); + } + return vector_access(bytes); +} + +#! How a vector of so many bytes is read and written whole. +#! @param bytes 16, 32, or 64. +#! @returns The access. +pub def vector_access(bytes: u64): access { + return bytes == 64 ? access::v512 : bytes == 32 ? access::v256 : access::v128; +} + +#! How an operand of an operation on lanes is read from where `lanes_apply` is +#! given it: as the vector, or for a shift's count a `u32`, or for +#! `lanes_splat`'s lane, and every operand of one lane alone, as the lane's type. +#! @param operation The operation. +#! @param lane The type of lane. +#! @param bytes The bytes of the vector. +#! @param k Which operand. +#! @returns The access. +pub def lanes_operand_access(operation: u32, lane: u32, bytes: u64, k: u32): access { + if operation == lanes_splat { + return match lane { + lane_i8 => access::i8, + lane_u8 => access::u8, + lane_i16 => access::i16, + lane_u16 => access::u16, + lane_i32 => access::i32, + lane_u32 => access::u32, + lane_f32 => access::f32, + lane_f64 => access::f64, + else => access::i64 + }; + } + return access::u32 if k == 1 && (operation == lanes_shift_left || operation == lanes_shift_right); + return access::v128 if k == 1 && operation == lanes_shuffle; + if (operation & 0xFF) == lanes_gather { + return access::i64 if k == 0; + return bytes / (lane_bits(lane) / 8) == 8 ? access::v256 : access::v128; + } + return (lane == lane_f32 ? access::f32 : access::f64) if bytes == lane_bits(lane) / 8; + return vector_access(bytes); +} diff --git a/compiler/layouts.sakura b/compiler/layouts.sakura new file mode 100644 index 00000000..8eab68fa --- /dev/null +++ b/compiler/layouts.sakura @@ -0,0 +1,503 @@ +#! @file layouts.sakura +#! @author John Christman (sorakatadzuma@gmail.com) +#! @copyright Malunal Studios, LLC. +#! @license MIT +#! +#! Contains the layouts of types, as the C compiler's `compiler__make_layout` +#! makes them: scalars aligned to their size, as C aligns them, so a struct is +#! laid out as C lays out one of the same fields, a union as its tag and then +#! its largest field, and each with a map of the words that may hold a heap +#! object. Also contains the signatures calls pass arguments by, and how many +#! words a value of each layout is as a value of the intermediate code. + +import sakura::analyzer; +module sakura::compiler; + + +#! The type a value is laid out as: what its aliases stand for, and what a +#! constant settles as where nothing converts it. +#! @param this The compiler. +#! @param kind The type. +#! @returns The type laid out. +pub def lowerer::layout_type(&mut this, kind: u32): u32 { + var at := this.checker.unalias(kind); + if this.checker.types.is_untyped(at) { + at = this.checker.unalias(this.checker.settle(at)); + } + return at; +} + +#! The layout of a type, made where it is new. +#! @param this The compiler. +#! @param kind The type. +#! @returns The layout's index. +pub def lowerer::layout_of(&mut this, kind: u32): u32 { + val plain := this.layout_type(kind); + if this.layout_ids.get(&plain) is some(got) { + return got; + } + return this.make_layout(plain); +} + +#! A copy of a layout, which stays as it is however the layouts grow. +#! @param this The compiler. +#! @param index The layout's index. +#! @returns The layout. +pub def lowerer::layout_at(&this, index: u32): layout { + return this.program.layouts[index]; +} + +#! The layout of a type's values: what kind it is, its size, and the rest. +#! @param this The compiler. +#! @param kind The type. +#! @returns A copy of the layout. +pub def lowerer::shape_of(&mut this, kind: u32): layout { + val index := this.layout_of(kind); + return this.program.layouts[index]; +} + +#! A field of a layout, by its position. +#! @param this The compiler. +#! @param index The layout's index. +#! @param at The field's position. +#! @returns A copy of the field. +pub def lowerer::field_at(&this, index: u32, at: u32): slot_field { + val first: u32 = this.program.layouts[index].fields; + return this.program.fields[first as u64 + at as u64]; +} + +#! Makes the layout of a type not yet laid out. It is registered before its +#! parts are laid out, so a type referring to itself through a reference or a +#! pointer finds it. +#! @param this The compiler. +#! @param kind The type, as `layout_type` gives it. +#! @returns The layout's index. +def lowerer::make_layout(&mut this, kind: u32): u32 { + this.laying++; + val index := this.program.layouts.length as u32; + this.program.layouts.append(layout { type_id = kind, align = 1, how = access::bytes }); + this.layout_ids.set(kind, index); + + var made := layout { type_id = kind, align = 1, how = access::bytes }; + var parts := vector::::new(); + match this.checker.types.kind_of(kind) { + ty::boolean, ty::untyped_bool => { + made.kind = lk::boolean; + made.bits = 8; + made.size = 1; + made.how = access::u8; + } + ty::signed, ty::unsigned => this.integer_layout(&mut made, this.checker.types.kind_of(kind) == ty::signed, + this.checker.types.first_of(kind)); + ty::floating => { + val bits := this.checker.types.first_of(kind); + made.kind = lk::floating; + made.bits = bits; + made.size = bits <= 32 ? 4 : 8; + made.align = made.size; + made.how = bits <= 32 ? access::f32 : access::f64; + } + ty::reference, ty::null_type => { + val referent := this.checker.types.kind_of(kind) == ty::reference ? this.checker.types.first_of(kind) : 0; + val traited := referent != 0 && this.checker.named_kind(this.checker.unalias(referent)) == dk::trait_type; + made.kind = traited ? lk::trait_reference : lk::reference; + made.size = traited ? 2 * word_size : word_size; + made.align = word_size; + made.how = traited ? access::bytes : access::i64; + } + ty::pointer => this.pointer_layout(&mut made); + ty::fixed => { + val element := this.layout_of(this.checker.types.first_of(kind)); + val inner := this.layout_at(element); + made.kind = lk::fixed; + made.element = element + 1; + made.count = this.checker.types.part_count(kind) == 0 ? this.checker.types.second_of(kind) : 0; + made.align = inner.align; + made.size = inner.size * made.count as u64; + } + ty::function => { + made.kind = lk::function; + made.size = 2 * word_size; + made.align = word_size; + } + ty::named => this.named_layout(kind, &mut made, &mut parts); + else => {} + } + + # A view is written as the elements it views, and a view of bytes, like the + # string that owns them, as the text itself. Both keep where the elements + # begin in a pointer field, with how many there are in the field after it. + if made.kind == lk::record && parts.length >= 2 { + val viewed := this.viewed(kind); + val element: u32 = viewed != 0 ? this.layout_of(viewed) + 1 : 0; + var bytes := this.is_string(kind); + if element != 0 { + val inner := this.layout_at(element - 1); + bytes = bytes || (inner.size == 1 && inner.kind != lk::record); + } + for i in 0..parts.length - 1 { + break if !bytes && element == 0; + continue if this.layout_at(parts[i].layout).kind != lk::pointer; + made.texts = bytes; + made.views = !bytes; + made.viewed = bytes ? 0 : element; + made.text = i as u32; + break; + } + } + + made.size = round_up(made.size, made.align); + val scalar := made.kind == lk::signed || made.kind == lk::unsigned || made.kind == lk::floating + || made.kind == lk::boolean || made.kind == lk::pointer; + made.frame = scalar ? word_size : round_up(made.size, word_size); + + # Each part is kept in a run of its own, after whatever laying out the parts + # made. + made.fields = this.program.fields.length as u32; + made.count = made.kind == lk::fixed ? made.count : parts.length as u32; + for &each in parts { + this.program.fields.append(each); + } + this.note_references(&mut made, parts.view()); + + # A reference or pointer is laid out without what it refers to, which may be a + # type still being laid out, or one holding a type that is, as `node` holds + # the `maybe<&node>` whose `&node` reaches it. So that comes once the outermost + # layout is made, where every size is known. + this.program.layouts[index] = made; + val held := this.checker.types.kind_of(kind); + if (held == ty::reference && made.kind == lk::reference) || held == ty::pointer { + this.referents.append(index); + this.referents.append(this.checker.types.first_of(kind)); + } + this.laying--; + if this.laying == 0 { + this.laying = 1; + var at: u64 = 0; + while at < this.referents.length { + val reaching: u32 = this.referents[at]; + val element := this.layout_of(this.referents[at + 1]); + this.program.layouts[reaching].element = element + 1; + at += 2; + } + this.referents.clear(); + this.laying = 0; + } + return index; +} + +#! Lays out an integer of the bits, aligned to its size as C aligns it. +#! @param this The compiler. +#! @param made The layout being made. +#! @param signed Whether it is signed. +#! @param bits Its bits. +def lowerer::integer_layout(&mut this, made: &mut layout, signed: bool, bits: u32): void { + made.kind = signed ? lk::signed : lk::unsigned; + made.bits = bits; + made.size = bits <= 8 ? 1 : bits <= 16 ? 2 : bits <= 32 ? 4 : 8; + made.align = made.size; + made.how = match made.size { + 1 => signed ? access::i8 : access::u8, + 2 => signed ? access::i16 : access::u16, + 4 => signed ? access::i32 : access::u32, + else => access::i64 + }; +} + +#! Lays out a pointer, an address the program follows itself, as the address +#! of a C function is too. +#! @param this The compiler. +#! @param made The layout being made. +def lowerer::pointer_layout(&mut this, made: &mut layout): void { + made.kind = lk::pointer; + made.size = word_size; + made.align = word_size; + made.how = access::i64; +} + +#! Lays out a named type: a struct, a union, an enum, or the address of a C +#! function. +#! @param this The compiler. +#! @param kind The type. +#! @param made The layout being made. +#! @param parts Where its fields are written. +def lowerer::named_layout(&mut this, kind: u32, made: &mut layout, parts: &mut vector): void { + val decl: u32 = this.checker.types.first_of(kind); + if this.checker.is_std(kind, word::cfn) { + this.pointer_layout(made); + return; + } + + match this.checker.decls.kinds.p[decl] { + dk::enum_type => { + # An enum is laid out as its integer, naming each member as a field whose + # offset is its value. + val integer := this.layout_at(this.layout_of(this.checker.enum_integer(kind))); + made.kind = integer.kind; + made.bits = integer.bits; + made.size = integer.size; + made.align = integer.align; + made.how = integer.how; + made.name = this.checker.decls.names.p[decl]; + val run: u32 = this.checker.decls.children.p[decl]; + for i in 0..this.checker.decls.list_length(run) { + val member := this.checker.decls.list_at(run, i as u32); + var value := constant {}; + this.checker.decl_value(member, &mut value); + parts.append(slot_field { + name = this.checker.decls.names.p[member], + offset = value.bits(), + decl = member + }); + } + } + dk::struct_type, dk::union_type => { + # An instance of a generic is named with its arguments, as `pair`. + made.name = this.checker.decls.names.p[decl]; + if this.checker.types.part_count(kind) != 0 { + val named := this.checker.describe(kind); + made.name = this.checker.names.intern(&named.view()); + } + val run: u32 = this.checker.decls.children.p[decl]; + for i in 0..this.checker.decls.list_length(run) { + val field := this.checker.decls.list_at(run, i as u32); + continue if this.checker.decls.kinds.p[field] != dk::field; + this.checker.resolve(field); + val held := this.checker.instantiated(this.checker.decls.types.p[field], decl, kind); + parts.append(slot_field { + name = this.checker.decls.names.p[field], + layout = this.layout_of(held), + type_id = held, + decl = field, + spread = this.checker.is_spread(field) + }); + } + + val is_union := this.checker.decls.kinds.p[decl] == dk::union_type; + if is_union && this.checker.decls.has(decl, df::foreign) { + # Every field of a C union begins where it does, as an `extern module` lays it out. + made.kind = lk::record; + for &each in parts { + val inner := this.layout_at(each.layout); + made.size = inner.size > made.size ? inner.size : made.size; + made.align = inner.align > made.align ? inner.align : made.align; + } + return; + } + if !is_union { + made.kind = lk::record; + var offset: u64 = 0; + for i in 0..parts.length { + val inner := this.layout_at(parts[i].layout); + offset = round_up(offset, inner.align); + parts[i].offset = offset; + offset += inner.size; + made.align = inner.align > made.align ? inner.align : made.align; + } + made.size = offset; + return; + } + + # A union of an empty field and a reference, a trait reference, a + # function value, or a struct of one of them alone, none of which is ever + # null, holds no tag: it holds the empty field where its first word is + # null, as `none` of `maybe<&T>` and `maybe>`. + made.kind = lk::variant; + if parts.length == 2 { + val first := this.layout_at(parts[0].layout); + val second := this.layout_at(parts[1].layout); + var held: u32 = 0; + if first.size == 0 && this.never_null(&second) { + held = 2; + } else if second.size == 0 && this.never_null(&first) { + held = 1; + } + if held != 0 { + val payload := this.layout_at(parts[held - 1].layout); + made.niche = held; + made.size = payload.size; + made.align = payload.align; + parts[0].offset = 0; + parts[1].offset = 0; + return; + } + } + + # Every field of a union is the payload after the tag, which is its index. + made.align = word_size; + var payload: u64 = 0; + for i in 0..parts.length { + val inner := this.layout_at(parts[i].layout); + parts[i].offset = word_size; + payload = inner.size > payload ? inner.size : payload; + made.align = inner.align > made.align ? inner.align : made.align; + } + made.size = word_size + payload; + } + else => {} + } +} + +#! Notes whether a layout may hold a reference: as a reference, a trait +#! reference, or a function value, which holds its environment, or as what +#! holds one by value. +#! @param this The compiler. +#! @param made The layout being made. +#! @param parts Its fields. +def lowerer::note_references(&mut this, made: &mut layout, parts: span): void { + match made.kind { + lk::reference, lk::trait_reference, lk::function => made.pointers = true; + lk::fixed => { + if made.element != 0 { + made.pointers = this.layout_at(made.element - 1).pointers; + } + } + lk::record, lk::variant => { + for &each in parts { + if each.layout != 0 && this.layout_at(each.layout).pointers { + made.pointers = true; + } + } + } + else => {} + } +} + +#! The elements a view of std views, or 0 for anything else: both the read-only +#! `span` and the writable `slice` are views, and hold the same two words. +#! @param this The compiler. +#! @param kind The type. +#! @returns The type of the elements, or 0. +pub def lowerer::viewed(&mut this, kind: u32): u32 { + val plain := this.checker.unalias(kind); + if this.checker.is_std(plain, word::span) || this.checker.is_std(plain, word::slice) { + return this.checker.types.part_count(plain) != 0 ? this.checker.types.part_at(plain, 0) : 0; + } + return 0; +} + +#! Whether a type is std's `string`, which owns the text it holds. +#! @param this The compiler. +#! @param kind The type. +#! @returns Whether it is. +pub def lowerer::is_string(&mut this, kind: u32): bool { + return this.checker.is_std(this.checker.unalias(kind), word::string); +} + +#! The field a union holds, by its index, given the first word of its value: +#! its tag, or of a union laid out without one, the field laid out where the +#! word is not null, and the empty one where it is. +#! @param held The union's layout. +#! @param first The first word of its value. +#! @returns The field's index. +pub def held_field(held: &layout, first: u64): u64 { + return first if held.niche == 0; + val laid: u64 = held.niche as u64 - 1; + return first != 0 ? laid : 1 - laid; +} + +#! Whether a value of the layout is never null in its first word: a reference, a +#! trait reference, a function value, or a struct whose one field is one, as +#! `box`, which a union holding it beside an empty field takes as its tag. +#! @param this The compiler. +#! @param held The layout. +#! @returns Whether it is. +pub def lowerer::never_null(&mut this, held: &layout): bool { + if held.kind == lk::record && held.count == 1 { + val field: slot_field = this.program.fields[held.fields as u64]; + val inner := this.layout_at(field.layout); + return field.offset == 0 && inner.size == held.size && this.never_null(&inner); + } + return held.kind == lk::reference || held.kind == lk::trait_reference || held.kind == lk::function; +} + +#! Whether a value of the layout is held in memory, at an address, rather than +#! as words: a fixed array, a struct, or a union. +#! @param held The layout. +#! @returns Whether it is. +pub def in_memory(held: &layout): bool { + return held.kind == lk::fixed || held.kind == lk::record || held.kind == lk::variant; +} + +#! Whether a function giving a value of the layout returns it in memory, at an +#! address its call gives: one held in memory that has bytes. A struct of no +#! fields is returned as nothing. +#! @param held The layout. +#! @returns Whether it is. +pub def returned_in_memory(held: &layout): bool { + return in_memory(held) && held.size != 0; +} + +#! How many words a value of the layout is, as a value of the code: none for +#! `void` and what is held in memory. +#! @param held The layout. +#! @returns How many. +pub def word_count(held: &layout): u32 { + return match held.kind { + lk::empty, lk::fixed, lk::record, lk::variant => 0, + lk::reference => 1, + lk::trait_reference, lk::function => 2, + else => 1 + }; +} + +#! The type of a word of a value of the layout, as a value of the code. +#! @param held The layout. +#! @returns A real for a float, and a word for anything else. +pub def word_type(held: &layout): vt { + return held.kind == lk::floating ? vt::real : vt::word; +} + +#! The signature of calls through a function type: the layout of each of its +#! parameters, where each begins, and its result's layout. +#! @param this The compiler. +#! @param kind The function type. +#! @returns The signature's index. +pub def lowerer::signature_of(&mut this, kind: u32): u32 { + val plain := this.checker.unalias(kind); + if this.signature_ids.get(&plain) is some(got) { + return got; + } + + var params := vector::::new(); + var offsets := vector::::new(); + var size: u64 = 0; + for i in 0..this.checker.types.part_count(plain) { + val each := this.layout_of(this.checker.types.part_at(plain, i as u32)); + params.append(each); + offsets.append(size); + size += this.layout_at(each).frame; + } + val result := this.layout_of(this.checker.types.first_of(plain)); + + val index := this.program.signatures.length as u32; + this.program.signatures.append(signature { + params = move(&mut params), + offsets = move(&mut offsets), + size = size, + result = result + }); + this.signature_ids.set(plain, index); + return index; +} + +#! The types of the values the code of a function of the signature takes: the +#! words of each parameter, or the address of one held in memory. +#! @param this The compiler. +#! @param index The signature. +#! @returns The types. +pub def lowerer::param_types(&this, index: u32): vector { + var made := vector::::new(); + val held := &this.program.signatures[index]; + for &each in held.params { + val shape := this.layout_at(each); + if in_memory(&shape) { + made.append(vt::word); + continue; + } + for _ in 0..word_count(&shape) { + made.append(word_type(&shape)); + } + } + return made; +} diff --git a/compiler/nodes.sakura b/compiler/nodes.sakura new file mode 100644 index 00000000..b62a91da --- /dev/null +++ b/compiler/nodes.sakura @@ -0,0 +1,64 @@ +#! @file nodes.sakura +#! @author John Christman (sorakatadzuma@gmail.com) +#! @copyright Malunal Studios, LLC. +#! @license MIT +#! +#! Contains the walk of a node of the syntax tree and the nodes under it, which +#! the scans lowering makes of what a body names share. + +import sakura::analyzer; +module sakura::compiler; + + +#! A walk of a node of the syntax tree and the nodes under it, each before the +#! nodes it holds. The walk goes under a node only where it is asked to, so a +#! scan may pass over what a node holds, or go under only some of it. +pub struct node_walk { + var todo: vector; #! The nodes yet to be given, the next last, 0 standing for one absent. +} + +#! Walks a node and the nodes under it. +#! @param node The node, or 0 for none. +#! @returns The walk. +pub def node_walk::new(node: u32): node_walk { + var made := node_walk { todo = vector::::new() }; + made.todo.append(node); + return made; +} + +#! Whether the walk has another node to give, passing over those absent. +#! @param this The walk. +#! @returns Whether it has. +pub def node_walk::more(&mut this): bool { + # It answers from within the loop, which keeps it small enough to be inlined. + while this.todo.length != 0 { + return true if this.todo.last() != 0; + this.todo.truncate(); + } + return false; +} + +#! Gives the next node, once `more` says there is one. +#! @param this The walk. +#! @returns The node. +pub def node_walk::next(&mut this): u32 { + val at: u32 = this.todo.last(); + this.todo.truncate(); + return at; +} + +#! Goes under a node: the nodes it holds are given next, the last its shape +#! lists first. +#! @param this The walk. +#! @param tree The syntax tree. +#! @param node The node. +pub def node_walk::enter(&mut this, tree: &syntax, node: u32): void { + tree.children(node, &mut this.todo); +} + +#! Goes under a node to one node it holds only, which is given next. +#! @param this The walk. +#! @param node The node held, or 0 for none. +pub def node_walk::add(&mut this, node: u32): void { + this.todo.append(node); +} diff --git a/compiler/optimizer/alias.sakura b/compiler/optimizer/alias.sakura new file mode 100644 index 00000000..0cc66049 --- /dev/null +++ b/compiler/optimizer/alias.sakura @@ -0,0 +1,393 @@ +#! @file alias.sakura +#! @author John Christman (sorakatadzuma@gmail.com) +#! @copyright Malunal Studios, LLC. +#! @license MIT +#! +#! Contains alias analysis, which the passes of the optimizer ask whether an +#! instruction writing memory may write what a read reads, or what they know +#! memory holds. An access touches a region: bytes from a base, which its +#! address steps from by constants, as `add`s of constants and the steps loads +#! and stores take give them. An address stepping by what is not known from one +#! within a cell, the globals, a datum, or memory made, as indexing an array +#! does, is anywhere within the same. +#! +#! Two regions may hold a byte in common but where it is known they do not. +#! Regions of one base, of one cell, or both of the globals, do not where their +#! bytes do not overlap, and two cells do not. A cell that is not escaped, its +#! address going nowhere but to the instructions reading, writing, copying, and +#! clearing it, and to calls as where to write what they return, as the memory +#! pass finds, is touched by nothing reaching through another address, nor by +#! a call, or anything else writing memory the code does not name, but where it +#! writes what it returns. No cell is what an address the function was given, +#! the globals, or the heap holds, none of which is the frame. Memory a `box` or +#! `allocate` made is not what an address the function was given, the globals, +#! other memory made so, or an address read before it was made holds, as none +#! could point at what was not yet there. And nothing writes a datum. +#! +#! Sakura has no rule that memory of one type is not read or written as +#! another: std and the runtime reach through pointers cast to other types, as +#! `float_bits` is written as an `f64` and read as a `u64`, and loads and stores say only how they read and +#! write, not what they reach. So no region is told apart from another by the +#! type of what it holds. + +module sakura::compiler; + + +#! What the base of a region is. +pub enum base_kind : u8 { + other, #! A value nothing more is known of. + cell, #! The address of a cell of the frame. + global, #! The start of the globals, a global's address stepping from it. + datum, #! The address of a datum, which nothing writes. + fresh, #! The address of memory a `box` or `allocate` made. + given, #! A parameter of the entry: an address the function was given. + loaded, #! An address read from memory. +} + +#! What a region's size is where it is not known. +pub const unknown_size: u64 = 0xFFFFFFFFFFFFFFFF; + +#! The bytes an access touches: a base, how far past it they begin, and how +#! many there are. +pub struct region { + pub var base: u32; #! The value the address steps from by constants. + pub var offset: u64; #! How far past the base the bytes begin, wrapping as addresses do; for a global, past the start of the globals. + pub var size: u64; #! How many bytes, or `unknown_size`. + pub var kind: base_kind; #! What the base is. + pub var cell: u32; #! The cell, where the base is a cell's address. +} + +#! What alias analysis knows of code: which cell each value is the address +#! of, which cells are escaped, the bytes each call writes what it returns to, +#! and which block dominates which, where that is known. +pub struct aliases { + var addresses: cell_table; #! Which cell each value is the address of. + var escaped: vector; #! Whether each cell is escaped. + var writes: vector; #! Of each instruction, the bytes a call writes what it returns to at its last operand, or 0. + var idom: vector; #! The immediate dominator of each block, or nothing where it is not known. + var found: bool; #! Whether which cells are escaped is found. +} + +#! Finds what alias analysis knows of the code. +#! @param this The code. +#! @param writes Of each instruction, the bytes a call writes what it returns +#! to at its last operand, or 0. +#! @param idom The immediate dominator of each block, or nothing, where +#! memory made after an address was read is not told apart +#! from what it points at, but within a block. +#! @returns What it knows, in scratch memory. +pub def code::aliases(&this, writes: span, idom: span): aliases { + var made := this.aliases_unfound(writes, idom); + made.find_escaped(this); + return made; +} + +#! Begins what alias analysis knows of the code, but for which cells are +#! escaped, which `aliases::find_escaped` finds before anything asks whether +#! one region may hold a byte of another, and before anything changes which +#! cells are escaped. +#! @param this The code. +#! @param writes Of each instruction, the bytes a call writes what it returns +#! to at its last operand, or 0. +#! @param idom The immediate dominator of each block, or nothing. +#! @returns What it knows, in scratch memory. +pub def code::aliases_unfound(&this, writes: span, idom: span): aliases { + var made := aliases { + escaped = vector::::new(scratch()), + writes = vector::::new(scratch()), + idom = vector::::new(scratch()) + }; + made.writes.extend(writes); + made.idom.extend(idom); + return made; +} + +#! Finds which cells are escaped, where that is not found yet. +#! @param this What alias analysis knows. +#! @param body The code. +pub def aliases::find_escaped(&mut this, body: &code): void { + return if this.found; + this.found = true; + this.addresses = body.cell_table(); + this.escaped = body.escaped_cells(&this.addresses, this.writes.view()); +} + +#! Which cells are escaped: their address goes anywhere but to the instructions +#! reading, writing, copying, and clearing them, to `ret`, or to a call as +#! where to write what it returns. +#! @param this The code. +#! @param addresses Which cell each value is the address of. +#! @param writes Of each instruction, the bytes a call writes what it +#! returns to at its last operand, or 0. +#! @returns Whether each cell is, in scratch memory. +pub def code::escaped_cells(&this, addresses: &cell_table, writes: span): vector { + var escaped := vector::::new(scratch()); + escaped.resize(this.cells.length); + return escaped if !addresses.any; + var walk := this.walk_all(); + var reads := this.reader(); + while walk.more() { + val at := walk.next(); + val held := &this.insts[at]; + reads.start(at); + while reads.more() { + val cell := addresses.cell(reads.next()); + continue if cell == 0; + # A cell's address an edge gives escapes. + val i := reads.operand(); + val direct := i != no_operand && match held.kind { + op::load, op::store, op::clear => i == 0, + op::copy => i < 2, + op::ret => true, + else => i + 1 == held.argc && (at as u64) < writes.length && writes[at] != 0 + }; + if !direct { + escaped[cell - 1] = true; + } + } + } + return escaped; +} + +#! The region an access touches. +#! @param this What alias analysis knows. +#! @param body The code. +#! @param index The `load`, `store`, `copy`, or `clear`. +#! @param operand Which address: of a `copy`, 0 for where it writes, 1 for +#! where it reads. +#! @returns The region. +pub def aliases::region_of(&this, body: &code, index: u32, operand: u32): region { + val held: inst = body.insts[index]; + if held.kind == op::load || held.kind == op::store { + val how: access = held.aux as access; + return this.region_at(body, body.arg(index, 0), held.imm, how == access::bytes ? unknown_size : how.width()); + } + return this.region_at(body, body.arg(index, operand), 0, held.imm); +} + +#! The region of bytes past an address. +#! @param this What alias analysis knows. +#! @param body The code. +#! @param address The address. +#! @param offset How far past it the bytes begin. +#! @param size How many there are, or `unknown_size`. +#! @returns The region. +pub def aliases::region_at(&this, body: &code, address: u32, offset: u64, size: u64): region { + var made := region { offset = offset, size = size }; + this.find_base(body, address, &mut made, 0); + return made; +} + +#! Finds the base of a region at an address, and how far past it the address +#! is, adding that to the region's offset. An address stepping by what is not +#! known from one within a cell, the globals, a datum, or memory made, and from +#! nothing else such, is somewhere within the same, as indexing an array is, +#! so the region is any of it. +#! @param this What alias analysis knows. +#! @param body The code. +#! @param address The address. +#! @param made The region. +#! @param depth How many such steps were followed to the address. +def aliases::find_base(&this, body: &code, address: u32, made: &mut region, depth: u32): void { + var at := address; + var steps := 0; + while steps < 8 { + val index := body.defining(at); + break if index == 0 || body.insts[index].kind != op::add; + var step: u64 = 0; + if body.word_constant(body.arg(index, 1), &mut step) { + at = body.arg(index, 0); + } else if body.word_constant(body.arg(index, 0), &mut step) { + at = body.arg(index, 1); + } else { + break if depth >= 2; + var one := region {}; + var two := region {}; + this.find_base(body, body.arg(index, 0), &mut one, depth + 1); + this.find_base(body, body.arg(index, 1), &mut two, depth + 1); + break if one.within_object() == two.within_object(); + val inside: region = one.within_object() ? one : two; + made.base = inside.base; + made.kind = inside.kind; + made.cell = inside.cell; + made.offset = 0; + made.size = unknown_size; + return; + } + made.offset = made.offset + step; + steps++; + } + made.base = at; + val held: origin = body.origins[at]; + if held.param { + made.kind = held.from == 0 ? base_kind::given : base_kind::other; + return; + } + val from: inst = body.insts[held.from]; + match from.kind { + op::cell => { + made.kind = base_kind::cell; + made.cell = from.aux; + } + op::global => { + made.kind = base_kind::global; + made.offset = made.offset + from.imm; + } + op::datum => made.kind = base_kind::datum; + op::allocate => made.kind = base_kind::fresh; + op::load => made.kind = base_kind::loaded; + else => made.kind = base_kind::other; + } +} + +#! Whether a region's base is within a cell, the globals, a datum, or memory +#! made, which a number never is. +#! @param this The region. +#! @returns Whether it is. +def region::within_object(&this): bool { + return match this.kind { + base_kind::cell, base_kind::global, base_kind::datum, base_kind::fresh => true, + else => false + }; +} + +#! Whether two regions may hold a byte in common, as the file says. +#! @param this What alias analysis knows. +#! @param body The code. +#! @param a One region. +#! @param b The other. +#! @returns Whether they may. +pub def aliases::may_alias(&this, body: &code, a: ®ion, b: ®ion): bool { + return false if a.size == 0 || b.size == 0; + return false if a.kind == base_kind::datum || b.kind == base_kind::datum; + if a.kind == base_kind::cell && b.kind == base_kind::cell { + return a.cell == b.cell && overlaps(a, b); + } + if a.kind == base_kind::cell { + return this.escaped[a.cell] && !b.outside_frame(); + } + if b.kind == base_kind::cell { + return this.escaped[b.cell] && !a.outside_frame(); + } + if a.kind == base_kind::global && b.kind == base_kind::global { + return overlaps(a, b); + } + return overlaps(a, b) if a.base == b.base; + if a.kind == base_kind::fresh { + return this.may_point_at(body, b, a.base); + } + if b.kind == base_kind::fresh { + return this.may_point_at(body, a, b.base); + } + return true; +} + +#! Whether a region may hold bytes of memory a `box` or `allocate` made, its +#! base being other than that memory's address. +#! @param this What alias analysis knows. +#! @param body The code. +#! @param other The region. +#! @param fresh The address of the memory made. +#! @returns Whether it may. +def aliases::may_point_at(&this, body: &code, other: ®ion, fresh: u32): bool { + return match other.kind { + base_kind::fresh, base_kind::given, base_kind::global => false, + base_kind::loaded => !this.read_before(body, other.base, fresh), + else => true + }; +} + +#! Whether an address was read before memory was made, wherever both are +#! known: the read is before the `box` or `allocate` in its block, or in a +#! block dominating its block. +#! @param this What alias analysis knows. +#! @param body The code. +#! @param loaded The address read. +#! @param fresh The address of the memory made. +#! @returns Whether it was. +def aliases::read_before(&this, body: &code, loaded: u32, fresh: u32): bool { + val read := body.defining(loaded); + val made := body.defining(fresh); + val at: u32 = body.insts[read].block; + val home: u32 = body.insts[made].block; + if at == home { + var walk := body.walk(at); + while walk.more() { + val each := walk.next(); + return true if each == read; + return false if each == made; + } + return false; + } + return (home as u64) < this.idom.length && dominates(&this.idom, at, home); +} + +#! Whether the bytes of two regions of one base overlap. +#! @param a One region. +#! @param b The other. +#! @returns Whether they do. +def overlaps(a: ®ion, b: ®ion): bool { + return b.offset - a.offset < a.size || a.offset - b.offset < b.size; +} + +#! Whether a region is outside the frame, so within no cell: the globals, the +#! heap, or what an address the function was given points at. +#! @param this The region. +#! @returns Whether it is. +def region::outside_frame(&this): bool { + return this.kind == base_kind::global || this.kind == base_kind::fresh || this.kind == base_kind::given; +} + +#! What an instruction writes, as alias analysis tells it. +pub struct writing { + pub var place: region; #! The region a store, copy, or clear writes, or that a call writes what it returns to, or none of no bytes. + pub var wide: bool; #! Whether it may write any memory but an unescaped cell's, as a call does. +} + +#! What an instruction writes: a store, copy, or clear its region; a call or +#! anything else writing memory the code does not name any but an unescaped +#! cell's, and where it writes what it returns; and anything else nothing. +#! @param this What alias analysis knows. +#! @param body The code. +#! @param index The instruction. +#! @returns What it writes. +pub def aliases::writes_of(&this, body: &code, index: u32): writing { + val held: inst = body.insts[index]; + var made := writing {}; + if held.kind == op::store || held.kind == op::clear || held.kind == op::copy { + made.place = this.region_of(body, index, 0); + return made; + } + return made if held.kind == op::load || (held.kind.traits() & op_write) == 0; + made.wide = true; + val result: u64 = (index as u64) < this.writes.length ? this.writes[index] : 0; + if result != 0 { + made.place = this.region_at(body, body.arg(index, held.argc - 1), 0, result); + } + return made; +} + +#! Whether what an instruction writes may hold a byte of a region. +#! @param this What alias analysis knows. +#! @param body The code. +#! @param written What the instruction writes. +#! @param place The region. +#! @returns Whether it may. +pub def aliases::touches(&this, body: &code, written: &writing, place: ®ion): bool { + if written.wide { + return false if place.kind == base_kind::datum; + return true if place.kind != base_kind::cell || this.escaped[place.cell]; + } + return this.may_alias(body, &written.place, place); +} + +#! Whether an instruction may write a byte of a region. +#! @param this What alias analysis knows. +#! @param body The code. +#! @param index The instruction. +#! @param place The region. +#! @returns Whether it may. +pub def aliases::clobbers(&this, body: &code, index: u32, place: ®ion): bool { + val written := this.writes_of(body, index); + return this.touches(body, &written, place); +} diff --git a/compiler/optimizer/control.sakura b/compiler/optimizer/control.sakura new file mode 100644 index 00000000..e8b267fb --- /dev/null +++ b/compiler/optimizer/control.sakura @@ -0,0 +1,1224 @@ +#! @file control.sakura +#! @author John Christman (sorakatadzuma@gmail.com) +#! @copyright Malunal Studios, LLC. +#! @license MIT +#! +#! Contains the third pass of the optimizer, which cleans up how control flows: +#! a `branch` or `switch` on a constant goes the one way it goes, as a `jump`; +#! a block nothing reaches goes; a block only one `jump` goes to is merged into +#! the block jumping; an edge into a block that only jumps on goes straight to +#! where that block goes; and an edge giving a block constants that the block +#! works out its branch from goes straight to where the branch goes for them, +#! as the constants `&&` and `||` join on do, and the flag a `for` loop's +#! cursor gives, what the block makes that is read past it reaching what reads +#! it as parameters of the successor it goes to. A chain of branches testing +#! one word against constants, as a `match` or `if`s comparing it are, becomes +#! one `switch`. A branch going to one block both ways becomes a `jump` giving +#! it a `select` of each argument the ways give differently, and the blocks of +#! a small diamond or triangle that only work out cheap values are worked out +#! before the branch, which then goes to where they join both ways. Then the +#! parameters standing for one value go, as building the code takes them out. + +module sakura::compiler; + + +#! Cleans up how control flows, as the file says, until nothing more changes. +#! @param this The code. +#! @returns Whether anything changed. +pub def code::clean_control(&mut this): bool { + # Code of one block has nowhere to go but out of the function. + var live: u64 = 0; + for b in 0..this.blocks.length { + if !this.blocks[b].gone { + live++; + } + } + return false if live <= 1; + + var changed := false; + var settled := false; + var rounds := 0; + while rounds < 8 { + rounds++; + var again := this.fold_branches(); + this.drop_unreached(); + again = this.merge_blocks() || again; + # How many times each value is read, where sending edges on past blocks + # that only jump on worked it out and sent none. + var uses := vector::::new(scratch()); + again = this.thread_jumps(&mut uses) || again; + again = this.thread_known(&mut uses) || again; + again = this.form_switches() || again; + again = this.form_selects() || again; + settled = !again; + break if settled; + changed = true; + } + # A round that changed nothing took out what the entry does not reach. + if !settled { + this.drop_unreached(); + } + val params := this.param_count(); + this.drop_lone_params(); + return changed || this.param_count() != params; +} + +#! How many parameters the blocks take, but for the entry's. +#! @param this The code. +#! @returns How many. +def code::param_count(&this): u64 { + var count: u64 = 0; + for b in 1..this.blocks.length { + if !this.blocks[b].gone { + count += this.blocks[b].params.length; + } + } + return count; +} + +#! Makes each `branch` and `switch` whose way is known a `jump`: one on a +#! constant, and a `branch` going the same way with the same arguments either +#! way. +#! @param this The code. +#! @returns Whether any changed. +def code::fold_branches(&mut this): bool { + var changed := false; + for b in 0..this.blocks.length { + continue if this.blocks[b].gone; + val last: u32 = this.blocks[b].last; + continue if last == 0; + val held: inst = this.insts[last]; + if held.kind == op::branch { + var bits: u64 = 0; + if this.word_constant(this.arg(last, 0), &mut bits) { + this.jump_only(last, bits != 0 ? held.aux : held.aux + 1); + changed = true; + continue; + } + val one: u32 = held.aux; + if this.edges[one].target == this.edges[one + 1].target + && this.edges[one].args.same(&this.edges[one + 1].args) { + this.jump_only(last, one); + changed = true; + } + continue; + } + if held.kind == op::switch { + var bits: u64 = 0; + continue if !this.word_constant(this.arg(last, 0), &mut bits); + val count := held.imm as u32; + var chosen := held.aux + count - 1; + for e in 0..count - 1 { + if this.edges[held.aux + e as u32].case == bits { + chosen = held.aux + e as u32; + break; + } + } + this.jump_only(last, chosen); + changed = true; + } + } + return changed; +} + + +#! Merges each block only one `jump` goes to into the block jumping, its +#! parameters read as the arguments the jump gives. +#! @param this The code. +#! @returns Whether any merged. +def code::merge_blocks(&mut this): bool { + var done := rewrite::new(); + for b in 1..this.blocks.length { + continue if this.blocks[b].gone || this.blocks[b].preds.length != 1; + val edge: u32 = this.blocks[b].preds[0]; + val jump: u32 = this.edges[edge].from; + continue if this.insts[jump].kind != op::jump; + val into: u32 = this.insts[jump].block; + continue if into == b as u32 || this.blocks[into].gone; + + for i in 0..this.blocks[b].params.length { + done.replace(this.blocks[b].params[i], this.edges[edge].args[i]); + } + + # The jump goes, and the block's instructions follow what came before it. + val before := this.before(jump); + val first: u32 = this.blocks[b].first; + if before == 0 { + this.blocks[into].first = first; + } else { + this.insts[before].next = first; + } + this.blocks[into].last = this.blocks[b].last; + var moved := this.walk(b as u32); + while moved.more() { + this.insts[moved.next()].block = into; + } + # What was bound where the block began is bound where its code now does. + for i in 0..this.bindings.length { + continue if this.bindings[i].block != b as u32; + this.bindings[i].block = into; + if this.bindings[i].after == 0 { + this.bindings[i].after = before; + } + } + this.blocks[b].first = 0; + this.blocks[b].last = 0; + this.blocks[b].gone = true; + this.blocks[b].preds.clear(); + this.blocks[b].params.clear(); + this.forget_order(); + done.changed = true; + } + this.apply(&done); + return done.changed; +} + +#! Sends each edge into a block that only jumps on straight to where it jumps, +#! where nothing but that jump reads what the block takes. +#! @param this The code. +#! @param uses Where how many times each value is read is written, where +#! that is asked; it is left empty where an edge was sent on. +#! @returns Whether any edge was sent on. +def code::thread_jumps(&mut this, uses: &mut vector): bool { + var changed := false; + for b in 1..this.blocks.length { + continue if this.blocks[b].gone; + val only: u32 = this.blocks[b].first; + continue if only == 0 || only != this.blocks[b].last || this.insts[only].kind != op::jump; + val out: u32 = this.insts[only].aux; + val target: u32 = this.edges[out].target; + continue if target == b as u32; + if uses.length == 0 && this.blocks[b].params.length != 0 { + uses = this.use_counts(); + } + continue if this.blocks[b].params.length != 0 && !this.reads_params_only_leaving(b as u32, uses); + + var preds := this.blocks[b].preds.copied(scratch()); + for &edge in preds { + continue if this.edge_source(edge) == b as u32; + this.send_on(edge, b as u32, out); + changed = true; + } + } + if changed { + uses.clear(); + } + return changed; +} + +#! Whether the parameters of a block are read nowhere but by its last +#! instruction, and as arguments of the edges leaving it. +#! @param this The code. +#! @param block The block. +#! @param uses How many times each value is read. +#! @returns Whether they are. +def code::reads_params_only_leaving(&this, block: u32, uses: &vector): bool { + val last: u32 = this.blocks[block].last; + for ¶m in this.blocks[block].params { + var here: u32 = 0; + var reads := this.reads_of(last); + while reads.more() { + if reads.next() == param { + here++; + } + } + return false if uses[param] != here; + } + return true; +} + +#! Sends an edge into a block on along an edge leaving that block, giving the +#! block's parameters the edge's arguments where the edge leaving gives them. +#! @param this The code. +#! @param edge The edge sent on. +#! @param block The block it went to. +#! @param out The edge it goes on along. +def code::send_on(&mut this, edge: u32, block: u32, out: u32): void { + var args := ids {}; + for &each in this.edges[out].args { + val held: origin = this.origins[each]; + if held.param && held.from == block { + args.append(this.edges[edge].args[held.index]); + } else { + args.append(each); + } + } + this.drop_pred(edge); + val target: u32 = this.edges[out].target; + this.edges[edge].target = target; + this.edges[edge].args = move(&mut args); + this.blocks[target].preds.append(edge); +} + +# Threading through known ways. + +#! The most instructions a block may hold before its `branch` or `switch` for +#! edges into it to be sent on past it, as its way is worked out for each. +const thread_limit: u32 = 16; + +#! What `code::known_way` gives where the way a block goes is not known. +const no_way: u32 = 0xFFFFFFFF; + +#! A word an instruction of a block gives along an edge into the block, as the +#! constants the edge gives say it. +struct known_word { + var value: u32; #! The instruction's result. + var bits: u64; #! The word. +} + +#! The tree of which block dominates which, as sending edges on past blocks +#! asks it, worked out again once edges have changed, from the order and +#! dominators the code keeps where it keeps them. +struct dom_tree { + var order: vector; #! The blocks the entry reaches, in reverse postorder. + var number: vector; #! Each block's place in that order. + var idom: vector; #! The immediate dominator of each block. + var first: vector; #! The first block each block immediately dominates, or `no_block`. + var after: vector; #! The next block the immediate dominator of each immediately dominates, or `no_block`. + var stale: bool; #! Whether edges changed since it was worked out. +} + +#! Makes a tree not yet worked out. +#! @returns The tree. +def dom_tree::new(): dom_tree { + return dom_tree { + order = vector::::new(scratch()), + number = vector::::new(scratch()), + idom = vector::::new(scratch()), + first = vector::::new(scratch()), + after = vector::::new(scratch()), + stale = true + }; +} + +#! Works the tree out again where edges changed since it was. +#! @param this The tree. +#! @param body The code. +def dom_tree::refresh(&mut this, body: &mut code): void { + return if !this.stale; + this.stale = false; + body.block_order(&mut this.order, &mut this.number); + this.idom = body.block_dominators(); + this.first.clear(); + this.after.clear(); + this.first.resize(body.blocks.length, no_block); + this.after.resize(body.blocks.length, no_block); + var k := this.order.length; + while k > 1 { + k--; + val block: u32 = this.order[k]; + val parent: u32 = this.idom[block]; + this.after[block] = this.first[parent]; + this.first[parent] = block; + } +} + +#! The blocks a block dominates, itself first. +#! @param this The tree. +#! @param root The block. +#! @param into Where the blocks are written. +def dom_tree::region(&this, root: u32, into: &mut vector): void { + into.clear(); + into.append(root); + var i: u64 = 0; + while i < into.length { + var child: u32 = this.first[into[i]]; + while child != no_block { + into.append(child); + child = this.after[child]; + } + i++; + } +} + +#! Sends each edge giving a block constants that the block works out its way +#! from straight to where the block goes for them. A block of nothing but a +#! branch on a parameter that nothing else reads needs nothing more; otherwise +#! `thread_through` has what the block makes reach what reads it past it. +#! @param this The code. +#! @param uses How many times each value is read, where that is known as +#! the code is now, or empty. +#! @returns Whether any edge was sent on. +def code::thread_known(&mut this, uses: &mut vector): bool { + var tree := dom_tree::new(); + var changed := false; + for b in 1..this.blocks.length { + continue if this.blocks[b].gone; + val last: u32 = this.blocks[b].last; + continue if last == 0; + val kind := this.insts[last].kind; + continue if (kind != op::branch && kind != op::switch) || !this.decides_alone(b as u32); + + if this.blocks[b].first == last && this.origins[this.arg(last, 0)].param { + if uses.length == 0 { + uses = this.use_counts(); + } + if this.reads_params_only_leaving(b as u32, uses) { + if this.thread_alone(b as u32) { + changed = true; + tree.stale = true; + } + continue; + } + } + if this.thread_through(b as u32, &mut tree) { + changed = true; + tree.stale = true; + uses.clear(); + } + } + return changed; +} + +#! Whether a block works out its way alone: what it holds before its `branch` +#! or `switch` only works out values, at most `thread_limit` of them, and what +#! it branches on is its own, a parameter or a value it works out. +#! @param this The code. +#! @param block The block, which ends in a `branch` or `switch`. +#! @returns Whether it does. +def code::decides_alone(&this, block: u32): bool { + val last: u32 = this.blocks[block].last; + return false if this.home_of(this.arg(last, 0)) != block; + var count: u32 = 0; + var walk := this.walk(block); + while walk.more() { + val at := walk.next(); + break if at == last; + count++; + return false if count > thread_limit || this.insts[at].count != 1 || (this.insts[at].kind.traits() & op_pure) == 0; + } + return true; +} + +#! Where a block's `branch` or `switch` goes for an edge into it, working out +#! what it can of the block's instructions from the constants the edge gives. +#! @param this The code. +#! @param block The block, which works out its way alone. +#! @param edge The edge. +#! @param made Where each word worked out is written. +#! @returns The edge the block leaves by, or `no_way` where it is not known. +def code::known_way(&this, block: u32, edge: u32, made: &mut vector): u32 { + made.clear(); + val last: u32 = this.blocks[block].last; + var walk := this.walk(block); + while walk.more() { + val at := walk.next(); + break if at == last; + var bits: u64 = 0; + if this.fold_along(at, block, edge, made, &mut bits) { + made.append(known_word { value = this.insts[at].result, bits = bits }); + } + } + var bits: u64 = 0; + return no_way if !this.known_along(block, edge, this.arg(last, 0), made, &mut bits); + val first: u32 = this.insts[last].aux; + if this.insts[last].kind == op::branch { + return bits != 0 ? first : first + 1; + } + val count := this.insts[last].imm as u32; + for e in 0..count - 1 { + return first + e as u32 if this.edges[first + e as u32].case == bits; + } + return first + count - 1; +} + +#! The constant a word is along an edge into a block: of a parameter, the +#! constant the edge gives it, and of what the block works out, what is worked +#! out so far. +#! @param this The code. +#! @param block The block. +#! @param edge The edge. +#! @param value The word. +#! @param made The words of the block worked out so far. +#! @param bits Where the constant is written, where it is known. +#! @returns Whether it is known. +def code::known_along(&this, block: u32, edge: u32, value: u32, made: &vector, bits: &mut u64): bool { + val held: origin = this.origins[value]; + if held.param && held.from == block { + return this.word_constant(this.edges[edge].args[held.index], bits); + } + if !held.param && this.insts[held.from].block == block { + for &each in made { + if each.value == value { + bits = each.bits; + return true; + } + } + return false; + } + return this.word_constant(value, bits); +} + +#! Works out the word an instruction of a block gives along an edge into the +#! block, where the constants it is worked out from are known. +#! @param this The code. +#! @param index The instruction. +#! @param block The block. +#! @param edge The edge. +#! @param made The words of the block worked out so far. +#! @param bits Where the word is written, where it is known. +#! @returns Whether it is known. +def code::fold_along(&this, index: u32, block: u32, edge: u32, made: &vector, bits: &mut u64): bool { + val held: inst = this.insts[index]; + return false if held.count != 1 || this.origins[held.result].kind != vt::word; + if held.kind == op::iconst { + bits = held.imm; + return true; + } + var x: u64 = 0; + return false if held.argc == 0 || !this.known_along(block, edge, this.arg(index, 0), made, &mut x); + if held.kind == op::select { + return this.known_along(block, edge, this.arg(index, x != 0 ? 1 : 2), made, bits); + } + val number := held.kind as u32; + if number >= op::add as u32 && number <= op::leus as u32 { + var y: u64 = 0; + return this.known_along(block, edge, this.arg(index, 1), made, &mut y) && fold_word(held.kind, x, y, bits); + } + match held.kind { + op::wrap => { + bits = wrap_word(x, held.aux, held.imm != 0); + return true; + } + op::neg, op::bnot, op::lnot, op::ones, op::clz, op::ctz, op::bswap => return fold_unary(held.kind, x, bits); + else => return false; + } + return false; +} + +#! Sends each edge into a block whose constants say where the block's branch +#! goes straight there, for a block of nothing but a branch on a parameter +#! that nothing else reads. +#! @param this The code. +#! @param block The block. +#! @returns Whether any edge was sent on. +def code::thread_alone(&mut this, block: u32): bool { + var made := vector::::new(scratch()); + var changed := false; + var preds := this.blocks[block].preds.copied(scratch()); + for &edge in preds { + continue if this.edge_source(edge) == block; + val out := this.known_way(block, edge, &mut made); + continue if out == no_way || this.edges[out].target == block; + this.send_on(edge, block, out); + changed = true; + } + return changed; +} + +#! Sends each edge into a block whose constants say where the block goes +#! straight there, where what the block makes that is read past it can reach +#! what reads it. Each value read within what a successor taking an edge sent +#! on dominates becomes a parameter of the successor, which the block's edge +#! gives it as the value, and each edge sent on as what the value is along +#! that edge: the argument the edge gave the block, or a constant the block +#! works out. A constant the block makes is made again where the successor +#! begins instead. Where a value is read past the block but within no +#! successor only the block goes to, no edge is sent on. +#! @param this The code. +#! @param block The block, which works out its way alone. +#! @param tree Which block dominates which, worked out again where stale. +#! @returns Whether any edge was sent on. +def code::thread_through(&mut this, block: u32, tree: &mut dom_tree): bool { + # The edges whose constants say where the block goes, each with its way. + var made := vector::::new(scratch()); + var found := vector::::new(scratch()); + var preds := this.blocks[block].preds.copied(scratch()); + for &edge in preds { + continue if this.edge_source(edge) == block; + val out := this.known_way(block, edge, &mut made); + continue if out == no_way || this.edges[out].target == block; + found.append(pair_key(edge, out)); + } + return false if found.length == 0; + tree.refresh(this); + var needs := vector::::new(scratch()); + return false if !this.reads_beyond(block, tree, &mut needs); + + # A block heading a loop, which an edge from within what it dominates goes + # back to, keeps each edge from outside that would go on into the loop, which + # would enter the loop past its head. + var looped := vector::::new(scratch()); + for &edge in preds { + if dominates(&tree.idom, block, this.edge_source(edge)) { + looped = this.loop_of(block, tree); + break; + } + } + + # An edge goes on only where each value its way needs is known along it. + var sent := vector::::new(scratch()); + for &pair in found { + val edge := pair_high(pair); + val out := pair_low(pair); + val target: u32 = this.edges[out].target; + continue if looped.length != 0 && looped[target] && !dominates(&tree.idom, block, this.edge_source(edge)); + this.known_way(block, edge, &mut made); + var known := true; + for &each in this.edges[out].args.view() { + known = known && this.maps_along(block, edge, each, &made); + } + for &need in needs { + if pair_high(need) == target { + known = known && this.maps_along(block, edge, pair_low(need), &made); + } + } + if known { + sent.append(pair); + } + } + return false if sent.length == 0; + + # Each successor an edge goes on to takes what it needs: a constant made again + # where it begins, or a parameter, which the block's edge gives as the value. + var region := vector::::new(scratch()); + for &need in needs { + val target := pair_high(need); + val value := pair_low(need); + var taken := false; + for &pair in sent { + taken = taken || this.edges[pair_low(pair)].target == target; + } + continue if !taken; + var stands: u32 = 0; + val from := this.defining(value); + if from != 0 && (this.insts[from].kind == op::iconst || this.insts[from].kind == op::fconst) { + val held: inst = this.insts[from]; + var gives: vt[1] = [this.type_of(value)]; + val copy := this.detached(held.kind, span::::empty(), gives[0:1], 0, held.imm, held.at, held.site); + this.put_first(target, copy); + stands = this.insts[copy].result; + } else { + stands = this.add_param(target, this.type_of(value)); + val into: u32 = this.blocks[target].preds[0]; + this.edges[into].args.append(value); + } + tree.region(target, &mut region); + this.replace_within(region.view(), value, stands); + } + + # Each edge goes on, giving what each value its way gives is along it. + for &pair in sent { + val edge := pair_high(pair); + val out := pair_low(pair); + this.known_way(block, edge, &mut made); + var given := this.edges[out].args.copied(scratch()); + var args := ids {}; + for &each in given { + args.append(this.mapped_along(block, edge, each, &made)); + } + this.drop_pred(edge); + val target: u32 = this.edges[out].target; + this.edges[edge].target = target; + this.edges[edge].args = move(&mut args); + this.blocks[target].preds.append(edge); + } + return true; +} + +#! Finds what a block makes that is read past it, which is within what the +#! block dominates: each read must be within what a successor only the block +#! goes to dominates, which the successor would need were edges to go to it +#! without the block. +#! @param this The code. +#! @param block The block. +#! @param tree Which block dominates which. +#! @param needs Where each successor and value read within what it dominates +#! is written, as `pair_key` packs them, each once. +#! @returns Whether every read past the block is within such a successor's. +def code::reads_beyond(&this, block: u32, tree: &dom_tree, needs: &mut vector): bool { + needs.clear(); + var region := vector::::new(scratch()); + var reads := this.reader(); + var child: u32 = tree.first[block]; + while child != no_block { + val preds := &this.blocks[child].preds; + val alone := preds.length == 1 && this.edge_source(preds[0]) == block; + tree.region(child, &mut region); + for &each in region { + var walk := this.walk(each); + while walk.more() { + reads.start(walk.next()); + while reads.more() { + val value := reads.next(); + continue if this.home_of(value) != block; + return false if !alone; + val key := pair_key(child, value); + if !needs.view().contains(&key) { + needs.append(key); + } + } + } + } + child = tree.after[child]; + } + return true; +} + +#! The blocks of the loop a block heads: those it dominates from which an edge +#! back to it is reached through blocks it dominates, and itself. +#! @param this The code. +#! @param block The block. +#! @param tree Which block dominates which. +#! @returns Whether each block is within the loop. +def code::loop_of(&this, block: u32, tree: &dom_tree): vector { + var looped := vector::::new(scratch()); + looped.resize(this.blocks.length); + looped[block] = true; + var todo := vector::::new(scratch()); + for &edge in this.blocks[block].preds { + todo.append(this.edge_source(edge)); + } + while todo.length != 0 { + val at: u32 = todo.last(); + todo.truncate(); + continue if looped[at] || !dominates(&tree.idom, block, at); + looped[at] = true; + for &edge in this.blocks[at].preds { + todo.append(this.edge_source(edge)); + } + } + return looped; +} + +#! Whether a value an edge sent on past a block needs is known along the edge: +#! one the block does not make, a parameter of the block, a constant it makes, +#! a word it works out from the constants the edge gives, or a `select` whose +#! choice they say, of what is known. +#! @param this The code. +#! @param block The block. +#! @param edge The edge. +#! @param value The value. +#! @param made The words of the block worked out along the edge. +#! @returns Whether it is. +def code::maps_along(&this, block: u32, edge: u32, value: u32, made: &vector): bool { + val held: origin = this.origins[value]; + return true if held.param || this.insts[held.from].block != block; + val kind := this.insts[held.from].kind; + return true if kind == op::iconst || kind == op::fconst; + var bits: u64 = 0; + return true if this.known_along(block, edge, value, made, &mut bits); + return false if kind != op::select || !this.known_along(block, edge, this.arg(held.from, 0), made, &mut bits); + return this.maps_along(block, edge, this.arg(held.from, bits != 0 ? 1 : 2), made); +} + +#! What a value is along an edge into a block, sent on past the block: of a +#! parameter, the argument the edge gave it, of what the block works out, the +#! constant it is, of a `select` whose choice is known, what it chooses there, +#! and otherwise the value itself. +#! @param this The code. +#! @param block The block. +#! @param edge The edge. +#! @param value The value, which `maps_along` says is known. +#! @param made The words of the block worked out along the edge. +#! @returns The value along the edge. +def code::mapped_along(&mut this, block: u32, edge: u32, value: u32, made: &vector): u32 { + val held: origin = this.origins[value]; + if held.param { + return value if held.from != block; + val given: u32 = this.edges[edge].args[held.index]; + return given; + } + val from: inst = this.insts[held.from]; + return value if from.block != block; + return this.real_value(from.imm) if from.kind == op::fconst; + var bits: u64 = 0; + return this.word_value(bits) if this.known_along(block, edge, value, made, &mut bits); + this.known_along(block, edge, this.arg(held.from, 0), made, &mut bits); + return this.mapped_along(block, edge, this.arg(held.from, bits != 0 ? 1 : 2), made); +} + +#! Makes each read of a value within some blocks read another instead: by their +#! instructions, the edges leaving them, and the variables bound in them. +#! @param this The code. +#! @param blocks The blocks. +#! @param from The value read. +#! @param to The value read instead. +def code::replace_within(&mut this, blocks: span, from: u32, to: u32): void { + var inside := vector::::new(scratch()); + inside.resize(this.blocks.length); + for &block in blocks { + inside[block] = true; + var walk := this.walk(block); + while walk.more() { + val at := walk.next(); + val held: inst = this.insts[at]; + for i in 0..held.argc { + val slot := held.args as u64 + i as u64; + if this.operands[slot] == from { + this.operands[slot] = to; + } + } + var outs := this.edges_of(at); + while outs.more() { + val args := this.edges[outs.next()].args.slice(); + for a in 0..args.length { + if args[a] == from { + args[a] = to; + } + } + } + } + } + for i in 0..this.bindings.length { + val bound: binding = this.bindings[i]; + if bound.value == from && bound.block != no_block && inside[bound.block] { + this.bindings[i].value = to; + } + } +} + + +# Switches. + +#! The fewest cases a chain of branches has for it to become a `switch`. +const switch_least: u64 = 4; + +#! A branch testing a word against a constant: the word, the constant, the +#! edge taken where the word is it, and the one taken where it is not. +struct test_step { + var subject: u32; + var case: u64; + var hit: u32; + var rest: u32; +} + +#! What a block's branch tests: a word against a constant, as `x == k`, +#! `x != k`, or `x` itself, which is the word against 0. +#! @param this The code. +#! @param block The block. +#! @param step Where what it tests is written. +#! @returns Whether it ends in such a branch. +def code::test_of(&this, block: u32, step: &mut test_step): bool { + val last: u32 = this.blocks[block].last; + return false if last == 0 || this.insts[last].kind != op::branch; + val first: u32 = this.insts[last].aux; + val cond := this.arg(last, 0); + return false if this.type_of(cond) != vt::word; + val held: origin = this.origins[cond]; + if !held.param { + val made: inst = this.insts[held.from]; + if made.kind == op::eq || made.kind == op::ne { + var bits: u64 = 0; + var subject: u32 = 0; + if this.word_constant(this.arg(held.from, 1), &mut bits) { + subject = this.arg(held.from, 0); + } else if this.word_constant(this.arg(held.from, 0), &mut bits) { + subject = this.arg(held.from, 1); + } else { + return false; + } + val equal := made.kind == op::eq; + step = test_step { subject = subject, case = bits, hit = equal ? first : first + 1, rest = equal ? first + 1 : first }; + return true; + } + } + step = test_step { subject = cond, case = 0, hit = first + 1, rest = first }; + return true; +} + +#! Whether a block is a step of a chain past its first: only the edge going on +#! from the step before goes to it, giving it nothing, and it holds nothing but +#! constants, the test of its branch, and the branch. Where how many times +#! each value is read is known, the test must be read by the branch alone. +#! @param this The code. +#! @param block The block, which ends in a branch. +#! @param from The edge going to it. +#! @param uses How many times each value is read, or nothing yet. +#! @returns Whether it is. +def code::chain_step(&this, block: u32, from: u32, uses: &vector): bool { + return false if block == 0 || this.blocks[block].preds.length != 1 || this.blocks[block].params.length != 0; + return false if this.blocks[block].preds[0] != from; + val last: u32 = this.blocks[block].last; + val cond := this.arg(last, 0); + var walk := this.walk(block); + while walk.more() { + val at := walk.next(); + break if at == last; + val held := &this.insts[at]; + val tests := held.count == 1 && held.result == cond && (uses.length == 0 || uses[cond] == 1); + return false if held.kind != op::iconst && held.kind != op::fconst && !tests; + } + return true; +} + +#! How many steps a chain has, from its first, stopping at as many as make it a +#! switch. +#! @param this The code. +#! @param first The chain's first block. +#! @param head What its first block tests. +#! @param uses How many times each value is read, or nothing yet. +#! @returns How many. +def code::chain_length(&this, first: u32, head: &test_step, uses: &vector): u64 { + var count: u64 = 1; + var step: test_step = head; + while count < switch_least { + val next: u32 = this.edges[step.rest].target; + var after := test_step {}; + break if next == first || !this.test_of(next, &mut after) || after.subject != head.subject; + break if !this.chain_step(next, step.rest, uses); + count++; + step = after; + } + return count; +} + +#! Makes each chain of branches testing one word against at least +#! `switch_least` constants one `switch` of the first, which goes where the +#! chain went for each, and where its last step went otherwise. The constants +#! its later steps make are made before the switch instead, where they stand +#! before everything that read them, and the later steps go. +#! @param this The code. +#! @returns Whether any chain became a switch. +def code::form_switches(&mut this): bool { + var uses := vector::::new(scratch()); + val none := vector::::new(scratch()); + var changed := false; + for b in 0..this.blocks.length { + continue if this.blocks[b].gone; + var head := test_step {}; + continue if !this.test_of(b as u32, &mut head) || this.type_of(head.subject) != vt::word; + + # A block a chain goes on into is part of that chain, not the first of one. + if b != 0 && this.blocks[b].preds.length == 1 { + val into: u32 = this.blocks[b].preds[0]; + var before := test_step {}; + if this.test_of(this.edge_source(into), &mut before) && before.subject == head.subject && before.rest == into { + continue; + } + } + # The steps, and the constant each goes on, the first of each. Whether a + # step's test is read elsewhere is only asked of a chain long enough. + if this.chain_length(b as u32, &head, &none) < switch_least { + continue; + } + if uses.length == 0 { + uses = this.use_counts(); + } + var cases := vector::::new(scratch()); + var hits := vector::::new(scratch()); + var steps := vector::::new(scratch()); + var step := head; + while true { + if !cases.view().contains(&step.case) { + cases.append(step.case); + hits.append(step.hit); + } + val next: u32 = this.edges[step.rest].target; + var after := test_step {}; + break if next == b as u32 || !this.test_of(next, &mut after) || after.subject != head.subject; + break if !this.chain_step(next, step.rest, &uses); + steps.append(next); + step = after; + } + continue if cases.length < switch_least; + + # The first's branch becomes the switch, its edges new. + val last: u32 = this.blocks[b].last; + val old: u32 = this.insts[last].aux; + val fallback := step.rest; + var first: u32 = 0; + for i in 0..cases.length { + val hit: u32 = hits[i]; + val made := this.add_edge(last, this.edges[hit].target, cases[i]); + this.edges[made].args = ids::copy_of(&this.edges[hit].args); + if i == 0 { + first = made; + } + } + val otherwise := this.add_edge(last, this.edges[fallback].target, 0); + this.edges[otherwise].args = ids::copy_of(&this.edges[fallback].args); + this.drop_pred(old); + this.drop_pred(old + 1); + var args: u32[1] = [head.subject]; + this.become(last, op::switch, args[0:1], first, cases.length as u64 + 1); + + # The constants of the later steps go before the switch, and the steps go. + for &block in steps { + var made := vector::::new(scratch()); + var walk := this.walk(block); + while walk.more() { + val each := walk.next(); + val kind := this.insts[each].kind; + if kind == op::iconst || kind == op::fconst { + made.append(each); + } + } + for &moved in made { + this.link_before(moved, last); + } + val ends: u32 = this.blocks[block].last; + val out: u32 = this.insts[ends].aux; + this.drop_pred(out); + this.drop_pred(out + 1); + this.blocks[block].first = 0; + this.blocks[block].last = 0; + this.blocks[block].gone = true; + this.blocks[block].preds.clear(); + } + changed = true; + } + return changed; +} + + +# Selects. + +#! The most `select`s a branch becomes, one for each argument its ways give +#! differently. +const select_limit: u32 = 4; + +#! The most instructions the blocks of a diamond or triangle may work out, but +#! for constants and addresses, which cost nothing, for them to be worked out +#! before the branch. +const arm_limit: u32 = 4; + +#! Makes each `branch` whose ways only work out cheap values a choice between +#! them, as `hoist_arms` and `form_select` say. +#! @param this The code. +#! @returns Whether any branch became one. +def code::form_selects(&mut this): bool { + var changed := false; + for b in 0..this.blocks.length { + continue if this.blocks[b].gone; + val last: u32 = this.blocks[b].last; + continue if last == 0 || this.insts[last].kind != op::branch; + this.hoist_arms(b as u32); + changed = this.form_select(b as u32) || changed; + } + return changed; +} + +#! How many `select`s a branch on a condition needs to give a block what its +#! two ways give it: one for each argument they give differently, but where +#! the way the condition is not zero gives the condition and the other zero, +#! which is the condition both ways. +#! @param this The code. +#! @param cond The condition. +#! @param one What the way the condition is not zero gives. +#! @param two What the other way gives. +#! @returns How many, or `no_way` where an argument is a vector, which no +#! `select` chooses. +def code::selects_needed(&this, cond: u32, one: span, two: span): u32 { + var count: u32 = 0; + for i in 0..one.length { + continue if one[i] == two[i] || (one[i] == cond && this.is_zero(two[i])); + return no_way if this.type_of(one[i]).lanes(); + count++; + } + return count; +} + +#! Makes a `branch` going to one block both ways, with at most `select_limit` +#! arguments given differently, a `jump` giving the block a `select` of each. +#! @param this The code. +#! @param block The block the branch ends. +#! @returns Whether it became one. +def code::form_select(&mut this, block: u32): bool { + val last: u32 = this.blocks[block].last; + val one: u32 = this.insts[last].aux; + val two := one + 1; + return false if this.edges[one].target != this.edges[two].target; + val cond := this.arg(last, 0); + val count := this.selects_needed(cond, this.edges[one].args.view(), this.edges[two].args.view()); + return false if count == no_way || count > select_limit; + val held: inst = this.insts[last]; + var args := ids {}; + for i in 0..this.edges[one].args.length { + val x: u32 = this.edges[one].args[i]; + val y: u32 = this.edges[two].args[i]; + if x == y || (x == cond && this.is_zero(y)) { + args.append(x); + continue; + } + var operands: u32[3] = [cond, x, y]; + var gives: vt[1] = [this.type_of(x)]; + val chosen := this.detached(op::select, operands[0:3], gives[0:1], 0, 0, held.at, held.site); + this.link_before(chosen, last); + args.append(this.insts[chosen].result); + } + this.edges[one].args = move(&mut args); + this.jump_only(last, one); + if count == 1 { + this.compare_late(block, cond); + } + return true; +} + +#! Moves the comparison a block works out a condition with to just before the +#! one instruction after it reading the condition, its last but one, so the +#! backend compares there for itself, as for a branch. Nothing between may +#! read the condition. +#! @param this The code. +#! @param block The block. +#! @param cond The condition. +def code::compare_late(&mut this, block: u32, cond: u32): void { + val from := this.defining(cond); + return if from == 0 || this.insts[from].block != block; + match this.insts[from].kind { + op::eq, op::ne, op::lts, op::ltu, op::les, op::leu, op::flt, op::fle => {} + else => return; + } + # The instruction reading it, and those between, which must not. + val last: u32 = this.blocks[block].last; + val reading := this.before(last); + return if reading == from; + var at: u32 = this.insts[from].next; + while at != reading { + var reads := this.reads_of(at); + while reads.more() { + return if reads.next() == cond; + } + at = this.insts[at].next; + } + val prior := this.before(from); + if prior == 0 { + this.blocks[block].first = this.insts[from].next; + } else { + this.insts[prior].next = this.insts[from].next; + } + this.link_before(from, reading); +} + +#! Works out before a branch what the blocks of a small diamond or triangle +#! after it work out: each block a way of the branch goes to, taking nothing, +#! working out only cheap values that cannot stop the program, at most +#! `arm_limit` of them in all, and jumping on to one block, which the other +#! way goes to or jumps on to too. The branch then goes to that block both +#! ways, giving it what each way gave it, where `form_select` makes it a +#! choice, and the blocks between go. A block other ways go to too may only +#! make constants, which are made again before the branch, as the constants +#! `&&` and `||` join with are, and it stays for those ways. +#! @param this The code. +#! @param block The block the branch ends. +#! @returns Whether the branch now goes to one block both ways. +def code::hoist_arms(&mut this, block: u32): bool { + val last: u32 = this.blocks[block].last; + val one: u32 = this.insts[last].aux; + val two := one + 1; + val first: u32 = this.edges[one].target; + val second: u32 = this.edges[two].target; + return false if first == second; + var cost_one: u32 = 0; + var cost_two: u32 = 0; + val join_one := this.arm_join(first, &mut cost_one); + val join_two := this.arm_join(second, &mut cost_two); + var join := no_block; + var cost: u32 = 0; + if join_one != no_block && join_one == join_two { + join = join_one; + cost = cost_one + cost_two; + } else if join_one == second { + join = second; + cost = cost_one; + } else if join_two == first { + join = first; + cost = cost_two; + } + return false if join == no_block || join == block || cost > arm_limit; + + # What each way would give the block they join at. + val gives_one := join == first ? one : this.insts[this.blocks[first].last].aux; + val gives_two := join == second ? two : this.insts[this.blocks[second].last].aux; + val count := this.selects_needed(this.arg(last, 0), this.edges[gives_one].args.view(), this.edges[gives_two].args.view()); + return false if count == no_way || count > select_limit; + + # Each arm's instructions come before the branch, and the way into it goes + # where it went, giving what it gave. + if join != first { + this.hoist_arm(first, one, last, join); + } + if join != second { + this.hoist_arm(second, two, last, join); + } + return true; +} + +#! Where a block jumps on to, where it is an arm of a diamond or triangle: it +#! takes nothing, and works out only cheap values that cannot stop the +#! program, as constants, addresses, comparisons, and arithmetic but for +#! dividing, and shifts by constants, before its `jump`, or only constants +#! where more than one way goes to it. +#! @param this The code. +#! @param arm The block. +#! @param cost Where how many it works out, but for constants and addresses, +#! is written. +#! @returns The block it jumps on to, or `no_block` where it is no arm. +def code::arm_join(&this, arm: u32, cost: &mut u32): u32 { + cost = 0; + return no_block if arm == 0 || this.blocks[arm].params.length != 0; + val shared := this.blocks[arm].preds.length != 1; + val last: u32 = this.blocks[arm].last; + return no_block if last == 0 || this.insts[last].kind != op::jump; + var bits: u64 = 0; + var walk := this.walk(arm); + while walk.more() { + val at := walk.next(); + break if at == last; + val kind := this.insts[at].kind; + continue if kind == op::iconst || kind == op::fconst; + return no_block if shared; + match kind { + op::cell, op::global, op::datum => {} + op::add, op::sub, op::mul, op::band, op::bor, op::bxor, op::eq, op::ne, op::lts, op::ltu, op::les, + op::leu, op::eqsu, op::ltsu, op::lesu, op::ltus, op::leus, op::neg, op::bnot, op::lnot, op::wrap, + op::select, op::fadd, op::fsub, op::fmul, op::fneg, op::feq, op::fne, op::flt, op::fle, op::itof, + op::fsingle => cost = cost + 1; + op::shl, op::shrs, op::shru => { + return no_block if !this.word_constant(this.arg(at, 1), &mut bits); + cost = cost + 1; + } + else => return no_block; + } + } + return this.edges[this.insts[last].aux].target; +} + +#! Moves what an arm works out before a branch, and has the way into the arm +#! go where the arm jumps on to, giving what it gave there; the arm goes. An +#! arm other ways go to too stays, its constants made again before the branch. +#! @param this The code. +#! @param arm The arm. +#! @param edge The way into it. +#! @param last The branch. +#! @param join Where the arm jumps on to. +def code::hoist_arm(&mut this, arm: u32, edge: u32, last: u32, join: u32): void { + val jump: u32 = this.blocks[arm].last; + val out: u32 = this.insts[jump].aux; + val shared := this.blocks[arm].preds.length != 1; + var args := ids::copy_of(&this.edges[out].args); + var moved := vector::::new(scratch()); + var walk := this.walk(arm); + while walk.more() { + val at := walk.next(); + if at != jump { + moved.append(at); + } + } + for &each in moved { + if !shared { + this.link_before(each, last); + continue; + } + val held: inst = this.insts[each]; + var gives: vt[1] = [this.type_of(held.result)]; + val copy := this.detached(held.kind, span::::empty(), gives[0:1], 0, held.imm, held.at, held.site); + this.link_before(copy, last); + val given := args.slice(); + for a in 0..given.length { + if given[a] == held.result { + given[a] = this.insts[copy].result; + } + } + } + this.drop_pred(edge); + this.edges[edge].target = join; + this.edges[edge].args = move(&mut args); + this.blocks[join].preds.append(edge); + return if shared; + this.drop_pred(out); + this.blocks[arm].first = 0; + this.blocks[arm].last = 0; + this.blocks[arm].gone = true; + this.blocks[arm].preds.clear(); +} diff --git a/compiler/optimizer/dead.sakura b/compiler/optimizer/dead.sakura new file mode 100644 index 00000000..3af56519 --- /dev/null +++ b/compiler/optimizer/dead.sakura @@ -0,0 +1,224 @@ +#! @file dead.sakura +#! @author John Christman (sorakatadzuma@gmail.com) +#! @copyright Malunal Studios, LLC. +#! @license MIT +#! +#! Contains the second pass of the optimizer, which takes out what nothing +#! needs: an instruction whose results nothing reads, where taking it out +#! changes nothing else, a parameter of a block that nothing reads, and a +#! cell whose address nothing takes, which leaves the frame smaller. What +#! is needed is found from what must stay, as a store or a call: what it +#! reads is needed, then what that reads in turn, and a parameter needed +#! needs the argument each edge into its block gives it. So a value carried +#! around a loop only to be carried around again goes too. + +module sakura::compiler; + + +#! Takes out what nothing needs, as the file says. +#! @param this The code. +#! @returns Whether anything changed. +pub def code::remove_dead(&mut this): bool { + var live := worklist::new(this.origins.length, scratch()); + var reached := vector::::new(scratch()); + reached.resize(this.insts.length); + + # What must stay needs what it reads, but for writes to cells nothing reads. + val read := this.read_cells(); + var walk := this.walk_all(); + while walk.more() { + val at := walk.next(); + if !this.removable(at) && !this.unread_write(at, &read) { + reached[at] = true; + this.need_operands(at, &mut live); + } + } + # The entry's parameters are what the function takes, which stay. + for &each in this.blocks[0].params { + live.push_new(each); + } + + while !live.is_empty { + val value := live.pop(); + val held: origin = this.origins[value]; + if held.param { + for &edge in this.blocks[held.from].preds { + val given: u32 = this.edges[edge].args[held.index]; + live.push_new(given); + } + continue; + } + if !reached[held.from] { + reached[held.from] = true; + this.need_operands(held.from, &mut live); + } + } + + var done := rewrite::new(); + var sweep := this.walk_all(); + while sweep.more() { + val at := sweep.next(); + if !reached[at] { + done.remove(at); + } + } + this.apply(&done); + + # Each parameter nothing needs goes, with what each edge gives it. + var changed := done.changed; + var keeps := vector::::new(scratch()); + for b in 1..this.blocks.length { + continue if this.blocks[b].gone; + keeps.clear(); + for ¶m in this.blocks[b].params.view() { + keeps.append(live.has(param)); + } + continue if !keeps.view().contains(&false); + changed = true; + this.drop_params(b as u32, keeps.view()); + } + return this.drop_cells() || changed; +} + +#! Takes out the cells whose address nothing takes, numbering those left in +#! the order they were. +#! @param this The code. +#! @returns Whether any was taken out. +def code::drop_cells(&mut this): bool { + return false if this.cells.length == 0; + var used := vector::::new(scratch()); + used.resize(this.cells.length); + var walk := this.walk_all(); + while walk.more() { + val at := walk.next(); + if this.insts[at].kind == op::cell { + used[this.insts[at].aux] = true; + } + } + + var renumbered := vector::::new(scratch()); + var kept := vector::::new(); + for c in 0..this.cells.length { + renumbered.append(kept.length as u32); + if used[c] { + kept.append(this.cells[c]); + } + } + return false if kept.length == this.cells.length; + var again := this.walk_all(); + while again.more() { + val at := again.next(); + if this.insts[at].kind == op::cell { + this.insts[at].aux = renumbered[this.insts[at].aux]; + } + } + this.cells = move(&mut kept); + for i in 0..this.variables.length { + val held: u32 = this.variables[i].cell; + continue if held == 0; + this.variables[i].cell = used[held - 1] ? renumbered[held - 1] + 1 : 0; + } + return true; +} + +#! Which cells something reads: by loading from them, copying out of them, +#! or anything else their address is given to, which may read them. +#! @param this The code. +#! @returns Whether each cell is read. +def code::read_cells(&this): vector { + var read := vector::::new(scratch()); + return read if this.cells.length == 0; + read.resize(this.cells.length); + var walk := this.walk_all(); + var reads := this.reader(); + while walk.more() { + val at := walk.next(); + # Writing a cell at its address does not read it. + val kind := this.insts[at].kind; + val writes := kind == op::store || kind == op::clear || kind == op::copy; + reads.start(at); + while reads.more() { + val cell := this.cell_of(reads.next()); + if cell != no_cell && !(writes && reads.operand() == 0) { + read[cell] = true; + } + } + } + return read; +} + +#! Whether an instruction only writes a cell nothing reads, which goes: a store +#! or a clear of it, or a copy into it from an address that cannot be null. +#! @param this The code. +#! @param index The instruction. +#! @param read Which cells something reads. +#! @returns Whether it does. +def code::unread_write(&this, index: u32, read: &vector): bool { + val held: inst = this.insts[index]; + return false if held.kind != op::store && held.kind != op::clear && held.kind != op::copy; + val cell := this.cell_of(this.arg(index, 0)); + return false if cell == no_cell || read[cell]; + return held.kind != op::copy || this.checked_address(index, this.arg(index, 1)); +} + +#! Whether an address an instruction reads cannot be null there: one never +#! zero, or a step from a pointer a check before it in its block found not +#! null. +#! @param this The code. +#! @param index The instruction. +#! @param address The address. +#! @returns Whether it cannot. +pub def code::checked_address(&this, index: u32, address: u32): bool { + return true if this.never_zero(address); + var base := address; + var steps := 0; + while steps < 8 { + val made := this.defining(base); + break if made == 0 || this.insts[made].kind != op::add; + base = this.arg(made, 0); + steps++; + } + var walk := this.walk(this.insts[index].block); + while walk.more() { + val at := walk.next(); + break if at == index; + val held := &this.insts[at]; + if held.kind == op::check && held.aux == fault::null_reference as u32 && this.arg(at, 0) == base { + return true; + } + } + return false; +} + +#! Marks what an instruction reads as needed. +#! @param this The code. +#! @param index The instruction. +#! @param live The values needed, those newly needed waiting for their own +#! needs to be marked. +def code::need_operands(&this, index: u32, live: &mut worklist): void { + val held := &this.insts[index]; + for i in 0..held.argc { + live.push_new(this.operands[held.args as u64 + i as u64]); + } +} + +#! Whether an instruction may be taken out where nothing reads what it gives: +#! one that only works out its results, a division by a constant other than +#! zero, which never stops the program, and a read of an address never zero. +#! @param this The code. +#! @param index The instruction. +#! @returns Whether it may. +pub def code::removable(&this, index: u32): bool { + val held: inst = this.insts[index]; + return false if held.count == 0 || held.kind.ends(); + return true if (held.kind.traits() & op_pure) != 0; + match held.kind { + op::divs, op::divu, op::rems, op::remu => { + var bits: u64 = 0; + return this.word_constant(this.arg(index, 1), &mut bits) && bits != 0; + } + op::load => return this.never_zero(this.arg(index, 0)); + else => return false; + } + return false; +} diff --git a/compiler/optimizer/edit.sakura b/compiler/optimizer/edit.sakura new file mode 100644 index 00000000..083ed09b --- /dev/null +++ b/compiler/optimizer/edit.sakura @@ -0,0 +1,592 @@ +#! @file edit.sakura +#! @author John Christman (sorakatadzuma@gmail.com) +#! @copyright Malunal Studios, LLC. +#! @license MIT +#! +#! Contains what the passes of the optimizer share to change code: a rewrite, +#! which gathers the values a pass replaces and the instructions it takes out +#! and applies them in one sweep once the pass is done, and the changes made +#! in place, as an instruction becoming another that gives the same values, an +#! instruction put first in a block or before another, and a branch whose ways +#! out are swapped. Also what the passes ask of code: the constant a value is, +#! whether a value is never zero, and how often each value is used. + +module sakura::compiler; + + +#! What a pass changes as it goes: the value each use of another reads instead, +#! and the instructions taken out, which `code::apply` applies in one sweep. +pub struct rewrite { + var forward: vector; #! The value read instead of each value, or 0. + var removed: vector; #! Whether each instruction is taken out. + var changed: bool; #! Whether the pass changed anything. +} + +#! Makes a rewrite that changes nothing yet. +#! @returns The rewrite. +pub def rewrite::new(): rewrite { + return rewrite { forward = vector::::new(scratch()), removed = vector::::new(scratch()) }; +} + +#! The value read where a value is, following each value replaced to what +#! replaces it. +#! @param this The rewrite. +#! @param value The value. +#! @returns The value read. +pub def rewrite::resolve(&this, value: u32): u32 { + return follow_replaced(this.forward.view().data, this.forward.length, value); +} + +#! The value read where a value is, following each value replaced to what +#! replaces it, until one not replaced, or a million steps, past which the +#! replacements are taken to go round. +#! @param forward The value replacing each value, by index, or 0 where it is +#! not replaced. +#! @param count How many values `forward` holds, past which none is +#! replaced. +#! @param value The value. +#! @returns The value read. +pub def follow_replaced(forward: *u32, count: u64, value: u32): u32 { + var at := value; + var steps := 0; + while (at as u64) < count && forward[at] != 0 && steps < 1000000 { + at = forward[at]; + steps++; + } + return at; +} + +#! Makes each use of a value read another. +#! @param this The rewrite. +#! @param from The value replaced. +#! @param to The value read instead. +pub def rewrite::replace(&mut this, from: u32, to: u32): void { + return if from == to || this.resolve(to) == from; + if this.forward.length <= from as u64 { + this.forward.resize(from as u64 + 1); + } + this.forward[from] = to; + this.changed = true; +} + +#! Takes an instruction out of its block. +#! @param this The rewrite. +#! @param index The instruction. +pub def rewrite::remove(&mut this, index: u32): void { + if this.removed.length <= index as u64 { + this.removed.resize(index as u64 + 1); + } + this.removed[index] = true; + this.changed = true; +} + +#! Whether an instruction is taken out. +#! @param this The rewrite. +#! @param index The instruction. +#! @returns Whether it is. +pub def rewrite::is_removed(&this, index: u32): bool { + return (index as u64) < this.removed.length && this.removed[index]; +} + +#! Applies a rewrite: each operand and argument reads what replaces the value +#! it named, and the instructions taken out leave their blocks. +#! @param this The code. +#! @param done The rewrite. +pub def code::apply(&mut this, done: &rewrite): void { + val count := done.forward.length; + if count != 0 { + # Read and written where the elements are, as this runs over every operand. + val forward := done.forward.view().data; + val operands := this.operands.slice().data; + for i in 0..this.operands.length { + operands[i] = follow_replaced(forward, count, operands[i]); + } + for e in 0..this.edges.length { + val args := this.edges[e].args.slice().data; + for a in 0..this.edges[e].args.length { + args[a] = follow_replaced(forward, count, args[a]); + } + } + # A variable takes what replaces a value it took. + for i in 0..this.bindings.length { + this.bindings[i].value = follow_replaced(forward, count, this.bindings[i].value); + } + } + this.take_out(done); +} + +#! Takes the instructions a rewrite takes out out of their blocks. +#! @param this The code. +#! @param done The rewrite. +pub def code::take_out(&mut this, done: &rewrite): void { + return if done.removed.length == 0; + + # Only the blocks holding what is taken out are linked anew. + var touched := vector::::new(scratch()); + touched.resize(this.blocks.length); + for i in 0..done.removed.length { + if done.removed[i] && (this.insts[i].block as u64) < touched.length { + touched[this.insts[i].block] = true; + } + } + for b in 0..this.blocks.length { + continue if this.blocks[b].gone || !touched[b]; + var walk := this.walk(b as u32); + var kept: u32 = 0; + this.blocks[b].first = 0; + this.blocks[b].last = 0; + while walk.more() { + val at := walk.next(); + continue if done.is_removed(at); + if kept == 0 { + this.blocks[b].first = at; + } else { + this.insts[kept].next = at; + } + kept = at; + } + if kept != 0 { + this.insts[kept].next = 0; + } + this.blocks[b].last = kept; + } +} + +#! The instruction giving a value, or 0 for one a block takes. +#! @param this The code. +#! @param value The value. +#! @returns The instruction. +pub def code::defining(&this, value: u32): u32 { + return 0 if value == 0 || (value as u64) >= this.origins.length; + val held: origin = this.origins[value]; + return held.param ? 0 : held.from; +} + +#! The block a value is made in: the block taking it, or holding the +#! instruction giving it. +#! @param this The code. +#! @param value The value. +#! @returns The block. +pub def code::home_of(&this, value: u32): u32 { + val held: origin = this.origins[value]; + return held.param ? held.from : this.insts[held.from].block; +} + +#! What `code::cell_of` gives for a value that is the address of no cell. +pub const no_cell: u32 = 0xFFFFFFFF; + +#! The cell a value is the address of, as the instruction giving it says. +#! @param this The code. +#! @param value The value. +#! @returns The cell, or `no_cell`. +pub def code::cell_of(&this, value: u32): u32 { + val index := this.defining(value); + return no_cell if index == 0 || this.insts[index].kind != op::cell; + return this.insts[index].aux; +} + +#! Which cell each value of code is the address of, found once from the `cell` +#! instructions of the blocks not removed, for a pass that asks it of many +#! values. +pub struct cell_table { + var of: vector; #! One more than the cell each value is the address of, or 0. + var any: bool; #! Whether any value is. +} + +#! Finds which cell each value is the address of. +#! @param this The code. +#! @returns The table, in scratch memory. +pub def code::cell_table(&this): cell_table { + var made := cell_table { of = vector::::new(scratch()) }; + # Code with no cells has no value that is the address of one. + return made if this.cells.length == 0; + made.of.resize(this.origins.length); + var walk := this.walk_all(); + while walk.more() { + val held := &this.insts[walk.next()]; + if held.kind == op::cell { + made.of[held.result] = held.aux + 1; + made.any = true; + } + } + return made; +} + +#! The cell a value is the address of, as the table found it. +#! @param this The table. +#! @param value The value. +#! @returns One more than the cell, or 0, as for a value made after the table. +pub def cell_table::cell(&this, value: u32): u32 { + return (value as u64) < this.of.length ? this.of[value] : 0; +} + +#! Whether a value is a constant word, and its bits. +#! @param this The code. +#! @param value The value. +#! @param bits Where its bits are written, where it is one. +#! @returns Whether it is. +pub def code::word_constant(&this, value: u32, bits: &mut u64): bool { + val index := this.defining(value); + return false if index == 0 || this.insts[index].kind != op::iconst; + bits = this.insts[index].imm; + return true; +} + +#! Whether a value is a constant real, and its bits. +#! @param this The code. +#! @param value The value. +#! @param bits Where the bits of the `f64` are written, where it is one. +#! @returns Whether it is. +pub def code::real_constant(&this, value: u32, bits: &mut u64): bool { + val index := this.defining(value); + return false if index == 0 || this.insts[index].kind != op::fconst; + bits = this.insts[index].imm; + return true; +} + +#! The type of the constant a value is, and its bits, read where the +#! instruction making it lies, taken out of its block or not, as a binding +#! naming the value keeps the constant once that instruction goes. +#! @param this The code. +#! @param value The value. +#! @param bits Where its bits are written, where it is one. +#! @returns Its type, or `none` where it is no constant. +pub def code::constant_kind(&this, value: u32, bits: &mut u64): vt { + return vt::word if this.word_constant(value, bits); + return vt::real if this.real_constant(value, bits); + return vt::none; +} + +#! Whether a word is never zero: the address of a cell, a global, or a datum, +#! or a small step past one. +#! @param this The code. +#! @param value The word. +#! @returns Whether it is never zero. +pub def code::never_zero(&this, value: u32): bool { + var at := value; + var steps := 0; + while steps < 8 { + val index := this.defining(at); + return false if index == 0; + val held: inst = this.insts[index]; + match held.kind { + op::cell, op::global, op::datum => return true; + op::iconst => return held.imm != 0; + op::add => { + var step: u64 = 0; + return false if !this.word_constant(this.arg(index, 1), &mut step) || step >= 0x100000000u; + at = this.arg(index, 0); + } + else => return false; + } + steps++; + } + return false; +} + +#! How many times each value is read, by operands and by the arguments of +#! edges, in the blocks not removed. +#! @param this The code. +#! @returns The count of each value. +pub def code::use_counts(&this): vector { + var counts := vector::::new(scratch()); + counts.resize(this.origins.length); + var walk := this.walk_all(); + var reads := this.reader(); + while walk.more() { + reads.start(walk.next()); + while reads.more() { + val value := reads.next(); + counts[value] = counts[value] + 1; + } + } + return counts; +} + +#! Makes an instruction another that gives the same values, in place, so what +#! reads them reads what it gives now. +#! @param this The code. +#! @param index The instruction. +#! @param kind What it does now. +#! @param args Its operands now. +#! @param aux What its kind says `aux` holds. +#! @param imm What its kind says `imm` holds. +pub def code::become(&mut this, index: u32, kind: op, args: span, aux: u32, imm: u64): void { + # Operands fit where its old ones were, or else go after every other. + var first: u32 = this.insts[index].args; + if args.length > this.insts[index].argc as u64 { + first = this.operands.length as u32; + this.operands.resize(this.operands.length + args.length); + } + for i in 0..args.length { + this.operands[first as u64 + i] = args[i]; + } + this.insts[index].kind = kind; + this.insts[index].args = first; + this.insts[index].argc = args.length as u32; + this.insts[index].aux = aux; + this.insts[index].imm = imm; +} + +#! Makes an instruction the constant word it gives. +#! @param this The code. +#! @param index The instruction. +#! @param bits The word's bits. +pub def code::become_word(&mut this, index: u32, bits: u64): void { + this.become(index, op::iconst, span::::empty(), 0, bits); + this.origins[this.insts[index].result].kind = vt::word; +} + +#! Makes an instruction the constant real it gives. +#! @param this The code. +#! @param index The instruction. +#! @param bits The bits of the `f64` it is. +pub def code::become_real(&mut this, index: u32, bits: u64): void { + this.become(index, op::fconst, span::::empty(), 0, bits); +} + +#! Adds an instruction, in no block yet. +#! @param this The code. +#! @param kind What it does. +#! @param args Its operands. +#! @param gives The types of its results, in order. +#! @param aux What its kind says `aux` holds. +#! @param imm What its kind says `imm` holds. +#! @param pos Where in the source it is from. +#! @param site One more than the site of the function it was inlined from, +#! or 0. +#! @returns Its index. +pub def code::detached( + &mut this, + kind: op, + args: span, + gives: span, + aux: u32, + imm: u64, + pos: u64, + site: u32 +): u32 { + val index := this.insts.length as u32; + val first := this.operands.length as u32; + # Appended one by one, which is inlined, where `extend` is a call for each + # instruction. + for &each in args { + this.operands.append(each); + } + val result := this.origins.length as u32; + for i in 0..gives.length { + this.origins.append(origin { kind = gives[i], from = index, index = i as u32 }); + } + this.insts.append(inst { + kind = kind, + count = gives.length as u8, + aux = aux, + imm = imm, + args = first, + argc = args.length as u32, + result = gives.length == 0 ? 0 : result, + at = pos, + site = site + }); + return index; +} + +#! Puts an instruction made in no block before another in its block. +#! @param this The code. +#! @param index The instruction. +#! @param before The instruction it goes before. +pub def code::link_before(&mut this, index: u32, before: u32): void { + val block: u32 = this.insts[before].block; + val prior := this.before(before); + this.insts[index].block = block; + this.insts[index].next = before; + if prior == 0 { + this.blocks[block].first = index; + } else { + this.insts[prior].next = index; + } +} + +#! The instruction before another in its block. +#! @param this The code. +#! @param index The instruction, which its block holds. +#! @returns The instruction before it, or 0 where it is the first. +pub def code::before(&this, index: u32): u32 { + var prior: u32 = 0; + var walk := this.walk(this.insts[index].block); + while walk.more() { + val at := walk.next(); + break if at == index; + prior = at; + } + return prior; +} + +#! Puts an instruction made in no block after another in its block. +#! @param this The code. +#! @param index The instruction. +#! @param after The instruction it goes after. +pub def code::link_after(&mut this, index: u32, after: u32): void { + val block: u32 = this.insts[after].block; + this.insts[index].block = block; + this.insts[index].next = this.insts[after].next; + this.insts[after].next = index; + if this.blocks[block].last == after { + this.blocks[block].last = index; + } +} + +#! A constant word, made first in the entry, where it stands before everything +#! that may read it. +#! @param this The code. +#! @param bits Its bits. +#! @returns The value. +pub def code::word_value(&mut this, bits: u64): u32 { + var gives: vt[1] = [vt::word]; + val index := this.detached(op::iconst, span::::empty(), gives[0:1], 0, bits, 0, 0); + this.put_first(0, index); + return this.insts[index].result; +} + +#! A constant real, made first in the entry. +#! @param this The code. +#! @param bits The bits of the `f64` it is. +#! @returns The value. +pub def code::real_value(&mut this, bits: u64): u32 { + var gives: vt[1] = [vt::real]; + val index := this.detached(op::fconst, span::::empty(), gives[0:1], 0, bits, 0, 0); + this.put_first(0, index); + return this.insts[index].result; +} + +#! The zero of a type of value, made first in the entry: the word 0, the real +#! 0, or a vector of zero bytes. +#! @param this The code. +#! @param kind The type. +#! @returns The value. +pub def code::zero_value(&mut this, kind: vt): u32 { + return this.real_value(0) if kind == vt::real; + return this.word_value(0) if !kind.lanes(); + var gives: vt[1] = [kind]; + val index := this.detached(op::vzero, span::::empty(), gives[0:1], 0, 0, 0, 0); + this.put_first(0, index); + return this.insts[index].result; +} + +#! The zero of each type of value a pass asks for, each made once, as +#! `code::zero_value` makes it. +pub struct zero_values { + var held: u32[vt::count as u64]; #! The zero of each type made, or 0. +} + +#! The zero of a type of value, made first in the entry the first time it is +#! asked for. +#! @param this The zeros. +#! @param body The code. +#! @param kind The type. +#! @returns The value. +pub def zero_values::of(&mut this, body: &mut code, kind: vt): u32 { + val at := kind as u64; + if this.held[at] == 0 { + this.held[at] = body.zero_value(kind); + } + return this.held[at]; +} + +#! Takes an edge out of the edges into its block. +#! @param this The code. +#! @param edge The edge. +pub def code::drop_pred(&mut this, edge: u32): void { + this.forget_order(); + val target: u32 = this.edges[edge].target; + var kept := ids {}; + for &each in this.blocks[target].preds { + if each != edge { + kept.append(each); + } + } + this.blocks[target].preds = move(&mut kept); +} + +#! Takes out the parameters of a block that do not stay, with the argument each +#! edge into the block gives them, numbering those left in the order they were. +#! @param this The code. +#! @param block The block. +#! @param keeps Whether each of its parameters stays, by its position. +pub def code::drop_params(&mut this, block: u32, keeps: span): void { + var kept := ids {}; + for p in 0..keeps.length { + continue if !keeps[p]; + val param: u32 = this.blocks[block].params[p]; + this.origins[param].index = kept.length as u32; + kept.append(param); + } + for &edge in this.blocks[block].preds.view() { + var args := ids {}; + for p in 0..keeps.length { + if keeps[p] { + args.append(this.edges[edge].args[p]); + } + } + this.edges[edge].args = move(&mut args); + } + this.blocks[block].params = move(&mut kept); +} + +#! Makes an instruction ending a block go along one of its edges only, as a +#! `jump`, taking the others out of the blocks they went to. +#! @param this The code. +#! @param index The instruction. +#! @param kept The edge it goes along. +pub def code::jump_only(&mut this, index: u32, kept: u32): void { + this.forget_order(); + var outs := this.edges_of(index); + while outs.more() { + val edge := outs.next(); + if edge != kept { + this.drop_pred(edge); + } + } + this.become(index, op::jump, span::::empty(), kept, 0); +} + +#! Swaps where a `branch` goes, so it goes where it went where its condition +#! was zero where it is not, as a branch on a condition's opposite does. +#! @param this The code. +#! @param index The `branch`. +pub def code::swap_branch(&mut this, index: u32): void { + this.forget_order(); + val one: u32 = this.insts[index].aux; + val two := one + 1; + val first: u32 = this.edges[one].target; + val second: u32 = this.edges[two].target; + var args := move(&mut this.edges[one].args); + this.edges[one].args = move(&mut this.edges[two].args); + this.edges[two].args = move(&mut args); + this.edges[one].target = second; + this.edges[two].target = first; + return if first == second; + for i in 0..this.blocks[first].preds.length { + if this.blocks[first].preds[i] == one { + this.blocks[first].preds[i] = two; + } + } + for i in 0..this.blocks[second].preds.length { + if this.blocks[second].preds[i] == two { + this.blocks[second].preds[i] = one; + } + } +} + +#! How many instructions the code holds, in the blocks not removed. +#! @param this The code. +#! @returns How many. +pub def code::size(&this): u32 { + var count: u32 = 0; + var walk := this.walk_all(); + while walk.more() { + walk.next(); + count++; + } + return count; +} diff --git a/compiler/optimizer/inline.sakura b/compiler/optimizer/inline.sakura new file mode 100644 index 00000000..f7da30a7 --- /dev/null +++ b/compiler/optimizer/inline.sakura @@ -0,0 +1,1136 @@ +#! @file inline.sakura +#! @author John Christman (sorakatadzuma@gmail.com) +#! @copyright Malunal Studios, LLC. +#! @license MIT +#! +#! Contains the fourth pass of the optimizer, inlining: a call of a function +#! small enough is replaced by a copy of the function's code. The block the +#! call is in ends going into the copy, which is given the call's arguments as +#! its parameters, its own copy of each one taken as memory, and zeroed cells +#! of its own; each `return` of the copy goes to the rest of the block, which +#! takes what was returned. Functions are inlined into those calling them +#! once their own calls are, so what is copied is already small. +#! +#! A function of any size is copied where the program calls it but once and +#! nothing else reaches it, as it is then left unused, and one of up to twice +#! the size where the call gives a constant deciding where its entry goes, +#! which folds the entry's branch and what only the other way leads to. A +#! function too large whose entry tests something and one way only returns +#! has just the test and that way copied, going on to call the function the +#! other way, which tests again. A call is left as it is where every way on +#! from it stops the program, as what inlining it would save never matters +#! there. +#! +#! A function written `@inline` is copied wherever it is called, whatever its +#! size, how much the function calling it has grown, or whether the call is +#! cold, at every level: below `-O2`, its calls are the only ones inlined. A +#! call it cannot be copied at stays a call: one of a function after the one +#! calling it in the order, as where it closes a loop of calls, or one through +#! a trait reference or a function value. +#! +#! A trace still names a function inlined, where it was, then where it was +#! called: each instruction copied names the site it was inlined at, which +#! names the function, the call, and the site that call was itself at. + +module sakura::compiler; + + +#! The most instructions a function inlined may have, but for its constants, +#! jumps, and returns. +pub const inline_limit: u32 = 16; + +#! The most instructions a method an iterator gives its elements by, or a +#! functor's `invoke`, may have, but for constants, jumps, and returns, where a +#! loop calls it: so each element of a chain of adapters is worked out within +#! the loop walking it, as a loop written out would. +pub const step_limit: u32 = 96; + +#! The most instructions a function may grow to by inlining what it calls. +pub const inline_growth: u32 = 6000; + +#! What a call's `imm` is where the function it calls was optimized before the +#! function holding it began, as one it waited for, or one that one waited for: +#! only such a function's code and facts are read, since any other may still +#! be changing on a thread of its own. Any other call's is 0. +pub const call_settled: u64 = 1; + +#! The most instructions a function may grow to by inlining a function it +#! alone calls: past it, optimizing the larger function costs more than the +#! call saves, and the code it makes is no smaller. +pub const sole_growth: u32 = 3000; + +#! The most instructions the test of a function's entry and the way it only +#! returns may have, but for constants, jumps, and returns, where a call copies +#! them and calls the function the other way. +pub const partial_limit: u32 = 4; + +#! What inlining knows of a function. All but `sole` is worked out once the +#! function is optimized, as its code no longer changes then; `sole` is worked +#! out with the order functions are optimized in, before any is. +pub struct inline_facts { + var known: bool; #! Whether what is worked out once it is optimized is. + var fits: bool; #! Whether its code may be copied where it is called: it is lowered, takes no environment, computes no evaluation, and does nothing that needs a frame of its own, as asking where its frame is. + var cost: u32; #! Its instructions, but for constants, jumps, returns, and vectors' reads, writes, and operations. + var size: u32; #! All its instructions. + var tested: u64; #! Which of its first 64 parameters decide where its entry goes, one bit each, as `entry_tests` says. + var returns: bool; #! Whether any way through it returns. + var asks: bool; #! Whether it asks which instructions the processor has, so its version, which calls of versions inline, does better than a copy of it would. + var short: u32; #! One more than the block its entry goes to one way that only returns, as `short_way` finds it, or 0. + var head: u32; #! What the test going there and that block cost, counted as `cost` is. + var sole: u32; #! One more than the function making the only call of it, where nothing else reaches it, or 0. +} + +#! Finds, of the functions about to be optimized, those the program calls but +#! once and reaches no other way: not as a value, through a vtable, from C, at +#! a safe point, nor by name, as `main`, the code initializing the globals, and +#! what the backend calls are. Each notes the function calling it, which copies +#! it whole, whatever its size, where the call is not cold. The calls are +#! counted before any function is optimized, so what each is made into is the +#! same however many threads optimize them. +#! @param this The compiler. +#! @param order The functions about to be optimized, which are all that call +#! them, as each calls only what was lowered with it or before. +pub def lowerer::find_sole_calls(&mut this, order: &vector): void { + return if this.options.level < 2; + val point := mark_scratch(); + val count := this.program.functions.length; + var calls := vector::::new(scratch()); + calls.resize(count); + var callers := vector::::new(scratch()); + callers.resize(count); + var other := vector::::new(scratch()); + other.resize(count); + for &function in order.view() { + val body := &this.program.functions[function].body; + var walk := body.walk_all(); + while walk.more() { + val at := walk.next(); + val kind := body.insts[at].kind; + val callee: u32 = body.insts[at].aux; + if kind == op::call { + calls[callee] = calls[callee] + 1; + callers[callee] = function; + } else if kind == op::callback || kind == op::safepoint { + other[callee] = true; + } + } + } + for &each in this.program.vtables { + for &function in each.functions { + if function != no_function { + other[function] = true; + } + } + } + val roots: u32[3] = [this.program.main, this.program.init, this.dispatch]; + for r in 0..3u { + if roots[r] != no_function { + other[roots[r]] = true; + } + } + + for &function in order.view() { + val held := &mut this.program.functions[function]; + held.inlining.sole = 0; + continue if calls[function] != 1 || callers[function] == function || other[function] || held.taken || held.callback; + held.inlining.sole = callers[function] + 1; + } + release_scratch(point); +} + +#! Whether a function may be inlined wherever it is called, being small enough. +#! @param this The compiler. +#! @param index The function. +#! @returns Whether it may. +pub def lowerer::inlinable(&mut this, index: u32): bool { + val facts := this.inline_facts(index); + val limit := this.options.inline_limit != 0 ? this.options.inline_limit : inline_limit; + return facts.fits && facts.cost <= limit; +} + +#! What inlining knows of a function, worked out once its own calls are +#! inlined, after which its code no longer changes, so what is found is kept. +#! @param this The compiler. +#! @param index The function. +#! @returns What it knows. +pub def lowerer::inline_facts(&mut this, index: u32): inline_facts { + if !this.program.functions[index].inlining.known { + this.work_out_facts(index); + } + return this.program.functions[index].inlining; +} + +#! Works out what inlining knows of an optimized function, keeping `sole`. +#! @param this The compiler. +#! @param index The function. +def lowerer::work_out_facts(&mut this, index: u32): void { + val held := &this.program.functions[index]; + val body := &held.body; + var facts: inline_facts = held.inlining; + facts.known = true; + facts.fits = held.lowered && !held.closure && held.evaluation == 0; + var walk := body.walk_all(); + while walk.more() { + val at := walk.next(); + val kind := body.insts[at].kind; + facts.size++; + facts.cost += body.inline_cost(at); + match kind { + op::frame, op::ready, op::reach, op::same => facts.fits = false; + op::ret => facts.returns = true; + op::cpu => facts.asks = true; + else => {} + } + } + facts.tested = body.entry_tests(); + if facts.fits { + var head: u32 = 0; + facts.short = this.short_way(index, &mut head); + facts.head = head; + } + this.program.functions[index].inlining = facts; +} + +#! Which parameters decide where code's entry goes, so a constant given for +#! one folds the entry's branch or switch, and what it alone leads to goes: +#! the word it branches or switches on, or what the entry compares with a +#! constant to give that word. +#! @param this The code. +#! @returns The parameters of its first 64, one bit each. +def code::entry_tests(&this): u64 { + val last: u32 = this.blocks[0].last; + return 0 if last == 0 || (this.insts[last].kind != op::branch && this.insts[last].kind != op::switch); + var tested: u64 = 0; + val cond := this.arg(last, 0); + var subjects: u32[2] = [cond, 0]; + val made := this.defining(cond); + if made != 0 && this.insts[made].block == 0 && this.insts[made].argc == 2 { + match this.insts[made].kind { + op::eq, op::ne, op::lts, op::ltu, op::les, op::leu, op::eqsu, op::ltsu, op::lesu, op::ltus, op::leus, + op::feq, op::fne, op::flt, op::fle => { + var bits: u64 = 0; + val a := this.arg(made, 0); + val b := this.arg(made, 1); + if this.word_constant(b, &mut bits) || this.real_constant(b, &mut bits) { + subjects[1] = a; + } else if this.word_constant(a, &mut bits) || this.real_constant(a, &mut bits) { + subjects[1] = b; + } + } + else => {} + } + } + for k in 0..2u { + continue if subjects[k] == 0; + val held: origin = this.origins[subjects[k]]; + if held.param && held.from == 0 && held.index < 64 { + tested = tested | (1u << held.index as u64); + } + } + return tested; +} + +#! What an instruction costs inlined: nothing for a constant, a jump, or a +#! return, which becomes a jump to the rest of the caller's block, as copied +#! they mostly fold or merge away; nor for vectors' reads, writes, and +#! operations, which inlined become values held in registers where the +#! caller's cells are promoted, or asking for the processor's instructions, +#! which code for those it has knows; and 1 for anything else. +#! @param this The code. +#! @param index The instruction. +#! @returns What it costs. +def code::inline_cost(&this, index: u32): u32 { + return match this.insts[index].kind { + op::iconst, op::fconst, op::jump, op::ret, op::cpu, op::vzero, op::lanes => 0, + op::load, op::store => (this.insts[index].aux as access).value_type().lanes() ? 0 : 1, + else => 1 + }; +} + +#! Inlines the calls a function makes of functions that come before it in the +#! order functions are optimized in, so their own calls are inlined already. +#! Each call is copied whole where the function it calls is small enough, is +#! called by it alone, or is given a constant deciding where its entry goes and +#! is up to twice as large; or else, where the function calling is itself too large to be +#! inlined whole, as far as the way the entry only returns. A call in a cold +#! block is left as it is, as is one of a function too large that asks which +#! instructions the processor has, but that a call of an `@inline` function is +#! copied whole wherever it is. Below `-O2`, those are the only calls copied, +#! and no call through a function value is made a call of the function. +#! @param this The compiler. +#! @param index The function. +#! @param ranks Where each function is in the order, as `optimizing` says. +#! @param rank Where the function is. +#! @returns Whether any call was. +pub def lowerer::inline_calls(&mut this, index: u32, ranks: &vector, rank: u32): bool { + val called := this.options.level >= 2 && this.devirtualize(index, ranks, rank); + val changed := this.inline_each(index, ranks, rank); + return called || changed; +} + +#! Inlines the calls a function makes of functions that come before it, as +#! `inline_calls` says, or below `-O2`, only those of `@inline` functions. +#! @param this The compiler. +#! @param index The function. +#! @param ranks Where each function is in the order, as `optimizing` says. +#! @param rank Where the function is. +#! @returns Whether any call was. +def lowerer::inline_each(&mut this, index: u32, ranks: &vector, rank: u32): bool { + val every := this.options.level >= 2; + val marks := this.inlines_marked(); + var calls := vector::::new(scratch()); + var cost: u32 = 0; + val body := &this.program.functions[index].body; + var walk := body.walk_all(); + while walk.more() { + val at := walk.next(); + cost += body.inline_cost(at); + if body.insts[at].kind == op::call && (every || marks && this.program.functions[body.insts[at].aux].inline) { + calls.append(at); + } + } + return false if calls.length == 0; + + # Only what inlines more than `@inline` functions asks which calls are cold, + # or in a loop. + var hot := vector::::new(scratch()); + var in_loop := vector::::new(scratch()); + if every { + val cold := this.cold_blocks(index, ranks, rank); + val looped := this.looped_blocks(index); + for &call in calls { + hot.append(!cold[body.insts[call].block]); + in_loop.append(looped[body.insts[call].block]); + } + } + + # What each call gave is replaced once every call is inlined. + var changed := false; + var done := rewrite::new(); + var size := this.program.functions[index].body.size(); + val limit := this.options.inline_limit != 0 ? this.options.inline_limit : inline_limit; + for c in 0..calls.length { + val call: u32 = calls[c]; + val callee: u32 = this.program.functions[index].body.insts[call].aux; + val marked := marks && this.program.functions[callee].inline; + continue if !marked && (size > inline_growth || !hot[c]); + continue if callee == index || ranks[callee] >= rank + || this.program.functions[index].body.insts[call].imm != call_settled; + val facts := this.inline_facts(callee); + continue if !facts.fits; + var whole := marked || facts.cost <= limit; + if !whole && facts.cost <= step_limit && this.program.functions[callee].stepping { + whole = in_loop[c]; + } + continue if !whole && facts.asks; + if !whole && facts.sole == index + 1 && size + facts.size <= sole_growth { + whole = calls_of(&this.program.functions[index].body, &calls, callee) == 1; + } + if !whole && facts.tested != 0 && facts.cost <= 2 * limit { + whole = this.program.functions[index].body.gives_tested(call, facts.tested); + } + if whole { + if this.inline_call(index, call, &mut done) { + size += facts.size; + cost += facts.cost; + changed = true; + this.names_of(index, callee, ranks); + } + continue; + } + + # A function small enough to be inlined whole stays so, as copying the test + # would leave it calling all the same, only larger. + continue if cost <= limit || facts.short == 0 || facts.head > partial_limit; + continue if !this.head_fits(index, call, facts.short - 1); + this.inline_head(index, call, facts.short - 1, &mut done); + size += facts.head; + cost += facts.head; + changed = true; + this.names_of(index, callee, ranks); + } + if changed { + this.program.functions[index].body.apply(&done); + this.program.functions[index].body.prune(); + } + return changed; +} + +#! Gives a function the functions named by one inlined into it, whose values +#! its code may now hold: those that one waited for, so they were optimized +#! before the function began. +#! @param this The compiler. +#! @param index The function. +#! @param callee The function inlined. +#! @param ranks Where each function is in the order. +def lowerer::names_of(&mut this, index: u32, callee: u32, ranks: &vector): void { + val count := this.program.functions[callee].named.length; + for i in 0..count { + val named: u32 = this.program.functions[callee].named[i]; + if ranks[named] < ranks[callee] { + this.names(index, named); + } + } +} + +#! Calls the function a function value holds directly where it is known, as +#! where the value was made in the code calling it, once what made it is +#! inlined: a call of it is then inlined as any other is, where the function was +#! named by the code, so optimizing it waited for it. One a constant's data +#! holds is called directly, but not inlined. A function taking an environment +#! is left called through the value. What made the value marked the function +#! `taken`, so nothing else learns of the call. +#! @param this The compiler. +#! @param index The function. +#! @param ranks Where each function is in the order, as `optimizing` says. +#! @param rank Where the function is. +#! @returns Whether any call changed. +def lowerer::devirtualize(&mut this, index: u32, ranks: &vector, rank: u32): bool { + var changed := false; + val count := this.program.functions.length as u64; + var found := vector::::new(scratch()); + var walk := this.program.functions[index].body.walk_all(); + while walk.more() { + val at := walk.next(); + if this.program.functions[index].body.insts[at].kind == op::call_value { + found.append(at); + } + } + for &at in found { + val body := &mut this.program.functions[index].body; + var bits: u64 = 0; + continue if !body.word_constant(body.arg(at, 0), &mut bits) || bits == 0 || bits > count; + val callee := (bits - 1) as u32; + continue if this.program.functions[callee].closure || this.program.functions[callee].signature != body.insts[at].aux; + var args := vector::::new(scratch()); + for i in 2..body.insts[at].argc { + args.append(body.arg(at, i)); + } + val settled := ranks[callee] < rank && this.named_by(index, callee); + body.become(at, op::call, args.view(), callee, settled ? call_settled : 0); + changed = true; + } + return changed; +} + +#! Whether a function's code, or code inlined into it, names another as a value. +#! @param this The compiler. +#! @param index The function. +#! @param callee The other. +#! @returns Whether it does. +def lowerer::named_by(&this, index: u32, callee: u32): bool { + for &each in this.program.functions[index].named.view() { + return true if each == callee; + } + return false; +} + +#! Which blocks of a function's code are within a loop of it. +#! @param this The compiler. +#! @param index The function. +#! @returns Whether each block is, by block, in scratch memory. +def lowerer::looped_blocks(&mut this, index: u32): vector { + var made := vector::::new(scratch()); + val body := &mut this.program.functions[index].body; + made.resize(body.blocks.length); + val view := body.view_loops(); + for b in 0..body.blocks.length { + made[b] = b < view.nest.inner.length && view.nest.inner[b] != no_loop; + } + return made; +} + +#! How many of the calls code makes call a function, of those not yet +#! inlined. +#! @param body The code. +#! @param calls The calls. +#! @param callee The function. +#! @returns How many. +def calls_of(body: &code, calls: &vector, callee: u32): u32 { + var count: u32 = 0; + for &each in calls { + if body.insts[each].kind == op::call && body.insts[each].aux == callee { + count++; + } + } + return count; +} + +#! Whether a call gives a constant for a parameter that decides where the entry +#! of the function it calls goes, which folds once the function is copied. +#! @param this The code. +#! @param call The call. +#! @param tested Which parameters decide it, as `entry_tests` says. +#! @returns Whether it does. +def code::gives_tested(&this, call: u32, tested: u64): bool { + val count := this.insts[call].argc; + for i in 0..(count < 64 ? count : 64) { + continue if (tested & (1u << i as u64)) == 0; + val made := this.defining(this.arg(call, i as u32)); + return true if made != 0 && (this.insts[made].kind == op::iconst || this.insts[made].kind == op::fconst); + } + return false; +} + +#! Finds the cold blocks of a function's code: those every way on from which +#! stops the program, by a trap, or what never returns, as an `abort`, or a +#! call of a function before it in the order that never returns, each block +#! then cold once every block it goes to is. +#! @param this The compiler. +#! @param index The function. +#! @param ranks Where each function is in the order functions are optimized +#! in, as `optimizing` says. +#! @param rank Where the function is. +#! @returns Whether each block is cold, by its index. +def lowerer::cold_blocks(&mut this, index: u32, ranks: &vector, rank: u32): vector { + val body := &this.program.functions[index].body; + var cold := vector::::new(scratch()); + cold.resize(body.blocks.length); + var any := false; + for b in 0..body.blocks.length { + continue if body.blocks[b].gone; + var walk := body.walk(b as u32); + while walk.more() { + val at := walk.next(); + val kind := body.insts[at].kind; + if kind == op::trap || kind == op::unreachable || kind == op::abort || kind == op::fault { + cold[b] = true; + } else if kind == op::call { + val callee: u32 = body.insts[at].aux; + if ranks[callee] < rank && body.insts[at].imm == call_settled && !this.inline_facts(callee).returns { + cold[b] = true; + } + } + } + any = any || cold[b]; + } + return cold if !any; + + # A loop never cold of itself stays as it is, as each of its blocks waits on + # another. + var changed := true; + while changed { + changed = false; + var b := body.blocks.length; + while b > 0 { + b--; + continue if cold[b] || body.blocks[b].gone; + val last: u32 = body.blocks[b].last; + continue if last == 0 || body.edge_count(last) == 0; + var all := true; + var edges := body.edges_of(last); + while edges.more() { + if !cold[body.edges[edges.next()].target] { + all = false; + break; + } + } + if all { + cold[b] = true; + changed = true; + } + } + } + return cold; +} + +#! Works out the order a function's blocks are copied in where it is inlined, +#! once, as its code no longer changes once it may be. +#! @param this The compiler. +#! @param index The function. +pub def lowerer::order_blocks(&mut this, index: u32): void { + return if this.program.functions[index].order.length != 0; + var order := vector::::new(); + var number := vector::::new(scratch()); + this.program.functions[index].body.block_order(&mut order, &mut number); + this.program.functions[index].order = move(&mut order); +} + +#! How a function takes each of the values its entry block takes: whether each +#! is the address of a parameter taken as memory, and the parameter's layout. +#! @param this The compiler. +#! @param signature The function's signature. +#! @param memory Where whether each is held in memory is written. +#! @param layouts Where the layout of each one held in memory is written. +def lowerer::entry_values(&this, signature: u32, memory: &mut vector, layouts: &mut vector): void { + val held := &this.program.signatures[signature]; + for i in 0..held.params.length { + val index: u32 = held.params[i]; + val shape := this.layout_at(index); + if in_memory(&shape) { + memory.append(true); + layouts.append(index); + continue; + } + for _ in 0..word_count(&shape) { + memory.append(false); + layouts.append(index); + } + } +} + +#! Ends the block a call is in at the call, the rest of it a block of its own +#! taking what the call gives, which what read that reads instead once every +#! call is inlined. +#! @param this The code. +#! @param call The call. +#! @param done Where what reads what the call gave is noted. +#! @returns The rest of the block. +def code::split_at(&mut this, call: u32, done: &mut rewrite): u32 { + val held: inst = this.insts[call]; + val home := held.block; + val rest := this.add_block(); + this.blocks[rest].first = held.next; + this.blocks[rest].last = this.blocks[home].last; + var moved := this.walk(rest); + while moved.more() { + this.insts[moved.next()].block = rest; + } + this.insts[call].next = 0; + this.blocks[home].last = call; + for r in 0..held.count { + val result := held.result + r as u32; + val param := this.add_param(rest, this.type_of(result)); + done.replace(result, param); + } + return rest; +} + +#! The site, among those of the code a function is copied into at a call, of +#! code of the function: the site of the call, for the function's own code, or +#! for code inlined into the function, a copy of the site it was inlined at, +#! within the copy of the site that was within. Each is made the first time it +#! is asked for, so none is made of a site whose code was taken out of the +#! function, or is left out of the copy. +#! @param this The code copied into. +#! @param callee The code of the function. +#! @param index The function. +#! @param held The call. +#! @param sites One more than the site made for the function's own code, +#! then for each of its sites, or 0 for each not made yet. +#! @param site One more than the function's site, or 0 for its own code. +#! @returns One more than the site made. +def code::site_in(&mut this, callee: &code, index: u32, held: &inst, sites: &mut vector, site: u32): u32 { + return sites[site] if sites[site] != 0; + var made := inline_site { function = index, at = held.at, parent = held.site }; + if site != 0 { + val each: inline_site = callee.sites[site - 1]; + made = inline_site { function = each.function, at = each.at, parent = this.site_in(callee, index, held, sites, each.parent) }; + } + this.sites.append(made); + sites[site] = this.sites.length as u32; + return sites[site]; +} + +#! Replaces a call with a copy of the code of the function it calls. +#! @param this The compiler. +#! @param caller The function calling. +#! @param call The `call`. +#! @param done What reads what the call gave reads instead, applied once +#! every call is inlined. +#! @returns Whether it was replaced, which it is not where the call does not +#! give what the function takes. +def lowerer::inline_call(&mut this, caller: u32, call: u32, done: &mut rewrite): bool { + val callee_index: u32 = this.program.functions[caller].body.insts[call].aux; + this.order_blocks(callee_index); + val callee := &this.program.functions[callee_index].body; + val body := &mut this.program.functions[caller].body; + val held: inst = body.insts[call]; + + var memory := vector::::new(scratch()); + var layouts := vector::::new(scratch()); + this.entry_values(this.program.functions[callee_index].signature, &mut memory, &mut layouts); + val takes := callee.blocks[0].params.length; + val returns_memory := callee.returned != 0; + val given := held.argc as u64 - (returns_memory ? 1 : 0); + return false if takes != given || memory.length != takes || held.count as u64 != callee.results.length; + + # The rest of the block, after the call, is a block of its own, taking what + # the call gives. + val rest := body.split_at(call, done); + val dst: u32 = returns_memory ? body.arg(call, held.argc - 1) : 0; + + # Where the function inlined was called, which each instruction copied names. + var sites := vector::::new(scratch()); + sites.resize(callee.sites.length + 1); + + # Its cells follow the caller's, cleared where the copy begins rather than + # as the frame does, but those it declares `undefined`. + val base := body.cells.length as u32; + for &each in callee.cells { + val kind := each.kind == ck::undefined ? ck::undefined : ck::inlined; + body.cells.append(cell { size = each.size, align = each.align, kind = kind, name = each.name }); + } + + # A block of the caller for each of its blocks, taking what it takes. + var map := vector::::new(scratch()); + map.resize(callee.origins.length); + var blocks := vector::::new(scratch()); + blocks.resize(callee.blocks.length); + for b in 0..callee.blocks.length { + continue if callee.blocks[b].gone; + val made := body.add_block(); + blocks[b] = made; + continue if b == 0; + for ¶m in callee.blocks[b].params { + map[param] = body.add_param(made, callee.type_of(param)); + } + } + + # The copy begins zeroing its cells, as a call's frame begins zeroed, but for + # those the function's own frame would not zero, as every word of them some + # path reads is written first, and taking its own copy of each parameter held + # in memory. + val entry: u32 = blocks[0]; + var gives: vt[1] = [vt::word]; + var ordered := vector::::new(scratch()); + var places := vector::::new(scratch()); + callee.copy_order(&mut ordered, &mut places); + val writes := this.result_writes(callee_index); + val zeroed := zeroed_cells(callee, ordered.view(), places.view(), writes.view()); + for c in 0..callee.cells.length { + continue if callee.cells[c].kind == ck::undefined || !zeroed[c]; + val address := body.append(entry, op::cell, span::::empty(), gives[0:1], base + c as u32, 0, held.at); + body.insts[address].site = held.site; + var args: u32[1] = [body.insts[address].result]; + val clear := body.append(entry, op::clear, args[0:1], span::::empty(), 0, callee.cells[c].size as u64, held.at); + body.insts[clear].site = held.site; + } + var copies := vector::::new(scratch()); + copies.resize(takes); + for i in 0..takes { + val param: u32 = callee.blocks[0].params[i]; + val arg := body.arg(call, i as u32); + if !memory[i] { + map[param] = arg; + continue; + } + val shape := this.layout_at(layouts[i]); + val cell := body.add_cell(round_up(shape.size, word_size) as u32, + shape.align < word_size ? word_size as u32 : shape.align as u32, ck::inlined, 0); + val address := body.append(entry, op::cell, span::::empty(), gives[0:1], cell, 0, held.at); + body.insts[address].site = held.site; + val copy_of := body.insts[address].result; + var args: u32[2] = [copy_of, arg]; + val copied := body.append(entry, op::copy, args[0:2], span::::empty(), 0, shape.size, held.at); + body.insts[copied].site = held.site; + map[param] = copy_of; + copies[i] = cell + 1; + } + + # Its instructions, in an order each value is made before it is read, each + # one's copy noted. + var copied := vector::::new(scratch()); + copied.resize(callee.insts.length); + val order := &this.program.functions[callee_index].order; + var args := vector::::new(scratch()); + var types := vector::::new(scratch()); + for &b in order.view() { + val into: u32 = blocks[b]; + var walk := callee.walk(b); + while walk.more() { + val at := walk.next(); + val from: inst = callee.insts[at]; + val site := body.site_in(callee, callee_index, &held, &mut sites, from.site); + args.clear(); + for i in 0..from.argc { + args.append(map[callee.arg(at, i as u32)]); + } + + if from.kind == op::ret { + # A return goes on to the rest of the caller's block, giving what it + # returns, or copying the memory it returns where the call said. + if returns_memory { + var copy_args: u32[2] = [dst, args.last()]; + val copied := body.append(into, op::copy, copy_args[0:2], span::::empty(), 0, callee.returned as u64, from.at); + body.insts[copied].site = site; + args.clear(); + } + body.jump_with(into, rest, args.view(), from.at, site); + continue; + } + + types.clear(); + for r in 0..from.count { + types.append(callee.type_of(from.result + r as u32)); + } + val aux := from.kind == op::cell ? from.aux + base : from.aux; + val made := body.append(into, from.kind, args.view(), types.view(), aux, from.imm, from.at); + body.insts[made].site = site; + copied[at] = made; + for r in 0..from.count { + map[from.result + r as u32] = body.insts[made].result + r as u32; + } + + # Its edges, made one after another, go where the copies of their blocks + # are, giving what the copies of their arguments are. + val count := callee.edge_count(at); + if count != 0 { + var first: u32 = 0; + for e in 0..count { + val out := &callee.edges[from.aux + e as u32]; + val copy := body.add_edge(made, blocks[out.target], out.case); + if e == 0 { + first = copy; + } + for &each in out.args { + body.edges[copy].args.append(map[each]); + } + } + body.insts[made].aux = first; + } + } + } + + # Its variables are the caller's too, where it was inlined, held where the + # copies of what held them are, or as the constants their bindings keep. + val first_variable := body.variables.length as u32; + for &each in callee.variables { + var made: variable_info = each; + made.site = body.site_in(callee, callee_index, &held, &mut sites, each.site); + made.first = 0; + made.end = 0; + if each.cell != 0 { + made.cell = base + each.cell; + } else if each.given != 0 { + made.cell = copies[each.given as u64 - 1]; + made.given = 0; + } + body.variables.append(made); + } + for &each in callee.bindings { + val value: u32 = map[each.value]; + var known := each.known; + var bits := each.bits; + if value == 0 && known == vt::none { + known = callee.constant_kind(each.value, &mut bits); + } + continue if value == 0 && known == vt::none; + val gone := each.block == no_block || callee.blocks[each.block].gone; + body.bindings.append(binding { + variable = first_variable + each.variable, + word = each.word, + value = value, + after = each.after != 0 ? copied[each.after] : 0, + block = gone ? no_block : blocks[each.block], + known = known, + bits = bits + }); + } + + # The call goes into the copy. + val edge := body.add_edge(call, entry, 0); + body.become(call, op::jump, span::::empty(), edge, 0); + body.insts[call].count = 0; + body.insts[call].result = 0; + return true; +} + +#! Ends a block jumping to another, giving it values. +#! @param this The code. +#! @param from The block. +#! @param target The block it jumps to. +#! @param args What it gives the target's parameters. +#! @param pos Where in the source the jump is from. +#! @param site One more than the site of the function it was inlined from. +def code::jump_with(&mut this, from: u32, target: u32, args: span, pos: u64, site: u32): void { + val jump := this.append(from, op::jump, span::::empty(), span::::empty(), 0, 0, pos); + this.insts[jump].site = site; + val edge := this.add_edge(jump, target, 0); + this.insts[jump].aux = edge; + for &each in args { + this.edges[edge].args.append(each); + } +} + + +# Inlining the test of an entry. + +#! Finds the way a function's entry only returns, which a call of it may copy +#! with the entry's test, calling the function the other way: the entry ends +#! branching, and before only computes, reads memory, or checks, taking no +#! cell's address, so the call made the other way, running it again, does +#! what the function would have; and one way goes to a block other than the +#! entry that returns, calling nothing and taking no cell's address. The +#! function takes nothing in memory, nor returns memory, so the copy reads +#! only what the call gives. Of two such ways, the one costing less is taken. +#! @param this The compiler. +#! @param index The function. +#! @param cost Where what the test and that way cost is written, counting +#! only what of the entry the test needs, as `head_needs` says. +#! @returns One more than the block it goes to, or 0 where it has none. +def lowerer::short_way(&this, index: u32, cost: &mut u32): u32 { + val held := &this.program.functions[index]; + val body := &held.body; + val last: u32 = body.blocks[0].last; + return 0 if body.returned != 0 || last == 0 || body.insts[last].kind != op::branch; + var memory := vector::::new(scratch()); + var layouts := vector::::new(scratch()); + this.entry_values(held.signature, &mut memory, &mut layouts); + return 0 if memory.length != body.blocks[0].params.length || memory.view().contains(&true); + var walk := body.walk(0); + while walk.more() { + val at := walk.next(); + val kind := body.insts[at].kind; + val traits := kind.traits(); + return 0 if kind == op::cell || (at != last && (traits & op_pure) == 0 && kind != op::load && traits != op_traps); + } + + var found: u32 = 0; + var least: u32 = 0xFFFFFFFF; + val first: u32 = body.insts[last].aux; + for side in 0..2u { + val way: u32 = body.edges[first + side].target; + continue if way == 0 || way == body.edges[first + 1 - side].target; + val end: u32 = body.blocks[way].last; + continue if end == 0 || body.insts[end].kind != op::ret; + var spent: u32 = 0; + var fits := true; + var steps := body.walk(way); + while steps.more() { + val at := steps.next(); + val kind := body.insts[at].kind; + if kind == op::cell || (kind.traits() & op_calls) == op_calls { + fits = false; + break; + } + spent += body.inline_cost(at); + } + continue if !fits; + + var needed := vector::::new(scratch()); + body.head_needs(way, &mut needed); + var entry := body.walk(0); + while entry.more() { + val at := entry.next(); + if needed[at] { + spent += body.inline_cost(at); + } + } + if spent < least { + least = spent; + found = way + 1; + } + } + cost = found != 0 ? least : 0; + return found; +} + +#! Marks which instructions of code's entry the test going to a way that only +#! returns needs: the branch, what may stop the program but a read, what the +#! edge going that way gives, and what the way reads, each with what it reads +#! in turn. The rest only computes, or reads memory, which a copy leaves out +#! where the address read is never zero. +#! @param this The code. +#! @param way The block the way begins at. +#! @param needed Where whether each instruction is needed is written, by +#! its index. +def code::head_needs(&this, way: u32, needed: &mut vector): void { + needed.resize(this.insts.length); + var values := vector::::new(scratch()); + val last: u32 = this.blocks[0].last; + var walk := this.walk(0); + while walk.more() { + val at := walk.next(); + val kind := this.insts[at].kind; + if at == last || ((kind.traits() & op_pure) == 0 && kind != op::load) { + needed[at] = true; + for i in 0..this.insts[at].argc { + values.append(this.arg(at, i as u32)); + } + } + } + val first: u32 = this.insts[last].aux; + for side in 0..2u { + continue if this.edges[first + side].target != way; + for &each in this.edges[first + side].args { + values.append(each); + } + } + var reads := this.reader(); + var steps := this.walk(way); + while steps.more() { + reads.start(steps.next()); + while reads.more() { + values.append(reads.next()); + } + } + + while values.length != 0 { + val value: u32 = values.last(); + values.truncate(); + val made := this.defining(value); + continue if made == 0 || this.insts[made].block != 0 || needed[made]; + needed[made] = true; + for i in 0..this.insts[made].argc { + values.append(this.arg(made, i as u32)); + } + } +} + +#! Whether a call may copy the test of the function it calls and the way it +#! only returns, leaving out what of the entry the test does not need: each +#! read left out reads an address never zero, as the call gives it, so leaving +#! it out never leaves out a stop. +#! @param this The compiler. +#! @param caller The function calling. +#! @param call The `call`. +#! @param way The block the way begins at. +#! @returns Whether it may. +def lowerer::head_fits(&this, caller: u32, call: u32, way: u32): bool { + val body := &this.program.functions[caller].body; + val callee := &this.program.functions[body.insts[call].aux].body; + return false if body.insts[call].argc as u64 != callee.blocks[0].params.length + || body.insts[call].count as u64 != callee.results.length; + var needed := vector::::new(scratch()); + callee.head_needs(way, &mut needed); + var walk := callee.walk(0); + while walk.more() { + val at := walk.next(); + continue if needed[at] || callee.insts[at].kind != op::load; + return false if !never_zero_given(body, call, callee, callee.arg(at, 0)); + } + return true; +} + +#! Whether an address a function's entry reads is never zero where a call +#! gives the function its arguments: a small step past a parameter the call +#! gives an address never zero, or past one the function's code never has zero. +#! @param body The code calling. +#! @param call The `call`. +#! @param callee The code of the function called. +#! @param address The address, in the function's code. +#! @returns Whether it is never zero. +def never_zero_given(body: &code, call: u32, callee: &code, address: u32): bool { + var at := address; + var steps := 0; + while steps < 8 { + val held: origin = callee.origins[at]; + if held.param { + return held.from == 0 && body.never_zero(body.arg(call, held.index)); + } + return callee.never_zero(at) if callee.insts[held.from].kind != op::add; + var step: u64 = 0; + return false if !callee.word_constant(callee.arg(held.from, 1), &mut step) || step >= 0x100000000u; + at = callee.arg(held.from, 0); + steps++; + } + return false; +} + +#! Replaces a call with a copy of the test the entry of the function it calls +#! makes, and of the way the entry only returns, which goes on to the rest of +#! the block; the other way calls the function, which tests again. +#! @param this The compiler. +#! @param caller The function calling. +#! @param call The `call`, which `head_fits` says may be replaced so. +#! @param way The block the way begins at. +#! @param done What reads what the call gave reads instead, applied once +#! every call is inlined. +def lowerer::inline_head(&mut this, caller: u32, call: u32, way: u32, done: &mut rewrite): void { + val callee_index: u32 = this.program.functions[caller].body.insts[call].aux; + val callee := &this.program.functions[callee_index].body; + val body := &mut this.program.functions[caller].body; + val held: inst = body.insts[call]; + val rest := body.split_at(call, done); + var sites := vector::::new(scratch()); + sites.resize(callee.sites.length + 1); + + # The test, of what the entry does that it needs, each value's copy noted. + var needed := vector::::new(scratch()); + callee.head_needs(way, &mut needed); + var map := vector::::new(scratch()); + map.resize(callee.origins.length); + for i in 0..callee.blocks[0].params.length { + map[callee.blocks[0].params[i]] = body.arg(call, i as u32); + } + val head := body.add_block(); + val quick := body.add_block(); + val slow := body.add_block(); + var args := vector::::new(scratch()); + var types := vector::::new(scratch()); + val last: u32 = callee.blocks[0].last; + var walk := callee.walk(0); + while walk.more() { + val at := walk.next(); + continue if !needed[at]; + val from: inst = callee.insts[at]; + val site := body.site_in(callee, callee_index, &held, &mut sites, from.site); + args.clear(); + types.clear(); + for i in 0..from.argc { + args.append(map[callee.arg(at, i as u32)]); + } + for r in 0..from.count { + types.append(callee.type_of(from.result + r as u32)); + } + val made := body.append(head, from.kind, args.view(), types.view(), from.aux, from.imm, from.at); + body.insts[made].site = site; + for r in 0..from.count { + map[from.result + r as u32] = body.insts[made].result + r as u32; + } + continue if at != last; + + # The branch goes the way that only returns, giving its parameters what the + # edge going there gives them, and calls the function the other way. + for side in 0..2u { + val out := &callee.edges[from.aux + side]; + val copy := body.add_edge(made, out.target == way ? quick : slow, 0); + if side == 0 { + body.insts[made].aux = copy; + } + continue if out.target != way; + for p in 0..out.args.length { + map[callee.blocks[way].params[p]] = map[out.args[p]]; + } + } + } + + # The way, whose return goes on to the rest of the block. + var steps := callee.walk(way); + while steps.more() { + val at := steps.next(); + val from: inst = callee.insts[at]; + val site := body.site_in(callee, callee_index, &held, &mut sites, from.site); + args.clear(); + types.clear(); + for i in 0..from.argc { + args.append(map[callee.arg(at, i as u32)]); + } + if from.kind == op::ret { + body.jump_with(quick, rest, args.view(), from.at, site); + break; + } + for r in 0..from.count { + types.append(callee.type_of(from.result + r as u32)); + } + val made := body.append(quick, from.kind, args.view(), types.view(), from.aux, from.imm, from.at); + body.insts[made].site = site; + for r in 0..from.count { + map[from.result + r as u32] = body.insts[made].result + r as u32; + } + } + + # The call the other way, giving the rest what it returns. + args.clear(); + types.clear(); + for i in 0..held.argc { + args.append(body.arg(call, i as u32)); + } + for r in 0..held.count { + types.append(body.type_of(held.result + r as u32)); + } + val again := body.append(slow, op::call, args.view(), types.view(), held.aux, held.imm, held.at); + body.insts[again].site = held.site; + args.clear(); + for r in 0..held.count { + args.append(body.insts[again].result + r as u32); + } + body.jump_with(slow, rest, args.view(), held.at, held.site); + + # The call goes into the test. + val edge := body.add_edge(call, head, 0); + body.become(call, op::jump, span::::empty(), edge, 0); + body.insts[call].count = 0; + body.insts[call].result = 0; +} diff --git a/compiler/optimizer/loops.sakura b/compiler/optimizer/loops.sakura new file mode 100644 index 00000000..e75603a2 --- /dev/null +++ b/compiler/optimizer/loops.sakura @@ -0,0 +1,985 @@ +#! @file loops.sakura +#! @author John Christman (sorakatadzuma@gmail.com) +#! @copyright Malunal Studios, LLC. +#! @license MIT +#! +#! Contains the ninth pass of the optimizer, which works on loops. A loop is +#! natural: its header dominates each block whose edge goes back to it, and it +#! holds the blocks from which those are reached without passing the header. +#! +#! A loop whose header asks whether to go round again, where no block going +#! back to it asks so too, is rotated: the header's code is copied into a guard +#! before the loop, which goes into it or past it as the header would have the +#! first time, and the header itself moves to the bottom, asking each time +#! round whether to go round again. Its edge back to the block after it is then +#! the loop's only jump. What the header made and the loop read is what the +#! block after it takes, from the guard's copy or from the header, as is what +#! it made and code past the loop read, where that is past the way out. +#! +#! Then what each loop works out the same each time round moves into the block +#! before it, its preheader, which is made where the loop has none: what only +#! works out its value from what is made outside the loop, and cannot stop the +#! program; a read of memory nothing in the loop may write, as alias analysis +#! tells, through an address read or written through, or checked, before the +#! loop; and a check of what is made outside the loop, or such a read through +#! an address that may be null, where it runs each time the loop is gone into +#! before anything the program would be seen to do in it, so that it stops the +#! program where it would have, and only where the loop is gone into. Inner +#! loops go first, so what moves out of one may move out of the loop holding it +#! in turn. + +import std::containers; +module sakura::compiler; + + +#! What stands for no loop. +const no_loop: u32 = 0xFFFFFFFF; + +#! The most instructions a header copied into a guard may hold, but for its +#! constants and the branch ending it. +const rotate_limit: u32 = 12; + +#! The most loops of one function rotated, past which the rest stay as they +#! are. +const rotate_most: u32 = 256; + +#! The natural loops of code. Two loops hold no block in common, or one holds +#! the other. +struct loop_nest { + var headers: vector; #! The block heading each loop, those holding fewer blocks first, so each comes before the loops holding it. + var parents: vector; #! The loop most nearly holding each loop, or `no_loop`. + var members: runs; #! The blocks of the loops, a run each, its header first. + var runs_of: vector; #! The run of `members` holding each loop's blocks. + var inner: vector; #! The loop most nearly holding each block, by block, or `no_loop`. +} + +#! Whether a loop holds a block. +#! @param this The loops. +#! @param loop The loop. +#! @param block The block, which may be newer than the loops, and so in none. +#! @returns Whether it does. +def loop_nest::holds(&this, loop: u32, block: u32): bool { + var at: u32 = (block as u64) < this.inner.length ? this.inner[block] : no_loop; + # A loop holding another comes after it. + while at != no_loop && at <= loop { + return true if at == loop; + at = this.parents[at]; + } + return false; +} + +#! Which block dominates which, and the natural loops, as a pass over loops +#! asks of them. +struct loop_view { + var order: vector; #! The blocks in reverse postorder. + var number: vector; #! Each block's place in that order. + var idom: vector; #! The immediate dominator of each block. + var first: vector; #! The first block each block immediately dominates, or `no_block`. + var after: vector; #! The next block the immediate dominator of each immediately dominates, or `no_block`. + var nest: loop_nest; #! The natural loops. +} + +#! A value a header makes that is read outside it, which rotating has read +#! what stands for it there. +struct header_read { + var place: u64; #! Where it is read: an operand's place among the code's operands, or an argument's among its edge's. + var edge: u32; #! The edge whose argument it is, or `no_block` for an operand. + var slot: u32; #! Which of the values the header makes it is. + var past: bool; #! Whether it is read past the way out of the loop, rather than past the way in. +} + +#! Optimizes the loops of a function's code, knowing what each call writes +#! what it returns to. +#! @param this The compiler. +#! @param index The function. +#! @returns Whether anything changed. +def lowerer::optimize_loops(&mut this, index: u32): bool { + val writes := this.result_writes(index); + return this.program.functions[index].body.optimize_loops(writes.view()); +} + +#! Optimizes the loops of the code, as the file says: rotating each that may +#! be, then moving out of each what it works out the same each time round. +#! @param this The code. +#! @param writes Of each instruction, the bytes a call writes what it returns +#! to at its last operand, or 0. +#! @returns Whether anything changed. +pub def code::optimize_loops(&mut this, writes: span): bool { + # Rotating a loop changes which block dominates which, so the loops are + # found again after each, but after the last that may rotate. A loop found + # not to rotate is not asked again. Code found to have no loops has nothing + # to move out of them either. + var refused := vector::::new(scratch()); + var rotated: u32 = 0; + var looped := true; + var last := false; + while rotated < rotate_most && !last { + refused.resize(this.blocks.length); + val point := mark_scratch(); + val more := this.rotate_one(&mut refused, &mut looped, &mut last); + release_scratch(point); + break if !more; + rotated++; + } + return rotated != 0 if !looped; + return this.hoist_invariants(writes) || rotated != 0; +} + +#! Finds which block dominates which, and the natural loops, from the order +#! and dominators the code keeps where it keeps them. +#! @param this The code. +#! @returns What was found, in scratch memory. +def code::view_loops(&mut this): loop_view { + var made := loop_view { + order = vector::::new(scratch()), + number = vector::::new(scratch()), + idom = vector::::new(scratch()), + first = vector::::new(scratch()), + after = vector::::new(scratch()) + }; + this.block_order(&mut made.order, &mut made.number); + made.idom = this.block_dominators(); + made.first.resize(this.blocks.length, no_block); + made.after.resize(this.blocks.length, no_block); + var k := made.order.length; + while k > 1 { + k--; + val block: u32 = made.order[k]; + val parent: u32 = made.idom[block]; + made.after[block] = made.first[parent]; + made.first[parent] = block; + } + made.nest = this.find_loops(made.order.view(), made.number.view(), &made.idom); + return made; +} + +#! Finds the natural loops of the code: each block an edge goes back to from a +#! block it dominates heads one, holding the blocks from which those edges are +#! reached without passing it. +#! @param this The code. +#! @param order The blocks in reverse postorder. +#! @param number Each block's place in that order. +#! @param idom The immediate dominator of each block. +#! @returns The loops, in scratch memory. +pub def code::find_loops(&this, order: span, number: span, idom: &vector): loop_nest { + var nest := loop_nest { + headers = vector::::new(scratch()), + parents = vector::::new(scratch()), + members = runs::::new(scratch()), + runs_of = vector::::new(scratch()), + inner = vector::::new(scratch()) + }; + nest.inner.resize(this.blocks.length, no_loop); + + # Where no edge goes to a block at or before the block it leaves in the + # order, none goes back, and there is no loop. + var back := false; + for &block in order { + for &edge in this.blocks[block].preds { + val from := this.edge_source(edge); + back = back || (number[from] != 0xFFFFFFFF && number[from] >= number[block]); + } + } + return nest if !back; + + # Each loop as it is found, its header first among its blocks, in the order + # the headers are in. + var heads := vector::::new(scratch()); + var found := vector::::new(scratch()); + var marks := stamped_set::new(this.blocks.length, scratch()); + var todo := vector::::new(scratch()); + for &block in order { + var any := false; + marks.next_round(); + for &edge in this.blocks[block].preds { + val from := this.edge_source(edge); + continue if number[from] == 0xFFFFFFFF || number[from] < number[block] || !dominates(idom, block, from); + if !any { + any = true; + marks.put(block); + nest.members.push(block); + } + if marks.insert(from) { + nest.members.push(from); + todo.append(from); + } + } + continue if !any; + while todo.length != 0 { + val at: u32 = todo.last(); + todo.truncate(); + for &edge in this.blocks[at].preds { + val back := this.edge_source(edge); + if number[back] != 0xFFFFFFFF && marks.insert(back) { + nest.members.push(back); + todo.append(back); + } + } + } + heads.append(block); + found.append(nest.members.end()); + } + + # The loops holding fewer blocks first, then in the order found, so each + # comes before those holding it. The largest first, each says which it is + # most nearly held by, as the loop holding its header is then. + var keys := vector::::new(scratch()); + for i in 0..heads.length { + keys.append(pair_key(nest.members.length(found[i]) as u32, i as u32)); + } + keys.sort(); + for &key in keys { + nest.headers.append(heads[pair_low(key)]); + nest.runs_of.append(found[pair_low(key)]); + } + val count := nest.headers.length; + nest.parents.resize(count, no_loop); + var k := count; + while k > 0 { + k--; + nest.parents[k] = nest.inner[nest.headers[k]]; + for &block in nest.members.view(nest.runs_of[k]) { + nest.inner[block] = k as u32; + } + } + return nest; +} + + +# Rotation. + +#! Rotates the first loop that may be rotated, innermost loops first. +#! @param this The code. +#! @param refused Whether each block heads a loop found not to rotate. +#! @param looped Where whether the code has any loop is written. +#! @param last Where whether no other loop may rotate is written. +#! @returns Whether one was. +def code::rotate_one(&mut this, refused: &mut vector, looped: &mut bool, last: &mut bool): bool { + val view := this.view_loops(); + looped = view.nest.headers.length != 0; + for k in 0..view.nest.headers.length { + val header: u32 = view.nest.headers[k]; + continue if refused[header]; + if this.rotate(&view, k as u32) { + this.forget_order(); + # The loop rotated is headed by the block after its header now, which + # does not rotate: it only jumps on, or the header, going back to it, + # leaves the loop too. So where every other loop was found not to + # rotate, none may. + var others := false; + for j in 0..view.nest.headers.length { + others = others || (j != k && !refused[view.nest.headers[j]]); + } + last = !others; + return true; + } + refused[header] = true; + } + return false; +} + +#! Rotates a loop, as the file says, where its header asks whether to go round +#! again, no edge back into it is from a block asking so too, as each is once +#! the loop is rotated, and it holds few instructions. Each value the header +#! makes that is read outside it must be read where the block after it in the +#! loop dominates, or where the block it leaves to does, every edge into which +#! is then from the header or from where the block after it dominates. +#! @param this The code. +#! @param view Which block dominates which, and the loops. +#! @param loop The loop. +#! @returns Whether it was rotated. +def code::rotate(&mut this, view: &loop_view, loop: u32): bool { + val nest := &view.nest; + val header: u32 = nest.headers[loop]; + val last: u32 = this.blocks[header].last; + return false if last == 0 || this.insts[last].kind != op::branch; + val one: u32 = this.insts[last].aux; + val first_in := nest.holds(loop, this.edges[one].target); + return false if first_in == nest.holds(loop, this.edges[one + 1].target); + val stay := first_in ? one : one + 1; + val leave := first_in ? one + 1 : one; + val into: u32 = this.edges[stay].target; + val out: u32 = this.edges[leave].target; + return false if into == header; + for &edge in this.blocks[header].preds { + val from := this.edges[edge].from; + continue if !nest.holds(loop, this.insts[from].block); + var outs := this.edges_of(from); + while outs.more() { + return false if !nest.holds(loop, this.edges[outs.next()].target); + } + } + var size: u32 = 0; + var sized := this.walk(header); + while sized.more() { + val at := sized.next(); + val kind := this.insts[at].kind; + continue if at == last || kind == op::iconst || kind == op::fconst; + size++; + return false if size > rotate_limit; + } + + # The values the header makes, its parameters first, each one more than its + # slot among them by value. Its constants go into the entry, where both it + # and the guard read them. + var slots := vector::::new(scratch()); + slots.resize(this.origins.length); + var made := vector::::new(scratch()); + for ¶m in this.blocks[header].params { + made.append(param); + slots[param] = made.length as u32; + } + var walk := this.walk(header); + while walk.more() { + val held: inst = this.insts[walk.next()]; + continue if held.kind.made_anywhere(); + for r in 0..held.count { + made.append(held.result + r as u32); + slots[held.result + r as u32] = made.length as u32; + } + } + + # Where each is read outside the header, and whether past the way in or out: + # within what the header dominates, as what reads a value is. + var reads := vector::::new(scratch()); + var inside := vector::::new(scratch()); + var past := vector::::new(scratch()); + inside.resize(made.length); + past.resize(made.length); + var below := vector::::new(scratch()); + var child: u32 = view.first[header]; + while child != no_block { + below.append(child); + child = view.after[child]; + } + var next_below: u64 = 0; + while next_below < below.length { + val b: u32 = below[next_below]; + next_below++; + child = view.first[b]; + while child != no_block { + below.append(child); + child = view.after[child]; + } + var side: u8 = 0; + var each := this.walk(b); + while each.more() { + val at := each.next(); + val held: inst = this.insts[at]; + for i in 0..held.argc { + val place := held.args as u64 + i as u64; + val slot: u32 = slots[this.operands[place]]; + continue if slot == 0; + side = side == 0 ? this.side_of(view, into, out, b) : side; + return false if side == 3; + reads.append(header_read { place = place, edge = no_block, slot = slot - 1, past = side == 2 }); + } + } + # Only the last instruction of a block leaves it by edges. + var outs := this.edges_of(this.blocks[b].last); + while outs.more() { + val edge := outs.next(); + for a in 0..this.edges[edge].args.length { + val slot: u32 = slots[this.edges[edge].args[a]]; + continue if slot == 0; + side = side == 0 ? this.side_of(view, into, out, b) : side; + return false if side == 3; + reads.append(header_read { place = a, edge = edge, slot = slot - 1, past = side == 2 }); + } + } + } + var any_past := false; + for &read in reads { + if read.past { + past[read.slot] = true; + any_past = true; + } else { + inside[read.slot] = true; + } + } + # The block left to takes what the header made where it is read past it, + # which each edge into it gives: the header, and the guard's copy, and from + # within the loop, what the block after the header took. + var exits := this.blocks[out].preds.copied(scratch()); + val leaving := this.edges[leave].args.copied(scratch()); + val staying := this.edges[stay].args.copied(scratch()); + if any_past { + for &edge in exits { + continue if edge == leave; + return false if !dominates(&view.idom, into, this.edge_source(edge)); + for s in 0..made.length { + inside[s] = inside[s] || past[s]; + } + } + } + + # The block after the header in the loop takes what the loop reads of what + # the header made; where other edges go into it too, a block of its own, + # going on to it, does. + var after := into; + var given := vector::::new(scratch()); + if this.blocks[into].preds.length != 1 { + after = this.add_block(); + for p in 0..this.blocks[into].params.length { + given.append(this.add_param(after, this.type_of(this.blocks[into].params[p]))); + } + } + var taken := vector::::new(scratch()); + taken.resize(made.length); + var left := vector::::new(scratch()); + left.resize(made.length); + for s in 0..made.length { + if inside[s] { + taken[s] = this.add_param(after, this.type_of(made[s])); + } + if past[s] { + left[s] = this.add_param(out, this.type_of(made[s])); + } + } + for &edge in exits { + for s in 0..made.length { + continue if !past[s]; + val given_out: u32 = edge == leave ? made[s] : taken[s]; + this.edges[edge].args.append(given_out); + } + } + + # The header's constants go first in the entry. + var prior: u32 = 0; + var moving := this.walk(header); + while moving.more() { + val at := moving.next(); + if !this.insts[at].kind.made_anywhere() { + prior = at; + continue; + } + if prior == 0 { + this.blocks[header].first = this.insts[at].next; + } else { + this.insts[prior].next = this.insts[at].next; + } + this.put_first(0, at); + } + + # The guard takes what the header took from outside the loop, and copies its + # code, each copy reading the copies of what the header made. Where one edge + # goes into the loop, the guard reads what it gives instead. + val guard := this.add_block(); + var copies := vector::::new(scratch()); + copies.resize(made.length); + var entries := vector::::new(scratch()); + for &edge in this.blocks[header].preds { + if !nest.holds(loop, this.edge_source(edge)) { + entries.append(edge); + } + } + for p in 0..this.blocks[header].params.length { + if entries.length == 1 { + copies[p] = this.edges[entries[0]].args[p]; + } else { + copies[p] = this.add_param(guard, this.type_of(this.blocks[header].params[p])); + } + } + for &edge in entries { + this.drop_pred(edge); + this.edges[edge].target = guard; + this.blocks[guard].preds.append(edge); + if entries.length == 1 { + this.edges[edge].args.clear(); + } + } + var pairs := vector::::new(scratch()); + var args := vector::::new(scratch()); + var types := vector::::new(scratch()); + var copying := this.walk(header); + while copying.more() { + val at := copying.next(); + break if at == last; + val from: inst = this.insts[at]; + args.clear(); + for i in 0..from.argc { + args.append(copy_of_read(&slots, &copies, this.arg(at, i as u32))); + } + types.clear(); + for r in 0..from.count { + types.append(this.type_of(from.result + r as u32)); + } + val copy := this.append(guard, from.kind, args.view(), types.view(), from.aux, from.imm, from.at); + this.insts[copy].site = from.site; + for r in 0..from.count { + copies[slots[from.result + r as u32] - 1] = this.insts[copy].result + r as u32; + } + pairs.append(pair_key(at, copy)); + } + + # The guard goes into the loop through a preheader, or out as the header + # would have the first time. + val pre := this.add_block(); + var cond: u32[1] = [copy_of_read(&slots, &copies, this.arg(last, 0))]; + val test := this.append(guard, op::branch, cond[0:1], span::::empty(), 0, 0, this.insts[last].at); + this.insts[test].site = this.insts[last].site; + val first := this.add_edge(test, first_in ? pre : out, 0); + this.add_edge(test, first_in ? out : pre, 0); + this.insts[test].aux = first; + val past_guard := first_in ? first + 1 : first; + for &each in leaving { + this.edges[past_guard].args.append(copy_of_read(&slots, &copies, each)); + } + for s in 0..made.length { + if past[s] { + this.edges[past_guard].args.append(copies[s]); + } + } + val jump := this.append(pre, op::jump, span::::empty(), span::::empty(), 0, 0, this.insts[last].at); + this.insts[jump].site = this.insts[last].site; + val going := this.add_edge(jump, after, 0); + this.insts[jump].aux = going; + for &each in staying { + this.edges[going].args.append(copy_of_read(&slots, &copies, each)); + } + + # The header, now the bottom of the loop, gives the block after it what it + # made. + if after != into { + this.drop_pred(stay); + this.edges[stay].target = after; + this.blocks[after].preds.append(stay); + val on := this.append(after, op::jump, span::::empty(), span::::empty(), 0, 0, this.insts[last].at); + this.insts[on].site = this.insts[last].site; + val edge := this.add_edge(on, into, 0); + this.insts[on].aux = edge; + for &each in given { + this.edges[edge].args.append(each); + } + } + for s in 0..made.length { + if inside[s] { + this.edges[stay].args.append(made[s]); + this.edges[going].args.append(copies[s]); + } + } + + # What read what the header made reads what stands for it. + for &read in reads { + val value: u32 = read.past ? left[read.slot] : taken[read.slot]; + if read.edge == no_block { + this.operands[read.place] = value; + } else { + var held := this.edges[read.edge].args.slice(); + held[read.place] = value; + } + } + this.rebind_rotated(view, header, guard, into, out, &slots, &copies, &taken, &left, pairs.view()); + return true; +} + +#! Whether an operation makes a constant, or the address of a cell, a global, +#! or a datum, which may be made anywhere, and which constant hoisting moves +#! out of loops into the entry. +#! @param this The operation. +#! @returns Whether it does. +def op::made_anywhere(&this): bool { + return match this { + op::iconst, op::fconst, op::cell, op::global, op::datum => true, + else => false + }; +} + +#! Which side of a loop being rotated a block reading what its header made is. +#! @param this The code. +#! @param view Which block dominates which, and the loops. +#! @param into The block after the header in the loop. +#! @param out The block the header leaves the loop to. +#! @param block The block. +#! @returns 1 where the block after the header dominates it, 2 where the block +#! left to does, and 3 where neither does. +def code::side_of(&this, view: &loop_view, into: u32, out: u32, block: u32): u8 { + return 1 if dominates(&view.idom, into, block); + return 2 if dominates(&view.idom, out, block); + return 3; +} + +#! What the guard's copy of a header reads where the header read a value: the +#! copy of what the header made, or the value itself. +#! @param slots One more than each value's slot among those the header +#! made, or 0. +#! @param copies The guard's copy of each value the header made. +#! @param value The value. +#! @returns The value read. +def copy_of_read(slots: &vector, copies: &vector, value: u32): u32 { + return value if value as u64 >= slots.length || slots[value] == 0; + return copies[slots[value] - 1]; +} + +#! Binds the variables a rotated loop's header bound in the guard too, to the +#! copies, and those bound where the parameters standing for what the header +#! made are read, to those parameters. +#! @param this The code. +#! @param view Which block dominated which before the loop was rotated. +#! @param header The header. +#! @param guard The guard. +#! @param into The block after the header in the loop. +#! @param out The block the header leaves the loop to. +#! @param slots One more than each value's slot among those the header +#! made, or 0. +#! @param copies The guard's copy of each value the header made. +#! @param taken What the block after the header takes for each, or 0. +#! @param left What the block left to takes for each, or 0. +#! @param pairs Each instruction of the header with its copy, as +#! `pair_key(instruction, copy)`. +def code::rebind_rotated( + &mut this, + view: &loop_view, + header: u32, + guard: u32, + into: u32, + out: u32, + slots: &vector, + copies: &vector, + taken: &vector, + left: &vector, + pairs: span +): void { + val count := this.bindings.length; + for i in 0..count { + val each: binding = this.bindings[i]; + continue if each.block == no_block || each.block as u64 >= view.idom.length || this.blocks[each.block].gone; + if each.block == header { + var copy: binding = each; + copy.block = guard; + copy.value = copy_of_read(slots, copies, each.value); + copy.after = 0; + for &pair in pairs { + if pair_high(pair) == each.after { + copy.after = pair_low(pair); + } + } + this.bindings.append(copy); + continue; + } + continue if each.value as u64 >= slots.length || slots[each.value] == 0; + val slot := slots[each.value] - 1; + if taken[slot] != 0 && dominates(&view.idom, into, each.block) { + this.bindings[i].value = taken[slot]; + } else if left[slot] != 0 && dominates(&view.idom, out, each.block) { + this.bindings[i].value = left[slot]; + } + } +} + + + +# Hoisting. + +#! What moving out of loops knows of the code as it goes. +struct hoisting { + var reached: hashset; #! Each address read or written through, or checked not null, with the block it is so in, as `pair_key(address, block)`. + var moved: stamped_set; #! The instructions moved out of the loop worked on, a round each loop. + var aliases: aliases; #! What may write what. + var writers: vector; #! What each instruction writing memory in the loop worked on writes. + var before: u32; #! The block most nearly dominating the loop's header. +} + +#! Moves what each loop works out the same each time round into its +#! preheader, inner loops first, as the file says. A loop with something to +#! move but no block before it that only jumps into it is given one first. +#! @param this The code. +#! @param writes Of each instruction, the bytes a call writes what it returns +#! to at its last operand, or 0. +#! @returns Whether anything moved. +def code::hoist_invariants(&mut this, writes: span): bool { + var view := this.view_loops(); + return false if view.nest.headers.length == 0; + var state := hoisting { + reached = this.reached_addresses(&view), + moved = stamped_set::new(this.insts.length + view.nest.headers.length, scratch()), + aliases = this.aliases(writes, view.idom.view()), + writers = vector::::new(scratch()) + }; + var made := false; + for k in 0..view.nest.headers.length { + continue if this.preheader_of(&view, k as u32) != no_block; + continue if !this.hoist_loop(&view, k as u32, no_block, &mut state); + this.make_preheader(&view, k as u32); + made = true; + } + if made { + this.forget_order(); + view = this.view_loops(); + state.aliases = this.aliases(writes, view.idom.view()); + } + + var changed := false; + for k in 0..view.nest.headers.length { + val pre := this.preheader_of(&view, k as u32); + continue if pre == no_block; + changed = this.hoist_loop(&view, k as u32, pre, &mut state) || changed; + } + return changed; +} + +#! Every address read or written through, or checked not null, with the block +#! it is so in, of those a read within a loop reads through, which are all that +#! is asked of. Reaching through null stops the program, so an address so in a +#! block dominating another is not null there. An instruction moving moves to +#! a block dominating the one it was in, where it is so still. +#! @param this The code. +#! @param view Which block dominates which, and the loops. +#! @returns Each, as `pair_key(address, block)`, in scratch memory. +def code::reached_addresses(&this, view: &loop_view): hashset { + var made := hashset::::new(scratch()); + var asked := vector::::new(scratch()); + asked.resize(this.origins.length); + var any := false; + for &block in view.order { + continue if view.nest.inner[block] == no_loop; + var inside := this.walk(block); + while inside.more() { + val at := inside.next(); + if this.insts[at].kind == op::load { + asked[this.arg(at, 0)] = true; + any = true; + } + } + } + return made if !any; + + var walk := this.walk_all(); + while walk.more() { + val at := walk.next(); + val held: inst = this.insts[at]; + val sized := (held.kind == op::copy || held.kind == op::clear) && held.imm != 0; + if (held.kind == op::load || held.kind == op::store || sized + || (held.kind == op::check && held.aux == fault::null_reference as u32)) && asked[this.arg(at, 0)] { + made.insert(pair_key(this.arg(at, 0), held.block)); + } + if held.kind == op::copy && sized && asked[this.arg(at, 1)] { + made.insert(pair_key(this.arg(at, 1), held.block)); + } + } + return made; +} + +#! Whether an address is not null where a block ends: it is never zero, or is +#! read or written through, or checked, in that block or one dominating it. +#! @param this The code. +#! @param view Which block dominates which, and the loops. +#! @param reached Each address read or written through, or checked, with +#! the block it is so in. +#! @param address The address. +#! @param block The block. +#! @returns Whether it is. +def code::reached_before(&this, view: &loop_view, reached: &hashset, address: u32, block: u32): bool { + return true if this.never_zero(address); + val home := this.home_of(address); + var at := block; + var steps := 0; + while steps < 64 && at != no_block && (at as u64) < view.idom.length { + val key := pair_key(address, at); + return true if reached.contains(&key); + return false if at == home || at == 0; + at = view.idom[at]; + steps++; + } + return false; +} + +#! The preheader of a loop: the one block outside it going into its header, +#! where that block only jumps there. +#! @param this The code. +#! @param view Which block dominates which, and the loops. +#! @param loop The loop. +#! @returns The block, or `no_block` where the loop has none. +def code::preheader_of(&this, view: &loop_view, loop: u32): u32 { + val header: u32 = view.nest.headers[loop]; + var found := no_block; + for &edge in this.blocks[header].preds { + val from := this.edge_source(edge); + continue if view.nest.holds(loop, from); + return no_block if found != no_block; + found = from; + } + return no_block if found == no_block || this.insts[this.blocks[found].last].kind != op::jump; + return found; +} + +#! Makes a preheader for a loop: a block taking what its header took from +#! outside it, every edge from outside going there, which jumps into the +#! header giving it that. +#! @param this The code. +#! @param view Which block dominates which, and the loops. +#! @param loop The loop. +def code::make_preheader(&mut this, view: &loop_view, loop: u32): void { + val header: u32 = view.nest.headers[loop]; + val pre := this.add_block(); + var given := vector::::new(scratch()); + for p in 0..this.blocks[header].params.length { + given.append(this.add_param(pre, this.type_of(this.blocks[header].params[p]))); + } + var entries := vector::::new(scratch()); + for &edge in this.blocks[header].preds { + if !view.nest.holds(loop, this.edge_source(edge)) { + entries.append(edge); + } + } + for &edge in entries { + this.drop_pred(edge); + this.edges[edge].target = pre; + this.blocks[pre].preds.append(edge); + } + val first: u32 = this.blocks[header].first; + val jump := this.append(pre, op::jump, span::::empty(), span::::empty(), 0, 0, this.insts[first].at); + this.insts[jump].site = this.insts[first].site; + val edge := this.add_edge(jump, header, 0); + this.insts[jump].aux = edge; + for &each in given { + this.edges[edge].args.append(each); + } +} + +#! Moves what a loop works out the same each time round into its preheader, in +#! the order the loop worked it out, or only finds whether anything would move. +#! The blocks running first each time the loop is gone into, its header and +#! each a jump goes on to in turn, run what may stop the program before +#! anything the program would be seen to do, until one of those that does not +#! move. +#! @param this The code. +#! @param view Which block dominates which, and the loops. +#! @param loop The loop. +#! @param pre The preheader, or `no_block` to only find whether anything +#! would move. +#! @param state What moving out of loops knows. +#! @returns Whether anything moved, or would. +def code::hoist_loop(&mut this, view: &loop_view, loop: u32, pre: u32, state: &mut hoisting): bool { + val nest := &view.nest; + val header: u32 = nest.headers[loop]; + var keys := vector::::new(scratch()); + for &block in nest.members.view(nest.runs_of[loop]) { + keys.append(pair_key(view.number[block], block)); + } + keys.sort(); + state.moved.next_round(); + state.before = view.idom[header]; + state.writers.clear(); + for &key in keys { + var walk := this.walk(pair_low(key)); + while walk.more() { + val at := walk.next(); + val kind := this.insts[at].kind; + if kind != op::load && (kind.traits() & op_write) != 0 { + state.writers.append(state.aliases.writes_of(this, at)); + } + } + } + + # The blocks running first, each jumping to the next. + var firsts := vector::::new(scratch()); + var at := header; + while true { + firsts.append(at); + val last: u32 = this.blocks[at].last; + break if this.insts[last].kind != op::jump; + at = this.edges[this.insts[last].aux].target; + break if !nest.holds(loop, at) || firsts.view().contains(&at); + } + + var any := false; + var seen := false; + var tail: u32 = 0; + for &key in keys { + val block := pair_low(key); + val first := firsts.view().contains(&block); + var prior: u32 = 0; + var walk := this.walk(block); + while walk.more() { + val index := walk.next(); + if this.invariant(index, view, loop, state, first && !seen) { + any = true; + state.moved.put(index); + continue if pre == no_block; + # It leaves its block, and follows what moved before it, but for a + # constant or the address of a cell, a global, or a datum, which goes + # first in the entry, as constant hoisting would put it. + val next: u32 = this.insts[index].next; + if prior == 0 { + this.blocks[block].first = next; + } else { + this.insts[prior].next = next; + } + if this.insts[index].kind.made_anywhere() { + this.put_first(0, index); + continue; + } + if tail == 0 { + this.link_before(index, this.blocks[pre].last); + } else { + this.link_after(index, tail); + } + tail = index; + continue; + } + if first && this.seen_to_run(index, view, state) { + seen = true; + } + prior = index; + } + } + return any; +} + +#! Whether an instruction of a loop works out the same each time round and may +#! move into the preheader: everything it reads is made outside the loop, or +#! moves; and it works out only its values, but for a division by zero; it +#! reads memory nothing in the loop writes, through an address not null before +#! the loop, or where it runs first; or it is a check, where it runs first. +#! @param this The code. +#! @param index The instruction. +#! @param view Which block dominates which, and the loops. +#! @param loop The loop. +#! @param state What moving out of loops knows. +#! @param first Whether it runs each time the loop is gone into before +#! anything the program would be seen to do in it. +#! @returns Whether it may. +def code::invariant(&this, index: u32, view: &loop_view, loop: u32, state: &hoisting, first: bool): bool { + val held: inst = this.insts[index]; + return false if held.kind.ends() || (held.count == 0 && held.kind != op::check); + for i in 0..held.argc { + val value := this.arg(index, i as u32); + val from := this.defining(value); + continue if from != 0 && state.moved.contains(from); + return false if view.nest.holds(loop, this.home_of(value)); + } + return match held.kind { + op::check => first, + op::load => !this.written_in_loop(index, state) && (first || this.reached_before(view, &state.reached, this.arg(index, 0), state.before)), + else => this.removable(index) + }; +} + +#! Whether anything in the loop worked on may write what a read reads. +#! @param this The code. +#! @param index The `load`. +#! @param state What moving out of loops knows. +#! @returns Whether it may. +def code::written_in_loop(&this, index: u32, state: &hoisting): bool { + return false if state.writers.length == 0; + val place := state.aliases.region_of(this, index, 0); + for &each in state.writers { + return true if state.aliases.touches(this, &each, &place); + } + return false; +} + +#! Whether an instruction that does not move does what the program would be +#! seen to do: writing memory, calling, or what may stop the program, as a read +#! through an address that may be null before the loop. +#! @param this The code. +#! @param index The instruction. +#! @param view Which block dominates which, and the loops. +#! @param state What moving out of loops knows. +#! @returns Whether it does. +def code::seen_to_run(&this, index: u32, view: &loop_view, state: &hoisting): bool { + val held := &this.insts[index]; + return !this.reached_before(view, &state.reached, this.arg(index, 0), state.before) if held.kind == op::load; + return (held.kind.traits() & (op_traps | op_write)) != 0 && !this.removable(index); +} diff --git a/compiler/optimizer/memory.sakura b/compiler/optimizer/memory.sakura new file mode 100644 index 00000000..c64ec9a2 --- /dev/null +++ b/compiler/optimizer/memory.sakura @@ -0,0 +1,500 @@ +#! @file memory.sakura +#! @author John Christman (sorakatadzuma@gmail.com) +#! @copyright Malunal Studios, LLC. +#! @license MIT +#! +#! Contains the eighth pass of the optimizer, which cleans up what the code does +#! with the memory of its cells, of which building values and inlining leave +#! much. Where each cell is known to hold zero is followed through the blocks, +#! from what the frame zeroes and what the blocks before each leave: clearing +#! what is zero already, or storing zero to it, goes; copying from what is zero +#! clears instead; and reading it reads the zero. A clear whose bytes are all +#! written before anything reads them goes. Then a copy into the memory a +#! function returns, right before it returns, is returned from where it was +#! copied from. +#! +#! A cell whose address goes anywhere but to the instructions reading, writing, +#! copying, and clearing it, or to a call as where to write what it returns, is +#! escaped, as alias analysis finds: anything that may read or write memory the +#! code does not name may read or write it, but for what reaches through an +#! address outside the frame. + +module sakura::compiler; + + +#! The most words of a cell the pass follows, a bit each. +const memory_words: u64 = 64; + +#! What stands for a cell the pass does not follow. +const unfollowed: u32 = 0xFFFFFFFF; + +#! The most words the ends of the blocks may take, past which no block begins +#! knowing what the blocks before it left. +const memory_ends_limit: u64 = 1048576; + +#! What the pass knows of the cells of the code. +struct memory_known { + var addresses: cell_table; #! Which cell each value is the address of. + var escaped: vector; #! Whether each cell's address goes where it may be read or written without the code saying. + var place: vector; #! The place of each cell among those followed, or `unfollowed`. + var cells: vector; #! The cell followed at each place. + var exposed: vector; #! The places of the escaped cells followed. + var zero: vector; #! The words known zero of each cell followed, where the walk is, a bit each. + var clears: vector; #! Of each cell followed, the clear of it nothing has read since, or 0. + var cleared: vector; #! The words that clear zeroes. + var covered: vector; #! The words of it written whole since. + var ends: vector; #! The words known zero where each block ends, a word for each place, block after block. + var walked: vector; #! Whether each block was walked. + var zeros: zero_values; #! The zero of each type, made once. +} + +#! The place among those followed of the cell an address is. +#! @param this What the pass knows. +#! @param value The address. +#! @returns The place, or `unfollowed`. +def memory_known::followed(&this, value: u32): u32 { + val cell := this.addresses.cell(value); + return cell == 0 ? unfollowed : this.place[cell - 1]; +} + +#! Says a cell was read, so the clear of it nothing had read stays. +#! @param this What the pass knows. +#! @param place The cell's place. +def memory_known::read(&mut this, place: u32): void { + this.clears[place] = 0; +} + +#! Says memory the code does not name was read, which may be any escaped cell. +#! @param this What the pass knows. +def memory_known::read_escaped(&mut this): void { + for &k in this.exposed { + this.clears[k] = 0; + } +} + +#! Says memory the code does not name was written, which may be any escaped +#! cell, so none is known zero. +#! @param this What the pass knows. +def memory_known::forget_escaped(&mut this): void { + for &k in this.exposed { + this.zero[k] = 0; + } +} + +#! Says words of a cell were written whole, taking out the clear of it they +#! write over all of. +#! @param this What the pass knows. +#! @param place The cell's place. +#! @param words The words, a bit each. +#! @param done What the pass changes. +def memory_known::cover(&mut this, place: u32, words: u64, done: &mut rewrite): void { + return if this.clears[place] == 0; + this.covered[place] = this.covered[place] | words; + if (this.covered[place] & this.cleared[place]) == this.cleared[place] { + done.remove(this.clears[place]); + this.clears[place] = 0; + } +} + +#! Says a cell was cleared by an instruction that stays. +#! @param this What the pass knows. +#! @param place The cell's place. +#! @param index The clear. +#! @param size How many bytes it clears. +#! @param done What the pass changes. +def memory_known::clear(&mut this, place: u32, index: u32, size: u64, done: &mut rewrite): void { + val whole := whole_words(0, size); + this.cover(place, whole, done); + this.clears[place] = index; + this.cleared[place] = touched_words(0, size); + this.covered[place] = 0; + this.zero[place] = this.zero[place] | whole; +} + +#! The words bytes touch, a bit each. +#! @param offset Where they begin. +#! @param size How many there are. +#! @returns The words. +def touched_words(offset: u64, size: u64): u64 { + return 0 if size == 0; + return 0xFFFFFFFFFFFFFFFFu if offset + size > memory_words * word_size; + val first := offset / word_size; + val last := (offset + size - 1) / word_size; + return words_between(first, last + 1); +} + +#! The words bytes cover whole, a bit each. +#! @param offset Where they begin. +#! @param size How many there are. +#! @returns The words. +def whole_words(offset: u64, size: u64): u64 { + return 0 if offset + size > memory_words * word_size; + val first := (offset + word_size - 1) / word_size; + val end := (offset + size) / word_size; + return first >= end ? 0 : words_between(first, end); +} + +#! The words from one to before another, a bit each. +#! @param first The first. +#! @param end The one after the last. +#! @returns The words. +def words_between(first: u64, end: u64): u64 { + val high := end >= 64 ? 0xFFFFFFFFFFFFFFFFu : (1u << end) - 1; + return high & ~((1u << first) - 1); +} + +#! Whether an address is within no cell: a step from a global, a datum, what +#! the program holds on the heap, or an address the function was given, which +#! points outside its frame. +#! @param this The code. +#! @param address The address. +#! @returns Whether it is. +def code::outside_cells(&this, address: u32): bool { + var at := address; + for _ in 0..8 { + val index := this.defining(at); + if index == 0 { + val held: origin = this.origins[at]; + return held.param && held.from == 0; + } + match this.insts[index].kind { + op::global, op::datum, op::allocate => return true; + op::add => at = this.arg(index, 0); + else => return false; + } + } + return false; +} + +#! Whether a value is a word or real all of whose bits are zero. +#! @param this The code. +#! @param value The value. +#! @returns Whether it is. +def code::zero_bits(&this, value: u32): bool { + var bits: u64 = 1; + val origin: origin = this.origins[value]; + return true if !origin.param && this.insts[origin.from].kind == op::vzero; + return (this.word_constant(value, &mut bits) || this.real_constant(value, &mut bits)) && bits == 0; +} + +#! Cleans up the memory of the cells, as the file says. +#! @param this The code. +#! @param writes Of each instruction, the bytes a call writes what it returns +#! to at its last operand, or 0. +#! @returns Whether anything changed. +pub def code::clean_memory(&mut this, writes: span): bool { + return false if this.cells.length == 0; + var state := memory_known { + addresses = this.cell_table(), + escaped = vector::::new(scratch()), + place = vector::::new(scratch()), + cells = vector::::new(scratch()), + exposed = vector::::new(scratch()), + zero = vector::::new(scratch()), + clears = vector::::new(scratch()), + cleared = vector::::new(scratch()), + covered = vector::::new(scratch()), + ends = vector::::new(scratch()), + walked = vector::::new(scratch()) + }; + return false if !state.addresses.any; + state.escaped = this.escaped_cells(&state.addresses, writes); + + state.place.resize(this.cells.length, unfollowed); + for c in 0..this.cells.length { + continue if this.cells[c].size as u64 > memory_words * word_size; + state.place[c] = state.cells.length as u32; + if state.escaped[c] { + state.exposed.append(state.cells.length as u32); + } + state.cells.append(c as u32); + } + val count := state.cells.length; + state.zero.resize(count); + state.clears.resize(count); + state.cleared.resize(count); + state.covered.resize(count); + + var done := rewrite::new(); + var order := vector::::new(scratch()); + var number := vector::::new(scratch()); + this.block_order(&mut order, &mut number); + val inherits := count != 0 && this.blocks.length * count <= memory_ends_limit; + if inherits { + state.ends.resize(this.blocks.length * count); + state.walked.resize(this.blocks.length); + } + for &block in order { + continue if count == 0; + this.begin_memory(block, &mut state, inherits); + this.walk_memory(block, &mut state, writes, &mut done); + if inherits { + for k in 0..count { + state.ends[block as u64 * count + k] = state.zero[k]; + } + state.walked[block] = true; + } + } + this.apply(&done); + + var returns := rewrite::new(); + this.forward_returns(&mut returns); + this.apply(&returns); + return done.changed || returns.changed; +} + +#! Begins what is known zero where a block begins: every word of each cell the +#! frame zeroes at the entry, and elsewhere what every block going there left, +#! where each was walked. +#! @param this The code. +#! @param block The block. +#! @param state What the pass knows. +#! @param inherits Whether what the blocks before it left is known. +def code::begin_memory(&this, block: u32, state: &mut memory_known, inherits: bool): void { + val count := state.cells.length; + for k in 0..count { + state.zero[k] = 0; + state.clears[k] = 0; + } + val preds := &this.blocks[block].preds; + if block == 0 && preds.length == 0 { + for k in 0..count { + val held: cell = this.cells[state.cells[k]]; + if held.kind == ck::temporary || held.kind == ck::local { + state.zero[k] = touched_words(0, held.size as u64); + } + } + return; + } + return if !inherits || preds.length == 0; + for &edge in preds.view() { + return if !state.walked[this.edge_source(edge)]; + } + for k in 0..count { + state.zero[k] = 0xFFFFFFFFFFFFFFFFu; + } + for &edge in preds.view() { + val from := this.edge_source(edge) as u64; + for k in 0..count { + state.zero[k] = state.zero[k] & state.ends[from * count + k]; + } + } +} + +#! Walks the instructions of a block, as the file says. +#! @param this The code. +#! @param block The block. +#! @param state What the pass knows. +#! @param writes Of each instruction, the bytes a call writes what it returns +#! to at its last operand, or 0. +#! @param done What the pass changes. +def code::walk_memory(&mut this, block: u32, state: &mut memory_known, writes: span, done: &mut rewrite): void { + var walk := this.walk(block); + while walk.more() { + val at := walk.next(); + val held: inst = this.insts[at]; + match held.kind { + op::load => this.memory_load(at, &held, state, done); + op::store => this.memory_store(at, &held, state, done); + op::clear => this.memory_clear(at, &held, state, done); + op::copy => this.memory_copy(at, &held, state, done); + else => this.memory_other(at, &held, state, writes, done); + } + } +} + +#! Follows a read: of a cell's words known zero, it is that zero. +#! @param this The code. +#! @param index The `load`. +#! @param held The instruction. +#! @param state What the pass knows. +#! @param done What the pass changes. +def code::memory_load(&mut this, index: u32, held: &inst, state: &mut memory_known, done: &mut rewrite): void { + val address := this.arg(index, 0); + if state.addresses.cell(address) == 0 { + if !this.outside_cells(address) { + state.read_escaped(); + } + return; + } + val k := state.followed(address); + return if k == unfollowed; + state.read(k); + val words := touched_words(held.imm, (held.aux as access).width()); + return if (state.zero[k] & words) != words; + done.replace(held.result, state.zeros.of(this, this.type_of(held.result))); + done.remove(index); +} + +#! Follows a write of a word: zero to words known zero goes. +#! @param this The code. +#! @param index The `store`. +#! @param held The instruction. +#! @param state What the pass knows. +#! @param done What the pass changes. +def code::memory_store(&mut this, index: u32, held: &inst, state: &mut memory_known, done: &mut rewrite): void { + val address := this.arg(index, 0); + if state.addresses.cell(address) == 0 { + if !this.outside_cells(address) { + state.forget_escaped(); + } + return; + } + val k := state.followed(address); + return if k == unfollowed; + val width := (held.aux as access).width(); + val words := touched_words(held.imm, width); + val whole := whole_words(held.imm, width); + if this.zero_bits(this.arg(index, 1)) { + if (state.zero[k] & words) == words { + done.remove(index); + return; + } + state.zero[k] = state.zero[k] | whole; + } else { + state.zero[k] = state.zero[k] & ~words; + } + state.cover(k, whole, done); +} + +#! Follows a clear: of words known zero already, it goes. +#! @param this The code. +#! @param index The `clear`. +#! @param held The instruction. +#! @param state What the pass knows. +#! @param done What the pass changes. +def code::memory_clear(&mut this, index: u32, held: &inst, state: &mut memory_known, done: &mut rewrite): void { + val address := this.arg(index, 0); + if state.addresses.cell(address) == 0 { + if !this.outside_cells(address) { + state.forget_escaped(); + } + return; + } + val k := state.followed(address); + return if k == unfollowed; + val words := touched_words(0, held.imm); + if (state.zero[k] & words) == words { + done.remove(index); + return; + } + state.clear(k, index, held.imm, done); +} + +#! Follows a copy: from words known zero, it clears instead, or goes where what +#! it writes is known zero already. +#! @param this The code. +#! @param index The `copy`. +#! @param held The instruction. +#! @param state What the pass knows. +#! @param done What the pass changes. +def code::memory_copy(&mut this, index: u32, held: &inst, state: &mut memory_known, done: &mut rewrite): void { + val to := this.arg(index, 0); + val from := this.arg(index, 1); + val words := touched_words(0, held.imm); + var zero := false; + if state.addresses.cell(from) == 0 { + if !this.outside_cells(from) { + state.read_escaped(); + } + } else { + val s := state.followed(from); + if s != unfollowed { + zero = (state.zero[s] & words) == words; + if !zero { + state.read(s); + } + } + } + + if zero { + val d := state.followed(to); + if d != unfollowed && (state.zero[d] & words) == words { + done.remove(index); + return; + } + var args: u32[1] = [to]; + this.become(index, op::clear, args[0:1], 0, held.imm); + done.changed = true; + if d != unfollowed { + state.clear(d, index, held.imm, done); + return; + } + } + if state.addresses.cell(to) == 0 { + if !this.outside_cells(to) { + state.forget_escaped(); + } + return; + } + val d := state.followed(to); + return if d == unfollowed || zero; + state.zero[d] = state.zero[d] & ~words; + state.cover(d, whole_words(0, held.imm), done); +} + +#! Follows any other instruction: one reading or writing memory the code does +#! not name may read or write any escaped cell, and a call writes what it +#! returns to the cell its last operand is. +#! @param this The code. +#! @param index The instruction. +#! @param held The instruction. +#! @param state What the pass knows. +#! @param writes Of each instruction, the bytes a call writes what it returns +#! to at its last operand, or 0. +#! @param done What the pass changes. +def code::memory_other(&mut this, index: u32, held: &inst, state: &mut memory_known, writes: span, done: &mut rewrite): void { + # What a cell's address is given to may read it, and as an operand write it, + # but for where a call writes what it returns, which is followed below. + val written: u64 = (index as u64) < writes.length ? writes[index] : 0; + var reads := this.reads_of(index); + while reads.more() { + val k := state.followed(reads.next()); + continue if k == unfollowed; + val i := reads.operand(); + if i == no_operand { + state.read(k); + continue; + } + continue if written != 0 && i + 1 == held.argc; + state.read(k); + state.zero[k] = 0; + } + val traits := held.kind.traits(); + if (traits & op_reads) != 0 { + state.read_escaped(); + } + if (traits & op_write) != 0 { + state.forget_escaped(); + } + if written != 0 { + val k := state.followed(this.arg(index, held.argc - 1)); + if k != unfollowed { + state.zero[k] = 0; + state.cover(k, whole_words(0, written), done); + } + } +} + +#! Returns from where a copy into the memory a function returns, right before +#! it returns, was copied from. +#! @param this The code. +#! @param done What the pass changes. +def code::forward_returns(&mut this, done: &mut rewrite): void { + return if this.returned == 0; + for b in 0..this.blocks.length { + continue if this.blocks[b].gone; + val last: u32 = this.blocks[b].last; + continue if last == 0 || this.insts[last].kind != op::ret || this.insts[last].argc != 1; + val before := this.before(last); + continue if before == 0 || this.insts[before].kind != op::copy; + val returned := this.arg(last, 0); + val to := this.arg(before, 0); + val from := this.arg(before, 1); + continue if this.insts[before].imm < this.returned as u64 || from == returned; + continue if to != returned && (this.cell_of(to) == no_cell || this.cell_of(to) != this.cell_of(returned)); + var args: u32[1] = [from]; + this.become(last, op::ret, args[0:1], this.insts[last].aux, this.insts[last].imm); + done.remove(before); + } +} diff --git a/compiler/optimizer/merge.sakura b/compiler/optimizer/merge.sakura new file mode 100644 index 00000000..4ff3ef27 --- /dev/null +++ b/compiler/optimizer/merge.sakura @@ -0,0 +1,186 @@ +#! @file merge.sakura +#! @author John Christman (sorakatadzuma@gmail.com) +#! @copyright Malunal Studios, LLC. +#! @license MIT +#! +#! Contains the merging of the stores filling 16 bytes of a cell into one, of a +#! vector built in a register, which an executable's code is given once it is +#! optimized. A load reading several stores waits until each reaches the cache, +#! where one store of all its bytes is forwarded to it at once, and a struct of +#! four `f32`s or two words, as a `vec3` holding its fourth, is copied out 16 +#! bytes at a time, as it is returned: built a field at a time, the copy waited +#! on every field. +#! +#! The 16 bytes from a multiple of 16 in a cell the frame zeroes are merged +#! where every instruction writing them in the code is a store of 4 or 8 bytes, +#! all reals or all words, each in one block, and nothing reads them from the +#! first to the last; what none writes is zero. The cell's address goes only to +#! what reads, writes, copies, clears, and returns it. It is done once nothing +#! more is inlined, so a function copying the code holds its fields as values +#! still, as promoting holds them, and only in an executable's code, which holds +#! vectors. + +module sakura::compiler; + + +#! What merging knows of a write or read of a cell. +struct touch { + var at: u32; #! The instruction. + var offset: u64; #! The first byte. + var size: u64; #! How many bytes. + var writes: bool; #! Whether it writes them. + var how: access; #! For a store, how it writes them; `access::bytes` for any other. +} + +#! Merges the stores filling 16 bytes of a cell, as the file says. +#! @param this The code. +#! @returns Whether anything changed. +pub def code::merge_stores(&mut this): bool { + return false if !this.vectors || this.cells.length == 0; + val addresses := this.cell_table(); + return false if !addresses.any; + + # What each cell's address goes to, where it goes only to what reads and + # writes it, and the order of each instruction within its block. + var touches := vector::>::new(scratch()); + touches.resize(this.cells.length); + var whole := vector::::new(scratch()); + whole.resize(this.cells.length, true); + var place := vector::::new(scratch()); + place.resize(this.insts.length); + for b in 0..this.blocks.length { + continue if this.blocks[b].gone; + var number: u32 = 0; + var walk := this.walk(b as u32); + while walk.more() { + place[walk.next()] = number; + number++; + } + } + var walk := this.walk_all(); + var reads := this.reader(); + while walk.more() { + val at := walk.next(); + val held: inst = this.insts[at]; + reads.start(at); + while reads.more() { + val cell := addresses.cell(reads.next()); + continue if cell == 0; + val c := (cell - 1) as u64; + val i := reads.operand(); + if i == no_operand { + whole[c] = false; + } else if held.kind == op::load && i == 0 { + touches[c].append(touch { at = at, offset = held.imm, size = (held.aux as access).width(), how = access::bytes }); + } else if held.kind == op::store && i == 0 { + val how := held.aux as access; + touches[c].append(touch { at = at, offset = held.imm, size = how.width(), writes = true, how = how }); + } else if held.kind == op::clear && i == 0 { + touches[c].append(touch { at = at, size = held.imm, writes = true, how = access::bytes }); + } else if held.kind == op::copy && i < 2 { + touches[c].append(touch { at = at, size = held.imm, writes = i == 0, how = access::bytes }); + } else if held.kind == op::ret { + touches[c].append(touch { at = at, size = this.cells[c].size as u64, how = access::bytes }); + } else { + whole[c] = false; + } + } + } + + var done := rewrite::new(); + var zeros := zero_values {}; + for c in 0..this.cells.length { + val held: cell = this.cells[c]; + continue if !whole[c] || (held.kind != ck::temporary && held.kind != ck::local); + var start: u64 = 0; + while start + 16 <= held.size as u64 { + this.merge_region(c as u32, start, touches[c].view(), place.view(), &mut zeros, &mut done); + start += 16; + } + } + this.apply(&done); + return done.changed; +} + +#! Merges the stores filling the 16 bytes of a cell from an offset, where they +#! may be merged, as the file says: the last becomes the store of the vector +#! of them all, built before it, and the rest go. +#! @param this The code. +#! @param cell The cell. +#! @param start Where the bytes begin. +#! @param touches What reads and writes the cell. +#! @param place The order of each instruction within its block. +#! @param zeros The zero of each type, made once. +#! @param done What the pass changes. +def code::merge_region(&mut this, cell: u32, start: u64, touches: span, place: span, zeros: &mut zero_values, done: &mut rewrite): void { + val end := start + 16; + var stores := vector::::new(scratch()); + var block: u32 = 0; + for &each in touches { + continue if !each.writes || each.offset >= end || each.offset + each.size <= start; + return if each.how == access::bytes || each.offset < start || each.offset + each.size > end; + val one: inst = this.insts[each.at]; + if stores.length == 0 { + block = one.block; + } + # One block's stores, each of a word or a real of the same width, at an + # offset of its own, as a struct's fields are written. + return if one.block != block || each.size != stores_width(&stores, each.size) || (each.size != 4 && each.size != 8); + return if stores.length != 0 && (each.how.value_type() != stores[0].how.value_type()); + for &other in stores { + return if other.offset == each.offset; + } + stores.append(each); + } + return if stores.length < 2; + var first: u32 = 0xFFFFFFFF; + var last: u32 = 0; + var last_at: u32 = 0; + for &each in stores { + val p := place[each.at]; + first = first < p ? first : p; + if p >= last { + last = p; + last_at = each.at; + } + } + # Nothing reads the bytes between the first store and the last. + for &each in touches { + continue if each.writes || each.offset >= end || each.offset + each.size <= start; + val p := place[each.at]; + return if this.insts[each.at].block == block && p > first && p < last; + } + + val width := stores[0].size; + val real := stores[0].how.value_type() == vt::real; + val lane: u32 = real ? (width == 4 ? lane_f32 : lane_f64) : (width == 4 ? lane_u32 : lane_u64); + val count := 16 / width; + var lanes := vector::::new(scratch()); + lanes.resize(count, 0); + for &each in stores { + lanes[(each.offset - start) / width] = this.arg(each.at, 1); + } + for k in 0..count { + if lanes[k] == 0 { + lanes[k] = zeros.of(this, real ? vt::real : vt::word); + } + } + val held: inst = this.insts[last_at]; + var gives: vt[1] = [vt::v128]; + val pack := this.detached(op::lanes, lanes.view(), gives[0:1], lanes_pack, lane as u64 | 16 << 8, held.at, held.site); + this.link_before(pack, last_at); + var args: u32[2] = [this.arg(last_at, 0), this.insts[pack].result]; + this.become(last_at, op::store, args[0:2], access::v128 as u32, start); + for &each in stores { + if each.at != last_at { + done.remove(each.at); + } + } + done.changed = true; +} + +# The width the stores of a region share: that of the first, or the one given +# where there is none yet. +def stores_width(stores: &vector, size: u64): u64 { + return stores.length == 0 ? size : stores[0].size; +} diff --git a/compiler/optimizer/numbering.sakura b/compiler/optimizer/numbering.sakura new file mode 100644 index 00000000..c9347395 --- /dev/null +++ b/compiler/optimizer/numbering.sakura @@ -0,0 +1,689 @@ +#! @file numbering.sakura +#! @author John Christman (sorakatadzuma@gmail.com) +#! @copyright Malunal Studios, LLC. +#! @license MIT +#! +#! Contains the sixth pass of the optimizer, value numbering: an instruction +#! working out what one before it already worked out, in a block that block +#! dominates, reads that instead, as two reads of `v[i]` share one bounds +#! check's comparison. A check of a condition a dominating check or branch +#! already proved goes, as does a branch's question where it was answered, and +#! a `select` on it is what it chooses. And a read of memory read or written +#! before, with nothing that may write it between, as alias analysis tells, +#! reads what was read or written: within a block, and from the block that +#! dominates it, but for what anything on the way between may write. + +import std::containers; +module sakura::compiler; + + +#! What numbering knows where it is in the walk: the instruction giving each +#! value worked out so far, by its hash, and each condition known, with what +#! each block added, which leaving it takes back. +struct numbering { + var table: scoped_dict; #! The instruction giving each value worked out, by its hash. + var facts: scoped_dict; #! What each condition known is. + var loads: vector; #! The reads and writes remembered in the block. + var copies: vector; #! The copies into cells remembered in the block. + var writers: runs; #! The instructions of each block writing memory, in order, a run each. + var writer_runs: vector; #! The run of `writers` of each block, by block, 0 where none writes, or `no_run` where they are not yet listed. + var kept: runs; #! What each block knew of memory where it ended, a run each. + var kept_runs: vector; #! The run of `kept` each block knew, by block, or 0 where it knew nothing or dominates no block. + var held_run: u32; #! The run of `kept` the reads and writes remembered are, where they were inherited whole and nothing changed them since, or `no_run`. + var aliases: aliases; #! What may write what. +} + +#! A read or write of memory numbering remembers: what is at an address, read +#! as an access reads it. +struct known_load { + var address: u32; #! The address. + var how: u32; #! The access. + var value: u32; #! What is there. + var offset: u64; #! How many bytes past the address it is. + var place: region; #! The bytes it is, as alias analysis tells. +} + +#! A copy into a cell numbering remembers: the cell holds what is where it +#! copied from, until something writes. +struct known_copy { + var to: u32; #! The cell's address. + var from: u32; #! The address it copied from. + var size: u64; #! How many bytes it copied. + var to_place: region; #! The bytes it wrote, as alias analysis tells. + var from_place: region; #! The bytes it read. +} + +#! What `numbering::held_run` holds where what is remembered of memory is no +#! run kept. +const no_run: u32 = 0xFFFFFFFF; + +#! A block on numbering's walk down the tree of which dominates which. +struct numbered_block { + var table: u64; #! How many changes the table had before the block, which leaving it takes back. + var facts: u64; #! How many changes the conditions known had before it. + var next: u32; #! The next of the blocks it immediately dominates to walk, or `no_block`. +} + +#! Forgets what numbering remembers of memory, as what writes it does. +#! @param this What numbering knows. +def numbering::forget_memory(&mut this): void { + this.loads.clear(); + this.copies.clear(); + this.held_run = 0; +} + +#! Numbers the values of a function's code, knowing what each call writes +#! what it returns to. +#! @param this The compiler. +#! @param index The function. +#! @returns Whether anything changed. +def lowerer::number_values(&mut this, index: u32): bool { + val writes := this.result_writes(index); + return this.program.functions[index].body.number_values(writes.view()); +} + +#! Numbers the values of the code, as the file says, walking the blocks down +#! the tree of which dominates which. +#! @param this The code. +#! @param writes Of each instruction, the bytes a call writes what it returns +#! to at its last operand, or 0. +#! @returns Whether anything changed. +pub def code::number_values(&mut this, writes: span): bool { + var order := vector::::new(scratch()); + var number := vector::::new(scratch()); + this.block_order(&mut order, &mut number); + val idom := this.block_dominators(); + + # The blocks each block immediately dominates. + var first := vector::::new(scratch()); + var after := vector::::new(scratch()); + first.resize(this.blocks.length, no_block); + after.resize(this.blocks.length, no_block); + var k := order.length; + while k > 1 { + k--; + val block: u32 = order[k]; + val parent: u32 = idom[block]; + after[block] = first[parent]; + first[parent] = block; + } + + var state := numbering { + table = scoped_dict::::new(scratch()), + facts = scoped_dict::::new(scratch()), + loads = vector::::new(scratch()), + copies = vector::::new(scratch()), + writers = runs::::new(scratch()), + writer_runs = vector::::new(scratch()), + kept = runs::::new(scratch()), + kept_runs = vector::::new(scratch()), + held_run = 0, + aliases = this.aliases_unfound(writes, idom.view()) + }; + state.writer_runs.resize(this.blocks.length, no_run); + state.kept_runs.resize(this.blocks.length); + var done := rewrite::new(); + + # The blocks on the walk, each with where its changes begin. + var stack := vector::::new(scratch()); + stack.append(numbered_block { next = first[0] }); + this.number_block(0, &mut state, &mut done); + if first[0] != no_block { + this.keep_memory(0, &mut state); + } + while stack.length != 0 { + # The top is written before a block is pushed, which may move it. + val top := &mut stack.last(); + val child := top.next; + if child != no_block { + top.next = after[child]; + stack.append(numbered_block { table = state.table.mark(), facts = state.facts.mark(), next = first[child] }); + this.learn_entry(child, &mut state); + this.inherit_memory(child, idom[child], &mut state); + this.number_block(child, &mut state, &mut done); + # Only the blocks a block dominates ask what it knew where it ended. + if first[child] != no_block { + this.keep_memory(child, &mut state); + } + continue; + } + + # Leaving a block takes back what it added. + state.table.rewind(top.table); + state.facts.rewind(top.facts); + stack.truncate(); + } + + # Numbering a block had what it reads read what replaces it, and what the + # edges leaving it give; so do those of the blocks the entry does not reach, + # never numbered, and the variables bound. + if done.forward.length != 0 { + for b in 0..this.blocks.length { + continue if this.blocks[b].gone || number[b] != 0xFFFFFFFF; + var walk := this.walk(b as u32); + while walk.more() { + val at := walk.next(); + val held: inst = this.insts[at]; + for i in 0..held.argc { + val slot := held.args as u64 + i as u64; + this.operands[slot] = done.resolve(this.operands[slot]); + } + } + this.resolve_edges(b as u32, &done); + } + for i in 0..this.bindings.length { + this.bindings[i].value = done.resolve(this.bindings[i].value); + } + } + this.take_out(&done); + return done.changed; +} + +#! Has the edges leaving a block give what replaces what they give. +#! @param this The code. +#! @param block The block. +#! @param done What the pass changes. +def code::resolve_edges(&mut this, block: u32, done: &rewrite): void { + var outs := this.edges_of(this.blocks[block].last); + while outs.more() { + val args := this.edges[outs.next()].args.slice(); + for a in 0..args.length { + args[a] = done.resolve(args[a]); + } + } +} + +#! Learns what the branch into a block says where only it goes there: its +#! condition is not zero along the way it goes where it is not, and is zero +#! along the other. +#! @param this The code. +#! @param block The block. +#! @param state What numbering knows. +def code::learn_entry(&this, block: u32, state: &mut numbering): void { + return if this.blocks[block].preds.length != 1; + val edge: u32 = this.blocks[block].preds[0]; + val from: u32 = this.edges[edge].from; + return if this.insts[from].kind != op::branch; + val cond := this.arg(from, 0); + return if state.facts.contains(&cond); + state.facts.set(cond, edge == this.insts[from].aux ? 1 : 0); +} + +#! Begins what numbering knows of memory where a block begins: what the block +#! dominating it knew where it ended, but for what anything on a way from +#! there to the block may write, and nothing where the ways pass too many +#! blocks. +#! @param this The code. +#! @param block The block. +#! @param parent The block dominating it. +#! @param state What numbering knows. +def code::inherit_memory(&this, block: u32, parent: u32, state: &mut numbering): void { + state.forget_memory(); + val run: u32 = state.kept_runs[parent]; + return if run == 0; + var between := vector::::new(scratch()); + return if !this.blocks_between(parent, block, &mut between); + state.loads.extend(state.kept.view(run)); + state.held_run = run; + for &each in between { + this.list_writers(each, state); + for &at in state.writers.view(state.writer_runs[each]) { + this.forget_written(at, state); + return if state.loads.length == 0; + } + } +} + +#! Lists the instructions of a block writing memory, where numbering it did not +#! list them already. +#! @param this The code. +#! @param block The block. +#! @param state What numbering knows. +def code::list_writers(&this, block: u32, state: &mut numbering): void { + return if state.writer_runs[block] != no_run; + var walk := this.walk(block); + while walk.more() { + val at := walk.next(); + val kind := this.insts[at].kind; + if kind != op::load && (kind.traits() & op_write) != 0 { + state.writers.push(at); + } + } + state.writer_runs[block] = state.writers.end(); +} + +#! Finds the blocks on the ways from where a block ends to where a block it +#! dominates begins. A way going round a loop through the block it ends at +#! passes that block whole, so it is among them; one coming back through the +#! dominating block begins again where that block ends, which knows what it +#! knows anew. Only so many blocks are looked through. +#! @param this The code. +#! @param parent The dominating block. +#! @param block The block it dominates. +#! @param between Where the blocks are written. +#! @returns Whether they are few enough to be looked through. +def code::blocks_between(&this, parent: u32, block: u32, between: &mut vector): bool { + val preds := &this.blocks[block].preds; + if preds.length == 1 && this.edge_source(preds[0]) == parent { + return true; + } + var todo := vector::::new(scratch()); + for &edge in preds.view() { + todo.append(this.edge_source(edge)); + } + while todo.length != 0 { + val at: u32 = todo.last(); + todo.truncate(); + continue if at == parent || between.view().contains(&at); + return false if between.length >= 32; + between.append(at); + for &edge in this.blocks[at].preds.view() { + todo.append(this.edge_source(edge)); + } + } + return true; +} + +#! Forgets what numbering remembers of memory that an instruction may write. +#! @param this The code. +#! @param index The instruction. +#! @param state What numbering knows. +def code::forget_written(&this, index: u32, state: &mut numbering): void { + return if state.loads.length == 0 && state.copies.length == 0; + val written := state.aliases.writes_of(this, index); + this.forget_writing(&written, state); +} + +#! Forgets what numbering remembers of memory that what an instruction writes +#! may hold. +#! @param this The code. +#! @param written What the instruction writes. +#! @param state What numbering knows. +def code::forget_writing(&this, written: &writing, state: &mut numbering): void { + return if state.loads.length == 0 && state.copies.length == 0; + state.aliases.find_escaped(this); + var kept: u64 = 0; + for i in 0..state.loads.length { + continue if state.aliases.touches(this, written, &state.loads[i].place); + if kept != i { + state.loads[kept] = state.loads[i]; + } + kept++; + } + if kept != state.loads.length { + state.loads.resize(kept); + state.held_run = no_run; + } + var held: u64 = 0; + for i in 0..state.copies.length { + val each: known_copy = state.copies[i]; + continue if state.aliases.touches(this, written, &each.to_place) || state.aliases.touches(this, written, &each.from_place); + state.copies[held] = each; + held++; + } + state.copies.resize(held); +} + +#! Keeps what numbering knows of memory where a block ends, for the blocks it +#! dominates: the run it inherited, where nothing changed it. +#! @param this The code. +#! @param block The block. +#! @param state What numbering knows. +def code::keep_memory(&this, block: u32, state: &mut numbering): void { + state.kept_runs[block] = state.held_run != no_run ? state.held_run : state.kept.add(state.loads.view()); +} + +#! Numbers the instructions of a block, in order, from what is known of memory +#! where it begins, which then holds what is known where it ends. +#! @param this The code. +#! @param block The block. +#! @param state What numbering knows. +#! @param done What the pass changes. +def code::number_block(&mut this, block: u32, state: &mut numbering, done: &mut rewrite): void { + # What writes memory is listed as it is met, where it is not listed yet. + val listing := state.writer_runs[block] == no_run; + var walk := this.walk(block); + while walk.more() { + val at := walk.next(); + val held: inst = this.insts[at]; + for i in 0..held.argc { + val slot := held.args as u64 + i as u64; + this.operands[slot] = done.resolve(this.operands[slot]); + } + + match held.kind { + op::check => { + val cond := this.arg(at, 0); + if state.facts.get(&cond) is some(known) { + if known != 0 { + done.remove(at); + } + } else { + state.facts.set(cond, 1); + } + } + op::branch => { + val cond := this.arg(at, 0); + if state.facts.get(&cond) is some(known) { + # Which cells are escaped is found as the code was, before the + # branch no longer reads its condition. + state.aliases.find_escaped(this); + val bits: u64 = known; + this.operands[held.args] = this.word_value(bits != 0 ? 1 : 0); + done.changed = true; + } + } + op::load => { + this.forward_copy(at, 0, (held.aux as access).width() + held.imm, state, done); + this.number_load(at, state, done); + } + op::copy => this.forward_copy(at, 1, held.imm, state, done); + op::select => this.number_select(at, state, done); + else => { + if this.removable(at) && held.count == 1 { + this.number_inst(at, state, done); + } + } + } + + # What writes memory makes what was read of what it may write unknown, + # but for what a store of a whole word writes. + if held.kind != op::load && (held.kind.traits() & op_write) != 0 { + if listing { + state.writers.push(at); + } + if held.kind == op::store && (held.aux == access::i64 as u32 || held.aux == access::f64 as u32) { + # What a store writes is the region it then holds. + val written := state.aliases.writes_of(this, at); + this.forget_writing(&written, state); + state.held_run = no_run; + var base: u32 = 0; + val offset := this.address_base(this.arg(at, 0), held.imm, &mut base); + state.loads.append(known_load { + address = base, + how = held.aux, + value = this.arg(at, 1), + offset = offset, + place = written.place + }); + } else { + this.forget_written(at, state); + } + # A cell a copy filled holds what it copied, until something writes. + if held.kind == op::copy && this.cell_of(this.arg(at, 0)) != no_cell + && this.cell_of(this.arg(at, 0)) != this.cell_of(this.arg(at, 1)) { + val to := this.arg(at, 0); + val from := this.arg(at, 1); + state.copies.append(known_copy { + to = to, + from = from, + size = held.imm, + to_place = state.aliases.region_at(this, to, 0, held.imm), + from_place = state.aliases.region_at(this, from, 0, held.imm) + }); + } + } + } + if listing { + state.writer_runs[block] = state.writers.end(); + } + this.resolve_edges(block, done); +} + +#! Numbers a `select`: one on a condition known where it is, as a dominating +#! check or branch made it, is what it chooses, and otherwise it is numbered as +#! any instruction working out its value is. +#! @param this The code. +#! @param index The `select`. +#! @param state What numbering knows. +#! @param done What the pass changes. +def code::number_select(&mut this, index: u32, state: &mut numbering, done: &mut rewrite): void { + val cond := this.arg(index, 0); + if state.facts.get(&cond) is some(known) { + val bits: u64 = known; + done.replace(this.insts[index].result, this.arg(index, bits != 0 ? 1 : 2)); + done.remove(index); + return; + } + this.number_inst(index, state, done); +} + +#! Reads what a cell a copy filled holds from where it was copied from +#! instead, where nothing wrote since: a load from it, or a copy out of it into +#! another cell. +#! @param this The code. +#! @param index The `load` or `copy`. +#! @param operand The operand reading the cell. +#! @param reach How far past the cell's address it reads. +#! @param state What numbering knows. +#! @param done What the pass changes. +def code::forward_copy(&mut this, index: u32, operand: u32, reach: u64, state: &mut numbering, done: &mut rewrite): void { + val address := this.arg(index, operand); + for i in 0..state.copies.length { + val each := &state.copies[i]; + continue if each.to != address || reach > each.size; + val from := each.from; + # A copy out of it goes on only into a cell, which nothing else overlaps. + if operand == 1 { + val into := this.cell_of(this.arg(index, 0)); + return if into == no_cell || into == this.cell_of(from); + } + this.operands[this.insts[index].args as u64 + operand as u64] = from; + done.changed = true; + return; + } +} + +#! Numbers a read of memory: one of what the block read or wrote before, with +#! nothing writing between, reads that instead, though one reached through a +#! step past the address the other was. +#! @param this The code. +#! @param index The `load`. +#! @param state What numbering knows. +#! @param done What the pass changes. +def code::number_load(&mut this, index: u32, state: &mut numbering, done: &mut rewrite): void { + val held: inst = this.insts[index]; + var address: u32 = 0; + val offset := this.address_base(this.arg(index, 0), held.imm, &mut address); + for i in 0..state.loads.length { + val each := &state.loads[i]; + continue if each.address != address || each.offset != offset || each.how != held.aux; + done.replace(held.result, each.value); + done.remove(index); + return; + } + state.held_run = no_run; + state.loads.append(known_load { + address = address, + how = held.aux, + value = held.result, + offset = offset, + place = state.aliases.region_of(this, index, 0) + }); +} + +#! Where a load or store reaches, as a value and how many bytes past it: a step +#! of a constant past another value reaches as far past that one, so the bytes +#! it reaches are known as the same as those reached from it directly. +#! @param this The code. +#! @param address The address the load or store is given. +#! @param offset How many bytes past it the load or store reaches. +#! @param base Where the value it reaches past is written. +#! @returns How many bytes past that value it reaches. +def code::address_base(&this, address: u32, offset: u64, base: &mut u32): u64 { + base = address; + val index := this.defining(address); + return offset if index == 0 || this.insts[index].kind != op::add; + var bits: u64 = 0; + return offset if !this.word_constant(this.arg(index, 1), &mut bits); + base = this.arg(index, 0); + return offset + bits; +} + +#! Numbers an instruction that only works out its value: one working out what +#! one dominating it did reads that instead. +#! @param this The code. +#! @param index The instruction. +#! @param state What numbering knows. +#! @param done What the pass changes. +def code::number_inst(&mut this, index: u32, state: &mut numbering, done: &mut rewrite): void { + val hash := this.hash_inst(index); + if state.table.get(&hash) is some(got) { + val other: u32 = got; + if this.same_inst(index, other) { + done.replace(this.insts[index].result, this.insts[other].result); + done.remove(index); + return; + } + } + state.table.set(hash, index); +} + +#! The hash of what an instruction works out: its operation, what its `aux` +#! and `imm` hold, the type of its value, and its operands, in either order +#! where the operation does not mind which. +#! @param this The code. +#! @param index The instruction. +#! @returns The hash. +def code::hash_inst(&this, index: u32): u64 { + val held: inst = this.insts[index]; + var hash := mix_hash(mix_hash(mix_hash(0xCBF29CE484222325u, held.kind as u64), held.aux as u64), held.imm); + hash = mix_hash(hash, this.origins[held.result].kind as u64); + if held.argc == 2 && commutes(held.kind) { + val a := this.arg(index, 0); + val b := this.arg(index, 1); + hash = mix_hash(mix_hash(hash, (a < b ? a : b) as u64), (a < b ? b : a) as u64); + return hash; + } + for i in 0..held.argc { + hash = mix_hash(hash, this.arg(index, i as u32) as u64); + } + return mix_hash(hash, held.argc as u64); +} + +#! Whether two instructions work out the same. Their values are of one type, +#! as a `vzero` of 16 bytes and one of 32 are not the same. +#! @param this The code. +#! @param a One instruction. +#! @param b The other. +#! @returns Whether they do. +def code::same_inst(&this, a: u32, b: u32): bool { + val x: inst = this.insts[a]; + val y: inst = this.insts[b]; + return false if x.kind != y.kind || x.aux != y.aux || x.imm != y.imm || x.argc != y.argc; + return false if this.origins[x.result].kind != this.origins[y.result].kind; + if x.argc == 2 && commutes(x.kind) { + val a0 := this.arg(a, 0); + val a1 := this.arg(a, 1); + val b0 := this.arg(b, 0); + val b1 := this.arg(b, 1); + return (a0 == b0 && a1 == b1) || (a0 == b1 && a1 == b0); + } + for i in 0..x.argc { + return false if this.arg(a, i as u32) != this.arg(b, i as u32); + } + return true; +} + +#! Mixes a word into a hash. +#! @param hash The hash so far. +#! @param value The word. +#! @returns The hash. +def mix_hash(hash: u64, value: u64): u64 { + return (hash ^ value) * 0x100000001B3u; +} + +#! Moves each constant made within a loop first into the entry, one of each, +#! so the machine makes it once a call rather than each time the loop goes +#! round, as it does the address of a cell, a global, or a datum. One made +#! outside every loop stays, since making it at the entry would make it where +#! nothing reads it. +#! @param this The code. +#! @returns Whether anything changed. +pub def code::hoist_constants(&mut this): bool { + var order := vector::::new(scratch()); + var number := vector::::new(scratch()); + this.block_order(&mut order, &mut number); + val looped := this.loop_blocks(order.view(), number.view()); + + var done := rewrite::new(); + var words := dict::::new(scratch()); + var reals := dict::::new(scratch()); + var moved := vector::::new(scratch()); + for &block in order { + continue if block != 0 && !looped[block]; + var walk := this.walk(block); + while walk.more() { + val at := walk.next(); + val held: inst = this.insts[at]; + if block != 0 && (held.kind == op::cell || held.kind == op::global || held.kind == op::datum) { + done.remove(at); + moved.append(at); + } else if held.kind == op::iconst || held.kind == op::fconst { + val seen := held.kind == op::iconst ? &mut words : &mut reals; + if seen.get(&held.imm) is some(got) { + done.replace(held.result, got); + done.remove(at); + } else { + seen.set(held.imm, held.result); + if block != 0 { + done.remove(at); + moved.append(at); + } + } + } + } + } + this.apply(&done); + var i := moved.length; + while i > 0 { + i--; + this.put_first(0, moved[i]); + } + return done.changed; +} + +#! Which blocks are within a loop: those from which an edge going back to a +#! block dominating them is reached, without passing that block, and that +#! block. +#! @param this The code. +#! @param order The blocks in reverse postorder. +#! @param number Each block's place in that order. +#! @returns Whether each block is within a loop. +pub def code::loop_blocks(&mut this, order: span, number: span): vector { + var looped := vector::::new(scratch()); + looped.resize(this.blocks.length); + + # The dominators are asked for only where an edge may go back. + var back := false; + for &block in order { + for &edge in this.blocks[block].preds { + back = back || number[this.edge_source(edge)] >= number[block]; + } + } + return looped if !back; + val idom := this.block_dominators(); + var todo := vector::::new(scratch()); + for &block in order { + for &edge in this.blocks[block].preds { + val from := this.edge_source(edge); + continue if number[from] < number[block] || !dominates(&idom, block, from); + # A loop headed by the block: walk back from where it goes back. + looped[block] = true; + todo.append(from); + while todo.length != 0 { + val at: u32 = todo.last(); + todo.truncate(); + continue if at == block || looped[at] && at != from; + looped[at] = true; + for &inner in this.blocks[at].preds { + val back := this.edge_source(inner); + if back != block && !looped[back] { + todo.append(back); + } + } + } + } + } + return looped; +} diff --git a/compiler/optimizer/optimizer.sakura b/compiler/optimizer/optimizer.sakura new file mode 100644 index 00000000..39d2ac2d --- /dev/null +++ b/compiler/optimizer/optimizer.sakura @@ -0,0 +1,575 @@ +#! @file optimizer.sakura +#! @author John Christman (sorakatadzuma@gmail.com) +#! @copyright Malunal Studios, LLC. +#! @license MIT +#! +#! Contains the optimizer, which runs passes over the code of each function +#! once the program is lowered. Each pass is small, in a file of its own, and +#! leaves the code well formed, which the verifier checks after each where +#! lowering verifies. `-O0` runs none, `-O1` simplification, control flow +#! cleanup, value numbering, and dead code removal, and `-O2` those with +#! inlining and the promotion of cells to values. Below `-O2`, calls of +#! `@inline` functions are inlined all the same, and nothing else is, so at +#! `-O0` the code is as written but for those, each local of the code copied +#! still in a cell of its own. The slots the passes leave are compacted away +#! at the end, which the backends and the functions inlining the code read. +#! Functions are optimized after the functions they call, so a function +#! inlined is already optimized. +#! At `-O2`, a function of an executable asking which vector instructions the +#! processor has is given a version for x86-64-v3's, as `versions.sakura` says. + +import std::containers; +module sakura::compiler; + + +#! The passes, as a problem a pass leaves names them. +pub enum pass : u8 { + simplify, #! Folding constants and simplifying operations. + dead, #! Taking out what nothing needs. + control, #! Cleaning up how control flows. + inline, #! Inlining calls of small functions. + promote, #! Promoting cells to values. + numbering, #! Numbering values. + hoist, #! Moving constants into the entry. + memory, #! Cleaning up the memory of cells. + loops, #! Rotating loops and moving out of them what they work out the same each time round. + sink, #! Moving what is read past one way out of a block into that way. + count, #! How many passes there are; not a pass itself. +} + +#! The name of a pass, as a problem names it. +#! @param this The pass. +#! @returns Its name. +pub def pass::name(&this): strview { + return match this { + pass::simplify => "simplification", + pass::dead => "dead code removal", + pass::control => "control flow cleanup", + pass::inline => "inlining", + pass::promote => "promotion", + pass::numbering => "value numbering", + pass::hoist => "constant hoisting", + pass::memory => "memory cleanup", + pass::loops => "loop optimization", + pass::sink => "code sinking", + else => "a pass" + }; +} + +#! Optimizes every function lowered and not yet optimized, as its level says, +#! each after those it calls, but for those calling each other, which go in the +#! order met. The order is worked out first, walking the calls, and a function +#! inlines only those before it, so what each is made into is the same however +#! many threads optimize them: as many as the options say work at once, each +#! taking a function once those before it that it calls are done. A function +#! the one calling it alone copies whole is optimized there, so only the passes +#! up to inlining run on it before, and the rest after, where something still +#! reaches it, as a cold call does. The versions of those asking which +#! instructions the processor has are made after, in the order, as each reads +#! what came before its function. +#! @param this The compiler. +pub def lowerer::optimize(&mut this): void { + return if this.options.level == 0 && !this.copies_marked(); + var plan := this.plan_optimizing(); + val count := plan.order.length; + + # What verifying each function finds, kept by its place in the order, so it + # is noted in that order whichever thread found it. + var found := vector::>::new(); + found.resize(count); + val compiler := &mut this; + share_out_ordered(count, this.options.threads, &plan.waiting, def(place: u64): void { + compiler.optimize_at(&plan, place, &mut found[place]); + }); + + # Those left for the function calling them that something still reaches, as + # one whose call is cold, have the rest of their passes run, each on its own, + # whichever optimizing left them. + var finishing := this.left_unfinished(); + var alone := groups::::new(0); + alone.reset(finishing.length); + alone.seal(); + var noted := vector::>::new(); + noted.resize(finishing.length); + share_out_ordered(finishing.length, this.options.threads, &alone, def(k: u64): void { + compiler.finish_unfinished(finishing[k], &plan.ranks, &mut noted[k]); + }); + for &each in found { + for &text in each { + this.problems.append(string::copy_of(&text)); + } + } + for &each in noted { + for &text in each { + this.problems.append(string::copy_of(&text)); + } + } + + if this.versions_made() { + for place in 0..count { + this.make_version(plan.order[place], &mut plan.ranks, (2 * place + 3) as u32); + } + } + this.merge_all(); +} + +#! Merges the stores filling 16 bytes of a cell, in each function of an +#! executable optimized, once nothing more is inlined, as `merge.sakura` says. +#! @param this The compiler. +def lowerer::merge_all(&mut this): void { + for i in 0..this.program.functions.length { + val function := &mut this.program.functions[i]; + continue if !function.optimized || !function.body.vectors; + val point := mark_scratch(); + if function.body.merge_stores() { + function.body.compact(); + if this.options.verify { + val verdict := function.body.verify(); + for &each in verdict.problems { + this.problems.append($"{function.name}: after merging stores: {each}"); + } + } + } + release_scratch(point); + } +} + +#! Whether calls of `@inline` functions are inlined below `-O2`, which inlines +#! nothing else: but where the program evaluates constants, or runs with its +#! memory checked, as each function's locals end where its frame does then. +#! @param this The compiler. +#! @returns Whether they are. +def lowerer::inlines_marked(&this): bool { + return !this.options.evaluating && !this.options.checks; +} + +#! Whether `-O0`, which optimizes nothing, has calls to inline all the same: +#! where a function lowered is `@inline`. +#! @param this The compiler. +#! @returns Whether it has. +def lowerer::copies_marked(&this): bool { + return false if !this.inlines_marked(); + for &each in this.program.functions { + return true if each.inline && each.lowered; + } + return false; +} + +#! Where a function never optimized is in the order functions are optimized in. +const unranked: u32 = 0xFFFFFFFF; + +#! The order functions are optimized in, and what each waits for. +struct optimizing { + var order: vector; #! The functions, each after those it calls, but for those calling each other. + var ranks: vector; #! Of each function, `2k + 2` where it is the `k`th in the order, `2k + 3` where it is the version of that one, 0 where it was optimized before, and `unranked` where it is not optimized. + var waiting: groups; #! The places in the order of those waiting on each, by its place: each calls it, and comes after it. +} + +#! A function on the walk of the calls that orders functions to be optimized. +struct calling { + var function: u32; #! The function. + var begin: u64; #! Where the functions it calls begin among the calls of those on the walk. + var end: u64; #! Where they end. + var next: u64; #! The next of them to walk. +} + +#! Works out the order functions are optimized in: walking the calls from each +#! function lowered and not yet optimized, each once those it calls are, but +#! for those calling each other, which go in the order met. Each waits for the +#! functions before it that it calls. +#! @param this The compiler. +#! @returns The order. +def lowerer::plan_optimizing(&mut this): optimizing { + val count := this.program.functions.length; + var plan := optimizing { + order = vector::::new(), + ranks = vector::::new(), + waiting = groups::::new(0) + }; + var seen := vector::::new(); + seen.resize(count); + plan.ranks.resize(count); + for i in 0..count { + if this.program.functions[i].optimized { + seen[i] = true; + this.ready_to_inline(i as u32); + } else { + plan.ranks[i] = unranked; + } + } + + # The functions on the walk, each with the functions it calls in `calls`. + # The callees of each function in the order are kept in `callees`, a run of + # each. + var stack := vector::::new(); + var calls := vector::::new(); + var callees := runs::::new(); + var callee_runs := vector::::new(); + for root in 0..count { + continue if seen[root] || !this.program.functions[root].lowered; + this.walk_into(root as u32, &mut seen, &mut stack, &mut calls); + while stack.length != 0 { + # The top is written before a callee is pushed, which may move it. + val top := &mut stack.last(); + if top.next < top.end { + val callee: u32 = calls[top.next]; + top.next++; + if !seen[callee] && this.program.functions[callee].lowered { + this.walk_into(callee, &mut seen, &mut stack, &mut calls); + } + continue; + } + callee_runs.append(callees.add(span::::over(calls.view().data + top.begin, top.end - top.begin))); + plan.ranks[top.function] = (2 * plan.order.length + 2) as u32; + plan.order.append(top.function); + calls.resize(top.begin); + stack.truncate(); + } + } + + # Each function waits for those before it that it calls, each once, as the + # functions counted for it say. + val placed := plan.order.length; + var counted := stamped_set::new(placed, nothing {}); + var pairs := vector::::new(); + plan.waiting.reset(placed); + for p in 0..placed { + counted.next_round(); + for &callee in callees.view(callee_runs[p]) { + val rank: u32 = plan.ranks[callee]; + continue if rank == 0 || rank == unranked; + val q := (rank - 2) / 2; + continue if q as u64 >= p || !counted.insert(q); + pairs.append(pair_key(q, p as u32)); + plan.waiting.count(q); + } + } + plan.waiting.seal(); + for &pair in pairs { + plan.waiting.put(pair_high(pair), pair_low(pair)); + } + this.find_sole_calls(&plan.order); + + # A call of a function this one waits for is settled, and stays so where it is + # inlined into another, which waited for this one. + for p in 0..placed { + val function: u32 = plan.order[p]; + val body := &mut this.program.functions[function].body; + var walk := body.walk_all(); + while walk.more() { + val at := walk.next(); + continue if body.insts[at].kind != op::call; + val rank: u32 = plan.ranks[body.insts[at].aux]; + body.insts[at].imm = rank != 0 && rank != unranked && rank < plan.ranks[function] ? call_settled : 0; + } + } + return plan; +} + +#! Puts a function on the walk, with the functions it calls. +#! @param this The compiler. +#! @param function The function. +#! @param seen Whether each function was put on the walk. +#! @param stack The functions on the walk. +#! @param calls The callees of the functions on the walk. +def lowerer::walk_into(&mut this, function: u32, seen: &mut vector, stack: &mut vector, calls: &mut vector): void { + seen[function] = true; + val begin := calls.length; + val body := &this.program.functions[function].body; + var walk := body.walk_all(); + while walk.more() { + val at := walk.next(); + if body.insts[at].kind == op::call { + calls.append(body.insts[at].aux); + } + } + # A function named as a value may be called directly once the value is known, + # so it is waited for as one called is. + for &named in this.program.functions[function].named.view() { + calls.append(named); + } + stack.append(calling { function = function, begin = begin, end = calls.length, next = begin }); +} + +#! Optimizes the function of a place in the order, then readies it to be +#! inlined. +#! @param this The compiler. +#! @param plan The order. +#! @param place The place. +#! @param found Where what verifying it finds is noted. +def lowerer::optimize_at(&mut this, plan: &optimizing, place: u64, found: &mut vector): void { + val function: u32 = plan.order[place]; + this.optimize_function(function, &plan.ranks, (2 * place + 2) as u32, found); + this.program.functions[function].optimized = true; + this.ready_to_inline(function); +} + +#! Finds the functions left unfinished that something still reaches. +#! @param this The compiler. +#! @returns The functions, in order. +def lowerer::left_unfinished(&mut this): vector { + var left := vector::::new(); + val count := this.program.functions.length; + var any := false; + for i in 0..count { + any = any || this.program.functions[i].unfinished; + } + return left if !any; + val point := mark_scratch(); + var reached := worklist::new(count, scratch()); + this.reach_functions(&mut reached); + for i in 0..count { + if this.program.functions[i].unfinished && reached.has(i as u32) { + left.append(i as u32); + } + } + release_scratch(point); + return left; +} + +#! Runs the rest of the passes on a function left unfinished, then readies it +#! to be inlined again, as its code changed. +#! @param this The compiler. +#! @param function The function. +#! @param ranks Where each function is in the order functions are +#! optimized in, which none of the passes left inlines by. +#! @param found Where what verifying it finds is noted. +def lowerer::finish_unfinished(&mut this, function: u32, ranks: &vector, found: &mut vector): void { + var sweep := passes { ranks = ranks, rank = 0, found = found, compacted = 0xFFFFFFFF }; + for i in 0..pass::count as u64 { + sweep.clean[i] = 0xFFFFFFFF; + } + this.finish_function(function, &mut sweep); + val held := &mut this.program.functions[function]; + held.unfinished = false; + held.inlining = inline_facts { sole = held.inlining.sole }; + held.order.clear(); + this.ready_to_inline(function); +} + +#! Works out what inlining an optimized function asks of it, as its code no +#! longer changes, rather than leave that to the first function inlining it, +#! as several may at once on threads of their own: what inlining knows of it, +#! and where it may be copied, the order its blocks are copied in. +#! @param this The compiler. +#! @param function The function. +def lowerer::ready_to_inline(&mut this, function: u32): void { + # Below `-O2`, only `@inline` functions are. + return if this.options.level < 2 && !this.program.functions[function].inline; + val point := mark_scratch(); + if this.inline_facts(function).fits { + this.order_blocks(function); + } + release_scratch(point); +} + +#! Optimizes one function, as its level says. A pass that found nothing to +#! change is not run again until another changes something. +#! @param this The compiler. +#! @param index The function. +#! @param ranks Where each function is in the order functions are optimized +#! in, as `optimizing` says: those before it are inlined. +#! @param rank Where the function is. +#! @param found Where what verifying it finds is noted. +def lowerer::optimize_function(&mut this, index: u32, ranks: &vector, rank: u32, found: &mut vector): void { + var sweep := passes { ranks = ranks, rank = rank, found = found, compacted = 0xFFFFFFFF }; + for i in 0..pass::count as u64 { + sweep.clean[i] = 0xFFFFFFFF; + } + # `-O0` inlines the calls of `@inline` functions, and changes nothing else. + if this.options.level == 0 { + this.sweep(index, &mut sweep, pass::inline); + if sweep.changes != 0 { + this.compact_function(index, &mut sweep); + } + return; + } + + this.sweep(index, &mut sweep, pass::simplify); + this.sweep(index, &mut sweep, pass::control); + if this.options.level < 2 && this.inlines_marked() { + this.sweep(index, &mut sweep, pass::inline); + } + if this.options.level >= 2 { + this.sweep(index, &mut sweep, pass::dead); + this.sweep(index, &mut sweep, pass::inline); + this.sweep(index, &mut sweep, pass::promote); + this.sweep(index, &mut sweep, pass::simplify); + this.sweep(index, &mut sweep, pass::control); + # Promoting may show which function a value calls, which is then called and + # inlined as any other. + this.sweep(index, &mut sweep, pass::inline); + this.sweep(index, &mut sweep, pass::promote); + this.sweep(index, &mut sweep, pass::simplify); + this.sweep(index, &mut sweep, pass::control); + # The function calling it copies it whole and optimizes it there, so the + # rest is left until then, and run after only where it is still called. + if this.awaits_caller(index) { + this.program.functions[index].unfinished = true; + return; + } + } + this.finish_function(index, &mut sweep); +} + +#! Runs the passes after inlining on a function's code, then compacts it. +#! @param this The compiler. +#! @param index The function. +#! @param sweep What is known of the passes run on it. +def lowerer::finish_function(&mut this, index: u32, sweep: &mut passes): void { + this.sweep(index, sweep, pass::numbering); + this.sweep(index, sweep, pass::memory); + this.sweep(index, sweep, pass::dead); + this.sweep(index, sweep, pass::loops); + this.sweep(index, sweep, pass::numbering); + this.sweep(index, sweep, pass::simplify); + this.sweep(index, sweep, pass::control); + this.sweep(index, sweep, pass::sink); + # What sinking moved past a branch, as a `select` on the condition the branch + # tests, is numbered again where the branch decided it. + this.sweep(index, sweep, pass::numbering); + this.sweep(index, sweep, pass::dead); + this.sweep(index, sweep, pass::hoist); + this.compact_function(index, sweep); +} + +#! Whether a function, its calls inlined, is left for the function calling it +#! to optimize: that alone calls it, and copies it whole, as it may be copied, +#! asks nothing of the processor, and leaves that function room to grow. +#! @param this The compiler. +#! @param index The function. +#! @returns Whether it is. +def lowerer::awaits_caller(&this, index: u32): bool { + val held := &this.program.functions[index]; + return false if held.inlining.sole == 0 || held.closure || held.evaluation != 0; + var size: u32 = 0; + var walk := held.body.walk_all(); + while walk.more() { + match held.body.insts[walk.next()].kind { + op::frame, op::ready, op::reach, op::same, op::cpu => { return false; } + else => {} + } + size++; + } + return size <= sole_growth; +} + +#! What optimizing one function knows of the passes run on it. +struct passes { + var ranks: &vector; #! Where each function is in the order functions are optimized in. + var rank: u32; #! Where the function is. + var found: &mut vector; #! What verifying it finds. + var changes: u32; #! How many passes changed something. + var compacted: u32; #! How many passes had changed something when the code was last compacted, or `0xFFFFFFFF` before it was. + var clean: u32[pass::count as u64]; #! How many passes had changed something when each last found nothing to change. +} + +#! Runs a pass over a function's code, but where it found nothing to change +#! since any pass last changed something. +#! @param this The compiler. +#! @param index The function. +#! @param sweep What is known of the passes run on it. +#! @param which The pass. +def lowerer::sweep(&mut this, index: u32, sweep: &mut passes, which: pass): void { + return if sweep.clean[which as u64] == sweep.changes; + if this.run_pass(index, which, sweep) { + sweep.changes++; + } else { + sweep.clean[which as u64] = sweep.changes; + } +} + +#! Compacts a function's code where a pass changed it since it was last +#! compacted, then verifies it where lowering verifies. +#! @param this The compiler. +#! @param index The function. +#! @param sweep What is known of the passes run on it. +def lowerer::compact_function(&mut this, index: u32, sweep: &mut passes): void { + return if sweep.compacted == sweep.changes; + sweep.compacted = sweep.changes; + val point := mark_scratch(); + this.program.functions[index].body.compact(); + if this.options.verify { + val verdict := this.program.functions[index].body.verify(); + for &each in verdict.problems { + sweep.found.append($"{this.program.functions[index].name}: after compacting: {each}"); + } + } + release_scratch(point); +} + +#! Cleans up the memory of the cells of a function's code, knowing what each +#! call writes what it returns to. +#! @param this The compiler. +#! @param index The function. +#! @returns Whether anything changed. +def lowerer::clean_memory(&mut this, index: u32): bool { + val writes := this.result_writes(index); + return this.program.functions[index].body.clean_memory(writes.view()); +} + +#! How many bytes each call of a function's code writes what it returns to, at +#! the address its last operand gives, as `emitter::call_with` passes it. Each +#! instruction is looked at where it lies, those taken out too, which nothing +#! asks of. +#! @param this The compiler. +#! @param index The function. +#! @returns The bytes, by instruction, or 0 for what writes none. +pub def lowerer::result_writes(&this, index: u32): vector { + val body := &this.program.functions[index].body; + var writes := vector::::new(scratch()); + writes.resize(body.insts.length); + for at in 1..body.insts.length { + val kind := body.insts[at].kind; + val aux: u32 = body.insts[at].aux; + var signature: u32 = no_function; + if kind == op::call { + signature = this.program.functions[aux].signature; + } else if kind == op::call_trait || kind == op::call_value || kind == op::call_c { + signature = aux; + } + continue if signature == no_function; + val shape := this.layout_at(this.program.signatures[signature].result); + if returned_in_memory(&shape) { + writes[at] = shape.size; + } + } + return writes; +} + +#! Runs a pass over a function's code, then verifies it where lowering +#! verifies, noting what is wrong with what the pass left. +#! @param this The compiler. +#! @param index The function. +#! @param which The pass. +#! @param sweep What is known of the passes run on it. +#! @returns Whether the pass changed anything. +def lowerer::run_pass(&mut this, index: u32, which: pass, sweep: &mut passes): bool { + # What the pass and the verifier work out is freed as the pass ends. + val point := mark_scratch(); + val body := &mut this.program.functions[index].body; + val changed := match which { + pass::simplify => body.simplify(this.program.data.view()), + pass::dead => body.remove_dead(), + pass::control => body.clean_control(), + pass::inline => this.inline_calls(index, sweep.ranks, sweep.rank), + pass::promote => body.promote_cells(), + pass::numbering => this.number_values(index), + pass::hoist => body.hoist_constants(), + pass::memory => this.clean_memory(index), + pass::loops => this.optimize_loops(index), + pass::sink => this.sink_code(index), + else => false + }; + # Each pass forgets the order and dominators the code keeps where it changes + # where blocks lead, or works them out anew, as pruning does after inlining, + # so they hold for the code it leaves. + if this.options.verify && changed { + val verdict := this.program.functions[index].body.verify(); + for &each in verdict.problems { + sweep.found.append($"{this.program.functions[index].name}: after {which.name()}: {each}"); + } + } + release_scratch(point); + return changed; +} diff --git a/compiler/optimizer/promote.sakura b/compiler/optimizer/promote.sakura new file mode 100644 index 00000000..3511a0a8 --- /dev/null +++ b/compiler/optimizer/promote.sakura @@ -0,0 +1,887 @@ +#! @file promote.sakura +#! @author John Christman (sorakatadzuma@gmail.com) +#! @copyright Malunal Studios, LLC. +#! @license MIT +#! +#! Contains the fifth pass of the optimizer, which promotes cells to values: a +#! cell whose address is only read from, written to, zeroed, or copied in and +#! out from its start, at offsets that do not overlap, holds values rather than +#! memory. Each word it holds becomes a variable, and the code is rebuilt as it +#! was built, each read reading what the variable holds there, which where +#! control flow joins is a parameter of the block. The bytes a copy moves that +#! nothing reads or writes alone are words of their own, so a value copied from +#! one cell to another and on is promoted whole. Inlining leaves many such +#! cells, where a function took the address of what it was given or returned. +#! A `simd` read and written whole becomes one vector, which an executable holds +#! in a vector register, but 32 bytes only in code for processors with AVX. + +import std::containers; +module sakura::compiler; + + +#! A word a cell promoted holds: where it is in the cell, how wide it is, and +#! the type of value it holds. +struct slot { + var cell: u32; #! The cell. + var offset: u64; #! Where it begins. + var size: u64; #! How many bytes it is. + var kind: vt; #! The type of value it holds. + var signed: bool; #! Whether it is read as a signed integer narrower than a word, which a copy narrows it as too. + var next: u32; #! One more than the next slot of the same cell, or 0. + var used: bool; #! Whether anything reads what it holds, or copies it out. +} + +#! What promoting knows of the cells of the code. +struct promotion { + var escaped: vector; #! Whether each cell's address is used as more than an address read and written through. + var extent: vector; #! How many bytes from its start the copies in and out of each cell move, which its slots must cover. + var slots: vector; #! The words of the cells, each once. + var heads: vector; #! One more than the first slot of each cell, or 0, its others following by `next`. + var addresses: cell_table; #! Which cell each value is the address of. + var ends: dict; #! The value each slot holds at the end of each block that writes it, by `pair_key(slot, block)`. + var starts: dict; #! The value each slot holds at the start of each block asked, by `pair_key(slot, block)`. + var zeros: zero_values; #! The zero of each type, made once. + var wide: bool; #! Whether 32 bytes of lanes may be a value. + var vectors: bool; #! Whether 16 bytes of lanes may be, as an executable's code holds them. + var pairs: vector; #! The copies from one cell into another. + var copies: dict; #! The read each copy into a cell promoted makes of each slot, by `pair_key(copy, slot)`. + var touch: vector; #! The instructions naming a cell, as operands or as what their edges give. + var current: vector; #! What each slot holds where the walk of a block is, where the block wrote it. + var written: stamped_set; #! The slots the block being rewritten wrote so far, a round each block. + var dense: u64; #! How many blocks `ends` and `starts` are held for in `dense_ends` and `dense_starts`, by slot then block, or 0 where they are not. + var dense_ends: vector; #! What `ends` holds, where it is dense, 0 for nothing. + var dense_starts: vector; #! What `starts` holds, where it is dense. +} + +#! What `promotion::slot_at` gives where a cell has no slot at an offset. +const no_slot: u32 = 0xFFFFFFFF; + +#! The most slots of every block the values they hold at each block's ends are +#! held for one after another, rather than by key. +const dense_slot_blocks: u64 = 65536; + +#! The value a slot holds where a block ends, where the block writes it. +#! @param this What promoting knows. +#! @param s The slot. +#! @param block The block. +#! @returns The value, or 0. +def promotion::end_at(&this, s: u32, block: u32): u32 { + return this.dense_ends[s as u64 * this.dense + block as u64] if this.dense != 0; + val key := pair_key(s, block); + return this.ends.get_or(&key, 0); +} + +#! Notes the value a slot holds where a block ends. +#! @param this What promoting knows. +#! @param s The slot. +#! @param block The block. +#! @param value The value. +def promotion::set_end(&mut this, s: u32, block: u32, value: u32): void { + if this.dense != 0 { + this.dense_ends[s as u64 * this.dense + block as u64] = value; + return; + } + this.ends.set(pair_key(s, block), value); +} + +#! The value a slot holds where a block begins, where it is known. +#! @param this What promoting knows. +#! @param s The slot. +#! @param block The block. +#! @returns The value, or 0. +def promotion::start_at(&this, s: u32, block: u32): u32 { + return this.dense_starts[s as u64 * this.dense + block as u64] if this.dense != 0; + val key := pair_key(s, block); + return this.starts.get_or(&key, 0); +} + +#! Notes the value a slot holds where a block begins. +#! @param this What promoting knows. +#! @param s The slot. +#! @param block The block. +#! @param value The value. +def promotion::set_start(&mut this, s: u32, block: u32, value: u32): void { + if this.dense != 0 { + this.dense_starts[s as u64 * this.dense + block as u64] = value; + return; + } + this.starts.set(pair_key(s, block), value); +} + +#! Promotes the cells that can be, as the file says. +#! @param this The code. +#! @returns Whether any was. +pub def code::promote_cells(&mut this): bool { + return false if this.cells.length == 0; + var state := promotion { + escaped = vector::::new(scratch()), + extent = vector::::new(scratch()), + slots = vector::::new(scratch()), + heads = vector::::new(scratch()), + addresses = this.cell_table(), + ends = dict::::new(scratch()), + starts = dict::::new(scratch()), + copies = dict::::new(scratch()), + pairs = vector::::new(scratch()), + touch = vector::::new(scratch()), + current = vector::::new(scratch()), + written = stamped_set::new(0, scratch()), + dense_ends = vector::::new(scratch()), + dense_starts = vector::::new(scratch()), + wide = this.wide, + vectors = this.vectors + }; + return false if !state.addresses.any; + state.escaped.resize(this.cells.length); + state.extent.resize(this.cells.length); + state.heads.resize(this.cells.length); + + # A copy from a cell its words cover into another is the reads and writes of + # each word, which then promote as any others, so the words of the cells + # are found again, as many times as a value is copied on. + this.find_touches(&mut state); + var rounds := 0; + while true { + rounds++; + this.find_slots(&mut state); + break if rounds == 4 || !this.split_pairs(&mut state); + for c in 0..this.cells.length { + state.escaped[c] = false; + state.extent[c] = 0; + state.heads[c] = 0; + } + state.slots.clear(); + state.pairs.clear(); + } + this.settle_pairs(&mut state); + var promoted := false; + for c in 0..this.cells.length { + if !state.escaped[c] { + promoted = true; + } + } + return false if !promoted; + + # Where control flow joins, slots are found in the order of the blocks. + if state.slots.length * this.blocks.length <= dense_slot_blocks { + state.dense = this.blocks.length; + state.dense_ends.resize(state.slots.length * state.dense); + state.dense_starts.resize(state.slots.length * state.dense); + } + var order := vector::::new(scratch()); + var number := vector::::new(scratch()); + this.block_order(&mut order, &mut number); + for &block in order { + this.note_ends(block, &mut state); + } + var done := rewrite::new(); + state.current.resize(state.slots.length); + state.written = stamped_set::new(state.slots.length, scratch()); + for &block in order { + state.written.next_round(); + this.rewrite_slots(block, &mut state, &mut done); + } + this.apply(&done); + this.drop_unreached(); + this.drop_lone_params(); + return true; +} + +#! Finds the instructions naming a cell, which are all that finding slots +#! walks. +#! @param this The code. +#! @param state What promoting knows. +def code::find_touches(&this, state: &mut promotion): void { + state.touch.clear(); + var walk := this.walk_all(); + var reads := this.reader(); + while walk.more() { + val at := walk.next(); + reads.start(at); + while reads.more() { + if state.addresses.cell(reads.next()) != 0 { + state.touch.append(at); + break; + } + } + } +} + +#! Leaves memory the cell each copy between cells neither escaped comes from, +#! where the copy was not split, so the copy is one out of memory into the one +#! it goes to. +#! @param this The code. +#! @param state What promoting knows. +def code::settle_pairs(&this, state: &mut promotion): void { + var changed := false; + for © in state.pairs { + val to := state.addresses.cell(this.arg(copy, 0)) - 1; + val from := state.addresses.cell(this.arg(copy, 1)) - 1; + if !state.escaped[to] && !state.escaped[from] { + state.escaped[from] = true; + changed = true; + } + } + if changed { + this.find_uses(state); + } +} + +#! Marks the slots of the cells not escaped that something reads, or copies +#! out of its cell, so a copy into the cell reads only those from where it +#! copies, and a slot read only as a copy moves it into another is used where +#! the other's is. +#! @param this The code. +#! @param state What promoting knows. +def code::find_uses(&this, state: &mut promotion): void { + for i in 0..state.slots.length { + state.slots[i].used = false; + } + for t in 0..state.touch.length { + val at: u32 = state.touch[t]; + val held: inst = this.insts[at]; + continue if held.kind != op::load && held.kind != op::copy; + val operand: u32 = held.kind == op::load ? 0 : 1; + val cell := state.addresses.cell(this.arg(at, operand)); + val into := held.kind == op::copy ? state.addresses.cell(this.arg(at, 0)) : 0; + val moved := into != 0 && !state.escaped[into - 1]; + continue if cell == 0 || state.escaped[cell - 1] || moved; + var i: u32 = state.heads[cell - 1]; + while i != 0 { + val each: slot = state.slots[i - 1]; + if (held.kind == op::load && each.offset == held.imm) || (held.kind == op::copy && each.offset < held.imm) { + state.slots[i - 1].used = true; + } + i = each.next; + } + } + + var changed := true; + var rounds := 0; + while changed && rounds < 8 { + rounds++; + changed = false; + for p in 0..state.pairs.length { + val copy: u32 = state.pairs[p]; + val to := state.addresses.cell(this.arg(copy, 0)) - 1; + val from := state.addresses.cell(this.arg(copy, 1)) - 1; + continue if state.escaped[to] || state.escaped[from]; + var i: u32 = state.heads[from]; + while i != 0 { + val each: slot = state.slots[i - 1]; + if !each.used && each.offset < this.insts[copy].imm && state.used_over(to, each.offset, each.size) { + state.slots[i - 1].used = true; + changed = true; + } + i = each.next; + } + } + } +} + +#! Finds how each cell's address is used, and the words each cell not escaped +#! holds, marking escaped a cell its words do not fit, and which of its words +#! are used. Copies between cells are gathered, to be split. +#! @param this The code. +#! @param state What promoting knows, whose instructions naming cells are +#! found. +def code::find_slots(&this, state: &mut promotion): void { + var reads := this.reader(); + for t in 0..state.touch.length { + val at: u32 = state.touch[t]; + val held: inst = this.insts[at]; + reads.start(at); + while reads.more() { + val cell := state.addresses.cell(reads.next()); + continue if cell == 0; + val c := cell - 1; + val i := reads.operand(); + # A cell's address an edge gives escapes. + if i == no_operand { + state.escaped[c] = true; + continue; + } + match held.kind { + op::load => { + val how := held.aux as access; + state.add_slot(c, held.imm, how.width(), how.value_type(), narrow_signed(how)); + } + op::store => { + if i == 0 { + state.add_slot(c, held.imm, (held.aux as access).width(), (held.aux as access).value_type(), false); + } else { + state.escaped[c] = true; + } + } + # A cell's address is never null, which inlining may check. + op::clear => {} + op::check => { + if held.aux != fault::null_reference as u32 { + state.escaped[c] = true; + } + } + op::copy => { + # A copy in or out of the cell from its start, between it and memory + # no cell promoted is, reads or writes each of the words it moves. + if held.imm > this.cells[c].size as u64 { + state.escaped[c] = true; + } else { + if i == 0 && state.addresses.cell(this.arg(at, 1)) != 0 { + state.pairs.append(at); + } + if held.imm > state.extent[c] { + state.extent[c] = held.imm; + } + } + } + else => state.escaped[c] = true; + } + } + } + + # A copy between cells moves the words either reads or writes alone, so each + # holds the other's, from one to the next along a chain of copies. + var rounds := 0; + var changed := state.pairs.length != 0; + while changed && rounds < 8 { + rounds++; + changed = false; + for p in 0..state.pairs.length { + val copy: u32 = state.pairs[p]; + val to := state.addresses.cell(this.arg(copy, 0)) - 1; + val from := state.addresses.cell(this.arg(copy, 1)) - 1; + val size: u64 = this.insts[copy].imm; + changed = state.share_slots(from, to, size) || changed; + changed = state.share_slots(to, from, size) || changed; + } + } + + # Each cell's words must not overlap, and the bytes its copies move that no + # word holds are words of their own. + for c in 0..this.cells.length { + continue if state.escaped[c]; + var i: u32 = state.heads[c]; + while i != 0 { + val each: slot = state.slots[i - 1]; + var j: u32 = each.next; + while j != 0 { + val other: slot = state.slots[j - 1]; + if other.offset < each.offset + each.size && each.offset < other.offset + other.size { + state.escaped[c] = true; + } + j = other.next; + } + i = each.next; + } + if !state.escaped[c] && state.extent[c] != 0 { + state.fill_gaps(c as u32); + } + } + + # Nor may a clear or a copy end within a word. + for t in 0..state.touch.length { + val at: u32 = state.touch[t]; + val held: inst = this.insts[at]; + continue if held.kind != op::clear && held.kind != op::copy; + for k in 0..held.argc { + val cell := state.addresses.cell(this.arg(at, k as u32)); + continue if cell == 0 || state.escaped[cell - 1]; + val c := cell - 1; + var i: u32 = state.heads[c]; + while i != 0 { + val each: slot = state.slots[i - 1]; + if each.offset < held.imm && held.imm < each.offset + each.size { + state.escaped[c] = true; + } + i = each.next; + } + } + } + this.find_uses(state); +} + +#! Gives a cell the words another holds within the bytes a copy between them +#! moves, which it does not hold yet. An escaped cell's words say nothing of +#! the values another holds, as an array indexed holds what is read of it one +#! lane at a time, so it gives none, and a vector copied into it stays one. +#! @param this What promoting knows. +#! @param from The cell whose words are given. +#! @param to The cell given them. +#! @param size How many bytes the copy moves. +#! @returns Whether any was new. +def promotion::share_slots(&mut this, from: u32, to: u32, size: u64): bool { + return false if from == to || this.escaped[to] || this.escaped[from]; + var added := false; + var i: u32 = this.heads[from]; + while i != 0 { + val each: slot = this.slots[i - 1]; + i = each.next; + continue if each.offset >= size || this.slot_at(to, each.offset) != no_slot; + this.add_slot(to, each.offset, each.size, each.kind, each.signed); + added = true; + } + return added; +} + +#! Gives the bytes a cell's copies move that no word holds words of their own, +#! each as wide as where it begins and the bytes left allow. +#! @param this What promoting knows. +#! @param cell The cell, whose words do not overlap. +def promotion::fill_gaps(&mut this, cell: u32): void { + # The words it holds, by where each begins. + var held := vector::::new(scratch()); + var i: u32 = this.heads[cell]; + while i != 0 { + val each: slot = this.slots[i - 1]; + held.append(pair_key(each.offset as u32, each.size as u32)); + i = each.next; + } + held.sort(); + + val extent: u64 = this.extent[cell]; + var at: u64 = 0; + for &key in held { + break if at >= extent; + val offset := pair_high(key) as u64; + this.fill(cell, at, offset < extent ? offset : extent); + val end := offset + pair_low(key) as u64; + if end > at { + at = end; + } + } + this.fill(cell, at, extent); +} + +#! Gives bytes of a cell no word holds words of their own: in an executable's +#! code, each 16 bytes from a multiple of 16 a vector, which a copy moves with +#! one read and write, or 32 from a multiple of 32 in code for processors with +#! AVX, and the rest words. +#! @param this What promoting knows. +#! @param cell The cell. +#! @param from Where the bytes begin. +#! @param to Where they end. +def promotion::fill(&mut this, cell: u32, from: u64, to: u64): void { + var at := from; + while this.wide && at % 32 == 0 && at + 32 <= to { + this.add_slot(cell, at, 32, vt::v256, false); + at += 32; + } + while this.vectors && at % 16 == 0 && at + 16 <= to { + this.add_slot(cell, at, 16, vt::v128, false); + at += 16; + } + while at < to { + var width: u64 = 8; + while width > 1 && (at % width != 0 || at + width > to) { + width = width / 2; + } + this.add_slot(cell, at, width, vt::word, false); + at += width; + } +} + +#! Splits each copy from a cell its words cover whole, and not escaped, into +#! another into a read of each word and a write of it where it goes. +#! @param this The code. +#! @param state What promoting knows. +#! @returns Whether any copy was split. +def code::split_pairs(&mut this, state: &mut promotion): bool { + var done := rewrite::new(); + var added := vector::::new(scratch()); + for p in 0..state.pairs.length { + val copy: u32 = state.pairs[p]; + val held: inst = this.insts[copy]; + val source := state.addresses.cell(this.arg(copy, 1)) - 1; + continue if state.escaped[source]; + var covered: u64 = 0; + var i: u32 = state.heads[source]; + while i != 0 { + if state.slots[i - 1].offset < held.imm { + covered += state.slots[i - 1].size; + } + i = state.slots[i - 1].next; + } + continue if covered != held.imm; + + # Only the words the cell it goes to reads go, where it holds them, each + # after the copy, which goes. + val target := state.addresses.cell(this.arg(copy, 0)) - 1; + var after := copy; + i = state.heads[source]; + while i != 0 { + val each: slot = state.slots[i - 1]; + i = each.next; + continue if each.offset >= held.imm; + val there := state.slot_at(target, each.offset); + continue if !state.escaped[target] && there != no_slot && !state.slots[there].used; + var from: u32[1] = [this.arg(copy, 1)]; + var gives: vt[1] = [each.kind]; + val how := slot_access(&each) as u32; + val load := this.detached(op::load, from[0:1], gives[0:1], how, each.offset, held.at, held.site); + this.link_after(load, after); + var to: u32[2] = [this.arg(copy, 0), this.insts[load].result]; + val store := this.detached(op::store, to[0:2], span::::empty(), how, each.offset, held.at, held.site); + this.link_after(store, load); + after = store; + added.append(load); + added.append(store); + } + done.remove(copy); + } + return false if !done.changed; + this.apply(&done); + + # The instructions naming cells are those that did but the copies split, and + # the reads and writes they became. + var kept: u64 = 0; + for t in 0..state.touch.length { + val at: u32 = state.touch[t]; + if !done.is_removed(at) { + state.touch[kept] = at; + kept++; + } + } + state.touch.resize(kept); + state.touch.extend(added.view()); + return true; +} + +#! Adds a word to those a cell holds, where it is new, marking the cell +#! escaped where the same offset is read or written as another width or kind, +#! or where it is 32 bytes of lanes and the code may run without AVX, or 64. +#! @param this What promoting knows. +#! @param cell The cell. +#! @param offset Where the word begins. +#! @param size How many bytes it is. +#! @param kind The type of value it holds. +#! @param signed Whether it is read as a signed integer narrower than a word. +def promotion::add_slot(&mut this, cell: u32, offset: u64, size: u64, kind: vt, signed: bool): void { + # 64 bytes of lanes stay in memory, as only code knowing the processor has + # AVX-512 holds them. + if kind == vt::v512 || (kind == vt::v256 && !this.wide) { + this.escaped[cell] = true; + return; + } + var i: u32 = this.heads[cell]; + while i != 0 { + val each: slot = this.slots[i - 1]; + if each.offset == offset { + if each.size != size || each.kind != kind { + this.escaped[cell] = true; + } + if signed { + this.slots[i - 1].signed = true; + } + return; + } + i = each.next; + } + this.slots.append(slot { cell = cell, offset = offset, size = size, kind = kind, signed = signed, next = this.heads[cell] }); + this.heads[cell] = this.slots.length as u32; +} + +#! The slot of a cell at an offset, or `no_slot`. +#! @param this What promoting knows. +#! @param cell The cell. +#! @param offset Where the word begins. +#! @returns The slot's index. +def promotion::slot_at(&this, cell: u32, offset: u64): u32 { + var i: u32 = this.heads[cell]; + while i != 0 { + return i - 1 if this.slots[i - 1].offset == offset; + i = this.slots[i - 1].next; + } + return no_slot; +} + +#! Whether a slot of a cell that bytes of it lie within is used. The cell copied +#! into may hold a word over several of the other's, as a vector over a struct's +#! fields where one cell holds each in turn, so each of those is used where the +#! word over it is. +#! @param this What promoting knows. +#! @param cell The cell. +#! @param offset Where the bytes begin. +#! @param size How many there are. +#! @returns Whether one is. +def promotion::used_over(&this, cell: u32, offset: u64, size: u64): bool { + var i: u32 = this.heads[cell]; + while i != 0 { + val each: slot = this.slots[i - 1]; + return true if each.used && each.offset < offset + size && offset < each.offset + each.size; + i = each.next; + } + return false; +} + +#! Notes the value each slot holds at the end of a block that writes it: what +#! it last stores or copies in, or zero where it last clears it. +#! @param this The code. +#! @param block The block. +#! @param state What promoting knows. +def code::note_ends(&mut this, block: u32, state: &mut promotion): void { + var walk := this.walk(block); + while walk.more() { + val at := walk.next(); + val held: inst = this.insts[at]; + continue if held.argc == 0; + val target := state.addresses.cell(this.arg(at, 0)); + continue if target == 0 || state.escaped[target - 1]; + val c := target - 1; + match held.kind { + op::store => { + state.set_end(state.slot_at(c, held.imm), block, this.arg(at, 1)); + } + op::clear => { + var i: u32 = state.heads[c]; + while i != 0 { + val s := i - 1; + val each: slot = state.slots[s]; + i = each.next; + continue if each.offset >= held.imm; + state.set_end(s, block, state.zeros.of(this, each.kind)); + } + } + # A copy in reads each word something reads from where it comes from, + # read here, before any block asks what a slot holds. Where nothing reads + # any, its first is still read, so an address that cannot be read stops + # the program there as the copy did. + op::copy => { + var reads := !this.checked_address(at, this.arg(at, 1)); + var i: u32 = state.heads[c]; + while i != 0 { + val each: slot = state.slots[i - 1]; + if each.offset < held.imm && each.used { + reads = false; + } + i = each.next; + } + var after := at; + i = state.heads[c]; + while i != 0 { + val s := i - 1; + val each: slot = state.slots[s]; + i = each.next; + continue if each.offset >= held.imm || (!each.used && !(reads && each.offset == 0)); + var args: u32[1] = [this.arg(at, 1)]; + var gives: vt[1] = [each.kind]; + val load := this.detached(op::load, args[0:1], gives[0:1], slot_access(&each) as u32, each.offset, held.at, held.site); + this.link_after(load, after); + after = load; + val value: u32 = this.insts[load].result; + state.copies.set(pair_key(at, s), value); + state.set_end(s, block, value); + } + } + else => {} + } + } +} + +#! The value a slot holds at the start of a block: zero at the entry, what it +#! holds at the end of the one block going there, or else a parameter the +#! block takes, given what it holds at the end of each. +#! @param this The code. +#! @param s The slot. +#! @param block The block. +#! @param state What promoting knows. +#! @returns The value. +def code::slot_start(&mut this, s: u32, block: u32, state: &mut promotion): u32 { + val known := state.start_at(s, block); + return known if known != 0; + val kind := state.slots[s].kind; + val preds := this.blocks[block].preds.length; + if block == 0 || preds == 0 { + val zero := state.zeros.of(this, kind); + state.set_start(s, block, zero); + return zero; + } + if preds == 1 { + val edge: u32 = this.blocks[block].preds[0]; + val made := this.slot_end(s, this.edge_source(edge), state); + state.set_start(s, block, made); + return made; + } + + # Noted before its arguments are found, which may come back to it. + val param := this.add_param(block, kind); + state.set_start(s, block, param); + var edges := this.blocks[block].preds.copied(scratch()); + for &edge in edges { + val given := this.slot_end(s, this.edge_source(edge), state); + this.edges[edge].args.append(given); + } + return param; +} + +#! The value a slot holds at the end of a block. +#! @param this The code. +#! @param s The slot. +#! @param block The block. +#! @param state What promoting knows. +#! @returns The value. +def code::slot_end(&mut this, s: u32, block: u32, state: &mut promotion): u32 { + val known := state.end_at(s, block); + return known if known != 0; + return this.slot_start(s, block, state); +} + +#! Notes what a slot holds where the walk of a block is. +#! @param this What promoting knows. +#! @param s The slot. +#! @param value The value. +def promotion::hold(&mut this, s: u32, value: u32): void { + this.current[s] = value; + this.written.put(s); +} + +#! What a slot holds where the walk of a block is: what the block wrote last, +#! or what it holds where the block begins. +#! @param this The code. +#! @param s The slot. +#! @param block The block. +#! @param state What promoting knows. +#! @returns The value. +def code::slot_now(&mut this, s: u32, block: u32, state: &mut promotion): u32 { + return state.current[s] if state.written.contains(s); + return this.slot_start(s, block, state); +} + +#! Rewrites the reads and writes of the slots of a block: a read reads what +#! the slot holds there, narrowed as the read narrows, and a write, a clear, +#! and a copy in or out go, a copy becoming reads or writes of its words. +#! @param this The code. +#! @param block The block. +#! @param state What promoting knows. +#! @param done What the pass changes. +def code::rewrite_slots(&mut this, block: u32, state: &mut promotion, done: &mut rewrite): void { + var walk := this.walk(block); + while walk.more() { + val at := walk.next(); + val held: inst = this.insts[at]; + if held.kind == op::cell { + if !state.escaped[held.aux] { + done.remove(at); + } + continue; + } + continue if held.argc == 0; + + val first := state.addresses.cell(this.arg(at, 0)); + val c := first != 0 && !state.escaped[first - 1] ? first - 1 : no_cell; + match held.kind { + op::check => { + if c != no_cell { + done.remove(at); + } + } + op::load => { + if c != no_cell { + val s := state.slot_at(c, held.imm); + val value := this.slot_now(s, block, state); + this.read_slot(at, value, done); + } + } + op::store => { + if c != no_cell { + state.hold(state.slot_at(c, held.imm), this.arg(at, 1)); + done.remove(at); + } + } + op::clear => { + if c != no_cell { + var i: u32 = state.heads[c]; + while i != 0 { + val each: slot = state.slots[i - 1]; + if each.offset < held.imm { + state.hold(i - 1, state.zeros.of(this, each.kind)); + } + i = each.next; + } + done.remove(at); + } + } + op::copy => { + val from := state.addresses.cell(this.arg(at, 1)); + if c != no_cell { + # Copied in: each word is what was read of where it comes from. + var i: u32 = state.heads[c]; + while i != 0 { + val key := pair_key(at, i - 1); + if state.copies.get(&key) is some(got) { + state.hold(i - 1, got); + } + i = state.slots[i - 1].next; + } + done.remove(at); + } else if from != 0 && !state.escaped[from - 1] { + # Copied out: each word is written where it goes, after the copy, + # which goes. + val source := from - 1; + var after := at; + var i: u32 = state.heads[source]; + while i != 0 { + val s := i - 1; + val each: slot = state.slots[s]; + i = each.next; + continue if each.offset >= held.imm; + val value := this.slot_now(s, block, state); + var args: u32[2] = [this.arg(at, 0), value]; + val store := this.detached(op::store, args[0:2], span::::empty(), slot_access(&each) as u32, each.offset, held.at, held.site); + this.link_after(store, after); + after = store; + } + done.remove(at); + } + } + else => {} + } + } +} + +#! How a slot is read and written in memory where a copy moves it: a narrow +#! integer as it is read, so a field of `i32` copied is narrowed as a read of it +#! narrows it again, and the two are one. +#! @param each The slot. +#! @returns The access. +def slot_access(each: &slot): access { + return access::v128 if each.kind == vt::v128; + return access::v256 if each.kind == vt::v256; + return each.kind == vt::real ? (each.size == 4 ? access::f32 : access::f64) : match each.size { + 1 => each.signed ? access::i8 : access::u8, + 2 => each.signed ? access::i16 : access::u16, + 4 => each.signed ? access::i32 : access::u32, + else => access::i64 + }; +} + +#! Whether an access reads a signed integer narrower than a word. +#! @param how The access. +#! @returns Whether it does. +def narrow_signed(how: access): bool { + return how == access::i8 || how == access::i16 || how == access::i32; +} + +#! Makes a read of a slot the value it holds, narrowed as the read narrows. +#! @param this The code. +#! @param index The `load`. +#! @param value What the slot holds. +#! @param done What the pass changes. +def code::read_slot(&mut this, index: u32, value: u32, done: &mut rewrite): void { + val how: access = this.insts[index].aux as access; + var args: u32[1] = [value]; + match how { + access::i64, access::f64, access::v128, access::v256 => { + done.replace(this.insts[index].result, value); + done.remove(index); + } + access::f32 => this.become(index, op::fsingle, args[0:1], 0, 0); + access::u8 => this.become(index, op::wrap, args[0:1], 8, 0); + access::i8 => this.become(index, op::wrap, args[0:1], 8, 1); + access::u16 => this.become(index, op::wrap, args[0:1], 16, 0); + access::i16 => this.become(index, op::wrap, args[0:1], 16, 1); + access::u32 => this.become(index, op::wrap, args[0:1], 32, 0); + access::i32 => this.become(index, op::wrap, args[0:1], 32, 1); + else => {} + } + done.changed = true; +} diff --git a/compiler/optimizer/simplify.sakura b/compiler/optimizer/simplify.sakura new file mode 100644 index 00000000..04c5a6e9 --- /dev/null +++ b/compiler/optimizer/simplify.sakura @@ -0,0 +1,925 @@ +#! @file simplify.sakura +#! @author John Christman (sorakatadzuma@gmail.com) +#! @copyright Malunal Studios, LLC. +#! @license MIT +#! +#! Contains the first pass of the optimizer, simplification: an operator of +#! constants becomes the constant it gives, worked out exactly as the machine +#! works it out; an operator whose result its operands already say becomes +#! that, as `x + 0` is `x` and `x == x` is 1; a multiplication, division, or +#! remainder of an unsigned word by a power of two becomes a shift or a mask; +#! a comparison with the least or greatest word says what it says of every +#! word, or asks only whether a word is one; a constant added to a word with a +#! constant added becomes one sum; a read of a datum, which is never written, +#! becomes what its bytes hold; a condition another says the opposite of is +#! read through it; a `select` whose choice is known is what it chooses; and a +#! check of what is known to hold goes. + +module sakura::compiler; + + +#! Simplifies the code, as the file says, in one walk of its blocks. +#! @param this The code. +#! @param data The program's datums, which reads of them are read from. +#! @returns Whether anything changed. +pub def code::simplify(&mut this, data: span): bool { + var done := rewrite::new(); + var order := vector::::new(scratch()); + var number := vector::::new(scratch()); + this.block_order(&mut order, &mut number); + for &block in order { + var walk := this.walk(block); + while walk.more() { + this.simplify_inst(walk.next(), data, &mut done); + } + } + this.apply(&done); + return done.changed; +} + +#! Simplifies one instruction. +#! @param this The code. +#! @param index The instruction. +#! @param data The program's datums. +#! @param done What the pass changes. +def code::simplify_inst(&mut this, index: u32, data: span, done: &mut rewrite): void { + val held: inst = this.insts[index]; + val kind := held.kind; + val number := kind as u32; + + # Operands read what replaced them, so what is worked out of one value is + # worked out of what it was replaced by. + for i in 0..held.argc { + val at := held.args as u64 + i as u64; + this.operands[at] = done.resolve(this.operands[at]); + } + + if number >= op::add as u32 && number <= op::leus as u32 { + this.simplify_word(index, done); + return; + } + if number >= op::fadd as u32 && number <= op::fle as u32 { + var x: u64 = 0; + var y: u64 = 0; + if this.real_constant(this.arg(index, 0), &mut x) && this.real_constant(this.arg(index, 1), &mut y) { + var made: u64 = 0; + if fold_real(kind, x, y, &mut made) { + if number >= op::feq as u32 { + this.become_word(index, made); + } else { + this.become_real(index, made); + } + done.changed = true; + } + } + return; + } + if number >= op::neg as u32 && number <= op::bswap as u32 { + this.simplify_unary(index, done); + return; + } + + match kind { + op::wrap => this.simplify_wrap(index, done); + op::check => { + var bits: u64 = 0; + val cond := this.arg(index, 0); + if this.word_constant(cond, &mut bits) && bits != 0 { + done.remove(index); + return; + } + # The address of a cell, the globals, or a datum is never null. + val made := this.defining(cond); + if made != 0 && (this.insts[made].kind == op::cell || this.insts[made].kind == op::global || this.insts[made].kind == op::datum) { + done.remove(index); + return; + } + # A check of whether a word is not zero checks the word. + val inner := this.defining(cond); + if inner != 0 && this.insts[inner].kind == op::ne && this.is_zero(this.arg(inner, 1)) { + this.operands[held.args] = this.arg(inner, 0); + done.changed = true; + } + } + op::branch => this.simplify_branch(index, done); + op::select => this.simplify_select(index, done); + op::load => { + this.fold_offset(index, done); + this.read_datum(index, data, done); + } + op::store => { + this.fold_offset(index, done); + this.simplify_store(index, done); + } + else => {} + } +} + +#! The offsets a read or write may be given by folding: a page, less the widest +#! access. +const folded_reach: u64 = 4096 - 32; + +#! Folds a constant added to the address a read or write is given into its +#! offset, so it is addressed as `[base + offset]` and a cell read at a field is +#! read at that offset of the cell. Only offsets within the page no program +#! maps, which reaching through null faults in on its own; one past it would +#! need an executable to test the base first. +#! @param this The code. +#! @param index The `load` or `store`. +#! @param done What the pass changes. +def code::fold_offset(&mut this, index: u32, done: &mut rewrite): void { + val inner := this.defining(this.arg(index, 0)); + return if inner == 0 || this.insts[inner].kind != op::add; + var bits: u64 = 0; + var base: u32 = 0; + if this.word_constant(this.arg(inner, 1), &mut bits) { + base = this.arg(inner, 0); + } else if this.word_constant(this.arg(inner, 0), &mut bits) { + base = this.arg(inner, 1); + } else { + return; + } + val offset := this.insts[index].imm + bits; + return if bits >= folded_reach || offset >= folded_reach; + this.operands[this.insts[index].args as u64] = base; + this.insts[index].imm = offset; + done.changed = true; +} + +#! Reads while compiling what a read of a datum reads, since a datum is never +#! written: the word or real its bytes hold, or, for a whole word where a +#! relocation is, the address it holds. A read of an `f32`, of lanes, or across +#! part of an address stays. +#! @param this The code. +#! @param index The `load`. +#! @param data The program's datums. +#! @param done What the pass changes. +def code::read_datum(&mut this, index: u32, data: span, done: &mut rewrite): void { + val from := this.defining(this.arg(index, 0)); + return if from == 0 || this.insts[from].kind != op::datum; + val target: u64 = this.insts[from].aux; + return if target >= data.length; + val held := &data[target]; + val how := this.insts[index].aux as access; + return if how == access::f32 || how == access::bytes || how.value_type().lanes(); + val width := how.width(); + val start := this.insts[from].imm + this.insts[index].imm; + return if start >= held.bytes.length || width > held.bytes.length - start; + + for &each in held.relocations { + continue if each.at + word_size <= start || each.at >= start + width; + return if each.at != start || how != access::i64; + this.become(index, op::datum, span::::empty(), each.target, each.addend); + done.changed = true; + return; + } + + var bits: u64 = 0; + for i in 0..width { + bits = bits | ((held.bytes[start + i as u64] as u64) << (8 * i as u64)); + } + match how { + access::i8 => bits = wrap_word(bits, 8, true); + access::i16 => bits = wrap_word(bits, 16, true); + access::i32 => bits = wrap_word(bits, 32, true); + access::f64 => { + this.become_real(index, bits); + done.changed = true; + return; + } + else => {} + } + this.become_word(index, bits); + done.changed = true; +} + +#! Simplifies a write of a narrow value: one narrowed to at least as many bits +#! as the write keeps, or an `f32` rounded already, is written as it was. +#! @param this The code. +#! @param index The `store`. +#! @param done What the pass changes. +def code::simplify_store(&mut this, index: u32, done: &mut rewrite): void { + val value := this.arg(index, 1); + val inner := this.defining(value); + return if inner == 0; + val how := this.insts[index].aux as access; + val kind := this.insts[inner].kind; + if kind == op::fsingle && how == access::f32 { + this.operands[this.insts[index].args as u64 + 1] = this.arg(inner, 0); + done.changed = true; + return; + } + return if kind != op::wrap || how == access::f32 || how == access::f64 || how == access::bytes; + if this.insts[inner].aux as u64 >= 8 * how.width() { + this.operands[this.insts[index].args as u64 + 1] = this.arg(inner, 0); + done.changed = true; + } +} + +#! Whether a value is known to have every bit of a word set: the processor's +#! instruction sets, where a version knows which it has. +#! @param this The code. +#! @param value The value. +#! @param bits The bits. +#! @returns Whether it is. +def code::holds_bits(&this, value: u32, bits: u64): bool { + val made := this.defining(value); + return made != 0 && this.insts[made].kind == op::cpu && (bits & ~this.insts[made].imm) == 0; +} + +#! Simplifies an operator of two words. +#! @param this The code. +#! @param index The instruction. +#! @param done What the pass changes. +def code::simplify_word(&mut this, index: u32, done: &mut rewrite): void { + val kind := this.insts[index].kind; + var a := this.arg(index, 0); + var b := this.arg(index, 1); + var x: u64 = 0; + var y: u64 = 0; + val known_a := this.word_constant(a, &mut x); + val known_b := this.word_constant(b, &mut y); + if known_a && known_b { + var made: u64 = 0; + if fold_word(kind, x, y, &mut made) { + this.become_word(index, made); + done.changed = true; + } + return; + } + + # A constant goes on the right of what does not mind which side it is on. + var right := known_b; + if known_a && !known_b && commutes(kind) { + var swapped: u32[2] = [b, a]; + this.become(index, kind, swapped[0:2], 0, 0); + a = swapped[0]; + b = swapped[1]; + y = x; + right = true; + done.changed = true; + } + + # What the operands say whatever they are. + if a == b { + match kind { + op::sub, op::bxor, op::ne, op::ltu, op::lts => { + this.become_word(index, 0); + done.changed = true; + return; + } + op::eq, op::leu, op::les => { + this.become_word(index, 1); + done.changed = true; + return; + } + op::band, op::bor => { + this.forward_to(index, a, done); + return; + } + else => {} + } + } + + # A never-zero address compared with zero. + if (kind == op::eq || kind == op::ne) && this.is_zero(b) && this.never_zero(a) { + this.become_word(index, kind == op::ne ? 1 : 0); + done.changed = true; + return; + } + if known_a && !right { + this.simplify_left_order(index, b, x, done); + return; + } + return if !right; + + match kind { + op::add, op::sub => { + if y == 0 { + this.forward_to(index, a, done); + } else { + this.combine_steps(index, a, kind == op::add ? y : 0 - y, done); + } + } + op::bor, op::bxor, op::shl, op::shru, op::shrs => { + if y == 0 { + this.forward_to(index, a, done); + } + } + op::mul => { + if y == 0 { + this.become_word(index, 0); + done.changed = true; + } else if y == 1 { + this.forward_to(index, a, done); + } else if is_power(y) { + this.become_shift(index, op::shl, a, log2(y)); + done.changed = true; + } + } + op::divs, op::divu => { + if y == 1 { + this.forward_to(index, a, done); + } else if kind == op::divu && is_power(y) { + this.become_shift(index, op::shru, a, log2(y)); + done.changed = true; + } + } + op::rems, op::remu => { + if y == 1 { + this.become_word(index, 0); + done.changed = true; + } else if kind == op::remu && is_power(y) { + var operands: u32[2] = [a, this.word_value(y - 1)]; + this.become(index, op::band, operands[0:2], 0, 0); + done.changed = true; + } + } + op::band => { + if y == 0 { + this.become_word(index, 0); + done.changed = true; + } else if y == 0xFFFFFFFFFFFFFFFFu { + this.forward_to(index, a, done); + } else if this.holds_bits(a, y) { + this.become_word(index, y); + done.changed = true; + } + } + op::ltu => { + if y == 0 { + this.become_word(index, 0); + done.changed = true; + } else if y == 1 { + this.become_compare(index, op::eq, a, 0); + done.changed = true; + } + } + op::leu => { + if y == greatest_unsigned { + this.become_word(index, 1); + done.changed = true; + } else if y == 0 { + this.become_compare(index, op::eq, a, 0); + done.changed = true; + } + } + op::lts => { + if y == least_signed { + this.become_word(index, 0); + done.changed = true; + } else if y == least_signed + 1 { + this.become_compare(index, op::eq, a, least_signed); + done.changed = true; + } + } + op::les => { + if y == greatest_signed { + this.become_word(index, 1); + done.changed = true; + } else if y == least_signed { + this.become_compare(index, op::eq, a, least_signed); + done.changed = true; + } + } + else => {} + } +} + +#! The greatest unsigned word. +const greatest_unsigned: u64 = 0xFFFFFFFFFFFFFFFFu; + +#! The least signed word, as its bits. +const least_signed: u64 = 0x8000000000000000u; + +#! The greatest signed word, as its bits. +const greatest_signed: u64 = 0x7FFFFFFFFFFFFFFFu; + +#! Simplifies an order whose left operand is a constant, which stays on the +#! left: one no word comes after, or every word does, says what it says of +#! every word, as `MAX < x` is 0, and one only a single word comes after asks +#! whether the word is that one, as `0 < x` asks whether `x` is not zero. +#! @param this The code. +#! @param index The comparison. +#! @param b Its right operand. +#! @param x The constant on its left. +#! @param done What the pass changes. +def code::simplify_left_order(&mut this, index: u32, b: u32, x: u64, done: &mut rewrite): void { + match this.insts[index].kind { + op::ltu => { + if x == greatest_unsigned { + this.become_word(index, 0); + } else if x == 0 { + this.become_compare(index, op::ne, b, 0); + } else { + return; + } + } + op::leu => { + if x == 0 { + this.become_word(index, 1); + } else if x == greatest_unsigned { + this.become_compare(index, op::eq, b, greatest_unsigned); + } else { + return; + } + } + op::lts => { + if x == greatest_signed { + this.become_word(index, 0); + } else if x == least_signed { + this.become_compare(index, op::ne, b, least_signed); + } else { + return; + } + } + op::les => { + if x == least_signed { + this.become_word(index, 1); + } else if x == greatest_signed { + this.become_compare(index, op::eq, b, greatest_signed); + } else { + return; + } + } + else => return; + } + done.changed = true; +} + +#! Makes an instruction a comparison of a word with a constant. +#! @param this The code. +#! @param index The instruction. +#! @param kind The comparison. +#! @param a The word. +#! @param bits The constant. +def code::become_compare(&mut this, index: u32, kind: op, a: u32, bits: u64): void { + var operands: u32[2] = [a, this.word_value(bits)]; + this.become(index, kind, operands[0:2], 0, 0); +} + +#! Adds a constant to a word that is itself a word with a constant added or +#! taken away, as one sum of both, so `(x + 4) + 8` is `x + 12`, and the inner +#! one goes where nothing else reads it. +#! @param this The code. +#! @param index The `add` or `sub`. +#! @param a The word it adds to. +#! @param step What it adds, as a wrapping word: what a `sub` takes away, negated. +#! @param done What the pass changes. +def code::combine_steps(&mut this, index: u32, a: u32, step: u64, done: &mut rewrite): void { + val inner := this.defining(a); + return if inner == 0; + val kind := this.insts[inner].kind; + return if kind != op::add && kind != op::sub; + var bits: u64 = 0; + return if !this.word_constant(this.arg(inner, 1), &mut bits); + val total := step + (kind == op::add ? bits : 0 - bits); + val base := this.arg(inner, 0); + if total == 0 { + this.forward_to(index, base, done); + return; + } + var operands: u32[2] = [base, this.word_value(total)]; + this.become(index, op::add, operands[0:2], 0, 0); + done.changed = true; +} + +#! Makes an instruction a shift of a word by a constant. +#! @param this The code. +#! @param index The instruction. +#! @param kind The shift. +#! @param a The word. +#! @param by How far it shifts. +def code::become_shift(&mut this, index: u32, kind: op, a: u32, by: u64): void { + var operands: u32[2] = [a, this.word_value(by)]; + this.become(index, kind, operands[0:2], 0, 0); +} + +#! Replaces what an instruction gives with a value, taking the instruction out. +#! @param this The code. +#! @param index The instruction. +#! @param value The value its result is. +#! @param done What the pass changes. +def code::forward_to(&mut this, index: u32, value: u32, done: &mut rewrite): void { + done.replace(this.insts[index].result, value); + done.remove(index); +} + +#! Whether a value is the word zero. +#! @param this The code. +#! @param value The value. +#! @returns Whether it is. +def code::is_zero(&this, value: u32): bool { + var bits: u64 = 0; + return this.word_constant(value, &mut bits) && bits == 0; +} + +#! Simplifies an operator of one value. +#! @param this The code. +#! @param index The instruction. +#! @param done What the pass changes. +def code::simplify_unary(&mut this, index: u32, done: &mut rewrite): void { + val kind := this.insts[index].kind; + val a := this.arg(index, 0); + var bits: u64 = 0; + val word := this.word_constant(a, &mut bits); + val real := !word && this.real_constant(a, &mut bits); + if word || real { + var made: u64 = 0; + val gives_real := kind == op::fneg || kind == op::itof || kind == op::utof || kind == op::fsingle || kind == op::fsqrt; + if fold_unary(kind, bits, &mut made) { + if gives_real { + this.become_real(index, made); + } else { + this.become_word(index, made); + } + done.changed = true; + } + return; + } + + val inner := this.defining(a); + return if inner == 0; + val from: inst = this.insts[inner]; + match kind { + # The opposite of a comparison is the comparison that says it. + op::lnot => { + var flipped := op::count; + var swap := false; + match from.kind { + op::eq => flipped = op::ne; + op::ne => flipped = op::eq; + op::ltu => { flipped = op::leu; swap = true; } + op::leu => { flipped = op::ltu; swap = true; } + op::lts => { flipped = op::les; swap = true; } + op::les => { flipped = op::lts; swap = true; } + op::ltsu => { flipped = op::leus; swap = true; } + op::lesu => { flipped = op::ltus; swap = true; } + op::ltus => { flipped = op::lesu; swap = true; } + op::leus => { flipped = op::ltsu; swap = true; } + op::lnot => { + if this.is_flag(this.arg(inner, 0)) { + this.forward_to(index, this.arg(inner, 0), done); + } + return; + } + else => return; + } + val x := this.arg(inner, 0); + val y := this.arg(inner, 1); + var operands: u32[2] = swap ? [y, x] : [x, y]; + this.become(index, flipped, operands[0:2], 0, 0); + done.changed = true; + } + op::fsingle => { + if from.kind == op::fsingle || (from.kind == op::load && from.aux == access::f32 as u32) { + this.forward_to(index, a, done); + } + } + op::neg, op::bnot => { + if from.kind == kind { + this.forward_to(index, this.arg(inner, 0), done); + } + } + else => {} + } +} + +#! Whether a word is 0 or 1, as a comparison gives. +#! @param this The code. +#! @param value The word. +#! @returns Whether it is. +def code::is_flag(&this, value: u32): bool { + var bits: u64 = 0; + return bits <= 1 if this.word_constant(value, &mut bits); + val index := this.defining(value); + return false if index == 0; + val number := this.insts[index].kind as u32; + return (number >= op::eq as u32 && number <= op::leus as u32) + || (number >= op::feq as u32 && number <= op::fle as u32) + || number == op::lnot as u32; +} + +#! Simplifies the narrowing of a word, which goes where the word is already as +#! narrow, and narrows what was narrowed less where it narrows more, or the +#! same, the other way: `wrap(wrap(x, 32, unsigned), 32, signed)` is +#! `wrap(x, 32, signed)`. +#! @param this The code. +#! @param index The instruction. +#! @param done What the pass changes. +def code::simplify_wrap(&mut this, index: u32, done: &mut rewrite): void { + val held: inst = this.insts[index]; + val a := this.arg(index, 0); + val bits := held.aux; + val signed := held.imm != 0; + if bits >= 64 { + this.forward_to(index, a, done); + return; + } + var value: u64 = 0; + if this.word_constant(a, &mut value) { + this.become_word(index, wrap_word(value, bits, signed)); + done.changed = true; + return; + } + + # The bits a word is held in already, and whether they are signed. + var held_bits: u32 = 64; + var held_signed := false; + val inner := this.defining(a); + if inner != 0 { + val from: inst = this.insts[inner]; + match from.kind { + op::wrap => { + held_bits = from.aux; + held_signed = from.imm != 0; + # Narrowing more than what was narrowed, or as much the other way, narrows + # the word itself. + if bits < held_bits || (bits == held_bits && signed != held_signed) { + var operands: u32[1] = [this.arg(inner, 0)]; + this.become(index, op::wrap, operands[0:1], bits, held.imm); + done.changed = true; + return; + } + } + op::load, op::atomic => { + match from.kind == op::load ? from.aux as access : atomic_access(from.imm) { + access::u8 => held_bits = 8; + access::i8 => { held_bits = 8; held_signed = true; } + access::u16 => held_bits = 16; + access::i16 => { held_bits = 16; held_signed = true; } + access::u32 => held_bits = 32; + access::i32 => { held_bits = 32; held_signed = true; } + else => {} + } + } + else => { + if this.is_flag(a) { + held_bits = 1; + } + } + } + } + if (signed == held_signed && bits >= held_bits) || (!held_signed && bits > held_bits) || this.param_narrow(a, bits, signed) { + this.forward_to(index, a, done); + } +} + +#! Whether a block's parameter is a word as narrow as a narrowing makes it +#! already: every edge into the block gives it one so narrowed, or the +#! parameter itself, as a loop keeps a field of `i32` it adds to. +#! @param this The code. +#! @param value The parameter. +#! @param bits The bits it would be narrowed to. +#! @param signed Whether it would be extended by its sign. +#! @returns Whether it is. +def code::param_narrow(&this, value: u32, bits: u32, signed: bool): bool { + return false if value == 0 || (value as u64) >= this.origins.length; + val held: origin = this.origins[value]; + return false if !held.param; + val preds := &this.blocks[held.from].preds; + return false if preds.length == 0; + for &e in preds.view() { + val given: u32 = this.edges[e as u64].args[held.index as u64]; + continue if given == value; + val made := this.defining(given); + return false if made == 0; + val from: inst = this.insts[made]; + var fits := false; + if from.kind == op::wrap { + fits = (from.imm != 0) == signed ? from.aux <= bits : from.imm == 0 && from.aux < bits; + } else if from.kind == op::iconst { + fits = wrap_word(from.imm, bits, signed) == from.imm; + } + return false if !fits; + } + return true; +} + +#! Simplifies a `branch`: one on a condition's opposite goes the other way on +#! the condition, and one on whether a word is not zero branches on the word. +#! @param this The code. +#! @param index The `branch`. +#! @param done What the pass changes. +def code::simplify_branch(&mut this, index: u32, done: &mut rewrite): void { + var steps := 0; + while steps < 8 { + steps++; + val cond := this.arg(index, 0); + val inner := this.defining(cond); + return if inner == 0; + val from: inst = this.insts[inner]; + if from.kind == op::lnot { + this.operands[this.insts[index].args] = this.arg(inner, 0); + this.swap_branch(index); + done.changed = true; + continue; + } + return if (from.kind != op::ne && from.kind != op::eq) || !this.is_zero(this.arg(inner, 1)); + this.operands[this.insts[index].args] = this.arg(inner, 0); + if from.kind == op::eq { + this.swap_branch(index); + } + done.changed = true; + } +} + +#! Simplifies a `select`: one on a constant, or between one value either way, +#! is the value it chooses; one on a condition's opposite, or on whether a word +#! is not zero, chooses on the condition or the word the other way round or the +#! same; one choosing 1 or 0 by a word is whether the word is not zero, which +#! is the word where it is 0 or 1, or is zero; and one choosing the condition +#! itself or 0 is the condition. +#! @param this The code. +#! @param index The `select`. +#! @param done What the pass changes. +def code::simplify_select(&mut this, index: u32, done: &mut rewrite): void { + var steps := 0; + while steps < 8 { + steps++; + val cond := this.arg(index, 0); + val a := this.arg(index, 1); + val b := this.arg(index, 2); + var bits: u64 = 0; + if this.word_constant(cond, &mut bits) { + this.forward_to(index, bits != 0 ? a : b, done); + return; + } + if a == b || (a == cond && this.is_zero(b)) { + this.forward_to(index, a, done); + return; + } + var x: u64 = 0; + var y: u64 = 0; + if this.word_constant(a, &mut x) && this.word_constant(b, &mut y) { + if x == 1 && y == 0 && this.is_flag(cond) { + this.forward_to(index, cond, done); + return; + } + if x == 1 && y == 0 { + var operands: u32[2] = [cond, this.word_value(0)]; + this.become(index, op::ne, operands[0:2], 0, 0); + done.changed = true; + return; + } + if x == 0 && y == 1 { + var operands: u32[1] = [cond]; + this.become(index, op::lnot, operands[0:1], 0, 0); + done.changed = true; + return; + } + } + + # A condition worked out from another is read through it. + val inner := this.defining(cond); + return if inner == 0; + val from: inst = this.insts[inner]; + val opposite := from.kind == op::lnot || (from.kind == op::eq && this.is_zero(this.arg(inner, 1))); + return if !opposite && (from.kind != op::ne || !this.is_zero(this.arg(inner, 1))); + var operands: u32[3] = opposite ? [this.arg(inner, 0), b, a] : [this.arg(inner, 0), a, b]; + this.become(index, op::select, operands[0:3], 0, 0); + done.changed = true; + } +} + +#! Whether an operator of two words gives the same whichever side each is on. +#! @param kind The operator. +#! @returns Whether it does. +def commutes(kind: op): bool { + return kind == op::add || kind == op::mul || kind == op::band || kind == op::bor || kind == op::bxor + || kind == op::eq || kind == op::ne; +} + +#! Whether a word is a power of two. +#! @param bits The word. +#! @returns Whether it is. +def is_power(bits: u64): bool { + return bits != 0 && (bits & (bits - 1)) == 0; +} + +#! Which power of two a word is. +#! @param bits The word, a power of two. +#! @returns The power. +def log2(bits: u64): u64 { + var at := bits; + var power: u64 = 0; + while at > 1 { + at = at >> 1; + power++; + } + return power; +} + +#! A word narrowed to a number of bits, as the machine narrows it. +#! @param value The word. +#! @param bits How many bits it keeps. +#! @param signed Whether it is sign-extended rather than zero-extended. +#! @returns The word narrowed. +pub def wrap_word(value: u64, bits: u32, signed: bool): u64 { + return value if bits >= 64; + val mask := (1u << bits as u64) - 1; + var made := value & mask; + if signed && (made >> (bits as u64 - 1)) != 0 { + made = made | ~mask; + } + return made; +} + +#! What an operator of two words gives, as the machine works it out. +#! @param kind The operator. +#! @param a The first word. +#! @param b The second word. +#! @param made Where what it gives is written. +#! @returns Whether it gives anything: not where it divides by zero, which +#! stops the program. +pub def fold_word(kind: op, a: u64, b: u64, made: &mut u64): bool { + match kind { + op::add => made = a + b; + op::sub => made = a - b; + op::mul => made = a * b; + op::divs, op::divu, op::rems, op::remu => { + return false if b == 0; + if kind == op::divu { + made = a / b; + } else if kind == op::remu { + made = a % b; + } else if (b as i64) == -1 { + made = kind == op::divs ? 0 - a : 0; + } else if kind == op::divs { + made = ((a as i64) / (b as i64)) as u64; + } else { + made = ((a as i64) % (b as i64)) as u64; + } + } + op::band => made = a & b; + op::bor => made = a | b; + op::bxor => made = a ^ b; + op::shl => made = a << b; + op::shru => made = a >> b; + op::shrs => made = ((a as i64) >> b) as u64; + op::eq => made = a == b ? 1 : 0; + op::ne => made = a != b ? 1 : 0; + op::lts => made = (a as i64) < (b as i64) ? 1 : 0; + op::ltu => made = a < b ? 1 : 0; + op::les => made = (a as i64) <= (b as i64) ? 1 : 0; + op::leu => made = a <= b ? 1 : 0; + op::eqsu => made = (a as i64) >= 0 && a == b ? 1 : 0; + op::ltsu => made = (a as i64) < 0 || a < b ? 1 : 0; + op::lesu => made = (a as i64) < 0 || a <= b ? 1 : 0; + op::ltus => made = (b as i64) >= 0 && a < b ? 1 : 0; + op::leus => made = (b as i64) >= 0 && a <= b ? 1 : 0; + else => return false; + } + return true; +} + +#! What an operator of two reals gives, as the machine works it out: a real's +#! bits, or a word of 0 or 1 for a comparison. +#! @param kind The operator. +#! @param a The bits of the first real. +#! @param b The bits of the second real. +#! @param made Where what it gives is written. +#! @returns Whether it gives anything. +pub def fold_real(kind: op, a: u64, b: u64, made: &mut u64): bool { + val x := real_of(a); + val y := real_of(b); + match kind { + op::fadd => made = bits_of_real(x + y); + op::fsub => made = bits_of_real(x - y); + op::fmul => made = bits_of_real(x * y); + op::fdiv => made = bits_of_real(x / y); + op::frem => made = bits_of_real(x % y); + op::feq => made = x == y ? 1 : 0; + op::fne => made = x != y ? 1 : 0; + op::flt => made = x < y ? 1 : 0; + op::fle => made = x <= y ? 1 : 0; + else => return false; + } + return true; +} + +#! What an operator of one value gives, as the machine works it out. +#! @param kind The operator. +#! @param a The bits of the word or real it takes. +#! @param made Where the bits of what it gives are written. +#! @returns Whether it gives anything. +pub def fold_unary(kind: op, a: u64, made: &mut u64): bool { + match kind { + op::neg => made = 0 - a; + op::bnot => made = ~a; + op::lnot => made = a == 0 ? 1 : 0; + op::fneg => made = bits_of_real(-real_of(a)); + op::itof => made = bits_of_real((a as i64) as f64); + op::utof => made = bits_of_real(a as f64); + op::ftoi => made = (real_of(a) as i64) as u64; + op::ftou => made = real_of(a) as u64; + op::fsingle => made = bits_of_real((real_of(a) as f32) as f64); + op::fsqrt => made = bits_of_real(root_of(real_of(a))); + op::ones => made = ones_of(a); + op::clz => made = leading_zeros_of(a); + op::ctz => made = trailing_zeros_of(a); + op::bswap => made = bytes_swapped(a); + else => return false; + } + return true; +} diff --git a/compiler/optimizer/sink.sakura b/compiler/optimizer/sink.sakura new file mode 100644 index 00000000..882f7ac5 --- /dev/null +++ b/compiler/optimizer/sink.sakura @@ -0,0 +1,271 @@ +#! @file sink.sakura +#! @author John Christman (sorakatadzuma@gmail.com) +#! @copyright Malunal Studios, LLC. +#! @license MIT +#! +#! Contains the tenth pass of the optimizer, code sinking: an instruction whose +#! values are read only past one way out of its block moves into the block +#! that way goes to, where nothing else goes there, so what it works out is +#! worked out only where it is read. What moves only works out its values and +#! cannot stop the program, or reads memory. A read moves only where nothing +#! after it in its block may write what it reads, as alias analysis tells, and +#! where it cannot stop the program but as it would have: its address is read +#! or written through, or checked, before it, or after it in its block before +#! anything the program would be seen to do. A block one way alone goes into +#! heads no loop, so nothing moves into a loop it was not in. Blocks are walked +#! before those they dominate, each from its end, so what moved may move on +#! again. + +import std::containers; +module sakura::compiler; + + +#! What sinking knows of the code as it goes. What reads ask of is found the +#! first time a read may move, as most code has none that may. +struct sinking { + var idom: vector; #! The immediate dominator of each block. + var readers: groups; #! The instructions reading each value, by value, once each time they read it. + var reached: dict; #! How many instructions read or write through each address, or check it, in each block, by `pair_key(address, block)`. + var list: vector; #! The instructions of the block walked, in order, each that moved out 0. + var aliases: aliases; #! What may write what. + var writes: span; #! Of each instruction, the bytes a call writes what it returns to at its last operand, or 0. + var ready: bool; #! Whether `reached` and `aliases` are found. +} + +#! Sinks the code of a function, knowing what each call writes what it +#! returns to. +#! @param this The compiler. +#! @param index The function. +#! @returns Whether anything moved. +def lowerer::sink_code(&mut this, index: u32): bool { + val writes := this.result_writes(index); + return this.program.functions[index].body.sink_code(writes.view()); +} + +#! Sinks the code, as the file says. +#! @param this The code. +#! @param writes Of each instruction, the bytes a call writes what it returns +#! to at its last operand, or 0. +#! @returns Whether anything moved. +pub def code::sink_code(&mut this, writes: span): bool { + # Only a block going more than one way has anything to move out of it. + var ways := false; + for b in 0..this.blocks.length { + if !this.blocks[b].gone && this.edge_count(this.blocks[b].last) >= 2 { + ways = true; + break; + } + } + return false if !ways; + + var order := vector::::new(scratch()); + var number := vector::::new(scratch()); + this.block_order(&mut order, &mut number); + var state := sinking { + idom = this.block_dominators(), + readers = groups::::new(this.origins.length, scratch()), + reached = dict::::new(scratch()), + list = vector::::new(scratch()), + writes = writes + }; + # What reads each value, counted then put. + var walk := this.walk_all(); + var reads := this.reader(); + while walk.more() { + reads.start(walk.next()); + while reads.more() { + state.readers.count(reads.next()); + } + } + state.readers.seal(); + var again := this.walk_all(); + while again.more() { + val at := again.next(); + reads.start(at); + while reads.more() { + state.readers.put(reads.next(), at); + } + } + + var changed := false; + for &block in order { + val last: u32 = this.blocks[block].last; + continue if this.edge_count(last) < 2; + changed = this.sink_block(block, &mut state) || changed; + } + return changed; +} + +#! Finds what reads moving ask of the code, where it is not yet found: what +#! may write what, and what reaches through each address in each block, as the +#! code is now. +#! @param this The code. +#! @param state What sinking knows. +def code::ready_sinking(&this, state: &mut sinking): void { + return if state.ready; + state.ready = true; + state.aliases = this.aliases(state.writes, state.idom.view()); + var walk := this.walk_all(); + while walk.more() { + val at := walk.next(); + val held: inst = this.insts[at]; + match held.kind { + op::load, op::store, op::clear, op::copy, op::check => { + val first := this.arg(at, 0); + if this.reaches(at, first) { + val key := pair_key(first, held.block); + state.reached.set(key, state.reached.get_or(&key, 0) + 1); + } + if held.kind == op::copy && held.imm != 0 && this.arg(at, 1) != first { + val key := pair_key(this.arg(at, 1), held.block); + state.reached.set(key, state.reached.get_or(&key, 0) + 1); + } + } + else => {} + } + } +} + +#! Whether an instruction reads or writes memory through an address, or checks +#! it is not null, so that it stops the program where the address is null. +#! @param this The code. +#! @param index The instruction. +#! @param address The address. +#! @returns Whether it does. +def code::reaches(&this, index: u32, address: u32): bool { + val held := &this.insts[index]; + return match held.kind { + op::load, op::store => this.arg(index, 0) == address, + op::clear => held.imm != 0 && this.arg(index, 0) == address, + op::copy => held.imm != 0 && (this.arg(index, 0) == address || this.arg(index, 1) == address), + op::check => held.aux == fault::null_reference as u32 && this.arg(index, 0) == address, + else => false + }; +} + +#! Moves what a block works out only for one way out of it into the block +#! that way goes to, from the block's end. +#! @param this The code. +#! @param block The block, which ends going more than one way. +#! @param state What sinking knows. +#! @returns Whether anything moved. +def code::sink_block(&mut this, block: u32, state: &mut sinking): bool { + state.list.clear(); + var walk := this.walk(block); + while walk.more() { + state.list.append(walk.next()); + } + var changed := false; + var k := state.list.length - 1; + while k > 0 { + k--; + val index: u32 = state.list[k]; + val into := this.sink_target(index, block, state); + continue if into == no_block; + val load := this.insts[index].kind == op::load; + if load { + this.ready_sinking(state); + } + continue if load && !this.load_sinks(index, k, block, state); + + # Those before it are all still in the block. + val prior: u32 = k == 0 ? 0 : state.list[k - 1]; + if prior == 0 { + this.blocks[block].first = this.insts[index].next; + } else { + this.insts[prior].next = this.insts[index].next; + } + this.put_first(into, index); + state.list[k] = 0; + changed = true; + if load { + val address := this.arg(index, 0); + val from := pair_key(address, block); + state.reached.set(from, state.reached.get_or(&from, 1) - 1); + val to := pair_key(address, into); + state.reached.set(to, state.reached.get_or(&to, 0) + 1); + } + } + return changed; +} + +#! Where an instruction of a block may move: the block one way out of it goes +#! to, where nothing else goes, past which everything reading its values is. +#! @param this The code. +#! @param index The instruction. +#! @param block Its block. +#! @param state What sinking knows. +#! @returns The block, or `no_block` where it stays. +def code::sink_target(&this, index: u32, block: u32, state: &sinking): u32 { + val held: inst = this.insts[index]; + return no_block if held.count == 0 || held.kind.made_anywhere(); + return no_block if held.kind != op::load && !this.removable(index); + var target := no_block; + for r in 0..held.count { + for &reader in state.readers.of(held.result + r as u32) { + # The block it dominates most nearly that dominates the reader's. + var at: u32 = this.insts[reader].block; + return no_block if at == block; + var steps := 0; + while true { + val up: u32 = state.idom[at]; + break if up == block; + return no_block if up == no_block || up == at || steps > 256; + at = up; + steps++; + } + return no_block if target != no_block && target != at; + target = at; + } + } + return no_block if target == no_block; + val preds := &this.blocks[target].preds; + return no_block if preds.length != 1 || this.edge_source(preds[0]) != block; + return target; +} + +#! Whether a read may move to after the end of its block: nothing after it in +#! the block may write what it reads, and its address is not null there, or +#! the program would have stopped as it does now. That it is read or written +#! through, or checked, before the read, in the block or one dominating it, +#! says so, as does its being so after the read in the block, before anything +#! the program would be seen to do. +#! @param this The code. +#! @param index The `load`. +#! @param k Its place among the block's instructions. +#! @param block Its block. +#! @param state What sinking knows. +#! @returns Whether it may. +def code::load_sinks(&this, index: u32, k: u64, block: u32, state: &sinking): bool { + val address := this.arg(index, 0); + val place := state.aliases.region_of(this, index, 0); + var safe := this.never_zero(address); + var quiet := true; + for j in k + 1..state.list.length { + val other: u32 = state.list[j]; + continue if other == 0; + val kind := this.insts[other].kind; + return false if kind != op::load && (kind.traits() & op_write) != 0 && state.aliases.clobbers(this, other, &place); + if quiet && this.reaches(other, address) { + safe = true; + } + val stops := kind == op::load ? !this.never_zero(this.arg(other, 0)) : (kind.traits() & op_traps) != 0 && !this.removable(other); + if stops { + quiet = false; + } + } + return true if safe; + for j in 0..k { + return true if this.reaches(state.list[j], address); + } + val home := this.home_of(address); + var at := block; + var steps := 0; + while at != home && at != 0 && steps < 64 { + at = state.idom[at]; + val key := pair_key(address, at); + return true if state.reached.get_or(&key, 0) != 0; + steps++; + } + return false; +} diff --git a/compiler/optimizer/unused.sakura b/compiler/optimizer/unused.sakura new file mode 100644 index 00000000..fb3e9cd8 --- /dev/null +++ b/compiler/optimizer/unused.sakura @@ -0,0 +1,79 @@ +#! @file unused.sakura +#! @author John Christman (sorakatadzuma@gmail.com) +#! @copyright Malunal Studios, LLC. +#! @license MIT +#! +#! Contains the dropping of the functions nothing reaches once the program is +#! optimized, as those whose every call inlining copied. What is reached is +#! found from what is reached other than by the code's calls: `main`, the code +#! initializing the globals, the function safe points call, each function a +#! vtable holds, each C calls, and each the program takes as a value or the +#! backend calls by name. Each function reached then reaches what its code +#! calls, calls at safe points, and gives C to call, and its version. The rest +#! are dropped as though never lowered, so no code is made of them, each +#! keeping its index, and its name, which a trace of the code inlined from it +#! still gives. + +module sakura::compiler; + + +#! Drops the functions nothing reaches, as the file says, once the program is +#! optimized and nothing more is lowered, but where every function is asked +#! for, or the program evaluates constants. +#! @param this The compiler. +pub def lowerer::drop_unreached_functions(&mut this): void { + return if this.options.everything || this.options.evaluating; + val point := mark_scratch(); + val count := this.program.functions.length; + var reached := worklist::new(count, scratch()); + this.reach_functions(&mut reached); + for i in 0..count { + if !reached.has(i as u32) { + this.program.functions[i].lowered = false; + } + } + release_scratch(point); +} + +#! Finds the functions reached, as the file says. +#! @param this The compiler. +#! @param reached Where the functions reached are put, empty and as long as +#! the functions are; each is in it after. +pub def lowerer::reach_functions(&this, reached: &mut worklist): void { + val count := this.program.functions.length; + for i in 0..count { + if this.program.functions[i].taken || this.program.functions[i].callback { + reached.push_new(i as u32); + } + } + val roots: u32[3] = [this.program.main, this.program.init, this.dispatch]; + for r in 0..3u { + if roots[r] != no_function { + reached.push_new(roots[r]); + } + } + for &each in this.program.vtables { + for &function in each.functions { + if function != no_function { + reached.push_new(function); + } + } + } + + while !reached.is_empty { + val function := reached.pop(); + val held := &this.program.functions[function]; + if held.version != 0 { + reached.push_new(held.version - 1); + } + continue if !held.lowered; + var walk := held.body.walk_all(); + while walk.more() { + val at := walk.next(); + val kind := held.body.insts[at].kind; + if kind == op::call || kind == op::callback || kind == op::safepoint { + reached.push_new(held.body.insts[at].aux); + } + } + } +} diff --git a/compiler/optimizer/versions.sakura b/compiler/optimizer/versions.sakura new file mode 100644 index 00000000..af147bb2 --- /dev/null +++ b/compiler/optimizer/versions.sakura @@ -0,0 +1,158 @@ +#! @file versions.sakura +#! @author John Christman (sorakatadzuma@gmail.com) +#! @copyright Malunal Studios, LLC. +#! @license MIT +#! +#! Contains the versions of functions for processors with x86-64-v3's +#! instructions. A function of an executable that asks while running which +#! vector instructions the processor has, as `core::simd`'s operations do, or +#! counts a word's bits, is optimized again as a version knowing it has those of +#! x86-64-v3: SSE through SSE4.2, AVX, AVX2, FMA3, `popcnt`, `lzcnt`, and BMI1's +#! `tzcnt`. There, every operation on 16 or 32 bytes of lanes is worked with +#! instructions, so the lanes written a lane at a time go, 32 bytes of lanes are +#! values held in registers, and a count of bits is one instruction; what asks +#! for more, as 64 bytes ask for AVX-512, still asks. The function itself goes +#! to its version as it begins, where the processor has them, and its version +#! calls the versions of the functions it calls. +#! +#! A function calling one whose version is small enough to inline is given a +#! version too, though it asks nothing itself, so that its version copies the +#! other's: a loop calling `fma` works it with the instruction, rather than +#! calling a function that asks the processor each time. + +module sakura::compiler; + + +#! The instruction sets of x86-64-v3, as the executable keeps them. +pub const cpu_v3: u64 = cpu_sse2 | cpu_ssse3 | cpu_sse41 | cpu_sse42 | cpu_avx | cpu_avx2 | cpu_fma | cpu_popcnt + | cpu_lzcnt | cpu_bmi1; + +#! Whether code asks which instructions the processor has, or counts a word's +#! bits, which x86-64-v3 has instructions for. The code is compacted, as each +#! function is once it is optimized, so each instruction it holds is in a block, +#! and is looked at where it lies. +#! @param this The code. +#! @returns Whether it does. +def code::asks_processor(&this): bool { + for i in 1..this.insts.length { + val kind := this.insts[i].kind; + return true if kind == op::cpu || kind == op::ones || kind == op::clz || kind == op::ctz; + } + return false; +} + +#! Copies code whole, sharing no memory with it. +#! @param this The code. +#! @returns The copy. +pub def code::duplicate(&this): code { + var made := code::new(); + made.insts.clear(); + made.origins.clear(); + made.blocks.clear(); + made.insts.extend(this.insts.view()); + made.operands.extend(this.operands.view()); + made.origins.extend(this.origins.view()); + for &each in this.blocks { + made.blocks.append(block { first = each.first, last = each.last, params = ids::copy_of(&each.params), preds = ids::copy_of(&each.preds), gone = each.gone }); + } + for &each in this.edges { + made.edges.append(edge { from = each.from, target = each.target, args = ids::copy_of(&each.args), case = each.case }); + } + made.cells.extend(this.cells.view()); + made.results.extend(this.results.view()); + made.sites.extend(this.sites.view()); + made.variables.extend(this.variables.view()); + made.bindings.extend(this.bindings.view()); + made.returned = this.returned; + made.vectors = this.vectors; + made.wide = this.wide; + return made; +} + +#! Whether a function calls one with a version small enough to be inlined +#! whole, or `@inline`, which its own version would copy. +#! @param this The compiler. +#! @param index The function. +#! @returns Whether it does. +def lowerer::calls_small_version(&mut this, index: u32): bool { + val limit := this.options.inline_limit != 0 ? this.options.inline_limit : inline_limit; + val body := &this.program.functions[index].body; + for i in 1..body.insts.length { + continue if body.insts[i].kind != op::call; + val version: u32 = this.program.functions[body.insts[i].aux].version; + continue if version == 0; + val facts := this.inline_facts(version - 1); + return true if facts.fits && (facts.cost <= limit || this.program.functions[version - 1].inline); + } + return false; +} + +#! Whether the program's functions are given versions: in an executable +#! optimized at all. +#! @param this The compiler. +#! @returns Whether they are. +def lowerer::versions_made(&this): bool { + return this.options.level >= 1 && !this.options.evaluating + && this.checker.names.text(this.checker.target.backend) == "native"; +} + +#! Makes the version of a function optimized for x86-64-v3, where it asks which +#! instructions the processor has, and optimizes it: what the processor has is +#! known to hold those, and each call goes to the version of what it calls, +#! where there is one. +#! @param this The compiler. +#! @param index The function, optimized. +#! @param ranks Where each function is in the order functions are optimized +#! in, as `optimizing` says, which the version is added to. +#! @param rank Where the version is: after the function, and before the +#! next in the order. +pub def lowerer::make_version(&mut this, index: u32, ranks: &mut vector, rank: u32): void { + return if !this.versions_made() || this.program.functions[index].body.wide; + # One left unfinished is not compacted, and nothing reaches it, so it is + # dropped rather than given a version. + return if this.program.functions[index].unfinished; + return if !this.program.functions[index].body.asks_processor() && !this.calls_small_version(index); + + var body := this.program.functions[index].body.duplicate(); + body.wide = true; + for i in 0..body.insts.length { + val kind := body.insts[i].kind; + if kind == op::cpu { + body.insts[i].imm = cpu_v3; + } else if kind == op::call { + val version: u32 = this.program.functions[body.insts[i].aux].version; + if version != 0 { + body.insts[i].aux = version - 1; + } + } + } + + val original := &this.program.functions[index]; + this.program.functions.append(function { + name = string::from(original.name.view(), nothing {}), + decl = original.decl, + instance = original.instance, + node = original.node, + outer = original.outer, + table = original.table, + file = original.file, + offset = original.offset, + signature = original.signature, + body = move(&mut body), + compiled = bytecode::new(), + lowered = true, + order = vector::::new(), + closure = original.closure, + callback = original.callback, + inline = original.inline + }); + val made := (this.program.functions.length - 1) as u32; + this.program.functions[index].version = made + 1; + ranks.append(rank); + var found := vector::::new(); + this.optimize_function(made, ranks, rank, &mut found); + this.program.functions[made].optimized = true; + for &each in found { + this.problems.append(string::copy_of(&each)); + } +} diff --git a/compiler/program.sakura b/compiler/program.sakura new file mode 100644 index 00000000..fe606480 --- /dev/null +++ b/compiler/program.sakura @@ -0,0 +1,199 @@ +#! @file program.sakura +#! @author John Christman (sorakatadzuma@gmail.com) +#! @copyright Malunal Studios, LLC. +#! @license MIT +#! +#! Contains the program lowering makes: the layouts of its types, the +#! signatures its calls pass arguments by, its functions, each with its +#! intermediate code, the C functions it calls, the vtables of the traits it +#! refers to values through, the bytes it holds for as long as it runs, and +#! the size of its globals. Layouts and signatures are those the C compiler's +#! `sources/program.h` describes, so the runtime reads the image an executable +#! is built with as it reads the C compiler's. + +module sakura::compiler; + + +#! Every frame word, and every scalar in a frame, is this many bytes. +pub const word_size: u64 = 8; + +#! The kinds of layout, numbered as `sources/program.h` and the runtime number +#! them. +pub enum lk : u8 { + empty, #! `void`, which holds nothing. + signed, #! A signed integer. + unsigned, #! An unsigned integer. + floating, #! A float. + boolean, #! `bool`. + reference, #! A reference: the address of what it refers to. + trait_reference, #! A reference to a trait: a reference, then its vtable. + fixed, #! A fixed array: its elements, one after another. + record, #! A struct: its fields where `offset` says. + variant, #! A union: its tag, which field it holds, then that field. + function, #! A function value: its function plus one, then its environment. + pointer, #! A pointer: an address the program follows itself. +} + +#! The layout of a type: how its values are held in memory and in frames. +pub struct layout { + pub var kind: lk; #! What kind of value it holds. + pub var how: access; #! How a scalar is read and written, or `bytes`. + pub var bits: u32; #! The bits of a number. + pub var size: u64; #! The bytes it takes in memory. + pub var align: u64; #! What its address in memory is a multiple of. + pub var frame: u64; #! The bytes it takes in a frame, where a scalar is widened to a word. + pub var type_id: u32; #! The type laid out. + pub var name: u32; #! The name of a struct, union, or enum, or 0. + pub var element: u32; #! One more than the layout of a fixed array's elements, or of what a reference or pointer reaches, or 0. + pub var fields: u32; #! The first of its fields in the program's `fields`. + pub var count: u32; #! How many fields it has, or elements a fixed array holds. + pub var pointers: bool; #! Whether it may hold a reference, a trait reference, or a function value. + pub var texts: bool; #! Whether it is text, written as the bytes it holds rather than as its fields. + pub var views: bool; #! Whether it is a view, written as the elements it views. + pub var viewed: u32; #! One more than the layout of the elements a view views, or 0. + pub var text: u32; #! The field saying where the bytes or elements begin, the next saying how many. + pub var niche: u32; #! Of a union laid out without a tag: one more than the field it holds wherever its first word is not zero, the other field, which is empty, held where it is. +} + +#! A field of a struct or union, or a member of an enum, which its layout +#! names as a field whose offset is its value. +pub struct slot_field { + pub var name: u32; #! The ID of its name. + pub var layout: u32; #! Its layout, or 0 for a member of an enum. + var type_id: u32; #! Its type. + pub var offset: u64; #! Where it begins, or a member's value. + var decl: u32; #! The field's declaration. + var spread: bool; #! Whether it spreads another struct's fields into its own. +} + +#! How a call passes arguments and takes a result: each parameter where it is +#! in the frame of the function called, and the result's layout. +pub struct signature { + pub var params: vector; #! The layout of each parameter. + var offsets: vector; #! Where each begins among the parameters. + var size: u64; #! The bytes of every parameter, in a frame. + pub var result: u32; #! The result's layout. +} + +#! A function of the program. +pub struct function { + pub var name: string; #! Its name, as a trace writes it, as `vec2::normalize`. + pub var decl: u32; #! Its declaration, or 0 for what lowering makes. + pub var instance: u32; #! One more than the instance of a generic it is, or 0. + pub var node: u32; #! The node of an anonymous function, or of a function named as a value of another function type, which an adapter calls; or 0. + pub var adapted: u32; #! Of an adapter, one more than the function it calls as the function type it is of asks, or 0. + pub var outer: u32; #! Of an anonymous function, the declaration of the function it is written in. + pub var table: u32; #! The result table of an anonymous function, which holds its nodes' results. + pub var file: u32; #! The file it is declared in. + pub var offset: u32; #! The byte of the file it is declared at. + pub var signature: u32; #! How it is called. + pub var body: code; #! Its code, once lowered. + pub var compiled: bytecode; #! Its code for the machine, once assembled. + pub var lowered: bool; #! Whether its code is lowered, and kept: what nothing reaches once the program is optimized is dropped, as though never lowered. + var optimized: bool; #! Whether its code is optimized, which is done once. + var unfinished: bool; #! Whether only the passes up to inlining ran on it, as the function alone calling it copies it whole, and optimizes it there. + var inlining: inline_facts; #! What inlining knows of it. + var order: vector; #! Its blocks in reverse postorder, made once it is first inlined. + var named: vector; #! The functions its code names as values, and the code inlined into it named, which optimizing it waits for as for those it calls, so a call through one may become a call of it. + var queued: bool; #! Whether it waits to be lowered. + pub var closure: bool; #! Whether its environment follows its parameters. + pub var callback: bool; #! Whether C calls it back, as it was given where a `cfn` is expected. + pub var stepping: bool; #! Whether it is a method an iterator gives its elements by, `next` or `next_back`, or a functor's `invoke`, which a loop calling it inlines though it is larger. + pub var inline: bool; #! Whether it is written `@inline`, so each call of it is copied wherever inlining can copy one, at every level, whatever its size. + pub var taken: bool; #! Whether it is reached other than by the program's calls: as a value code takes or a constant holds, or by the backend calling it by name. + var evaluation: u32; #! One more than the evaluation it computes, of a program evaluating constants, or 0. + var builtin: u32; #! The name of the method it gives a built-in type, or 0. + var owner_type: u32; #! The built-in type it gives the method. + pub var version: u32; #! One more than its version for processors with x86-64-v3's instructions, which it goes to where the processor has them, or 0. +} + +#! A C function the program calls by name, which the system finds in the +#! libraries its file's `extern import`s name, or among what the running program +#! has where it names none. +pub struct linked { + pub var name: u32; #! The ID of its name. + pub var library: string; #! The first of its libraries, which is its only one on Windows, or empty. + pub var libraries: vector; #! Every library its file names for the target, which a dynamically linked executable needs. + pub var decl: u32; #! Its declaration. +} + +#! The functions a type gives for a trait's methods, in the order the trait's +#! dispatch numbers them. +pub struct vtable { + var type_id: u32; #! The type referred to. + var trait_id: u32; #! The trait's type, given its arguments. + pub var layout: u32; #! The layout of what the trait reference refers to. + pub var functions: vector; #! The function of each method, or `no_function` for an `@optional` one left out. + pub var owners: vector; #! The vtable each method's code addresses: this, or a composed trait's whose default it is. +} + +#! What stands where a vtable has no function, as for an `@optional` method a +#! type leaves out. +pub const no_function: u32 = 0xFFFFFFFF; + +#! Where each vtable of one trait goes as a reference to it converts to a +#! reference to another, once every vtable is made. +pub struct retrait { + var from: u32; #! The trait's type converted from. + var to: u32; #! The trait's type converted to. + pub var vtables: vector; #! The vtable each becomes, by the vtable it was. +} + +#! Where bytes held for as long as the program runs hold the address of other +#! such bytes: `addend` bytes into datum `target`, written at byte `at`. +pub struct relocation { + pub var at: u64; #! The byte the address is written at. + pub var target: u32; #! The datum it points into. + pub var addend: u64; #! The byte within that datum. +} + +#! Bytes the program holds for as long as it runs, as text and the elements of +#! a literal viewed, which are never written. Each is followed by a zero the +#! length does not count, so text is also what C reads. +pub struct datum { + pub var bytes: vector; #! Its bytes. + pub var align: u64; #! What its address is a multiple of. + pub var relocations: vector; #! Where its bytes hold the address of a datum. +} + +#! The program. +pub struct program { + pub var layouts: vector; #! Every layout, by index. + pub var fields: vector; #! The fields of every layout, as runs each layout's `fields` begins. + pub var signatures: vector; #! Every signature, by index. + pub var functions: vector; #! Every function, by index. + pub var linked: vector; #! The C functions it calls by name. + pub var vtables: vector; #! Its vtables. + pub var retraits: vector; #! The conversions between references to traits it makes. + pub var data: vector; #! What it holds for as long as it runs. + pub var globals: u64; #! The bytes of its globals. + pub var preset: vector; #! The bytes its globals begin with, as far as values known while compiling give them; the rest begin as zeros. + pub var init: u32; #! The function initializing the globals. + pub var main: u32; #! The function `main`, or `no_function`. +} + +#! Makes an empty program. +#! @returns The program. +pub def program::new(): program { + return program { + layouts = vector::::new(), + fields = vector::::new(), + signatures = vector::::new(), + functions = vector::::new(), + linked = vector::::new(), + vtables = vector::::new(), + retraits = vector::::new(), + data = vector::::new(), + preset = vector::::new(), + init = no_function, + main = no_function + }; +} + +#! Rounds a size up to a multiple of an alignment. +#! @param size The size. +#! @param align The alignment, which is not 0. +#! @returns The size rounded. +pub def round_up(size: u64, align: u64): u64 { + return (size + align - 1) / align * align; +} diff --git a/compiler/report.sakura b/compiler/report.sakura new file mode 100644 index 00000000..42f715bc --- /dev/null +++ b/compiler/report.sakura @@ -0,0 +1,113 @@ +#! @file report.sakura +#! @author John Christman (sorakatadzuma@gmail.com) +#! @copyright Malunal Studios, LLC. +#! @license MIT +#! +#! Contains what `check --checks-report` lists: the checks a checked program +#! makes that the optimizer could not leave out, in the code of the program's +#! own functions, each at the line of the function's own source it comes from. +#! A check inlined from std, as `vector::at`'s, is at the line of the call, so +#! the list says where an unchecked build trusts the program, and where a `get` +#! may be better than `[]`. + +import sakura::analyzer; +import std::containers; +module sakura::compiler; + + +#! What a check stops the program for. +pub enum checked : u8 { + index, #! An index or a slice past the end, of a view, a fixed array, or a container. + field, #! The field a union does not hold, read. + member, #! An integer converted to an enum none of whose members has its value, or a `match` finding no arm. + fault, #! A contract, or a check std makes itself, which faults where it fails. + count, #! How many kinds there are; not a kind itself. +} + +#! The checks of one kind a function's code makes at one line of its own +#! source. +pub struct check_site { + pub var function: u32; #! The function. + pub var at: u64; #! Where in its own source: one more than the file, then the byte of the code's own instruction or of the call it was inlined from. + pub var kind: checked; #! What they stop the program for. + pub var count: u32; #! How many there are. +} + +#! The checks the code of the program's own functions makes, once lowered and +#! optimized, in the order of the functions and of where each is. +#! @param this The compiler. +#! @returns The checks, those of each place and kind together. +pub def lowerer::checks_left(&mut this): vector { + var made := vector::::new(); + for f in 0..this.program.functions.length { + val held := &this.program.functions[f]; + continue if !held.lowered; + val decl := held.decl != 0 ? held.decl : held.outer; + continue if decl == 0 || this.in_std(decl); + var found := dict::::new(); + var places := vector::::new(); + var walk := held.body.walk_all(); + while walk.more() { + val each: inst = held.body.insts[walk.next()]; + val kind := this.check_kind(&each); + continue if kind == checked::count; + val at := own_place(&held.body, &each); + val key := (at << 3) | kind as u64; + if found.contains(&key) { + found[key] += 1; + } else { + found.set(key, 1); + places.append(key); + } + } + places.sort(); + for &key in places { + made.append(check_site { function = f as u32, at = key >> 3, kind = (key & 7) as checked, count = found[key] }); + } + } + return made; +} + +#! What an instruction checks, or `checked::count` where it checks nothing. +#! @param this The compiler. +#! @param held The instruction. +#! @returns The kind. +def lowerer::check_kind(&mut this, held: &inst): checked { + match held.kind { + op::check => { + return match held.aux { + fault::out_of_bounds as u32 => checked::index, + fault::not_held as u32 => checked::field, + fault::not_member as u32 => checked::member, + else => checked::count + }; + } + op::trap => return held.aux == fault::not_member as u32 ? checked::member : checked::count; + op::fault => return checked::fault; + op::call => { + # A container's own check calls `past_end` only where it fails. + val decl := this.program.functions[held.aux].decl; + return checked::count if decl == 0 || !this.in_std(decl); + return this.checker.names.text(this.checker.decls.names.p[decl]) == "past_end" ? checked::index : checked::count; + } + else => return checked::count; + } +} + +#! Where an instruction is in the source of the function whose code holds it: +#! its own place, or, inlined, that of the outermost call it was inlined from. +#! @param body The code. +#! @param held The instruction. +#! @returns The place: one more than the file, then the byte. +def own_place(body: &code, held: &inst): u64 { + var site := held.site; + var at := held.at; + var steps := 0; + while site != 0 && steps < 256 { + val from: inline_site = body.sites[site - 1]; + at = from.at; + site = from.parent; + steps++; + } + return at; +} diff --git a/compiler/scratch.sakura b/compiler/scratch.sakura new file mode 100644 index 00000000..c78d8ca3 --- /dev/null +++ b/compiler/scratch.sakura @@ -0,0 +1,145 @@ +#! @file scratch.sakura +#! @author John Christman (sorakatadzuma@gmail.com) +#! @copyright Malunal Studios, LLC. +#! @license MIT +#! +#! Contains the arenas what the compiler works out only for a while is held in: +#! what a pass of the optimizer finds before it changes the code, and what +#! lowering, verifying, and assembling a function find as they go. Each of those +#! marks the arena where it begins and rewinds it to the mark where it ends, so +#! what it took is freed at once, and the next takes the same memory again. +#! Handing out a block is then an addition, and giving it back nothing at all. +#! +#! Each thread has an arena of its own, as a mark and a rewind on one thread +#! would otherwise free what another still holds. The first thread takes from +#! one of its own; the threads `share_out` starts, its crew, each take from one +#! of the crew's arenas, which each finds by the number the system knows its +#! thread by, while the crew works. Where none works, as while the compiler +#! works alone, nothing is looked for. + +import std::thread; +import std::allocators; +module sakura::compiler; + + +#! The arena the first thread's scratch memory comes from, in chunks of 256 KiB, +#! which the compiler never closes. +var scratch_arena := arena::new(262144); + +#! The arenas of the crew, which stay where they are while it works, so the +#! room for them is made before any of it starts. They are kept, with their +#! chunks, for the next crew. +var crew_arenas := vector::::new(); + +#! The number the system knows each thread of the crew by, by its place, or 0 +#! until it starts. Every thread reads these, and none writes them once the +#! crew has started, so they stay in every processor's cache. +var crew_threads := vector::>::new(); + +#! The arena each thread of the crew takes from, by its place, which only that +#! thread reads and writes once the crew has started, each on a line of the +#! processor's cache of its own, so one writing its own makes no other read +#! again. +var crew_hands := vector::::new(); + +#! How many threads the crew has, or 0 where none works. +var crew_size := atomic::::new(0); + +#! The arena a thread of the crew takes from, padded to a line of the +#! processor's cache. +struct hand { + var arena: u32; #! Its place in `crew_arenas`. + var pad: u64[7]; #! What fills the rest of the line. +} + +#! Memory for what the compiler works out only while it does one thing, which +#! is freed where that ends. +#! @returns The arena of the thread calling, as an allocator. +#! @remarks Nothing taken from it may be kept past the mark it was taken after: +#! a vector of it is closed before the mark is rewound to, and never +#! moved into what outlives it, as the code of a function does. +pub def scratch(): maybe<&mut allocator> { + return own_arena(); +} + +#! Where the scratch memory of the thread calling has been handed out to, which +#! `release_scratch` frees what was handed out after. +#! @returns The mark. +pub def mark_scratch(): arena::point { + return own_arena().mark(); +} + +#! Frees the scratch memory the thread calling had handed out after a mark. +#! @param to The mark, which `mark_scratch` gave on the same thread. +pub def release_scratch(to: arena::point): void { + own_arena().rewind(to); +} + +#! The arena the thread calling takes its scratch memory from: that of its place +#! in the crew, or the first thread's. +#! @returns The arena. +def own_arena(): &mut arena { + val size := crew_size.load(order::acquire); + if size != 0 { + val me := thread::id(); + for k in 0..size as u64 { + if crew_threads[k].load(order::relaxed) == me { + return &mut crew_arenas[crew_hands[k].arena as u64]; + } + } + } + return &mut scratch_arena; +} + +#! Makes the room a crew works in, before any of it starts: a place for each +#! thread, the `k`th taking from the `k`th arena until it takes from another, +#! and as many arenas as are asked for, at least one for each thread. +#! @param threads How many threads the crew has. +#! @param arenas How many arenas it takes from. +pub def gather_crew(threads: u32, arenas: u32): void { + expects(crew_size.load(order::acquire) == 0); + val wanted := arenas > threads ? arenas : threads; + while crew_arenas.length < wanted as u64 { + crew_arenas.append(arena::new(262144)); + } + crew_threads.clear(); + crew_hands.clear(); + for k in 0..threads { + crew_threads.append(atomic::::new(0)); + crew_hands.append(hand { arena = k }); + } + crew_size.store(threads, order::release); +} + +#! Says the thread calling is the one of a place in the crew, which takes its +#! scratch memory from that place's arena from then on. +#! @param place Its place. +pub def join_crew(place: u32): void { + crew_threads[place as u64].store(thread::id(), order::release); +} + +#! Has the thread of a place in the crew, which calls it, take its scratch +#! memory from another arena. +#! @param place Its place. +#! @param arena The arena, by its place among the crew's. +pub def take_scratch_from(place: u32, arena: u32): void { + crew_hands[place as u64].arena = arena; +} + +#! One of the crew's arenas, for the thread that holds it alone, as to reset it. +#! @param index Its place among the crew's. +#! @returns The arena. +pub def crew_arena(index: u32): &mut arena { + return &mut crew_arenas[index as u64]; +} + +#! Says no crew works any more, once every thread of it has ended. Its arenas +#! are reset, keeping their chunks for the next. +pub def dismiss_crew(): void { + crew_size.store(0, order::release); + crew_threads.clear(); + crew_hands.clear(); + for &mut each in crew_arenas { + each.reset(); + } +} diff --git a/compiler/tracking.sakura b/compiler/tracking.sakura new file mode 100644 index 00000000..c1bd3030 --- /dev/null +++ b/compiler/tracking.sakura @@ -0,0 +1,211 @@ +#! @file tracking.sakura +#! @author John Christman (sorakatadzuma@gmail.com) +#! @copyright Malunal Studios, LLC. +#! @license MIT +#! +#! Contains the small containers the compiler's passes keep track of what they +#! find with: a worklist, which takes each index once, a set emptied at once +#! each round, and a dictionary whose changes are taken back as a scope ends. + +import std::containers; +module sakura::compiler; + + +#! A worklist of indices below a count, as of the blocks a walk reaches or the +#! values a pass finds needed: each is pushed once, and is known to have been +#! pushed after it is popped. +pub struct worklist { + var seen: vector; #! Whether each index was pushed. + var todo: vector; #! The indices pushed and not popped yet, the next last. +} + +#! Makes an empty worklist. +#! @param count How many indices there are. +#! @param alloc The optional allocator its memory is taken from. +#! @returns The worklist. +pub def worklist::new(count: u64, alloc: maybe<&mut allocator>): worklist { + var made := worklist { seen = vector::::new(alloc), todo = vector::::new(alloc) }; + made.seen.resize(count); + return made; +} + +#! Whether no index pushed is left to pop. +#! @param this The worklist. +#! @returns Whether none is. +pub val worklist::is_empty: bool { + get => this.todo.length == 0; +} + +#! Pushes an index, where it was never pushed before. +#! @param this The worklist. +#! @param index The index. +#! @returns Whether it was new. +pub def worklist::push_new(&mut this, index: u32): bool { + return false if this.seen[index]; + this.push(index); + return true; +} + +# Pushes an index never pushed before, apart from `push_new`, so that what +# asks whether it was is small enough to be inlined. +def worklist::push(&mut this, index: u32): void { + this.seen[index] = true; + this.todo.append(index); +} + +#! Pops the index pushed last of those left. +#! @param this The worklist, which holds one, or else the program stops. +#! @returns The index. +pub def worklist::pop(&mut this): u32 { + val index: u32 = this.todo.last(); + this.todo.truncate(); + return index; +} + +#! Whether an index was ever pushed. +#! @param this The worklist. +#! @param index The index. +#! @returns Whether it was. +pub def worklist::has(&this, index: u32): bool { + return this.seen[index]; +} + +#! A set of indices below a count, emptied at once as each round begins, as +#! what one function, or one block, of many counted: an index is in the set +#! where it was put in during the round. +pub struct stamped_set { + var stamps: vector; #! The round each index was last put in during, or 0. + var round: u32; #! The round now, from 1. +} + +#! Makes an empty set, in its first round. +#! @param count How many indices there are. +#! @param alloc The optional allocator its memory is taken from. +#! @returns The set. +pub def stamped_set::new(count: u64, alloc: maybe<&mut allocator>): stamped_set { + var made := stamped_set { stamps = vector::::new(alloc), round = 1 }; + made.stamps.resize(count); + return made; +} + +#! Begins the next round, which empties the set. +#! @param this The set. +pub def stamped_set::next_round(&mut this): void { + this.round++; +} + +#! Puts an index in the set, whether or not it is in it already. +#! @param this The set. +#! @param index The index. +pub def stamped_set::put(&mut this, index: u32): void { + this.stamps[index] = this.round; +} + +#! Puts an index in the set. +#! @param this The set. +#! @param index The index. +#! @returns Whether it was new to the set this round. +pub def stamped_set::insert(&mut this, index: u32): bool { + return false if this.stamps[index] == this.round; + this.stamps[index] = this.round; + return true; +} + +#! Whether an index was put in the set this round. +#! @param this The set. +#! @param index The index. +#! @returns Whether it was. +pub def stamped_set::contains(&this, index: u32): bool { + return this.stamps[index] == this.round; +} + +#! A dictionary of plain keys and values, as indices, whose changes are taken +#! back as a scope ends: each value set is noted with what its key held before, +#! and rewinding to a mark puts back what each key held then, the last change +#! first, as a walk down a tree takes back what each node added as it leaves. +#! @tparam K The type of its keys, which a `dict` takes. +#! @tparam V The type of its values. +pub struct scoped_dict { + var map: dict; #! What each key holds now. + var changes: vector::change>; #! Each change made, in order. +} + +#! A change a scoped dictionary made: the key set, and what it held before. +pub struct scoped_dict::change { + var key: K; #! The key. + var old: V; #! The value it held before, where it held one. + var had: bool; #! Whether it held one. +} + +#! Makes an empty dictionary. +#! @param alloc The optional allocator its memory is taken from. +#! @returns The dictionary. +pub def scoped_dict::new(alloc: maybe<&mut allocator>): scoped_dict { + return scoped_dict:: { + map = dict::::new(alloc), + changes = vector::::change>::new(alloc) + }; +} + +#! Reads the value of a key. +#! @param this The dictionary. +#! @param key The key. +#! @returns Maybe the value; otherwise, `nothing`. +pub def scoped_dict::get(&this, key: &K): maybe<&V> { + return this.map.get(key); +} + +#! The value of a key, or another value where it holds none. +#! @param this The dictionary. +#! @param key The key. +#! @param fallback What is given where the key holds no value. +#! @returns The value, or `fallback`. +pub def scoped_dict::get_or(&this, key: &K, fallback: V): V { + return this.map.get_or(key, fallback); +} + +#! Whether a key holds a value. +#! @param this The dictionary. +#! @param key The key. +#! @returns Whether it does. +pub def scoped_dict::contains(&this, key: &K): bool { + return this.map.contains(key); +} + +#! Sets the value of a key, noting what it held before. +#! @param this The dictionary. +#! @param key The key. +#! @param value The value. +pub def scoped_dict::set(&mut this, key: K, value: V): void { + if this.map.insert(key, value) { + this.changes.append(scoped_dict::::change { key = key, old = value, had = false }); + return; + } + this.changes.append(scoped_dict::::change { key = key, old = this.map.get_or(&key, value), had = true }); + this.map.set(key, value); +} + +#! How many changes were made, which `rewind` takes back those made since. +#! @param this The dictionary. +#! @returns The mark. +pub def scoped_dict::mark(&this): u64 { + return this.changes.length; +} + +#! Takes back the changes made since a mark, the last first. +#! @param this The dictionary. +#! @param mark How many changes were made before. +pub def scoped_dict::rewind(&mut this, mark: u64): void { + return if this.changes.length <= mark; + var at := this.changes.length; + while at > mark { + at--; + val each: scoped_dict::change = this.changes[at]; + if each.had { + this.map.set(each.key, each.old); + } else { + this.map.remove(&each.key); + } + } + this.changes.resize(mark); +} diff --git a/compiler/workers.sakura b/compiler/workers.sakura new file mode 100644 index 00000000..4bdef08a --- /dev/null +++ b/compiler/workers.sakura @@ -0,0 +1,145 @@ +#! @file workers.sakura +#! @author John Christman (sorakatadzuma@gmail.com) +#! @copyright Malunal Studios, LLC. +#! @license MIT +#! +#! Contains how the compiler shares work out among threads: a crew of them, +#! with the thread asking, takes the indexes of what is to be done, each the +#! next one none has taken, until none is left. What each does is its own, as +#! the code of one function, and what they all read stays as it is while they +#! work, so they never wait on one another but to take an index. Each thread of +#! the crew has scratch memory of its own, as `scratch.sakura` says. +#! +#! Where one thread is asked for, none starts, and the thread asking does every +#! index, in order: the compiler then works as it would with no threads at all. + +import std::containers; +import std::thread; +module sakura::compiler; + + +#! Does something for each index below a count, on as many threads as asked, +#! the one calling among them, each taking the next index none has taken. +#! @param count How many indexes there are. +#! @param threads How many threads work, the one calling among them; where +#! more are asked for than there are indexes, one is started +#! for each index but the first, and where some cannot be +#! started, those that were do it all. +#! @param each What is done for an index, which may be done on any of the +#! threads, at the same time as for others. +pub def share_out(count: u64, threads: u32, each: def(u64): void): void { + val helpers := crew_for(count, threads); + if helpers == 0 { + for i in 0..count { + each(i); + } + return; + } + + var next := atomic::::new(0); + run_crew(helpers, def(): void { + take_each(&mut next, count, each); + }); +} + +#! Does something for each index below a count, as `share_out` does, but for +#! each only once it is done for those the index waits for, each of which is +#! below it, so one thread doing them all does them in order. +#! @param count How many indexes there are. +#! @param threads How many threads work, the one calling among them. +#! @param waiting The indexes waiting for each index, grouped by it, sealed, +#! each once in a group. +#! @param each What is done for an index, which may be done on any of the +#! threads, at the same time as for others it does not wait +#! for. +pub def share_out_ordered(count: u64, threads: u32, waiting: &groups, each: def(u64): void): void { + val helpers := crew_for(count, threads); + if helpers == 0 { + for i in 0..count { + each(i); + } + return; + } + + # Each index is handed out once nothing it waits for is left undone, and the + # thread doing the last closes the channel, which ends every thread taking + # from it. + var waits := vector::::new(); + waits.resize(count); + for i in 0..count { + for &after in waiting.of(i) { + waits[after] = waits[after] + 1; + } + } + var left := vector::>::new(); + var ready := thread::channel::::new(0); + var done := atomic::::new(0); + for i in 0..count { + left.append(atomic::::new(waits[i])); + if waits[i] == 0 { + _ = ready.send(i); + } + } + val work := def(): void { + while ready.receive() is some(index) { + each(index); + for &after in waiting.of(index) { + if left[after].fetch_sub(1) == 1 { + _ = ready.send(after as u64); + } + } + if done.fetch_add(1) + 1 == count { + ready.close(); + } + } + }; + + run_crew(helpers, work); +} + +#! Runs work on a crew of threads started beside the one calling, which runs it +#! too, each with scratch memory of its own, and waits for every one to end. +#! @param helpers How many threads to start; where some cannot be started, +#! those that were and the one calling do the work. +#! @param work What each thread runs, which shares out what it does with +#! the others. +pub def run_crew(helpers: u32, work: def(): void): void { + gather_crew(helpers, helpers); + var started := vector::>::new(); + for k in 0..helpers { + var made := thread::spawn_with::(def(place: u32): void { + join_crew(place); + work(); + }, k) else (_) { break; }; + started.append(move(&mut made)); + } + work(); + for &mut handle in started { + handle.join(); + } + dismiss_crew(); +} + +#! How many threads to start beside the one calling, for a count of indexes and +#! the threads asked for. +#! @param count How many indexes there are. +#! @param threads How many threads are asked for, the one calling among them. +#! @returns How many, 0 where the one calling does it all. +pub def crew_for(count: u64, threads: u32): u32 { + return 0 if threads <= 1 || count <= 1; + return (count - 1) as u32 if count - 1 < (threads - 1) as u64; + return threads - 1; +} + +#! Takes the next index none has taken, and does what is done for it, until +#! none is left. +#! @param next The next index none has taken. +#! @param count How many indexes there are. +#! @param each What is done for each. +def take_each(next: &mut atomic, count: u64, each: def(u64): void): void { + while true { + val index := next.fetch_add(1); + return if index >= count; + each(index); + } +} diff --git a/core/allocators/allocator.sakura b/core/allocators/allocator.sakura new file mode 100644 index 00000000..e7cdd05d --- /dev/null +++ b/core/allocators/allocator.sakura @@ -0,0 +1,170 @@ +#! @file allocator.sakura +#! @author John Christman (sorakatadzuma@gmail.com) +#! @copyright Malunal Studios, LLC. +#! @license MIT +#! +#! Contains the `allocator` trait, which hands out blocks of memory and takes +#! them back, and the functions containers acquire, dispose of, and resize their +#! memory through: each uses the allocator it is given, or the program's heap +#! where it is given none. Each block is asked for with its size and its +#! alignment, and an allocator must outlive every block it gave. + +module core; + +#! Defines what all allocators should be able to do. +#! +#! Allocators are simply a structured mechanism for being able to manage memory +#! in a way that is clear and simple, as an arena, a pool, or the program's heap +#! does. +#! +#! A block is given back with the size it was asked for with, so an allocator +#! need not keep the size of each block itself. +pub trait allocator { + #! The purpose of acquire is to provide you with a block of memory from the + #! backing data store that the allocator is managing. + #! @param this The allocator to acquire from. + #! @param size The number of bytes the block holds. + #! @param align What the address of its first byte is a multiple of, a power + #! of two no wider than `max_align`. + #! @returns The block if it could be acquired; otherwise `null`. + #! @remarks The block may hold anything at first. + def acquire(&mut this, size: u64, align: u64): *mut u8; + + #! The purpose of dispose is to reclaim the block of memory that was allocated + #! to you, freeing it in the backing data store that the allocator is + #! managing. + #! @param this The allocator to dispose to. + #! @param addr The block of memory to dispose. + #! @param size The number of bytes it was acquired or last resized with. + def dispose(&mut this, addr: *mut u8, size: u64): void; + + #! The purpose of resize is to provide you with a block of memory of another + #! size, holding what a block it handed out holds, as far as both reach. + #! + #! It will allocate the new block, copy the data of the old block to the newly + #! allocated one, then release the old block in most cases. The allocator + #! implementation has discretion in how it actually accomplishes this, and may + #! grow or shrink the block where it is. + #! @param this The allocator to resize the allocation. + #! @param addr The block to resize, or `null` to acquire one. + #! @param old The number of bytes it was acquired or last resized with, or + #! 0 where `addr` is `null`. + #! @param size The number of bytes the new block holds. + #! @param align What the address of its first byte is a multiple of, as it + #! was acquired with. + #! @returns The new block if it could be acquired; otherwise `null`, leaving + #! the old block as it was. + #! @remarks What the new block holds past what it keeps may be anything. + def resize(&mut this, addr: *mut u8, old: u64, size: u64, align: u64): *mut u8; +} + +#! Acquires memory for a number of elements, from an allocator or the heap. +#! +#! When the allocator is present, its `acquire` gives the block. Otherwise the +#! program's heap gives it, as `raw_allocate` does, uncleared. +#! @tparam T The type of the elements the memory holds. +#! @param alloc The optional allocator to acquire from. +#! @param count How many elements the memory holds. +#! @returns The block, as a pointer to its first element. +#! @remarks The block is zeroed where `T` is `closeable`, so that assigning an +#! element into it closes nothing; otherwise it may hold anything at +#! first. An allocator that gives no memory stops the program, as +#! `raw_allocate` does where the system gives none, so what is given is +#! never `null` where any memory was asked for. +pub def acquire(alloc: maybe<&mut allocator>, count: u64): *mut T { + if const T is closeable { + return acquire_zeroed::(alloc, count); + } + val wanted := bytes_of::(count); + val block := match alloc { + some(held) => held.acquire(wanted, align_of::()), + none => raw_allocate(wanted) + }; + if block == null && wanted != 0 { + exhausted(wanted); + } + return block as *mut T; +} + +#! Takes zeroed memory for a number of elements, from an allocator or, where +#! none is given, from the program's heap, which clears only memory it used +#! before, as `raw_allocate_zeroed` does. +#! @tparam T The type of the elements. +#! @param alloc The optional allocator to take it from. +#! @param count How many elements. +#! @returns The first element, zeroed. +#! @remarks An allocator that gives no memory stops the program, as `acquire` +#! does. +pub def acquire_zeroed(alloc: maybe<&mut allocator>, count: u64): *mut T { + val wanted := bytes_of::(count); + val block := match alloc { + some(held) => held.acquire(wanted, align_of::()), + none => raw_allocate_zeroed(wanted) + }; + if block == null && wanted != 0 { + exhausted(wanted); + } + if alloc is some(_) { + memset(block, 0, wanted); + } + return block as *mut T; +} + +#! Gives memory back to the allocator it came from, or to the heap. +#! +#! When the allocator is present, its `dispose` takes the block. Otherwise +#! `raw_release` gives it back to the program's heap. +#! @tparam T The type of the elements the memory holds. +#! @param alloc The optional allocator the memory came from. +#! @param addr The first element of the block to give back, or `null`, which +#! gives back nothing. +#! @param count How many elements it was acquired or last resized for. +#! @remarks The block must have come from the same allocator, or from the heap +#! where none is given. Where it did not, what happens is up to the +#! allocator, which may stop the program. +pub def dispose(alloc: maybe<&mut allocator>, addr: *mut T, count: u64): void { + if addr == null { + return; + } + match alloc { + some(held) => held.dispose(addr as *mut u8, bytes_of::(count)); + none => raw_release(addr as *mut u8); + } +} + +#! Resizes memory for a number of elements, from an allocator or the heap. +#! +#! When the allocator is present, its `resize` gives the new block. Otherwise +#! `raw_resize` gives it, from the program's heap, or `acquire` does where there +#! is no block yet. Either keeps what the old block held, as far as the new one +#! reaches, and gives the old block back. +#! @tparam T The type of the elements the memory holds. +#! @param alloc The optional allocator the memory came from. +#! @param addr The first element of the block to resize, which may be `null` +#! to acquire a new one. +#! @param old How many elements it was acquired or last resized for, or 0 +#! where `addr` is `null`. +#! @param count How many elements the new block holds. +#! @returns The new block, as a pointer to its first element. +#! @remarks The new block is zeroed past what was kept where `T` is +#! `closeable`, as `acquire` zeroes it. The block must have come from +#! the same allocator, or from the heap where none is given. An +#! allocator that gives no memory stops the program, as `acquire` does. +pub def resize(alloc: maybe<&mut allocator>, addr: *mut T, old: u64, count: u64): *mut T { + # The old count is one the memory was acquired for, as `dispose` counts it. + val had := addr == null ? 0 : old * size_of::(); + val wanted := bytes_of::(count); + val block := match alloc { + some(held) => held.resize(addr as *mut u8, had, wanted, align_of::()), + none => addr == null ? raw_allocate(wanted) : raw_resize(addr as *mut u8, wanted) + }; + if block == null && wanted != 0 { + exhausted(wanted); + } + if const T is closeable { + if wanted > had { + memset(block + had, 0, wanted - had); + } + } + return block as *mut T; +} diff --git a/core/atomic.sakura b/core/atomic.sakura new file mode 100644 index 00000000..5b9cf026 --- /dev/null +++ b/core/atomic.sakura @@ -0,0 +1,291 @@ +#! @file atomic.sakura +#! @author John Christman (sorakatadzuma@gmail.com) +#! @copyright Malunal Studios, LLC. +#! @license MIT +#! +#! Contains atomics: values that several threads, or a thread and a signal +#! handler, read and write without a lock, the orders that say what each of +#! them sees of the reads and writes around them, and fences. + +module core; + + +#! How an atomic operation orders the reads and writes around it, as C11's +#! memory model has them, which C, C++, Rust, and Zig share. +#! +#! Within a thread, everything happens in the order the program says. Between +#! threads, a `release` store that an `acquire` load reads makes everything the +#! storing thread did before the store visible to the loading thread after the +#! load. `seq_cst` operations also fall in one order that every thread agrees +#! on, and `relaxed` ones are atomic and nothing more. Two threads touching the +#! same memory that is not atomic, at least one of them writing, with neither +#! happening before the other, is a race, which is the program's mistake: what +#! either then reads is not defined. +pub enum order : u8 { + relaxed, #! Only the operation itself is atomic. + acquire, #! What follows a load stays after it. + release, #! What comes before a store stays before it. + acq_rel, #! Both, for operations that read and write. + seq_cst, #! Both, and every `seq_cst` operation falls in one order all threads see. +} + +#! The types an atomic holds: those of a word or less that every processor reads +#! and writes whole without a lock, which are the integers, `bool`, enums, and +#! pointers. The compiler decides what is lock-free, so no type can implement it. +pub trait lockfree {} + +#! A value that threads read and write without a lock. +#! +#! Every operation takes an order, `seq_cst` where none is written, so code that +#! does not care writes none, and code that does says exactly what it needs. +#! Writing takes `&mut this` and reading `&this`, so no read-only reference +#! ever writes; threads share one atomic through `&mut atomic`. +#! +#! It is `owning`, closing nothing, so it is never copied by accident: a copy +#! would read the value without an atomic load, which is a race where another +#! thread writes it. A struct holding one is not copied implicitly either, which +#! is what shared state wants. +#! @tparam T What it holds: an integer, `bool`, enum, or pointer. +pub struct atomic : owning where T: lockfree { + var _value: T; +} + +#! Makes an atomic. +#! @param value What it holds first. +#! @returns The atomic. +pub def atomic::new(value: T): atomic { + return atomic:: { _value = value }; +} + +#! Reads what an atomic holds. +#! @param this The atomic. +#! @param how The order: `relaxed`, `acquire`, or `seq_cst`, since a load +#! publishes nothing. Another stops the program with a fault, +#! which no switch leaves out. +#! @returns What it holds. +pub def atomic::load(&this, how: order = order::seq_cst): T { + if how == order::release || how == order::acq_rel { + misordered(0, how); + } + return atomic_load::((&this._value) as *T, how); +} + +#! Writes a value into an atomic. +#! @param this The atomic. +#! @param value What it holds after. +#! @param how The order: `relaxed`, `release`, or `seq_cst`, since a store +#! sees nothing. Another stops the program with a fault, which +#! no switch leaves out. +pub def atomic::store(&mut this, value: T, how: order = order::seq_cst): void { + if how == order::acquire || how == order::acq_rel { + misordered(1, how); + } + atomic_store::((&mut this._value) as *mut T, value, how); +} + +#! Writes a value into an atomic, giving what it held, in one step. +#! @param this The atomic. +#! @param value What it holds after. +#! @param how The order. +#! @returns What it held before. +pub def atomic::exchange(&mut this, value: T, how: order = order::seq_cst): T { + return atomic_exchange::((&mut this._value) as *mut T, value, how); +} + +#! Writes a value into an atomic where it holds what is expected, in one step. +#! @param this The atomic. +#! @param expected What it must hold to be written. +#! @param desired What it holds after, where it is written. +#! @param success The order where it is written. +#! @param failure The order where it is not, which only reads: `relaxed`, +#! `acquire`, or `seq_cst`, and no stronger than what +#! `success` reads. Another stops the program with a fault, +#! which no switch leaves out. +#! @returns What it held: as the `value` where it was written, and as the +#! `error` where it was not. +pub def atomic::compare_exchange( + &mut this, + expected: T, + desired: T, + success: order = order::seq_cst, + failure: order = order::seq_cst +): result { + if ((failures_taken >> (success as u64 * 5 + failure as u64)) & 1) == 0 { + misordered(2, failure); + } + var found := expected; + if atomic_compare_exchange::((&mut this._value) as *mut T, expected, desired, (&mut found) as *mut T, success, failure) { + return result:: { value = expected }; + } + return result:: { error = found }; +} + +#! As `compare_exchange`, but may fail although the atomic holds what is +#! expected, which costs less on some processors, so it is meant for loops that +#! try again. On x86-64 it never fails so. +#! @param this The atomic. +#! @param expected What it must hold to be written. +#! @param desired What it holds after, where it is written. +#! @param success The order where it is written. +#! @param failure The order where it is not, as `compare_exchange` takes. +#! @returns What it held: as the `value` where it was written, and as the +#! `error` where it was not. +pub def atomic::compare_exchange_weak( + &mut this, + expected: T, + desired: T, + success: order = order::seq_cst, + failure: order = order::seq_cst +): result { + return this.compare_exchange(expected, desired, success, failure); +} + +#! Adds to an integer an atomic holds, wrapping, giving what it held. +#! @param this The atomic. +#! @param amount What is added. +#! @param how The order. +#! @returns What it held before. +pub def atomic::fetch_add(&mut this, amount: T, how: order = order::seq_cst): T { + if const !(T is integer) { + compile_error("`fetch_add` adds to an integer, and the atomic holds none."); + } + return atomic_fetch::((&mut this._value) as *mut T, amount, how); +} + +#! Subtracts from an integer an atomic holds, wrapping, giving what it held. +#! @param this The atomic. +#! @param amount What is subtracted. +#! @param how The order. +#! @returns What it held before. +pub def atomic::fetch_sub(&mut this, amount: T, how: order = order::seq_cst): T { + if const !(T is integer) { + compile_error("`fetch_sub` subtracts from an integer, and the atomic holds none."); + } + return atomic_fetch::((&mut this._value) as *mut T, amount, how); +} + +#! Keeps the bits of an integer an atomic holds that are also set in others, +#! giving what it held. +#! @param this The atomic. +#! @param bits The others. +#! @param how The order. +#! @returns What it held before. +pub def atomic::fetch_and(&mut this, bits: T, how: order = order::seq_cst): T { + if const !(T is integer) { + compile_error("`fetch_and` combines the bits of an integer, and the atomic holds none."); + } + return atomic_fetch::((&mut this._value) as *mut T, bits, how); +} + +#! Sets bits of an integer an atomic holds, giving what it held. +#! @param this The atomic. +#! @param bits The bits set. +#! @param how The order. +#! @returns What it held before. +pub def atomic::fetch_or(&mut this, bits: T, how: order = order::seq_cst): T { + if const !(T is integer) { + compile_error("`fetch_or` combines the bits of an integer, and the atomic holds none."); + } + return atomic_fetch::((&mut this._value) as *mut T, bits, how); +} + +#! Flips bits of an integer an atomic holds, giving what it held. +#! @param this The atomic. +#! @param bits The bits flipped. +#! @param how The order. +#! @returns What it held before. +pub def atomic::fetch_xor(&mut this, bits: T, how: order = order::seq_cst): T { + if const !(T is integer) { + compile_error("`fetch_xor` combines the bits of an integer, and the atomic holds none."); + } + return atomic_fetch::((&mut this._value) as *mut T, bits, how); +} + +#! Lowers an integer an atomic holds to a value where that is less, compared as +#! `T` is, signed or unsigned, giving what it held. +#! @param this The atomic. +#! @param value The value. +#! @param how The order. +#! @returns What it held before. +pub def atomic::fetch_min(&mut this, value: T, how: order = order::seq_cst): T { + if const !(T is integer) { + compile_error("`fetch_min` compares integers, and the atomic holds none."); + } + return atomic_fetch::((&mut this._value) as *mut T, value, how); +} + +#! Raises an integer an atomic holds to a value where that is greater, compared +#! as `T` is, signed or unsigned, giving what it held. +#! @param this The atomic. +#! @param value The value. +#! @param how The order. +#! @returns What it held before. +pub def atomic::fetch_max(&mut this, value: T, how: order = order::seq_cst): T { + if const !(T is integer) { + compile_error("`fetch_max` compares integers, and the atomic holds none."); + } + return atomic_fetch::((&mut this._value) as *mut T, value, how); +} + +#! Closes an atomic, which owns nothing, so it does nothing; an atomic is +#! `owning` only so that it is never copied by accident. +#! @param this The atomic. +pub def atomic::close(&mut this): void { +} + +#! Orders the reads and writes around it as an atomic operation of the order +#! would, without one. +#! @param how The order. +pub def fence(how: order): void { + atomic_fence(how); +} + +# Stops the program where an atomic operation is given an order it does not +# take, as a fault. It is called only where the check fails, so where the +# check holds it costs a compare, which folds away where the order is known, and +# what calls it stays short enough to be emitted where it is called. +# The operation is 0 for a load, 1 for a store, and 2 for a compare-exchange +# failing, whose text it says. +def misordered(operation: u8, how: order): void { + val what := operation == 0 ? "A load's order is `relaxed`, `acquire`, or `seq_cst`" + : operation == 1 ? "A store's order is `relaxed`, `release`, or `seq_cst`" + : "A compare-exchange failing only reads, so its order is `relaxed`, `acquire`, or `seq_cst`, and no stronger than what it reads succeeding"; + fault($"{what}, not `{how}`."); +} + +# The orders a failed compare-exchange takes, of each it takes where it writes: +# the bit `5 * success + failure` is set where that failure order only reads, as +# `relaxed`, `acquire`, and `seq_cst` do, no more strongly than what the success +# order reads. `relaxed` and `release` read as `relaxed`, `acquire` and +# `acq_rel` as `acquire`, and `seq_cst` as itself. +const failures_taken: u64 = 0x1 | 0x60 | 0x400 | 0x18000 | 0x1300000; + +# The operations `atomic_fetch` works, as the compilers number them, after a +# load, store, exchange, and compare-exchange. +const atomic_add: u32 = 4; # Adds, wrapping. +const atomic_sub: u32 = 5; # Subtracts, wrapping. +const atomic_and: u32 = 6; # Keeps the bits both have. +const atomic_or: u32 = 7; # Keeps the bits either has. +const atomic_xor: u32 = 8; # Keeps the bits one has. +const atomic_min: u32 = 9; # Keeps the less, compared as `T` is. +const atomic_max: u32 = 10; # Keeps the greater. + +# Reads `T` at the pointer, in one step, ordered as `how` says. +@intrinsic def atomic_load(at: *T, how: order): T where T: lockfree; + +# Writes a value at the pointer, in one step. +@intrinsic def atomic_store(at: *mut T, value: T, how: order): void where T: lockfree; + +# Writes a value at the pointer, giving what was there, in one step. +@intrinsic def atomic_exchange(at: *mut T, value: T, how: order): T where T: lockfree; + +# Writes `desired` at the pointer where it holds `expected`, in one step, giving +# whether it wrote, and writing what it held where `found` points. +@intrinsic def atomic_compare_exchange(at: *mut T, expected: T, desired: T, found: *mut T, success: order, failure: order): bool where T: lockfree; + +# Works operation `OP` on the integer at the pointer and the operand, writing +# what it gives there, in one step, and giving what was there. +@intrinsic def atomic_fetch(at: *mut T, operand: T, how: order): T where T: lockfree; + +# Orders the reads and writes around it. +@intrinsic def atomic_fence(how: order): void; diff --git a/core/attribute.sakura b/core/attribute.sakura new file mode 100644 index 00000000..d428dab0 --- /dev/null +++ b/core/attribute.sakura @@ -0,0 +1,104 @@ +#! @file attribute.sakura +#! @author John Christman (sorakatadzuma@gmail.com) +#! @copyright Malunal Studios, LLC. +#! @license MIT +#! +#! Contains the `attribute` trait a struct declares to be written after `@`, the +#! `usage` attribute saying what each attribute may be written on, and the +#! attributes the compiler itself reads: `optional`, `intrinsic`, `nodiscard`, +#! `allow`, and `inline`. + +module core; + +#! Marks a struct as one that may be written after `@` on a declaration, as +#! `@test def parses(): void {}`. +#! +#! It asks for no methods: a struct is an attribute only by declaring it, as +#! `struct test : attribute`, and only a struct can be one, since an attribute +#! is written as a struct literal. What it may be written on is said by +#! `@usage`. +pub trait attribute {} + +#! The kinds of declaration an attribute may be written on, which `usage` +#! combines, as `target::functions | target::constants`. +pub enum target : u32 { + functions = 0x0001, #! Functions declared outside any type. + methods = 0x0002, #! Functions declared on a type, as `def list::push`. + constants = 0x0004, #! Constants, including a type's own, as `const u8::top`. + variables = 0x0008, #! Variables outside any function, including a type's own. + fields = 0x0010, #! Fields of structs and unions. + structs = 0x0020, #! Structs. + unions = 0x0040, #! Unions. + enums = 0x0080, #! Enums. + members = 0x0100, #! Members of enums. + traits = 0x0200, #! Traits. + requirements = 0x0400, #! What a trait declares: its methods, properties, and constants. + aliases = 0x0800, #! Declarations of aliases, as `type id = u64`. + properties = 0x1000, #! Properties, both of whose accessors share their attributes. + parameters = 0x2000, #! Parameters of functions, which reflection describes and no attribute is written on. + all = 0xFFFF, #! Every kind of declaration. +} + +#! Says what the attribute struct it is written on may describe. +#! +#! The compiler reads it where each attribute is written, so an attribute on a +#! declaration its usage leaves out, or a second on the same declaration, is an +#! error there. A struct without one may go anywhere, once per declaration. +@usage{ on = target::structs } +pub struct usage : attribute { + #! The kinds of declaration it may be written on. + #! + #! It is defined as a `flags32` to make it explicitly convertible to + #! and from an unsigned integer. By combining targets, an attribute with a + #! non-defaulted `@usage{}` then declares what the attribute may be used on, + #! which becomes enforced by the compiler. + pub val on: flags32 = target::all; + + #! Whether a declaration may have more than one of it. + #! + #! Multiple attributes of the same kind are typically discouraged, but allowed. + #! For example, it may be useful to an application to be able to define an + #! `@alias{ name = ... }` attribute on some object whose name can be many + #! different values. + pub val many: bool = false; + + #! Whether an alias of the declaration it is written on has it too, as reflection + #! sees it. + pub val through: bool = true; +} + +#! Marks a trait's method as one a type may leave out. A call reaches it where +#! the type is known to have it, and through a trait reference, the call goes to +#! the method the trait requires instead, as `at(&this)` stands in for an +#! `indexable`'s `@optional def at(&mut this, key: K): &mut V;`. +@usage{ on = target::requirements } +pub struct optional : attribute {} + +#! Marks what the compiler gives, which ends at its signature: a function, as +#! `@intrinsic def size_of(): u64;`, or a property whose accessors do. +@usage{ on = target::functions | target::methods | target::properties | target::structs } +pub struct intrinsic : attribute {} + +#! Marks what must be handled where it is made: a function whose result each +#! call must use, or a type whose values must be, as `result` is. A call +#! written as a statement of its own that lets such a value go is an error, and +#! `_ = f();` lets it go on purpose. +@usage{ on = target::functions | target::methods | target::requirements | target::structs | target::unions | target::enums } +pub struct nodiscard : attribute {} + +#! Quiets the warnings the checker makes of a function, as of a reference kept +#! past what it refers to, where the function is right for reasons the checker +#! cannot see. +@usage{ on = target::functions | target::methods } +pub struct allow : attribute {} + +#! Marks a function whose calls are each replaced by a copy of its body, at +#! every level of optimizing, `-O0` too, whatever its size. A call it cannot +#! copy stays a call: one through a trait reference, or a function value whose +#! function is not known, and the one closing a loop of calls, as a function +#! calling itself. Written on a property, it marks both accessors. A function +#! C or the compiler gives has no body to copy, so it is never `@inline`. A run +#! checking its memory copies none, so each function's locals end where its +#! frame does. +@usage{ on = target::functions | target::methods | target::properties } +pub struct inline : attribute {} diff --git a/core/bits.sakura b/core/bits.sakura new file mode 100644 index 00000000..44dce092 --- /dev/null +++ b/core/bits.sakura @@ -0,0 +1,74 @@ +#! @file bits.sakura +#! @author John Christman (sorakatadzuma@gmail.com) +#! @copyright Malunal Studios, LLC. +#! @license MIT +#! +#! Contains counting and reversing the bits and bytes of an integer, which no +#! operator writes, and which text, memory, and vectors are searched with. +#! +#! The compiler gives the operations of a whole word they are built on: the +#! virtual machine runs its own, and an executable the instructions `bsr`, +#! `bsf`, and `bswap`, and a sequence counting ones, since SSE2 alone has no +#! `popcnt`. + +module core; + + +#! How many bits of an integer are 1, as its type holds it, so -1 of an `i8` has +#! 8. +#! @tparam T The type of integer. +#! @param x The integer. +#! @returns How many. +pub def count_ones(x: T): u32 where T: integer { + return ones_in(x as u64 & bits_mask::()) as u32; +} + +#! How many 0 bits lead an integer, from its top bit, as its type holds it. +#! @tparam T The type of integer. +#! @param x The integer. +#! @returns How many: the width of the type where it is zero, and 0 where it is +#! below zero. +pub def leading_zeros(x: T): u32 where T: integer { + return (zeros_leading(x as u64 & bits_mask::()) - (64 - size_of::() * 8)) as u32; +} + +#! How many 0 bits trail an integer, from its bottom bit. +#! @tparam T The type of integer. +#! @param x The integer. +#! @returns How many: the width of the type where it is zero. +@inline +pub def trailing_zeros(x: T): u32 where T: integer { + if const size_of::() == 8 { + return zeros_trailing(x as u64) as u32; + } + return zeros_trailing(x as u64 | (1u << (size_of::() * 8))) as u32; +} + +#! An integer with its bytes in the reverse order, as converting between little +#! and big endian does. +#! @tparam T The type of integer. +#! @param x The integer. +#! @returns The integer reversed. +pub def swap_bytes(x: T): T where T: integer { + return (bytes_reversed(x as u64) >> (64 - size_of::() * 8)) as T; +} + +# The bits of a word a type of integer holds. +def bits_mask(): u64 where T: integer { + if const size_of::() == 8 { + return 0xFFFFFFFFFFFFFFFFu; + } + return (1u << (size_of::() * 8)) - 1; +} + +# How many bits of a word are 1. +@intrinsic def ones_in(word: u64): u64; + +# How many 0 bits lead a word from its top: 64 where it is zero. +@intrinsic def zeros_leading(word: u64): u64; + +# How many 0 bits trail a word from its bottom: 64 where it is zero. +@intrinsic def zeros_trailing(word: u64): u64; + +# A word with its bytes in the reverse order. +@intrinsic def bytes_reversed(word: u64): u64; diff --git a/core/bool.ext.sakura b/core/bool.ext.sakura new file mode 100644 index 00000000..5a410296 --- /dev/null +++ b/core/bool.ext.sakura @@ -0,0 +1,14 @@ +#! @file bool.ext.sakura +#! @author John Christman (sorakatadzuma@gmail.com) +#! @copyright Malunal Studios, LLC. +#! @license MIT +#! +#! +module core; + +#! +pub def bool::parse(value: &strview): bool { + return + value == "true" || value == "1" || + value == "yes" || value == "on"; +} diff --git a/core/containers/decimal.sakura b/core/containers/decimal.sakura new file mode 100644 index 00000000..3711583f --- /dev/null +++ b/core/containers/decimal.sakura @@ -0,0 +1,349 @@ +#! @file decimal.sakura +#! @author John Christman (sorakatadzuma@gmail.com) +#! @copyright Malunal Studios, LLC. +#! @license MIT +#! +#! Contains the conversion of decimal text to the nearest 64-bit float, which +#! `real::parse` reads numbers with. +#! +#! Most numbers have few enough digits, and a small enough exponent, that one +#! multiplication or division of two exact floats gives the nearest float. The +#! rest are converted as Go's `strconv` converts them: the number is held as +#! decimal digits, and multiplied and divided by powers of two, which a decimal +#! holds exactly, until its 53 bits can be read off and rounded. + +module core; + +# Digits a decimal holds; past them, only whether any was not zero matters. +const decimal_capacity: u64 = 800; + +# Digits a shift by 60 bits can add, which is how far one shift goes. +const decimal_room: u64 = 19; + +# The largest integer every integer below which a float holds exactly. +const decimal_exact: u64 = 9007199254740992; + +# How far to shift a decimal whose point is a number of digits from where it should +# be, so the shift moves it by no more than that. +const decimal_shifts: u64[9] = [1, 3, 6, 9, 13, 16, 19, 23, 26]; + +# A number as decimal digits, each from 0 to 9, with the point `point` digits from +# the first, which may be before it or past the last. +struct decimal_digits { + var digits: u8[decimal_capacity + decimal_room]; + var count: u64; + var point: i64; + var truncated: bool; #! Whether a digit past those held was not zero. +} + +# The float nearest the number some digits write, which may hold a `.`, times ten +# to an exponent, or `nothing` where it is too large for one. +def decimal_digits::nearest(written: strview, exponent: i64): maybe { + # The first 19 digits after the leading zeros, and whether those after were all + # zero, which is all one exact multiplication needs. + var mantissa := 0u; + var held := 0u; + var scale := exponent; + var exact: bool = true; + var dotted: bool = false; + for byte in written { + if byte == '.' { + dotted = true; + continue; + } + if held == 0 && byte == '0' { + if dotted { + scale--; + } + continue; + } + if held < 19 { + mantissa = mantissa * 10 + byte.digit_value; + held++; + if dotted { + scale--; + } + continue; + } + if byte != '0' { + exact = false; + } + if !dotted { + scale++; + } + } + + if mantissa == 0 { + return 0.0; + } + if exact && mantissa <= decimal_exact && scale >= -22 && scale <= 22 { + val whole := mantissa as f64; + return scale < 0 ? whole / decimal_digits::power_of_ten(-scale) : whole * decimal_digits::power_of_ten(scale); + } + + var number: decimal_digits; + number.read(written, exponent); + return number.to_float(); +} + +# Reads the digits some text writes, without their leading zeros. +def decimal_digits::read(&mut this, written: strview, exponent: i64): void { + var dotted: bool = false; + for byte in written { + if byte == '.' { + dotted = true; + continue; + } + if this.count == 0 && byte == '0' { + if dotted { + this.point--; + } + continue; + } + + if !dotted { + this.point++; + } + if this.count < decimal_capacity { + this.digits[this.count] = byte.digit_value as u8; + this.count++; + } else if byte != '0' { + this.truncated = true; + } + } + + this.point += exponent; + this.trim(); +} + +# The float nearest the number, as Go's `strconv` finds it, or `nothing` where it +# is too large for one. +def decimal_digits::to_float(&mut this): maybe { + if this.count == 0 || this.point < -330 { + return 0.0; + } + if this.point > 310 { + return nothing{}; + } + + # Halve or double the number, counting how often, until it is in [0.5, 1). + var exponent: i64 = 0; + while this.point > 0 { + val by := decimal_digits::shift_for(this.point); + this.shift(-by); + exponent += by; + } + while this.point < 0 || (this.point == 0 && this.digits[0] < 5) { + val by := decimal_digits::shift_for(-this.point); + this.shift(by); + exponent -= by; + } + + # A float's significand is in [1, 2), and below the smallest exponent a float + # holds, the number is subnormal, with fewer bits. + exponent--; + if exponent < -1022 { + val by := -1022 - exponent; + this.shift(-by); + exponent += by; + } + if exponent > 1023 { + return nothing{}; + } + + # Its 53 bits, rounded, which may round up to one bit more. + this.shift(53); + var mantissa := this.rounded(); + if mantissa == decimal_exact { + mantissa = mantissa >> 1; + exponent++; + if exponent > 1023 { + return nothing{}; + } + } + return (mantissa as f64) * decimal_digits::power_of_two(exponent - 52); +} + +# Multiplies the number by two to a power, which divides it where the power is +# negative, sixty bits at a time. +def decimal_digits::shift(&mut this, by: i64): void { + if this.count == 0 { + return; + } + + var left := by; + while left > 60 { + this.shift_left(60); + left -= 60; + } + while left < -60 { + this.shift_right(60); + left += 60; + } + if left > 0 { + this.shift_left(left as u64); + } + if left < 0 { + this.shift_right((-left) as u64); + } +} + +# Multiplies the number by two to a power of at most 60, writing the digits from +# the last into the room past those held, then moving them to the front. +def decimal_digits::shift_left(&mut this, by: u64): void { + var read := this.count; + var write := this.count + decimal_room; + var carry := 0u; + while read > 0 { + read--; + carry += (this.digits[read] as u64) << by; + val quotient := carry / 10; + write--; + this.digits[write] = (carry - quotient * 10) as u8; + carry = quotient; + } + while carry > 0 { + val quotient := carry / 10; + write--; + this.digits[write] = (carry - quotient * 10) as u8; + carry = quotient; + } + + val made := this.count + decimal_room - write; + val first := (&mut this.digits) as *mut u8; + memcpy(first, first + write, made); + for k in decimal_capacity..made { + if this.digits[k] != 0 { + this.truncated = true; + } + } + + this.point += (made - this.count) as i64; + this.count = made < decimal_capacity ? made : decimal_capacity; + this.trim(); +} + +# Divides the number by two to a power of at most 60. +def decimal_digits::shift_right(&mut this, by: u64): void { + var read := 0u; + var write := 0u; + var carry := 0u; + + # Enough of the first digits to divide, counting zeros past the last as digits. + while (carry >> by) == 0 { + if read >= this.count { + if carry == 0 { + this.count = 0; + return; + } + while (carry >> by) == 0 { + carry = carry * 10; + read++; + } + break; + } + carry = carry * 10 + this.digits[read]; + read++; + } + + this.point -= (read as i64) - 1; + val mask := (1u << by) - 1; + while read < this.count { + val next := this.digits[read]; + this.digits[write] = (carry >> by) as u8; + write++; + carry = (carry & mask) * 10 + next; + read++; + } + while carry > 0 { + val digit := carry >> by; + carry = (carry & mask) * 10; + if write < decimal_capacity { + this.digits[write] = digit as u8; + write++; + } else if digit > 0 { + this.truncated = true; + } + } + + this.count = write; + this.trim(); +} + +# The integer part of the number, rounded by the digits after the point, halfway +# going to an even integer. +def decimal_digits::rounded(&this): u64 { + if this.point > 20 { + return 0xFFFFFFFFFFFFFFFF; + } + + var whole := 0u; + var at: i64 = 0; + while at < this.point && at < (this.count as i64) { + whole = whole * 10 + this.digits[at as u64]; + at++; + } + while at < this.point { + whole = whole * 10; + at++; + } + if this.rounds_up() { + whole++; + } + return whole; +} + +# Whether the digits after the point round the integer part up: past halfway, or +# exactly halfway with an odd integer part, or halfway with digits left out past it. +def decimal_digits::rounds_up(&this): bool { + if this.point < 0 || this.point >= (this.count as i64) { + return false; + } + + val at := this.point as u64; + if this.digits[at] == 5 && at + 1 == this.count { + if this.truncated { + return true; + } + return at > 0 && this.digits[at - 1] % 2 == 1; + } + return this.digits[at] >= 5; +} + +# Drops the zeros after the last digit that is not one. +def decimal_digits::trim(&mut this): void { + while this.count > 0 && this.digits[this.count - 1] == 0 { + this.count--; + } + if this.count == 0 { + this.point = 0; + } +} + +def decimal_digits::shift_for(digits: i64): i64 { + return digits < 9 ? decimal_shifts[digits as u64] as i64 : 27; +} + +# Ten to a power from 0 to 22, which a float holds exactly. +def decimal_digits::power_of_ten(power: i64): f64 { + var made: f64 = 1; + for _ in 0..power { + made *= 10; + } + return made; +} + +# Two to a power from -1074 to 1023, which a float holds exactly. +def decimal_digits::power_of_two(power: i64): f64 { + var made: f64 = 1; + var left := power; + while left > 0 { + made *= 2; + left--; + } + while left < 0 { + made *= 0.5; + left++; + } + return made; +} diff --git a/core/containers/pair.sakura b/core/containers/pair.sakura new file mode 100644 index 00000000..413e634d --- /dev/null +++ b/core/containers/pair.sakura @@ -0,0 +1,18 @@ +#! @file pair.sakura +#! @author John Christman (sorakatadzuma@gmail.com) +#! @copyright Malunal Studios, LLC. +#! @license MIT +#! +#! Contains `pair`, two values kept together, as `enumerate` gives each element +#! with its index and `zip` the elements of two iterators side by side. + +module core; + + +#! Two values kept together, each named for where it stands. +#! @tparam A The type of the first. +#! @tparam B The type of the second. +pub struct pair { + pub var first: A; #! The first value. + pub var second: B; #! The second value. +} diff --git a/core/containers/slice.sakura b/core/containers/slice.sakura new file mode 100644 index 00000000..a1b4eaff --- /dev/null +++ b/core/containers/slice.sakura @@ -0,0 +1,249 @@ +#! @file slice.sakura +#! @author John Christman (sorakatadzuma@gmail.com) +#! @copyright Malunal Studios, LLC. +#! @license MIT +#! +#! Contains the methods of `slice`, a writable view over elements that something +#! else holds. It is the counterpart of `span`, which only reads, and lends one +#! of itself wherever a reader is wanted. +#! +#! `slice` is among the types the syntax makes, which the compiler declares +#! itself. A slice owns nothing: writing through it writes the elements where +#! they already live, and closing whatever holds them leaves the slice pointing +#! at memory that is no longer there, so keep a slice no longer than the thing +#! it views. It converts to a `span` wherever a reader is wanted, which drops +#! the right to write. +module core; + + +#! The number of elements the view covers. +#! @param this The slice to measure. +#! @returns How many elements it covers, starting at `data`. +pub val slice::length: u64 { + get => this._len; +} + +#! The first element the view covers, which is `null` for an empty view. +#! @param this The slice to read the address of. +#! @returns Where the elements begin. +pub val slice::data: *mut T { + get => this._dat; +} + +#! Makes a writable view over a run of elements. +#! @param data The first element, or `null` for a view over nothing. +#! @param length The number of elements the view covers. +#! @returns The view, which covers nothing where `data` is `null`. +#! @remarks A fixed array holds its elements where it stands, so a writable view +#! over a `var` one is `array[0:N]`. +pub def slice::over(data: *mut T, length: u64): slice { + return data == null + ? slice { _dat = null, _len = 0 } + : slice { _dat = data, _len = length }; +} + +#! Makes a view over nothing, which is the zero value of a slice. +#! @returns A view of no elements. +pub def slice::empty(): slice { + return slice { _dat = null, _len = 0 }; +} + +#! Tells whether the view covers no elements. +#! @param this The slice to test. +#! @returns Whether its length is zero. +pub def slice::is_empty(&this): bool { + return this._len == 0; +} + +#! Reads the element at an index, which `slice[index]` does without calling it. +#! @param this The slice to read. +#! @param index The index of the element, below `length`, past which a checked +#! program stops. +#! @returns The element, which refers into whatever holds the elements. +pub def slice::at(&this, index: u64): &T { + # Indexed as a view, it is checked as `slice[index]` is, which the compiler does + # itself rather than calling this. + val whole: slice = this; + return &whole[index]; +} + +#! Reaches the element at an index to write it, which `slice[index] = x` does +#! without calling it. +#! @param this The slice to write through. +#! @param index The index of the element, below `length`, past which a checked +#! program stops. +#! @returns The element, which refers into whatever holds the elements. +pub def slice::at(&mut this, index: u64): &mut T { + var whole: slice = this; + return &mut whole[index]; +} + +#! Gets the element at an index, if the slice covers one there. +#! @param this The slice to read. +#! @param index The index of the element. +#! @returns Maybe the element, which refers into whatever holds the elements; +#! otherwise, `nothing`. +pub def slice::get(&this, index: u64): maybe<&T> { + # Reached as the view's element, whose check the test answers. + val whole: slice = this; + return index < this._len ? &whole[index] : nothing {}; +} + +#! Gets the element at an index to write it, if the slice covers one there. +#! @param this The slice to write through. +#! @param index The index of the element. +#! @returns Maybe the element, which refers into whatever holds the elements; +#! otherwise, `nothing`. +pub def slice::get(&mut this, index: u64): maybe<&mut T> { + var whole: slice = this; + return index < this._len ? &mut whole[index] : nothing {}; +} + +#! Lends a writable view of the same elements, which is the slice itself. +#! @param this The slice to lend. +#! @returns A copy of the slice, covering the same elements. +pub def slice::slice(&mut this): slice { + return this; +} + +#! Walks the elements a slice covers, giving a reference that reads each in +#! turn, which is what `iter(&this)` lends and `for x` and `for &x` walk. +pub struct slice::cursor : sized_iterator<&T>, backward_iterator<&T> { + var _at: *mut T; + var _left: u64; +} + +#! Gives the next element the slice covers. +#! @param this The cursor to advance. +#! @returns Maybe a reference to the next element; otherwise, `nothing`. +pub def slice::cursor::next(&mut this): maybe<&T> { + if this._left == 0 { + return nothing {}; + } + + val here := this._at; + this._at = here + 1; + this._left = this._left - 1; + # Reached as the one element of a view, which is never over null and whose + # index is known, so reaching it checks nothing. + return &span:: { _dat = here as *T, _len = 1 }[0]; +} + +#! How many elements the cursor has left to give. +#! @param this The cursor. +#! @returns How many. +pub def slice::cursor::remaining(&this): u64 { + return this._left; +} + +#! Gives the last element the cursor has left, from the far end of the slice. +#! @param this The cursor to advance from its far end. +#! @returns Maybe a reference to the element; otherwise, `nothing`. +pub def slice::cursor::next_back(&mut this): maybe<&T> { + if this._left == 0 { + return nothing {}; + } + + this._left = this._left - 1; + return &span:: { _dat = (this._at + this._left) as *T, _len = 1 }[0]; +} + +#! Walks the elements a slice covers, giving a reference that writes each in +#! turn, which is what `iter(&mut this)` lends and `for &mut x` walks. +pub struct slice::mut_cursor : sized_iterator<&mut T>, backward_iterator<&mut T> { + var _at: *mut T; + var _left: u64; +} + +#! Gives the next element the slice covers, to be written. +#! @param this The cursor to advance. +#! @returns Maybe a reference to the next element; otherwise, `nothing`. +pub def slice::mut_cursor::next(&mut this): maybe<&mut T> { + if this._left == 0 { + return nothing {}; + } + + val here := this._at; + this._at = here + 1; + this._left = this._left - 1; + return &mut here[0]; +} + +#! How many elements the cursor has left to give. +#! @param this The cursor. +#! @returns How many. +pub def slice::mut_cursor::remaining(&this): u64 { + return this._left; +} + +#! Gives the last element the cursor has left, from the far end of the slice, +#! to be written. +#! @param this The cursor to advance from its far end. +#! @returns Maybe a reference to the element; otherwise, `nothing`. +pub def slice::mut_cursor::next_back(&mut this): maybe<&mut T> { + if this._left == 0 { + return nothing {}; + } + + this._left = this._left - 1; + return &mut this._at[this._left]; +} + +#! Lends a cursor that reads the elements the slice covers. +#! @param this The slice to walk. +#! @returns The cursor, which refers into whatever holds the elements. +pub def slice::iter(&this): slice::cursor { + return slice::::cursor { _at = this._dat, _left = this._len }; +} + +#! Lends a cursor that writes the elements the slice covers where they are. +#! @param this The slice to walk. +#! @returns The cursor, which refers into whatever holds the elements. +pub def slice::iter(&mut this): slice::mut_cursor { + return slice::::mut_cursor { _at = this._dat, _left = this._len }; +} + +#! Lends a read-only view of the same elements. +#! @param this The slice to lend. +#! @returns A `span` over the elements this one covers. +#! @remarks A slice converts to a span on its own wherever one is wanted, so +#! this is only written where the conversion needs to be named. +pub def slice::view(&this): span { + # A slice is never over null while it covers anything, so the view is made as + # it is. + return span:: { _dat = this._dat as *T, _len = this._len }; +} + +#! Narrows the view to a run of the elements it already covers. +#! @param this The slice to narrow. +#! @param from The index the narrower view starts at, from `0` to `length`. +#! @param length The number of elements it covers. +#! @returns Maybe the narrower view if this one covers all of it; otherwise, +#! `nothing`. +pub def slice::sub(&this, from: u64, length: u64): maybe> { + if from > this._len || length > this._len - from { + return nothing {}; + } + + return length == 0 + ? slice::::empty() + : slice::::over(this._dat + from, length); +} + +#! Compares one view to another for equality. +#! @param this The slice to compare against. +#! @param other The slice to compare with. +#! @returns Whether both cover the same number of equal elements, in the same +#! order, which is what comparing the spans they lend answers. +pub def slice::equals(&this, other: &slice): bool { + val mine := this.view(); + val yours := other.view(); + return mine.equals(&yours); +} + +#! Hashes the view provided. +#! @param this The slice to hash. +#! @returns The hash code of the view, which it shares with the span it lends. +pub def slice::hash(&this): u64 { + return this.view().hash(); +} diff --git a/core/containers/sort.sakura b/core/containers/sort.sakura new file mode 100644 index 00000000..8645fffb --- /dev/null +++ b/core/containers/sort.sakura @@ -0,0 +1,199 @@ +#! @file sort.sakura +#! @author John Christman (sorakatadzuma@gmail.com) +#! @copyright Malunal Studios, LLC. +#! @license MIT +#! +#! Contains the sorts of slices and vectors: `sort`, by the order `<` gives, and +#! `sort_by`, by a function saying whether one element comes before another. +#! Both are stable, keeping elements neither comes before in the order they were +#! in, so what is sorted comes out the same however many times it is sorted. +module core; + + +#! Puts the elements in order, least first, by the order `<` gives. +#! @param this The slice to sort, whose elements are `ordered`. +#! @remarks The sort is stable: elements equal to each other keep the order they +#! were in. Runs of a few are sorted by insertion and then merged, which +#! takes memory for as many elements again while it sorts. Elements +#! are moved byte for byte, so nothing is closed or copied. +pub def slice::sort(&mut this): void { + sort_elements::>(this._dat, this._len, &natural_order:: {}); +} + +#! Puts the elements in an order a function gives. +#! @param this The slice to sort. +#! @param before Whether one element comes before another, which holds of no +#! element and itself, as `<` does. +#! @remarks The sort is stable, as `sort` is: elements neither comes before keep +#! the order they were in. +pub def slice::sort_by(&mut this, before: def(&T, &T): bool): void { + sort_elements::>(this._dat, this._len, &given_order:: { before_of = before }); +} + +#! Puts the elements in order, least first, by the order `<` gives. +#! @param this The vector to sort, whose elements are `ordered`. +#! @remarks The sort is stable, as a slice's `sort` is. +pub def vector::sort(&mut this): void { + var whole := this.slice(); + whole.sort(); +} + +#! Puts the elements in an order a function gives. +#! @param this The vector to sort. +#! @param before Whether one element comes before another, which holds of no +#! element and itself, as `<` does. +#! @remarks The sort is stable, as a slice's `sort_by` is. +pub def vector::sort_by(&mut this, before: def(&T, &T): bool): void { + var whole := this.slice(); + whole.sort_by(before); +} + +# What a sort orders elements by: whether one comes before another. +trait sort_order { + def before(&this, first: &T, second: &T): bool; +} + +# The order `<` gives. +struct natural_order : sort_order {} + +def natural_order::before(&this, first: &T, second: &T): bool { + if const !(T is ordered) { + compile_error("`sort` puts elements in the order `<` gives, so they are `ordered`. `sort_by` takes an order of its own."); + } + return first < second; +} + +# The order a function gives. +struct given_order : sort_order { + var before_of: def(&T, &T): bool; +} + +def given_order::before(&this, first: &T, second: &T): bool { + return this.before_of(first, second); +} + +# How many elements a run sorted by insertion holds, before runs are merged. +const sort_run: u64 = 16; + +# Sorts elements in place, stably: runs of a few by insertion, then each pair of +# runs merged, back and forth between the elements and as many slots again. +def sort_elements(data: *mut T, count: u64, order: &O): void where O: sort_order { + return if count < 2; + + var at: u64 = 0; + while at < count { + insert_sorted::(data + at, count - at < sort_run ? count - at : sort_run, order); + at += sort_run; + } + return if count <= sort_run; + + # The spare slots hold the elements a while, so they are cleared where the + # elements close, as `acquire` clears them. + val spare := acquire::(nothing {}, count); + var from := data; + var to := spare; + var width := sort_run; + while width < count { + var low: u64 = 0; + while low < count { + val middle := low + width < count ? low + width : count; + val high := low + 2 * width < count ? low + 2 * width : count; + merge_runs::(from, low, middle, high, to, order); + low = high; + } + val swap := from; + from = to; + to = swap; + width *= 2; + } + + if from != data { + move_elements::(data, from, count); + } + dispose::(nothing {}, spare, count); +} + +# Sorts a few elements in place by insertion, which keeps equal ones in order. +# Where each goes is found while it is still in its place, so the order is only +# asked about elements in the block: one held aside in a local would be put on +# the heap each time, where the order is a function's. +def insert_sorted(data: *mut T, count: u64, order: &O): void where O: sort_order { + if const T is closeable { + # What closes is held aside byte for byte, in a slot of its own, so nothing is + # closed or copied as it moves. + val held := acquire::(nothing {}, 1); + for i in 1..count { + val j := insertion_place::(data, i, order); + continue if j == i; + move_elements::(held, data + i, 1); + var k := i; + while k > j { + move_elements::(data + k, data + k - 1, 1); + k--; + } + move_elements::(data + j, held, 1); + } + dispose::(nothing {}, held, 1); + return; + } + + for i in 1..count { + val j := insertion_place::(data, i, order); + continue if j == i; + val held: T = data[i]; + var k := i; + while k > j { + data[k] = data[k - 1]; + k--; + } + data[j] = held; + } +} + +# Where an element goes among those before it, which are in order: after the +# last it does not come before. +def insertion_place(data: *mut T, at: u64, order: &O): u64 where O: sort_order { + var j := at; + while j > 0 && order.before(&data[at], &data[j - 1]) { + j--; + } + return j; +} + +# Merges two runs next to each other, each in order, into the same places of +# another block, taking from the first where neither comes before the other. +def merge_runs(from: *mut T, low: u64, middle: u64, high: u64, to: *mut T, order: &O): void where O: sort_order { + var left := low; + var right := middle; + var out := low; + while left < middle && right < high { + if order.before(&from[right], &from[left]) { + move_elements::(to + out, from + right, 1); + right++; + } else { + move_elements::(to + out, from + left, 1); + left++; + } + out++; + } + + if left < middle { + move_elements::(to + out, from + left, middle - left); + out += middle - left; + } + if right < high { + move_elements::(to + out, from + right, high - right); + } +} + +# Moves elements byte for byte, which neither closes what they land on nor copies +# what they hold, as a sort only puts them in other places. +def move_elements(to: *mut T, from: *mut T, count: u64): void { + if const !(T is closeable) { + for i in 0..count { + to[i] = from[i]; + } + return; + } + memcpy(to as *mut u8, from as *u8, bytes_of::(count)); +} diff --git a/core/containers/span.sakura b/core/containers/span.sakura new file mode 100644 index 00000000..12c707ef --- /dev/null +++ b/core/containers/span.sakura @@ -0,0 +1,373 @@ +#! @file span.sakura +#! @author John Christman (sorakatadzuma@gmail.com) +#! @copyright Malunal Studios, LLC. +#! @license MIT +#! +#! Contains the methods of `span`, a read-only view over elements that something +#! else holds, which read and narrow such a view. The writable counterpart is +#! `slice`, which lends a span of itself. +#! +#! `span` is among the types the syntax makes, which the compiler declares +#! itself, as `a[:]` makes one: where the elements begin, and how many there +#! are. A span owns nothing and writes nothing. It is not `owning`, and closing +#! whatever holds the elements leaves the span pointing at memory that is no +#! longer there, the same way a raw pointer does, so keep a span no longer than +#! the thing it views. A view only reads, so it can be taken of anything, +#! including memory that cannot be written such as the text of a literal. +module core; + + +#! The number of elements the view covers. +#! @param this The span to measure. +#! @returns How many elements it reads, starting at `data`. +@inline +pub val span::length: u64 { + get => this._len; +} + +#! The first element the view covers, which is `null` for an empty view. +#! @param this The span to read the address of. +#! @returns Where the elements begin. +@inline +pub val span::data: *T { + get => this._dat; +} + +#! Makes a view over a run of elements. +#! @param data The first element, or `null` for a view over nothing. +#! @param length The number of elements the view covers. +#! @returns The view, which covers nothing where `data` is `null`. +#! @remarks A fixed array holds its elements where it stands, so a view over one +#! is `array[0:N]`, or `span::::over((&array) as *T, N)` written +#! out. +pub def span::over(data: *T, length: u64): span { + return data == null + ? span { _dat = null, _len = 0 } + : span { _dat = data, _len = length }; +} + +#! Makes a view over nothing, which is the zero value of a span. +#! @returns A view of no elements. +pub def span::empty(): span { + return span { _dat = null, _len = 0 }; +} + +#! Tells whether the view covers no elements. +#! @param this The span to test. +#! @returns Whether its length is zero. +pub def span::is_empty(&this): bool { + return this._len == 0; +} + +#! Reads the element at an index, which `span[index]` does without calling it. +#! @param this The span to read. +#! @param index The index of the element, below `length`. +#! @returns The element, which refers into whatever holds the elements. +#! @remarks It is what makes a span `indexable`, so generic code bounded by that +#! trait reads a view as it reads any other container. An index past +#! the end stops a checked program, as `span[index]` does. +pub def span::at(&this, index: u64): &T { + # Indexed as a view, it is checked as `span[index]` is, which the compiler does + # itself rather than calling this. + val whole: span = this; + return &whole[index]; +} + +#! Lends a view of the same elements, which is the span itself. +#! @param this The span to lend. +#! @returns A copy of the span, covering the same elements. +pub def span::view(&this): span { + return this; +} + +#! Walks the elements a view covers, giving a reference to each in turn, which +#! is what `iter` lends and `for` walks. +pub struct span::cursor : sized_iterator<&T>, backward_iterator<&T> { + var _at: *T; + var _left: u64; +} + +#! Gives the next element the view covers. +#! @param this The cursor to advance. +#! @returns Maybe a reference to the next element; otherwise, `nothing`. +pub def span::cursor::next(&mut this): maybe<&T> { + if this._left == 0 { + return nothing {}; + } + + val here := this._at; + this._at = here + 1; + this._left = this._left - 1; + # Reached as the one element of a view, which is never over null and whose + # index is known, so reaching it checks nothing. + return &span:: { _dat = here, _len = 1 }[0]; +} + +#! How many elements the cursor has left to give. +#! @param this The cursor. +#! @returns How many. +pub def span::cursor::remaining(&this): u64 { + return this._left; +} + +#! Gives the last element the cursor has left, from the far end of the view. +#! @param this The cursor to advance from its far end. +#! @returns Maybe a reference to the element; otherwise, `nothing`. +pub def span::cursor::next_back(&mut this): maybe<&T> { + if this._left == 0 { + return nothing {}; + } + + this._left = this._left - 1; + return &span:: { _dat = this._at + this._left, _len = 1 }[0]; +} + +#! Lends a cursor over the elements the view covers, which `for` walks. +#! @param this The span to walk. +#! @returns The cursor, which refers into whatever holds the elements. +pub def span::iter(&this): span::cursor { + return span::::cursor { _at = this._dat, _left = this._len }; +} + +#! Gets the element at an index, if the view covers one there. +#! @param this The span to read. +#! @param index The index of the element, below `length`. +#! @returns Maybe the element if the index is one it covers; otherwise, +#! `nothing`. +#! @remarks What it gives refers into whatever holds the elements, so it is only +#! good for as long as the view is. +pub def span::get(&this, index: u64): maybe<&T> { + # Reached as the view's element, whose check the test answers. + return index < this._len + ? &span:: { _dat = this._dat, _len = this._len }[index] + : nothing {}; +} + +#! Gets the first element the view covers. +#! @param this The span to read. +#! @returns Maybe the first element; otherwise, `nothing` for an empty view. +pub def span::first(&this): maybe<&T> { + return this.get(0); +} + +#! Gets the last element the view covers. +#! @param this The span to read. +#! @returns Maybe the last element; otherwise, `nothing` for an empty view. +pub def span::last(&this): maybe<&T> { + return this._len == 0 + ? nothing {} + : this.get(this._len - 1); +} + +#! Narrows the view to a run of the elements it already covers. +#! @param this The span to narrow. +#! @param from The index the narrower view starts at, from `0` to `length`. +#! @param length The number of elements it covers. +#! @returns Maybe the narrower view if this one covers all of it; otherwise, +#! `nothing`. +pub def span::sub(&this, from: u64, length: u64): maybe> { + if from > this._len || length > this._len - from { + return nothing {}; + } + + return length == 0 + ? span::::empty() + : span::::over(this._dat + from, length); +} + +#! Finds where the view first covers an element equal to the one given. +#! @param this The span to search. +#! @param elem The element to look for. +#! @returns Maybe the index of the first equal element; otherwise, `nothing`. +#! @remarks Elements are compared with `equals`, so they are `equatable`. Bytes, +#! as text is, are searched eight or sixteen at a time. +pub def span::index_of(&this, elem: &T): maybe { + if const T is integer && size_of::() == 1 { + val at := find_byte(this._dat as *u8, 0, this._len, *(elem as *u8)); + return nothing {} if at == this._len; + return at; + } + + for index in 0..this._len { + if equals::(&this._dat[index], elem) { + return index; + } + } + + return nothing {}; +} + +#! Finds where the view last covers an element equal to the one given. +#! @param this The span to search. +#! @param elem The element to look for. +#! @returns Maybe the index of the last equal element; otherwise, `nothing`. +#! @remarks Elements are compared with `equals`, so they are `equatable`. Bytes, +#! as text is, are searched eight at a time. +pub def span::last_index_of(&this, elem: &T): maybe { + if const T is integer && size_of::() == 1 { + val at := find_last_byte(this._dat as *u8, 0, this._len, *(elem as *u8)); + return nothing {} if at == this._len; + return at; + } + + var index := this._len; + while index > 0 { + index--; + if equals::(&this._dat[index], elem) { + return index; + } + } + + return nothing {}; +} + +#! Counts the elements of the view equal to the one given. +#! @param this The span to search. +#! @param elem The element to count. +#! @returns How many equal it. +#! @remarks Elements are compared with `equals`, so they are `equatable`. Bytes, +#! as text is, are counted eight at a time, as the lines of text are +#! by counting `'\n'`. +pub def span::count_of(&this, elem: &T): u64 { + if const T is integer && size_of::() == 1 { + return count_byte(this._dat as *u8, 0, this._len, *(elem as *u8)); + } + + var count: u64 = 0; + for index in 0..this._len { + if equals::(&this._dat[index], elem) { + count++; + } + } + return count; +} + +#! Tells whether the view covers an element equal to the one given. +#! @param this The span to search. +#! @param elem The element to look for. +#! @returns Whether any element equals it. +pub def span::contains(&this, elem: &T): bool { + return this.index_of(elem) is some; +} + +#! Finds where a value goes among elements kept in order: the first element that +#! is not less than it. +#! @param this The span to search, whose elements are in the order `<` gives. +#! @param value The value to look for. +#! @returns The index of the first element not less than the value, or the +#! length where every element is less. +#! @remarks The elements are `ordered`, and halved until one is found, so a view +#! out of order gives an index that means nothing. +pub def span::lower_bound(&this, value: &T): u64 { + if const !(T is ordered) { + compile_error("`lower_bound` searches by the order `<` gives, so the elements are `ordered`."); + } + + var low: u64 = 0; + var high: u64 = this._len; + while low < high { + val middle := low + (high - low) / 2; + if this._dat[middle] < value { + low = middle + 1; + } else { + high = middle; + } + } + return low; +} + +#! Finds where a value goes after those equal to it among elements kept in +#! order: the first element greater than it. +#! @param this The span to search, whose elements are in the order `<` gives. +#! @param value The value to look for. +#! @returns The index of the first element greater than the value, or the length +#! where none is. +#! @remarks The elements are `ordered`, and halved until one is found, so a view +#! out of order gives an index that means nothing. +pub def span::upper_bound(&this, value: &T): u64 { + if const !(T is ordered) { + compile_error("`upper_bound` searches by the order `<` gives, so the elements are `ordered`."); + } + + var low: u64 = 0; + var high: u64 = this._len; + while low < high { + val middle := low + (high - low) / 2; + if value < this._dat[middle] { + high = middle; + } else { + low = middle + 1; + } + } + return low; +} + +#! Finds where elements a test holds of give way to those it does not, among +#! elements kept so that every one it holds of comes first. +#! @param this The span to search. +#! @param held The test, which holds of the elements before the index given +#! and of none from it on. +#! @returns The index of the first element the test does not hold of, or the +#! length where it holds of every one. +#! @remarks Elements are halved until it is found, so the test is called about +#! `log2(length)` times. It finds by a part of each element, such as an +#! offset, where `lower_bound` finds by the whole. +pub def span::partition_point(&this, held: def(&T): bool): u64 { + var low: u64 = 0; + var high: u64 = this._len; + while low < high { + val middle := low + (high - low) / 2; + if held(&this._dat[middle]) { + low = middle + 1; + } else { + high = middle; + } + } + return low; +} + +#! Compares one view to another for equality. +#! @param this The span to compare against. +#! @param other The span to compare with. +#! @returns Whether both cover the same number of equal elements, in the same +#! order. Two views of the same elements are equal, and so are two +#! empty views. +pub def span::equals(&this, other: &span): bool { + if this._len != other._len { + return false; + } + + if this._dat == other._dat || this._len == 0 { + return true; + } + + # Integers are equal where their bytes are, which are compared a word at a time. + if const T is integer { + return memcmp(this._dat as *u8, other._dat as *u8, bytes_of::(this._len)) == 0; + } + + for index in 0..this._len { + if !equals::(&this._dat[index], &other._dat[index]) { + return false; + } + } + + return true; +} + +#! Hashes the view provided. +#! @param this The span to hash. +#! @returns The hash code of the view, which spans of equal elements share. +#! @remarks Elements are hashed by their `hash`, so they are `hashable`. +pub def span::hash(&this): u64 { + # Integers hash as their bytes, a word at a time, which equal ones share. + if const T is integer { + return hash_bytes(this._dat as *u8, bytes_of::(this._len)); + } + + var code := this._len; + for index in 0..this._len { + code = mix(code, hash(this._dat[index])); + } + return code; +} diff --git a/core/containers/string.sakura b/core/containers/string.sakura new file mode 100644 index 00000000..737915ec --- /dev/null +++ b/core/containers/string.sakura @@ -0,0 +1,416 @@ +#! @file string.sakura +#! @author John Christman (sorakatadzuma@gmail.com) +#! @copyright Malunal Studios, LLC. +#! @license MIT +#! +#! Contains the methods of `string`, which owns the bytes of text it holds, and +#! the functions that build one and give it back. +#! +#! `string` is among the types the syntax makes, which the compiler declares +#! itself, since interpolation, as `$"{count} items"`, builds one. A string is +#! `owning`, so the memory goes back where its scope ends. Text that is only read +#! is a `strview`, which owns nothing: a literal such as `"hello"` is one, and so +#! is what `view` gives. A string whose allocator is `nothing` holds memory from +#! `raw_allocate`, and one made with an allocator gives its memory back to that +#! allocator. Either way the zero value of a string holds no memory, so closing +#! one that was never built does nothing. +module core; + + +#! The number of bytes the string holds. +#! @param this The string to measure. +#! @returns How many bytes of text it holds, which is no more than its capacity. +pub val string::length: u64 { + get => this._len; +} + +#! The number of bytes the string has room for. +#! @param this The string to measure. +#! @returns How many bytes it can hold before it has to grow. +pub val string::capacity: u64 { + get => this._cap; +} + +#! The allocator the string takes its memory from, or `nothing` where it takes +#! it from `raw_allocate`, so what is made from it can take memory alike. +#! @param this The string. +#! @returns The allocator, or `nothing`. +pub val string::alloc: maybe<&mut allocator> { + get => this._alc; +} + +#! Whether the string holds no text. +#! @param this The string to check. +#! @returns Whether its length is zero. +pub val string::is_empty: bool { + get => this._len == 0; +} + +#! Whether the string has no room left, so the next byte added makes it grow. +#! @param this The string to check. +#! @returns Whether its length is its capacity. +pub val string::is_full: bool { + get => this._len == this._cap; +} + +#! Makes a string that holds no text yet. +#! @param alloc An optional allocator for the string to take memory from. A +#! string given none takes it from `raw_allocate`. +#! @returns The empty string, which holds no memory until it is written to. +pub def string::new(alloc: maybe<&mut allocator>): string { + return string { _alc = alloc, _dat = null, _len = 0, _cap = 0 }; +} + +#! Makes a string holding a copy of the text given. +#! @param text The text to copy, such as a literal or a view of one. +#! @param alloc An optional allocator for the string to take memory from. +#! @returns The string, which holds no text where there was no memory for it. +#! @remarks An allocator that gives no memory stops the program. +pub def string::from(text: strview, alloc: maybe<&mut allocator>): string { + var made := string::new(alloc); + made.append(text); + return made; +} + +#! Views the text the string holds, without copying it. +#! @param this The string to view. +#! @returns A view of its bytes, which is only good until the string grows, +#! shrinks, or closes. +pub def string::view(&this): strview { + return strview::over(this._dat as *u8, this._len); +} + +#! Lends a writable view of the bytes the string holds, without copying them. +#! @param this The string to view. +#! @returns A view of its bytes, which writes them where they are, and is only +#! good until the string grows, shrinks, or closes. +pub def string::slice(&mut this): slice { + return slice::::over(this._dat, this._len); +} + +#! Reads the byte at an index, which `s[index]` calls. +#! @param this The string to read. +#! @param index The index of the byte, below `length`, past which a checked +#! program stops. +#! @returns The byte, which is only good until the string grows, shrinks, or +#! closes. +pub def string::at(&this, index: u64): &u8 { + # Indexed as a view of the bytes, it is checked as a view's index is. + return &span:: { _dat = this._dat, _len = this._len }[index]; +} + +#! Reaches the byte at an index to write it, which `s[index] = b` calls. +#! @param this The string to write. +#! @param index The index of the byte, below `length`, past which a checked +#! program stops. +#! @returns The byte, which is only good until the string grows, shrinks, or +#! closes. +pub def string::at(&mut this, index: u64): &mut u8 { + return &mut slice:: { _dat = this._dat, _len = this._len }[index]; +} + +#! Gets the byte at an index, if the string holds one there, for an index that +#! may be past the end in a program that is right. +#! @param this The string to read. +#! @param index The index of the byte. +#! @returns Maybe the byte, which is only good until the string grows, shrinks, +#! or closes; otherwise, `nothing`. +pub def string::get(&this, index: u64): maybe<&u8> { + # Reached as a view's byte, whose check the test answers. + return index < this._len + ? &span:: { _dat = this._dat, _len = this._len }[index] + : nothing {}; +} + +#! Gets the byte at an index to write it, if the string holds one there. +#! @param this The string to write. +#! @param index The index of the byte. +#! @returns Maybe the byte, which is only good until the string grows, shrinks, +#! or closes; otherwise, `nothing`. +pub def string::get(&mut this, index: u64): maybe<&mut u8> { + return index < this._len + ? &mut slice:: { _dat = this._dat, _len = this._len }[index] + : nothing {}; +} + +#! Makes room for at least a number of bytes, keeping the text it holds. +#! @param this The string to make room in. +#! @param capacity The number of bytes it should have room for. +#! @remarks A string already that large is left as it is, and an allocator that +#! gives no more memory stops the program. +pub def string::reserve(&mut this, capacity: u64): void { + if capacity <= this._cap { + return; + } + + this.recapacity(capacity); +} + +#! Makes the string hold a number of bytes, adding zero bytes after the last or +#! removing those past it, as a reader filling the room it made does. +#! @param this The string to resize. +#! @param length How many bytes it holds after. +#! @remarks The memory is kept where it shrinks, and an allocator that gives no +#! more memory stops the program where it grows. +pub def string::resize(&mut this, length: u64): void { + if length > this._cap { + this.grow(length); + } + if length > this._len { + memset(this._dat + this._len, 0, length - this._len); + } + this._len = length; +} + +#! Adds a byte after the last. +#! @param this The string to append to. +#! @param byte The byte to append. +#! @remarks An allocator that gives no more memory stops the program. +pub def string::push(&mut this, byte: u8): void { + if this._len == this._cap { + this.grow(this._len + 1); + } + + this._dat[this._len] = byte; + this._len++; +} + +#! Adds the bytes of some text after the last. +#! @param this The string to append to. +#! @param text The text to append, which may view this string's own bytes. +#! @remarks An allocator that gives no more memory stops the program. +pub def string::append(&mut this, text: strview): void { + val count := text.length; + if count == 0 { + return; + } + + if this._len + count > this._cap { + this.grow(this._len + count); + } + + memcpy(this._dat + this._len, text.data, count); + this._len += count; +} + +#! Removes every byte, keeping the memory the string holds them in. +#! @param this The string to empty. +pub def string::clear(&mut this): void { + this._len = 0; +} + +#! Gives back the memory the string holds, leaving it empty. +#! @param this The string to close out. +pub def string::close(&mut this): void { + if this._dat == null { + return; + } + + match this._alc { + some(owner) => owner.dispose(this._dat, this._cap); + none => raw_release(this._dat); + } + + this._dat = null; + this._len = 0; + this._cap = 0; +} + +#! Compares one string to another for equality. +#! @param this The string to compare against. +#! @param other The string to compare with. +#! @returns Whether both hold the same bytes, in the same order. +pub def string::equals(&this, other: &string): bool { + return this.view().equals(&other.view()); +} + +#! Compares one string with another, by their bytes and then by their length. +#! @param this The string to compare against. +#! @param other The string to compare with. +#! @retval -1 Where this string orders before the other. +#! @retval 0 Where they hold the same bytes. +#! @retval 1 Where this string orders after the other. +pub def string::compare(&this, other: &string): i64 { + return this.view().compare(other.view()); +} + +#! What `iter(&this)` lends, which reads the bytes where the string holds them. +pub type string::cursor = span::cursor; + +#! What `iter(&mut this)` lends, which writes the bytes where the string holds +#! them. +pub type string::mut_cursor = slice::mut_cursor; + +#! Lends a cursor that reads the bytes, in order, which `for byte in s` walks. +#! @param this The string to walk. +#! @returns The cursor, which is only good until the string grows, shrinks, or +#! closes. +pub def string::iter(&this): span::cursor { + return this.view().iter(); +} + +#! Lends a cursor that writes the bytes where they are, which `for &mut byte in +#! s` walks. +#! @param this The string to walk. +#! @returns The cursor, which is only good until the string grows, shrinks, or +#! closes. +pub def string::iter(&mut this): slice::mut_cursor { + var whole := this.slice(); + return whole.iter(); +} + +#! Hashes the string provided. +#! @param this The string to hash. +#! @returns The hash code of the text it holds, which equal strings share. +pub def string::hash(&this): u64 { + return this.view().hash(); +} + +#! Builds a string holding the same text as another, with its allocator. +#! @param other The string to copy text from. +#! @returns The copy, which owns memory of its own. +pub def string::copy_of(other: &string): string { + return string::from(other.view(), other._alc); +} + +#! Builds a string holding the text of another, leaving the other empty. +#! @param other The string to move text from, which holds nothing after. +#! @returns The moved string, which takes the memory and the allocator with it. +#! @remarks Nothing is copied: the memory moves as it stands, and the other is +#! left empty rather than dead, so closing it afterwards is harmless. +pub def string::move_of(other: &mut string): string { + var made: string = string { + _alc = other._alc, + _dat = other._dat, + _len = other._len, + _cap = other._cap + }; + + other._dat = null; + other._len = 0; + other._cap = 0; + return made; +} + +#! Views a run of the text, from an index for a number of bytes. +#! @param this The string to narrow. +#! @param start Where the narrower view begins, from `0` to `length`. +#! @param count How many bytes it covers, cut short by the end of the text. +#! @returns A view of that run, which is empty where it begins past the end, and +#! is only good until the string grows, shrinks, or closes. +pub def string::substr(&this, start: u64, count: u64): strview { + return this.view().substr(start, count); +} + +#! Tells whether the text begins with some other text. +#! @param this The string to read. +#! @param prefix The text to look for at its beginning. +#! @returns Whether it begins with the prefix, which empty text always does. +pub def string::starts_with(&this, prefix: strview): bool { + return this.view().starts_with(prefix); +} + +#! Tells whether the text ends with some other text. +#! @param this The string to read. +#! @param suffix The text to look for at its end. +#! @returns Whether it ends with the suffix, which empty text always does. +pub def string::ends_with(&this, suffix: strview): bool { + return this.view().ends_with(suffix); +} + +#! Makes a string of the text without the whitespace at its beginning. +#! @param this The string to read. +#! @returns A new string holding what is left, from the same allocator. +pub def string::ltrim(&this): string { + return string::from(this.view().ltrim(), this._alc); +} + +#! Makes a string of the text without the whitespace at its end. +#! @param this The string to read. +#! @returns A new string holding what is left, from the same allocator. +pub def string::rtrim(&this): string { + return string::from(this.view().rtrim(), this._alc); +} + +#! Makes a string of the text without the whitespace at either end. +#! @param this The string to read. +#! @returns A new string holding what is left, from the same allocator. +pub def string::trim(&this): string { + return string::from(this.view().trim(), this._alc); +} + +#! Compares the text with other text, by their bytes and then by their length. +#! @param this The string to compare against. +#! @param other The text to compare with. +#! @retval -1 Where this string orders before the other. +#! @retval 0 Where they hold the same bytes. +#! @retval 1 Where this string orders after the other. +pub def string::compare(&this, other: strview): i64 { + return this.view().compare(other); +} + +#! Makes text of the string with every letter in upper case. +#! @param this The string to read. +#! @returns A new string holding the converted text. +pub def string::upper(&this): string { + return this.view().upper(); +} + +#! Makes text of the string with every letter in lower case. +#! @param this The string to read. +#! @returns A new string holding the converted text. +pub def string::lower(&this): string { + return this.view().lower(); +} + +#! Makes text of a width, with the string's text at its end and a byte before +#! it. +#! @param this The string to read. +#! @param width How many bytes the text should hold. +#! @param fill The byte to put before it. +#! @returns A new string holding the padded text, which is a copy of this one +#! where it is already that wide. +pub def string::lpad(&this, width: u64, fill: u8): string { + return this.view().lpad(width, fill); +} + +#! Makes text of a width, with the string's text at its beginning and a byte +#! after it. +#! @param this The string to read. +#! @param width How many bytes the text should hold. +#! @param fill The byte to put after it. +#! @returns A new string holding the padded text, which is a copy of this one +#! where it is already that wide. +pub def string::rpad(&this, width: u64, fill: u8): string { + return this.view().rpad(width, fill); +} + +# Gives the string room for more bytes than it holds, which is what it needs +# before more are added. +def string::grow(&mut this, wanted: u64): void { + var capacity := this._cap == 0 ? 16u : this._cap; + while capacity < wanted { + capacity *= 2; + } + + this.recapacity(capacity); +} + +# Moves the bytes to memory of another size, keeping what fits. An allocator that +# gives no memory stops the program, as `resize` does. +def string::recapacity(&mut this, capacity: u64): void { + if capacity == this._cap { + return; + } + + if capacity == 0 { + this.close(); + return; + } + + this._dat = resize::(this._alc, this._dat, this._cap, capacity); + this._cap = capacity; + if this._len > capacity { + this._len = capacity; + } +} diff --git a/core/containers/strview.sakura b/core/containers/strview.sakura new file mode 100644 index 00000000..dfded93b --- /dev/null +++ b/core/containers/strview.sakura @@ -0,0 +1,301 @@ +#! @file strview.sakura +#! @author John Christman (sorakatadzuma@gmail.com) +#! @copyright Malunal Studios, LLC. +#! @license MIT +#! +#! Contains `strview`, the view of text that is only read, and the methods of +#! text: narrowing, splitting, finding, trimming, comparing, changing case, +#! padding, and reading numbers. +#! +#! Anything that only reads text takes a `strview`, so a literal, a view of one, +#! and the text a `string` lends are all read by the same function, since a +#! string lends a view of itself wherever one is wanted. Anything that makes new +#! text gives a `string`, which owns the memory it is written into and gives it +#! back where its scope ends. +#! +#! `strview` is an alias of `span`, among the types the syntax makes, which +#! the compiler declares itself, so it converts to and from one implicitly and +#! has its methods too. The methods of text are declared on the +#! alias because a method cannot be declared on one instance of a generic type: +#! `def span::trim` would declare a type parameter named `u8`. + +import core::swar; +module core; + + +#! Views a run of the text, from an index for a number of bytes. +#! @param this The text to narrow. +#! @param start Where the narrower view begins, from `0` to `length`. +#! @param count How many bytes it covers, cut short by the end of the text. +#! @returns A view of that run, which is empty where it begins past the end. +@inline +pub def strview::substr(&this, start: u64, count: u64): strview { + if start >= this.length { + return strview::empty(); + } + + val left := this.length - start; + return this.sub(start, count < left ? count : left).some; +} + +#! Tells whether the text begins with some other text. +#! @param this The text to read. +#! @param prefix The text to look for at its beginning. +#! @returns Whether it begins with the prefix, which empty text always does. +pub def strview::starts_with(&this, prefix: strview): bool { + return + this.length >= prefix.length && + this.substr(0, prefix.length).equals(&prefix); +} + +#! Tells whether the text ends with some other text. +#! @param this The text to read. +#! @param suffix The text to look for at its end. +#! @returns Whether it ends with the suffix, which empty text always does. +pub def strview::ends_with(&this, suffix: strview): bool { + return + this.length >= suffix.length && + this.substr(this.length - suffix.length, suffix.length).equals(&suffix); +} + +#! Finds where a run of text first begins within the text. +#! @param this The text to search. +#! @param text The run to look for. +#! @returns Maybe the index where it first begins; otherwise, `nothing`. Empty +#! text is found at 0. +#! @remarks Its first and last bytes are looked for at once, at eight places a +#! step, and the bytes between compared only where both are found, as +#! Wojciech Muła's search does with vectors. +pub def strview::find(&this, text: strview): maybe { + val length := text.length; + return 0 if length == 0; + return nothing {} if length > this._len; + return this.index_of(&text[0]) if length == 1; + + # The places it may begin are 0 to `last`, eight at a time, then the last few + # read without passing the end. + val data := this._dat; + val last := this._len - length; + val first_byte := swar::repeat(text[0]); + val last_byte := swar::repeat(text[length - 1]); + var at: u64 = 0; + while at <= last { + val places := last + 1 - at; + var firsts: swar::bytes8; + var lasts: swar::bytes8; + if places >= 8 { + firsts = swar::load(data + at) ^ first_byte; + lasts = swar::load(data + at + length - 1) ^ last_byte; + } else { + firsts = swar::load_last(data + at, places) ^ first_byte; + lasts = swar::load_last(data + at + length - 1, places) ^ last_byte; + } + var found: swar::mask8 = firsts.zero() & lasts.zero() & swar::mask8::leading(places); + while found.any() { + val begins := at + found.first(); + return begins if memcmp(data + begins + 1, text._dat + 1, length - 2) == 0; + found = found.rest(); + } + at += 8; + } + return nothing {}; +} + +#! Finds where the text first holds any of some bytes. +#! @param this The text to search. +#! @param bytes The bytes to look for. +#! @returns Maybe the index of the first; otherwise, `nothing`, as for no bytes. +#! @remarks Up to four bytes are looked for eight places a step, and more a byte +#! at a time, through a set of the 256. +pub def strview::find_any(&this, bytes: span): maybe { + val count := bytes.length; + return nothing {} if count == 0; + val data := this._dat; + if count <= 4 { + # Each byte repeated, where the first stands for any not given. + val a := swar::repeat(bytes[0]); + val b := swar::repeat(bytes[count > 1 ? 1 : 0]); + val c := swar::repeat(bytes[count > 2 ? 2 : 0]); + val d := swar::repeat(bytes[count > 3 ? 3 : 0]); + var at: u64 = 0; + while at < this._len { + val left := this._len - at; + val word := left >= 8 ? swar::load(data + at) : swar::load_last(data + at, left); + val wa: swar::bytes8 = word ^ a; + val wb: swar::bytes8 = word ^ b; + val wc: swar::bytes8 = word ^ c; + val wd: swar::bytes8 = word ^ d; + val found: swar::mask8 = (wa.zero() | wb.zero() | wc.zero() | wd.zero()) & swar::mask8::leading(left); + return at + found.first() if found.any(); + at += 8; + } + return nothing {}; + } + + var set: u64[4] = [0, 0, 0, 0]; + for byte in bytes { + set[(byte >> 6) as u64] |= 1u << (byte & 63) as u64; + } + for at in 0..this._len { + val byte := data[at]; + return at if ((set[(byte >> 6) as u64] >> (byte & 63) as u64) & 1) != 0; + } + return nothing {}; +} + +#! Tells whether the text is all ASCII, every byte below 128. +#! @param this The text to check. +#! @returns Whether it is, which empty text is. +#! @remarks Thirty-two bytes are read a step, as four words whose high bits are +#! gathered, then eight, then the last few. +pub def strview::is_ascii(&this): bool { + val data := this._dat; + var at: u64 = 0; + while at + 32 <= this._len { + val high := (swar::load(data + at) | swar::load(data + at + 8) | swar::load(data + at + 16) | swar::load(data + at + 24)) + & 0x8080808080808080; + return false if high != 0; + at += 32; + } + while at + 8 <= this._len { + return false if (swar::load(data + at) & 0x8080808080808080) != 0; + at += 8; + } + return (swar::load_last(data + at, this._len - at) & 0x8080808080808080) == 0; +} + +#! Views the text without the whitespace at its beginning. +#! @param this The text to read. +#! @returns A view of what is left, which views into the same text. +pub def strview::ltrim(&this): strview { + var at := 0u; + while at < this.length && this[at].is_space { + at++; + } + + return this.substr(at, this.length - at); +} + +#! Views the text without the whitespace at its end. +#! @param this The text to read. +#! @returns A view of what is left, which views into the same text. +pub def strview::rtrim(&this): strview { + var count := this.length; + while count > 0 && this[count - 1].is_space { + count--; + } + + return this.substr(0, count); +} + +#! Views the text without the whitespace at either end. +#! @param this The text to read. +#! @returns A view of what is left, which views into the same text. +pub def strview::trim(&this): strview { + return this.rtrim().ltrim(); +} + +#! Compares text with other text, by their bytes and then by their length. +#! @param this The text to compare against. +#! @param other The text to compare with. +#! @retval -1 Where this text orders before the other. +#! @retval 0 Where they hold the same bytes. +#! @retval 1 Where this text orders after the other. +pub def strview::compare(&this, other: strview): i64 { + val shorter := this.length < other.length ? this.length : other.length; + if shorter != 0 { + val order := memcmp(this._dat, other._dat, shorter); + return order if order != 0; + } + + if this.length == other.length { + return 0; + } + return this.length < other.length ? -1 : 1; +} + +#! Makes a copy of the text with every ASCII letter in upper case. +#! @param this The text to read. +#! @returns A string holding the converted text. +pub def strview::upper(&this): string { + var made := string::from(this, nothing {}); + change_case(made._dat, made._len, true); + return made; +} + +#! Makes a copy of the text with every ASCII letter in lower case. +#! @param this The text to read. +#! @returns A string holding the converted text. +pub def strview::lower(&this): string { + var made := string::from(this, nothing {}); + change_case(made._dat, made._len, false); + return made; +} + +# Changes the case of the ASCII letters of bytes where they are, eight at a time, +# the last word ending where the bytes do, over letters the words before changed, +# which changing again leaves as they are. Fewer than eight a byte at a time. +def change_case(data: *mut u8, length: u64, upper: bool): void { + if length < 8 { + for at in 0..length { + data[at] = upper ? data[at].to_upper : data[at].to_lower; + } + return; + } + + var at: u64 = 0; + while true { + val word := swar::load(data + at); + *((data + at) as *mut u64) = upper ? word.upper() : word.lower(); + break if at + 8 == length; + at = at + 16 <= length ? at + 8 : length - 8; + } +} + +#! Makes text of a width, with this text at its end and a byte repeated before +#! it. +#! @param this The text to read. +#! @param width How many bytes the text should hold. +#! @param fill The byte to put before it. +#! @returns A string holding the padded text, which is a copy of this text where +#! it is already that wide. +pub def strview::lpad(&this, width: u64, fill: u8): string { + var made := string::new(nothing {}); + made.reserve(width > this.length ? width : this.length); + var at := this.length; + while at < width { + made.push(fill); + at++; + } + + made.append(this); + return made; +} + +#! Makes text of a width, with this text at its beginning and a byte repeated +#! after it. +#! @param this The text to read. +#! @param width How many bytes the text should hold. +#! @param fill The byte to put after it. +#! @returns A string holding the padded text, which is a copy of this text where +#! it is already that wide. +pub def strview::rpad(&this, width: u64, fill: u8): string { + var made := string::new(nothing {}); + made.reserve(width > this.length ? width : this.length); + made.append(this); + var at := this.length; + while at < width { + made.push(fill); + at++; + } + return made; +} + + +# NOTE: Extremely fragile! Should be moved somewhere else or dropped because +# it is just storing a string. Replace with a standard error when it is +# finally added. +#! Explains why text could not be read as a number. +pub struct failure { + pub var message: string; #! What was wrong with the text. +} diff --git a/core/containers/vector.sakura b/core/containers/vector.sakura new file mode 100644 index 00000000..4e321dba --- /dev/null +++ b/core/containers/vector.sakura @@ -0,0 +1,688 @@ +#! @file vector.sakura +#! @author John Christman (sorakatadzuma@gmail.com) +#! @copyright Malunal Studios, LLC. +#! @license MIT +#! +#! Defines an implementation for a `vector` container. Vectors are a structured +#! container that acts like a regular array, but storing its data dynamically. +module core; + + +#! A growable array, holding its elements one after another in one block of +#! memory, which it owns. +#! +#! It is the general container wherever an array that grows is wanted: adding at +#! its end, indexing, and walking are cheap, and adding or removing anywhere +#! else moves the elements after it. +#! @tparam T The type of its elements. +pub struct vector + : owning + , copyable + , moveable + , equatable + , hashable + , indexable + , sliceable + , viewable + , iterable + , extendable +{ + var _alc: maybe<&mut allocator>; + var _dat: *mut T; + var _len: u64; + var _cap: u64; +} + +#! Provides read only access to the length of a vector. +#! @param this The vector to get the length of. +#! @returns The length of the vector. +pub val vector::length: u64 { + get => this._len; +} + +#! Provides read only access to the capacity of a vector. +#! @param this The vector to get the capacity of. +#! @returns The capacity of the vector. +pub val vector::capacity: u64 { + get => this._cap; +} + +#! Indicates if a vector is empty. +#! @param this The vector to check. +#! @returns Whether the vector is empty. +pub val vector::is_empty: bool { + get => this._len == 0; +} + +#! Indicates if a vector is full. +#! @param this The vector to check. +#! @returns Whether the vector is full. +pub val vector::is_full: bool { + get => this._len == this._cap; +} + +#! Makes an empty vector, which takes memory from the program's heap once +#! something is added. +#! @returns The vector, which holds no memory yet. +pub def vector::new(): vector { + return vector::::new(nothing{}); +} + +#! Makes an empty vector, which takes memory once something is added. +#! @param alloc The optional allocator to take memory from, or `nothing` for +#! the program's heap. +#! @returns The vector, which holds no memory yet. +pub def vector::new(alloc: maybe<&mut allocator>): vector { + return vector:: { _alc = alloc, _dat = null, _len = 0, _cap = 0 }; +} + +#! Makes an empty vector with room for a number of elements. +#! @param size How many elements it has room for before it grows. +#! @param alloc The optional allocator to take memory from, or `nothing` for +#! the program's heap. +#! @returns The vector, which holds no elements yet. +#! @remarks An allocator that gives no memory stops the program. +pub def vector::new(size: u64, alloc: maybe<&mut allocator>): vector { + var made := vector::::new(alloc); + made.reserve(size); + return made; +} + +#! Builds a vector holding copies of another's elements, with its allocator. +#! @param other The vector to copy elements from. +#! @returns The copy, which owns its own memory and its own elements. +#! @remarks Each element is copied by `copyable` where it provides one, so an +#! element owning memory is copied rather than shared. Elements are +#! filled where they stand, so nothing is built only to be written +#! over. +pub def vector::copy_of(other: &vector): vector { + var made := vector::::new(other._len, other._alc); + for index in 0..other._len { + made.append(copy::(&other._dat[index])); + } + return made; +} + +#! Creates a new vector by moving the data of another vector into it. +#! @param other The vector to move elements from, which holds none after. +#! @returns The moved vector, which takes the memory and the allocator with it. +#! @remarks Nothing is copied and no element is touched: the memory moves as it +#! stands, and the other is left empty rather than dead, so closing it +#! afterwards is harmless. +pub def vector::move_of(other: &mut vector): vector { + var made: vector = vector { + _alc = other._alc, + _dat = other._dat, + _len = other._len, + _cap = other._cap + }; + + other._dat = null; + other._len = 0; + other._cap = 0; + return made; +} + +#! Lends a writable view of the elements, without copying them. +#! @param this The vector to view. +#! @returns A view of its elements, which writes them where they are, and is +#! only good until the vector grows, shrinks, or closes. +pub def vector::slice(&mut this): slice { + # A vector holding any element is never over null, so the slice is made as it + # is rather than through `over`, which would ask. + return slice:: { _dat = this._dat, _len = this._len }; +} + +#! Lends a view of the elements, without copying them. +#! @param this The vector to view. +#! @returns A view of its elements, which is only good until the vector grows, +#! shrinks, or closes. +pub def vector::view(&this): span { + # Made as it is, as `slice` is. + return span:: { _dat = this._dat, _len = this._len }; +} + +#! Reads the element at an index, which `v[index]` calls. +#! @param this The vector to read. +#! @param index The index of the element, below `length`, past which a checked +#! program stops. +#! @returns The element, which is only good until the vector grows, shrinks, or +#! closes. +pub def vector::at(&this, index: u64): &T { + # Indexed as a view of the elements, it is checked as a view's index is. + return &span:: { _dat = this._dat, _len = this._len }[index]; +} + +#! Reaches the element at an index to write it, which `v[index] = x` calls. +#! @param this The vector to write. +#! @param index The index of the element, below `length`, past which a checked +#! program stops. +#! @returns The element, which is only good until the vector grows, shrinks, or +#! closes. +pub def vector::at(&mut this, index: u64): &mut T { + return &mut slice:: { _dat = this._dat, _len = this._len }[index]; +} + +#! Gets the element at an index, if the vector holds one there, for an index +#! that may be past the end in a program that is right. +#! @param this The vector to read. +#! @param index The index of the element. +#! @returns Maybe the element, which is only good until the vector grows, +#! shrinks, or closes; otherwise, `nothing`. +pub def vector::get(&this, index: u64): maybe<&T> { + # Reached as a view's element, whose check the test answers. + return index < this._len + ? &span:: { _dat = this._dat, _len = this._len }[index] + : nothing {}; +} + +#! Gets the element at an index to write it, if the vector holds one there. +#! @param this The vector to write. +#! @param index The index of the element. +#! @returns Maybe the element, which is only good until the vector grows, +#! shrinks, or closes; otherwise, `nothing`. +pub def vector::get(&mut this, index: u64): maybe<&mut T> { + return index < this._len + ? &mut slice:: { _dat = this._dat, _len = this._len }[index] + : nothing {}; +} + +#! Reads the first element. +#! @param this The vector to read, which holds an element, or else a checked +#! program stops. +#! @returns The first element, which is only good until the vector grows, +#! shrinks, or closes. +#! @remarks A view's `first` gives `none` where it is empty instead, as one that +#! is asked whether it holds anything. +pub def vector::first(&this): &T { + if const checking() { + if this._len == 0 { + past_end(0, 0); + } + } + # Reached as a view's element, whose check the test above answers. + return &span:: { _dat = this._dat, _len = this._len }[0]; +} + +#! Reaches the first element to write it. +#! @param this The vector to write, which holds an element, or else a checked +#! program stops. +#! @returns The first element, which is only good until the vector grows, +#! shrinks, or closes. +pub def vector::first(&mut this): &mut T { + if const checking() { + if this._len == 0 { + past_end(0, 0); + } + } + return &mut slice:: { _dat = this._dat, _len = this._len }[0]; +} + +#! Reads the last element, which `v[v.length - 1]` reads. +#! @param this The vector to read, which holds an element, or else a checked +#! program stops. +#! @returns The last element, which is only good until the vector grows, +#! shrinks, or closes. +#! @remarks A view's `last` gives `none` where it is empty instead, as one that +#! is asked whether it holds anything. +pub def vector::last(&this): &T { + if const checking() { + if this._len == 0 { + past_end(0, 0); + } + } + return &this._dat[this._len - 1]; +} + +#! Reaches the last element to write it. +#! @param this The vector to write, which holds an element, or else a checked +#! program stops. +#! @returns The last element, which is only good until the vector grows, +#! shrinks, or closes. +pub def vector::last(&mut this): &mut T { + if const checking() { + if this._len == 0 { + past_end(0, 0); + } + } + return &mut this._dat[this._len - 1]; +} + +#! Replaces the element at an index. +#! @param this The vector to write. +#! @param index The index of the element, below `length`, past which a checked +#! program stops. +#! @param elem The element to store there. +pub def vector::set(&mut this, index: u64, elem: T): void { + slice:: { _dat = this._dat, _len = this._len }[index] = move(elem); +} + +#! Adds an element after the last. +#! @param this The vector to append to. +#! @param elem The element to append. +#! @remarks An allocator that gives no more memory stops the program. +pub def vector::append(&mut this, elem: T): void { + if this.is_full { + this.grow(); + } + this._dat[this._len++] = move(elem); +} + +#! Adds copies of elements after the last, in order, as appending each would. +#! @param this The vector to add to. +#! @param items The elements to add, which are not the vector's own, since +#! growing would move them. +#! @remarks Elements are copied by `copyable` where they provide one, and byte +#! for byte where nothing they hold closes. The vector grows once for +#! all of them. An allocator that gives no more memory stops the +#! program. +pub def vector::extend(&mut this, items: span): void { + val count := items.length; + return if count == 0; + + val wanted := this._len + count; + if wanted > this._cap { + this.grow(wanted > this._cap * 2 ? wanted : this._cap * 2); + } + + if const T is copyable || T is closeable { + for index in 0..count { + this._dat[this._len + index] = copy::(&items.data[index]); + } + } else { + memcpy((this._dat + this._len) as *mut u8, items.data as *u8, bytes_of::(count)); + } + this._len = wanted; +} + +#! Removes the first element equal to the one given, where any is, moving the +#! elements after it down one. +#! @param this The vector to remove from. +#! @param elem The element to look for, compared by `equals`. +#! @remarks The element removed is closed where it closes, or holds what does. +pub def vector::remove(&mut this, elem: &T): void { + for index in 0..this._len { + if equals::(&this._dat[index], elem) { + this.remove_at(index); + return; + } + } +} + +#! Adds an element at an index, moving the elements from it up one. +#! @param this The vector to insert into. +#! @param index Where the element goes, from `0` to `length`, where `length` +#! appends. An index past that stops a checked program. +#! @param elem The element to insert. +pub def vector::insert_at(&mut this, index: u64, elem: T): void { + if const checking() { + if index > this._len { + past_end(index, this._len); + } + } + if index == this._len { + this.append(move(elem)); + return; + } + + if this.is_full { + this.grow(); + } + + val orig := this._dat; + val src := orig + index; + val dst := src + 1; + memcpy( + dst as *mut u8, + src as *mut u8, + bytes_of::(this._len - index) + ); + + # The slot still holds the bytes of the element moved up from it, which writing + # over would close, so it is emptied first. + if const T is closeable { + memset(src as *mut u8, 0, bytes_of::(1)); + } + this._dat[index] = move(elem); + this._len++; +} + +#! Removes the element at an index, moving the elements after it down one. +#! @param this The vector to remove from. +#! @param index The index of the element, below `length`, past which a checked +#! program stops. +#! @remarks The element is closed where it closes, or holds what does. +pub def vector::remove_at(&mut this, index: u64): void { + close(&mut slice:: { _dat = this._dat, _len = this._len }[index]); + + # Removing the last element moves nothing, as a stack popping does. + val orig := this._dat; + val after := this._len - index - 1; + if after != 0 { + val dst := orig + index; + memcpy(dst as *mut u8, (dst + 1) as *mut u8, bytes_of::(after)); + } + + # The last slot still holds the bytes of the element moved down from it, which + # appending would close. + this._len--; + if const T is closeable { + memset((orig + this._len) as *mut u8, 0, bytes_of::(1)); + } +} + +#! Removes the last element, as `remove_at(length - 1)` does, without moving +#! any other. +#! @param this The vector to remove from, which holds an element, or else a +#! checked program stops. +#! @remarks The element is closed where it closes, or holds what does, and not +#! given back, so read it with `last` first. It is named apart from the +#! `pop` of the stack, queue and heap, which a vector is not. +pub def vector::truncate(&mut this): void { + if const checking() { + if this._len == 0 { + past_end(0, 0); + } + } + + this._len--; + if const T is closeable { + close(&mut this._dat[this._len]); + + # The slot past the length is kept empty where appending would close it. + memset((this._dat + this._len) as *mut u8, 0, bytes_of::(1)); + } +} + +#! Makes room for at least a number of elements, keeping those it holds. +#! @param this The vector to make room in. +#! @param count How many elements it should have room for. +#! @remarks A vector with room for that many already is left as it is, so this +#! never shrinks it. An allocator that gives no more memory stops the +#! program. +pub def vector::reserve(&mut this, count: u64): void { + this.grow(count); +} + +#! Where the elements begin, `length` of them, for what reads or writes them +#! through a pointer, as a container built on a vector does. +#! @param this The vector. +#! @returns The pointer, which is only good until the vector grows, shrinks, or +#! closes. Nothing checks what is reached through it. +pub val vector::data: *mut T { + get => this._dat; +} + +#! Makes the vector hold a number of elements, adding zeroed ones or removing +#! those past it. +#! @param this The vector to resize. +#! @param size How many elements it holds after. +#! @remarks Elements removed are closed where they close, or hold what does. An +#! allocator that gives no more memory stops the program. +pub def vector::resize(&mut this, size: u64): void { + # A vector holding no memory yet takes it zeroed, which memory the system + # gives fresh already is, so it is not cleared again. + if this._dat == null && size != 0 { + this._dat = acquire_zeroed::(this._alc, size); + this._cap = size; + this._len = size; + return; + } + + # Growing doubles at least, so resizing a little at a time copies little. + if size > this._cap { + this.grow(size > this._cap * 2 ? size : this._cap * 2); + } + + if size < this._len { + if const T is closeable { + for index in size..this._len { + close(&mut this._dat[index]); + } + } + + # The slots past the length are kept empty where appending would close them. + if const T is closeable { + memset((this._dat + size) as *mut u8, 0, bytes_of::(this._len - size)); + } + } + else { + memset((this._dat + this._len) as *mut u8, 0, bytes_of::(size - this._len)); + } + this._len = size; +} + +#! Makes the vector hold a number more elements, which hold what their memory +#! happened to, for elements the program writes before it reads them, as a +#! table it fills whole: what `resize` adds, without zeroing it. +#! @param this The vector to grow. +#! @param count How many elements it gains. +#! @remarks Only for what closes nothing, since closing an element would close +#! what its memory held. Reading an element before writing it is the +#! program's mistake, which `run --checks` stops at. An allocator that +#! gives no more memory stops the program. +pub def vector::extend_undefined(&mut this, count: u64): void { + if const T is closeable { + compile_error("Elements left undefined would be closed holding what their memory happened to, so a vector of what closes is grown by `resize`."); + } + val size := this._len + count; + if size > this._cap { + this.grow(size > this._cap * 2 ? size : this._cap * 2); + } + this._len = size; +} + +#! Makes the vector hold a number of elements, adding copies of one or removing +#! those past it. +#! @param this The vector to resize. +#! @param size How many elements it holds after. +#! @param fill The element each one added is a copy of. +#! @remarks Elements added are copied by `copyable` where they provide one, and +#! elements removed are closed where they close, or hold what does. An +#! allocator that gives no more memory stops the program. +pub def vector::resize(&mut this, size: u64, fill: T): void { + if size <= this._len { + this.resize(size); + return; + } + + if size > this._cap { + this.grow(size > this._cap * 2 ? size : this._cap * 2); + } + for index in this._len..size { + this._dat[index] = copy::(&fill); + } + this._len = size; +} + +#! Removes every element, keeping the memory the vector holds them in. +#! @param this The vector to empty. +#! @remarks Elements are closed where they close, or hold what does. +pub def vector::clear(&mut this): void { + if const T is closeable { + for index in 0..this._len { + close(&mut this._dat[index]); + } + } + + if const T is closeable { + memset(this._dat as *mut u8, 0, bytes_of::(this._len)); + } + this._len = 0; +} + +#! Removes every element and gives back the memory the vector holds. +#! @param this The vector to close. +#! @remarks Elements are closed where they close, or hold what does. The vector +#! is left empty, so closing it again does nothing. +pub def vector::close(&mut this): void { + if const T is closeable { + for index in 0..this._len { + close(&mut this._dat[index]); + } + } + + dispose::(this._alc, this._dat, this._cap); + this._dat = null; + this._len = 0; + this._cap = 0; +} + +#! Compares one vector to another for equality. +#! @param this The vector to compare against. +#! @param other The vector to compare with. +#! @returns Whether both hold the same elements, in the same order. +pub def vector::equals(&this, other: &vector): bool { + if this._len != other._len { + return false; + } + + for index in 0..this._len { + return false if !equals::( + &this._dat[index], + &other._dat[index] + ); + } + return true; +} + +#! What `iter(&this)` lends, which reads the elements where the vector holds +#! them. +pub type vector::cursor = span::cursor; + +#! What `iter(&mut this)` lends, which writes the elements where the vector +#! holds them. +pub type vector::mut_cursor = slice::mut_cursor; + +#! Lends a cursor that reads the elements, in order, which `for x in v` walks. +#! @param this The vector to walk. +#! @returns The cursor, which is only good until the vector grows, shrinks, or +#! closes. +pub def vector::iter(&this): span::cursor { + return this.view().iter(); +} + +#! Lends a cursor that writes the elements where they are, which `for &mut x in +#! v` walks. +#! @param this The vector to walk. +#! @returns The cursor, which is only good until the vector grows, shrinks, or +#! closes. +pub def vector::iter(&mut this): slice::mut_cursor { + var whole := this.slice(); + return whole.iter(); +} + +#! Makes a vector of the elements an iterator gives, as its `to_vector` does. +#! @tparam I The iterator. +#! @param from The iterator, walked to its end. +#! @returns The vector, given room for them all at once where the iterator knows +#! how many it has left. +pub def vector::from(from: I): vector where I: iterator { + return from.to_vector(); +} + +#! Moves the elements a range of indexes covers out of the vector, one at a +#! time, as what it gives is walked. Those not walked to are closed where it +#! closes, and the elements after the range then move down into the gap, so +#! the vector holds only those outside the range. +#! @param this The vector to take from. +#! @param which The indexes, from `0` up to `length`, past which a checked +#! program stops. +#! @returns The elements, from the front or the far end, which the vector is not +#! to be changed by anything else while they are walked. +pub def vector::drain(&mut this, which: range): vector::drained { + val start := which.start; + val stop := start + which.remaining(); + if const checking() { + if stop > this._len || start > stop { + past_end(stop, this._len); + } + } + return vector::::drained { _of = this, _start = start, _at = start, _end = stop, _stop = stop }; +} + +#! What `drain` gives: the elements of a range of indexes, moved out of the +#! vector as they are given. Closing it closes those it did not give and moves +#! the elements after the range down into the gap. +pub struct vector::drained : owning, sized_iterator, backward_iterator { + var _of: &mut vector; #! The vector drained. + var _start: u64; #! Where the range begins, which the gap begins at. + var _at: u64; #! The next element to give from the front. + var _end: u64; #! Just past the next to give from the far end. + var _stop: u64; #! Where the range ends, after which the rest stay. +} + +#! Moves out the next element of the range. +#! @param this The drain. +#! @returns Maybe the element; otherwise, `nothing` once the ends have met. +pub def vector::drained::next(&mut this): maybe { + return nothing {} if this._at == this._end; + val at := this._at; + this._at++; + return move(&mut this._of._dat[at]); +} + +#! Moves out the element of the range at its far end. +#! @param this The drain. +#! @returns Maybe the element; otherwise, `nothing` once the ends have met. +pub def vector::drained::next_back(&mut this): maybe { + return nothing {} if this._at == this._end; + this._end--; + return move(&mut this._of._dat[this._end]); +} + +#! How many elements of the range it has left to give. +#! @param this The drain. +#! @returns How many. +pub def vector::drained::remaining(&this): u64 { + return this._end - this._at; +} + +#! Closes the elements of the range it did not give, and moves the elements +#! after the range down into the gap. +#! @param this The drain. +pub def vector::drained::close(&mut this): void { + if const T is closeable { + for index in this._at..this._end { + close(&mut this._of._dat[index]); + } + } + val after := this._of._len - this._stop; + if after != 0 && this._stop != this._start { + val base := this._of._dat; + memcpy((base + this._start) as *mut u8, (base + this._stop) as *mut u8, bytes_of::(after)); + } + this._of._len = this._start + after; + this._at = this._end; + this._stop = this._start; +} + +#! Hashes the elements, in order. +#! @param this The vector to hash. +#! @returns The hash code, which vectors holding equal elements share. +#! @remarks Elements are hashed by their `hash`, so they are `hashable`. +pub def vector::hash(&this): u64 { + var code := this._len; + for index in 0..this._len { + code = mix(code, hash(this._dat[index])); + } + return code; +} + +# Gives the vector room for more elements, doubling it. +def vector::grow(&mut this): void { + this.grow(this._cap == 0 ? 4 : this._cap * 2); +} + +# Gives the vector room for a number of elements, where it has less. An allocator +# that gives no memory stops the program, as `acquire` and `resize` do. +def vector::grow(&mut this, size: u64): void { + if size <= this._cap { + return; + } + + this._dat = this._dat == null + ? acquire::(this._alc, size) + : resize::(this._alc, this._dat, this._cap, size); + this._cap = size; +} diff --git a/core/fault.sakura b/core/fault.sakura new file mode 100644 index 00000000..f6bf9a37 --- /dev/null +++ b/core/fault.sakura @@ -0,0 +1,70 @@ +#! @file fault.sakura +#! @author John Christman (sorakatadzuma@gmail.com) +#! @copyright Malunal Studios, LLC. +#! @license MIT +#! +#! Contains `fault`, which stops a program that has found a mistake of its own, +#! saying what, as an index past the end of a view stops it, as a contract that +#! fails does, `contracts`, which says whether they are checked, `checking`, +#! which says whether the program checks what it does, and the faults the +#! containers and allocators of `core` stop with. + +module core; + + +#! Stops the program at once, as a fault does: the report is "runtime error: " +#! and the text given, then the functions that were running, and the status is +#! 1, as every fault's. +#! +#! This is for a mistake the program cannot go on from, as a container asked +#! for an element past its end. It needs nothing of the system it runs on, so +#! every place a program runs gives it, and it never returns. +#! @param why What went wrong, as `Index 5 is out of bounds: the length is 3.` +@intrinsic +pub def fault(why: strview): void; + +#! Whether the program's contracts are checked: true unless it was built or +#! run with `--contracts off`, which leaves out each `expects`, `asserts`, and +#! `ensures`, conditions and all. +#! +#! It is known while compiling, so `if const contracts()` keeps work that only +#! contracts read out of a program that leaves them out. +#! @returns Whether they are. +@intrinsic +pub def contracts(): bool; + +#! Whether the program checks what it does: true where it runs on the machine, +#! but for `run --fast`, and where it was built with `--checks`. +#! +#! A checked program stops at an index past the end, the wrong field of a union +#! read, an integer converted to an enum none of whose members has its value, +#! and a `match` finding no arm, each with what went wrong and where, as std's +#! containers stop where asked for what they do not hold. One that is not +#! checked does none of that, and reads and writes where the program said, as C +#! does. Every program stops at null reached through, at a division by zero, +#! and where its stack runs out. Contracts are apart from this, and `contracts` +#! says whether they are checked. +#! +#! It is known while compiling, so the checks a container makes itself are +#! written `if const checking() { ... }`, and an unchecked program has none of +#! their code. +#! @returns Whether it does. +@intrinsic +pub def checking(): bool; + +# Stops the program where a container of the language's own is asked for an +# element past its end, as indexing a view outside its length does, where the +# program checks. A container calls it only where its check fails, so that where +# the check holds, it costs a compare, and the call is no more than its two +# numbers, which keeps what calls it short enough to be emitted where it is +# called. +def past_end(index: u64, length: u64): void { + fault($"Index {index} is out of bounds: the length is {length}."); +} + +# Stops the program where an allocator gives no memory for what is asked of it, +# as `raw_allocate` stops it where the system gives none, which every program +# does, checked or not. +def exhausted(size: u64): void { + fault($"The allocator gave no memory for {size} bytes."); +} diff --git a/core/ffi.sakura b/core/ffi.sakura new file mode 100644 index 00000000..03093232 --- /dev/null +++ b/core/ffi.sakura @@ -0,0 +1,19 @@ +#! @file ffi.sakura +#! @author John Christman (sorakatadzuma@gmail.com) +#! @copyright Malunal Studios, LLC. +#! @license MIT +#! +#! Contains `cfn`, the address of a C function. C's functions, structs, and +#! unions are declared in an `extern module`, and `extern import` names the +#! library they are found in. + +module core; + +#! The address of a C function taking and giving what `F` does, as +#! `cfn`, which may be `null`. It is callable, and converts with +#! `as` to and from pointers, integers, and other addresses of C functions. A +#! function of the program given where one is expected is the address of an +#! entry C calls it back through. +#! @tparam F The function type the C function has, as `def(i32): void`. +@intrinsic +pub struct cfn {} diff --git a/core/flags.sakura b/core/flags.sakura new file mode 100644 index 00000000..f46578b9 --- /dev/null +++ b/core/flags.sakura @@ -0,0 +1,73 @@ +#! @file flags.sakura +#! @author John Christman (sorakatadzuma@gmail.com) +#! @copyright Malunal Studios, LLC. +#! @license MIT +#! +#! Contains `flags32`, a set of up to 32 flags held as a `u32`, whose bits are +#! named by the members of an enum. + +module core; + +#! A set of up to 32 flags, held as a `u32`, whose bits are named by the members +#! of an enum. +#! +#! It converts to and from `u32` as any alias does, so it is written where an +#! integer of flags is wanted, and its methods read and write the bits by member +#! or by index. +#! @tparam T The enum naming the bits, whose members' values are the bits they +#! set. +pub type flags32 = u32 + where T : ordinal; + + +#! Whether the flags hold any bit of a value. +#! @param this The flags to read. +#! @param value The value whose bits to look for. +#! @returns Whether any of its bits is set. +pub def flags32::get(&this, value: T): bool { + return (this & value as u32) != 0; +} + +#! Whether the flags hold a bit. +#! @param this The flags to read. +#! @param index Which bit, from 0 to 31. +#! @returns Whether it is set. +pub def flags32::get(&this, index: u8): bool { + return (this & ((1 as u32) << index as u32)) != 0; +} + +#! Sets the bits of a value. +#! @param this The flags to change. +#! @param value The value whose bits to set. +pub def flags32::set(&mut this, value: T): void { + this |= value as u32; +} + +#! Sets or clears a bit. +#! @param this The flags to change. +#! @param index Which bit, from 0 to 31. +#! @param value Whether the bit is set, or else cleared. +pub def flags32::set(&mut this, index: u8, value: bool): void { + val bit := (1 as u32) << index as u32; + this = value ? this | bit : this & ~bit; +} + +#! The flags with the bits of a value set too. +#! @param this The flags to start from. +#! @param value The value whose bits to set. +#! @returns The flags with those bits set, leaving these as they are. +pub def flags32::with(&this, value: T): flags32 { + return this | value as u32; +} + +#! The flags with a bit set or cleared. +#! @param this The flags to start from. +#! @param index Which bit, from 0 to 31. +#! @param value Whether the bit is set, or else cleared. +#! @returns The flags with the bit changed, leaving these as they are. +pub def flags32::with(&this, index: u8, value: bool): flags32 { + val bit := (1 as u32) << index as u32; + return value ? this | bit : this & ~bit; +} + + diff --git a/core/functions/function.sakura b/core/functions/function.sakura new file mode 100644 index 00000000..b287ee66 --- /dev/null +++ b/core/functions/function.sakura @@ -0,0 +1,163 @@ +#! @file function.sakura +#! @author John Christman (sorakatadzuma@gmail.com) +#! @copyright Malunal Studios, LLC. +#! @license MIT +#! +#! Contains `function`, one callable of a signature, whatever its type, which it +#! owns, as C++'s `std::function` and Rust's `Box`: for a callable kept +#! past the call that is given it, where its type is not one to name. + +module core; + +#! A callable of one signature, whatever its type, which it owns and closes where +#! it closes: a functor, a function, a lambda, or the address of a C function, as +#! `function`. +#! +#! It holds a callable of 24 bytes or fewer, aligned to 8 or less, in the value +#! itself, as it does a function value, a C function's address, and most +#! functors, and a larger one in a `box`. A call goes through one table of what +#! the held type does, which each type has one of, so calling it costs one load +#! and one indirect call more than calling what it holds. +#! +#! It is moved, never copied: `move` leaves the one moved from empty. Its zero +#! value holds nothing, so a field or a variable needs none given, and calling a +#! function that holds nothing stops the program, as reaching through `null` +#! does. +#! +#! ```sakura +#! var handlers := vector::>::new(); +#! handlers.append(function::new(tally {})); +#! handlers.append(function::new(def(e: &event) { println(e.name); })); +#! for &h in handlers { h(&e); } +#! ``` +#! @tparam S The signature, as `def(i64): bool`. +#! @remarks A lambda refers to the locals it uses, so a function holding one +#! refers to them too, and must not outlive them. What must outlive the +#! frame making it is a functor holding what it needs. A function is no +#! constant, since a constant would keep the words of what it holds but +#! not the function a function value among them is. +pub struct function : invokable, owning where S: signature { + var _ops: *function_ops; #! What the held type does, or `null` where it holds nothing. + var _held: u64[3]; #! The callable where it fits, or a `box` of it. +} + +# What a function does with the type it holds: one constant for each type, so its +# address names the type. +struct function_ops where S: signature { + var call: def(*mut u8, S::params...): S::result; # Calls the callable held at the buffer. + var close: def(*mut u8): void; # Closes it, and its box where it has one. +} + +# Whether a function holds a callable of a type in its buffer, rather than in a box. +def function_ops::fits(): bool { + return size_of::() <= 24 && align_of::() <= 8; +} + +# The table of what a function does with a type it holds, at one address for each +# type. +def function_ops::of(): *function_ops where F: invokable { + if const function_ops::::fits::() { + const held: function_ops = function_ops:: { + call = function_ops::::call_held::, + close = function_ops::::close_held:: + }; + return &held as *function_ops; + } else { + const boxed: function_ops = function_ops:: { + call = function_ops::::call_boxed::, + close = function_ops::::close_boxed:: + }; + return &boxed as *function_ops; + } +} + +# Calls a callable held in the buffer. +def function_ops::call_held(at: *mut u8, args: S::params...): S::result where F: invokable { + return (at as *mut F)[0](...args); +} + +# Closes a callable held in the buffer. +def function_ops::close_held(at: *mut u8): void { + close(through(at as *mut F)); +} + +# Calls a callable the buffer holds a box of. +def function_ops::call_boxed(at: *mut u8, args: S::params...): S::result where F: invokable { + val held := &mut (at as *mut box)[0].get(); + return held(...args); +} + +# Closes the box the buffer holds, which closes the callable and gives back its +# memory. +def function_ops::close_boxed(at: *mut u8): void { + close(through(at as *mut box)); +} + +#! Makes a function holding a callable: a functor, a function value, named or a +#! lambda, the address of a C function, or a method taken through its type, as +#! `vec2::length`, which takes its receiver first. +#! @tparam F The callable's type. +#! @param callable The callable, which the function then owns. +#! @returns The function. +pub def function::new(callable: F): function where F: invokable { + var made := function:: { _ops = function_ops::::of::() }; + # Reached through the buffer's address as a number, which no constant is made + # by, since a constant would keep the callable's words but not the function a + # function value among them is. + if const function_ops::::fits::() { + (made.buffer() as *mut F)[0] = move(&mut callable); + } else { + (made.buffer() as *mut box)[0] = box::::new(move(&mut callable)); + } + return made; +} + +#! Calls what a function holds, as `f(args)` does. +#! @param this The function, which must hold a callable. +#! @param args The arguments, one of each of the signature's parameter types. +#! @returns What the call gives. +#! @remarks The callable may change what it holds, as a functor's `invoke` +#! taking `&mut this` does, though the function is called as it is, as +#! a function value is. +pub def function::invoke(&this, args: S::params...): S::result { + return (*this._ops).call(this.buffer(), ...args); +} + +# The buffer's address, which a callable held there is called with, and which it +# may change through, as calling a function value may change what it refers to. +def function::buffer(&this): *mut u8 { + return (&this._held as *u8) as u64 as *mut u8; +} + +#! Whether a function holds a callable, which one moved from or closed does not. +#! @param this The function. +#! @returns Whether it does. +pub def function::holds(&this): bool { + return this._ops != null; +} + +#! Lends the callable a function holds, where it is of a type. +#! @tparam F The type asked for. +#! @param this The function. +#! @returns The callable, good while the function holds it, or `nothing` where +#! it holds nothing, or a callable of another type. +pub def function::get(&this): maybe<&F> where F: invokable { + if this._ops != function_ops::::of::() { + return nothing {}; + } + if const function_ops::::fits::() { + return through(&this._held as *F); + } else { + return (&this._held as *box)[0].get(); + } +} + +#! Closes what a function holds. +#! @param this The function, which holds nothing after, so closing it again +#! does nothing. +pub def function::close(&mut this): void { + val ops := this._ops; + return if ops == null; + this._ops = null; + (*ops).close(&mut this._held as *mut u8); +} diff --git a/core/intrinsics.sakura b/core/intrinsics.sakura new file mode 100644 index 00000000..fb6dc846 --- /dev/null +++ b/core/intrinsics.sakura @@ -0,0 +1,46 @@ +#! @file intrinsics.sakura +#! @author John Christman (sorakatadzuma@gmail.com) +#! @copyright Malunal Studios, LLC. +#! @license MIT +#! +#! Contains the operations of the machine the compiler gives that libraries +#! build on, and which no operator writes: a square root, which IEEE 754 +#! defines to the bit, and working an operation on lanes of numbers with the +#! instructions the processor has. `std::math` builds its functions of real +#! numbers and of lanes on them. +#! +#! The compiler gives them: the virtual machine runs its own, and an executable +#! the instruction `sqrtsd`, and the vector instructions the processor running +#! it has. A square root is the true root rounded once, so they agree to the +#! bit, and a constant worked out while compiling is what running gives. +#! +#! They are a module within `core`, rather than its root, so their names are +#! seen only where it is imported. + +module core::intrinsics; + + +#! The square root of a double, correctly rounded: `-0` for `-0`, infinity for +#! infinity, and not a number for what is below zero or not a number. +#! @param x The double. +#! @returns Its square root. +@intrinsic pub def square_root(x: f64): f64; + +#! Whether the processor running the program has the instructions working `OP` +#! on `N` lanes of `L`, which the program asked it once as it started. +#! @tparam L The type of each lane. +#! @tparam OP The operation, as the compiler numbers it. +#! @tparam N How many lanes. +#! @returns Whether it has them: never in the virtual machine. +@intrinsic pub def lanes_have(): bool; + +#! Works `OP` on `N` lanes of `L`, from the bytes `a`, `b`, and `c` into those +#! of `into`, with the instructions `lanes_have` says the processor has. +#! @tparam L The type of each lane. +#! @tparam OP The operation, as the compiler numbers it. +#! @tparam N How many lanes. +#! @param into Where the lanes worked out are written. +#! @param a The first operand's lanes. +#! @param b The second's, or null where the operation takes one. +#! @param c The third's, or null where it takes fewer. +@intrinsic pub def lanes_apply(into: *mut u8, a: *u8, b: *u8, c: *u8): void; diff --git a/core/iterators/adapters.sakura b/core/iterators/adapters.sakura new file mode 100644 index 00000000..dd6dd54e --- /dev/null +++ b/core/iterators/adapters.sakura @@ -0,0 +1,547 @@ +#! @file adapters.sakura +#! @author John Christman (sorakatadzuma@gmail.com) +#! @copyright Malunal Studios, LLC. +#! @license MIT +#! +#! Contains the adapters, each the iterator one of `iterator`'s defaults makes of +#! another, which it owns: what it gives, and, where what it adapts knows how +#! many elements it has left or walks backward, how many it has left or its +#! elements from the far end. Each is named for what it does, and only written +#! out where a program keeps one in a field. + +module core; + + +#! What `map` makes: what a function makes of each element. +#! @tparam T What the iterator it adapts gives. +#! @tparam U What the function gives. +#! @tparam I The iterator it adapts. +#! @tparam F The function. +pub struct mapped : iterator where I: iterator where F: invokable { + var _from: I; + var _f: F; +} + +#! Gives what the function makes of the next element. +#! @param this The iterator. +#! @returns Maybe what it makes; otherwise, `nothing`. +pub def mapped::next(&mut this): maybe { + if this._from.next() is some(x) { + return this._f(move(&mut x)); + } + return nothing {}; +} + +#! How many elements it has left, which are what it adapts has. +#! @param this The iterator. +#! @returns How many. +pub def mapped::remaining(&this): u64 where I: sized_iterator { + return this._from.remaining(); +} + +#! Gives what the function makes of the element at the far end. +#! @param this The iterator. +#! @returns Maybe what it makes; otherwise, `nothing`. +pub def mapped::next_back(&mut this): maybe where I: backward_iterator { + if this._from.next_back() is some(x) { + return this._f(move(&mut x)); + } + return nothing {}; +} + +#! What `filter` makes: each element a test passes. +#! @tparam T What it gives. +#! @tparam I The iterator it adapts. +#! @tparam F The test. +pub struct filtered : iterator where I: iterator where F: invokable { + var _from: I; + var _test: F; +} + +#! Gives the next element the test passes. +#! @param this The iterator. +#! @returns Maybe the element; otherwise, `nothing`. +pub def filtered::next(&mut this): maybe { + while this._from.next() is some(x) { + return move(&mut x) if this._test(&x); + } + return nothing {}; +} + +#! Gives the element nearest the far end the test passes. +#! @param this The iterator. +#! @returns Maybe the element; otherwise, `nothing`. +pub def filtered::next_back(&mut this): maybe where I: backward_iterator { + while this._from.next_back() is some(x) { + return move(&mut x) if this._test(&x); + } + return nothing {}; +} + +#! What `filter_map` makes: what a function makes of each element, where it +#! makes something. +#! @tparam T What the iterator it adapts gives. +#! @tparam U What the function may give. +#! @tparam I The iterator it adapts. +#! @tparam F The function. +pub struct filter_mapped : iterator where I: iterator where F: invokable> { + var _from: I; + var _f: F; +} + +#! Gives the next thing the function makes. +#! @param this The iterator. +#! @returns Maybe what it makes; otherwise, `nothing`. +pub def filter_mapped::next(&mut this): maybe { + while this._from.next() is some(x) { + var made := this._f(move(&mut x)); + if made is some(&mut kept) { + return move(kept); + } + } + return nothing {}; +} + +#! Gives the thing the function makes nearest the far end. +#! @param this The iterator. +#! @returns Maybe what it makes; otherwise, `nothing`. +pub def filter_mapped::next_back(&mut this): maybe where I: backward_iterator { + while this._from.next_back() is some(x) { + var made := this._f(move(&mut x)); + if made is some(&mut kept) { + return move(kept); + } + } + return nothing {}; +} + +#! What `enumerate` makes: each element with its index, counting from 0. +#! @tparam T What the iterator it adapts gives. +#! @tparam I The iterator it adapts. +pub struct enumerated : iterator> where I: iterator { + var _from: I; + var _at: u64; +} + +#! Gives the next element with its index. +#! @param this The iterator. +#! @returns Maybe the pair; otherwise, `nothing`. +pub def enumerated::next(&mut this): maybe> { + if this._from.next() is some(x) { + val at := this._at; + this._at++; + return pair:: { first = at, second = move(&mut x) }; + } + return nothing {}; +} + +#! How many elements it has left, which are what it adapts has. +#! @param this The iterator. +#! @returns How many. +pub def enumerated::remaining(&this): u64 where I: sized_iterator { + return this._from.remaining(); +} + +#! Gives the element at the far end with its index, which how many are left +#! says. +#! @param this The iterator. +#! @returns Maybe the pair; otherwise, `nothing`. +pub def enumerated::next_back(&mut this): maybe> where I: backward_iterator, sized_iterator { + val left := this._from.remaining(); + if this._from.next_back() is some(x) { + return pair:: { first = this._at + left - 1, second = move(&mut x) }; + } + return nothing {}; +} + +#! What `zip` makes: the elements of two iterators side by side, until either +#! ends. +#! @tparam T What the first gives. +#! @tparam U What the second gives. +#! @tparam I The first. +#! @tparam J The second. +pub struct zipped : iterator> where I: iterator where J: iterator { + var _from: I; + var _other: J; +} + +#! Gives the next element of each, side by side. +#! @param this The iterator. +#! @returns Maybe the pair; otherwise, `nothing` once either ends. +pub def zipped::next(&mut this): maybe> { + var first := this._from.next(); + if first is not some(&mut a) { + return nothing {}; + } + var second := this._other.next(); + if second is not some(&mut b) { + return nothing {}; + } + return pair:: { first = move(a), second = move(b) }; +} + +#! How many pairs it has left: as many as the shorter has. +#! @param this The iterator. +#! @returns How many. +pub def zipped::remaining(&this): u64 where I: sized_iterator where J: sized_iterator { + val a := this._from.remaining(); + val b := this._other.remaining(); + return a < b ? a : b; +} + +#! What `chain` makes: the elements of one iterator, then another's. +#! @tparam T What both give. +#! @tparam I The first. +#! @tparam J The second. +pub struct chained : iterator where I: iterator where J: iterator { + var _first: I; + var _second: J; + var _on_second: bool; +} + +#! Gives the next element of the first, or once it has ended, of the second. +#! @param this The iterator. +#! @returns Maybe the element; otherwise, `nothing`. +pub def chained::next(&mut this): maybe { + if !this._on_second { + if this._first.next() is some(x) { + return move(&mut x); + } + this._on_second = true; + } + return this._second.next(); +} + +#! How many elements it has left: what both have. +#! @param this The iterator. +#! @returns How many. +pub def chained::remaining(&this): u64 where I: sized_iterator where J: sized_iterator { + return (this._on_second ? 0 : this._first.remaining()) + this._second.remaining(); +} + +#! Gives the element at the far end of the second, or once it has met its +#! front, of the first. +#! @param this The iterator. +#! @returns Maybe the element; otherwise, `nothing`. +pub def chained::next_back(&mut this): maybe where I: backward_iterator where J: backward_iterator { + if this._second.next_back() is some(x) { + return move(&mut x); + } + return nothing {} if this._on_second; + return this._first.next_back(); +} + +#! What `take` makes: the first elements, up to a count. +#! @tparam T What it gives. +#! @tparam I The iterator it adapts. +pub struct taken : iterator where I: iterator { + var _from: I; + var _left: u64; +} + +#! Gives the next element, while the count lasts. +#! @param this The iterator. +#! @returns Maybe the element; otherwise, `nothing`. +pub def taken::next(&mut this): maybe { + return nothing {} if this._left == 0; + this._left--; + return this._from.next(); +} + +#! How many elements it has left: the fewer of the count and what it adapts has. +#! @param this The iterator. +#! @returns How many. +pub def taken::remaining(&this): u64 where I: sized_iterator { + val held := this._from.remaining(); + return held < this._left ? held : this._left; +} + +#! What `skip` makes: the elements after the first, up to a count. +#! @tparam T What it gives. +#! @tparam I The iterator it adapts. +pub struct skipped : iterator where I: iterator { + var _from: I; + var _skip: u64; +} + +#! Gives the next element, passing over those to skip the first time. +#! @param this The iterator. +#! @returns Maybe the element; otherwise, `nothing`. +pub def skipped::next(&mut this): maybe { + if this._skip != 0 { + val n := this._skip; + this._skip = 0; + return this._from.nth(n); + } + return this._from.next(); +} + +#! How many elements it has left: what it adapts has, past those to skip. +#! @param this The iterator. +#! @returns How many. +pub def skipped::remaining(&this): u64 where I: sized_iterator { + val held := this._from.remaining(); + return held > this._skip ? held - this._skip : 0; +} + +#! Gives the element at the far end, while it is past those to skip. +#! @param this The iterator. +#! @returns Maybe the element; otherwise, `nothing`. +pub def skipped::next_back(&mut this): maybe where I: backward_iterator, sized_iterator { + return nothing {} if this._from.remaining() <= this._skip; + return this._from.next_back(); +} + +#! What `take_while` makes: the elements while a test passes them. +#! @tparam T What it gives. +#! @tparam I The iterator it adapts. +#! @tparam F The test. +pub struct taken_while : iterator where I: iterator where F: invokable { + var _from: I; + var _test: F; + var _done: bool; +} + +#! Gives the next element where the test passes it, and ends at the first it +#! does not. +#! @param this The iterator. +#! @returns Maybe the element; otherwise, `nothing`. +pub def taken_while::next(&mut this): maybe { + return nothing {} if this._done; + if this._from.next() is some(x) { + return move(&mut x) if this._test(&x); + } + this._done = true; + return nothing {}; +} + +#! What `skip_while` makes: the elements from the first a test does not pass. +#! @tparam T What it gives. +#! @tparam I The iterator it adapts. +#! @tparam F The test. +pub struct skipped_while : iterator where I: iterator where F: invokable { + var _from: I; + var _test: F; + var _past: bool; +} + +#! Gives the next element, passing over those the test passes the first time. +#! @param this The iterator. +#! @returns Maybe the element; otherwise, `nothing`. +pub def skipped_while::next(&mut this): maybe { + return this._from.next() if this._past; + this._past = true; + while this._from.next() is some(x) { + return move(&mut x) if !this._test(&x); + } + return nothing {}; +} + +#! What `step` makes: every `n`th element, the first included. +#! @tparam T What it gives. +#! @tparam I The iterator it adapts. +pub struct stepped : iterator where I: iterator { + var _from: I; + var _by: u64; + var _first: bool; +} + +#! Gives the next element, passing over those between. +#! @param this The iterator. +#! @returns Maybe the element; otherwise, `nothing`. +pub def stepped::next(&mut this): maybe { + if this._first { + this._first = false; + return this._from.next(); + } + return this._from.nth(this._by - 1); +} + +#! How many elements it has left: every `n`th of what it adapts has. +#! @param this The iterator. +#! @returns How many. +pub def stepped::remaining(&this): u64 where I: sized_iterator { + val held := this._from.remaining(); + return this._first ? (held + this._by - 1) / this._by : held / this._by; +} + +#! What `rev` makes: the elements from the far end. +#! @tparam T What it gives. +#! @tparam I The iterator it adapts, which walks backward. +pub struct reversed : iterator where I: backward_iterator { + var _from: I; +} + +#! Gives the element at the far end of what it adapts. +#! @param this The iterator. +#! @returns Maybe the element; otherwise, `nothing`. +pub def reversed::next(&mut this): maybe { + return this._from.next_back(); +} + +#! Gives the element at the front of what it adapts, its own far end. +#! @param this The iterator. +#! @returns Maybe the element; otherwise, `nothing`. +pub def reversed::next_back(&mut this): maybe { + return this._from.next(); +} + +#! How many elements it has left, which are what it adapts has. +#! @param this The iterator. +#! @returns How many. +pub def reversed::remaining(&this): u64 where I: sized_iterator { + return this._from.remaining(); +} + +#! What `peekable` makes: the elements, with the next looked at by `peek` +#! before it is given. +#! @tparam T What it gives. +#! @tparam I The iterator it adapts. +pub struct peeking : iterator where I: iterator { + var _from: I; + var _held: maybe; + var _peeked: bool; +} + +#! Gives the next element, the one `peek` looked at where it did. +#! @param this The iterator. +#! @returns Maybe the element; otherwise, `nothing`. +pub def peeking::next(&mut this): maybe { + if this._peeked { + this._peeked = false; + return move(&mut this._held); + } + return this._from.next(); +} + +#! Looks at the next element without giving it, so `next` gives it after. +#! @param this The iterator. +#! @returns Maybe a reference to the element, which it holds; otherwise, +#! `nothing`. +pub def peeking::peek(&mut this): maybe<&T> { + if !this._peeked { + this._held = this._from.next(); + this._peeked = true; + } + if this._held is some(&x) { + return x; + } + return nothing {}; +} + +#! How many elements it has left: what it adapts has, and the one it holds. +#! @param this The iterator. +#! @returns How many. +pub def peeking::remaining(&this): u64 where I: sized_iterator { + var made := this._from.remaining(); + if this._peeked && this._held is some(&x) { + made++; + } + return made; +} + +#! What `flat_map` makes: the elements of each iterator a function makes of +#! each element, in turn. +#! @tparam T What the iterator it adapts gives. +#! @tparam U What the iterators the function makes give. +#! @tparam I The iterator it adapts. +#! @tparam J The iterators the function makes. +#! @tparam F The function. +pub struct flat_mapped : iterator + where I: iterator where J: iterator where F: invokable { + var _from: I; + var _f: F; + var _inner: maybe; +} + +#! Gives the next element of the iterator it is walking, or of the next it +#! makes, once that one ends. +#! @param this The iterator. +#! @returns Maybe the element; otherwise, `nothing`. +pub def flat_mapped::next(&mut this): maybe { + while true { + if this._inner is some(&mut inner) { + if inner.next() is some(x) { + return move(&mut x); + } + } + if this._from.next() is not some(y) { + return nothing {}; + } + this._inner = this._f(move(&mut y)); + } + return nothing {}; +} + +#! What `copied` makes: a copy of what each reference refers to. +#! @tparam X What the references refer to. +#! @tparam I The iterator of references it adapts. +pub struct copying : iterator where I: iterator<&X> { + var _from: I; +} + +#! Gives a copy of what the next reference refers to. +#! @param this The iterator. +#! @returns Maybe the copy; otherwise, `nothing`. +pub def copying::next(&mut this): maybe { + if this._from.next() is some(r) { + return copy(r); + } + return nothing {}; +} + +#! How many elements it has left, which are what it adapts has. +#! @param this The iterator. +#! @returns How many. +pub def copying::remaining(&this): u64 where I: sized_iterator<&X> { + return this._from.remaining(); +} + +#! Gives a copy of what the reference at the far end refers to. +#! @param this The iterator. +#! @returns Maybe the copy; otherwise, `nothing`. +pub def copying::next_back(&mut this): maybe where I: backward_iterator<&X> { + if this._from.next_back() is some(r) { + return copy(r); + } + return nothing {}; +} + +#! What `inspect` makes: the elements as they are, after a function is called on +#! each. +#! @tparam T What it gives. +#! @tparam I The iterator it adapts. +#! @tparam F The function. +pub struct inspected : iterator where I: iterator where F: invokable { + var _from: I; + var _f: F; +} + +#! Gives the next element, once the function has seen it. +#! @param this The iterator. +#! @returns Maybe the element; otherwise, `nothing`. +pub def inspected::next(&mut this): maybe { + if this._from.next() is some(x) { + this._f(&x); + return move(&mut x); + } + return nothing {}; +} + +#! How many elements it has left, which are what it adapts has. +#! @param this The iterator. +#! @returns How many. +pub def inspected::remaining(&this): u64 where I: sized_iterator { + return this._from.remaining(); +} + +#! Gives the element at the far end, once the function has seen it. +#! @param this The iterator. +#! @returns Maybe the element; otherwise, `nothing`. +pub def inspected::next_back(&mut this): maybe where I: backward_iterator { + if this._from.next_back() is some(x) { + this._f(&x); + return move(&mut x); + } + return nothing {}; +} diff --git a/core/iterators/range.sakura b/core/iterators/range.sakura new file mode 100644 index 00000000..f4adf2e0 --- /dev/null +++ b/core/iterators/range.sakura @@ -0,0 +1,165 @@ +#! @file range.sakura +#! @author John Christman (sorakatadzuma@gmail.com) +#! @copyright Malunal Studios, LLC. +#! @license MIT +#! +#! Contains the methods of `range`, the integers from a start up to an end, or +#! the members of an enum between two, which `a..b` and `a..=b` make wherever +#! they are written as a value. +#! +#! `range` is among the types the syntax makes, which the compiler declares +#! itself. It is an iterator, walked forward or from its far end, that knows how +#! many it has left, so `(0..n).rev()` and `(0..n).step(2)` count as a loop +#! would. A `for` loop over `a..b` written in place counts without making one. +#! +#! A range of an enum's members gives them in the order of their values, each +#! value once, passing over those no member has, as `color::red..=color::blue` +#! gives `red`, `green`, and `blue` of `enum color { red, green = 4, blue }`. + +module core; + + +#! The place of a member of an enum among the values of its members, from 0 for +#! the least, each value counted once. +#! @tparam T The enum. +#! @param member The member. +#! @returns Its place. +@intrinsic +def rank_of(member: T): u64; + +#! The member of an enum at a place among the values of its members, as +#! `rank_of` gives it. +#! @tparam T The enum. +#! @param rank The place, before the count of the members' values. +#! @returns The member. +@intrinsic +def member_at(rank: u64): T; + +#! The value a number of places past another, as a range counts: the integer +#! that far past it, or the member of an enum that many members past it. +#! @tparam T The integer type, or the enum. +#! @param from The value to count from. +#! @param n How many places past it. +#! @returns The value. +def range::past(from: T, n: u64): T { + if const T is integer { + return ((from as u64) + n) as T; + } + return member_at::(rank_of(from) + n); +} + +#! How many places a range counts from one value up to another, which does not +#! come before it. +#! @tparam T The integer type, or the enum. +#! @param from The first value. +#! @param to The value it counts up to. +#! @returns How many. +def range::between(from: T, to: T): u64 { + if const T is integer { + return (to as u64) - (from as u64); + } + return rank_of(to) - rank_of(from); +} + + +#! Gives the next value, counting up from the start. +#! @param this The range. +#! @returns Maybe the value; otherwise, `nothing` once it has given them all. +pub def range::next(&mut this): maybe { + if this.start < this.end { + val at := this.start; + if const T is integer { + this.start++; + } else { + this.start = range::::past(at, 1); + } + return at; + } + if this._last && this.start == this.end { + this._last = false; + return this.end; + } + return nothing {}; +} + +#! Gives the value at the far end, counting down from the end. +#! @param this The range. +#! @returns Maybe the value; otherwise, `nothing` once the ends have met. +pub def range::next_back(&mut this): maybe { + if this._last && !(this.end < this.start) { + this._last = false; + return this.end; + } + if this.start < this.end { + if const T is integer { + this.end--; + } else { + this.end = member_at::(rank_of(this.end) - 1); + } + return this.end; + } + return nothing {}; +} + +#! How many values it has left to give. +#! @param this The range. +#! @returns How many. +pub def range::remaining(&this): u64 { + var made: u64 = this.start < this.end ? range::::between(this.start, this.end) : 0; + if this._last && !(this.end < this.start) { + made++; + } + return made; +} + +#! How many values it has left to give, as `remaining` says. +#! @param this The range. +#! @returns How many. +pub val range::length: u64 { + get => this.remaining(); +} + +#! Whether it has given every value, or had none to give. +#! @param this The range. +#! @returns Whether it has none left. +pub def range::is_empty(&this): bool { + return !(this.start < this.end) && !(this._last && this.start == this.end); +} + +#! Whether a value is among those it has left to give. +#! @param this The range. +#! @param x The value. +#! @returns Whether it is. +pub def range::contains(&this, x: T): bool { + return !(x < this.start) && (x < this.end || (this._last && x == this.end)); +} + +#! The value `n` along, counting from 0, passing over those before it at once. +#! @param this The range. +#! @param n How many to pass over first. +#! @returns Maybe the value; otherwise, `nothing` where it has fewer left. +pub def range::nth(&mut this, n: u64): maybe { + val held: u64 = this.start < this.end ? range::::between(this.start, this.end) : 0; + if n < held { + this.start = range::::past(this.start, n); + return this.next(); + } + if this.start < this.end { + this.start = this.end; + } + return this.next() if n == held; + this._last = false; + return nothing {}; +} + +#! Gives every value it has left at once, counting them. +#! @param this The range. +#! @returns How many it had left. +pub def range::count(&mut this): u64 { + val made := this.remaining(); + if this.start < this.end { + this.start = this.end; + } + this._last = false; + return made; +} diff --git a/core/iterators/text.sakura b/core/iterators/text.sakura new file mode 100644 index 00000000..6d6b79c1 --- /dev/null +++ b/core/iterators/text.sakura @@ -0,0 +1,201 @@ +#! @file text.sakura +#! @author John Christman (sorakatadzuma@gmail.com) +#! @copyright Malunal Studios, LLC. +#! @license MIT +#! +#! Contains text walked lazily, each piece a view into the text as it is +#! reached, without a vector of them: its runs between a byte, its lines, its +#! words, and its code points. `.to_vector()` gives the pieces as a vector. + +module core; + + +#! Splits text by a byte, giving a view of each run between them in turn: one +#! more than there are of the byte, so `"a,,b"` gives `a`, an empty run, and +#! `b`, and empty text gives one empty run. +#! @param this The text to split. +#! @param delim The byte to split by, which no run holds. +#! @returns The runs, each viewing into the text, so they are only good for as +#! long as it is. +pub def strview::split(&this, delim: u8): splits { + return splits { _left = this, _delim = delim, _done = false }; +} + +#! Splits the text by a byte, giving a view of each run between them in turn. +#! @param this The string to split. +#! @param delim The byte to split by, which no run holds. +#! @returns The runs, each viewing into the string, so they are only good until +#! it grows, shrinks, or closes. +pub def string::split(&this, delim: u8): splits { + return this.view().split(delim); +} + +#! What `split` gives: the runs of text between each of a byte, from the front +#! or the far end. +pub struct splits : backward_iterator { + var _left: strview; #! The text not yet given. + var _delim: u8; #! The byte split by. + var _done: bool; #! Whether the last run has been given. +} + +#! A split that gives no runs at all, as of what has nothing to split. +#! @returns The split. +pub def splits::empty(): splits { + return splits { _left = strview::empty(), _delim = 0, _done = true }; +} + +#! Gives the next run, up to the next of the byte or the end of the text. +#! @param this The split. +#! @returns Maybe a view of the run; otherwise, `nothing` once the last is given. +pub def splits::next(&mut this): maybe { + return nothing {} if this._done; + val text := this._left; + val at := find_byte(text._dat, 0, text._len, this._delim); + if at == text._len { + this._done = true; + return text; + } + this._left = text.substr(at + 1, text._len - at - 1); + return text.substr(0, at); +} + +#! Gives the run at the far end, back to the last of the byte or the front of +#! what is left. +#! @param this The split. +#! @returns Maybe a view of the run; otherwise, `nothing` once the last is given. +pub def splits::next_back(&mut this): maybe { + return nothing {} if this._done; + val text := this._left; + val at := find_last_byte(text._dat, 0, text._len, this._delim); + if at == text._len { + this._done = true; + return text; + } + this._left = text.substr(0, at); + return text.substr(at + 1, text._len - at - 1); +} + +#! Gives each line of text without the `\n` that ends it or a `\r` before that, +#! as reading a stream's lines does: a last line without a line break is still a +#! line, and text ending in one has no empty line after it. +#! @param this The text to walk. +#! @returns The lines, each viewing into the text. +pub def strview::lines(&this): text_lines { + return text_lines { _left = this }; +} + +#! What `lines` gives: each line of text. +pub struct text_lines : iterator { + var _left: strview; #! The text not yet given. +} + +#! Gives the next line. +#! @param this The lines. +#! @returns Maybe a view of the line; otherwise, `nothing` once the text ends. +pub def text_lines::next(&mut this): maybe { + val text := this._left; + return nothing {} if text._len == 0; + val at := find_byte(text._dat, 0, text._len, '\n'); + var line := text.substr(0, at); + this._left = at == text._len ? text.substr(text._len, 0) : text.substr(at + 1, text._len - at - 1); + if at < text._len && line._len > 0 && line[line._len - 1] == '\r' { + line = line.substr(0, line._len - 1); + } + return line; +} + +#! Gives each word of text: each run between whitespace, as `is_space` says, +#! which no word holds. +#! @param this The text to walk. +#! @returns The words, each viewing into the text. +pub def strview::words(&this): text_words { + return text_words { _left = this }; +} + +#! What `words` gives: each run of text between whitespace. +pub struct text_words : iterator { + var _left: strview; #! The text not yet given. +} + +#! Gives the next word. +#! @param this The words. +#! @returns Maybe a view of the word; otherwise, `nothing` once the text ends. +pub def text_words::next(&mut this): maybe { + val text := this._left; + var start: u64 = 0; + while start < text._len && text[start].is_space { + start++; + } + var end := start; + while end < text._len && !text[end].is_space { + end++; + } + this._left = text.substr(end, text._len - end); + return nothing {} if start == end; + return text.substr(start, end - start); +} + +#! Gives each code point of text, decoding UTF-8. A byte that begins no +#! character, as one past a sequence's end, or a sequence that is cut short, +#! too long for its value, or a surrogate's, gives U+FFFD, one for each byte +#! that starts none. +#! @param this The text to walk. +#! @returns The code points. +pub def strview::chars(&this): code_points { + return code_points { _left = this }; +} + +#! What `chars` gives: each code point of UTF-8 text. +pub struct code_points : iterator { + var _left: strview; #! The text not yet given. +} + +#! What a malformed byte gives, U+FFFD. +const replacement: u32 = 0xFFFD; + +#! Gives the next code point. +#! @param this The code points. +#! @returns Maybe the code point; otherwise, `nothing` once the text ends. +pub def code_points::next(&mut this): maybe { + val text := this._left; + return nothing {} if text._len == 0; + val lead := text[0]; + if lead < 0x80 { + this._left = text.substr(1, text._len - 1); + return lead as u32; + } + + # How many bytes follow the lead, what it gives of the value, and the least + # value that many encode, below which the sequence is too long. + var follow: u64 = 0; + var value: u32 = 0; + var least: u32 = 0; + if (lead & 0xE0) == 0xC0 { + follow = 1; + value = (lead & 0x1F) as u32; + least = 0x80; + } else if (lead & 0xF0) == 0xE0 { + follow = 2; + value = (lead & 0x0F) as u32; + least = 0x800; + } else if (lead & 0xF8) == 0xF0 { + follow = 3; + value = (lead & 0x07) as u32; + least = 0x10000; + } + + var valid := follow != 0 && follow < text._len; + for k in 1..=follow { + break if !valid; + val byte := text[k]; + valid = (byte & 0xC0) == 0x80; + value = (value << 6) | (byte & 0x3F) as u32; + } + valid = valid && value >= least && value <= 0x10FFFF && (value < 0xD800 || value > 0xDFFF); + if !valid { + this._left = text.substr(1, text._len - 1); + return replacement; + } + this._left = text.substr(follow + 1, text._len - follow - 1); + return value; +} diff --git a/core/mem.sakura b/core/mem.sakura new file mode 100644 index 00000000..4826ad26 --- /dev/null +++ b/core/mem.sakura @@ -0,0 +1,422 @@ +#! @file mem.sakura +#! @author John Christman (sorakatadzuma@gmail.com) +#! @copyright Malunal Studios, LLC. +#! @license MIT +#! +#! Contains what a program manages memory with itself: the sizes and alignments +#! of types, allocating, resizing, and releasing blocks, reaching through +#! pointers, and copying, filling, and comparing bytes. +#! +#! A block is the program's until it releases it, and nothing keeps one alive: +#! a pointer or a reference into one is good while the block is, and using one +#! past that is the program's mistake. Owners such as `box`, `rc`, `arc`, and +#! the containers release what they allocate where they close. + +import core::swar; +module core; + +#! The number of bytes a value of a type takes in memory, which the compiler +#! gives. +#! @tparam T The type to measure. +#! @returns Its size in bytes, known while compiling. +@intrinsic +pub def size_of(): u64; + +#! The alignment a value of a type needs in memory, which the compiler gives. +#! @tparam T The type to measure. +#! @returns Its alignment in bytes, known while compiling. +@intrinsic +pub def align_of(): u64; + +#! The widest alignment any type needs, which `raw_allocate` aligns every block +#! to. +pub const max_align := 16u; + +#! Allocates a block of bytes from the program's heap, as C's `malloc` does, +#! without clearing it, for what is written before it is read. +#! @param size The number of bytes to allocate. +#! @returns The first byte of the block, aligned to `max_align`, which may hold +#! anything at first. +#! @remarks Where the system gives no memory, the program stops, so this never +#! gives `null` where any memory was asked for. Reading a byte before +#! writing it is the program's mistake, which `run --checks` stops at. +@intrinsic +pub def raw_allocate(size: u64): *mut u8; + +#! Allocates a block of zeroed bytes from the program's heap, as C's `calloc` +#! does. Memory the system gives fresh is zero already, so only a block used +#! before is cleared. +#! @param size The number of bytes to allocate. +#! @returns The first byte of the block, aligned to `max_align`. +#! @remarks Where the system gives no memory, the program stops, as +#! `raw_allocate` does. +@intrinsic +pub def raw_allocate_zeroed(size: u64): *mut u8; + +# Allocates a block a value of a type is written into: zeroed where the type +# closes, since writing it closes what the block held, and as it is otherwise. +def allocate_for(size: u64): *mut u8 { + if const T is closeable { + return raw_allocate_zeroed(size); + } + return raw_allocate(size); +} + +#! Releases a block allocated by `raw_allocate`, `raw_allocate_zeroed`, or +#! `raw_resize`. +#! @param pointer The first byte of the block, or `null`, which does nothing. +#! @remarks Releasing a block twice stops the program. +@intrinsic +pub def raw_release(pointer: *mut u8): void; + +#! Moves an allocated block to one of another size, keeping as many bytes as +#! fit, then releases the old one. +#! @param pointer The first byte of the block, or `null` to allocate a new +#! one as `raw_allocate` does. +#! @param size The number of bytes the new block holds. +#! @returns The first byte of the new block, which may hold anything past what +#! was kept. It may be the old block, where that is large enough +#! already. +#! @remarks Where the system gives no memory, the program stops, as +#! `raw_allocate` does. +@intrinsic +pub def raw_resize(pointer: *mut u8, size: u64): *mut u8; + +#! A reference that reads what a pointer points at. +#! +#! A pointer is an address with no members of its own, so this reaches them, as +#! `through(node).next` does, the same as `(*node).next`. +#! @tparam T The type pointed at. +#! @param pointer The pointer to read through. +#! @returns A reference that only reads what the pointer points at. +#! @remarks A null pointer stops the program. +pub def through(pointer: *T): &T { + return &pointer[0]; +} + +#! A reference that writes what a pointer points at, as `through(node).next = +#! null` does. +#! @tparam T The type pointed at. +#! @param pointer The pointer to write through. +#! @returns A reference that writes what the pointer points at. +#! @remarks A null pointer stops the program. +pub def through(pointer: *mut T): &mut T { + return &mut pointer[0]; +} + +#! A pointer that writes what a reference refers to, as `through` gives a +#! reference at what a pointer points at, as `address(node)` is `&mut node as +#! *mut node`. Given a place, a call lends it, as `address(x)` does a `var x`. +#! @tparam T The type referred to. +#! @param value The reference. +#! @returns A pointer at what the reference refers to, which keeps nothing alive. +pub def address(value: &mut T): *mut T { + return value as *mut T; +} + +#! A pointer that reads what a reference refers to, as `address(x)` is of a +#! `val x`. +#! @tparam T The type referred to. +#! @param value The reference. +#! @returns A pointer at what the reference refers to, which keeps nothing alive. +pub def address(value: &T): *T { + return value as *T; +} + +# The bytes a number of elements take, or more than can be allocated when that +# overflows, so the allocation stops the program instead of being too small. +#! The bytes a number of elements of a type take. +#! @tparam T The type of the elements. +#! @param count How many elements. +#! @returns Their size in bytes, or the largest `u64` where that overflows, so +#! that allocating it stops the program rather than giving too small a +#! block. +pub def bytes_of(count: u64): u64 { + val size := size_of::(); + if size != 0 && count > 0xFFFFFFFFFFFFFFFF / size { + return 0xFFFFFFFFFFFFFFFF; + } + return count * size; +} + +#! Rounds an address up to the next multiple of an alignment. +#! @param addr The address to align. +#! @param align The alignment, which is a power of two. +#! @returns The address, or the next past it that is a multiple of the +#! alignment. +pub def align(addr: u64, align: u64): u64 { + return (addr + (align - 1)) & ~(align - 1); +} + +#! Copies bytes from one buffer into another. +#! @param dst The first byte to copy to. +#! @param src The first byte to copy from. +#! @param len How many bytes to copy. +#! @returns The destination, `dst`. +#! @remarks The buffers may overlap. Either pointer being `null` copies nothing. +pub def memcpy(dst: *mut u8, src: *u8, len: u64): *mut u8 { + if dst == null || src == null { return dst; } + if dst == src || len == 0 { return dst; } + if len >= 8 { + return (dst as u64) - (src as u64) >= len + ? copyfwd(dst, src, len) + : copybwd(dst, src, len); + } + + if len >= 4 { + val head := *(src as *u32); + val tail := *((src + len - 4) as *u32); + *(dst as *mut u32) = head; + *((dst + len - 4) as *mut u32) = tail; + return dst; + } + + if len >= 2 { + val head := *(src as *u16); + val tail := *((src + len - 2) as *u16); + *(dst as *mut u16) = head; + *((dst + len - 2) as *mut u16) = tail; + return dst; + } + + *dst = *src; + return dst; +} + +#! Sets every byte of a buffer to one value. +#! @param dst The first byte to set. +#! @param data The value to set each byte to. +#! @param len How many bytes to set. +#! @returns The destination, `dst`. +#! @remarks The bytes are set a word at a time, each word the byte repeated, and +#! the last word ends where the buffer does, over what the words before +#! it set, so no byte is set alone. A buffer shorter than a word is set +#! by two halves of one, which overlap the same way. A `null` +#! destination sets nothing. +pub def memset(dst: *mut u8, data: u8, len: u64): *mut u8 { + if dst == null { return dst; } + if len == 0 { return dst; } + + val end := dst + len; + # Where vectors are held in registers, 16 bytes at a time, the last ending + # where the buffer does. + if len >= 32 && lanes_held() { + val pattern := u8x16::splat(data); + var at := dst; + val last := end - 16; + while at < last { + lanes_apply::(at, (&pattern._lanes) as *u8, null, null); + at = at + 16; + } + lanes_apply::(last, (&pattern._lanes) as *u8, null, null); + return dst; + } + if len >= 8 { + val word := (data as u64) * 0x0101010101010101; + var each := dst as *mut u64; + val last := each + (len >> 3); + while each < last { *each++ = word; } + *((end - 8) as *mut u64) = word; + return dst; + } + + if len >= 4 { + val half := (data as u32) * 0x01010101; + *(dst as *mut u32) = half; + *((end - 4) as *mut u32) = half; + return dst; + } + + if len >= 2 { + val pair := (data as u16) * 0x0101; + *(dst as *mut u16) = pair; + *((end - 2) as *mut u16) = pair; + return dst; + } + + *dst = data; + return dst; +} + +#! Compares the bytes of two buffers, in order, as unsigned numbers. +#! @param bpa The first byte of the first buffer. +#! @param bpb The first byte of the second buffer. +#! @param len How many bytes to compare. +#! @retval -1 Where the first buffer orders before the second. +#! @retval 0 Where their bytes are the same. +#! @retval 1 Where the first buffer orders after the second. +#! @remarks Where either is `null`, the pointers themselves are compared. +pub def memcmp(bpa: *u8, bpb: *u8, len: u64): i64 { + if bpa == null || bpb == null { + if bpa < bpb { return -1; } + if bpa > bpb { return 1; } + return 0; + } + + # Whole words first, then what is left a byte at a time, and the word that + # differs a byte at a time to say which way. Fewer than eight bytes that are the + # same are found so with two words of half or a quarter as many, which may overlap. + var p := bpa; + var q := bpb; + var i := len; + # Where vectors are held in registers, 16 bytes at a time, the first that + # differs found from the lanes that do. + while i >= 16 && lanes_held() { + var a: u8x16; + var b: u8x16; + lanes_apply::((&mut a._lanes) as *mut u8, p, null, null); + lanes_apply::((&mut b._lanes) as *mut u8, q, null, null); + val same := a.equal(&b).bits(); + if same != 0xFFFF { + val k := trailing_zeros(~same) as u64; + return p[k] < q[k] ? -1 : 1; + } + p = p + 16; + q = q + 16; + i = i - 16; + } + while i >= 8 && *(p as *u64) == *(q as *u64) { + p = p + 8; + q = q + 8; + i = i - 8; + } + if i >= 4 && i < 8 && *(p as *u32) == *(q as *u32) && *((p + i - 4) as *u32) == *((q + i - 4) as *u32) { + return 0; + } + if i >= 2 && i < 4 && *(p as *u16) == *(q as *u16) && *((p + i - 2) as *u16) == *((q + i - 2) as *u16) { + return 0; + } + while i > 0 { + val a := *p++; + val b := *q++; + if a != b { return a < b ? -1 : 1; } + i--; + } + return 0; +} + +# The first place from `from` up to `end` where the bytes hold one byte, or +# `end` where none does: sixteen at a time where vectors are held in registers, +# the first found from the bits of those that are it, then eight at a time as +# words, and the last few as one word read without passing the end. +def find_byte(data: *u8, from: u64, end: u64, byte: u8): u64 { + var at := from; + if lanes_held() { + val wanted := u8x16::splat(byte); + while at + 16 <= end { + var chunk: u8x16; + lanes_apply::((&mut chunk._lanes) as *mut u8, data + at, null, null); + val found := chunk.equal(&wanted).bits(); + if found != 0 { + return at + trailing_zeros(found) as u64; + } + at += 16; + } + } + val wanted := swar::repeat(byte); + while at + 8 <= end { + val word: swar::bytes8 = swar::load(data + at) ^ wanted; + val found := word.zero(); + return at + found.first() if found.any(); + at += 8; + } + if at < end { + val word: swar::bytes8 = swar::load_last(data + at, end - at) ^ wanted; + val found: swar::mask8 = word.zero() & swar::mask8::leading(end - at); + return at + found.first() if found.any(); + } + return end; +} + +# The last place from `from` up to `end` where the bytes hold one byte, or +# `end` where none does: eight at a time as words from the end back, and the +# first few as one word read without passing their beginning. +def find_last_byte(data: *u8, from: u64, end: u64, byte: u8): u64 { + val wanted := swar::repeat(byte); + var at := end; + while at >= from + 8 { + val word: swar::bytes8 = swar::load(data + at - 8) ^ wanted; + val found := word.zero(); + return at - 8 + found.last() if found.any(); + at -= 8; + } + if at > from { + val word: swar::bytes8 = swar::load_last(data + from, at - from) ^ wanted; + val found: swar::mask8 = word.zero() & swar::mask8::leading(at - from); + return from + found.last() if found.any(); + } + return end; +} + +# How many of the bytes from `from` up to `end` are one byte: eight at a time +# as words, and the last few as one word read without passing the end. +def count_byte(data: *u8, from: u64, end: u64, byte: u8): u64 { + val wanted := swar::repeat(byte); + var count: u64 = 0; + var at := from; + while at + 8 <= end { + val word: swar::bytes8 = swar::load(data + at) ^ wanted; + count += word.zero().count(); + at += 8; + } + if at < end { + val word: swar::bytes8 = swar::load_last(data + at, end - at) ^ wanted; + val found: swar::mask8 = word.zero() & swar::mask8::leading(end - at); + count += found.count(); + } + return count; +} + +# Copies at least a word from the first byte up, a word at a time, each read before +# it is written, so a destination below the source never writes over what is left +# to read. The last word ends where the buffers do, read before anything is written. +def copyfwd(dst: *mut u8, src: *u8, len: u64): *mut u8 { + # Where vectors are held in registers, 16 bytes at a time, the same way. + if len >= 32 && lanes_held() { + var last: u8x16; + lanes_apply::((&mut last._lanes) as *mut u8, src + len - 16, null, null); + var to := dst; + var from := src; + val end := dst + len - 16; + while to < end { + lanes_apply::(to, from, null, null); + to = to + 16; + from = from + 16; + } + lanes_apply::(end, (&last._lanes) as *u8, null, null); + return dst; + } + val tail := *((src + len - 8) as *u64); + var dw := dst as *mut u64; + var sw := src as *u64; + val last := dw + (len >> 3); + while dw < last { *dw++ = *sw++; } + *((dst + len - 8) as *mut u64) = tail; + return dst; +} + +# Copies at least a word from the last byte down, so a destination above the source +# never writes over what is left. The first word begins where the buffers do, read +# before anything is written. +def copybwd(dst: *mut u8, src: *u8, len: u64): *mut u8 { + if len >= 32 && lanes_held() { + var first: u8x16; + lanes_apply::((&mut first._lanes) as *mut u8, src, null, null); + var to := dst + len; + var from := src + len; + while to > dst + 16 { + to = to - 16; + from = from - 16; + lanes_apply::(to, from, null, null); + } + lanes_apply::(dst, (&first._lanes) as *u8, null, null); + return dst; + } + val head := *(src as *u64); + var dw := (dst + len) as *mut u64; + var sw := (src + len) as *u64; + val first := dw - (len >> 3); + while dw > first { *--dw = *--sw; } + *(dst as *mut u64) = head; + return dst; +} diff --git a/core/owners/box.sakura b/core/owners/box.sakura new file mode 100644 index 00000000..d91a6b89 --- /dev/null +++ b/core/owners/box.sakura @@ -0,0 +1,87 @@ +#! @file box.sakura +#! @author John Christman (sorakatadzuma@gmail.com) +#! @copyright Malunal Studios, LLC. +#! @license MIT +#! +#! Contains `box`, one value on the heap, which it owns alone, as C++'s +#! `unique_ptr` and Rust's `Box`: for a value that outlives the scope making it +#! without being copied, one too large for a frame, or a structure linking to +#! more of itself. + +module core; + + +#! One value on the heap, which the box owns alone and closes where the box +#! closes. +#! +#! A box is one word, the value's address, which is never null, so a +#! `maybe>` is one word too, holding `nothing` where the address is +#! null. Moving a box moves the address, never the value, and leaves the box +#! moved from empty: closing it again does nothing, and reaching its value +#! reaches through `null`. +#! @tparam T What it holds. +pub struct box : owning, moveable { + var _at: &mut T; +} + +#! Moves a value to the heap. +#! @param value The value, which the box then owns. +#! @returns The box. +pub def box::new(value: T): box { + val size := size_of::(); + val at := allocate_for::(size == 0 ? 1 : size) as *mut T; + at[0] = move(&mut value); + return box:: { _at = through(at) }; +} + +#! Lends the value a box holds. +#! @param this The box. +#! @returns The value, good while the box holds it. +pub def box::get(&this): &T { + return this._at; +} + +#! Lends the value a box holds, to be changed. +#! @param this The box. +#! @returns The value, good while the box holds it. +pub def box::get(&mut this): &mut T { + return this._at; +} + +#! Whether a box holds a value, which one moved from or taken from does not. +#! @param this The box. +#! @returns Whether it does. +pub def box::holds(&this): bool { + return this._at as *T != null; +} + +#! Moves the value out of a box, giving back its memory. +#! @param this The box, which is empty after. +#! @returns The value. +pub def box::take(&mut this): T { + val at := this._at as *mut T; + var made := move(through(at)); + raw_release(at as *mut u8); + (this as *mut u64)[0] = 0; + return made; +} + +#! Closes the value a box holds and gives back its memory. +#! @param this The box, which is empty after, so closing it again does +#! nothing. +pub def box::close(&mut this): void { + val at := this._at as *mut T; + return if at == null; + (this as *mut u64)[0] = 0; + close(through(at)); + raw_release(at as *mut u8); +} + +#! Moves a box, leaving the one moved from empty. +#! @param other The box to move from. +#! @returns The box holding what it held. +pub def box::move_of(other: &mut box): box { + val made := box:: { _at = other._at }; + (other as *mut u64)[0] = 0; + return made; +} diff --git a/core/reflect.sakura b/core/reflect.sakura new file mode 100644 index 00000000..0d7b08e3 --- /dev/null +++ b/core/reflect.sakura @@ -0,0 +1,120 @@ +#! @file reflect.sakura +#! @author John Christman (sorakatadzuma@gmail.com) +#! @copyright Malunal Studios, LLC. +#! @license MIT +#! +#! Contains compile-time reflection: `decl`, which describes a declaration of +#! the program, and the intrinsics that find declarations, walk what they +#! declare, read their attributes, reach what they name, and report errors while +#! compiling. + +module core; + +#! Describes a declaration of the program, as the compiler found it. +#! +#! A `decl` is plain data, made only by the intrinsics below, the way +#! `call_site()` makes a `site`. Walked by `for const`, each one is known while +#! compiling, so `value_of(d)` and `x.(d)` reach what it declares as though its +#! name were written. +pub struct decl { + pub val id: u32; #! Which declaration. Meaningful only while compiling. + pub val kind: target; #! What it is, as the bit `@usage` checks attributes against. + pub val name: strview; #! As written: `interns_keywords`, `push`, `red`. + pub val path: strview; #! Qualified: `sakura::analyzer::interns_keywords`. + pub val at: site; #! Where it is declared. + pub val exported: bool; #! Whether it is `pub`. + pub val generic: bool; #! Whether it has type parameters of its own. +} + +#! Gives every declaration outside a function in the program, including methods, +#! a type's own constants and variables, and nested types, in the order the +#! files were given and then the order they are written in. +#! +#! Only those the calling module could name are given, and those carrying an +#! attribute whose type the calling module declares, since writing that +#! attribute is consent for the module owning it to find and use what it marks. +#! @returns The declarations, which are known while compiling. +@intrinsic +pub def declarations(): span; + +#! Gives the declaration of a type, as `decl_of::>()`. +#! @tparam T The type, which is an instance where it is generic. +#! @returns Its declaration. +@intrinsic +pub def decl_of(): decl; + +#! Gives what a type declares: the fields of a struct or union, with the fields +#! of a spread in its place, the members of an enum, or what a trait requires, +#! and then the methods, properties, constants, variables, and nested types +#! declared on it. +#! @param d The declaration of a type. +#! @returns The members, in the order they are declared. +@intrinsic +pub def members_of(d: decl): span; + +#! Gives the type a field, member, method, or a type's own declaration belongs +#! to. +#! @param d A declaration belonging to a type. +#! @returns The declaration of the type it belongs to. +@intrinsic +pub def owner_of(d: decl): decl; + +#! Gives the declarations of every attribute written on a declaration, in the +#! order they are written, each a constant whose value `value_of` reads. +#! @param d The declaration the attributes are written on. +#! @returns The attributes, each a constant whose value `value_of` reads. +@intrinsic +pub def attributes_of(d: decl): span; + +#! Gives the values of the `@A` attributes written on a declaration: often none, +#! and at most one unless the usage of `A` allows `many`. An alias also has +#! those of what it aliases, when the usage of `A` says `through`. +#! @tparam A The type of attribute to look for. +#! @param d The declaration the attributes are written on. +#! @returns Their values, which are known while compiling. +@intrinsic +pub def attached(d: decl): span where A: attribute; + +#! Stands for what a declaration names, as though its name were written here: a +#! function, a constant, a member of an enum, a global variable, or an +#! attribute's value. +#! +#! A generic function is given its type arguments after the call, as +#! `value_of(d)::`. +#! @param d The declaration, which must be known while compiling. +#! @remarks Its type is that of what it names, rather than the `void` it is +#! declared with. +@intrinsic +pub def value_of(d: decl): void; + +#! Gives the parameters of a function, including `this`, in the order they are +#! declared. `type_of(p)` is the type of each, written wherever a type is, as +#! `var fixture: type_of(params_of(d)[1]);`. Anything but a function has none. +#! @param d The declaration of a function. +#! @returns Its parameters, or none where it is not a function. +@intrinsic +pub def params_of(d: decl): span; + +#! Gives a type's name as errors spell it, without the modules of the types it +#! names, as `list` or `&mut position`. +#! @tparam T The type to name. +#! @returns Its name, which is known while compiling. +@intrinsic +pub def name_of(): strview; + +#! Gives a type's name with the module of each type it names, as +#! `std::containers::dict` or `&mut game::position`, +#! which no two types share, as `decl.path` qualifies `decl.name`. +#! @tparam T The type to name. +#! @returns Its name, which is known while compiling. +@intrinsic +pub def path_of(): strview; + +#! Reports an error while compiling, where checking reaches the call, which a +#! branch of `if const` that is not taken never does. +#! @param text What the error says, as text known while compiling, which may +#! be worked out, as interpolated text is. +#! @param at Where the error is, which a library gives as the `at` of a +#! declaration it was handed, to point at its user's code. +@intrinsic +pub def compile_error(text: strview, at: site = call_site()): void; diff --git a/core/results/maybe.sakura b/core/results/maybe.sakura new file mode 100644 index 00000000..26d68e85 --- /dev/null +++ b/core/results/maybe.sakura @@ -0,0 +1,286 @@ +#! @file maybe.sakura +#! @author John Christman (sorakatadzuma@gmail.com) +#! @copyright Malunal Studios, LLC. +#! @license MIT +#! +#! Contains the properties and methods of `maybe`, and `something`, which wraps +#! a value in one. +#! +#! `maybe`, which holds a value or `nothing`, is among the types the syntax +#! makes, which the compiler declares itself, as it does `i64`: `none` comes +#! first, so a `maybe` left without a value holds nothing. A value converts to +#! a `maybe` of its type wherever one is wanted, and it is read by `is`, +#! `match`, or `else`, as `val x := find(key) else { return; };`. `nothing` is +#! apart from `void`, the value of what gives nothing, so `maybe` tells a +#! value missing from the value of `void`. +#! +#! The methods reading the value, as `unwrap`, move it out of what can be +#! written, as `move` does, so a `maybe` of what closes is left holding +#! nothing, and copy it out of what is only read, which a value that closes +#! refuses. Those making another value of it, as `map`, move it in, as an +#! iterator's adapters do: `as_ref` lends them what one that is only read +#! holds. + +module core; + + +#! Whether it holds a value. +#! @param this The `maybe`. +#! @returns Whether it does. +pub val maybe::is_some: bool { get => this is some; } + +#! Whether it holds nothing. +#! @param this The `maybe`. +#! @returns Whether it does. +pub val maybe::is_none: bool { get => this is none; } + +#! Whether it holds a value a test passes. +#! @tparam F The test. +#! @param this The `maybe`. +#! @param test The test, given a reference to the value. +#! @returns Whether it holds one that passes. +pub def maybe::is_some_and(&this, test: F): bool + where F: invokable +{ + return this is some(&value) && test(value); +} + +#! Gives the value it holds, moved out as `move` moves it, so one that closes +#! leaves it holding nothing. It stops the program where it holds nothing. +#! @param this The `maybe`. +#! @returns The value. +pub def maybe::unwrap(&mut this): T { + var held := move(this); + return move(value) if held is some(&mut value); + fault("A `maybe` holding nothing was unwrapped."); +} + +#! Gives a copy of the value it holds, which a value that closes refuses. It +#! stops the program where it holds nothing. +#! @param this The `maybe`. +#! @returns The value. +pub def maybe::unwrap(&this): T { + if const T is closeable { + copied::(); + } else { + return value if this is some(value); + } + fault("A `maybe` holding nothing was unwrapped."); +} + +#! Gives the value it holds, moved out as `unwrap` moves it. It stops the +#! program where it holds nothing, saying why. +#! @param this The `maybe`. +#! @param why What went wrong, where it holds nothing. +#! @returns The value. +pub def maybe::expect(&mut this, why: strview): T { + var held := move(this); + return move(value) if held is some(&mut value); + fault(why); +} + +#! Gives a copy of the value it holds, which a value that closes refuses. It +#! stops the program where it holds nothing, saying why. +#! @param this The `maybe`. +#! @param why What went wrong, where it holds nothing. +#! @returns The value. +pub def maybe::expect(&this, why: strview): T { + if const T is closeable { + copied::(); + } else { + return value if this is some(value); + } + fault(why); +} + +#! Gives the value it holds, moved out as `unwrap` moves it, or a fallback +#! where it holds nothing. +#! @param this The `maybe`. +#! @param fallback The value given where it holds nothing. +#! @returns The value, or the fallback. +pub def maybe::unwrap_or(&mut this, fallback: T): T { + var held := move(this); + return move(value) if held is some(&mut value); + return move(&mut fallback); +} + +#! Gives a copy of the value it holds, which a value that closes refuses, or a +#! fallback where it holds nothing. +#! @param this The `maybe`. +#! @param fallback The value given where it holds nothing. +#! @returns The value, or the fallback. +pub def maybe::unwrap_or(&this, fallback: T): T { + if const T is closeable { + copied::(); + } else { + return value if this is some(value); + } + return move(&mut fallback); +} + +#! Gives the value it holds, moved out as `unwrap` moves it, or what a +#! function makes where it holds nothing, which is called only then. +#! @tparam F The function. +#! @param this The `maybe`. +#! @param make The function, making the value where it holds nothing. +#! @returns The value, or what the function made. +pub def maybe::unwrap_or_else(&mut this, make: F): T where F: invokable { + var held := move(this); + return move(value) if held is some(&mut value); + return make(); +} + +#! Takes what it holds, leaving it holding nothing, whatever the value is. +#! @param this The `maybe`. +#! @returns What it held. +pub def maybe::take(&mut this): maybe { + var made := move(this); + this = nothing {}; + return made; +} + +#! Puts a value in it, in place of what it held. +#! @param this The `maybe`. +#! @param value The value it holds from now on. +#! @returns What it held before. +pub def maybe::replace(&mut this, value: T): maybe { + var made := move(this); + this = maybe:: { some = move(&mut value) }; + return made; +} + +#! Lends what it holds: a reference to the value, or nothing. +#! @param this The `maybe`. +#! @returns Maybe a reference to the value; otherwise, `nothing`. +pub def maybe::as_ref(&this): maybe<&T> { + return maybe::<&T> { some = value } if this is some(&value); + return nothing {}; +} + +#! Lends what it holds to be written: a reference to the value, or nothing. +#! @param this The `maybe`. +#! @returns Maybe a reference to the value; otherwise, `nothing`. +pub def maybe::as_mut(&mut this): maybe<&mut T> { + return maybe::<&mut T> { some = value } if this is some(&mut value); + return nothing {}; +} + +#! Makes a value of the value it holds, which a function is given, moved in. +#! @tparam U What the function makes. +#! @tparam F The function. +#! @param this The `maybe`, moved in as `unwrap` moves it. +#! @param f The function, called on the value where it holds one. +#! @returns Maybe what the function made; otherwise, `nothing`. +pub def maybe::map(&mut this, f: F): maybe where F: invokable { + var held := move(this); + return maybe:: { some = f(move(value)) } if held is some(&mut value); + return nothing {}; +} + +#! Gives what a function makes of the value it holds, which may be nothing: +#! the next step of work that may find nothing. +#! @tparam U What the function may make. +#! @tparam F The function. +#! @param this The `maybe`, moved in as `unwrap` moves it. +#! @param f The function, called on the value where it holds one. +#! @returns What the function gave; otherwise, `nothing`. +pub def maybe::and_then(&mut this, f: F): maybe where F: invokable> { + var held := move(this); + return f(move(value)) if held is some(&mut value); + return nothing {}; +} + +#! Keeps the value it holds where a test passes it. +#! @tparam F The test. +#! @param this The `maybe`, moved in as `unwrap` moves it. +#! @param test The test, given a reference to the value. +#! @returns Maybe the value; otherwise, `nothing` where it fails the test. +pub def maybe::filter(&mut this, test: F): maybe where F: invokable { + var held := move(this); + return held if held is some(&value) && test(value); + return nothing {}; +} + +#! Gives what it holds where it holds a value, and another `maybe` otherwise. +#! @param this The `maybe`, moved in as `unwrap` moves it. +#! @param other What is given where it holds nothing. +#! @returns It, or the other. +pub def maybe::or(&mut this, other: maybe): maybe { + var held := move(this); + return held if held is some; + return move(&mut other); +} + +#! Gives what it holds where it holds a value, and what a function makes +#! otherwise, which is called only then. +#! @tparam F The function. +#! @param this The `maybe`, moved in as `unwrap` moves it. +#! @param make The function, making what is given where it holds nothing. +#! @returns It, or what the function made. +pub def maybe::or_else(&mut this, make: F): maybe where F: invokable> { + var held := move(this); + return held if held is some; + return make(); +} + +#! Makes a `result` of it: the value it holds, or an error where it holds +#! nothing. +#! @tparam E The error's type. +#! @param this The `maybe`, moved in as `unwrap` moves it. +#! @param error The error, where it holds nothing. +#! @returns The result. +pub def maybe::ok_or(&mut this, error: E): result { + var held := move(this); + return result:: { value = move(value) } if held is some(&mut value); + return result:: { error = move(&mut error) }; +} + +#! Whether it holds what another does: both nothing, or equal values, as `==` +#! compares them. +#! @param this The `maybe`. +#! @param other The other. +#! @returns Whether they are equal. +#! @remarks A `maybe` of a type that is not `equatable` is an error where it is +#! compared. +pub def maybe::equals(&this, other: &maybe): bool { + if this is some(&mine) { + return other is some(&theirs) && equals::(mine, theirs); + } + return other is none; +} + +#! Hashes what it holds, so a `maybe` holding nothing hashes apart from one +#! holding a value. +#! @param this The `maybe`. +#! @returns The hash. +#! @remarks A `maybe` of a type that is not `hashable` is an error where it is +#! hashed. +pub def maybe::hash(&this): u64 { + return mix(1, hash::(value)) if this is some(&value); + return 0; +} + +#! Builds a copy of a `maybe`, holding a copy of its value, as `copy` makes it. +#! @param other The `maybe` to copy. +#! @returns The copy. +pub def maybe::copy_of(other: &maybe): maybe { + return maybe:: { some = copy::(value) } if other is some(&value); + return nothing {}; +} + +#! Refuses a copy of a value that closes, which a `maybe` or a `result` only +#! read would give of what it holds. +#! @tparam T The type of what it holds. +def copied(): void { + if const T is closeable { + compile_error("A `maybe` or `result` that is only read gives a copy of what it holds, which a value that closes refuses: call it on one that can be written, as a `var`, which moves the value out."); + } +} + +#! Wraps a value in a `maybe`, holding it. +#! @tparam T The type of the value. +#! @param data The value to hold. +#! @returns A `maybe` holding the value, as `some`. +pub def something(data: T): maybe { + return maybe:: { some = move(&mut data) }; +} diff --git a/core/results/result.sakura b/core/results/result.sakura new file mode 100644 index 00000000..e8a76ccf --- /dev/null +++ b/core/results/result.sakura @@ -0,0 +1,357 @@ +#! @file result.sakura +#! @author John Christman (sorakatadzuma@gmail.com) +#! @copyright Malunal Studios, LLC. +#! @license MIT +#! +#! Contains the properties and methods of `result`, and `ok` and `err`, which +#! make one holding a value or an error. +#! +#! `result`, which holds either the value an operation gave or the error that +#! stopped it, is among the types the syntax makes, which the compiler declares +#! itself. It must be handled where it is made, since letting it go would lose +#! the error it may hold: by `match`, by `is`, or by `else`, as +#! `val f := open(path) else (e) { return e; };`. +#! +#! The methods reading what it holds, as `unwrap`, move it out of what can be +#! written, as `move` does, and copy it out of what is only read, which a value +#! that closes refuses. Those making another `result` of it, as `map`, move it +#! in, as an iterator's adapters do: `as_ref` lends them what one that is only +#! read holds. Each makes what it gives by naming the field, so a `result` whose +#! value and error are of one type is told apart. + +module core; + + +#! Makes a result holding a value. +#! @param value The value to hold. +#! @returns The result, holding the value. +pub def result::ok(value: T): result { + return result:: { value = move(&mut value) }; +} + +#! Makes a result holding an error. +#! @param error The error to hold. +#! @returns The result, holding the error. +pub def result::err(error: E): result { + return result:: { error = move(&mut error) }; +} + +#! Whether it holds the value, where the work succeeded. +#! @param this The result. +#! @returns Whether it does. +pub val result::is_ok: bool { get => this is value; } + +#! Whether it holds the error, where the work failed. +#! @param this The result. +#! @returns Whether it does. +pub val result::is_err: bool { get => this is error; } + +#! Whether it holds a value a test passes. +#! @tparam F The test. +#! @param this The result. +#! @param test The test, given a reference to the value. +#! @returns Whether it holds one that passes. +pub def result::is_ok_and(&this, test: F): bool + where F: invokable +{ + return this is value(&held) && test(held); +} + +#! Whether it holds an error a test passes. +#! @tparam F The test. +#! @param this The result. +#! @param test The test, given a reference to the error. +#! @returns Whether it holds one that passes. +pub def result::is_err_and(&this, test: F): bool + where F: invokable +{ + return this is error(&held) && test(held); +} + +#! Gives the value it holds, moved out as `move` moves it. It stops the program +#! where it holds an error. +#! @param this The result. +#! @returns The value. +pub def result::unwrap(&mut this): T { + var held := move(this); + return move(got) if held is value(&mut got); + fault("A `result` holding an error was unwrapped."); +} + +#! Gives a copy of the value it holds, which a value that closes refuses. It +#! stops the program where it holds an error. +#! @param this The result. +#! @returns The value. +pub def result::unwrap(&this): T { + if const T is closeable { + copied::(); + } else { + return got if + this is value(got); + } + fault("A `result` holding an error was unwrapped."); +} + +#! Gives the value it holds, moved out as `unwrap` moves it. It stops the +#! program where it holds an error, saying why. +#! @param this The result. +#! @param why What went wrong, where it holds an error. +#! @returns The value. +pub def result::expect(&mut this, why: strview): T { + var held := move(this); + return move(got) if + held is value(&mut got); + fault(why); +} + +#! Gives a copy of the value it holds, which a value that closes refuses. It +#! stops the program where it holds an error, saying why. +#! @param this The result. +#! @param why What went wrong, where it holds an error. +#! @returns The value. +pub def result::expect(&this, why: strview): T { + if const T is closeable { + copied::(); + } else { + return got if + this is value(got); + } + fault(why); +} + +#! Gives the error it holds, moved out as `move` moves it. It stops the program +#! where it holds a value. +#! @param this The result. +#! @returns The error. +pub def result::unwrap_err(&mut this): E { + var held := move(this); + return move(got) if + held is error(&mut got); + fault("A `result` holding a value was unwrapped for its error."); +} + +#! Gives a copy of the error it holds, which an error that closes refuses. It +#! stops the program where it holds a value. +#! @param this The result. +#! @returns The error. +pub def result::unwrap_err(&this): E { + if const E is closeable { + copied::(); + } else { + return got if + this is error(got); + } + fault("A `result` holding a value was unwrapped for its error."); +} + +#! Gives the error it holds, moved out as `unwrap_err` moves it. It stops the +#! program where it holds a value, saying why. +#! @param this The result. +#! @param why What went wrong, where it holds a value. +#! @returns The error. +pub def result::expect_err(&mut this, why: strview): E { + var held := move(this); + return move(got) if + held is error(&mut got); + fault(why); +} + +#! Gives a copy of the error it holds, which an error that closes refuses. It +#! stops the program where it holds a value, saying why. +#! @param this The result. +#! @param why What went wrong, where it holds a value. +#! @returns The error. +pub def result::expect_err(&this, why: strview): E { + if const E is closeable { + copied::(); + } else { + return got if + this is error(got); + } + fault(why); +} + +#! Gives the value it holds, moved out as `unwrap` moves it, or a fallback +#! where it holds an error. +#! @param this The result. +#! @param fallback The value given where it holds an error. +#! @returns The value, or the fallback. +pub def result::unwrap_or(&mut this, fallback: T): T { + var held := move(this); + return move(got) if + held is value(&mut got); + return move(&mut fallback); +} + +#! Gives a copy of the value it holds, which a value that closes refuses, or a +#! fallback where it holds an error. +#! @param this The result. +#! @param fallback The value given where it holds an error. +#! @returns The value, or the fallback. +pub def result::unwrap_or(&this, fallback: T): T { + if const T is closeable { + copied::(); + } else { + return got if + this is value(got); + } + return move(&mut fallback); +} + +#! Gives the value it holds, moved out as `unwrap` moves it, or what a function +#! makes of the error, which it is called on only then. +#! @tparam F The function. +#! @param this The result. +#! @param make The function, given the error, moved out. +#! @returns The value, or what the function made. +pub def result::unwrap_or_else(&mut this, make: F): T where F: invokable { + var held := move(this); + return match held { + value(&mut got) => move(got), + error(&mut bad) => make(move(bad)) + }; +} + +#! Lends what it holds: a reference to the value or to the error. +#! @param this The result. +#! @returns The result of the references. +pub def result::as_ref(&this): result<&T, &E> { + return match this { + value(&got) => result::<&T, &E> { value = got }, + error(&bad) => result::<&T, &E> { error = bad } + }; +} + +#! Lends what it holds to be written: a reference to the value or to the +#! error. +#! @param this The result. +#! @returns The result of the references. +pub def result::as_mut(&mut this): result<&mut T, &mut E> { + return match this { + value(&mut got) => result::<&mut T, &mut E> { value = got }, + error(&mut bad) => result::<&mut T, &mut E> { error = bad } + }; +} + +#! Makes a value of the value it holds, which a function is given, moved in, +#! keeping the error it holds otherwise. +#! @tparam U What the function makes. +#! @tparam F The function. +#! @param this The result, moved in as `unwrap` moves it. +#! @param f The function, called on the value where it holds one. +#! @returns The result of what the function made, or of the error. +pub def result::map(&mut this, f: F): result + where F: invokable +{ + var held := move(this); + return match held { + value(&mut got) => result:: { value = f(move(got)) }, + error(&mut bad) => result:: { error = move(bad) } + }; +} + +#! Makes another error of the error it holds, which a function is given, moved +#! in, keeping the value it holds otherwise. +#! @tparam D What the function makes. +#! @tparam F The function. +#! @param this The result, moved in as `unwrap` moves it. +#! @param f The function, called on the error where it holds one. +#! @returns The result of the value, or of what the function made. +pub def result::map_err(&mut this, f: F): result + where F: invokable +{ + var held := move(this); + return match held { + value(&mut got) => result:: { value = move(got) }, + error(&mut bad) => result:: { error = f(move(bad)) } + }; +} + +#! Gives what a function makes of the value it holds, which may fail too: the +#! next step of work that may fail, keeping the error it holds otherwise. +#! @tparam U What the function may make. +#! @tparam F The function. +#! @param this The result, moved in as `unwrap` moves it. +#! @param f The function, called on the value where it holds one. +#! @returns What the function gave, or the result of the error. +pub def result::and_then(&mut this, f: F): result + where F: invokable> +{ + var held := move(this); + return match held { + value(&mut got) => f(move(got)), + error(&mut bad) => result:: { error = move(bad) } + }; +} + +#! Gives what a function makes of the error it holds, which may recover from +#! it, keeping the value it holds otherwise. +#! @tparam D The error of what the function makes. +#! @tparam F The function. +#! @param this The result, moved in as `unwrap` moves it. +#! @param f The function, called on the error where it holds one. +#! @returns The result of the value, or what the function gave. +pub def result::or_else(&mut this, f: F): result + where F: invokable> +{ + var held := move(this); + return match held { + value(&mut got) => result:: { value = move(got) }, + error(&mut bad) => f(move(bad)) + }; +} + +#! Gives the value it holds, as a `maybe`, losing the error. +#! @param this The result, moved in as `unwrap` moves it. +#! @returns Maybe the value; otherwise, `nothing` where it holds an error. +pub def result::to_maybe(&mut this): maybe { + var held := move(this); + return maybe:: { some = move(got) } if held is value(&mut got); + return nothing {}; +} + +#! Gives the error it holds, as a `maybe`, losing the value. +#! @param this The result, moved in as `unwrap` moves it. +#! @returns Maybe the error; otherwise, `nothing` where it holds a value. +pub def result::err_to_maybe(&mut this): maybe { + var held := move(this); + return maybe:: { some = move(got) } if held is error(&mut got); + return nothing {}; +} + +#! Whether it holds what another does: equal values, or equal errors, as `==` +#! compares them. +#! @param this The result. +#! @param other The other. +#! @returns Whether they are equal. +#! @remarks A `result` whose value or error is of a type that is not +#! `equatable` is an error where it is compared. +pub def result::equals(&this, other: &result): bool { + return match this { + value(&mine) => other is value(&theirs) && equals::(mine, theirs), + error(&mine) => other is error(&theirs) && equals::(mine, theirs) + }; +} + +#! Hashes what it holds, so a value hashes apart from an error. +#! @param this The result. +#! @returns The hash. +#! @remarks A `result` whose value or error is of a type that is not `hashable` +#! is an error where it is hashed. +pub def result::hash(&this): u64 { + return match this { + value(&got) => mix(1, hash::(got)), + error(&bad) => mix(2, hash::(bad)) + }; +} + +#! Builds a copy of a result, holding a copy of its value or its error, as +#! `copy` makes it. +#! @param other The result to copy. +#! @returns The copy. +pub def result::copy_of(other: &result): result { + return match other { + value(&got) => result:: { value = copy::(got) }, + error(&bad) => result:: { error = copy::(bad) } + }; +} diff --git a/core/simd.sakura b/core/simd.sakura new file mode 100644 index 00000000..6b86fa21 --- /dev/null +++ b/core/simd.sakura @@ -0,0 +1,1251 @@ +#! @file simd.sakura +#! @author John Christman (sorakatadzuma@gmail.com) +#! @copyright Malunal Studios, LLC. +#! @license MIT +#! +#! Contains `simd`, a vector of numbers one instruction works on lane by lane, +#! and `mask`, which lane comparisons give: `simd` is four `f32`s, 16 +#! bytes, and `simd` thirty-two bytes. A vector holds 16 or 32 bytes of +#! numbers, or 64 of 16 bits or more, and the aliases name each, as `f32x4`, +#! `u8x32`, and `f32x16`. +#! +#! Each operation is written here lane by lane, as the number's own operator +#! gives it, which is what the virtual machine and constants worked out while +#! compiling run. An executable asks the processor running it, once +#! as it starts, which vector instructions it has, and where it has those of an +#! operation, as SSE2 for most of 16 bytes, SSE4.1 for some, and AVX2 for 32, +#! works the lanes with them instead, and AVX-512's for 64. Where it has them +#! only for fewer bytes, a vector is worked a half or a quarter at a time, and +#! where it has none, as here. The bits are the same either way. +#! +#! The functions of real lanes, as `sqrt`, `floor`, and `fma`, are methods +#! `std::math` declares, as the functions of reals are. + +module core; + + +#! A vector of numbers, worked on lane by lane: `L` is the type of each lane, +#! and `N` how many lanes there are, as `simd` writes them, 16 or 32 +#! bytes in all, or 64 of at most 32 lanes. It is zero where nothing is written. +#! @tparam L The type of each lane, a number. +#! @tparam N How many lanes it has. +pub struct simd where L: numeric, ordered, zeroable { + var _lanes: L[N]; +} + +#! What comparing two vectors lane by lane gives: for each lane, every bit set +#! where it holds, and every bit clear where it does not, as the processor's +#! comparisons give it. +#! @tparam L The type of each lane of the vectors compared. +#! @tparam N How many lanes they have. +pub struct mask where L: numeric, ordered, zeroable { + var _lanes: L[N]; +} + +pub type f32x4 = simd; +pub type f32x8 = simd; +pub type f64x2 = simd; +pub type f64x4 = simd; +pub type i8x16 = simd; +pub type i8x32 = simd; +pub type u8x16 = simd; +pub type u8x32 = simd; +pub type i16x8 = simd; +pub type i16x16 = simd; +pub type u16x8 = simd; +pub type u16x16 = simd; +pub type i32x4 = simd; +pub type i32x8 = simd; +pub type u32x4 = simd; +pub type u32x8 = simd; +pub type i64x2 = simd; +pub type i64x4 = simd; +pub type u64x2 = simd; +pub type u64x4 = simd; +pub type f32x16 = simd; +pub type f64x8 = simd; +pub type i16x32 = simd; +pub type u16x32 = simd; +pub type i32x16 = simd; +pub type u32x16 = simd; +pub type i64x8 = simd; +pub type u64x8 = simd; + + +# Making and taking apart. + +#! The vector of an array's numbers, the first in lane 0. +#! @param lanes The numbers. +#! @returns The vector. +pub def simd::of(lanes: L[N]): simd { + return simd:: { _lanes = lanes }; +} + +#! The vector holding a number in every lane. +#! @param value The number. +#! @returns The vector. +pub def simd::splat(value: L): simd { + var made: simd; + val lane: L = value; + if !lanes_done::((&mut made._lanes) as *mut u8, (&lane) as *u8, null, null, 0, 0) { + var r: L[N]; + for i in 0..N { + r[i] = lane; + } + made._lanes = r; + } + return made; +} + +#! The vector of the numbers a view holds from a place, as many as it has lanes. +#! @param from The view. +#! @param at Where its first lane is read from. +#! @returns The vector. +#! @remarks Reading past the view's end stops the program, as indexing does. +pub def simd::load(from: span, at: u64): simd { + _ = from[at]; + _ = from[at + N - 1]; + return ((from._dat + at) as *simd)[0]; +} + +#! Writes the vector's lanes into a view from a place. +#! @param this The vector. +#! @param into The view. +#! @param at Where its first lane is written. +#! @remarks Writing past the view's end stops the program, as indexing does. +pub def simd::store(&this, into: slice, at: u64): void { + _ = into[at]; + _ = into[at + N - 1]; + val copied: simd = this; + ((into._dat + at) as *mut simd)[0] = copied; +} + +#! The vector's numbers as an array, lane 0 first. +#! @param this The vector. +#! @returns The array. +pub def simd::lanes(&this): L[N] { + return lanes_read(this); +} + +#! Reaches a lane, to read it, which `v[i]` does. +#! @param this The vector. +#! @param lane The lane, below how many there are. +#! @returns The lane. +#! @remarks A lane past the last stops the program. +pub def simd::at(&this, lane: u64): &L { + return &this._lanes[lane]; +} + +#! Reaches a lane, to write it, which `v[i] = x` does. +#! @param this The vector. +#! @param lane The lane, below how many there are. +#! @returns The lane. +#! @remarks A lane past the last stops the program. +pub def simd::at(&mut this, lane: u64): &mut L { + return &mut this._lanes[lane]; +} + +#! The lanes in another order: lane `i` of what it gives is lane `order[i]` of +#! the vector. +#! @param this The vector. +#! @param order For each lane, the lane it is taken from. +#! @returns The vector. +#! @remarks A lane past the last stops the program. +pub def simd::shuffle(&this, order: u8[N]): simd { + if lanes_have::() { + # The order, then zeros, as the instructions read 16 bytes of it. In a + # checked program, each lane it names one of the vector's, or the lanes are + # read one at a time, each checked as an index is. + var held: u8[32]; + ((&mut held) as *mut u8[N])[0] = order; + val named := ((&held) as *simd)[0]; + if !checking() || named.less(&simd::::splat(N as u8)).all() { + var made: simd; + lanes_apply::((&mut made._lanes) as *mut u8, (&this._lanes) as *u8, (&held) as *u8, null); + return made; + } + } + val a: L[N] = lanes_read(this); + var r: L[N]; + for i in 0..N { + r[i] = a[order[i] as u64]; + } + return simd:: { _lanes = r }; +} + +#! Each lane converted to another type of number, as `as` converts it: a real +#! made an integer rounds toward zero, as a 64-bit integer, which holds at its +#! limits where the real is past them and is 0 for NaN, and an integer narrower +#! than that keeps its low bits. +#! @tparam M The type of each lane of what it gives. +#! @param this The vector. +#! @returns The vector, of as many lanes. +pub def simd::convert(&this): simd where M: numeric, ordered, zeroable { + var worked: simd; + if within_integers::(this) { + return worked if lanes_to::((&mut worked._lanes) as *mut u8, (&this._lanes) as *u8, null); + } + val a: L[N] = lanes_read(this); + var r: M[N]; + for i in 0..N { + r[i] = a[i] as M; + } + return simd:: { _lanes = r }; +} + +#! The vector's bytes as a vector of other lanes, of the same size in all. +#! @tparam M The type of each lane of what it gives. +#! @tparam K How many lanes it has. +#! @param this The vector. +#! @returns The vector. +#! @remarks A vector of another size is refused while compiling. +pub def simd::bits(&this): simd where M: numeric, ordered, zeroable { + if const K * size_of::() != N * size_of::() { + compile_error("`bits` is asked for a vector of another size than the one it is called on."); + } + return ((&this._lanes) as *simd)[0]; +} + + +#! The first half of the vector's lanes, as a vector of half as many: of 32 +#! bytes, the first 16. +#! @param this The vector. +#! @returns The half. +pub def simd::low(&this): simd { + var made: simd; + return made if lanes_also::((&mut made._lanes) as *mut u8, (&this._lanes) as *u8, null); + return ((&this._lanes) as *simd)[0]; +} + +#! The second half of the vector's lanes, as a vector of half as many. +#! @param this The vector. +#! @returns The half. +pub def simd::high(&this): simd { + var made: simd; + return made if lanes_also::((&mut made._lanes) as *mut u8, (&this._lanes) as *u8, null); + return ((&this._lanes) as *simd)[1]; +} + +#! The vector of two vectors' lanes, the first's first: of two of 16 bytes, one +#! of 32. +#! @param low The first half. +#! @param high The second. +#! @returns The vector. +pub def simd::join(low: simd, high: simd): simd { + var made: simd; + return made if lanes_also::((&mut made._lanes) as *mut u8, (&low._lanes) as *u8, (&high._lanes) as *u8); + val halves := (&mut made._lanes) as *mut simd; + halves[0] = low; + halves[1] = high; + return made; +} + +#! The first half of the vector's lanes, each converted to a type twice as +#! wide, as `as` converts it: an integer to one of twice the bits, keeping its +#! value, or an `f32` to an `f64`. +#! @tparam M The type of each lane of what it gives. +#! @param this The vector. +#! @returns The vector, of half as many lanes, as many bytes. +pub def simd::widened(&this): simd where M: numeric, ordered, zeroable { + if const size_of::() != 2 * size_of::() { + compile_error("`widened` gives lanes twice as wide as the vector's."); + } + var made: simd; + return made if lanes_to::((&mut made._lanes) as *mut u8, (&this._lanes) as *u8, null); + val a: L[N] = lanes_read(this); + var r: M[N / 2]; + for i in 0..N / 2 { + r[i] = a[i] as M; + } + made._lanes = r; + return made; +} + +#! The second half of the vector's lanes, each converted to a type twice as +#! wide, as `widened` converts the first. +#! @tparam M The type of each lane of what it gives. +#! @param this The vector. +#! @returns The vector, of half as many lanes, as many bytes. +pub def simd::widened_high(&this): simd where M: numeric, ordered, zeroable { + if const size_of::() != 2 * size_of::() { + compile_error("`widened_high` gives lanes twice as wide as the vector's."); + } + var made: simd; + return made if lanes_to::((&mut made._lanes) as *mut u8, (&this._lanes) as *u8, null); + val a: L[N] = lanes_read(this); + var r: M[N / 2]; + for i in 0..N / 2 { + r[i] = a[N / 2 + i] as M; + } + made._lanes = r; + return made; +} + +#! The lanes of the vector and another, this one's first, each converted to a +#! type half as wide: an integer to one of half the bits, held at its least or +#! greatest where it is past them, as packing saturates it, or an `f64` to the +#! `f32` `as` rounds it to. +#! @tparam M The type of each lane of what it gives. +#! @param this The first vector. +#! @param other The second. +#! @returns The vector, of twice as many lanes, as many bytes as each. +pub def simd::narrowed(&this, other: &simd): simd where M: numeric, ordered, zeroable { + if const 2 * size_of::() != size_of::() { + compile_error("`narrowed` gives lanes half as wide as the vector's."); + } + var made: simd; + return made if lanes_to::((&mut made._lanes) as *mut u8, (&this._lanes) as *u8, (&other._lanes) as *u8); + val a: L[N] = lanes_read(this); + val b: L[N] = lanes_read(other); + var r: M[N * 2]; + for i in 0..N { + r[i] = saturated::(a[i]); + r[N + i] = saturated::(b[i]); + } + made._lanes = r; + return made; +} + +#! The lanes a view holds at the places another vector names: lane `i` is +#! `from[at[i]]`, which AVX2 reads at once. +#! @param from The view. +#! @param at Where each lane is read from. +#! @returns The vector. +#! @remarks A place below zero or past the view's end stops a checked program, +#! as indexing does. +pub def simd::gather(from: span, at: simd): simd { + var made: simd; + if lanes_have::() { + # In a checked program, each place below the length, as an unsigned number, + # so one below zero is past it too, or the lanes are read one at a time, + # each place checked as an index is. + val limit: u32 = from.length < 0xFFFFFFFF ? from.length as u32 : 0xFFFFFFFF; + if !checking() || at.bits::().less(&simd::::splat(limit)).all() { + val base := from._dat; + lanes_apply::((&mut made._lanes) as *mut u8, (&base) as *u8, (&at._lanes) as *u8, null); + return made; + } + } + val places: i32[N] = at.lanes(); + var r: L[N]; + for i in 0..N { + r[i] = from[places[i] as u64]; + } + made._lanes = r; + return made; +} + +#! Writes the vector's lanes into a view at the places another vector names: +#! lane `i` to `into[at[i]]`, a later lane's lasting where two places are one. +#! @param this The vector. +#! @param into The view. +#! @param at Where each lane is written. +#! @remarks A place below zero or past the view's end stops the program, as +#! indexing does, before any lane is written. +pub def simd::scatter(&this, into: slice, at: simd): void { + val places: i32[N] = at.lanes(); + for i in 0..N { + _ = into[places[i] as u64]; + } + val a: L[N] = lanes_read(this); + for i in 0..N { + into[places[i] as u64] = a[i]; + } +} + + +# Arithmetic, which the operators call. + +#! `a + b`, lane by lane. Integers wrap, as their own `+` does. +#! @param this The left vector. +#! @param other The right one. +#! @returns The sums. +pub def simd::add(&this, other: &simd): simd { + var made: simd; + if !lanes_done::((&mut made._lanes) as *mut u8, (&this._lanes) as *u8, (&other._lanes) as *u8, null, 16, 16) { + val a: L[N] = this._lanes; + val b: L[N] = other._lanes; + var r: L[N]; + for i in 0..N { + r[i] = a[i] + b[i]; + } + made._lanes = r; + } + return made; +} + +#! `a - b`, lane by lane. Integers wrap, as their own `-` does. +#! @param this The left vector. +#! @param other The right one. +#! @returns The differences. +pub def simd::sub(&this, other: &simd): simd { + var made: simd; + if !lanes_done::((&mut made._lanes) as *mut u8, (&this._lanes) as *u8, (&other._lanes) as *u8, null, 16, 16) { + val a: L[N] = this._lanes; + val b: L[N] = other._lanes; + var r: L[N]; + for i in 0..N { + r[i] = a[i] - b[i]; + } + made._lanes = r; + } + return made; +} + +#! `a * b`, lane by lane. Integers wrap, as their own `*` does. +#! @param this The left vector. +#! @param other The right one. +#! @returns The products. +pub def simd::mul(&this, other: &simd): simd { + var made: simd; + if !lanes_done::((&mut made._lanes) as *mut u8, (&this._lanes) as *u8, (&other._lanes) as *u8, null, 16, 16) { + val a: L[N] = this._lanes; + val b: L[N] = other._lanes; + var r: L[N]; + for i in 0..N { + r[i] = a[i] * b[i]; + } + made._lanes = r; + } + return made; +} + +#! `a / b`, lane by lane. An integer lane divided by zero stops the program, as +#! dividing the integer does, and has no instruction, so integers are divided a +#! lane at a time. +#! @param this The left vector. +#! @param other The right one. +#! @returns The quotients. +pub def simd::div(&this, other: &simd): simd { + var made: simd; + if !lanes_done::((&mut made._lanes) as *mut u8, (&this._lanes) as *u8, (&other._lanes) as *u8, null, 16, 16) { + val a: L[N] = this._lanes; + val b: L[N] = other._lanes; + var r: L[N]; + for i in 0..N { + r[i] = a[i] / b[i]; + } + made._lanes = r; + } + return made; +} + +#! `a % b`, lane by lane, as the number's own `%` gives it, a lane at a time. +#! @param this The left vector. +#! @param other The right one. +#! @returns The remainders. +pub def simd::rem(&this, other: &simd): simd { + var made: simd; + val a: L[N] = lanes_read(this); + val b: L[N] = lanes_read(other); + var r: L[N]; + for i in 0..N { + r[i] = a[i] % b[i]; + } + made._lanes = r; + return made; +} + +#! `-a`, lane by lane: a real's sign flipped, and an integer wrapping. +#! @param this The vector. +#! @returns The negations. +pub def simd::negate(&this): simd { + var made: simd; + if !lanes_done::((&mut made._lanes) as *mut u8, (&this._lanes) as *u8, null, null, 16, 16) { + val a: L[N] = this._lanes; + var r: L[N]; + for i in 0..N { + r[i] = -a[i]; + } + made._lanes = r; + } + return made; +} + +#! `a & b`, the bits both integer lanes have. +#! @param this The left vector. +#! @param other The right one. +#! @returns The vector. +pub def simd::bit_and(&this, other: &simd): simd { + var made: simd; + if const L is integer { + if !lanes_done::((&mut made._lanes) as *mut u8, (&this._lanes) as *u8, (&other._lanes) as *u8, null, 16, 16) { + val a: L[N] = this._lanes; + val b: L[N] = other._lanes; + var r: L[N]; + for i in 0..N { + r[i] = a[i] & b[i]; + } + made._lanes = r; + } + } else { + compile_error("`&` combines the bits of integer lanes, and these are reals."); + } + return made; +} + +#! `a | b`, the bits either integer lane has. +#! @param this The left vector. +#! @param other The right one. +#! @returns The vector. +pub def simd::bit_or(&this, other: &simd): simd { + var made: simd; + if const L is integer { + if !lanes_done::((&mut made._lanes) as *mut u8, (&this._lanes) as *u8, (&other._lanes) as *u8, null, 16, 16) { + val a: L[N] = this._lanes; + val b: L[N] = other._lanes; + var r: L[N]; + for i in 0..N { + r[i] = a[i] | b[i]; + } + made._lanes = r; + } + } else { + compile_error("`|` combines the bits of integer lanes, and these are reals."); + } + return made; +} + +#! `a ^ b`, the bits one integer lane has and the other does not. +#! @param this The left vector. +#! @param other The right one. +#! @returns The vector. +pub def simd::bit_xor(&this, other: &simd): simd { + var made: simd; + if const L is integer { + if !lanes_done::((&mut made._lanes) as *mut u8, (&this._lanes) as *u8, (&other._lanes) as *u8, null, 16, 16) { + val a: L[N] = this._lanes; + val b: L[N] = other._lanes; + var r: L[N]; + for i in 0..N { + r[i] = a[i] ^ b[i]; + } + made._lanes = r; + } + } else { + compile_error("`^` combines the bits of integer lanes, and these are reals."); + } + return made; +} + +#! `~a`, each integer lane's bits flipped. +#! @param this The vector. +#! @returns The vector. +pub def simd::bit_not(&this): simd { + var made: simd; + if const L is integer { + if !lanes_done::((&mut made._lanes) as *mut u8, (&this._lanes) as *u8, null, null, 16, 16) { + val a: L[N] = this._lanes; + var r: L[N]; + for i in 0..N { + r[i] = ~a[i]; + } + made._lanes = r; + } + } else { + compile_error("`~` flips the bits of integer lanes, and these are reals."); + } + return made; +} + +#! `a << n`, each integer lane shifted toward its top by as many bits, as the +#! integer's own `<<` shifts it: by its width or more gives 0. +#! @param this The vector. +#! @param by How many bits. +#! @returns The vector. +pub def simd::shift_left(&this, by: &u32): simd { + var made: simd; + if const L is integer { + val count: u32 = by; + if !lanes_done::((&mut made._lanes) as *mut u8, (&this._lanes) as *u8, (&count) as *u8, null, 16, 0) { + val a: L[N] = this._lanes; + var r: L[N]; + for i in 0..N { + r[i] = a[i] << count; + } + made._lanes = r; + } + } else { + compile_error("`<<` shifts the bits of integer lanes, and these are reals."); + } + return made; +} + +#! `a >> n`, each integer lane shifted toward its bottom by as many bits, as the +#! integer's own `>>` shifts it: a signed one keeps its sign. +#! @param this The vector. +#! @param by How many bits. +#! @returns The vector. +pub def simd::shift_right(&this, by: &u32): simd { + var made: simd; + if const L is integer { + val count: u32 = by; + if !lanes_done::((&mut made._lanes) as *mut u8, (&this._lanes) as *u8, (&count) as *u8, null, 16, 0) { + val a: L[N] = this._lanes; + var r: L[N]; + for i in 0..N { + r[i] = a[i] >> count; + } + made._lanes = r; + } + } else { + compile_error("`>>` shifts the bits of integer lanes, and these are reals."); + } + return made; +} + +#! Whether every lane of one vector equals that of another, as `==` asks. +#! @param this The one vector. +#! @param other The other. +#! @returns Whether they do. +pub def simd::equals(&this, other: &simd): bool { + return this.equal(other).all(); +} + + +# Comparing lanes. + +#! Which lanes equal those of another vector. A NaN equals nothing. +#! @param this The left vector. +#! @param other The right one. +#! @returns The mask. +pub def simd::equal(&this, other: &simd): mask { + var made: mask; + if !lanes_done::((&mut made._lanes) as *mut u8, (&this._lanes) as *u8, (&other._lanes) as *u8, null, 16, 16) { + val a: L[N] = this._lanes; + val b: L[N] = other._lanes; + var bits: u32 = 0; + for i in 0..N { + if a[i] == b[i] { + bits = bits | ((1 as u32) << i); + } + } + made = mask_of::(bits); + } + return made; +} + +#! Which lanes do not equal those of another vector. A NaN equals nothing. +#! @param this The left vector. +#! @param other The right one. +#! @returns The mask. +pub def simd::not_equal(&this, other: &simd): mask { + var made: mask; + if !lanes_done::((&mut made._lanes) as *mut u8, (&this._lanes) as *u8, (&other._lanes) as *u8, null, 16, 16) { + val a: L[N] = this._lanes; + val b: L[N] = other._lanes; + var bits: u32 = 0; + for i in 0..N { + if a[i] != b[i] { + bits = bits | ((1 as u32) << i); + } + } + made = mask_of::(bits); + } + return made; +} + +#! Which lanes are below those of another vector. +#! @param this The left vector. +#! @param other The right one. +#! @returns The mask. +pub def simd::less(&this, other: &simd): mask { + var made: mask; + if !lanes_done::((&mut made._lanes) as *mut u8, (&this._lanes) as *u8, (&other._lanes) as *u8, null, 16, 16) { + val a: L[N] = this._lanes; + val b: L[N] = other._lanes; + var bits: u32 = 0; + for i in 0..N { + if a[i] < b[i] { + bits = bits | ((1 as u32) << i); + } + } + made = mask_of::(bits); + } + return made; +} + +#! Which lanes are not above those of another vector. +#! @param this The left vector. +#! @param other The right one. +#! @returns The mask. +pub def simd::less_equal(&this, other: &simd): mask { + var made: mask; + if !lanes_done::((&mut made._lanes) as *mut u8, (&this._lanes) as *u8, (&other._lanes) as *u8, null, 16, 16) { + val a: L[N] = this._lanes; + val b: L[N] = other._lanes; + var bits: u32 = 0; + for i in 0..N { + if a[i] <= b[i] { + bits = bits | ((1 as u32) << i); + } + } + made = mask_of::(bits); + } + return made; +} + +#! Which lanes are above those of another vector. +#! @param this The left vector. +#! @param other The right one. +#! @returns The mask. +pub def simd::greater(&this, other: &simd): mask { + var made: mask; + if !lanes_done::((&mut made._lanes) as *mut u8, (&this._lanes) as *u8, (&other._lanes) as *u8, null, 16, 16) { + val a: L[N] = this._lanes; + val b: L[N] = other._lanes; + var bits: u32 = 0; + for i in 0..N { + if a[i] > b[i] { + bits = bits | ((1 as u32) << i); + } + } + made = mask_of::(bits); + } + return made; +} + +#! Which lanes are not below those of another vector. +#! @param this The left vector. +#! @param other The right one. +#! @returns The mask. +pub def simd::greater_equal(&this, other: &simd): mask { + var made: mask; + if !lanes_done::((&mut made._lanes) as *mut u8, (&this._lanes) as *u8, (&other._lanes) as *u8, null, 16, 16) { + val a: L[N] = this._lanes; + val b: L[N] = other._lanes; + var bits: u32 = 0; + for i in 0..N { + if a[i] >= b[i] { + bits = bits | ((1 as u32) << i); + } + } + made = mask_of::(bits); + } + return made; +} + + +# Functions of lanes. + +#! The lesser of each pair of lanes: of reals, IEEE 754's `minimum`, NaN where +#! either is NaN, and `-0` below `0`, as `math::min` gives it. +#! @param this The one vector. +#! @param other The other. +#! @returns The vector. +pub def simd::min(&this, other: &simd): simd { + var made: simd; + if !lanes_done::((&mut made._lanes) as *mut u8, (&this._lanes) as *u8, (&other._lanes) as *u8, null, 16, 16) { + val a: L[N] = this._lanes; + val b: L[N] = other._lanes; + var r: L[N]; + for i in 0..N { + r[i] = lane_min(a[i], b[i]); + } + made._lanes = r; + } + return made; +} + +#! The greater of each pair of lanes: of reals, IEEE 754's `maximum`, NaN where +#! either is NaN, and `0` above `-0`, as `math::max` gives it. +#! @param this The one vector. +#! @param other The other. +#! @returns The vector. +pub def simd::max(&this, other: &simd): simd { + var made: simd; + if !lanes_done::((&mut made._lanes) as *mut u8, (&this._lanes) as *u8, (&other._lanes) as *u8, null, 16, 16) { + val a: L[N] = this._lanes; + val b: L[N] = other._lanes; + var r: L[N]; + for i in 0..N { + r[i] = lane_max(a[i], b[i]); + } + made._lanes = r; + } + return made; +} + +#! Each lane's distance from zero: a real's sign bit cleared, a signed integer +#! negated where it is below zero, the most negative staying itself, and an +#! unsigned integer as it is. +#! @param this The vector. +#! @returns The vector. +pub def simd::abs(&this): simd { + var made: simd; + if !lanes_done::((&mut made._lanes) as *mut u8, (&this._lanes) as *u8, null, null, 16, 16) { + val a: L[N] = this._lanes; + var r: L[N]; + for i in 0..N { + r[i] = lane_abs(a[i]); + } + made._lanes = r; + } + return made; +} + +# Across the lanes. + +#! The lanes added together, lane 0 first: `((l0 + l1) + l2) + ...`. +#! @param this The vector. +#! @returns The sum. +pub def simd::sum(&this): L { + var worked: L; + return worked if lanes_whole::((&mut worked) as *mut u8, (&this._lanes) as *u8); + val a: L[N] = lanes_read(this); + var total: L = a[0]; + for i in 1..N { + total = total + a[i]; + } + return total; +} + +#! The lanes multiplied together, lane 0 first. +#! @param this The vector. +#! @returns The product. +pub def simd::product(&this): L { + var worked: L; + return worked if lanes_whole::((&mut worked) as *mut u8, (&this._lanes) as *u8); + val a: L[N] = lanes_read(this); + var total: L = a[0]; + for i in 1..N { + total = total * a[i]; + } + return total; +} + +#! The least lane, as `min` gives it of each pair, lane 0 first. +#! @param this The vector. +#! @returns The lane. +pub def simd::smallest(&this): L { + var worked: L; + return worked if lanes_whole::((&mut worked) as *mut u8, (&this._lanes) as *u8); + val a: L[N] = lanes_read(this); + var least: L = a[0]; + for i in 1..N { + val lane: L = a[i]; + least = lane_min(least, lane); + } + return least; +} + +#! The greatest lane, as `max` gives it of each pair, lane 0 first. +#! @param this The vector. +#! @returns The lane. +pub def simd::largest(&this): L { + var worked: L; + return worked if lanes_whole::((&mut worked) as *mut u8, (&this._lanes) as *u8); + val a: L[N] = lanes_read(this); + var most: L = a[0]; + for i in 1..N { + val lane: L = a[i]; + most = lane_max(most, lane); + } + return most; +} + + +# Masks. + +#! Whether a lane of the mask is set. +#! @param this The mask. +#! @param lane The lane, below how many there are. +#! @returns Whether it is. +#! @remarks A lane past the last stops the program. +pub def mask::has(&this, lane: u64): bool { + if lane >= N { + val held: L[N] = this._lanes; + _ = held[lane]; + } + return ((this.bits() >> lane) & 1) != 0; +} + +#! One bit for each lane of the mask, set where the lane is: lane 0 the lowest. +#! @param this The mask. +#! @returns The bits. +pub def mask::bits(&this): u32 { + var made: u32 = 0; + if lanes_have::() { + lanes_apply::((&mut made) as *mut u8, (&this._lanes) as *u8, null, null); + return made; + } + if const N * size_of::() >= 32 { + # A half, or a quarter, of the lanes at a time. + val half := N * size_of::() / 2; + if lanes_have::() { + var high: u32 = 0; + lanes_apply::((&mut made) as *mut u8, (&this._lanes) as *u8, null, null); + lanes_apply::((&mut high) as *mut u8, ((&this._lanes) as *u8) + half, null, null); + return made | (high << (N / 2)); + } + if const N * size_of::() == 64 { + if lanes_have::() { + for k in 0..4u { + var part: u32 = 0; + lanes_apply::((&mut part) as *mut u8, ((&this._lanes) as *u8) + 16 * k, null, null); + made = made | (part << (N / 4 * k) as u32); + } + return made; + } + } + } + val held: L[N] = this._lanes; + val bytes := (&held) as *u8; + for i in 0..N { + if bytes[i * size_of::()] != 0 { + made = made | ((1 as u32) << i); + } + } + return made; +} + +#! Whether any lane of the mask is set. +#! @param this The mask. +#! @returns Whether one is. +pub def mask::any(&this): bool { + return this.bits() != 0; +} + +#! Whether every lane of the mask is set. +#! @param this The mask. +#! @returns Whether each is. +pub def mask::all(&this): bool { + return this.bits() as u64 == ((1 as u64) << N) - 1; +} + +#! Whether no lane of the mask is set. +#! @param this The mask. +#! @returns Whether none is. +pub def mask::none(&this): bool { + return this.bits() == 0; +} + +#! How many lanes of the mask are set. +#! @param this The mask. +#! @returns How many. +pub def mask::count(&this): u32 { + return count_ones(this.bits()); +} + +#! The lowest lane of the mask that is set. +#! @param this The mask. +#! @returns The lane, or nothing where none is. +pub def mask::first(&this): maybe { + val bits := this.bits(); + return nothing {} if bits == 0; + return trailing_zeros(bits); +} + +#! The lanes both masks have set, as `a & b` asks. +#! @param this The one mask. +#! @param other The other. +#! @returns The mask. +pub def mask::bit_and(&this, other: &mask): mask { + var made: mask; + return made if lanes_done::((&mut made._lanes) as *mut u8, (&this._lanes) as *u8, (&other._lanes) as *u8, null, 16, 16); + return mask_of::(this.bits() & other.bits()); +} + +#! The lanes either mask has set, as `a | b` asks. +#! @param this The one mask. +#! @param other The other. +#! @returns The mask. +pub def mask::bit_or(&this, other: &mask): mask { + var made: mask; + return made if lanes_done::((&mut made._lanes) as *mut u8, (&this._lanes) as *u8, (&other._lanes) as *u8, null, 16, 16); + return mask_of::(this.bits() | other.bits()); +} + +#! The lanes one mask has set and the other does not, as `a ^ b` asks. +#! @param this The one mask. +#! @param other The other. +#! @returns The mask. +pub def mask::bit_xor(&this, other: &mask): mask { + var made: mask; + return made if lanes_done::((&mut made._lanes) as *mut u8, (&this._lanes) as *u8, (&other._lanes) as *u8, null, 16, 16); + return mask_of::(this.bits() ^ other.bits()); +} + +#! The lanes the mask does not have set, as `~a` asks. +#! @param this The mask. +#! @returns The mask. +pub def mask::bit_not(&this): mask { + var made: mask; + return made if lanes_done::((&mut made._lanes) as *mut u8, (&this._lanes) as *u8, null, null, 16, 16); + return mask_of::(~this.bits()); +} + +#! Whether two masks have the same lanes set, as `==` asks. +#! @param this The one mask. +#! @param other The other. +#! @returns Whether they do. +pub def mask::equals(&this, other: &mask): bool { + return this.bits() == other.bits(); +} + +#! Each lane taken from one vector where the mask has it set, and from the other +#! where it does not. +#! @tparam L The type of each lane. +#! @tparam N How many lanes there are. +#! @param which The mask. +#! @param then The lanes taken where it is set. +#! @param otherwise The lanes taken where it is not. +#! @returns The vector. +pub def select(which: mask, then: simd, otherwise: simd): simd + where L: numeric, ordered, zeroable { + var made: simd; + if !lanes_done::((&mut made._lanes) as *mut u8, (&which._lanes) as *u8, (&then._lanes) as *u8, (&otherwise._lanes) as *u8, 16, 16) { + val bits := which.bits(); + val b: L[N] = then._lanes; + val c: L[N] = otherwise._lanes; + var r: L[N]; + for i in 0..N { + r[i] = ((bits >> i) & 1) != 0 ? b[i] : c[i]; + } + made._lanes = r; + } + return made; +} + + +# How the lanes are worked. + +# The mask whose lanes are set where the bits are, lane 0 the lowest: every bit +# of a lane set, or none. +def mask_of(bits: u32): mask where L: numeric, ordered, zeroable { + var lanes: L[N]; + val at := (&mut lanes) as *mut u8; + for i in 0..N { + if ((bits >> i) & 1) != 0 { + for k in 0..size_of::() { + at[i * size_of::() + k] = 0xFF; + } + } + } + return mask:: { _lanes = lanes }; +} + +# Whether converting a vector's lanes to `M` is one the instructions work: any +# but real lanes to integers, which they convert only where each is within +# `i32`'s range, and not NaN, where `as` and they agree. +def within_integers(v: &simd): bool where L: numeric, ordered, zeroable where M: numeric, ordered, zeroable { + if const L is real { + if const M is integer { + return v.abs().less(&simd::::splat(2147483648 as L)).all(); + } + } + return true; +} + +# A lane converted to a type half as wide, held at the type's least or greatest +# where it is past them, or of a real, rounded as `as` rounds it. +def saturated(x: L): M where L: numeric, ordered, zeroable where M: numeric, ordered, zeroable { + if const L is integer { + if const M is integer { + val top := (size_of::() * 8 - 1) as u32; + val unsigned := ~(0 as M) > (0 as M); + val most: M = unsigned ? ~(0 as M) : ((1 as M) << top) - (1 as M); + return most if x > most as L; + if !(~(0 as L) > (0 as L)) { + val least: M = unsigned ? 0 as M : (1 as M) << top; + return least if x < least as L; + } + } + } + return x as M; +} + +# The lanes of a vector as an array, which what works them one at a time reads: +# moved whole where the processor's instructions move them, so a vector held in +# a register is read from it whole, 32 bytes as one. +def lanes_read(v: &simd): L[N] where L: numeric, ordered, zeroable { + var made: L[N]; + if !lanes_done::((&mut made) as *mut u8, (&v._lanes) as *u8, null, null, 16, 16) { + made = v._lanes; + } + return made; +} + +# A lane's distance from zero: an unsigned integer is its own, and a real's sign +# bit is cleared, so `-0` gives `0`, and NaN a NaN. +def lane_abs(x: L): L where L: numeric, ordered, zeroable { + if const L is integer { + return x if ~(0 as L) > (0 as L); + return x < -x ? -x : x; + } + var held := x; + if const size_of::() == 4 { + ((&mut held) as *mut u32)[0] = ((&mut held) as *mut u32)[0] & 0x7FFFFFFF; + } else { + ((&mut held) as *mut u64)[0] = ((&mut held) as *mut u64)[0] & 0x7FFFFFFFFFFFFFFF; + } + return held; +} + +# The lesser of two lanes: of reals, NaN where either is NaN, and `-0` below `0`. +def lane_min(a: L, b: L): L where L: numeric, ordered, zeroable { + if const L is real { + return a + b if a != a || b != b; + if a == b { + return lane_negative(a) ? a : b; + } + } + return b < a ? b : a; +} + +# The greater of two lanes: of reals, NaN where either is NaN, and `0` above `-0`. +def lane_max(a: L, b: L): L where L: numeric, ordered, zeroable { + if const L is real { + return a + b if a != a || b != b; + if a == b { + return lane_negative(a) ? b : a; + } + } + return a < b ? b : a; +} + +# Whether a real lane's sign bit is set, as `-0`'s is. +def lane_negative(x: L): bool where L: numeric, ordered, zeroable { + var held := x; + if const size_of::() == 4 { + return (((&mut held) as *mut u32)[0] >> 31) != 0; + } + return (((&mut held) as *mut u64)[0] >> 63) != 0; +} + +# Works an operation out with the vector instructions of the processor running +# the program, where it has them: the whole vector at once, or a part at a time +# where it has them only for fewer bytes, 32 as two halves of 16, and 64 as two +# of 32 or four of 16. The first and second operands' parts are `a_half` and +# `b_half` bytes on for each 16 bytes of the vector, which a lane splatted or a +# shift's count, the same for every part, is not. +# +# Where it gives false, the caller works the lanes one at a time, reading and +# writing each vector whole, so a vector read and written only so is a value +# held in a register wherever its cell is promoted. +def lanes_done(into: *mut u8, a: *u8, b: *u8, c: *u8, a_half: u64, b_half: u64): bool { + if lanes_have::() { + lanes_apply::(into, a, b, c); + return true; + } + if const N * size_of::() == 32 { + if lanes_have::() { + lanes_apply::(into, a, b, c); + lanes_apply::(into + 16, a + a_half, b == null ? b : b + b_half, c == null ? c : c + 16); + return true; + } + } + if const N * size_of::() == 64 { + if lanes_have::() { + lanes_apply::(into, a, b, c); + lanes_apply::(into + 32, a + 2 * a_half, b == null ? b : b + 2 * b_half, c == null ? c : c + 32); + return true; + } + if lanes_have::() { + lanes_apply::(into, a, b, c); + lanes_apply::(into + 16, a + a_half, b == null ? b : b + b_half, c == null ? c : c + 16); + lanes_apply::(into + 32, a + 2 * a_half, b == null ? b : b + 2 * b_half, c == null ? c : c + 32); + lanes_apply::(into + 48, a + 3 * a_half, b == null ? b : b + 3 * b_half, c == null ? c : c + 48); + return true; + } + } + return false; +} + +# Works an operation out with the processor's instructions, where it has them, +# the operation's result of another size, or of two vectors' lanes: never a +# half at a time. +def lanes_also(into: *mut u8, a: *u8, b: *u8): bool { + return false if !lanes_have::(); + lanes_apply::(into, a, b, null); + return true; +} + +# Works an operation giving lanes of another type, `M`, as `lanes_also` works +# one: its number with `M`'s type of lane above it, as the compiler numbers +# them, chosen while compiling. +def lanes_to(into: *mut u8, a: *u8, b: *u8): bool where M: numeric, ordered, zeroable { + if const M is i8 { return lanes_also::(into, a, b); } + if const M is u8 { return lanes_also::(into, a, b); } + if const M is i16 { return lanes_also::(into, a, b); } + if const M is u16 { return lanes_also::(into, a, b); } + if const M is i32 { return lanes_also::(into, a, b); } + if const M is u32 { return lanes_also::(into, a, b); } + if const M is i64 { return lanes_also::(into, a, b); } + if const M is u64 { return lanes_also::(into, a, b); } + if const M is f32 { return lanes_also::(into, a, b); } + if const M is f64 { return lanes_also::(into, a, b); } + return false; +} + +# Works out an operation of the whole vector at once, as working the lanes +# together does, where the processor has the instructions for it: never a half +# at a time, as the halves would have to be worked together after. +def lanes_whole(into: *mut u8, a: *u8): bool { + return false if !lanes_have::(); + lanes_apply::(into, a, null, null); + return true; +} + +# The operations on lanes the compiler gives instructions for. +const lanes_add: u32 = 1; +const lanes_sub: u32 = 2; +const lanes_mul: u32 = 3; +const lanes_div: u32 = 4; +const lanes_and: u32 = 5; +const lanes_or: u32 = 6; +const lanes_xor: u32 = 7; +const lanes_negate: u32 = 8; +const lanes_not: u32 = 9; +const lanes_min: u32 = 10; +const lanes_max: u32 = 11; +const lanes_abs: u32 = 12; +const lanes_sqrt: u32 = 13; +const lanes_floor: u32 = 14; +const lanes_ceil: u32 = 15; +const lanes_trunc: u32 = 16; +const lanes_round_even: u32 = 17; +const lanes_equal: u32 = 18; +const lanes_not_equal: u32 = 19; +const lanes_less: u32 = 20; +const lanes_less_equal: u32 = 21; +const lanes_greater: u32 = 22; +const lanes_greater_equal: u32 = 23; +const lanes_select: u32 = 24; # `a` the mask, `b` taken where it is set, `c` where not. +const lanes_fma: u32 = 25; # `a * b + c`. +const lanes_shift_left: u32 = 26; # `b` the `u32` count. +const lanes_shift_right: u32 = 27; +const lanes_bits: u32 = 28; # `into` the `u32` of the lanes `a` has set. +const lanes_splat: u32 = 29; # The lane `a` points at, in every lane. +const lanes_copy: u32 = 30; # The lanes `a` points at, moved whole. +const lanes_sum: u32 = 32; # `into` the lanes added together, lane 0 first. +const lanes_product: u32 = 33; # `into` the lanes multiplied together, lane 0 first. +const lanes_smallest: u32 = 34; # `into` the least lane. +const lanes_largest: u32 = 35; # `into` the greatest lane. +const lanes_shuffle: u32 = 37; # `a`'s lanes in the order the bytes `b` points at name. +const lanes_convert: u32 = 38; # `a`'s lanes as the type above the number, as many. +const lanes_low: u32 = 39; # `a`'s first half. +const lanes_high: u32 = 40; # `a`'s second half. +const lanes_join: u32 = 41; # `a`'s lanes, then `b`'s. +const lanes_widen: u32 = 42; # `a`'s first half as the type above the number, twice as wide. +const lanes_widen_high: u32 = 43; # `a`'s second half so. +const lanes_narrow: u32 = 44; # `a`'s lanes, then `b`'s, as the type above the number, half as wide, saturated. +const lanes_gather: u32 = 45; # The lanes at the address `a` points at, at the 32-bit places `b` names. + +#! Whether the program holds vectors in registers between their operations, as +#! an executable optimized with `-O2` does, so code working many numbers at once +#! with them outruns code working one at a time. The virtual machine and +#! constants work their lanes one at a time, and the C compiler's executables +#! move each through memory, where code for one number is faster. It is known +#! while compiling, so only the code it chooses is kept. +#! @returns Whether it does. +@intrinsic pub def lanes_held(): bool; + +# Whether the processor running the program has the instructions working `OP` on +# `N` lanes of `L`, which the program asked it once as it started. The virtual +# machine and constants have none. +@intrinsic def lanes_have(): bool; + +# Works `OP` on `N` lanes of `L`, from the bytes `a`, `b`, and `c` into those of +# `into`, with the instructions `lanes_have` says the processor has. +@intrinsic def lanes_apply(into: *mut u8, a: *u8, b: *u8, c: *u8): void; diff --git a/core/site.sakura b/core/site.sakura new file mode 100644 index 00000000..7f2762ba --- /dev/null +++ b/core/site.sakura @@ -0,0 +1,57 @@ +#! @file site.sakura +#! @author John Christman (sorakatadzuma@gmail.com) +#! @copyright Malunal Studios, LLC. +#! @license MIT +#! +#! Contains `site`, where a call is written, and the intrinsics the compiler +#! fills in where a call is written: `call_site`, which gives that site, and +#! `source_of` and `values_of`, which give an expression's text and its +#! operands' values, as checks report them. + +module core; + + +#! Where a call is written, which the compiler fills in at each call site. +#! +#! A `site` is made only by `call_site`, which gives the site of the call it is +#! written in, so a function is told where it was called from by taking one and +#! being passed `call_site()`. +pub struct site { + pub val path: strview; #! The file the call is written in. + pub val line: u32; #! Its one-based line. + pub val column: u32; #! Its one-based column. + pub val signature: strview; #! The function the call is written in, as it is declared. +} + +#! Gives where this call is written. +#! @returns The path, line, and column of the call, and the signature of the +#! function holding it. The compiler fills each in while compiling, so +#! this costs nothing where the program runs. +@intrinsic +pub def call_site(): site; + +#! Gives the text of an expression as it is written. +#! +#! The expression is not evaluated: only the source it was written as is taken, +#! so `source_of(count != 0)` is the text `count != 0` and nothing runs. The +#! text is written into the program, so this costs nothing where it runs. +#! @tparam T The type of the expression, which is never evaluated. +#! @param value The expression to take the text of. +#! @returns Its text, exactly as it is written. +@intrinsic +pub def source_of(value: T): strview; + +#! Gives the values the operands of an expression held. +#! +#! Unlike `source_of`, this evaluates the expression's operands, so it costs +#! what they cost and what printing them costs. A comparison gives both of its +#! operands, as `count = 0`, leaving out any that is written as a literal. An +#! expression that is neither a comparison nor a value of its own gives no text, +#! since the operands of `&&` and `||` are not both evaluated. +#! @tparam T The type of the expression. +#! @param value The expression to take the values of. +#! @returns What its operands held, or empty text. The text is built where the +#! call is written, so it is a `string` that gives its memory back +#! there. +@intrinsic +pub def values_of(value: T): string; diff --git a/core/swar.sakura b/core/swar.sakura new file mode 100644 index 00000000..5edde75b --- /dev/null +++ b/core/swar.sakura @@ -0,0 +1,287 @@ +#! @file swar.sakura +#! @author John Christman (sorakatadzuma@gmail.com) +#! @copyright Malunal Studios, LLC. +#! @license MIT +#! +#! Contains words of bytes: eight bytes of text held in a `u64`, `bytes8`, and +#! tested at once with the arithmetic every processor has, which is SIMD within +#! a register. A test gives a `mask8`, the bytes it chose, which then says where +#! the first of them is, the last, or how many there are, so text is searched +#! eight bytes a step rather than one. +#! +#! The first byte of text is the lowest byte of its word, as x86-64 reads it. +#! Every test is exact in every byte: each adds within a byte's low seven bits, +#! which carry nothing into the byte above, so a mask can be counted, and read +#! past its first byte, as well as tested. +#! +#! The text functions of `core`, as `index_of`, `find`, and `is_ascii`, work this +#! way where vectors are not held in registers, as in the virtual machine, and +#! on the last few bytes where they are, so most programs use words without +#! naming them. A program reading text its own way, as the JSON reader does, +#! names them here. What a loop asks of each word is `@inline`, so code built at +#! `-O0` reads a word without a call for each test. + +module core::swar; + + +#! Eight bytes of text in a `u64`, the first in its lowest byte. +pub type bytes8 = u64; + +#! A choice of the bytes of a `bytes8`: the high bit of each byte chosen, and +#! nothing else. +pub type mask8 = u64; + +# The low seven bits of each byte, and the high bit of each. +const low7: u64 = 0x7F7F7F7F7F7F7F7F; +const high1: u64 = 0x8080808080808080; +# One in each byte, which a byte multiplied by repeats into each. +const ones: u64 = 0x0101010101010101; + + +#! A word of one byte repeated. +#! @param byte The byte. +#! @returns Eight of it. +@inline +pub def repeat(byte: u8): bytes8 { + return (byte as u64) * ones; +} + +#! The eight bytes of text from a place. +#! @param text The text. +#! @param at Where the first is. +#! @returns The word. +#! @remarks Reading past the text's end stops the program, as indexing does, so +#! eight bytes must be left; `load_last` reads fewer. +pub def load(text: strview, at: u64): bytes8 { + _ = text[at]; + _ = text[at + 7]; + return *((text.data + at) as *u64); +} + +#! The eight bytes from a pointer, which needn't be aligned. +#! @param from The first byte. +#! @returns The word. +#! @remarks Nothing checks that eight bytes are there, as `*` checks nothing. +@inline +pub def load(from: *u8): bytes8 { + return *(from as *u64); +} + +#! The bytes of text from a place to its end, eight at most, and zero bytes +#! after them. +#! @param text The text. +#! @param at Where the first is, within the text. +#! @returns The word, whose bytes past the text's end are zero. +#! @remarks No byte past the text's end is read: the last few are read as +#! `load_last` of a pointer reads them. Beginning past the end stops +#! the program, as indexing does. +pub def load_last(text: strview, at: u64): bytes8 { + _ = text[at]; + val left := text.length - at; + return load_last(text.data + at, left < 8 ? left : 8); +} + +#! A number of bytes from a pointer, eight at most, and zero bytes after them, +#! read without reading any byte past them. +#! @param from The first byte. +#! @param count How many to read, from 0 to 8. +#! @returns The word, whose bytes from `count` up are zero. +#! @remarks Four to seven are read as two halves of four, which overlap, and two +#! or three as two of two, each shifted into its place, as `hash_bytes` +#! reads its last few. +pub def load_last(from: *u8, count: u64): bytes8 { + if count >= 8 { + return *(from as *u64); + } + if count >= 4 { + val low := *(from as *u32) as u64; + val high := *((from + count - 4) as *u32) as u64; + return low | (high << ((count - 4) * 8)); + } + if count >= 2 { + val low := *(from as *u16) as u64; + val high := *((from + count - 2) as *u16) as u64; + return low | (high << ((count - 2) * 8)); + } + return count == 1 ? *from as u64 : 0; +} + + +# Tests, each exact in every byte. + +#! The bytes that are zero. +#! @param this The word. +#! @returns Them. +@inline +pub def bytes8::zero(&this): mask8 { + # Adding the low seven bits to seven ones sets a byte's high bit unless they + # are all zero, and `| this` sets it where the byte's own is. + val word: u64 = this; + return ~(((word & low7) + low7) | word | low7); +} + +#! The bytes equal to a byte. +#! @param this The word. +#! @param byte The byte. +#! @returns Them. +@inline +pub def bytes8::equal(&this, byte: u8): mask8 { + val word: bytes8 = this ^ repeat(byte); + return word.zero(); +} + +#! The bytes below a bound, as unsigned numbers. +#! @param this The word. +#! @param bound The bound, which no byte chosen reaches. +#! @returns Them: none where the bound is 0. +@inline +pub def bytes8::below(&this, bound: u8): mask8 { + val word: u64 = this; + # A byte under 128 reaches its high bit by the sum where it is at least the + # bound, and one of 128 or more has it already. Over 128, a byte of 128 or more + # is below where its low seven bits don't reach the bound less 128, and every + # byte under 128 is. + if bound <= 128 { + return ~(((word & low7) + repeat(128 - bound)) | word) & high1; + } + return ~(((word & low7) + repeat((256 - bound as u64) as u8)) & word) & high1; +} + +#! The bytes above a bound, as unsigned numbers. +#! @param this The word. +#! @param bound The bound, which every byte chosen passes. +#! @returns Them: none where the bound is 255. +pub def bytes8::above(&this, bound: u8): mask8 { + return 0 if bound == 255; + return ~this.below(bound + 1) & high1; +} + +#! The bytes from one bound to another, both included, as unsigned numbers. +#! @param this The word. +#! @param low The least byte chosen. +#! @param high The greatest. +#! @returns Them: none where `low` is above `high`. +@inline +pub def bytes8::within(&this, low: u8, high: u8): mask8 { + val under: u64 = high == 255 ? high1 : this.below(high + 1); + return under & ~this.below(low); +} + +#! The bytes that are ASCII, below 128. +#! @param this The word. +#! @returns Them. +pub def bytes8::ascii(&this): mask8 { + return ~this & high1; +} + + +# Changes. + +#! The word with each ASCII letter in upper case, as `u8::to_upper` has it. +#! @param this The word. +#! @returns The word changed, where `a` to `z` become `A` to `Z`. +pub def bytes8::upper(&this): bytes8 { + # A letter's cases differ by 0x20, which is a mask's high bit moved down two. + return this ^ (this.within('a', 'z') >> 2); +} + +#! The word with each ASCII letter in lower case, as `u8::to_lower` has it. +#! @param this The word. +#! @returns The word changed, where `A` to `Z` become `a` to `z`. +pub def bytes8::lower(&this): bytes8 { + return this ^ (this.within('A', 'Z') >> 2); +} + +#! One byte of the word. +#! @param this The word. +#! @param index Which, from 0 for the first to 7. +#! @returns It. +pub def bytes8::byte(&this, index: u64): u8 { + return ((this >> ((index & 7) * 8)) & 0xFF) as u8; +} + +#! The number eight ASCII digits write, the first the most significant, as +#! `20261016` is written. +#! @param this The word. +#! @returns The number, or `nothing` where a byte is no digit. +pub def bytes8::digits(&this): maybe { + return nothing {} if this.within('0', '9') != high1; + + # Each byte its digit, which joins its neighbor's into pairs, quads, and the + # eight: the first of each is the more significant, and lower in the word. + var value: u64 = this - repeat('0'); + value = (value * 10 + (value >> 8)) & 0x00FF00FF00FF00FF; + value = (value * 100 + (value >> 16)) & 0x0000FFFF0000FFFF; + value = (value * 10000 + (value >> 32)) & 0xFFFFFFFF; + return value; +} + +#! The bytes of one word where a mask chooses them, and of another elsewhere. +#! @param which The mask. +#! @param then The word whose bytes the mask chooses. +#! @param otherwise The word whose bytes it doesn't. +#! @returns The word of both. +pub def choose(which: mask8, then: bytes8, otherwise: bytes8): bytes8 { + val chosen := which.spread(); + return (then & chosen) | (otherwise & ~chosen); +} + + +# Masks. + +#! Whether the mask chooses any byte. +#! @param this The mask. +#! @returns Whether it does. +@inline +pub def mask8::any(&this): bool { + return this != 0; +} + +#! The first byte the mask chooses, the lowest. +#! @param this The mask. +#! @returns Its index, from 0 to 7, or 8 where it chooses none. +@inline +pub def mask8::first(&this): u64 { + return trailing_zeros::(this) as u64 >> 3; +} + +#! The last byte the mask chooses, the highest. +#! @param this The mask. +#! @returns Its index, from 0 to 7, or 8 where it chooses none. +pub def mask8::last(&this): u64 { + return 8 if this == 0; + return (63 - leading_zeros::(this) as u64) >> 3; +} + +#! How many bytes the mask chooses. +#! @param this The mask. +#! @returns How many, from 0 to 8. +@inline +pub def mask8::count(&this): u64 { + # Each byte's 1, multiplied by ones, is summed into the top byte. + return ((this >> 7) * ones) >> 56; +} + +#! The mask without its first byte, to go on to the next. +#! @param this The mask. +#! @returns It. +@inline +pub def mask8::rest(&this): mask8 { + return this & (this - 1); +} + +#! The mask of the first bytes of a word, as the end of text keeps them. +#! @param count How many, from 0; 8 or more chooses every byte. +#! @returns It. +@inline +pub def mask8::leading(count: u64): mask8 { + return high1 if count >= 8; + return high1 & ((1u << (count * 8)) - 1); +} + +#! Every bit of each byte the mask chooses. +#! @param this The mask. +#! @returns A word of `0xFF` in each byte chosen, and zero in the rest. +pub def mask8::spread(&this): bytes8 { + return (this >> 7) * 0xFF; +} diff --git a/core/target.sakura b/core/target.sakura new file mode 100644 index 00000000..2d57e1c2 --- /dev/null +++ b/core/target.sakura @@ -0,0 +1,25 @@ +#! @file target.sakura +#! @author John Christman (sorakatadzuma@gmail.com) +#! @copyright Malunal Studios, LLC. +#! @license MIT +#! +#! Contains the intrinsics naming the platform the program was checked for, as +#! text. +#! +#! Code only for some platforms goes in `when os == linux { ... }`, or in a file +#! declared `module path when os == linux;`, since both leave out what other +#! platforms have. These give the same facts where code wants them as values. + +module core; + +#! The operating system the program was checked for. +#! @returns `linux`, `macos`, `windows`, `freebsd`, or `unknown`. +@intrinsic pub def os(): strview; + +#! The processor the program was checked for. +#! @returns `x86_64`, `aarch64`, or `unknown`. +@intrinsic pub def arch(): strview; + +#! How the program runs. +#! @returns `vm` when run by `sakura run`, or `native` as an executable. +@intrinsic pub def backend(): strview; diff --git a/core/traits/addable.sakura b/core/traits/addable.sakura new file mode 100644 index 00000000..0630634f --- /dev/null +++ b/core/traits/addable.sakura @@ -0,0 +1,25 @@ +#! @file addable.sakura +#! @author John Christman (sorakatadzuma@gmail.com) +#! @copyright Malunal Studios, LLC. +#! @license MIT +#! +#! Contains the addable trait, which asks for the method `+` calls between two +#! values of one type. + +module core; + + +#! A type whose values add to another of the type, giving one more. +#! +#! `a + b` calls `add`, and `a += b` writes what it gives over `a`. A type has +#! `+` by declaring the method, whether or not it names this trait, and may +#! declare others taking other types, as `instant::add(&this, by: &duration)`. +#! The trait is what generic code asks for to add two values of a type. Numbers +#! are addable without declaring anything. +pub trait addable { + #! Adds another value to this one, as `+` does. + #! @param this The value to add to. + #! @param other The value to add. + #! @returns The sum. + def add(&this, other: &self): self; +} diff --git a/core/traits/additive.sakura b/core/traits/additive.sakura new file mode 100644 index 00000000..d02b5a33 --- /dev/null +++ b/core/traits/additive.sakura @@ -0,0 +1,22 @@ +#! @file additive.sakura +#! @author John Christman (sorakatadzuma@gmail.com) +#! @copyright Malunal Studios, LLC. +#! @license MIT +#! +#! Contains the additive trait, which a type implements to add, subtract, and +#! negate its values, and which every number has. + +module core; + + +#! A type whose values add, subtract, and negate, all as one type: lengths of +#! time, vectors, matrices, amounts of money. +#! +#! It composes `addable`, `subtractable`, and `negatable`, which give `+`, `-`, +#! and `-x`, beside `equatable`. It asks for no multiplication, since two +#! lengths of time have no product. Numbers are additive without declaring +#! anything. +#! +#! Within a generic bounded by it, a constant does not stand for a value, as it +#! does under `numeric`: a length of time is no number. +pub trait additive : equatable, addable, subtractable, negatable {} diff --git a/core/traits/closeable.sakura b/core/traits/closeable.sakura new file mode 100644 index 00000000..d96f129c --- /dev/null +++ b/core/traits/closeable.sakura @@ -0,0 +1,19 @@ +#! @file closeable.sakura +#! @author John Christman (sorakatadzuma@gmail.com) +#! @copyright Malunal Studios, LLC. +#! @license MIT +#! +#! Contains the closeable trait, which the compiler gives every type whose +#! values are closed where they go away. + +module core; + +#! A type whose values are closed where they go away: one that is `owning`, or +#! one holding a value that is, in a field or an element. +#! +#! Generic code asks `if const T is closeable` where what it does only matters +#! for values that close, such as emptying the memory a value was moved out of +#! so that it is not closed twice, which plain data has no need of. +#! +#! The compiler decides what is closeable, so no type can implement it. +pub trait closeable {} diff --git a/core/traits/copyable.sakura b/core/traits/copyable.sakura new file mode 100644 index 00000000..70ab5e11 --- /dev/null +++ b/core/traits/copyable.sakura @@ -0,0 +1,48 @@ +#! @file copyable.sakura +#! @author John Christman (sorakatadzuma@gmail.com) +#! @copyright Malunal Studios, LLC. +#! @license MIT +#! +#! Contains the copyable trait, which a type implements to be copied, and +#! `copy`, which copies a value through it, or byte for byte where nothing it +#! holds closes. + +module core; + +#! A type whose values can be copied, by a static function building a copy of +#! another value. +#! +#! The function is static, and gives the copy back rather than filling a +#! destination that already exists, so that returning it writes straight into +#! whatever takes it and nothing throwaway is built on the way. +#! +#! A type that must not be copied simply does not implement this trait, which is +#! why the function gives the copy rather than an error: the type system says +#! what cannot be copied, and running out of memory stops the program, as +#! `acquire` does. +pub trait copyable { + #! Builds a copy of a value, which owns copies of whatever the value owns. + #! @param other The value to copy. + #! @returns The copy. + def copy_of(other: &self): self; +} + +#! Shortcut function for copying a value, giving the copy back. +#! @tparam T The type of the value. +#! @param src The source object to copy. +#! @returns The copy, which whatever takes it owns. A type that is `copyable` is +#! copied by its `copy_of`, and one that closes nothing byte for byte. +#! @remarks The copy is given back rather than written into a destination that +#! already exists, so that returning it writes straight into whatever +#! takes it. A type that closes, or holds what does, and is not +#! `copyable` is an error where it is copied, since its bytes would +#! share what it closes, and both copies would close it. +pub def copy(src: &T): T { + if const T is copyable { + return T::copy_of(src); + } + if const T is closeable { + compile_error("`copy` copies a value that closes, or holds one that does, only through `copyable`, which this type does not implement."); + } + return src; +} diff --git a/core/traits/divisible.sakura b/core/traits/divisible.sakura new file mode 100644 index 00000000..97845ee1 --- /dev/null +++ b/core/traits/divisible.sakura @@ -0,0 +1,25 @@ +#! @file divisible.sakura +#! @author John Christman (sorakatadzuma@gmail.com) +#! @copyright Malunal Studios, LLC. +#! @license MIT +#! +#! Contains the divisible trait, which asks for the method `/` calls between two +#! values of one type. + +module core; + + +#! A type whose values divide by another of the type, giving one more. +#! +#! `a / b` calls `div`, and `a /= b` writes what it gives over `a`. A type has +#! `/` by declaring the method, and may declare others taking other types, as +#! `duration::div(&this, by: &i64)`. The trait is what generic code asks for to +#! divide two values of a type. Numbers are divisible without declaring +#! anything. +pub trait divisible { + #! Divides this value by another, as `/` does. + #! @param this The value to divide. + #! @param other The value to divide by. + #! @returns The quotient. + def div(&this, other: &self): self; +} diff --git a/core/traits/equatable.sakura b/core/traits/equatable.sakura new file mode 100644 index 00000000..53b7759e --- /dev/null +++ b/core/traits/equatable.sakura @@ -0,0 +1,37 @@ +#! @file equatable.sakura +#! @author John Christman (sorakatadzuma@gmail.com) +#! @copyright Malunal Studios, LLC. +#! @license MIT +#! +#! Contains the equatable trait, which a type implements to be compared with +#! `==`, and `equals`, which compares two values through it. + +module core; + +#! A type whose values can be compared for equality, by a method comparing a +#! value with another of the same type. +#! +#! A type that is `equatable` is compared by `==` and `!=`, which call its +#! `equals`, and the method can be called by name too. +pub trait equatable { + #! Compares this value with another of the same type. + #! @param this The value to compare against. + #! @param other The value to compare with. + #! @returns Whether the two are equal. + def equals(&this, other: &self): bool; +} + +#! Compares two values of the same type through its `equals`, as `==` does. +#! @tparam T The type of the values. +#! @param first The value to compare against. +#! @param second The value to compare with. +#! @returns Whether the two are equal. +#! @remarks A type that is not `equatable` is an error where it is compared, as +#! it is with `==`, since its bytes may differ where its values do not, +#! as the padding between fields does. +pub def equals(first: &T, second: &T): bool { + if const !(T is equatable) { + compile_error("`equals` compares values through `equatable`, which this type does not implement, as `==` does."); + } + return first.equals(second); +} diff --git a/core/traits/extendable.sakura b/core/traits/extendable.sakura new file mode 100644 index 00000000..88795264 --- /dev/null +++ b/core/traits/extendable.sakura @@ -0,0 +1,20 @@ +#! @file extendable.sakura +#! @author John Christman (sorakatadzuma@gmail.com) +#! @copyright Malunal Studios, LLC. +#! @license MIT +#! +#! Contains the extendable trait, which a container implements to have values +#! appended to it, as an iterator's `into` appends each element it gives. + +module core; + + +#! A container values are appended to one at a time, as a `vector` takes its +#! elements and a `string` its text. +#! @tparam T The type of what is appended. +pub trait extendable { + #! Appends a value, after those the container holds. + #! @param this The container. + #! @param value The value, which the container then owns. + def append(&mut this, value: T): void; +} diff --git a/core/traits/hashable.sakura b/core/traits/hashable.sakura new file mode 100644 index 00000000..9c193271 --- /dev/null +++ b/core/traits/hashable.sakura @@ -0,0 +1,93 @@ +#! @file hashable.sakura +#! @author John Christman (sorakatadzuma@gmail.com) +#! @copyright Malunal Studios, LLC. +#! @license MIT +#! +#! Contains the hashable trait, which a type implements to be hashed, as a +#! dictionary's keys are, and `hash` and `mix`, which hash values and fold words +#! into a hash. + +module core; + +#! A type whose values can be hashed into a `u64`, as a dictionary's keys are. +#! +#! Equal values must hash alike, and values that differ should hash differently +#! as often as possible. +pub trait hashable { + #! Hashes this value. + #! @param this The value to hash. + #! @returns Its hash code, which equal values share. + def hash(&this): u64; +} + +#! Shortcut function for hashing a value, providing a 64-bit hashed value. +#! @tparam T The type of the value. +#! @param item The object to hash. +#! @returns The hash value of the object, from its `hash`. +#! @remarks A type that is not `hashable` is an error where it is hashed, since +#! its bytes may differ where its values do not, as the padding between +#! fields does, and equal values must hash alike. +pub def hash(item: &T): u64 { + if const !(T is hashable) { + compile_error("`hash` hashes values through `hashable`, which this type does not implement."); + } + return item.hash(); +} + +# Hashes bytes a word at a time, the last few as one word read without passing +# their end, so that equal bytes always hash alike. +def hash_bytes(data: *u8, len: u64): u64 { + var code := len; + var at := data; + var left := len; + while left >= 8 { + code = mix(code, *(at as *u64)); + at = at + 8; + left = left - 8; + } + if left >= 4 { + return mix(code, (*(at as *u32) as u64) | ((*((at + left - 4) as *u32) as u64) << 32)); + } + if left >= 2 { + return mix(code, (*(at as *u16) as u64) | ((*((at + left - 2) as *u16) as u64) << 16)); + } + if left == 1 { + return mix(code, *at as u64); + } + return code; +} + +#! Packs two 32-bit numbers into one word, the first in its high half, as a key +#! naming a pair, such as a type and a trait, is made for a dictionary. +#! @param high The number held in the high half. +#! @param low The number held in the low half. +#! @returns The word, which `pair_high` and `pair_low` take apart, and which no +#! other pair packs into. +pub def pair_key(high: u32, low: u32): u64 { + return (high as u64 << 32) | low as u64; +} + +#! The number held in the high half of a word `pair_key` packed. +#! @param key The word. +#! @returns The first number given to `pair_key`. +pub def pair_high(key: u64): u32 { + return (key >> 32) as u32; +} + +#! The number held in the low half of a word `pair_key` packed. +#! @param key The word. +#! @returns The second number given to `pair_key`. +pub def pair_low(key: u64): u32 { + return (key & 0xFFFFFFFF) as u32; +} + +#! Folds a word into a hash code, as hashing a value made of several does for +#! each. +#! @param code The hash code so far. +#! @param value The word to fold in. +#! @returns The new hash code. +pub def mix(code: u64, value: u64): u64 { + var bits := code ^ value; + bits *= 0x9E3779B97F4A7C15; + return bits ^ (bits >> 29); +} diff --git a/core/traits/indexable.sakura b/core/traits/indexable.sakura new file mode 100644 index 00000000..b060166e --- /dev/null +++ b/core/traits/indexable.sakura @@ -0,0 +1,53 @@ +#! @file indexable.sakura +#! @author John Christman (sorakatadzuma@gmail.com) +#! @copyright Malunal Studios, LLC. +#! @license MIT +#! +#! Contains the indexable trait, which lets a type of the standard library or of a +#! program be written `d[key]`, the way the language already writes a fixed array, +#! a pointer, and a view. +module core; + +#! Defines that a type is indexed by a key, giving the element it holds there. +#! +#! `d[key]` is `d.at(key)`: the reference the accessor gives, which is read, +#! assigned through, and bound as any reference is, so indexing copies nothing. +#! `val e := d[key]` refers to the element, and `val e: V = d[key]` copies it. +#! There are two accessors, both named `at`: one taking `&this` gives a `&V`, and +#! one taking `&mut this` gives a `&mut V`. The receiver chooses between them, so +#! a value that can be written is given the element to write, and one that +#! cannot is given it only to read. +#! +#! Only `at(&this)` is required. A type that is only ever read leaves out the +#! other, which is `@optional`, and is then read through `at(&this)` however it +#! is held, so writing an element of it is an error where it is written. +#! +#! Both accessors are given the same key, and both are expected to stop a +#! checked program where the key is one the value does not hold, as indexing a +#! fixed array outside its length does, with `if const checking()`: one that +#! is not checked trusts the key, as C does. A key that may be one the value +#! does not hold in a program that is right is asked of a `get` the type gives +#! beside this trait, returning `maybe<&V>`, as each container of std's does. +#! +#! Traits are satisfied by shape, as they are everywhere else, so a type with +#! `at` is indexable whether or not it names the trait. Naming it is still worth +#! doing: it says the type means to be indexed, and it is what a `where` clause +#! bounds a type parameter by. +#! @tparam K The type of the keys it is indexed by. +#! @tparam V The type of the elements it holds. +pub trait indexable { + #! Reaches the element held at a key, to read it. + #! @param this The value to index. + #! @param key The key of the element. + #! @returns The element. + #! @remarks A key the value does not hold stops a checked program. + def at(&this, key: K): &V; + + #! Reaches the element held at a key, to write it. + #! @param this The value to index. + #! @param key The key of the element. + #! @returns The element. + #! @remarks A key the value does not hold stops a checked program. + @optional + def at(&mut this, key: K): &mut V; +} diff --git a/core/traits/integer.sakura b/core/traits/integer.sakura new file mode 100644 index 00000000..33e75d18 --- /dev/null +++ b/core/traits/integer.sakura @@ -0,0 +1,67 @@ +#! @file integer.sakura +#! @author John Christman (sorakatadzuma@gmail.com) +#! @copyright Malunal Studios, LLC. +#! @license MIT +#! +#! Contains the integer trait, which the compiler gives every integer type. + +module core; + + +#! An integer type, signed or unsigned, of any width. +#! +#! A type parameter bounded by `integer` has what numbers have, as `numeric` and +#! `ordered` give, along with bitwise operators, shifts, and indexing, and it is +#! `ordinal`. The compiler decides what is an integer, so no other type can +#! implement it. +pub trait integer {} + + +#! Reads the text as a signed 64-bit integer, in decimal or with a `0x`, `0o`, +#! or `0b` prefix, where `_` may separate digits. +#! @param this The text to read, which may start with `-` or `+`. +#! @returns The integer, or why the text is not one. +pub def integer::parse(text: strview): + result where T : integer +{ + var at := 0u; + var neg := false; + if text.length > 0 { + neg = text[0] == '-'; + at = (text[0] == '+' || neg) as uint; + } + + var base := 10u; + if text.length > at + 1 && text[at] == '0' { + val marker := text[at + 1]; + if marker == 'x' || marker == 'X' { base = 16; } else + if marker == 'o' || marker == 'O' { base = 8; } else + if marker == 'b' || marker == 'B' { base = 2; } + + if base != 10 { at += 2; } + } + + return failure { $"`{text}` has no digits" } + if at >= text.length; + + const signed := 0x8000000000000000u; + const unsigned := 0x7FFFFFFFFFFFFFFFu; + val limit := neg ? signed : unsigned; + var magnitude := 0u; + for byte in text[at:] { + continue if byte == '_'; + + val digit := byte.digit_value; + return failure { $"`{text}` is not a base {base} integer" } + if digit >= base; + + return failure { $"`{text}` does not fit in 64 bits" } + if magnitude > (limit - digit) / base; + + magnitude = magnitude * base + digit; + } + + return neg + ? (0 - magnitude) as T + : magnitude as T; +} diff --git a/core/traits/invokable.sakura b/core/traits/invokable.sakura new file mode 100644 index 00000000..24498bc4 --- /dev/null +++ b/core/traits/invokable.sakura @@ -0,0 +1,45 @@ +#! @file invokable.sakura +#! @author John Christman (sorakatadzuma@gmail.com) +#! @copyright Malunal Studios, LLC. +#! @license MIT +#! +#! Contains the invokable trait, which a type implements to be called as a +#! function is, `f(args)`, and which every function is. + +module core; + +#! What is called as a function of a signature: a function value, the address of +#! a C function, or a value of a type with an `invoke` taking the arguments. +#! +#! The trait is given the signature whole, as `invokable`, +#! whose parameter types it names `Ts` and whose result `R`, so `invoke` takes a +#! parameter of each of the types, as `def adder::invoke(&mut this, a: i64, b: +#! bool): u8` does. A variadic signature, as `def(i64...): i64`, asks for a +#! variadic `invoke`. Generic code over any signature names it through a type +#! parameter bounded by `signature`, as `invokable`. +#! +#! A call of a value whose type is no function, `f(1, true)`, calls its `invoke`, +#! as `f.invoke(1, true)`, by the rules a method's call has: the overloads are +#! chosen between as they are, and one taking `&mut this` is called on what can be +#! written. Any type with an `invoke` is called so, whether or not it names this +#! trait, which bounds generic code taking functions and callable values alike: +#! +#! ```sakura +#! def twice(f: &mut F, x: i64): i64 where F: invokable { +#! return f(f(x)); +#! } +#! ``` +#! +#! A function value, and the address of a C function, have an `invoke` the +#! compiler gives them, which calls them, so each is `invokable` of its own type. +#! An `invoke` taking `&this` meets the trait too, since what can be written can +#! be read. +#! @tparam Ts The types of the arguments it is called with. +#! @tparam R The type it gives. +pub trait invokable { + #! Calls it with the arguments, as `f(args)` does. + #! @param this The value called. + #! @param args The arguments, one of each of the signature's parameter types. + #! @returns What the call gives. + def invoke(&mut this, args: Ts...): R; +} diff --git a/core/traits/iterable.sakura b/core/traits/iterable.sakura new file mode 100644 index 00000000..ae6c6c3d --- /dev/null +++ b/core/traits/iterable.sakura @@ -0,0 +1,41 @@ +#! @file iterable.sakura +#! @author John Christman (sorakatadzuma@gmail.com) +#! @copyright Malunal Studios, LLC. +#! @license MIT +#! +#! Contains the iterable trait, which lends an iterator over the elements a +#! container holds, and which a `for` loop walks. + +module core; + +#! Lends an iterator over the elements it holds, as references to them. +#! +#! `for x in c` calls `iter(&this)` once and walks what it gives, copying each +#! element, and `for &x in c` refers to each instead. `for &mut x in c` calls +#! `iter(&mut this)`, which a container whose elements may be changed in place +#! gives, and which one that only reads leaves out. What `iter` gives is closed +#! where the loop ends, however it ends, where it is `owning`. +#! +#! The iterator types are asked of the container, as `type list::cursor = +#! ...;`, so generic code names them through a bound, as `C::cursor` where `C: +#! iterable`. +#! @tparam T The type of the elements, which the iterators give references to. +pub trait iterable { + #! What `iter(&this)` gives, which gives references that read the elements. + type cursor: iterator<&T>; + + #! What `iter(&mut this)` gives, which gives references that write them. + @optional + type mut_cursor: iterator<&mut T>; + + #! Lends an iterator that reads the elements. + #! @param this The container to iterate. + #! @returns The iterator, which refers into the container. + def iter(&this): cursor; + + #! Lends an iterator that writes the elements where they are. + #! @param this The container to iterate. + #! @returns The iterator, which refers into the container. + @optional + def iter(&mut this): mut_cursor; +} diff --git a/core/traits/iterator.sakura b/core/traits/iterator.sakura new file mode 100644 index 00000000..ca297c2a --- /dev/null +++ b/core/traits/iterator.sakura @@ -0,0 +1,529 @@ +#! @file iterator.sakura +#! @author John Christman (sorakatadzuma@gmail.com) +#! @copyright Malunal Studios, LLC. +#! @license MIT +#! +#! Contains the iterator traits: `iterator`, which gives elements one at a time +#! and which a `for` loop walks, with the adapters making one iterator of +#! another and the consumers walking one to its end as its defaults; +#! `sized_iterator`, which knows how many elements it has left; and +#! `backward_iterator`, which also walks from its far end. + +module core; + + +#! Gives elements one at a time, as `some` of each while there are more and +#! `none` once there are no more. +#! +#! `for x in it` walks an iterator where it is, calling `next` until it gives +#! `none`, so one that a loop stops early carries on from there in the next. An +#! iterator that is `owning` and that a loop is given as a value, rather than as +#! a variable, is closed where the loop ends, however it ends. +#! +#! A type naming the trait has its defaults: the adapters, which make an +#! iterator of it, as `v.iter().filter(odd).map(square)`, and the consumers, +#! which walk it to its end, or until they know their answer, as `.sum()`. Each +#! is compiled for the type, so what it calls of the type is called directly. An +#! adapter moves the iterator it is called on into what it makes, which closes +#! it where that closes, so `it.map(f)` leaves `it` walked to its end. +#! @tparam T The type of what it gives. +pub trait iterator { + #! Gives the next element, or `none` once there are no more. + #! @param this The iterator to advance. + #! @returns Maybe the next element; otherwise, `nothing`. + def next(&mut this): maybe; + + #! Gives what a function makes of each element. + #! @tparam U What the function gives. + #! @tparam F The function, a lambda, or anything `invokable`. + #! @param this The iterator, moved into what is made. + #! @param f The function, called on each element as it is given. + #! @returns The iterator of what it makes. + def map(&mut this, f: F): mapped where F: invokable { + return mapped:: { _from = move(this), _f = move(&mut f) }; + } + + #! Gives each element a test passes. + #! @tparam F The test. + #! @param this The iterator, moved into what is made. + #! @param test The test, given a reference to each element. + #! @returns The iterator of those that pass. + def filter(&mut this, test: F): filtered where F: invokable { + return filtered:: { _from = move(this), _test = move(&mut test) }; + } + + #! Gives what a function makes of each element where it makes something, as + #! `some`. + #! @tparam U What the function may give. + #! @tparam F The function. + #! @param this The iterator, moved into what is made. + #! @param f The function, called on each element. + #! @returns The iterator of what it makes. + def filter_map(&mut this, f: F): filter_mapped where F: invokable> { + return filter_mapped:: { _from = move(this), _f = move(&mut f) }; + } + + #! Gives each element with its index, counting from 0, as a `pair`. + #! @param this The iterator, moved into what is made. + #! @returns The iterator of pairs. + def enumerate(&mut this): enumerated { + return enumerated:: { _from = move(this), _at = 0 }; + } + + #! Gives the elements of this iterator and another side by side, as a `pair`, + #! until either ends. + #! @tparam U What the other gives. + #! @tparam J The other iterator. + #! @param this The iterator, moved into what is made. + #! @param other The other iterator, moved into what is made. + #! @returns The iterator of pairs. + def zip(&mut this, other: J): zipped where J: iterator { + return zipped:: { _from = move(this), _other = move(&mut other) }; + } + + #! Gives this iterator's elements, then another's. + #! @tparam J The other iterator, giving what this one gives. + #! @param this The iterator, moved into what is made. + #! @param other The other iterator, moved into what is made. + #! @returns The iterator of both. + def chain(&mut this, other: J): chained where J: iterator { + return chained:: { _first = move(this), _second = move(&mut other), _on_second = false }; + } + + #! Gives the first elements, up to a count. + #! @param this The iterator, moved into what is made. + #! @param n How many to give at most. + #! @returns The iterator of those. + def take(&mut this, n: u64): taken { + return taken:: { _from = move(this), _left = n }; + } + + #! Gives the elements after the first, up to a count, which it passes over. + #! @param this The iterator, moved into what is made. + #! @param n How many to pass over. + #! @returns The iterator of the rest. + def skip(&mut this, n: u64): skipped { + return skipped:: { _from = move(this), _skip = n }; + } + + #! Gives the elements while a test passes them, ending at the first it does + #! not. + #! @tparam F The test. + #! @param this The iterator, moved into what is made. + #! @param test The test, given a reference to each element. + #! @returns The iterator of the run that passes. + def take_while(&mut this, test: F): taken_while where F: invokable { + return taken_while:: { _from = move(this), _test = move(&mut test), _done = false }; + } + + #! Gives the elements from the first a test does not pass on, passing over + #! those before it. + #! @tparam F The test. + #! @param this The iterator, moved into what is made. + #! @param test The test, given a reference to each element. + #! @returns The iterator of the rest. + def skip_while(&mut this, test: F): skipped_while where F: invokable { + return skipped_while:: { _from = move(this), _test = move(&mut test), _past = false }; + } + + #! Gives every `n`th element, the first included. + #! @param this The iterator, moved into what is made. + #! @param n How far apart the elements given are, at least 1. + #! @returns The iterator of those. + def step(&mut this, n: u64): stepped { + if n == 0 { + fault("An iterator steps by 0, which is no step."); + } + return stepped:: { _from = move(this), _by = n, _first = true }; + } + + #! Gives the elements from the far end. + #! @param this The iterator, moved into what is made. + #! @returns The iterator walking backward. + def rev(&mut this): reversed where self: backward_iterator { + return reversed:: { _from = move(this) }; + } + + #! Gives the elements, and looks at the next before it is given, by `peek`. + #! @param this The iterator, moved into what is made. + #! @returns The iterator that peeks. + def peekable(&mut this): peeking { + return peeking:: { _from = move(this), _held = nothing {} }; + } + + #! Gives the elements of each iterator a function makes of each element. + #! @tparam U What the iterators it makes give. + #! @tparam J The iterators it makes. + #! @tparam F The function. + #! @param this The iterator, moved into what is made. + #! @param f The function, called on each element. + #! @returns The iterator of what each gives, in turn. + def flat_map(&mut this, f: F): flat_mapped + where F: invokable where J: iterator { + return flat_mapped:: { _from = move(this), _f = move(&mut f), _inner = nothing {} }; + } + + #! Gives a copy of what each reference it gives refers to, of what closes + #! nothing. + #! @tparam X What the references refer to. + #! @param this The iterator of references, moved into what is made. + #! @returns The iterator of copies. + def copied(&mut this): copying where self: iterator<&X> { + return copying:: { _from = move(this) }; + } + + #! Gives the elements as they are, after calling a function on each. + #! @tparam F The function. + #! @param this The iterator, moved into what is made. + #! @param f The function, given a reference to each element. + #! @returns The iterator. + def inspect(&mut this, f: F): inspected where F: invokable { + return inspected:: { _from = move(this), _f = move(&mut f) }; + } + + #! Walks to the end, counting the elements. + #! @param this The iterator. + #! @returns How many it gave. + def count(&mut this): u64 { + var n: u64 = 0; + while this.next() is some(x) { + n++; + } + return n; + } + + #! Walks to the end, adding the elements up. + #! @param this The iterator, of numbers. + #! @returns The sum, or 0 where it gives none. + def sum(&mut this): T where T: numeric { + var total: T = 0; + while this.next() is some(x) { + total += x; + } + return total; + } + + #! Walks to the end, multiplying the elements together. + #! @param this The iterator, of numbers. + #! @returns The product, or 1 where it gives none. + def product(&mut this): T where T: numeric { + var total: T = 1; + while this.next() is some(x) { + total *= x; + } + return total; + } + + #! Walks to the end, folding each element into a value: `f(f(start, x0), x1)` + #! and on. + #! @tparam A The value. + #! @tparam F The function folding each in. + #! @param this The iterator. + #! @param start The value before any element is folded in. + #! @param f The function, given the value so far and the element. + #! @returns The value once every element is folded in. + def fold(&mut this, start: A, f: F): A where F: invokable { + var made := move(&mut start); + while this.next() is some(x) { + made = f(move(&mut made), move(&mut x)); + } + return made; + } + + #! Walks to the end, folding the elements into the first: `f(f(x0, x1), x2)` + #! and on. + #! @tparam F The function folding each in. + #! @param this The iterator. + #! @param f The function, given the value so far and the element. + #! @returns Maybe the value; otherwise, `nothing` where it gives no elements. + def reduce(&mut this, f: F): maybe where F: invokable { + var first := this.next(); + if first is not some(&mut start) { + return nothing {}; + } + var made := move(start); + while this.next() is some(x) { + made = f(move(&mut made), move(&mut x)); + } + return made; + } + + #! Whether a test passes any element, walking until one does. + #! @tparam F The test. + #! @param this The iterator. + #! @param test The test, given a reference to each element. + #! @returns Whether it passes one. + def any(&mut this, test: F): bool where F: invokable { + while this.next() is some(x) { + return true if test(&x); + } + return false; + } + + #! Whether a test passes every element, walking until one fails it. + #! @tparam F The test. + #! @param this The iterator. + #! @param test The test, given a reference to each element. + #! @returns Whether it passes all of them, as it does where there are none. + def all(&mut this, test: F): bool where F: invokable { + while this.next() is some(x) { + return false if !test(&x); + } + return true; + } + + #! The first element a test passes, walking until it finds one. + #! @tparam F The test. + #! @param this The iterator. + #! @param test The test, given a reference to each element. + #! @returns Maybe the element; otherwise, `nothing`. + def find(&mut this, test: F): maybe where F: invokable { + while this.next() is some(x) { + return move(&mut x) if test(&x); + } + return nothing {}; + } + + #! The index of the first element a test passes, counting from 0, walking + #! until it finds one. + #! @tparam F The test. + #! @param this The iterator. + #! @param test The test, given a reference to each element. + #! @returns Maybe the index; otherwise, `nothing`. + def position(&mut this, test: F): maybe where F: invokable { + var at: u64 = 0; + while this.next() is some(x) { + return at if test(&x); + at++; + } + return nothing {}; + } + + #! Walks to the end, keeping the least element, the first of those equally + #! least. + #! @param this The iterator, of what is ordered. + #! @returns Maybe the least; otherwise, `nothing` where it gives none. + def min(&mut this): maybe where T: ordered { + var first := this.next(); + if first is not some(&mut start) { + return nothing {}; + } + var best := move(start); + while this.next() is some(x) { + if x < best { + best = move(&mut x); + } + } + return best; + } + + #! Walks to the end, keeping the greatest element, the last of those equally + #! greatest. + #! @param this The iterator, of what is ordered. + #! @returns Maybe the greatest; otherwise, `nothing` where it gives none. + def max(&mut this): maybe where T: ordered { + var first := this.next(); + if first is not some(&mut start) { + return nothing {}; + } + var best := move(start); + while this.next() is some(x) { + if !(x < best) { + best = move(&mut x); + } + } + return best; + } + + #! Walks to the end, keeping the least element as an order says, the first of + #! those equally least. + #! @tparam F The order. + #! @param this The iterator. + #! @param order Whether one element comes before another. + #! @returns Maybe the least; otherwise, `nothing` where it gives none. + def min_by(&mut this, order: F): maybe where F: invokable { + var first := this.next(); + if first is not some(&mut start) { + return nothing {}; + } + var best := move(start); + while this.next() is some(x) { + if order(&x, &best) { + best = move(&mut x); + } + } + return best; + } + + #! Walks to the end, keeping the greatest element as an order says, the last + #! of those equally greatest. + #! @tparam F The order. + #! @param this The iterator. + #! @param order Whether one element comes before another. + #! @returns Maybe the greatest; otherwise, `nothing` where it gives none. + def max_by(&mut this, order: F): maybe where F: invokable { + var first := this.next(); + if first is not some(&mut start) { + return nothing {}; + } + var best := move(start); + while this.next() is some(x) { + if !order(&x, &best) { + best = move(&mut x); + } + } + return best; + } + + #! Walks to the end, keeping the element whose key is least, the first of + #! those equally least. + #! @tparam K The key, which is ordered. + #! @tparam F The function giving the key. + #! @param this The iterator. + #! @param key The function, given a reference to each element. + #! @returns Maybe the element; otherwise, `nothing` where it gives none. + def min_by_key(&mut this, key: F): maybe where F: invokable where K: ordered { + var first := this.next(); + if first is not some(&mut start) { + return nothing {}; + } + var best := move(start); + var least := key(&best); + while this.next() is some(x) { + var made := key(&x); + if made < least { + best = move(&mut x); + least = move(&mut made); + } + } + return best; + } + + #! Walks to the end, keeping the element whose key is greatest, the last of + #! those equally greatest. + #! @tparam K The key, which is ordered. + #! @tparam F The function giving the key. + #! @param this The iterator. + #! @param key The function, given a reference to each element. + #! @returns Maybe the element; otherwise, `nothing` where it gives none. + def max_by_key(&mut this, key: F): maybe where F: invokable where K: ordered { + var first := this.next(); + if first is not some(&mut start) { + return nothing {}; + } + var best := move(start); + var most := key(&best); + while this.next() is some(x) { + var made := key(&x); + if !(made < most) { + best = move(&mut x); + most = move(&mut made); + } + } + return best; + } + + #! The last element: from the far end where the iterator walks backward, + #! and otherwise by walking to the end. + #! @param this The iterator. + #! @returns Maybe the last element; otherwise, `nothing` where it gives none. + def last(&mut this): maybe { + if const self is backward_iterator { + return this.next_back(); + } + var kept: maybe = nothing {}; + while this.next() is some(x) { + kept = move(&mut x); + } + return kept; + } + + #! The element `n` along, counting from 0, passing over those before it. + #! @param this The iterator. + #! @param n How many to pass over first. + #! @returns Maybe the element; otherwise, `nothing` where it gives fewer. + def nth(&mut this, n: u64): maybe { + var left := n; + while left != 0 { + return nothing {} if this.next() is not some(x); + left--; + } + return this.next(); + } + + #! Walks to the end, calling a function on each element. + #! @tparam F The function. + #! @param this The iterator. + #! @param f The function, given each element. + def for_each(&mut this, f: F): void where F: invokable { + while this.next() is some(x) { + f(move(&mut x)); + } + } + + #! Walks to the end, collecting the elements into a vector, which is given + #! room for them all at once where the iterator knows how many it has left. + #! @param this The iterator. + #! @returns The vector. + def to_vector(&mut this): vector { + var made := vector::::new(); + if const self is sized_iterator { + made.reserve(this.remaining()); + } + while this.next() is some(x) { + made.append(move(&mut x)); + } + return made; + } + + #! Walks to the end, joining the text of the elements, as `$"{x}"` writes + #! each, with text between each two. + #! @param this The iterator. + #! @param between What is written between each two elements. + #! @returns The text. + def to_string(&mut this, between: strview): string { + var made := string::new(nothing {}); + var first := true; + while this.next() is some(x) { + if !first { + made.append(between); + } + first = false; + val text := $"{x}"; + made.append(text.view()); + } + return made; + } + + #! Walks to the end, appending each element to a container, as a `vector`, a + #! `string`, or anything `extendable` is. + #! @tparam C The container. + #! @param this The iterator. + #! @param target The container, which keeps what it held before. + def into(&mut this, target: &mut C): void where C: extendable { + while this.next() is some(x) { + target.append(move(&mut x)); + } + } +} + +#! An iterator that knows how many elements it has left, as a view, a range, +#! and the containers' iterators do, so collecting it makes room for them at +#! once. +#! @tparam T The type of what it gives. +pub trait sized_iterator : iterator { + #! How many elements it has left to give. + #! @param this The iterator. + #! @returns How many. + def remaining(&this): u64; +} + +#! An iterator that also walks from its far end, until the two ends meet, as a +#! view, a range, a `deque`, and a `chain` do, which `rev` and `last` take. +#! @tparam T The type of what it gives. +pub trait backward_iterator : iterator { + #! Gives the element at the far end, or `none` once the ends have met. + #! @param this The iterator. + #! @returns Maybe the last element left; otherwise, `nothing`. + def next_back(&mut this): maybe; +} diff --git a/core/traits/modular.sakura b/core/traits/modular.sakura new file mode 100644 index 00000000..862e95d2 --- /dev/null +++ b/core/traits/modular.sakura @@ -0,0 +1,24 @@ +#! @file modular.sakura +#! @author John Christman (sorakatadzuma@gmail.com) +#! @copyright Malunal Studios, LLC. +#! @license MIT +#! +#! Contains the modular trait, which asks for the method `%` calls between two +#! values of one type. + +module core; + + +#! A type whose values leave a remainder when divided by another of the type. +#! +#! `a % b` calls `rem`, and `a %= b` writes what it gives over `a`. A type has +#! `%` by declaring the method. The trait is what generic code asks for to take +#! the remainder of two values of a type. Numbers are modular without declaring +#! anything. +pub trait modular { + #! The remainder of dividing this value by another, as `%` gives it. + #! @param this The value to divide. + #! @param other The value to divide by. + #! @returns The remainder. + def rem(&this, other: &self): self; +} diff --git a/core/traits/moveable.sakura b/core/traits/moveable.sakura new file mode 100644 index 00000000..d33134e8 --- /dev/null +++ b/core/traits/moveable.sakura @@ -0,0 +1,76 @@ +#! @file moveable.sakura +#! @author John Christman (sorakatadzuma@gmail.com) +#! @copyright Malunal Studios, LLC. +#! @license MIT +#! +#! Contains the moveable trait, which a type implements to move what it holds +#! into a new value, and `move`, which moves a value through it, or byte for +#! byte. + +module core; + +#! Defines that a type or generic must conform to being moveable, where the data +#! of one object is handed to a new one and the source left empty. +#! +#! The function is static, and gives the moved value back rather than filling a +#! destination that already exists, so that returning it writes straight into +#! whatever takes it and nothing throwaway is built on the way. +#! +#! The source is `&mut` because a move empties it, which is the whole difference +#! between this and `copyable`. What it leaves is valid but empty rather than +#! dead, so closing it afterwards is harmless. +pub trait moveable { + #! Builds a value from what another holds, leaving the other empty. + #! @param other The value to move from, which is left empty but valid. + #! @returns The new value, holding what the other held. + def move_of(other: &mut self): self; +} + +#! Moves a value out of where it stands, leaving it empty. +#! @tparam T The type of the value. +#! @param src The value to move from, which holds nothing after. +#! @returns The moved value, which whatever takes it owns. A type that is +#! `moveable` is moved by its `move_of`, and any other byte for byte. +#! @remarks The source is left valid but empty rather than dead, so closing it +#! afterwards is harmless: one that closes, or holds what does, is +#! zeroed. Plain data, which nothing closes, is left as it was. +pub def move(src: &mut T): T { + if const T is moveable { + return T::move_of(src); + } + + # Plain data, which nothing closes, is copied as it is. + if const !(T is closeable) { + return src; + } + + # Fallback: read the value out byte for byte, then leave the source zeroed, so it + # is not closed twice: by a store of each word where it is one to four words, as + # most that close are, and by `memset` otherwise. + val made := bits_of(src as *T); + val words := src as *mut u64; + if const size_of::() == 8 { + words[0] = 0; + } else if const size_of::() == 16 { + words[0] = 0; + words[1] = 0; + } else if const size_of::() == 24 { + words[0] = 0; + words[1] = 0; + words[2] = 0; + } else if const size_of::() == 32 { + words[0] = 0; + words[1] = 0; + words[2] = 0; + words[3] = 0; + } else { + memset(src as *mut u8, 0, size_of::()); + } + return made; +} + +# The value a pointer points at, byte for byte. A `return` hands over what a pointer +# points at without emptying it, so the caller decides what is left there. +def bits_of(from: *T): T { + return from[0]; +} diff --git a/core/traits/multipliable.sakura b/core/traits/multipliable.sakura new file mode 100644 index 00000000..a0a6addf --- /dev/null +++ b/core/traits/multipliable.sakura @@ -0,0 +1,25 @@ +#! @file multipliable.sakura +#! @author John Christman (sorakatadzuma@gmail.com) +#! @copyright Malunal Studios, LLC. +#! @license MIT +#! +#! Contains the multipliable trait, which asks for the method `*` calls between +#! two values of one type. + +module core; + + +#! A type whose values multiply by another of the type, giving one more. +#! +#! `a * b` calls `mul`, and `a *= b` writes what it gives over `a`. A type has +#! `*` by declaring the method, and may declare others taking other types, as +#! `vec2::mul(&this, by: &f64)`. The trait is what generic code asks for to +#! multiply two values of a type, as two matrices. Numbers are multipliable +#! without declaring anything. +pub trait multipliable { + #! Multiplies this value by another, as `*` does. + #! @param this The value to multiply. + #! @param other The value to multiply by. + #! @returns The product. + def mul(&this, other: &self): self; +} diff --git a/core/traits/multiplicative.sakura b/core/traits/multiplicative.sakura new file mode 100644 index 00000000..afc8d039 --- /dev/null +++ b/core/traits/multiplicative.sakura @@ -0,0 +1,18 @@ +#! @file multiplicative.sakura +#! @author John Christman (sorakatadzuma@gmail.com) +#! @copyright Malunal Studios, LLC. +#! @license MIT +#! +#! Contains the multiplicative trait, which a type implements to multiply its +#! values, and which every number has. + +module core; + + +#! A type whose values multiply, as one type: matrices, and whatever is +#! numeric. +#! +#! It composes `multipliable`, which gives `*`, beside `equatable`. It asks for +#! no division, since not every matrix divides another. Numbers are +#! multiplicative without declaring anything. +pub trait multiplicative : equatable, multipliable {} diff --git a/core/traits/negatable.sakura b/core/traits/negatable.sakura new file mode 100644 index 00000000..1f8c0cf3 --- /dev/null +++ b/core/traits/negatable.sakura @@ -0,0 +1,21 @@ +#! @file negatable.sakura +#! @author John Christman (sorakatadzuma@gmail.com) +#! @copyright Malunal Studios, LLC. +#! @license MIT +#! +#! Contains the negatable trait, which asks for the method a prefix `-` calls. + +module core; + + +#! A type whose values negate, giving another of the type. +#! +#! `-a` calls `negate`. A type has it by declaring the method. The trait is +#! what generic code asks for to negate a value. Numbers are negatable without +#! declaring anything. +pub trait negatable { + #! Negates this value, as `-x` does. + #! @param this The value to negate. + #! @returns The negated value. + def negate(&this): self; +} diff --git a/core/traits/numeric.sakura b/core/traits/numeric.sakura new file mode 100644 index 00000000..4d4de407 --- /dev/null +++ b/core/traits/numeric.sakura @@ -0,0 +1,29 @@ +#! @file numeric.sakura +#! @author John Christman (sorakatadzuma@gmail.com) +#! @copyright Malunal Studios, LLC. +#! @license MIT +#! +#! Contains the numeric trait, which a type implements to have all of arithmetic, +#! and which every number has. + +module core; + + +#! A type with arithmetic. +#! +#! It composes `additive` and `multiplicative`, and `divisible` and `modular` +#! beside them, so it asks for `add`, `sub`, `mul`, `div`, `rem`, and `negate` +#! between two values of the type, with their `equals`. `+`, `-`, `*`, `/`, and +#! `%` call them, the compound assignments such as `+=` call them too, and `-x` +#! calls `negate`. Numbers are numeric without declaring anything. It does not +#! ask for an order, so vectors and matrices can be numeric; write +#! `where T: numeric, ordered` for both. +#! +#! A type has each operator by the method that gives it, so one that means only +#! some of them declares only those, and satisfies the smaller traits this one +#! composes. +#! +#! Within a generic bounded by it, a constant such as `x + 1`, and `as` between +#! numbers, work where `T` is a number and are errors in an instance where it is +#! not. +pub trait numeric : additive, multiplicative, divisible, modular {} diff --git a/core/traits/ordered.sakura b/core/traits/ordered.sakura new file mode 100644 index 00000000..3786bea2 --- /dev/null +++ b/core/traits/ordered.sakura @@ -0,0 +1,26 @@ +#! @file ordered.sakura +#! @author John Christman (sorakatadzuma@gmail.com) +#! @copyright Malunal Studios, LLC. +#! @license MIT +#! +#! Contains the ordered trait, which a type implements for its values to have an +#! order, and which numbers, enums, and pointers have. + +module core; + + +#! A type whose values have an order. +#! +#! `compare` gives a negative number when `this` comes before `other`, zero when +#! they are equal, and a positive number when it comes after. `<`, `<=`, `>`, +#! and `>=` between two values of the type call it, as `==` calls `equals`, +#! which an ordered type also gives, so the two always agree. Numbers, enums, +#! and pointers are ordered without declaring anything. +pub trait ordered : equatable { + #! Compares this value with another of the same type, for their order. + #! @param this The value to compare against. + #! @param other The value to compare with. + #! @returns A negative number where this value comes first, zero where they + #! are equal, and a positive number where it comes after. + def compare(&this, other: &self): i64; +} diff --git a/core/traits/ordinal.sakura b/core/traits/ordinal.sakura new file mode 100644 index 00000000..8398214b --- /dev/null +++ b/core/traits/ordinal.sakura @@ -0,0 +1,19 @@ +#! @file ordinal.sakura +#! @author John Christman (sorakatadzuma@gmail.com) +#! @copyright Malunal Studios, LLC. +#! @license MIT +#! +#! Contains the ordinal trait, which the compiler gives every integer type and +#! every enum. + +module core; + +#! A value that is an integer underneath: every integer type, and every enum. +#! +#! A type parameter bounded by `ordinal` compares with `==`, orders with `<`, +#! and converts to and from the integer types with `as`, which is what flags and +#! tables indexed by an enum need. An integer becomes an enum only when it is +#! some member's value, and stops the program otherwise. +#! +#! The compiler decides what is ordinal, so no other type can implement it. +pub trait ordinal {} diff --git a/core/traits/owning.sakura b/core/traits/owning.sakura new file mode 100644 index 00000000..46485619 --- /dev/null +++ b/core/traits/owning.sakura @@ -0,0 +1,49 @@ +#! @file owning.sakura +#! @author John Christman (sorakatadzuma@gmail.com) +#! @copyright Malunal Studios, LLC. +#! @license MIT +#! +#! Contains the owning trait, which a type names to own what it holds and close it +#! where its values go away, and the function closing a value where it stands. +module core; + + +#! Defines that a type owns what it holds, such as memory or a file, and +#! disposes of it in `close`. A value of a type naming `owning` is closed where +#! its scope ends, as RAII does, so that something like an allocator or +#! collection has released its data by the time it goes away. +#! +#! A type is owning only by naming the trait, so a `close` meant to be called by +#! hand never becomes a destructor by accident. A reference to an owning value +#! owns nothing, so it is never owning, though `close` is called through it. +#! +#! Unlike `copyable` and `moveable`, nothing fails where a type is not owning: +#! generic code asks `if const T is owning`, or calls `close`, which closes +#! whatever is given as its scope ending would. +pub trait owning { + #! Disposes of what the value owns, as its scope ending does. + #! @param this The value to close, which should be left empty, so closing it + #! again does nothing. + def close(&mut this): void; +} + +#! Closes a value where it stands, as its scope ending would: through its own +#! `close` where it is `owning`, then each value it holds that closes, such as +#! a `string` in a field, the last first. A value that closes nothing is left +#! alone. +#! @tparam T The type of the value. +#! @param value The value to close, which is left empty. +#! @remarks Containers close their elements with it, so that an element holding +#! something that closes is closed as a local holding it would be. +pub def close(value: &mut T): void { + if const T is closeable { + close_where_it_is(value); + memset(value as *mut u8, 0, size_of::()); + } +} + +# Closes a value where it is, as the compiler closes a local whose scope ends: +# its own `close` where it is `owning`, then each field that closes, the last +# first, or the field a union holds, or each element of a fixed array. +@intrinsic +def close_where_it_is(value: &mut T): void; diff --git a/core/traits/pointer.sakura b/core/traits/pointer.sakura new file mode 100644 index 00000000..31700162 --- /dev/null +++ b/core/traits/pointer.sakura @@ -0,0 +1,23 @@ +#! @file pointer.sakura +#! @author John Christman (sorakatadzuma@gmail.com) +#! @copyright Malunal Studios, LLC. +#! @license MIT +#! +#! Contains the pointer trait, which the compiler gives every pointer type. + +module core; + + +#! A pointer, whatever it points at, however many pointers deep. +#! +#! A pointer is an address. It is compared, ordered, and hashed as one, starts +#! as `null`, and moves by whole elements, so `p + 1` is the element after `p`, +#! and two pointers subtract to the number of elements between them. Nothing of +#! what it points at is reached through it: `*p`, `p[i]`, and `through(p)` reach +#! that. +#! +#! A type parameter bounded by `pointer` has what pointers have, as `equatable`, +#! `ordered`, and `zeroable` give, along with moving by an integer and +#! subtracting. The compiler decides what is a pointer, so no type can implement +#! it. +pub trait pointer {} diff --git a/core/traits/real.sakura b/core/traits/real.sakura new file mode 100644 index 00000000..af7f08f3 --- /dev/null +++ b/core/traits/real.sakura @@ -0,0 +1,94 @@ +#! @file real.sakura +#! @author John Christman (sorakatadzuma@gmail.com) +#! @copyright Malunal Studios, LLC. +#! @license MIT +#! +#! Contains the real trait, which the compiler gives every floating-point type. + +module core; + + +#! A type of real numbers: `f32` or `f64`, or an alias of either. +#! +#! A type parameter bounded by `real` has what numbers have, as `numeric` and +#! `ordered` give, along with a zero value, and `as` to and from the other +#! numbers. It is what the functions of `std::math` ask of what they take, as +#! `math::sqrt(x: T): T where T: real`. The compiler decides what is real, so +#! no other type can implement it. +pub trait real {} + + +#! Reads the text as a real number such as `42`, `-0.5`, `.25`, or `6.02e23`. +#! @param this The text to read, which may start with `-` or `+`, and may end +#! with an exponent: `e` or `E`, an optional sign, and digits. +#! @returns The 64-bit float nearest the number, halfway between two going to +#! the one whose last bit is zero, or why the text is not one. A number +#! too large for 64 bits is a failure, and one too small is zero. +pub def real::parse(text: strview): + result where T : real +{ + var at := 0u; + var neg := false; + if text.length > 0 { + neg = text[0] == '-'; + at = (text[0] == '+' || neg) as uint; + } + + # The digits, with at most one `.` among them. + val start := at; + var digits := 0u; + var dotted := false; + while at < text.length { + val byte := text[at]; + if byte == '.' && !dotted { + dotted = true; + } else { + break if !byte.is_digit; + digits++; + } + at++; + } + + return failure { $"`{text}` is not a number" } + if digits == 0; + + # The exponent, which is held at a hundred thousand, far past where every number + # is too large or too small, so a long one cannot overflow it. + var exponent := 0; + val written := text.substr(start, at - start); + if at < text.length && (text[at] == 'e' || text[at] == 'E') { + at++; + + var down := false; + if at < text.length { + down = text[at] == '-'; + at += (text[at] == '+' || down) as uint; + } + + val first := at; + while at < text.length && text[at].is_digit { + if exponent < 100000 { + exponent = exponent * 10 + (text[at].digit_value as i64); + } + at++; + } + + return failure { $"`{text}` has a malformed exponent" } + if at == first; + + if down { + exponent = -exponent; + } + } + + return failure { $"`{text}` is not a number" } + if at != text.length; + + return failure { $"`{text}` is too large for 64 bits" } + if decimal_digits::nearest(written, exponent) + is not some(result); + + return neg + ? -result as T + : result as T; +} diff --git a/core/traits/signature.sakura b/core/traits/signature.sakura new file mode 100644 index 00000000..a609f36b --- /dev/null +++ b/core/traits/signature.sakura @@ -0,0 +1,32 @@ +#! @file signature.sakura +#! @author John Christman (sorakatadzuma@gmail.com) +#! @copyright Malunal Studios, LLC. +#! @license MIT +#! +#! Contains the signature trait, which the compiler gives every function type, +#! and which names what a function takes and what it gives. + +module core; + +#! A function type, as `def(i64, bool): u8`, a variadic one, as `def(i64...): +#! i64`, or the address of a C function, as `cfn`. +#! +#! Generic code bounded by it names the parts of the type it is given: `F::result` +#! is what a function of it gives, and `F::params` the types it takes, as a pack, +#! so `args: F::params...` takes the arguments it does. A variadic function's +#! pack ends in the type of the values its last parameter takes, so a parameter +#! of the pack is variadic too. +#! +#! A pattern parameter, as `def(Ts...): R` of `invokable`, is given a signature +#! whole: `invokable` where `F: signature` names `F::params` and `F::result` +#! as `Ts` and `R`. +#! +#! The compiler decides what is a signature, so no type implements it. +pub trait signature { + #! What a function of the type gives. + type result; + + #! The types a function of the type takes, as a pack, which only the compiler + #! gives. + type params...; +} diff --git a/core/traits/sliceable.sakura b/core/traits/sliceable.sakura new file mode 100644 index 00000000..33653c4d --- /dev/null +++ b/core/traits/sliceable.sakura @@ -0,0 +1,21 @@ +#! @file sliceable.sakura +#! @author John Christman (sorakatadzuma@gmail.com) +#! @copyright Malunal Studios, LLC. +#! @license MIT +#! +#! Contains the sliceable trait, which a type implements to lend a writable view +#! of the elements it holds. + +module core; + + +#! A type that lends a writable view of the elements it holds, as a container +#! lends one of its elements. +#! @tparam T The type of the elements. +pub trait sliceable { + #! Lends a writable view of the elements, without copying them. + #! @param this The value to view. + #! @returns The view, which writes the elements where they are, and is only + #! good until the value changes or closes. + def slice(&mut this): slice; +} diff --git a/core/traits/subtractable.sakura b/core/traits/subtractable.sakura new file mode 100644 index 00000000..ee2a1692 --- /dev/null +++ b/core/traits/subtractable.sakura @@ -0,0 +1,25 @@ +#! @file subtractable.sakura +#! @author John Christman (sorakatadzuma@gmail.com) +#! @copyright Malunal Studios, LLC. +#! @license MIT +#! +#! Contains the subtractable trait, which asks for the method `-` calls between +#! two values of one type. + +module core; + + +#! A type whose values subtract from another of the type, giving one more. +#! +#! `a - b` calls `sub`, and `a -= b` writes what it gives over `a`. A type has +#! `-` by declaring the method, and may declare others taking or giving other +#! types, as `instant::sub(&this, since: &instant): duration`. The trait is +#! what generic code asks for to subtract two values of a type. Numbers are +#! subtractable without declaring anything. +pub trait subtractable { + #! Subtracts another value from this one, as `-` does. + #! @param this The value to subtract from. + #! @param other The value to subtract. + #! @returns The difference. + def sub(&this, other: &self): self; +} diff --git a/core/traits/viewable.sakura b/core/traits/viewable.sakura new file mode 100644 index 00000000..10363de8 --- /dev/null +++ b/core/traits/viewable.sakura @@ -0,0 +1,23 @@ +#! @file viewable.sakura +#! @author John Christman (sorakatadzuma@gmail.com) +#! @copyright Malunal Studios, LLC. +#! @license MIT +#! +#! Contains the viewable trait, which a type implements to lend a view of the +#! elements it holds, and to be given wherever such a view is wanted. + +module core; + +#! A type that lends a view of the elements it holds, as a `string` lends its +#! text and a container its elements. +#! +#! Generic code bounded by it reads the elements of whatever it is given through +#! `view`. +#! @tparam T The type of the elements. +pub trait viewable { + #! Lends a view of the elements, without copying them. + #! @param this The value to view. + #! @returns The view, which is only good until the value changes or closes. + def view(&this): span; +} + diff --git a/core/traits/zeroable.sakura b/core/traits/zeroable.sakura new file mode 100644 index 00000000..ec67334e --- /dev/null +++ b/core/traits/zeroable.sakura @@ -0,0 +1,21 @@ +#! @file zeroable.sakura +#! @author John Christman (sorakatadzuma@gmail.com) +#! @copyright Malunal Studios, LLC. +#! @license MIT +#! +#! Contains the zeroable trait, which the compiler gives every type that has a +#! zero value. + +module core; + +#! A type with a zero value, which a variable left without a value starts at: a +#! number, `bool`, a pointer, an enum with a member of value 0, and an array, +#! struct, or union of what is, where a struct's fields with defaults start at +#! their defaults instead. A reference or a function is not, nor is what holds +#! one. +#! +#! Generic code bounded by it may write `var made: T;`, and code that only may +#! asks `if const T is zeroable` first. +#! +#! The compiler decides what is zeroable, so no type can implement it. +pub trait zeroable {} diff --git a/core/u8.ext.sakura b/core/u8.ext.sakura new file mode 100644 index 00000000..e4752d78 --- /dev/null +++ b/core/u8.ext.sakura @@ -0,0 +1,149 @@ +#! @file u8.ext.sakura +#! @author John Christman (sorakatadzuma@gmail.com) +#! @copyright Malunal Studios, LLC. +#! @license MIT +#! +#! Contains what a byte of text is asked: whether it is a letter, a digit of +#! some base, whitespace, or one of several bytes, and its letter's other case. + +module core; + +#! The zero byte, which ends text C reads and marks the end of text a scanner +#! reads. +pub const nullbyte: u8 = '\0'; +#! The line feed byte, `'\n'`, which ends a line. +pub const newline: u8 = '\n'; + +#! Whether the byte is the zero byte. +#! @param this The byte to check. +#! @returns Whether it is `'\0'`. +pub val u8::is_null: bool { get => this == nullbyte; } + +#! Whether the byte marks the end of text, as the zero byte does to a scanner. +#! @param this The byte to check. +#! @returns Whether it is `'\0'`. +pub val u8::is_eof: bool { get => this == nullbyte; } + +#! Whether the byte ends a line. +#! @param this The byte to check. +#! @returns Whether it is `'\n'`. +pub val u8::is_eol: bool { get => this == newline; } + +#! Whether the byte is whitespace. +#! @param this The byte to check. +#! @returns Whether it is a space, or a tab, line feed, vertical tab, form feed, +#! or carriage return. +@inline +pub val u8::is_space: bool { + get => this == ' ' || (this >= '\t' && this <= '\r'); +} + +#! Whether the byte is an uppercase ASCII letter. +#! @param this The byte to check. +#! @returns Whether it is one of `A` to `Z`. +@inline +pub val u8::is_upper: bool { get => this >= 'A' && this <= 'Z'; } + +#! Whether the byte is a lowercase ASCII letter. +#! @param this The byte to check. +#! @returns Whether it is one of `a` to `z`. +@inline +pub val u8::is_lower: bool { get => this >= 'a' && this <= 'z'; } + +#! The byte in uppercase, where it is a lowercase ASCII letter. +#! @param this The byte to convert. +#! @returns The uppercase letter, or the byte as it is where it is no lowercase +#! letter. +@inline +pub val u8::to_upper: u8 { get => this.is_lower ? this - 32 : this; } + +#! The byte in lowercase, where it is an uppercase ASCII letter. +#! @param this The byte to convert. +#! @returns The lowercase letter, or the byte as it is where it is no uppercase +#! letter. +@inline +pub val u8::to_lower: u8 { get => this.is_upper ? this + 32 : this; } + +#! Whether the byte is an ASCII letter of either case. +#! @param this The byte to check. +#! @returns Whether it is a letter. +pub val u8::is_alpha: bool { get => this.is_lower || this.is_upper; } + +#! Whether the byte is an ASCII letter or a decimal digit. +#! @param this The byte to check. +#! @returns Whether it is a letter or a digit. +pub val u8::is_alnum: bool { get => this.is_alpha || this.is_digit; } + +#! Whether the byte may begin a name: a letter, or `_`. +#! @param this The byte to check. +#! @returns Whether it is a letter or `_`. +pub val u8::is_name: bool { get => this.is_alpha || this == '_'; } + +#! Whether the byte may go on a name: a letter, a digit, or `_`. +#! @param this The byte to check. +#! @returns Whether it is a letter, a digit, or `_`. +pub val u8::is_ident: bool { get => this.is_alnum || this == '_'; } + +#! Whether the byte is a decimal digit. +#! @param this The byte to check. +#! @returns Whether it is one of `0` to `9`. +@inline +pub val u8::is_digit: bool { get => this >= '0' && this <= '9'; } + +#! Whether the byte is a binary digit. +#! @param this The byte to check. +#! @returns Whether it is `0` or `1`. +pub val u8::is_bin: bool { get => this == '0' || this == '1'; } + +#! Whether the byte is an octal digit. +#! @param this The byte to check. +#! @returns Whether it is one of `0` to `7`. +pub val u8::is_oct: bool { get => this >= '0' && this <= '7'; } + +#! Whether the byte is a lowercase letter a hexadecimal digit may be. +#! @param this The byte to check. +#! @returns Whether it is one of `a` to `f`. +pub val u8::is_hex_lower: bool { get => this >= 'a' && this <= 'f'; } + +#! Whether the byte is an uppercase letter a hexadecimal digit may be. +#! @param this The byte to check. +#! @returns Whether it is one of `A` to `F`. +pub val u8::is_hex_upper: bool { get => this >= 'A' && this <= 'F'; } + +#! Whether the byte is a hexadecimal digit, of either case. +#! @param this The byte to check. +#! @returns Whether it is a decimal digit, or one of `a` to `f` or `A` to `F`. +pub val u8::is_hex: bool { + get => this.is_digit || this.is_hex_lower || this.is_hex_upper; +} + +#! Gives the value of the current byte as a digit of any base up to 36, where +#! the letters follow `9` in either case. +#! @param this The byte to convert. +#! @returns The value of the digit, or 99 when the byte is not a digit. +pub val u8::digit_value: u64 { + get { + if this.is_digit { return this - '0'; } + if this.is_lower { return this - 'a' + 10; } + if this.is_upper { return this - 'A' + 10; } + return 99; + } +} + +#! Checks if the current byte is a digit of the given base, of any base up to +#! 36, where the letters follow `9` in either case, as `digit_value` reads them. +#! @param this The byte that we are checking. +#! @param base The base of the number we are checking for. +#! @returns Whether the byte is a digit of the given base. +pub def u8::is_base_digit(&this, base: u8): bool { + return this.digit_value < base as u64; +} + +#! Whether the byte is any of several bytes. +#! @param this The byte to check. +#! @param chars The bytes to look for. +#! @returns Whether it is one of them. +pub def u8::matches(&this, chars: u8...): bool { + for value in chars { return true if this == value; } + return false; +} diff --git a/docs/algorithms.md b/docs/algorithms.md new file mode 100644 index 00000000..936fb491 --- /dev/null +++ b/docs/algorithms.md @@ -0,0 +1,663 @@ +# Plan: algorithms + +Written 2026-10-08, revised 2026-10-09 for `invokable`, which changes how +predicates, orders and keys are taken, and brought up to date 2026-10-20 for what std +and the compilers gained since: sorting, bisection, `heap`, `groups` and `runs` in std, +the iterators' consumers, `min`, `max` and `clamp` in `std::math`, lambdas typed from +`invokable` bounds, and lambdas that no longer allocate. This is a proposal. std is +yours, so the decisions at the end are yours to make. Much of what it proposed is in std +now, built apart from it; the rest isn't built. + +**Comes after the ffi plan, now built:** `std::sys` is `system`, and `@foreign` and +`@link` are `extern` sections. + +**Built in the rebuild alone** ([roadmap.md](roadmap.md), decision 1). Where this plan +says both compilers, C's half is left out. What was measured in C stays as measured. + +**What it is:** the operations on runs of elements that programs keep writing by hand: +- sorting; +- searching, including by bisection; +- testing, counting and finding; +- grouping elements by a key; +- reversing, filling and removing; +- a heap of least-first elements; +- `min`, `max`, `clamp` and `swap`. + +std has most of these now (see [What's there now](#whats-there-now)). What's left: +- orders and tests taken as anything `invokable`, sorting by a key, and a sort that + allocates nothing; +- `swap`, `reverse`, `fill` and `is_sorted`; +- for vectors, taking the last element out, keeping only some, and dropping repeats. + +**Its users:** +- **the compiler rebuild,** which moved onto std's sort, heap, groups, runs and + bisections on 2026-10-19, and still writes the rest by hand. See + [What the compiler gains](#what-the-compiler-gains); +- the random plan ([random.md](random.md)), whose `shuffle` swaps elements; +- the build tool, ordering files and steps; +- writers of documents that want keys in order, and every program that sorts. + +**Probed:** in the scratchpad, on 2026-10-08 and 2026-10-09 (`algo/`, since gone), and +again on 2026-10-20 (`plans/algorithms/`) against std as it is now. Each program was +built at `-O2` by the rebuild's own compiler and by the C compiler, and both gave the +same results. Times are the rebuild's where only one is given. The machine was busy on +2026-10-20, so those times are the best of three runs on one core. + +- **A generic sort** (2026-10-08): introsort over a private `comparer` trait, sorting + 1,000,000 random words: + + | How the order is given | Time | + |---|---| + | `<`, through `ordered` | 0.17 s | + | A function value | 0.23 s | + | The rebuild's own `sort_words`, a heap sort | 0.30–0.35 s | + + Also: + - Sorting 1,000,000 structs by a function value took 0.25 s. Packing the same two + fields into words and calling `sort_words` took 0.30 s. + - Sorting 100,000 strings by a function value worked. +- **std's sort** (2026-10-20), a stable merge sort, over a million random words made the + same way: + + | Sort | Rebuild | C | + |---|---|---| + | `sort`, by `<` | 0.19 s | 0.26 s | + | `sort_by`, a named function | 0.26 s | 0.31 s | + | `sort_by`, a lambda | 0.25 s | 0.31 s | + | 1,000,000 structs by a field, `sort_by` with a lambda | 0.19 s | 0.31 s | + | The introsort above, by `<`, written again beside it | 0.13 s | 0.17 s | + + The introsort allocates nothing and isn't stable. The merge sort takes a buffer as + long as the run. +- **Grouping by key** (2026-10-08): a counting sort of 1,000,000 items into 65,536 keys + took 0.02 s. The register allocator's way then, which packed, sorted, counted and + summed, took 0.33 s for the same order. std's `groups` counts this way now. +- **Bisection through a key function that captures nothing** (2026-10-08) ran as fast as + the loop written out: 3.24 s against 3.40 s for 10,000,000 searches. +- **Through `invokable`** (2026-10-09). The same introsort, generic over its order + `F: invokable` instead of the private trait, sorting 1,000,000 + random words: + + | How the order is given | Rebuild | C | + |---|---|---| + | `<`, through a functor, `by_order` | 0.14 s | 0.18 s | + | A functor comparing a key of its own | 0.15 s | 0.17 s | + | A function value | 0.22 s | 0.24 s | + | A function value held in a struct, as `comparer` held it | 0.23 s | 0.24 s | + + A function value costs the same through `invokable` as through a parameter of + function type, or held as `comparer` held it: 0.23 s in the sort. +- **Lambdas in a hot loop** (2026-10-20): 10,000,000 searches of 8 elements, each for a + value that changes: + + | Search | Rebuild | C | + |---|---|---| + | A loop over indexes, written out | 0.12 s | 0.24 s | + | `span::contains` | 0.19 s | 0.24 s | + | `any` of a span, generic over its test, given a functor holding the value | 0.19 s | 0.27 s | + | `for &each in v`, written out | 0.26 s | 0.42 s | + | `iter().any`, given such a functor | 0.26 s | 0.37 s | + | `any` of a span, given a lambda referring to the value | 0.44 s | 0.51 s | + | `iter().any`, given that lambda | 0.65 s | 1.45 s | + + - Memory grew in none. + - On 2026-10-09 such a lambda took 3.23 s (C 4.09 s), where a functor took 0.09 s, in + a probe searching for one value. Each lambda made then allocated twice. + - A named function given for the test, looking for a constant, took 0.13 s in the + rebuild, which calls it directly and inlines it, and 0.49 s in C, which calls it + through the value. + +**Found:** +- **A lambda allocates nothing now, but is called through its value.** + - Lambdas refer to the locals they use where those are (README, "Functions"), so the + two allocations are gone: 0.44 s where it was 3.23 s. + - The rebuild's `devirtualize` (compiler/optimizer/inline.sakura) calls a known + function value directly, so a named function, or a lambda referring to nothing, is + inlined once the algorithm is. "A function taking an environment is left called + through the value," so a lambda referring to locals isn't: 2.3 times a functor in + the search. + - A lambda given for `F` is of its function type, so all lambdas of one signature + share an instance of an algorithm. One the optimizer doesn't inline, as a sort, + calls its order through the value however the order was made. + + Decision 4 is about this. +- **A functor costs about what `span::contains` costs.** An algorithm generic over its + test is compiled for each functor's type, so `invoke` is a direct call, inlined at + `-O2`, and what the test needs is a field. It's still the cheap path, and needs no + change to the compilers. The loop over indexes is faster still in the rebuild, 0.12 s + against 0.19 s, where on 2026-10-09 they ran even. +- **A functor for a view's iterator takes `& &T`.** `v.view().iter()` gives `&T`, and + the consumers' tests take a reference to what's given, so `iter().any` wants + `invokable`. A functor taking `&block` doesn't meet it, in both + compilers. A lambda doesn't care (decision 3). +- **Bounds at methods work in both compilers now.** Both take + `def span::is_sorted(&this): bool where T: ordered`, and the method belongs only to + ordered `T` (README, "Methods and properties"). The C compiler refused it on + 2026-10-09, so this plan guarded such methods with `if const !(T is ordered)` and + `compile_error`. std's `lower_bound`, `upper_bound`, `sort` and `heap` still guard that + way, which gives a message of their own. Probed. +- **Lambdas take their types from `invokable` bounds,** in both compilers, and the + rebuild infers a type parameter from a lambda, as `F` of `take(f: F)` given + `def(x: i64): i64 => x`, as C did. That was phase 0 here, built with the iterators on + 2026-10-19. Probed. +- **Overloads still split the compilers.** Where `apply(x: i64, f: def(i64): i64)` and + `apply(x: i64, f: F) where F: invokable` take the same arguments, + the rebuild gives a lambda the function type and calls the first, and C refuses the + lambda, since no function type is expected. Neither gives a lambda its types from the + bound of a generic overload, even where the other overloads take fewer arguments. So + overloads still don't serve both forms (decision 1). Probed. +- **A key's type is inferred from what gives it,** in both compilers, as `K` of + `least_by_key` from a lambda giving a `u32`. Probed again. +- **A test taken by value is a copy.** A functor counting what it's asked counts in the + algorithm's copy, and lent as `&mut` it counts in the caller's. Both work in both + compilers. Probed again. +- **`strview` isn't `ordered`.** Its `compare` takes the other view by value, not as + `&self`, so `<` doesn't work on text views, in either compiler. Taking `&strview` fixes + it. `string` is ordered, so `sort` sorts strings, as std's tests do. +- **`for &each in v` over a vector runs about 1.4 times** `span::contains`, and twice the + loop over indexes, in the rebuild. It ran about 3 times `span::contains` on + 2026-10-09, before `maybe<&T>` was one word. std's algorithms loop over the span's + pointer. +- **`sort_words` is gone.** std's `sort`, `heap` and `groups` replaced both copies, in + `machine/heap.sakura` and `native/registers.sakura`, on 2026-10-19. +- **std's `sort_by` and `partition_point` take a function type,** `def(&T, &T): bool` + and `def(&T): bool`, where the iterators' adapters and consumers take + `F: invokable`. A functor reaches them only through a lambda calling it (decision 1). +- **std's `pop`s give nothing back.** `stack`, `queue` and `heap` `pop` the value `peek` + reads, and give nothing back. `vector::truncate()` removes the last, which `last()` + reads, and is named apart from `pop`, its comment says, since a vector is no stack. + So this plan's `vector::pop(): maybe` would be a `pop` unlike the others, and its + `truncate(length)` takes a name std uses (decision 5). +- **Fixed while probing** on 2026-10-09, in both compilers' sources, each with a test: + - The rebuild moved a functor called as `f(x)` to the heap on every call, where + `f.invoke(x)` kept it in the frame: 1.45 s against 0.09 s for the functor search. + Its `keeps` analysis also took `f(x)` to keep `f`. + - Fixing that showed an older fault: the rebuild's machine ran a function returning + a struct of no fields with a destination its code didn't take, and gave wrong + values or crashed. Native code was right. + - C refused `f(x)` in a generic of another module where `f` was a `&mut` functor + whose `invoke` wasn't `pub`, and accepted `f.invoke(x)`. + - The rebuild didn't infer the `K` of `invokable` from a function given + for it, which C did. + +## What's there now + +- **`span`** (std/containers/span.sakura): `index_of`, `last_index_of`, `count_of`, + `contains`, `equals`, `first`, `last`, `get` and `sub`. In a sorted run, `lower_bound` + and `upper_bound` by `<`, and `partition_point` by a test, `def(&T): bool`. +- **Sorting** (std/containers/sort.sakura): `sort`, by `<`, and `sort_by`, by a function + `def(&T, &T): bool`, of `slice` and `vector`. + - Both are stable. Runs of 16 are sorted by insertion, then merged in pairs, back and + forth with a buffer as long as the run, from the program's heap. No allocator is + taken. + - Elements are moved byte for byte, so strings and other owning values sort without + being copied or closed. + - One core, `sort_elements`, is generic over a private trait, `sort_order`: + `natural_order` gives `<`, and `given_order` holds the function. +- **`vector`:** `append`, `extend`, which copies a span's elements, `insert_at`, + `remove_at`, `remove`, `truncate()`, which closes the last, `first()` and `last()`, + which give a reference and stop the program where it's empty, `resize(size)` and + `resize(size, fill)`, `clear`, `reserve`, `drain(range)` and `from(iterator)`. Nothing + takes the last out, and there's no `retain` or `dedup`. +- **`heap`** (std/containers/heap.sakura): least first by `<`, with `push`, `peek`, + `pop`, which gives nothing, `view` and `clear`. No order but `<`. +- **`groups`** (std/containers/groups.sakura): elements gathered by a key from 0, in + two passes: `count` each key's, `seal`, which turns the counts into starts, then `put` + each. `of(key)` gives a run as a span. +- **`runs`** (std/containers/runs.sakura): many short lists in one block, each added + whole by `add(span)` or built by `push` and `end`, named by a `u32`, and read by + `view(id)`. +- **The iterators' consumers,** default methods of `iterator` + (std/traits/iterator.sakura), over any iterator, as `v.iter()`: `count`, `sum`, + `product`, `fold`, `reduce`, `any`, `all`, `find`, `position`, `min`, `max`, `min_by`, + `max_by`, `min_by_key`, `max_by_key`, `last`, `nth`, `for_each`, `to_vector` and + `into`. Their tests, orders and keys are anything `invokable` (README, "Control + flow"), and `rev()` walks a view from its far end. +- **`min`, `max` and `clamp`,** in `std::math` (std/math/exact.sakura), for every ordered + type. Of reals, `min` and `max` give NaN where either is NaN, and put `-0` below `0`. +- **`invokable` and `signature`,** in `std/traits`. Functions, lambdas and + addresses of C functions meet `invokable` through an `invoke` the compiler gives them. + A value of any other type is called through its own `invoke`, so `f(x)` works on all of + them. A lambda leaving out its types takes them from an `invokable` bound, in both + compilers. `function` (std/functions/function.sakura) holds any callable. +- **No** `swap`, `reverse`, `fill` of a slice, `is_sorted`, sort by a key, sort that + allocates nothing, or heap by an order given. + +## What it needs + +Of the ten needs this plan began with, std meets bisection, the tests over a run, +grouping, a heap, `min`, `max` and `clamp`, and owning elements sorted and moved. It +sorts stably. What's left: + +1. **Sorting by a key,** and **sorting in place without allocating** where equal + elements may move. +2. **Orders and tests of every kind** for `sort_by` and `partition_point`, as the + iterators take them: functions, lambdas, and functors holding what they need. +3. **Changing a run:** swapping, reversing and filling, and, for vectors, taking the + last out, keeping only some, and dropping repeats. +4. **`is_sorted`,** to check a run's order. +5. **As fast as code written out,** so the compiler loses nothing by using them. + +## How it fits the rules + +- **Elements are moved, never copied,** except where a type copies freely. + - `swap` copies plain data through a held value, and swaps the bytes of anything that + closes, so nothing is closed twice, as `heap`'s private `swap` does. + - Sorting and reversing move elements only by `swap`, or byte for byte as std's sort + does, so they work on strings and other owning values. + - `fill` copies, as `resize(size, fill)` does, so it needs `copyable` or plain data. +- **Nothing allocates** but the stable sorts, which take a buffer as `sort` does now, + and `groups`, which is a container. +- **Tests, orders and keys are anything `invokable` (decision 1):** a function, a + lambda, or a functor, or `&mut` one. + - Each is taken by value, as a function value is. A functor is copied in, or moved in + where it owns something. + - `&mut f` lends a functor instead, so the caller keeps it and sees what it changed. + - An algorithm is compiled for each functor's type, so a functor's `invoke` is a + direct call. +- **Orders come three ways:** + - through `ordered`, where `<` is inlined: `sort`; + - through anything invokable as `def(&T, &T): bool`: `sort_by`; + - through a key it gives: `sort_by_key`. + + One sorting core serves all three, generic over its order, as `sort_elements` is now. + `sort` gives it `by_order::{}`, `sort_by` the order given, and `sort_by_key` a + `by_key` holding the key's function. They take the place of the private + `sort_order`, `natural_order` and `given_order`. +- **Bounds:** `where`, on free functions, on a method's own type parameters, as `F` and + `K` of `sort_by_key`, on a struct, as `by_order` and `by_key`, and on a type's own + parameters at a method, as `def span::is_sorted(&this): bool where T: ordered`. Both + compilers take all four now. A guard of `if const` and `compile_error` still serves + where a message of its own reads better, as std's sort has one. +- **Nothing fails:** a bisection gives a position, and what may find nothing gives a + `maybe`. + +## The API (decisions 1, 2, 3 and 5) + +What's there stays as it is: `sort`, `lower_bound`, `upper_bound`, `heap`, `groups`, +`runs`, the iterators' consumers, and `std::math`'s `min`, `max` and `clamp`. This adds: + +```sakura +module std; + +# Two values. +pub def swap(a: &mut T, b: &mut T): void; # moves both, copying nothing that closes + +# Orders, which the sorts take as they take any other. +pub struct by_order : invokable where T: ordered {} # `<` +pub struct by_key : invokable + where F: invokable where K: ordered { pub var key_of: F; } # `<` of the keys + +# Reading a run: the tests, counts, least and greatest are the iterators' consumers, +# as `v.iter().any(test)` (decision 3). +pub def span::is_sorted(&this): bool where T: ordered; + +# In a sorted run: `partition_point` takes anything invokable, where it takes +# `def(&T): bool` now (decision 1). +pub def span::partition_point(&this, held: F): u64 # the first that fails + where F: invokable; + +# Changing a run where it is: methods of slice, and of vector as `sort` is. +pub def slice::sort_by(&mut this, before: F): void # stable, as now (decision 1) + where F: invokable; +pub def slice::sort_by_key(&mut this, key_of: F): void # stable + where F: invokable where K: ordered; +pub def slice::sort_unstable(&mut this): void where T: ordered; # decision 2; also + # `_by` and `_by_key` +pub def slice::reverse(&mut this): void; +pub def slice::fill(&mut this, value: T): void; +pub def slice::swap(&mut this, i: u64, j: u64): void; + +# Vectors (decision 5). +pub def vector::take_last(&mut this): maybe; # moved out; `truncate()` closes it +pub def vector::retain(&mut this, keep: F): void # in order; closes the rest + where F: invokable; +pub def vector::dedup(&mut this): void where T: equatable; # equal neighbours +``` + +`sort_by_key` takes its buffer as `sort` does, from the program's heap. + +```sakura +names.sort(); # strings are ordered +entries.sort_by_key(def(e) => e.size); # equal sizes keep their order +views.sort_by(def(a, b) => a.compare(b) < 0); # views aren't ordered + +# A lambda refers to `wanted` where it is, and allocates nothing. +val slot := this.free.view().iter().position(def(c) => c.size == wanted) else { return made(); }; + +# A functor holds what it tests against, and is called directly. A view's iterator +# gives `&block`, so its test takes `& &block`. +struct sized : invokable { var wanted: u64; } +def sized::invoke(&this, c: & &block): bool { return c.size == this.wanted; } + +val slot := this.free.view().iter().position(sized{ wanted = wanted }) else { return made(); }; + +# Lent as `&mut`, a functor keeps what it saw, once `sort_by` takes one (decision 1). +struct counting_order : invokable { var comparisons: u64; } +def counting_order::invoke(&mut this, a: &u64, b: &u64): bool { + this.comparisons++; + return a < b; +} + +var asked := counting_order{}; +words.sort_by(&mut asked); +println($"{asked.comparisons} comparisons"); + +deepest = math::max(inner, deepest); +while todo.take_last() is some(at) { + # ... +} +``` + +The two `position`s, `names.sort()`, `views.sort_by` and `math::max` work today, in +both compilers. Probed. + +## How each part works + +- **`sort_unstable`** is introsort (decision 2): + - quicksort with the median of three; + - insertion sort for runs of 16 or fewer; + - heap sort once the depth passes 2·log₂ n, so it's never quadratic. + + It's in place, allocates nothing, and isn't stable. Probed: 0.13 s against `sort`'s + 0.19 s for a million words. +- **One core, three orders, for each sort:** + - `sort`, `sort_by` and `sort_by_key` call one core, generic over its order + `F: invokable` and compiled for each order's type. std's merge + core is generic that way now, over its private trait. + - `by_order`'s `invoke` is `<`, a direct call inlined at `-O2`, so sorting numbers + costs no more than written-out code. A functor's order is as cheap. + - A function value or a lambda costs an indirect call per comparison, as through + `given_order` now: 0.26 s against 0.19 s. Every function value of a signature shares + one instance of the core, so not even a named function's order is inlined into it. +- **`sort_by_key`** is the stable merge sort through `by_key`, which compares the keys + its function gives. A functor's key cost 0.15 s against `<`'s 0.14 s on 2026-10-09. +- **`partition_point`** is the bisection there now, taking `F` rather than a function + type. The compiler's calls of it give lambdas, which still work. +- **`is_sorted`** compares each element with the one before. +- **`reverse`** swaps from both ends inward. **`fill`** copies its value into each + element, closing what was there. A slice's **`swap`** swaps two of its elements as the + free `swap` does. +- **`take_last`** moves the last element out and shortens the vector, giving `none` + where it's empty. +- **`retain`** moves the kept elements down in one pass and closes the rest. Calling + `remove_at` in a loop shifts the tail for every removal. +- **`dedup`** keeps the first of each run of equal neighbours and closes the rest, in + one pass. +- **Tests, orders and keys:** + - A functor is cheap: the functor search ran as fast as `span::contains`. In the + rebuild, a named function or a lambda referring to nothing is as cheap, where the + algorithm is inlined. + - A lambda referring to locals allocates nothing, but is called through its value: + 0.44 s against 0.19 s for the same search by a functor. That's fine outside hot + loops. + - Decision 4 is whether the rebuild learns to call that lambda directly too. + +## What the compiler gains + +These counts come from the rebuild as it stands on 2026-10-20: about 72,700 lines in +`analyzer/`, `compiler/`, `machine/`, `native/` and `entry.sakura`, where there were +about 49,000 on 2026-10-08. + +**Moved onto std on 2026-10-19,** apart from this plan: + +| Written by hand on 2026-10-08 | Sites then | Now | +|---|---|---| +| A heap sort of words with keys packed in, as `key << 32 \| item` | 5 calls, 2 copies of the sort | `sort` at 7 sites, `sort_by` at 3 and one more in `server/`, `heap`, and `groups` | +| Pack, sort, count, sum and scatter into a `*_first` array | 2: live-ins and gap moves | `groups` | +| Count, sum and fill, in two passes | 4 more | `groups` and `runs` | +| Loops from one `_first` entry to the next | at least 9 | `groups::of` and `runs::view` | +| Bisection | 5 | `lower_bound`, `upper_bound` and `partition_point`, at 10 sites | +| A binary heap | 1 | `heap`, of a start and an interval packed as a pair's key | +| A loop filling a vector after `resize` | 12 | `resize(size, fill)`, at 34 sites | +| A loop appending another run's elements | 6 | `extend`, at 81 sites | + +Seven `*_first` arrays are left, as `child_first`, `edge_first` and `row_first`. Some +index several vectors at once, as `child_first` does `child_starts`, `child_ends` and +`child_locs`, which neither `groups` nor `runs` holds. + +**Still by hand:** + +| Written by hand now | Sites | Becomes | +|---|---|---| +| `a < b ? a : b`, and the like | 38 | `math::min`, `max`, `clamp` | +| `val at: u32 = todo.last();`, then `todo.truncate();` | 29 | `take_last` | +| A loop filling a vector or array where it is | 6 | `fill` | +| Reversing | 1, in `code::reverse_postorder` | `reverse` | +| Searches by hand, as in the emitter's cells | several | `iter().any`, `position`, `index_of` | + +**Before and after.** The grouping and the bisection this section showed on 2026-10-08 +are done: `native/registers.sakura` counts, seals and puts the live-ins with `groups`, +and `analyzer/syntax.sakura` finds a declaration's first documentation line with +`partition_point`. What's left: + +```sakura +# compiler/flows.sakura, and 28 more. +while todo.length != 0 { + val at: u32 = todo.last(); + todo.truncate(); + +# After. +while todo.take_last() is some(at) { +``` + +```sakura +# compiler/emitter.sakura: whether a statement still closes a cell. +var kept := false; +for &each in this.kept { + kept = kept || each.cell == cell + 1; +} + +# After. The lambda refers to `cell` where it is and allocates nothing, but is called +# through its value unless decision 4(b) is built. +val kept := this.kept.iter().any(def(each) => each.cell == cell + 1); + +# Or, where it's hot, a functor, which costs what `span::contains` does. +struct closes_cell : invokable { var cell: u32; } +def closes_cell::invoke(&this, each: & &kept_value): bool { return each.cell == this.cell; } + +val kept := this.kept.view().iter().any(closes_cell{ cell = cell + 1 }); +``` + +```sakura +# analyzer/checker/generics.sakura: the deepest nesting of a type's parts. +deepest = inner > deepest ? inner : deepest; + +# After, with `import std::math`, which the compiler's sources don't import today. +deepest = math::max(inner, deepest); +``` + +```sakura +# compiler/intermediate/verifier.sakura: postorder turned round. +val length := order.length; +for i in 0..length / 2 { + val other := length - 1 - i; + val held: u32 = order[i]; + order[i] = order[other]; + order[other] = held; +} + +# After. +order.slice().reverse(); +``` + +**Speed:** +- **Sorting** became faster where `sort_words` was used: std's `sort` takes 0.19 s for + a million words, where `sort_words` took 0.30–0.35 s on 2026-10-08. + `sort_unstable` would take 0.13 s. +- **The two pack-and-sort groupings** became linear with `groups`. +- **Pops, `min` and `reverse`** cost what they cost now. +- **Loops over a vector** that become `any`, `position` or `count` run a little faster + given a functor, 0.19 s against 0.26 s for `for &each in v`. Given a lambda referring + to locals they run slower, 0.44 s, unless decision 4(b) is built. + +What's left hasn't been measured on a self-build. Phase 4 measures it, and keeps only +the changes that don't slow it. + +## Lambdas for `invokable` parameters (phase 0, built) + +Built with the iterators on 2026-10-19, in both compilers, as this section planned +(README, "Functions"): +- a lambda leaving out its types takes them from a type parameter's + `invokable` bound, with the type parameters inferred so far put in, and + one in the result not yet known, as `K` of a key, inferred from the lambda's result; +- the rebuild infers a type parameter from a lambda, as C does; +- a type parameter bounded only by `signature` still needs the lambda's types written. + +Overloads take no part: neither compiler gives a lambda its types from the bound of an +overloaded function (see Found). + +## Lambdas that refer to locals (decision 4) + +The memory work of 2026-10-19 built half of what this section planned. A lambda refers +to the locals it uses where they are, through an environment that is a cell of the +frame, so nothing moves to the heap and a lambda never allocates (README, "Functions"). +The search it took 3.23 s for on 2026-10-09 takes 0.44 s. + +What's left is the call. The rebuild's `devirtualize` turns a `call_value` whose +function is a known constant into a direct `call`, but leaves one taking an +environment called through the value. So a lambda referring to locals isn't inlined +into the loop calling it, and costs 2.3 times a functor: 0.44 s against 0.19 s. +Decision 4 is whether that call should be direct too: + +- **(a) Leave it.** A test that refers to locals in a hot loop is written as a functor, + and as a lambda elsewhere. Phase 4's measurements say where it's hot. +- **(b) Call a known lambda directly, environment and all.** `devirtualize` learns + closures: the call becomes a direct `call` given the environment. Once `any` is + inlined, the lambda is called directly, may be inlined in turn, and `promote` can then + make the locals it refers to plain values. + - It helps only where the algorithm is inlined into the code making the lambda, as + `any` and `position` are. A sort's core isn't, and calls each order through the + value, whatever this decides. + - What a program means doesn't change, only how a call is made, so the C compiler, + which only builds stage 1, needn't follow. + - It's smaller than the 150 lines planned on 2026-10-09, which included the frame + half, now built. It hasn't been estimated again. + - The 0.44 s case should come near the 0.19 s functor. That's the phase's measure. + +Only a type for each lambda would inline a lambda's order into a sort. That's a change +to the language, which the memory work left open, and isn't proposed here. + +## Testing + +- **`test/std/algorithms.sakura`, written with `std::testing`,** beside + `test/std/containers.sakura`, which tests std's sort, heap, runs and groups now, + covers: + - **sorting,** by `sort_unstable`, `sort_by` and `sort_by_key`: + - inputs of every length from 0 to 40, and of 1,000 and 100,000 elements; + - random, sorted, reversed, all equal, and organ-pipe orders; + - an input that defeats the median of three, to drive heap sort; + - checked by `is_sorted`, and against a count of each element; + - **stability** of `sort_by` and `sort_by_key`; + - **owning elements:** strings sorted, reversed, retained and taken out, each closed + exactly once, counted as the containers' tests count closes; + - **tests, orders and keys** given as named functions, lambdas with and without their + types, functors taking `&this` or `&mut this`, and functors lent as `&mut`, whose + state the caller reads after; + - **`partition_point`** given a functor, in empty runs, below and above every + element, and among repeats; + - **the rest:** `retain` closing what it drops, `dedup`, `fill`, `reverse` of odd and + even lengths, `take_last` of an empty vector, and `swap`. +- **Where they run:** in the rebuild's machine, as executables at `-O0` and `-O2`, and + under `run --checks`, which stops at a dangling reference or a block released twice, + and lists what leaked. The C compiler and its machine must give the same. +- **Direct calls of lambdas (phase 3, if decision 4(b)):** a test of the intermediate + code showing a direct `call` of a lambda given to `any`, and the probe's loop timed. +- **The compiler moved onto them (phase 4),** after each file: + - stage 2 equals stage 3; + - the corpus passes at every level; + - the rebuild's and std's tests pass; + - the self-build's instructions are measured against before. + +## Phases + +About 350 lines of std and 300 of tests, judged by the size of std's sort and +containers. Decision 4(b) adds to the rebuild's optimizer only. Moving the compiler onto what's left removes +few lines, about 50: it reads better rather than shrinks. + +0. **Lambdas for `invokable` parameters:** built with the iterators, 2026-10-19. +1. **`swap`, `by_order` and `by_key`;** `sort_by` and `partition_point` taking `F` + (decision 1), `sort_by_key` and `is_sorted`; the slice's `reverse`, `fill` and + `swap`; and `strview` becoming `ordered`. +2. **The vector methods** (decision 5), and **`sort_unstable`** (decision 2). +3. **Direct calls of lambdas,** if decision 4 is (b). +4. **The compiler moved onto them,** file by file: the pops, `min` and `max`, the + fills and the reverse, and searches, with functors where a test refers to locals in a + hot loop. The sorts, the heap, the groupings and the bisections moved on 2026-10-19. +5. **The README:** sorting and bisection, which it doesn't mention today, beside the + containers in "Variables and types", and the new methods. + +## Later, where wanted + +- **Runs already in order,** sorted in linear time: pdqsort for `sort_unstable`, or a + merge sort that finds the runs it's given, for `sort`. The compiler often sorts what's + nearly in order, such as blocks in layout order. +- **Order adaptors,** as `reversed`, which gives a descending sort from any order. +- **A heap by an order given.** The register allocator packs a start and an interval + into a `u64` so `heap` orders them by `<`. +- **`groups` from a key function in one call,** as `groups::by_key(items, keys, key_of)`, + which counts, seals and puts. +- **A sort's buffer from an allocator given,** so the compiler's sorts, whose vectors + are in its scratch arena, take their buffers from it too. +- **Merging and intersecting sorted runs.** The register allocator's `intersection` is + one. +- **A bit set,** for the 56 places the compiler makes a `vector`. +- **Selection,** as `nth_element`, and parallel sorting, now that `std::thread` exists. + +Built elsewhere since: **lazy adaptors,** as `map`, `filter`, `enumerate` and `zip`, +with the iterators on 2026-10-19, generic over their functions through `invokable`. + +## Decisions for you + +What was built since settled four of the eight decisions of 2026-10-09: +- **Where it lives:** module `std`, beside the containers, in + `std/containers/sort.sakura`, `heap.sakura`, `groups.sakura` and `runs.sakura`. +- **How they're spelled:** methods of `span`, `slice` and `vector`, as `v.sort()` and + `v.view().lower_bound(&x)`. Both compilers take `where` at a method now, so the + `if const` guards are a choice, not a need. +- **Grouping:** `groups`, filled in two passes by `count`, `seal` and `put`, with + `runs` for lists built one at a time. `seal` does what `prefix_sums` would have. +- **`min` and `max`:** in `std::math`, for every ordered type, with IEEE 754's rule for + reals. + +The decisions on how orders are given and what a test is are one now, the first below. +The rest are left: + +1. **What an order or a test is, for `sort_by` and `partition_point`:** + - **(a) Anything `invokable`, with `sort_by_key` beside them (recommended),** as the + iterators' adapters and consumers take them. A functor is called directly, `&mut` + lends one, and a lambda still leaves out its types, so no caller changes. The + private `sort_order` goes. + - **(b) Function types, as now,** with `sort_by_key` taking `def(&T): K`. A functor + is given as a lambda calling it, which is called through its value. + - **(c) Both, as overloads.** Each is declared twice, and C refuses a lambda where a + function type and an `invokable` overload take the same arguments, as probed. +2. **A sort that allocates nothing:** + - **(a) `sort_unstable`, an introsort, beside the stable `sort` (recommended).** It + takes 0.13 s against `sort`'s 0.19 s for a million words, and no buffer. All seven + of the compiler's `sort`s are of `u64` words, where equal ones can't be told apart, + so stability buys them nothing. + - **(b) Only the stable `sort`,** as now, and its buffer. +3. **Tests over a run:** + - **(a) The iterators' consumers, as `v.iter().any(test)` (recommended).** There's + one of each, and views take no more names. A functor for a view's iterator takes + `& &T`. + - **(b) Also methods of `span`:** `any`, `all`, `count`, `position`, + `last_position`, `least` and `least_by_key`, as this plan had them, taking tests of + `&T`. They read shorter and take a functor of `&T`, but repeat the consumers. +4. **Lambdas that refer to locals:** + - **(a) Leave them called through their value, and write a test that refers to + locals in a hot loop as a functor (recommended).** A lambda no longer allocates, + so it costs 2.3 times a functor, not 36 times. Direct calls can follow if phase 4 + shows lambdas costing where a functor would read badly. + - **(b) Also call a known lambda directly, environment and all.** Lambdas then cost + about what functors do, where the algorithm is inlined. It's in the rebuild's + optimizer only. +5. **The vector methods:** + - **(a) `take_last`, `retain` and `dedup` (recommended).** The compiler pops by hand + 29 times, and taking an owning element out needs a `move` of it before + `truncate()` closes what's left. `pop` stays the name of removing without giving + back, as the stack, queue and heap have it. + - **(b) The same, with the first named `pop`,** giving a `maybe`, and the `pop`s + of `stack`, `queue` and `heap` changed to match. + - **(c) None,** keeping `vector` as it is. diff --git a/docs/benchmarks.md b/docs/benchmarks.md new file mode 100644 index 00000000..3b70163d --- /dev/null +++ b/docs/benchmarks.md @@ -0,0 +1,626 @@ +# Plan: benchmarks + +Written 2026-10-18, and brought up to date 2026-10-20 for memory without a collector, +fixtures lent by reference, callables taken through `invokable` bounds, and a second probe +on Linux. This is a proposal. std is yours, so the decisions at the end are yours to make. +Nothing is built yet. + +**Comes after the ffi plan, now built:** `std::sys` is `system`, and `@foreign` and +`@link` are `extern` sections. + +**Built in the rebuild alone** ([roadmap.md](roadmap.md), decision 1). Where this plan +says both compilers, C's half is left out. What was measured in C stays as measured. + +**What it is:** measuring how long code takes, the way `std::testing` checks what it +does: +- functions marked `@bench`, which a runner finds and measures one after another; +- a report of each, as a typical time a round and how much it varied; +- saving what was measured, and comparing a later run with it; +- `keep`, which stops the optimizer from taking away the work being measured. + +**Its users:** +- std's containers: `dict` against `hashset`, the interner, sorting, and `vector` + growing. The abstraction and optimization work chose between these by timing by hand; +- the rebuild's hot spots that `docs/performance.md` names: hash tables, the lexer's + cost a token, and allocation; +- the optimizer: whether a pass makes code faster, at each `-O` level. The 2026-10-18 + passes were measured only by timing whole builds; +- the probes in `tools/`, which time calls, iterators and memory by hand, and check a + ratio between two ways of each; +- JSON, YAML and regex throughput; +- any program, comparing two ways of doing something. + +**Probed:** twice, in the scratchpad: +- on 2026-10-18 (`benchprobe/`), on Windows, with both compilers as executables at + `-O2`, the rebuild's at `-O0` too, and in both VMs; +- on 2026-10-20 (`plans/benchmarks/`), on Linux, the same, pinned to one P-core of an + i5-13420H. Other work kept the machine busy, so its numbers come from the runs where + it was quiet. + +The probes covered: +- **The steady clock,** which `instant::now()` reads: + - On Windows, through `QueryPerformanceCounter`, its smallest step is 100 ns. A read + took 30 ns in the rebuild's `-O2` executables, 58 ns in its `-O0` ones, and 94 ns + in the C compiler's `-O2` ones. + - On Linux, `CLOCK_MONOTONIC` steps by 1 ns, but std makes a system call for each + read. A read took 211 ns in the rebuild's `-O2` executables, 293 ns in its `-O0` + ones, and 220 ns in the C compiler's `-O2` ones. A C program reading the same clock + through the vDSO, as glibc does, took 25 ns. +- **What the optimizers take away from a loop timed by hand,** in nanoseconds a round, + the best of five runs of 20 million rounds, on Linux on 2026-10-20. The work is three + multiplies and shifts, as a hash finishes a word: + + | The loop | C compiler `-O2` | Rebuild `-O2` | Rebuild `-O0` | + |---|---|---|---| + | Empty | 0.48 | 0.24 | 0.38 | + | A constant in, the result stored to a global | 2.28 | **0.32** | 3.64 | + | A global read in, the result stored to a global | 2.24 | **0.27** | 3.70 | + | The counter in, the result discarded | **0.48** | **0.24** | 3.61 | + | The counter in, the result stored to a global | 2.20 | 1.79 | 3.65 | + | The counter in, the results summed and printed | 2.26 | 1.96 | 3.85 | + | In and out through a `@foreign def` that gives its argument back, the result stored | 2.18 | 1.79 | 7.75 | + | The same, the result discarded | **0.48** | **0.24** | 7.32 | + | In and out through relaxed atomics | 9.60 | 1.92 | 10.65 | + | The work in a function value read from a global, called each round | 4.67 | 3.20 | 4.88 | + + - The bold rows measured an empty loop. The rebuild moves work on a constant or a + global out of the loop, and the C compiler doesn't. + - Both compilers drop a result that nothing reads, even through a `@foreign def` with + a body, so going through one hides nothing. + - Relaxed atomics keep the work in both compilers. Three a round, a store and a load in + and a store out, cost the rebuild 0.1 ns over storing to a global, and the C compiler + 7.4 ns. + - The 2026-10-18 run on Windows found the same of a constant, a global, and a result + discarded. +- **A runner, written in a program of its own.** It found `@bench` functions through + `declarations()` and `attached`, as `std::testing` finds tests. It doubled the rounds + until a run took 1 ms, then took 51 runs as samples, each giving a time a round. Each + benchmark took 2–3 ms to calibrate and 60–90 ms to sample. A relaxed atomic stood in + for `keep`. + - **Medians on Windows,** on 2026-10-18, over three runs of each executable and one in + each VM: + + | Benchmark | C compiler `-O2` | Rebuild `-O2` | C compiler's VM | Rebuild's VM | + |---|---|---|---|---| + | `mixes`, the work above | 1.49–1.50 ns | 0.672–0.673 ns | 19.0 ns | 22.8 ns | + | `inserts_1000`, into a new `dict` | 13.2–13.3 µs | 4.84–4.85 µs | 141 µs | 159 µs | + | `formats`, interpolating two numbers | 83.1–84.5 ns | 54.10–54.12 ns | 130 ns | 173 ns | + + The median absolute deviation was under 0.5% of the median in the executables, + except the C compiler's `mixes`, at up to 1.4%. + - **Medians on Linux,** on 2026-10-20, over three runs of each executable, and eight to + ten of `links_100`: + + | Benchmark | C compiler `-O2` | Rebuild `-O2` | + |---|---|---| + | `mixes` | 8.17–8.23 ns | 1.92–1.93 ns | + | `inserts_1000` | 55.9–57.2 µs | 35.3–36.0 µs | + | `formats` | 227–228 ns | 172–173 ns | + | `links_100`, a list of 100 `box`es made and closed | 6.01–6.12 µs, and once 7.82 µs | 4.63–4.73 µs, and twice 5.76 µs | + + - The median absolute deviation was under 1.4% of the median in the rebuild, and + under 2.4% in the C compiler. + - The C compiler's `mixes` is mostly the stand-in for `keep`: four relaxed atomics a + round. + - **Allocation no longer splits the samples.** On 2026-10-18, `links_100` made a list + of 100 references from the collector each round. Its median was six times its + fastest sample in the rebuild (3.05 µs and 0.51 µs), and eight times in the C + compiler (8.71 µs and 1.07 µs), since most samples held a collection. With no + collector, its fastest sample is within 1% of its median in the rebuild, and within + 6% in the C compiler. + - **A build, or a run, can be off as a whole:** + - Code layout alone moved a result by 13%. `inserts_1000` took 4.85 µs in one + rebuild `-O2` build on Windows, and 5.47 µs in a build that only added other + benchmarks. + - On Linux, one executable gave `links_100` medians of 4.63–4.73 µs in eight runs + and 5.76 µs in two. Each run's own deviation was under 0.6%. + - **Calibrating can stop early.** In one Linux run, `inserts_1000` stopped doubling at + 2 rounds, 75 µs a run, where every other run of the rebuild's executable stopped at + 32. One slow run while doubling is enough to stop it. + - **Benchmarks in constants:** generic instances, as `@bench const views_u8 := + views::;`, worked in both compilers. A closure in a constant, as + `@bench const inserts_10 := def(b: &mut bencher): void { inserts(b, 10); };`, + worked in the rebuild, but the C compiler refused it, and still did on 2026-10-20. + See "Found along the way". +- **Fixtures, on 2026-10-20,** in both compilers: + - A fixture that closes, given by value to a benchmark the runner calls many times, is + refused: "`words` is closed where its scope ends, so it has one owner and is not + copied out of the place holding it." A test runs once, so `std::testing` can give + its fixture by value. + - Lent as `&F` or `&mut F`, a fixture was made once, lent to every run, and closed + once. + - `type_of(params_of(d)[1])` gives only the reference, and nothing gives the type it + refers to. Two overloads of a generic function, taking `def(&mut bencher, &F): void` + and `def(&mut bencher, &mut F): void`, found `F` from the benchmark itself. A + parameter that isn't a fixture gave the runner's `compile_error`. + - `if const type_of(params_of(d)[1]) is fixture` holds of a + fixture taken by value and not of one lent, so the runner can refuse the first with a + `compile_error` of its own. +- **`batched` taking lambdas, on 2026-10-20:** with `make` and `work` bounded by + `invokable`, both compilers took `b.batched(def() => shuffled(10000), def(v: &mut + vector) { v.sort(); })`, and inferred `T` from the first lambda. +- **Windows' CPU clocks:** + - `GetThreadTimes` and `GetProcessTimes` step by 15.625 ms, so they can't time a + 1 ms sample. + - `QueryThreadCycleTime` counts cycles exactly: 428.7 million in 100 ms busy, about + 4.29 GHz. But a cycle's length changes as the processor speeds up and slows down. + +## What's there now + +- **`std::testing`** (`std/testing.sakura`, the same in both trees): + - It finds `@test` functions and constants while compiling, through + `declarations()`, `attached` and `value_of`. It tells their shapes apart with `if + const value_of(d) is def(&mut tester): void` and `params_of`, and reports any other + with `compile_error`. + - It runs each test in a copy of the program: forked on Linux, started again with + `SAKURA_TEST_ONE` on Windows. + - It reads `--only TEXT` and `--here`. + - It gives a test a fixture by value, after the tester, made by the fixture's + `setup(t: &mut tester)`. The test runs once, and the fixture closes where the test + returns, where it's a type that closes. +- **`std::time`:** + - `instant::now()` reads the steady clock: `QueryPerformanceCounter` on Windows, and + `clock_gettime(CLOCK_MONOTONIC)` by a system call on Linux, not through the vDSO. + - `instant - instant` and `elapsed()` give a `duration`, which counts whole + nanoseconds in an `i64`. One divided by another is an `f64`, so `took / + nanoseconds(1)` is the nanoseconds as a real. + - `describe` writes one to two places, as "250ms". +- **No CPU clock.** `sys::clock` reads only `clock_kind::wall` and `clock_kind::steady`. + Nor does std pin a thread to a core: it reads the affinity only to count processors. +- **Nothing that stops the optimizer.** Neither compiler has `keep` or anything like it. + As the probe found, a loop timed by hand at `-O2` can measure nothing at all. +- **No collector, and no allocation counts.** Memory is owned, as the README's "Pointers + and memory" says, so there are no collections for a benchmark to account for. Each + block is taken from and given back to free lists as the program goes, and once the + program starts a thread, through a cache of that thread's own. A program still can't + ask how many blocks or bytes it allocated. `run --checks` knows every block, but only + lists those never released, as the program ends. +- **Benchmarks so far are probes timed by hand,** or scripts outside the language: + - `tools/function.sakura`, `tools/iterators.sakura` and `tools/memory.sakura` each time + one loop each way with `instant::now()`, keep the work by printing what it gave, and + check a ratio: a functor held in a `function` costs what a function value does; + adapters given functors are within 10% of `for &x in v`; a `box` costs within a + tenth of `raw_allocate`. Each is built at `-O2` and run pinned to a core with + `taskset`; + - CPU-time medians of whole builds, and profiles of `build -g` compilers through + `tools/profile/`; + - hand-timed loops in a plan's probe, as the random plan's. + +## What it needs + +1. **Benchmarks marked and found as tests are,** with nothing in the compiler knowing + about them, except `keep`. +2. **A way to keep the work being measured** from being moved or taken away, at every + `-O` level, that costs nothing itself. +3. **Rounds sized to the clock:** enough per sample that Windows' 100 ns clock step, and + a clock read of 30–94 ns there and about 210 ns on Linux, don't matter. +4. **Statistics that ignore outliers:** a median, and how much the samples spread. An + interrupt, a page fault, or another program's work makes a sample slower, never + faster. +5. **Setup that isn't timed:** once for a benchmark, through fixtures, and once a round + for work that uses up its input, such as sorting. +6. **Rates:** bytes a second, where a benchmark says how many bytes a round handles. +7. **Saving and comparing:** whether a change made code faster, slower, or neither, + given the noise. +8. **The same in the VM and as executables,** with the report saying which it is. + +## How it fits the rules + +- **A benchmark is a function with an attribute,** found by reflection while compiling, + as a test is. One that isn't one of the shapes below is a `compile_error`, which says + which shapes are allowed, as `tester::run` does. +- **`bencher` is plain data,** passed as `&mut bencher`. It owns nothing. +- **Inputs made for a batch belong to the runner,** in a vector it sized before. The + work borrows each one as `&mut T`. They're closed after the clock stops, so closing + isn't timed: the one-owner rule decides when, and the runner decides it's outside the + measurement. +- **Callables are taken as std's adapters take them,** through `invokable` bounds, so a + lambda given to `batched` is compiled for its type. It refers to the benchmark's + locals where they are, allocates nothing, and doesn't outlive the call. +- **A fixture** is made before calibration and closed after the last sample. Neither is + timed. In between it's lent to every run, as `&F` or `&mut F`: a fixture that closes + has one owner, so it can't be given by value to a benchmark run more than once. +- **The runner allocates nothing while timing.** Its vectors of samples are sized + before the clock starts. With no collector, what a benchmark allocates costs it as it + goes, and no pause lands in a later sample. +- **One thread.** Benchmarks run one at a time on the thread that called the runner. A + benchmark may start threads of its own. +- **Not while compiling.** The runner reads the clock, a system call evaluation + refuses, so a constant that runs it is noted as not constant. +- **`keep` changes no value.** A program means the same with every `keep` taken out. It + only limits what the optimizer may assume. + +## Layers + +### The compilers gain `keep` (decision 4) + +```sakura +#! Gives a value back as it is, while the optimizer takes it as unknown. The work +#! making the value is never taken away or moved out of a loop, and nothing is +#! worked out ahead from what it gives back. Memory a reference given to it +#! reaches is taken as read and written. Where the program runs, it costs nothing +#! beyond the value being made, and while compiling it is the value itself. +#! @tparam T The type of the value. +#! @param value The value to keep. +#! @returns The value. +@intrinsic +pub def keep(value: T): T; +``` + +- **The rebuild:** + - A new operation, `keep`, in `compiler/intermediate/code.sakura`, with the traits + `op_calls`. The passes go by an operation's traits, so none moves it, merges it, or + takes it away: `dead.sakura`, `loops.sakura` and `sink.sakura` remove or move only + loads and what `code::removable` allows, which no call is. Numbering doesn't take + its result as its operand, so nothing is folded through it. + - `escapes.sakura` and `keeps.sakura` already take what an intrinsic is given as kept, + so `keep(&buffer)` keeps the buffer in memory with nothing added there. + - `emitter/intrinsics.sakura` emits it. + - Natively it's a move into a register, which the allocator usually removes. In + bytecode it's a move. +- **The C compiler:** + - `INTRINSIC_KEEP` in `sources/table.h` and the intrinsic table in `checker.c`. + - `compiler.c` emits an instruction that `optimizer.c` doesn't mark `pure`, and that + reads and writes memory, as a call does. + - `machine.c` and `native.c` treat it as a move. + +### `std::testing` gains (decision 1) + +```sakura +#! Marks a function, or a constant holding one, as a benchmark that `bencher::run` +#! measures, as `@test` marks a test. +#! +#! A benchmark is a `def(b: &mut bencher): void` that does its work `b.rounds` +#! times. It may also take a fixture after the bencher, by reference, as +#! `def(b: &mut bencher, text: &sample_text): void`, which is made once before it +#! is measured, lent to every run, and closed after, untimed. +@usage{ on = target::functions | target::constants } +pub struct bench : attribute { + pub val name: strview = ""; #! What the report calls it, which is its path when this is empty. + pub val skip: bool = false; #! Whether it is left out, which the report counts. +} + +#! What a benchmark is run with. +pub struct bencher { + pub val rounds: u64; #! How many times to do the work in this run. + pub var bytes: u64; #! How many bytes a round handles, which the report gives a rate of where set. +} + +#! Does the work once for each of `rounds` inputs that `make` gives, timing only +#! the work. `make` runs before the clock starts, and what it gave is closed after +#! the clock stops. Each is compiled for the callable given, as a lambda. +pub def bencher::batched(&mut this, make: M, work: W): void + where M: invokable where W: invokable; + +#! Measures every benchmark of the program, one after another (decision 2), and +#! reports each as it finishes. +#! +#! The arguments may say: +#! - `--only TEXT`: the benchmarks whose name holds the text; +#! - `--time MS`: how long each sample runs at least, 1 by default; +#! - `--samples N`: how many samples are taken, 51 by default; +#! - `--save FILE`: write every sample to the file, as JSON; +#! - `--compare FILE`: compare with the samples saved there (decision 3). +#! @param args The arguments the program was given. +#! @returns The status to stop with: zero unless a benchmark could not run. +pub def bencher::run(args: span): i32; +``` + +`std::sys` gains nothing: the steady clock is enough. Two reads a sample of 1 ms are +0.04% of it, even at a system call each on Linux. + +## Using it + +```sakura +import std; +import std::io; +import std::json; +import std::sys; +import std::testing; + +# The work itself, in the loop: for the smallest work, with no call each round. +@bench def hashes_words(b: &mut bencher): void { + for i in 0..b.rounds { + val word := keep(i); + _ = keep(hash(&word)); + } +} + +# Text read once by a fixture, so reading it isn't timed, and closed after the last +# sample, as the string it holds closes. +struct sample_text : fixture { + var data: string; +} + +def sample_text::setup(t: &mut tester): sample_text { + val at := path::parse("bench/sample.json") else (_) { return sample_text {}; }; + var text := io::read_file(&at) else (_) { + _ = t.expects(false); + return sample_text {}; + }; + return sample_text { data = move(&mut text) }; +} + +# The fixture lent to every run. A rate is reported. +@bench def parses_json(b: &mut bencher, text: &sample_text): void { + b.bytes = text.data.length; + for _ in 0..b.rounds { + val doc := json::parse(text.data.view()) else (_) { return; }; + _ = keep(&doc); + } +} + +# Work that uses up its input: each round sorts a vector shuffled before the clock +# started. +@bench def sorts_10000(b: &mut bencher): void { + b.batched(def() => shuffled(10000), def(v: &mut vector) { v.sort(); }); +} + +# One generic benchmark, measured at two types. +@bench const fills_u8 := fills::; +@bench const fills_u64 := fills::; + +def main(args: span): void { + exit(bencher::run(args)); +} +``` + +Built and run: + +``` +sakura build -O2 --std std -o bench.exe bench/*.sakura +bench.exe --only json --save before.json + ... a change ... +bench.exe --only json --compare before.json +``` + +The report would read like this. The numbers are only for illustration: + +``` +windows-x86_64, native: 51 samples of at least 1 ms each +[ BENCH ] hashes_words 0.673 ns ±0.2% +[ BENCH ] parses_json 1.21 ms ±0.4% 412 MB/s +[ BENCH ] sorts_10000 402 µs ±0.9% +[ BENCH ] fills_u8 2.10 µs ±0.3% +``` + +And compared: + +``` +parses_json 1.21 ms -> 1.09 ms -9.9% faster +sorts_10000 402 µs -> 405 µs +0.7% same +``` + +## How each part works + +- **Calibrating:** + - The benchmark runs with 1 round, then 2, 4 and so on, until one run takes at least + the sample time, 1 ms by default. That's ten thousand of Windows' clock steps, so + the step is under 0.01% of a sample. + - Calibrating also warms the caches, and lets the code page in. + - One slow run stops the doubling early, as the Linux probe found once. So the rounds + found are run once more, and doubled on while that run is under the sample time. + - The probe took 2–3 ms for each benchmark. +- **Sampling:** + - The rounds found are run 51 times. Each run is one sample: its time divided by its + rounds. + - An odd count makes the median one of the samples. + - The probe took 60–90 ms for each benchmark, so a hundred benchmarks take about ten + seconds. +- **The report:** + - **The median,** which an interrupt or a page fault hardly moves. + - **The median absolute deviation,** as a percentage of the median. + - **Not the fastest sample.** The 2026-10-18 report showed it where it was under half + the median, since that meant most samples held a collection. With no collector, + `links_100`'s fastest sample is within 6% of its median, so a wide spread shows in + the deviation alone. + - **A rate,** where `bytes` is set: bytes a round over the median, in MB/s of 10^6 + bytes. + - **Times to three figures,** in ns, µs, ms or s. Interpolation writes a real in full, + and `describe` counts whole nanoseconds, so the runner rounds them itself. + - **The header** names the system and the backend, through the `os`, `arch` and + `backend` intrinsics, so a VM's numbers aren't mistaken for an executable's. +- **`batched`:** + - Inputs are made in batches of up to 1,024. Each batch is timed on its own, and the + times are summed, so a batch's inputs needn't all fit in memory at once. + - Each round is one call of `work`, compiled for the lambda given, so at `-O2` it's + inlined. By `tools/function.sakura` on 2026-10-20, such a call costs 0.50 ns in + the rebuild's `-O2` executables and 1.78 ns in the C compiler's, against 2.78 ns + and 4.80 ns for a function value. Work that needs fresh input usually takes far + longer than either. +- **Saving (`--save`):** + - A JSON object, written through `@serial` structs and `json::to_text`, and read back + by `json::from_text`, which the probe did in both compilers. It holds the header, + then each benchmark's name, rounds, bytes, and every sample, in nanoseconds a round. + - `io::write_file` gives a `result`. A file that can't be written is + reported, and the status is 1. +- **Comparing (`--compare`, decision 3):** + - For each benchmark in both runs: the old median, the new median, and the change. + - **"faster" or "slower"** only where a Mann–Whitney U test on the two sets of + samples gives p < 0.01, and the medians differ by at least 1%. Otherwise "same". + - The test compares ranks, so it doesn't assume the samples are normal. They + aren't: interrupts and page faults only ever slow a sample down. + - With 51 samples a side, the normal approximation of U is close. It needs only + sorting and a square root. + - **A header that differs,** as a VM against an executable, is said before anything + else. + - **The 1% floor is a guess,** and may be too low: the probe saw code layout alone move + a result by 13% between two builds of the same benchmark. The documentation should + say that a change of a few percent between builds may be layout. Building twice, + with an unrelated change, shows how big that is. + - **Two runs of one build can differ too.** The Linux probe's `links_100` was 4.63–4.73 + µs in eight runs and 5.76 µs in two, while each run's samples agreed within 0.6%. The + U test on one run a side would call that a change, so the documentation should say + to compare a few runs a side before believing one. +- **A benchmark's shapes,** checked while compiling: + - `def(b: &mut bencher): void`; + - `def(b: &mut bencher, f: &F): void` or `def(b: &mut bencher, f: &mut F): void`, + where `F` is a `fixture`, lent to every run. Its `setup` takes a tester, which + the runner makes, and where a check fails, the benchmark fails with that check's + message. A fixture taken by value, as a test takes one, is a `compile_error` saying + to take it by reference; + - a constant holding any of these, including a generic instance. + - The runner finds `F` through two overloads of a generic function, one taking + `def(&mut bencher, &F): void` and one `def(&mut bencher, &mut F): void`, since + `type_of` gives the parameter's type only as the reference. +- **`keep` in a benchmark:** + - **Input:** `keep(i)` stops the work from being worked out once, ahead of the loop. + - **Output:** `keep(result)` stops it from being dropped. + - **A reference:** `keep(&buffer)` keeps the writes into a buffer that nothing reads + after. + +## Testing + +- **The runner, in each tree's std tests** (`tests/std/bench.sakura` in the C + compiler's tree, `test/std/bench.sakura` in the rebuild's), written with + `std::testing`: + - **calibration and sampling against a clock the test drives:** the runner reads its + clock through a function value inside, so a fake clock gives fixed times. That + covers doubling, stopping at the sample time, and the count of samples; + - **statistics on fixed samples:** + - the median and the median absolute deviation; + - Mann–Whitney U and its p, against SciPy's `mannwhitneyu`, run once in the + scratchpad. SciPy isn't installed here, so that run installs it; + - **numbers in the report:** three figures, and units changing at 1,000; + - **`--save` read back by `--compare`,** a header that differs, a benchmark in only + one of the two, and a file that can't be written; + - **fixtures:** made once, lent to every run, and closed once, as `&F` and as `&mut F`; + - **`batched`:** each input made once and closed once, outside the time; + - **`--only` and `skip`;** + - **shapes that aren't allowed,** as `compile_error`s, in the analyzer's tests. +- **`keep`, in each compiler's tests:** + - At `-O2`, a loop of `keep(mixed(keep(i)))` still holds its multiplies: + - in the rebuild, by its IR tests and `--verify`; + - in the C compiler, in `tests/native.c`. + - `keep(42)` isn't folded. + - `keep(&buffer)` keeps stores that nothing reads after. + - A corpus program printing values through `keep` gives the same output at every + level, and in the VM. +- **Where they run:** both compilers, in the VM and as executables at `-O0` and `-O2`, + and under `run --checks`, which stops where an input or fixture is used after it's + closed, and lists the blocks of any never closed. (`SAKURA_COLLECT_ALWAYS=1` went with + the collector.) + +## Phases + +About 60 lines in each compiler for `keep`, 700 of `std::testing`, and 400 of tests. + +1. **`keep`, in both compilers,** with its tests. +2. **The runner:** `@bench`, `bencher`, calibrating, sampling, the report, `--only`, + `--time` and `--samples`. Lent fixtures and constants included. Mirrored in both + stds. +3. **`batched` and rates.** +4. **`--save` and `--compare`.** +5. **Benchmarks of std,** in a `bench/` directory beside each tree's tests: + - containers, hashing, sorting and formatting; + - JSON and YAML throughput; + - and in the rebuild, its lexer, interner and hash tables, which + `docs/performance.md` names; + - and the probes in `tools/`, `function.sakura`, `iterators.sakura` and + `memory.sakura`, as benchmarks in place of their loops timed by hand. +6. **A "Benchmarks" section in the README.** + +## Found along the way + +- **The C compiler refuses a closure in a constant whose body calls what can't run + while compiling.** The rebuild accepts it, and runs it: + + ```sakura + def shown(n: u64): void { println($"shown {n}"); } + const plain := def(): void { shown(1); }; + # C compiler: "Value is not known while compiling. `shown` cannot run while + # compiling: it calls `println`, which reads `output_held` ..." + ``` + + Making a closure doesn't run its body, so this looks like a fix to the C compiler. + It still held on 2026-10-20, and also where the closure only fills a `dict`, which C + refuses since `dispose` "is a method of a trait that is not a `const def`". Until it's + fixed, std's own benchmarks write one function a size, since both compilers run them. +- **std can't write a real to a number of places.** Interpolation writes + `1.4970779418945312`, and `describe` counts whole nanoseconds. The runner rounds + numbers itself, but a formatter in std would serve it, and others. Still so on + 2026-10-20: `lpad` and `rpad` pad text, but nothing rounds a real. +- **Reading the steady clock costs three times as much in the C compiler's + executables on Windows** (94 ns) as in the rebuild's (30 ns). Both call + `QueryPerformanceCounter`. Not probed again, as Windows wasn't at hand. On Linux the + two cost the same, 220 ns and 211 ns. +- **Relaxed atomics cost the C compiler time,** and cost the rebuild nothing. On + Windows, one round of them cost it 1.3 ns. On Linux, three a round cost it 7.4 ns, + and the rebuild 0.1 ns. On x86-64, a relaxed load or store is a plain `mov`. +- **On Linux, std reads the steady clock by a system call,** about 210 ns a read in both + compilers' executables, where glibc's `clock_gettime` reads it through the vDSO in + 25 ns. A sample of 1 ms doesn't notice, but code timing short spans by hand does. + +## Later, where wanted + +- **Allocation counts:** blocks and bytes allocated a round. With no collector, there + are no collections to count or force. This needs a counter in each of the four + runtimes: both compilers' native runtimes, in the rebuild's `runtime/memory.sakura` + and C's `std/runtime/memory.sakura`, and both VMs. Since threads allocate from caches of their + own, each thread counts its own. +- **Timing whole programs:** running a command a number of times and giving the median + of its CPU time, as the optimizer work measured builds. `std::process`'s status would + gain the child's CPU time: `GetProcessTimes` on Windows, and `wait4`'s `rusage` on + Linux, where `sys::wait` already calls `wait4`, asking for none. On Windows, it comes + in 15.625 ms steps. +- **Ratios within a run,** as the probes in `tools/` check theirs: adapters within 10% of + a loop, a `box` within a tenth of `raw_allocate`. A benchmark would name the one it's + measured against, and the report would give the ratio. +- **The steady clock through the vDSO on Linux,** 25 ns a read rather than 210 ns. The + runtime would find it through the auxiliary vector's `AT_SYSINFO_EHDR`, as C libraries + do. +- **Cycles a round,** where the system counts them: `QueryThreadCycleTime`, or Linux's + performance counters. +- **Steadier numbers:** pinning the thread to one core (`SetThreadAffinityMask`, + `sched_setaffinity`), and a higher priority. +- **A failing status for slowing down,** as `--compare FILE --slower 5`, for a check + before merging. +- **The `-O` level in the header,** and whether `run --checks` is checking every access, + neither of which an intrinsic gives yet. `lanes_held()` tells only the rebuild's `-O2` + executables from the rest. + +## Decisions for you + +1. **Where it lives:** + - **(a) In `std::testing` (recommended).** It shares the walk over attributes, + `--only`, fixtures, and the style of the report. A program importing + `std::testing` gets both. + - **(b) In a module of its own, `std::bench`.** It's separate from tests, but + repeats the walk and the arguments, or the two share code through a third module. +2. **How benchmarks run:** + - **(a) One after another in one program (recommended),** as Go and Criterion run + them. + - There's no copying, and no protocol for handing samples back. + - A benchmark that faults stops the run, with its trace. + - What one benchmark leaves behind can change the next. There's no collector's heap + now, but the blocks it released wait on the free lists, the chunks it opened stay + open, and once any benchmark starts a thread, every allocation after goes + through a thread's cache. `--only` measures one alone. + - **(b) Each in a copy of its own, as tests run.** + - Each starts from the memory the program had before the runner, so the order + doesn't matter, and a fault fails alone. + - But a copy must hand its samples back: through a pipe on Linux, and through a + handle named in the environment on Windows. That isn't probed. +3. **Comparing:** + - **(a) A Mann–Whitney U test on every sample, with a 1% floor (recommended).** This + needs every sample saved, about 1 KB of JSON for each benchmark. + - **(b) Medians only,** where the change is called real when it's over three median + absolute deviations. This is simpler and saves less, but it's worse at telling + noise from a change. + - Either way, each side is one run, and the Linux probe saw two runs of one build + differ by a fifth. `--save` could add a run to its file rather than replace it, so + that `--compare` weighs several. +4. **`keep`'s name and home:** + - **(a) `keep`, in `std::testing` (recommended).** The rebuild's corpus has programs + with functions of their own named `keep`, and `std::args` has a private one, so it + isn't put in module `std`, where every program would see it. Programs that + benchmark import `std::testing` anyway. + - **(b) `black_box`, as Rust names it, in module `std`.** No program here uses that + name, and the optimizer's own tests could use it without `std::testing`. +5. **Samples by default:** + - **(a) 51 samples of at least 1 ms (recommended).** That's 60–90 ms a benchmark. On + Windows, the probe's medians repeated within 0.3% in the rebuild, and within 1.7% + in the C compiler. On Linux, within 2.3% in both, but for the runs of `links_100` + that were off by a fifth as a whole, which more samples in one run wouldn't fix. + - **(b) A time for each benchmark, as Criterion's 5 seconds,** with as many samples + as fit. That's steadier, but a hundred benchmarks take minutes. diff --git a/docs/freestanding.md b/docs/freestanding.md new file mode 100644 index 00000000..c8a74d5d --- /dev/null +++ b/docs/freestanding.md @@ -0,0 +1,607 @@ +# Plan: programs with no operating system + +Written 2026-10-20. This is a proposal. The language is yours, so the decisions at the end +are yours to make. Nothing is built yet. + +**Comes after the ffi plan, now built:** `std::sys` is `system`, and `@foreign` and +`@link` are `extern` sections. + +**Built in the rebuild alone** ([roadmap.md](roadmap.md), decision 1). Where this plan +says both compilers, C's half is left out. What was measured in C stays as measured. + +**The std plan is built:** `core/` and `system/` are libraries found beside the +compiler, and `core` needs nothing of a system but memory and `fault`. + +**The runtime is a library of its own** since 2026-10-21: `runtime/` (`rt/` for part of +2026-10-26), found beside the compiler as `core/` and `system/` are, whose module is +`runtime`. It needs `core` and +`system`, and nothing of std, so std plays no part in a build that doesn't import it. + +**The short answer:** +- **The std plan's `core` makes the source freestanding.** None of its files has a + `when os` section. Its only ties to a platform are intrinsics: the heap's, `fault`'s, + atomics' and lanes'. +- **An executable is more than that source.** Three things tie every native build to + Linux or Windows: + 1. **The runtime** the compilers build into every executable: the module `runtime`, + whose 16 helpers they call by name. + 2. **Code the compilers write themselves:** `_start`, the fault handlers, the trap + stub, thread starts. All of it makes system calls or calls `kernel32`. + 3. **What generated code assumes:** + - a thread record at `gs`, read by function prologues; + - an image at `0x400000` addressed absolutely; + - SSE2 and x87 turned on; + - an ELF or console PE. +- **Allocation is the smallest of these.** The heap's algorithm is already plain Sakura: + size classes, chunks, free lists, thread caches. Only taking memory from the system + (`mmap`, `mprotect`, `mremap`, `VirtualAlloc`) and the lock (`futex`, `WaitOnAddress`) + belong to a platform. Split there, the algorithm goes into `core`, and a platform + gives it pages. On bare metal, that's a region of the image, or what the boot memory + map says is free. +- **Alongside the platforms there now, the platform becomes a layer the target chooses.** + - `linux-x86_64` and `windows-x86_64` keep the runtime of `runtime/`. + - A new `none-x86_64` takes the program's own: a module `platform` of up to four + functions, of which only `stop` is required. + - The compilers write a start for it that needs no system. +- **Operating systems need more than a target:** + - privileged instructions; + - memory the optimizer leaves alone (`volatile`); + - interrupt handlers; + - alignment and packing; + - a kernel in the top 2 GiB. + + None of these exists yet, in either compiler. + +**Its users:** +- **Kernels and bootloaders,** in ring 0, booted by a loader such as Limine. +- **Programs for an operating system of one's own,** in ring 3, whose platform module + makes that system's calls. +- **UEFI tools,** later, whose platform is the firmware's boot services. +- **Programs on Linux and Windows,** which are unchanged. The heap's split moves code + but not behavior. + +**Probed** on 2026-10-20, in the scratchpad's `plans2/f/`, with `x2` (the rebuild's fixed +point) and `cexp/sakura` (C's working tree), and by three searches of both compilers' +sources. A program summing a vector, built at `-O2`: + +| | Rebuild | C | +|---|---|---| +| Executable | 164 KB | 761 KB | +| Kind | ELF `ET_EXEC`, base `0x400000`, segments `.rodata`, `.data`, `.text`, `.lines` | the same | +| Instructions reading through `gs` | 55 | 174 | +| `syscall` instructions | 42: `_start`, the heap, its lock, threads, `fail`, `exit`, the trap stub | 61 | +| Instructions naming an `xmm` register | 133: formatting, `memcpy`, clearing, comparing | 101 | +| RIP-relative operands | 0 | 0 | +| Stores below `rsp` (the red zone) | 0 | 0 | + +- **`core`'s source has no `when` section.** The copy of `core` the std plan probed (11,294 + lines) has none, and its intrinsics are only the heap's, `exit` and `abort`, atomics, + lanes, bits, and compile time. +- **Linux lets a program here set its own `gs` base.** `AT_HWCAP2` holds FSGSBASE, and a + C program's `wrgsbase` and `rdgsbase` worked in user mode on this machine. So a + freestanding image can be tested as a Linux process ([Testing](#testing)). +- **There's no QEMU here.** Booting a kernel needs `qemu-system-x86_64`, and UEFI + needs OVMF as well. + +## What's there now + +### What an executable takes from its platform + +| Piece | What it does now | What it needs of the system | +|---|---|---| +| `_start` (rebuild `native.sakura:1080-1141` in `sakura-native`, C `native.c:5208-5277`) | Points `gs` at the first thread's record, reads the thread's ID, maps a stack, installs a `SIGSEGV` handler, probes the CPU, runs `processor` over the environment, then `` and `main`, then exits with 0 | `arch_prctl`, `gettid`, `mmap`, `rt_sigaction`, `exit_group`; argc, argv and envp on the first stack. On Windows, `kernel32` throughout (`windows.sakura:306-365`) | +| Stacks | The rebuild keeps frames on `rsp`, 32 MiB mapped. C keeps frames on a stack of its own through `rbx` (8 MiB), and return addresses on `rsp` (33 MiB) | `mmap`, or the system's thread stack | +| The thread record | 32 words at `gs`. It holds the stack limit (word 1), the trap frame, the record itself, C-call words, signals, heap caches and format builders | Something must set the `gs` base: `arch_prctl`, or a TLS slot on Windows | +| The 16 helpers, by name in `runtime` (rebuild `native.sakura:31-58`, C `native.c:210-250`) | `fail`, `arguments`, `allocate`, `allocate_untraced`, `release`, `resize`, `equal`, `format_begin`, `format_text`, `format_value`, `format_owned`, `exit`, `abort`, `processor`, `start_thread`, `thread_main`, and `system_start` on Windows | Formatting, `equal` and the heap's logic need nothing. The rest map memory, write, exit, lock or start threads | +| The heap (`runtime/memory.sakura`, 809 lines) | 19 size classes carved from 1 MiB chunks, in up to 64 GiB of reserved address space. Larger blocks are mapped alone. Caches per thread once threaded | `mmap` with `PROT_NONE`, `mprotect`, `munmap`, `mremap`; `VirtualAlloc` on Windows. A `futex` or `WaitOnAddress` lock once threaded | +| Faults | Checks call the trap stub, which calls `fail`. A second trap while reporting exits at once, by `exit_group` written inline. A null read faults in page 0, and the `SIGSEGV` or vectored handler turns it into a report | `fail` allocates from the heap, walks the `rbp` chain over the `.lines` tables, writes to descriptor 2, and exits with 1 | +| Safe points | Only where `std::sys::handle` is used | Signals | + +**Generated code assumes:** +- **The stack limit through `gs`.** + - The rebuild checks `rsp - frame` against `gs:[8]` in every prologue but a small + leaf's (`calls.sakura:1039-1047`). + - C checks `rbx + frame` against `gs:[8]` in every one (`native.c:3868-3880`). +- **SSE2 and x87, always.** + - Floats are scalar SSE2. + - Copies and clears up to 128 bytes, and the rebuild's prologue zeroing, go through + `xmm` registers. + - Float `%` is x87's `fprem`. + - AVX is chosen at run time, from the probe. +- **Frame pointers, always,** for traces. **No red zone.** +- **Absolute addresses:** + - `[disp32]` with no base, sign-extended; + - in the rebuild, also `mov r32, imm32`, which is zero-extended, and switch tables of + `u32`. + + So an image runs only where it was linked, in the low 2 GiB. + +**The image** (rebuild `binary::elf` and `binary::pe`, in `binary`; C `elf.c`, `pe.c`): +- `ET_EXEC` at `0x400000`, or a console PE with its relocations stripped that imports + `kernel32`. +- No `.bss`: `.data` is written whole, zeros and all, so a large zeroed global grows + the file. +- No object files, no flat binaries, no linker. +- An ELF calling C names `/lib64/ld-linux-x86-64.so.2`. +- `build_options.stack` exists in both compilers, but nothing sets it. + +**Targets are a closed list in each compiler:** +- the rebuild's `platform` enum (`entry.sakura:107-110`), `checker::target_value` + (`checker/declare.sakura:146-171` in `sakura-analyzer`), and + `build_options.windows: bool`, tested in about 18 places; +- C's `target_parse` and `context_build` (`context.c:114-133`, `501-504`), the names in + `table.c:16-25`, and `native.c`'s Windows-or-else (`5994`). + +`os` may be `linux`, `macos`, `windows` or `freebsd`, and none of these means "no +system". + +### What the language has for systems work + +**There:** +- **Raw pointers,** with arithmetic, and `as` between integers and pointers, so a device + register's address can be a pointer. +- **`cfn`** made from an address. +- **Atomics,** with C11's orders. A fence keeps loads and stores from moving across it, + in both optimizers, even where no instruction is emitted. +- **Struct layout as C's:** fields in order, each aligned to itself, never reordered. + It's stated only in the compilers' sources. `@foreign` unions overlay their fields. + +**Not there, in either compiler:** +- **Inline assembly,** or any intrinsic for `in`/`out`, `cli`/`sti`/`hlt`, control + registers, MSRs, `lgdt`/`lidt`/`ltr`, `invlpg`, `iretq`, `swapgs`, `rdtsc` or `pause`. + - The encoders emit only `syscall`, `cpuid`, `xgetbv`, `mfence`, `lock`, `rep`, + `ud2`, `vzeroupper` and `fprem` beyond ordinary code. + - The only one a program can reach is Linux's `std::sys::syscall`. +- **Volatile memory.** + - Both optimizers reuse a value read through a pointer when nothing between may + write it. + - The rebuild's loop passes move such a read out of the loop. + - So a loop polling a device register would read it once. +- **`@align`, `@packed`,** field offsets, sections, placing anything at an address. +- **An entry of one's own.** `main` is `def main(): void` or + `def main(args: span): void`. +- **Interrupt handlers,** naked functions, a function C or assembly can call outside a C + call, `noreturn` beyond `exit` and `abort`, exported symbols. + +**Allocators:** +- Every container's `new` takes a `maybe<&mut allocator>`, and `nothing {}` means the + default heap. +- These always use the default heap: `box`, `rc` and `arc`; a `function` holding more + than 24 bytes; `$"..."`; `to_vector`, `vector::from`, `dict::from` and `to_string`. +- `arena::over(buffer)` serves from memory it's given, then falls back to the heap. + +### std with no operating system + +| Needs only `core` and a heap | Needs a system | +|---|---| +| `std::math`, `std::json`, `std::yaml`, `std::serial`, `regex`, `uri`, `version` | `std::io`, `std::sys`, `std::args`, `std::time`, `std::thread`, `std::process`, `std::testing` | + +## What it needs + +1. **A target with no operating system,** beside the two, in both compilers, and a + `when` value for it. +2. **The platform as a layer the target chooses:** std's for Linux and Windows, the + program's for none. +3. **The heap's algorithm apart from where its memory comes from.** +4. **A start that needs no system:** the thread record, stacks, SSE, ``, + `main`. +5. **Faults reported with no system:** a place the platform says the report goes, and a + way for a kernel's own exception handlers to report as a fault does. +6. **An image a loader can place:** its base, the top 2 GiB for kernels, and a `.bss`. +7. **What operating-system code does:** + - privileged instructions; + - volatile memory; + - interrupt handlers; + - alignment and packing. +8. **Testing without hardware,** and on QEMU where it's installed. + +## How it fits the rules + +- **"Programs run on a virtual machine, or as standalone x86-64 executables for Linux + and Windows that behave identically."** + - A freestanding executable behaves the same wherever it shares a meaning with them: + the same faults, reports and traces. + - Where the report goes, where memory comes from, and how the program stops are the + platform's. +- **Targets:** `os` gains `none`. `--target none-x86_64` is `os == none`, + `arch == x86_64` and `backend == native`. Nothing existing changes name. +- **The VM stays hosted.** `run` refuses `none`. A freestanding program's logic runs in + the VM under the host's target, with its `when os == none` sections set aside. +- **std's system modules aren't read** on `none` unless a program refers to them, under + reading by reference. Where one is, the compilers say it's for other + targets ([std on none](#std-on-none)). +- **Both compilers agree,** with the same tests run by each. + +## The design + +### The target (decision 1) + +- **`none-x86_64`:** no operating system. The program's platform module decides whether + it runs in ring 0, as a kernel, or in ring 3, on a system of its own. +- `check --target none-x86_64` and `build --target none-x86_64`. The language server + takes it as `check` does. +- **The native backend's one switch,** `build_options.windows: bool` in the rebuild, and + C's Windows-or-else, become a choice of three systems. +- **UEFI** comes later ([Later](#later-where-wanted)): a PE for the firmware, with the + Windows calling convention the compilers already have. + +### The platform layer (decision 2) + +The 16 helpers split three ways: + +| Helpers | Where they go | Why | +|---|---|---| +| `format_begin`, `format_text`, `format_value`, `format_owned`, `equal`, and `float`'s and `values`' code | `core` | They're the language's: `$"..."` and comparing values | +| `allocate`, `allocate_untraced`, `release`, `resize` | `core`'s heap, over the platform's pages | The algorithm is the language's, the memory the platform's | +| `fail` | `core` builds the report and walks the trace; the platform writes it and stops | The `.lines` tables are the image's own | +| `arguments`, `processor`, `exit`, `abort`, `start_thread`, `thread_main`, `system_start` | `runtime`'s Linux and Windows sections only | They're the system's. On `none`: no arguments, the probe's features as they are, `exit` stops, and `abort` traps | + +**On `none`, the platform is a module `platform`,** given by the program or by a +library, which the compilers look up by name, as they look up `runtime` now: + +```sakura +module platform; + +pub def start(): void; # optional: runs first, before +pub def pages(count: u64): *mut u8; # optional: count 4 KiB pages for the heap, or null +pub def report(text: strview): void; # optional: where a fault's report goes; dropped if absent +pub def stop(status: i32): void; # required: never returns +``` + +- **On Linux and Windows,** `system` gives the same four, from the ffi plan. So the + runtime's system parts shrink to those, the lock's wait and wake, and threads. +- **A kernel may write its `platform` as `extern module platform when os == none;`,** so + the structs its loader hands over, as Limine's requests and answers, are laid out as + C's. + +### The heap (decision 3) + +- **`memory.sakura`'s algorithm moves into `core`.** Its system parts become calls to the + platform: reserving and opening chunks, mapping a large block, giving memory back. + `mremap`'s growth stays Linux's, as an extra the platform may give. +- **On Linux and Windows, nothing changes:** their `pages` are the reservation and + `mprotect` or `VirtualAlloc` of today. +- **On `none`, memory comes from where the program says:** + - `platform::pages`, from what a kernel knows is free; + - or `--heap SIZE`, a region of the image's `.bss` the heap takes first; + - or both, the region first. +- **With neither, there is no default heap.** A build that reaches it fails, naming the + way: "`main` reaches the heap through `vector::append` and `acquire`, and + `none-x86_64` gives no memory: declare `platform::pages`, build with `--heap SIZE`, or + give the vector an allocator." + - The compilers already know what's reached, since they compile only that. + - C's errors about constants already name such chains. +- **Allocators given by hand work with no heap at all,** for every container but those + above that always use it. Allocators for `box`, `rc` and `arc` come later. +- **One processor at first.** The heap's lock does nothing until a thread starts, and + `none` has no threads. Several processors come later. + +### The start (decision 4) + +On `none`, the compilers write `_start` as they do now, without the system: +1. **Ring 0** (`cs & 3 == 0`): + - turn on x87 and SSE, since every prologue and copy may use them: CR0's EM off and + MP on, CR4's OSFXSR and OSXMMEXCPT on, `fninit`; + - set the `gs` base with `wrmsr` to `IA32_GS_BASE`. + + **Ring 3:** set it with `wrgsbase`, which the system must allow, as Linux does. +2. **The stacks:** + - switch `rsp` to a stack in `.bss`, `--stack SIZE` (C also its stack of frames); + - set the limit in the record, and `rbp` to 0. +3. **Probe the CPU** into the record. No `SAKURA_CPU`, since there's no environment. +4. **Run** `platform::start()` if it's declared, then ``, then `main()`, then + `platform::stop(0)`. + +No system calls, no signal handlers, no arguments. `main` stays `def main(): void`. What a +loader hands over, as Limine's answers or a memory map, the platform module reads in its +own way. + +### Faults + +- **Reporting:** + - The trap stub's second trap calls `platform::stop(1)` rather than `exit_group`. + - `fail` builds "sakura: runtime error: ..." and the trace from `.lines` into a buffer + in `.bss`, not the heap, since the heap may be what failed. + - It hands the buffer to `platform::report`, then calls `platform::stop(1)`. +- **The processor's own faults** are the kernel's, through its interrupt table. + - A null read faults only if the kernel leaves page 0 unmapped. + - A kernel's `@interrupt` handler for a page fault, a division or a general protection + fault calls `core::fault_at(kind, rip, rbp)`. That reports it as the language + reports a fault, with the trace. +- **The stack:** the prologue's compare works as it does on Linux. + +### The image (decision 5) + +- **ELF `ET_EXEC`, as now,** with: + - `--base ADDR`; + - a `.bss`, so zeroed globals, `--heap` and `--stack` cost nothing in the file; + - `_start` as the entry. +- **The top 2 GiB,** where kernels usually live and where Limine's protocol wants them. + - `[disp32]` already sign-extends and reaches it. + - The rebuild's `mov r32, imm32` of an address becomes `mov r64, simm32`, and its + switch tables of `u32` become `i32`. + - So do the handlers' `mov ecx, imm32` of the text's end. + - C writes addresses as 32-bit numbers in the same kinds of places, which need the + same review. +- **Not now:** code that can be placed anywhere (RIP-relative), relocatable PEs, flat + binaries. Multiboot2 enters in 32-bit mode, which neither backend can write. + +### Reaching the hardware (decision 6) + +**`core::x86_64`,** a child of `core`, imported where it's used: + +| Intrinsics | Instruction | +|---|---| +| `port_in8`, `port_in16`, `port_in32`, `port_out8`, `port_out16`, `port_out32` | `in`, `out` | +| `read_cr0`, `read_cr2`, `read_cr3`, `read_cr4`, `write_cr0`, `write_cr3`, `write_cr4` | `mov` to and from control registers | +| `read_msr`, `write_msr` | `rdmsr`, `wrmsr` | +| `load_gdt`, `load_idt`, `load_task` | `lgdt`, `lidt`, `ltr` | +| `interrupts_off`, `interrupts_on`, `halt`, `pause` | `cli`, `sti`, `hlt`, `pause` | +| `invalidate_page` | `invlpg` | +| `cpuid`, `read_tsc` | `cpuid`, `rdtsc` | +| `read_gs_base`, `write_gs_base` | `rdgsbase`, `wrgsbase` | +| `system_call` | `syscall`, for a platform in ring 3 | + +**`volatile_load(p: *T): T` and `volatile_store(p: *mut T, value: T)`,** in +`core` for every target. +- Both optimizers treat each as they treat an atomic: touching all memory, so it's + neither removed, merged nor moved. +- An atomic already works this way, in both. + +The table holds 28 intrinsics. The encoders gain about 20 instructions each, with `fninit`, `fxsave`, +`fxrstor` and `iretq` for the start and interrupts. On the VM, a privileged intrinsic stops +the program, as it can't be run there. `check` is unaffected. + +### Interrupt handlers (decision 7) + +```sakura +struct interrupt_frame { pub val rip: u64; pub val cs: u64; pub val flags: u64; pub val rsp: u64; pub val ss: u64; } + +@interrupt def page_fault(frame: &interrupt_frame, code: u64): void { ... } +@interrupt def timer(frame: &interrupt_frame): void { ... } +``` + +- **The compilers write the entry:** + - save every general register and the SSE state (`fxsave`); + - set up what generated code needs, then call the body; + - restore everything, and `iretq`. + + A handler taking `code` is one the processor pushes an error code for. +- **Its address,** for the interrupt table, comes from naming it: an `@interrupt` + function's value is a `u64`. +- **Frames differ between the compilers.** + - The rebuild keeps them on `rsp`, so a handler's frames go below the interrupted + code's. + - C keeps them on a stack of its own through `rbx`. An interrupt can't know where the + interrupted function's frame ends, so C's handlers get a stack of frames of their + own. + +### Layout (decision 8) + +- **`@align(N)`** on a struct or a global, as a page table's 4096. +- **`@packed`** on a struct: no padding. Its fields may be unaligned, which x86-64 reads + and writes. +- **The README says how structs are laid out,** as the compilers already do it. + +### std on `none` + +- **What it can use:** `core`, and std's modules that need only a heap. +- **A module whose sections are all for other targets** is reported as such: "`std::io` + is written for `os == linux` and `os == windows`, and this target is `none`." + - Today that case gives "No file declares this module", or a missing `sys::` name + deep inside. + - This helps every target, not only `none`. + +## Using it + +```sakura +# platform.sakura: what this kernel gives the language +module platform; +import core::x86_64; + +pub def report(text: strview): void { + for c in text { x86_64::port_out8(0x3F8, c); } # the first serial port +} + +pub def stop(status: i32): void { + x86_64::interrupts_off(); + while true { x86_64::halt(); } +} +``` + +```sakura +# kernel.sakura +def main(): void { + var frames := vector::::new(); # from --heap + frames.append(0x100000); + platform::report($"{frames.length} frame\n"); +} +``` + +```sh +sakura check --target none-x86_64 kernel.sakura platform.sakura +sakura build --target none-x86_64 --base 0xffffffff80000000 --heap 16M --stack 64K \ + -g -o kernel.elf kernel.sakura platform.sakura +qemu-system-x86_64 -cdrom os.iso -serial stdio -s # gdb loads kernel.elf.petal for source lines +``` + +## How each part works + +**The rebuild:** +- **Targets:** + - `entry.sakura`'s `platform` gains `none-x86_64`; + - `target_checker` (`program.sakura` in `sakura-server`) sets `os = "none"`; + - `checker::target_value` (`checker/declare.sakura` in `sakura-analyzer`) gains `none`; + - `build_options.windows` becomes a system of three, at its 18 places. +- **The start** (`native.sakura` in `sakura-native`): a third entry beside Linux's and + Windows'. Ring 0 or 3 by `cs`, the stacks from `.bss`, then the `platform` functions + found as `runtime`'s are (`building::prepare`). +- **Faults:** + - the trap stub's second trap calls `stop`; + - on `none` there's no `SIGSEGV` or vectored handler; + - `core::fault_at` enters the trap stub as the Linux handler does now. +- **The image** (`binary::elf`, in `binary`): a `.bss` segment of `PT_LOAD` with a + file size short of its memory size, `--base`, and, for the top 2 GiB, the sign-extended + forms in `binary::amd64`, `calls.sakura` in `sakura-native` and the handlers. +- **Intrinsics:** + - `emitter/intrinsics.sakura` in `sakura-compiler` lowers each to an IR operation; + - `binary::amd64` encodes it; + - the optimizer's table (`intermediate/code.sakura` in `sakura-compiler`) marks the + volatile and privileged ones as touching all memory. +- **`@interrupt`, `@align` and `@packed`:** + - the checker reads them (`checker/attributes.sakura` in `sakura-analyzer`); + - `layouts.sakura` in `sakura-compiler` lays out `@align` and `@packed`; + - `calls.sakura` in `sakura-native` writes the interrupt entry. + +**C:** +- **Targets:** `context.c`'s `target_parse` and `context_build`, `table.c`'s names, + `checker__meets`, and `native.c`'s Windows-or-else. +- **The start and faults:** a third entry in `native.c`. +- **Code generation:** `elf.c` for `.bss` and the base, `x64.c` for the instructions, + `compiler.c`'s `emitter__intrinsic` and `checker.c`'s table of intrinsics, and + `compiler.c`'s layouts. + +**`runtime` and `core`:** +- `runtime/`'s formatting, values, floats and the heap's algorithm move into `core`; +- the four platform functions go into its Linux and Windows sections; +- `core::x86_64` and the volatile intrinsics are added. + +## Testing + +- **As a Linux process,** without QEMU, in both compilers. + - An image for `none-x86_64` runs on this machine. Linux loads its `ET_EXEC` and + starts it in ring 3, where the start takes `wrgsbase`. + - A test platform module stops and reports through `x86_64::system_call`, as Linux's + `exit_group` and `write`. + - That tests the start, the heap over `pages` and over `--heap`, faults and their + traces, ``, the stack's limit, volatile memory, and the corpus's programs + that need only `core`. +- **Each build that reaches the heap with none given** fails, naming the way. +- **On QEMU,** where it's installed: a small kernel in `test/kernel/`, booted by Limine. + - It writes to the serial port, which `-serial stdio` gives the test. + - It ends through QEMU's `isa-debug-exit` device, `port_out32(0xF4, code)`, which + gives QEMU's exit status. + - It takes a breakpoint and a page fault through `@interrupt` handlers, and reports + the page fault as a fault, with its trace. + - It reads a timer through volatile memory, and builds at its top-2-GiB base. +- **Layout:** `@packed` and `@align` structs' sizes and offsets, checked by reflection, + in both compilers. +- **Linux and Windows unchanged:** + - the corpus in each VM and natively at each level; + - both std suites, the rebuild's unit tests, C's `sakura_tests`; + - the rebuild building itself to its fixed point. + +## Phases + +1. **The runtime split,** in both compilers and both trees, after the std plan's `core`: + - formatting, values and floats into `core`; + - the heap's algorithm into `core` over `pages`; + - `fail` split into building and writing. + + Linux and Windows behave as before. About 900 lines of `runtime` moved, and 150 in each + compiler. +2. **`none-x86_64`:** the target and `when os == none`, the start, `platform`, faults, + `.bss`, `--base` (low 2 GiB), `--heap` and `--stack`, and the note for a module of + other targets. Tested as a Linux process. About 600 lines in each compiler. +3. **The hardware:** `core::x86_64` and the volatile intrinsics. About 400 lines in each + compiler. +4. **Layout:** `@align` and `@packed`, and the README's layout. About 250 lines in each. +5. **Interrupts:** `@interrupt`. About 300 lines in each. +6. **The top 2 GiB.** About 300 lines in each. +7. **A kernel booting on QEMU,** in `test/kernel/`. This needs QEMU, and Limine's files, + on the machine running it. +8. **Both READMEs:** "Executables and tools", "Pointers and memory", and a section on + programs with no operating system. + +## Found along the way + +- **A loop polling memory reads it once,** in both optimizers, since nothing in the loop + writes it. Harmless now, wrong for a device register. +- **`.data` is written whole,** so a zeroed global costs its size in the file. +- **The two compilers lay frames out differently:** the rebuild on `rsp`, C on a stack of + its own through `rbx`. Each needs its own interrupt entry. +- **`build_options.stack` exists in both,** and nothing sets it. +- **`arena::over(buffer)` falls back to the heap** when its buffer is full, which on a + target with no heap must fail instead. + +## Later, where wanted + +- **UEFI:** `uefi-x86_64`, a PE for the firmware (subsystem 10) with its entry under the + Windows calling convention. + - Its platform: pages from `AllocatePages`, reports to `ConOut`, `stop` through + `Exit`. + - A PE with its relocations stripped loads only where its base is free, so it may + need a `.reloc`. +- **Several processors:** a record per processor at `gs`, the heap's lock as a spin, and + starting the others. +- **Programs for one's own system,** in ring 3, with `swapgs` and system calls of its + own. +- **Code that can be placed anywhere,** RIP-relative, for PIE and relocatable PEs. +- **Allocators for `box`, `rc` and `arc`,** and for `$"..."`, so a program with no heap + can use them. +- **`aarch64`,** where the platform layer would carry over unchanged. +- **Object files and exported symbols,** to link with assembly or C. +- **Thread-local variables,** which [later.md](later.md) lists already. + +## Decisions for you + +1. **Which targets first:** + - **(a) `none-x86_64` alone,** with UEFI later. + - **(b) `none-x86_64` and `uefi-x86_64` together.** + + Recommended: **(a)**. It holds everything a kernel needs, and UEFI then reuses its + platform layer. +2. **Where a freestanding program's platform lives:** + - **(a) A module `platform`, given by the program or a library,** whose functions the + compilers find by name, as they find `runtime`'s. A platform can be shared as + a package. + - **(b) Attributes on the program's functions,** as `@platform(stop)`. + - **(c) A whole runtime of the program's own** in place of `runtime`, writing all + 16 helpers. + + Recommended: **(a)**. Four functions, one required, and the language's helpers stay + the language's. +3. **The heap on `none`:** + - **(a) Only where it's given,** by `platform::pages` or `--heap SIZE`. A build that + reaches it otherwise fails, naming the way. + - **(b) Always a region of a fixed size,** unless `--heap` says otherwise. + - **(c) None at all.** Every container takes an allocator, and `box`, `rc`, `arc` and + `$"..."` are refused. + + Recommended: **(a)**. A kernel chooses where its memory comes from, and a mistake is + caught at build time, not at boot. +4. **The start:** + - **(a) Written by the compilers,** as now, with no system calls. + - **(b) Written by the program,** with naked functions and the intrinsics. + + Recommended: **(a)**. The thread record, the stacks and SSE must be set before any + Sakura code runs, and only the compilers know their layouts. +5. **Where an image may be placed:** + - **(a) The low 2 GiB,** at `--base`. + - **(b) Also the top 2 GiB,** for kernels. + - **(c) Anywhere,** with RIP-relative code. + + Recommended: **(b)**. Kernels live there, and it changes only how addresses are + written as numbers. (c) changes every address the backends write. +6. **Reaching the hardware:** + - **(a) Intrinsics in `core::x86_64`,** and `volatile_load` and `volatile_store`. + - **(b) Inline assembly.** + + Recommended: **(a)**. 28 intrinsics cover a kernel. The optimizers know what + each does. And neither compiler has an assembler to read text with. +7. **Interrupt handlers:** + - **(a) `@interrupt` functions,** whose entry and exit the compilers write. + - **(b) Naked functions** the program writes, with the intrinsics. + + Recommended: **(a)**, for the same reason as decision 4. +8. **Layout:** + - **(a) `@align(N)` and `@packed`.** + - **(b) `@align(N)` only,** with packed data written as bytes. + + Recommended: **(a)**. Descriptor tables' pointers and many on-disk formats are + packed. +9. **The first boot to test on:** + - **(a) Limine,** whose protocol starts a 64-bit ELF in long mode, in the top 2 GiB. + - **(b) UEFI,** which needs decision 1's (b). + + Recommended: **(a)**, with decision 5's (b). diff --git a/docs/inconsistencies.md b/docs/inconsistencies.md new file mode 100644 index 00000000..268cdcfb --- /dev/null +++ b/docs/inconsistencies.md @@ -0,0 +1,71 @@ +# Where the compilers disagreed + +The places where the C compiler and the rebuild didn't agree, as the plans and their builds +noted them. The C compiler is frozen, so the rebuild's behavior is the language +([roadmap.md](roadmap.md), decision 1), and the rules step 5 settled on 2026-10-20 are +built. Probed again on 2026-10-28 with the rebuild alone: what was decided, or works in the +rebuild, went, and what's left is where the rebuild still falls short of what C did or of +what the README says. Probes leave out their imports. This file goes at the freeze. + +## What runs while compiling + +### What follows an `if const` only evaluating decides + +```sakura +def size_or_refuse(): u64 { + if const size_of::() == size_of::() { return size_of::(); } + compile_error("not the same size"); + return 0; +} +``` + +`size_or_refuse::()` is refused: "not the same size (In `size_or_refuse`)". Where the checker decides an `if const` whose branch leaves, as `T is integer`, +what follows it is compiled only where the branch isn't taken. Where only evaluating +decides, as here, what follows is compiled either way, so its `compile_error` is reported +whichever way the condition goes, as C reported every one. Within the branch, as +`simd::bits` writes it, or in an `else`, it's reported only where evaluating chooses that +branch: so since 2026-10-28, with the text it's given, in a property's accessors too. + +### A local constant reading another + +```sakura +def main(): void { const a: i64[3] = [1, 2, 3]; const b := a[1]; println($"{b}"); } +``` + +"A constant's value is known while compiling", where the constant read isn't a number. The +same for a struct's field and a span given to a function. A global constant read this way, +and local constants that are numbers, work. + +### `remove_at`, `extend` and `string::append` in a constant + +std's containers work in a constant, but `memcpy` (`core/mem.sakura`) turns two addresses +into numbers to compare them where it moves 8 bytes or more, so evaluating stops there: +"Function does not run while compiling. at memcpy". Comparing the pointers themselves +(`p < q`, `q - p`) runs in a constant, so `memcpy` could do without the numbers. + +### An address made a number while evaluating + +Where it happens, evaluating says only "Evaluating `h` stopped: Function does not run while +compiling.", with a trace. C said what happened: "An address is only known where the +program runs, so pointers and integers do not convert while compiling." + +### A constant holding what is written through + +```sakura +const b: box = box::new(3); +const s: string = string::from("abc", nothing {}); +``` + +The rebuild takes both, and a `vector` made by a function, on the machine, under +`--checks` and in executables. The README's "a `string` doesn't" sides with C, which +refused them: "A constant stands in memory the program only reads, so it holds `*T` and +`&T` but not what is written through". Which is the language isn't decided. + +### `decl_of` of a built-in type + +`decl_of::()` gives a declaration named `i64`, whose kind is `target::all`, 65,535, so +`decl_of::().kind == target::structs` is false of it but +`(kind & target::structs) == target::structs` is true. The README says `decl_of` takes no +number, and C refused it: "`int` is built into the language, so there is no declaration of +it to describe." diff --git a/docs/later.md b/docs/later.md new file mode 100644 index 00000000..6c53d4b1 --- /dev/null +++ b/docs/later.md @@ -0,0 +1,582 @@ + + + +# Later + +What the built plans left for later, and the problems they found and didn't fix. Each item +was checked against the rebuild and std on 2026-10-28, and is still open unless it says +what's left of it. What was built since went, as did the records of what was built, which +the CHANGELOGs keep. + +Where the C compiler and the rebuild disagreed and the rebuild still falls short, the item +is in [inconsistencies.md](inconsistencies.md) instead. The plans not yet built keep their +own "Later" lists: [algorithms.md](algorithms.md), [benchmarks.md](benchmarks.md), +[freestanding.md](freestanding.md), [linear.md](linear.md), [logging.md](logging.md), +[random.md](random.md) and [tui.md](tui.md). + +[roadmap.md](roadmap.md) gives the order the plans are built in up to the language's +freeze. It also says which items here must come before the freeze and which can wait. + +## The language + +### Lambdas that own what they use + +A lambda only refers to the locals it uses. Whatever must outlive its frame is a functor +written by hand, or a `function` holding one. Capture lists, or a `func` that owns what it +captures, would let a lambda be returned or given to a thread. You set both aside when +the memory plan was built ("for now"). A `function` holding such a lambda would own what +it captured with nothing in `function` changed. It's the roadmap's last step, with +directions that avoid a list in brackets ([roadmap.md](roadmap.md#7-lambdas-that-own-what-they-use-decisions-2-and-3)). + +### References and values: what the rule left + +What the rule "where a value goes says what happens to it", built on 2026-10-22, left: + +- **Only named functions are adapted.** A lambda whose parameter types are written, + as `def(s: &string)` given where `def(&mut string)` is asked, and a function value + held in a variable, must still match. A lambda with its types left out takes them + from where it goes. +- **A copy of `T` in generic code is refused only per instance.** `val x := v[i]` in a + generic over `T` copies, and an instance whose `T` closes reports it, as C++ would. + A bound saying "closes nothing" would let the template report it once. +- **`&&T` still exists inside instances.** Where a type parameter is a reference, + `&x` of a `T` refers to the variable holding it, as the template means. Only + generic code sees such a type; a function given where one is asked is adapted. +- **A reference variable is pointed elsewhere by a reference written as one**, `r = + &y`, as C++'s pointers are and its references aren't. Refusing it would match + C++'s references, but chains walked by reassigning a reference need it. +- **An overloaded member named with its type's arguments**, as `box::::get`, + is the first overload, not the one the type expected chooses. Named without them, + `box::get` chooses. +- **`for x` copies each element**, which for a large struct costs a copy that + `for &x` avoids. How often the optimizer removes it hasn't been measured; for a + 256-byte struct at `-O2`, it did. + +### Joining text with `+` + +`string + strview`, with `+=` as an `add_assign` that appends in place, which a compound +assignment calls since the rules were settled (roadmap step 5). The rebuild refuses `+` +today: "`string` has no `add` taking a `&strview`, which `+` calls." + +### More operator traits + +- Traits for mixed operands, as `scales` for a vector times a number, once programs + show which ones they need. +- A partial order for floats, so generic code can say what NaN does. +- There is no `bitwise` trait, by decision: a program's own trait gives `&`, `|` and the + shifts to generic code. + +### `strview` has no order + +`strview::compare` takes the other view by value, so `strview` isn't `ordered`, and +`v < w` of two views is refused: "`strview` has no order". So the note refusing `s < v` of +a `string` and a view, which asks for `s.view()`, leads to a second refusal. + +### A trait's defaults reach only the types naming it + +A method a trait writes a body for is its default, which a type may leave out. The rebuild +counts a type as meeting the trait by its methods, whether or not it names the trait, but +only one naming it gets the defaults. So a struct with only `put` passes `where S: sink` +for a `sink` asking for `put` and giving `done`, and `S is sink` is true of it, and the +instance then fails where the generic calls `done`: "`plain` has no field, property, or +method `done`. (In `finish`)". Either the defaults should reach every type meeting +the trait, or a type leaving a default out should meet the trait only by naming it. The +first would let `writable` give a `flush` that does nothing, so `flushable` could go with +`if const S is flushable` in `std::io::writer`. + +### Named constants without a type + +`const pi := 3.14` is an `f64`, and `const k := 7` an `i64`, so `val x: f32 = pi` is +refused, where the literal would fit. `std::math`'s constants are `f64` for that reason, +and f32 code writes `math::pi as f32`. + +### `type_of(f)::name()` + +It doesn't parse: "Expected `)` to close the arguments. Found `::`." `std::args` works +around it with generic helpers, as `switched::()`, `is_command` and +`shape_of`. + +### A module named as a type it declares hides the type + +A path's first name is a module's before a type's, so `std::uri`'s `uri::parse` would look +in the module. So `std::regex`, `std::uri` and `std::version` are `std::text`, `std::net` +and `std::semver`. A rule reaching the type is a language addition that could come after +the freeze. + +### Documentation as a reflection intrinsic + +An intrinsic giving a declaration's `#!` comment would let `std::args` print a field's +documentation as its help, rather than `help = "..."` repeating it. Only the language +server reads those comments now. + +### Thread-local variables + +`@thread_local var`, reached through the thread's record at `gs:[offset]`. + +### 128-bit integers + +Their multiplication would serve `fma` and hashing. + +### Tracking moved locals + +A local moved on every path needn't be closed at all, and reading one after a move could +be an error. The checker doesn't track moves: a moved-from value is left zeroed and +closed as usual. + +### `equatable` and `hashable` for `void` + +They'd take methods the compiler gives, and nothing needs them yet. So `dict` +fails at `hash` and `equals`. + +### Contracts + +What the contracts plan left for later: +- **Contracts on a trait's methods,** checked for every type implementing it. +- **`old` of what closes,** copied and closed after the check. +- **A type's invariant,** checked after each of its `pub` methods. +- **The checker proving contracts:** warning where one always fails, and leaving out one + it proved, from what it already knows of bounds. +- **Levels,** as `--contracts expects`, keeping pre-conditions only. + +### Calling C + +What the ffi plan left for later: +- **C's variables,** as `errno` or `environ`: a `var` in an extern section is a Sakura + global of its own. +- **Variadic C functions,** as `printf`. A parameter written `i64...` passes a span. +- **A C name that isn't a Sakura name,** as a keyword: a name given to the symbol apart + from the declaration's. +- **The machine calling C on Linux,** with System V's convention, so a program calling C + runs without being built. It stops where it reaches one, or a C function's address: "Program + uses a construct that cannot be compiled." +- **`system::macos` and `system::freebsd`.** macOS needs `libSystem` and a Mach-O writer. + +## Warnings the checker misses + +### A lambda returned through a call + +A lambda returned directly, or in a struct literal, is warned of: "The value returned +refers to `s`, which ends as the function returns". Returned through a call, as +`return function::new(def() => ...)` or `return pass(def() => ...)`, it isn't. Calling it +later reads a frame that's gone. `run --checks` misses it too, most of the time: the +closure's frame is pushed where the ended frame was, so the address it reads lies within +frames in use. + +### A thread handle outliving its closure's locals + +A function that starts a thread whose closure updates one of its locals, and returns the +handle, gets no warning, where returning the closure itself would. `run` reads a stale +frame, and `run --checks` prints garbage. + +### `compile_error` at the call that made the instance + +A `compile_error` is reported where it's written. In a generic, that's inside std, as +`std/serial/walk.sakura:45` for `json::to_text` of a type that isn't `@serial`, not the +user's call. `compile_error` takes a place (`at: site = call_site()`), so a library can +point at a declaration, but std's walk passes none, and the compiler doesn't note the call +that made the instance. + +## The compiler + +### Small unions as values + +A union of two or three words, as `maybe`, would be held as words and returned in +`rax`, `rdx` and `rcx`, so a range's `next` gives its `maybe` in registers. It's returned +in memory now. The iterators plan's numbers held without it. + +### Lambdas given to adapters + +`v.iter().filter(lambda).map(lambda).sum()` costs 3 to 4 times what functors do: 565 to +599 ms against 144 to 190 ms over ten million elements at `-O2` (`tools/iterators.sakura`). +The adapter is built by 16-byte copies, and its lambdas are called through `call_value`, +so they aren't inlined, even one whose function is known as a constant. Reading words +through wide copies, or a type of each lambda, would fix it. + +### `box` within 10% of `raw_allocate` + +The memory plan asked for it. `tools/memory.sakura` gives `box` 1.31 to 1.38 times +`raw_allocate`. What's left: +- walking a list through a `maybe<&T>` picks the next node with a `select` that the + loop's exit also reads; +- every `move` of a value that closes writes the zeroes its source is left with. + +### Atomics + +- **`lock add`, `lock or` and the like where the result isn't used,** as + `_ = hits.fetch_add(1)`, which is `lock xadd`. `fetch_and`, `fetch_or` and `fetch_xor` + would lose their `lock cmpxchg` loops. +- **Two-word atomics through `cmpxchg16b`,** for a pointer with a count beside it. The + oldest x86-64 processors lack it. + +### What the vector work left + +- **`%` of lanes is a loop over them,** as no instruction divides integers. +- **The least and greatest of real lanes, and the product of integer ones,** are loops. + `smallest` and `largest` work real lanes from lane 0, as which NaN or zero they give + depends on the order, which the instructions' pairs of lanes don't keep. +- **`scatter` writes a lane at a time.** Only AVX-512 has an instruction for it. +- **64 bytes, AVX-512's,** were checked only by disassembling what's built, as this + machine has no AVX-512. On one that has it, native's test + `vectors_of_64_bytes_give_the_same_bits_at_every_level` works each operation with the + instructions, and `tests/programs/simd_lanes_agree_everywhere_2`, built and run, does + too; the corpus itself runs on the machine. Such a vector is held in its + slot, never a register, and read a quarter at a time; a mask of one is a vector, and + `k1` holds it only within an operation. 64 bytes of 8-bit lanes aren't allowed, as their + mask's bits wouldn't fit a `u32`. The least and greatest of real lanes go a half or a + quarter at a time, and the sums across the lanes, `shuffle`, and changing the lanes' + type or size a lane at a time. +- **A struct of a size not a multiple of 16,** as three `f32` fields, is built a field at a + time: merging stores fills 16 bytes from a multiple of 16 only. +- **32-byte vectors go through memory a half at a time** in a function working several, + as `geometry`'s frustum test of eight planes as one `f32x8` did: each `select`'s and + splat's result was stored whole and read back as two halves, and each splat was two + shuffles where `vbroadcastss` is one. It ran no faster than a plane at a time, and in + one build twice as slow, where two `f32x4`s run twice as fast, so `geometry` uses those. +- **A vector's lanes read as numbers,** as `vec3::dot` adds its products' lanes, made + `geometry`'s rays two to three times as slow as the same dot worked a number at a time, + though `linear`'s bench of `dot` alone finds the two even. `geometry` works its dots a + number at a time. + +### What the analyzer's tables left + +What making the analyzer's tables smaller and its passes quicker left, as checking the +compiler's own sources measured it: +- **Vectors made for each call checked.** `arg_kinds`, `try_candidate`, the five vectors + `begin_inference` makes, and `check_args_bounds`'s copy of the parameters are made for + each call, about 1% of checking. They nest, as checking an argument checks its calls, + so a scratch column would need marks, as `type_table::substitute`'s has. +- **Rows for nodes that have no results.** A result table has a row for each node, but + half are never written: statements, type names, and declarations. Numbering only the + nodes checking gives a type would halve `r_types`, `r_refs`, and `r_flags`. +- **Evaluating what checking left.** Lowering it, making an interpreter, and running it + took 5.5% of checking the compiler, and wasn't looked into. +- **Words written a field at a time.** `zeroed_cells` counts a word as written only where + one store covers it whole, so a cell built field by field, of fields narrower than a + word, is zeroed though every byte of it is written. Following 4-byte halves would catch + most structs. + +### What `@inline` left + +- `@inline` on `checker::unalias`, a test of a type's flags and a call where it fails, + made the compiler 312 KB larger across its 342 calls, about 900 bytes each, and ran no + fewer cycles, so it isn't marked. What a copy takes at each call is worth seeing. + +- std's own helpers called in its loops over text aren't marked, std being a repository + of its own: `json`'s `plain_stops` and `is_json_space`, and `yaml`'s `comment_ends`. +- At `-O0` a copy still writes each argument into its cell and reads it back, and each + span a copy returns waits on the stores that built it, so a chain of copies waits on + memory as a chain of calls does. Marked, `span::sub` and `span::over`, `find_byte`, + `find_last_byte` and `count_byte`, and `bytes8::upper` and `lower` were slower at `-O0` + (`find_byte` at `-O2` too), so they aren't. `swar::load_last` and `u8::digit_value` + gained only at `-O2`, by 4%, so they aren't either. + +### aarch64 + +There's no aarch64 back end. Atomics would be `ldar`, `stlr` and `ldaxr`/`stlxr` loops or +LSE there, which is why an atomic's order is a value as the program runs, and `simd` +would be NEON. + +### The command's name + +`sakurac check --help` says `usage: sakura check`, and a wrong option says "Try +`sakura build --help`", the name the compiler had. + +### What `--checks` misses + +A reference read only by interpolation isn't checked: `val r := &v[k];`, then `v` grows, +then `println($"{r}")` prints a stale value, where `val y: u64 = r` is stopped. Nor is a +view's element read after the memory it covers is released, as a span after `raw_release` +or a vector's view after `close`, at every level; reading through the pointer itself is +stopped. The README's account of `--checks` claims more than this. + +It stops at a read of memory nothing wrote, but not of an `undefined` number the +optimizer holds in a register rather than in memory, and not where formatting reads a +struct's bytes, or `==` compares arrays' bytes. + +### Checked executables + +`build --checks` makes the checks of a checked program, as indexes, and none of +`run --checks`' of memory. A runtime with a shadow map, as AddressSanitizer has, would +check an executable's references and pointers, and the bytes nothing wrote. + +### Guard pages for the stack + +A page nothing may touch below each stack would report an overflow from the fault, and +the prologue's compare with the stack's end could go. The rebuild already leaves that +compare out of small leaf functions. + +### Overflow checks + +Checked builds could stop where integer arithmetic overflows, for programs that ask for +it. Today it wraps in every build, and `math::checked_add` and its kin are the way to +know. + +### Fresh pages taken as zero + +The compiler's result tables read zero as "nothing yet", so they grow by zeroed +elements, a file at a time, and every byte is cleared. A vector grown into pages fresh +from the system could take them as zero without clearing them, if `raw_resize` said +which bytes it gave fresh. Only a vector's first allocation does that today. + +### Reading libraries + +What the std plan left for later: +- **Files of other systems left unread.** A section's `when` is decided once its file is + parsed, so `system/on_windows.sakura`'s 2,449 lines are parsed on Linux. The reader + could decide a file's first `when` from its text, as it reads its first `module` line. +- **The checked `core` kept between runs.** It's the same for every program, so the time + checking it takes could be read from a file the compiler wrote, rather than checked + again. +- **Checking only what's reached.** Declarations nothing refers to would still be parsed, + but not checked. All of std parsed with nothing declared took 37 ms, against 93 ms + checked, so that's the most it could save over reading by reference. It matters for + large libraries, and for `core`'s 2,590 lines of containers. +- **`core` written into the compiler whole.** It needs the compiler to take a file in + while compiling, as an `embed` intrinsic, which it can't now. +- **An index of a library's modules,** written by blossom where it fetches a package, if + a library's folders ever grow too many to list. + +### Large blocks kept at one size + +The runtime keeps up to 64 large blocks given back, 32 MB in all, but hands one out again +only for as many bytes as it was, so the token and node vectors the lexer and parser trim +to fit leave their old blocks resident, and so do the vectors that grew past them. Checking +the compiler peaks at 48 MB resident where the analyzer's tables hold 28 MB. + +### A race checker in the machine + +As ThreadSanitizer does. `run --checks` checks that memory is held, not who writes it +when. + +### The machine interrupting waits + +`system` has no signal to spare on the machine. While threads run, a futex wait without a +time lasts 0.1 s and std's waits wait again, a read blocked forever isn't interrupted, and +the first thread waits up to 3 s for the others as `main` ends. With a thread blocked +reading, `run` takes about 3.7 s, where the executable ends at once. + +## std + +### `function` + +`core`'s `function`: +- **Converting where a `function` is expected,** so `val f: function = functor;` + needs no `function::new`. The compiler would have to know the type by name, and the + conversion allocates where the callable doesn't fit. +- **`function::bound(&mut x, T::m)`,** binding a method to a value. +- **More held in place,** through a constant parameter for the buffer's size, for code + that must never allocate. Callables of 24 bytes or fewer are held in place now. +- **An allocator for the box,** once `box` takes one as the containers do. +- **Constants.** A constant keeps the buffer's words but not the function a function + value among them names, so `function::new` reaches its buffer through its address as a + number, which refuses every constant `function`. A functor that holds no function + value could be allowed. +- **C functions,** which `function` holds, but no test covers: the machine can't take a C + function's address. + +### Threads + +- **A pool of threads taking tasks, and a parallel `for`.** The compiler's own crew + (`compiler/workers.sakura`) could seed one. +- **Read-write locks, semaphores and barriers.** `std::thread` has a mutex, a condition, + a channel and `once`. +- **Waiting on several channels at once.** +- **Calling C from any thread, on Linux.** Threads started by `clone` keep the first + thread's `fs`, so libc's state for each thread, as malloc's caches and `errno`, is + shared. Five threads calling `malloc` and `free` 200,000 times each abort in glibc + every time, and nothing warns. Windows starts threads through `CreateThread` and is + fine. +- **Reentrant console locks.** A thread holding `io::output_locked()` that calls + `println` waits forever, even with no other thread. +- **A thread given a value and giving one.** `spawn_with` gives a `handle`, so such + a thread needs a closure, and a loop variable must be moved in by hand. Merging + `spawn` and `spawn_with` into overloads waits on the checker inferring a closure's type + through overloads, which it doesn't: "No overload of `go` takes these arguments." + +### Atomics and signals + +- **The signals' waiting word as an `atomic`.** Handlers would set it, `dispatch` + would empty it with `exchange`, and the `take_signals` intrinsic would go. +- **Holding signals off for a stretch of code,** as a guard over `rt_sigprocmask`. +- **Timers:** `alarm`, and timers that repeat. `signal::alarm` exists, but nothing sets + one. +- **What a signal says of itself,** as who sent it or which child stopped. A handler is + given only the `signal`. +- **Real-time signals,** and rarer ones as SIGTTIN, SIGTTOU and SIGPROF. +- **Signals as a stream,** through `signalfd` or a pipe, so `poll` wakes for them. + `system::watch` and `system::watched` note a signal, but aren't a handle. +- **Chaining handlers:** `handle` giving back the handler it replaced. + +### Processes + +- **Waiting for whichever of several children stops first,** and capturing several at + once, for a build tool's jobs. Only `system::wait(-1, ...)` waits for any child. +- **`child::send(signal)`,** to ask a child to stop, and timeouts on `wait`. `child` has + only `kill`. `system::poll` takes a timeout, but `std::process` doesn't use it. +- **The error merged into the output in order,** as `2>&1`, and `io::file::duplicate`. +- **Overlapped reads on Windows,** in place of looking at each pipe with + `PeekNamedPipe` and sleeping up to 10 ms between looks. +- **Starting faster with `clone(CLONE_VM | CLONE_VFORK)`,** for a large program starting + many children. +- **Process groups and sessions,** and a child that outlives the program. + +### Streams + +- **Interpolation written straight into a stream,** without a `string` made for each + `$"..."`. A language change. +- **Adapters:** a tee, a writer that counts, a reader limited to a length, and + compression. +- **Reads that don't wait, timeouts, and polling several readers.** `system::poll` does + it for handles, but nothing in `std::io` does. + +### Text + +- **Vectors in more text functions.** `find_byte`, and so `index_of`, `contains`, `split` + and `read_line`, use vectors where they're held, as do `memset`, `memcpy`, `memcmp` + and the JSON reader. `strview::find`, `find_any`, `is_ascii`, `upper` and `lower`, + spans' `last_index_of` and `count_of`, and `std::serial`'s `is_utf8` read words only. +- **UTF-8 checked a word at a time past ASCII,** as simdutf does. `is_utf8` skips ASCII + by words, then checks each sequence a byte at a time. +- **Hexadecimal and base64,** encoded and decoded by words. std has neither. +- **Comparing text without regard to ASCII case,** through `lower` of each word. +- **`core::swar` lanes of 16 and 32 bits,** for UTF-16 and wider tables. It has bytes + only. +- **Left a byte at a time, on measurement:** trimming (0.76 to 0.93 times as fast by + words), and YAML's plain scalars (0.82 to 0.97). + +### Reading the clock + +On Linux, `std::time` reads the steady clock with a system call, about 211 ns in an +executable, where glibc reads it through the vDSO in 25 ns. Programs that time small work, +and the benchmarks plan, pay it on every read. + +### Parsing numbers + +`integer::parse::` checks only the 64-bit limits, so a narrower `T` wraps: +`integer::parse::("300")` is 44, and `parse::("-200")` is 56. Positive values +stop at `i64`'s largest, so `std::args` reads a `u64` with a reader of its own +(`whole_of`, `signed_within` and `unsigned_within`). + +### JSON, YAML and `std::serial` + +- **Fixed arrays,** `T[n]`, aren't written or read by the walk, which refuses a type + holding one. A type holding one gives a form of its own. +- **The walk over trait references.** It's `encode(value, out: &mut encoder)`, one + indirect call for each value, because a trait couldn't be a type argument then. That + works now (`feed(out: E) where E: sink` given a `&mut sink`), so the walk could be + generic over its encoder. +- **Faster float printing,** as Ryu. About 45% of writing JSON, 0.46 s for a 4.3 MB + document, was the runtime's `put_float`, exact but working in big integers of 128 + limbs. Every program printing floats pays it. +- **JSON Pointer,** as `doc.find("/params/position/line")`. +- **Trees that can be changed,** for JSON and YAML. Both are read-only arrays of 16-byte + nodes. +- **A field read as a `json::value`.** `json::value` is written but not read, so the + language server reads `method` first, then decodes `params`. +- **YAML:** comments kept when read and written again; a writer of comments, flow style + and anchors for repeated values; tags in typed values, as `!circle {radius: 1}`; and + keys that are collections, which `serial::encoder` can't write. + +### Iterators + +- **Splitting a sized iterator across threads.** +- **`chunks(n)` and `windows(n)` of a view,** giving views. +- **Iterators that write,** as `fill` and `copy_into`, which the algorithms plan has as + methods of slices. + +### Math + +- **`erf`, `gamma`, `lgamma`, and the Bessel functions.** +- **Correctly rounded versions,** from CORE-MATH, for programs that need results never + off by a rounding. MIT-licensed, but several times larger and slower than musl's. + +### Time + +- **`TZ`, and `TZDIR` beyond Windows,** read from the environment. On Linux, zones come + from `/usr/share/zoneinfo` and `/etc/localtime` only. `process::variable` exists, so + nothing blocks it. +- **Formats written with a pattern,** as `strftime`'s. +- **Windows zones by name, and the history of its local zone,** from the registry or + ICU. `zone::local()` there is the current rule only. +- **Leap seconds.** A day is 86,400 seconds, and a second of 60 is `out_of_range`. + +### Arguments + +- **`std::testing` reading its arguments through `std::args`.** `tester::run` compares + `--only` and `--here` by hand, since `std::args` would refuse the other arguments tests + are run with. +- **Environment variables as fallbacks,** as `@option{ env = "SAKURA_TARGET" }` for + `--target`. `process::variable` exists, so nothing blocks it. +- **Suggestions for a misspelled option:** "`--levle` is not an option; did you mean + `--level`?" +- **Shell completion scripts** written from the declarations. +- **Response files,** `@arguments.txt`, for lists longer than a system allows. +- **Help wrapped to the terminal's width.** It aligns its columns but never wraps. +- **The rest of the declarations checked while compiling.** The marks' shapes and types + are `compile_error`s, but duplicate names, duplicate short letters, which letters may + be short names, and `count` of an integer are checked as each run starts. Since + 2026-10-28 a `compile_error` a running condition chooses is reported, so they could be + too. + +### `core` + +- **A `core` for places with no heap,** with the containers in a child of their own. +- **Lang items by attribute,** as `@lang("string")`, rather than by name in the module + `core`, so `core` could be split into modules of its own. + +### A failing test + +`readers_and_writers_close_what_they_own`, of `std::io`, fails natively and on the +machine: it expects 4 bytes written once closed. It failed with the compiler from before +2026-10-27 too. + +## blossom + +- **The blossom plan's "Later, where wanted":** more `install` tags than `!include`, tags + for the build and test pipelines, versions resolved from ranges with a lock file, + `blossom new`, compiling in blossom's own process, several projects built as one, and an + index of packages by `gpid/name`. +- **Not run here:** an rpm package, as there's no `rpmbuild`, though the spec it's built + from is written and the missing tool said; a Debian package with `dpkg`, which isn't here + either, though `ar` and `tar` read it back whole; and blossom on Windows, which was only + built and checked. Its tests of its commands run `git`, `sh` and `tar`, so they're + Linux's. +- **Building the compiler is checked by hand, not by a test.** A test would take + minutes. +- **zip files are stored, not compressed,** until std has deflate. + +## Debugging information + +- **No Windows debugger has read a PDB file.** Visual Studio or WinDbg, stopping in a + program built with `-g`, would show whether they take what LLVM's tools do. +- **What CodeView can't say of a variable:** a value known as a constant over a range, + which the DWARF gives, isn't named there; a part of a variable of several words held + in the frame isn't either; and a variable whose frame slot holds the address of its + object of the heap is shown as a pointer to it. +- **Every function's type is `void ()`** in the PDB file, as the DWARF gives none, and a + debugger can't call them anyway. +- **Names aren't qualified.** Two functions of one name in different modules, as two + `write_all`s, are told apart by their IDs, but a debugger finding one by name finds + both, as with the DWARF and the symbol tables. +- **Globals aren't described,** in the PDB file or the DWARF. +- **`binary::amd64`'s `absolute` meets `std::io`'s,** so a file importing both, as + `native/native.sakura` does, writes `amd64::absolute`. + +## Tests not written + +- **Writing to the program's own output once nothing reads it.** A test can't make its + own output a closed pipe. The machine stops with status 141, as it should. +- **A read from a real pipe interrupted by a signal.** `io::pipe::open()` exists, but + the test reads a stream made to look interrupted. +- **`function` holding a C function.** See [`function`](#function). +- **Windows, since `extern` and `system`.** Its sources and std's tests were checked for + `windows-x86_64`, and the compiler's import table matched the seed's. None of it was + run, and neither was the machine's test of `ucrtbase.dll` + (`tests/machine/machine.sakura`): there's no Windows or Wine here. Since `core` the + same holds, with `CreateDirectoryW` imported too, for the language server's copy of the + built-in text. +- **`--deps` from the compiler's own tests.** Only blossom's tests run `sakurac` with it, + through blossom. +- **Native tests reading by reference.** The native backend's tests build their programs + over every file of `core`, `system`, the runtime and std, passing over std's `tests`, as + the compiler did before the std plan, so they take minutes where they took seconds. diff --git a/docs/linear.md b/docs/linear.md new file mode 100644 index 00000000..9bc8eac2 --- /dev/null +++ b/docs/linear.md @@ -0,0 +1,595 @@ +# Plan: vectors, matrices and quaternions + +Written 2026-10-14, and brought up to date 2026-10-20 for what was built since (method +bounds, `std::math`, `simd` and the optimizer's passes), probed and measured again. +This is a proposal. std is yours, so the decisions at the end are yours to make. Nothing +in std is built yet. Two compiler bugs the first probes found are fixed already (see +"Fixed along the way"). + +**Comes after the ffi plan, now built:** `std::sys` is `system`, and `@foreign` and +`@link` are `extern` sections. + +**Built in the rebuild alone** ([roadmap.md](roadmap.md), decision 1). Where this plan +says both compilers, C's half is left out. What was measured in C stays as measured. + +**What it is:** the objects of 2D and 3D math, with their operators: +- vectors of two, three and four numbers; +- square matrices of two, three and four columns; +- quaternions, for rotations; +- transforms of a position, a rotation and a scale; +- the camera's matrices, as Vulkan, OpenGL and Direct3D want them. + +**Its users:** +- programs drawing through Vulkan, whose vertices, uniforms and push constants hold + these; +- games and simulations: movement, collision, physics and cameras; +- tools reading 3D formats, such as glTF, whose nodes are transforms; +- grids and screens, with vectors of integers as keys and positions. + +**It builds on what's built:** +- **Operators by method** (the README's "Operators"). `a + b`, `m * v` and `q * r` are + methods. +- **`std::math`** (std/math/, built 2026-10-14). A length needs its `sqrt`, a rotation + its `sin` and `cos`, and `slerp` its `acos`. Its `real` trait says which types those + apply to. Its constants are `f64`s, so `f32` code writes `math::pi as f32`. +- **Bounds on a generic type's methods** (built 2026-10-19), so `length` is + `where T: real`. +- **`simd`** (std/simd.sakura, built 2026-10-14), which `vec4` may work through + (decision 11). + +**Probed:** again on 2026-10-20 (`plans/linear/` in the scratchpad), under both +compilers, in the VM and as executables at `-O2`. Every result here was the same +everywhere. Two that weren't are under "Found along the way". +- `struct vec3 : additive, indexable where T: numeric` with `add`, `sub`, + `negate`, `mul` and `equals` gave `+`, `-`, `-v`, `*`, `==` and `+=`: + - for `f32`, `f64` and `i32`; + - with `v * 2.0` taking the constant as the vector's own number; + - with a vector times a vector, and a vector times a number, as overloads of `mul`. +- **A number on the left,** as `2.0f * v`, through `def f32::mul(&this, v: &vec3)`. + But `2.0 * v` is still refused for an `f32` vector: an untyped `2.0` is an `f64`, + which asks for `f64::mul` (decision 2). +- **A matrix times a vector,** as columns times components, summed, and + `mat3f::identity()` through the alias. +- **Indexing:** `v[1] = 9`, through `indexable` and the fields read as an array, and + `v[3]` stopping the program. +- **A swizzle,** `a.xy`, as a property. +- **Methods for reals alone,** as `def vec3::length(&this): T where T: real`, now in + both compilers. Asking it of a `vec3` is an error where it's written, naming the + bound. +- **Hashing integers alone,** as `def vec2::hash(&this): u64 where T: integer`, so a + `vec2` keys a `dict`. +- **Constants** made by `cross` and `length`, and a Vulkan projection through + `math::tan` with its `clip_space` defaulted, in both compilers. +- **One type of any length,** `struct vec` holding a `T[N]`, with its + operators, `length`, and `cross` refusing other lengths by + `if const N != 3 { compile_error(...) }` (decision 3). + +**Measured** on 2026-10-20, the best of five, pinned to a performance core of a busy +machine: ten million steps of `total = total + step * half` on `vec3`, against the +same written as three fields. The 2026-10-14 times are in parentheses. + +| Where | Operators | Fields | +|---|---|---| +| The rebuild, `-O2` | 166 ms (400) | 67 ms (60) | +| C, `-O2` | 417 ms, the same with `0.5` written in place of `half` (430, and 2.1 s) | 159 ms (126) | + +- **Inlining is done.** Both compilers inline `add` and `mul` at `-O2` now, with a dozen + callers too. The rebuild moves `step * half` out of the loop, and zeroes nothing and + checks no pointers in it. +- **What's left is the rebuild's, for `f32` and other 4-byte numbers:** + - each `f32` operation is still done in double precision. An add is `addsd`, then + `cvtsd2ss` and `cvtss2sd`: three instructions for one `addss`. The fields pay it + too, and take twice what `f64`'s do: 67 ms against 31; + - the vector's fields are written to the stack and read back each step: 36 + instructions a step, against the fields' 12. A `vec3` does the same, 23 ms + against 11, while a `vec3` stays in registers, its operators as fast as its + fields: 29 ms and 31. +- **C no longer boxes an `f32` lent by reference.** `step * 0.5` and `step.mul(0.5)` cost + what they cost with a variable. Its code is still about 2.5 times as slow as the + rebuild's, and does `f32` in double precision too. +- **Lanes:** a `vec4` whose `add` and `mul` read its fields as one `f32x4` where + `lanes_held()` took 73 ms, against 67 written as four fields, and 182 where its + operators work field by field. The bits were the same. + +So the types can be built today. Vectors of `f64` are as fast as written out already. +Those of `f32` need the rebuild's code generator, or lanes for `vec4` (decision 11). + +## What's there now + +- **Operators by method** (the README's "Operators"), chosen by the right operand, with + a number on the left asking its own type, and `a += b` as `a = a + b`. +- **Numbers' methods beside the compiler's:** a program may declare `f32::mul` taking a + vector. +- **Bounds on a generic type's methods,** in both compilers since 2026-10-19, as + `def vec3::length(&this): T where T: real`. Only the instances meeting them have + the method. +- **Constant parameters and `for const`,** so `vec` can be written, one body for + every length (decision 3). +- **`indexable`, properties, `if const`, and static methods through an alias,** as + `mat3f::identity()`. Generic types have no associated variables, so `vec3::zero` + is a function. +- **`std::math`** (the README's "Math"): `sqrt`, `sin`, `cos`, `tan`, `acos`, `atan2` + and `fma` of any `real`, with the same bits in the VM, in executables and in + constants. It has no `radians`, `degrees`, `lerp`, `smoothstep` or `remap` yet. +- **`simd`** (the README's "Vectors"): `f32x4` and the rest, held in registers by + the rebuild's `-O2` executables, which `lanes_held()` says while compiling. An `f32x4` + is 16 bytes aligned to 4, as a packed `vec4f` is. +- **`f32` is rounded after every operation,** in the VM and in executables, so the two + agree. Both compilers' executables work it in double precision. + +## What it needs + +1. **Vectors of 2, 3 and 4,** of any number: `f32` and `f64` for geometry, and integers + for grids and pixels. +2. **Their arithmetic as operators:** with each other component by component, with a + number on either side, and negation. +3. **Their geometry:** dot and cross products, length, distance, normalizing, + interpolating, reflecting and projecting. +4. **Matrices of 2, 3 and 4:** + - products with each other and with vectors; + - transposing, the determinant and the inverse; + - translating, scaling and rotating; + - looking at a point; + - perspective and orthographic projections. +5. **Quaternions:** + - from an axis and an angle, from Euler angles, from one direction to another, and + from a matrix; + - composing and rotating vectors; + - interpolating; + - to a matrix and back. +6. **Transforms:** a position, a rotation and a scale, combined, inverted, applied and + interpolated. +7. **Layouts C and the GPU read,** so a `vec3` is three floats one after another. +8. **The same bits in the VM, in executables, and in constants.** +9. **As fast as written out,** at `-O2`. + +## How it fits the rules + +- **Plain data.** Vectors, matrices and quaternions copy freely, hold nothing, close + nothing, and are `equatable`. Vectors of integers are `hashable`, by a `hash` + bounded `where T: integer`, so they key a `dict`. +- **Arithmetic is operators, by method.** A vector is `additive`. It isn't `numeric`, + since `*` between two vectors isn't a ring's product, and there's no `%`. +- **Nothing stops the program.** + - Normalizing a zero vector gives NaNs, as IEEE 754 does, and `normalize_or` gives a + fallback. + - An inverse is a `maybe`, which is `nothing` where the determinant is zero. + - So nothing calls `contract`, and every function runs in a constant in C too, which + refuses constants that could reach `contract`. +- **Methods for reals alone** are bounded `where T: real`, so asking one of a `vec3i` + is an error where it's written. Quaternions and transforms are of reals alone, bounded + so on the type. +- **The same bits everywhere:** + - each operation rounds as its type does, and nothing fuses a multiply and an add but + `math::fma`; + - the functions are `std::math`'s, which agree by construction; + - `simd`'s lanes give the bits the fields would, so `vec4` may take either way. + +## The types (decisions 1 to 5) + +```sakura +module std::math; + +pub struct vec2 : additive, indexable where T: numeric { pub var x: T; pub var y: T; } +pub struct vec3 : additive, indexable where T: numeric { pub var x: T; pub var y: T; pub var z: T; } +pub struct vec4 : additive, indexable where T: numeric { pub var x: T; pub var y: T; pub var z: T; pub var w: T; } + +#! Column by column, as GLSL, SPIR-V and Vulkan lay them out (decision 5). +pub struct mat2 where T: numeric { pub var columns: vec2[2]; } +pub struct mat3 where T: numeric { pub var columns: vec3[3]; } +pub struct mat4 where T: numeric { pub var columns: vec4[4]; } + +#! A rotation, `w` last, as glm, Eigen and glTF hold it. +pub struct quat where T: real { pub var x: T; pub var y: T; pub var z: T; pub var w: T; } + +#! Where something is, how it's turned, and how large, applied scale first. +pub struct transform where T: real { + pub var translation: vec3; + pub var rotation: quat; + pub var scale: vec3; +} + +pub type vec2f = vec2; pub type vec3f = vec3; pub type vec4f = vec4; +pub type vec2d = vec2; pub type vec3d = vec3; pub type vec4d = vec4; +pub type vec2i = vec2; pub type vec3i = vec3; pub type vec4i = vec4; +pub type mat3f = mat3; pub type mat4f = mat4; pub type quatf = quat; +# and mat2f, the f64 ones, and transformf +``` + +## The operations + +**Vectors,** for any `T`: + +```sakura +a + b a - b -a a += b # component by component +a * b a / b # component by component +v * s v / s s * v # by a number; s * v for f32, f64 and i32 +a == b # every component equal +v[i] # a component, read or written + +pub def vec3::dot(&this, other: &vec3): T; +pub def vec3::cross(&this, other: &vec3): vec3; # vec3 alone +pub def vec3::length_squared(&this): T; +pub def vec3::min(&this, other: &vec3): vec3; # also max, clamp, abs +pub def vec3::sum(&this): T; +pub def vec3::cast(&this): vec3; # each as `as` converts it +pub def vec3::hash(&this): u64 where T: integer; # so integers key a dict +pub def vec3::of(xy: vec2, z: T): vec3; # and vec4::of(xyz, w) +pub val vec3::xy: vec2; # a property; the other swizzles (decision 9) +pub def vec3::zero(): vec3; # also one, x_axis, y_axis, z_axis, as vec3f::zero() +``` + +**Vectors,** where `T` is `f32` or `f64`: + +```sakura +pub def vec3::length(&this): T where T: real; # and so is each below +pub def vec3::distance(&this, other: &vec3): T; +pub def vec3::normalize(&this): vec3; # NaNs for a zero vector +pub def vec3::normalize_or(&this, fallback: vec3): vec3; +pub def vec3::lerp(&this, to: &vec3, t: T): vec3; +pub def vec3::reflect(&this, normal: &vec3): vec3; +pub def vec3::project_onto(&this, onto: &vec3): vec3; +pub def vec3::angle_to(&this, other: &vec3): T; # radians +pub def vec3::near(&this, other: &vec3, tolerance: T): bool; +``` + +**Matrices:** + +```sakura +m * n m * v m * s m + n m - n m == n m[c] # m[c] is column c + +pub def mat4::identity(): mat4; +pub def mat4::of_rows(rows: vec4[4]): mat4; +pub def mat4::transpose(&this): mat4; +pub def mat4::determinant(&this): T; +pub def mat4::row(&this, index: u64): vec4; +pub def mat4::translation(by: vec3): mat4; +pub def mat4::scaling(by: vec3): mat4; + +# Each of these is `where T: real`. +pub def mat4::inverse(&this): maybe>; +pub def mat4::rotation(axis: vec3, angle: T): mat4; # also rotation_x, _y, _z +pub def mat4::look_at(eye: vec3, target: vec3, up: vec3): mat4; +pub def mat4::perspective(fov_y: T, aspect: T, near: T, far: T, clip: clip_space = clip_space::vulkan): mat4; +pub def mat4::orthographic(left: T, right: T, bottom: T, top: T, near: T, far: T, clip: clip_space = clip_space::vulkan): mat4; +pub def mat4::transform_point(&this, point: vec3): vec3; # w of 1, divided through +pub def mat4::transform_direction(&this, direction: vec3): vec3; # w of 0 +pub def mat4::normal_matrix(&this): maybe>; # the inverse transposed + +#! Where depth runs and which way y points after projecting (decision 6). +pub enum clip_space: u8 { + vulkan, #! depth 0 to 1, y down + opengl, #! depth -1 to 1, y up + direct3d, #! depth 0 to 1, y up, as Metal and WebGPU too +} +``` + +**Quaternions:** + +```sakura +q * r q * v q == r -q + +pub def quat::identity(): quat; +pub def quat::of_axis_angle(axis: vec3, angle: T): quat; +pub def quat::of_euler(yaw: T, pitch: T, roll: T): quat; # decision 8 +pub def quat::between(from: vec3, to: vec3): quat; # the shortest arc +pub def quat::look_rotation(forward: vec3, up: vec3): quat; +pub def quat::of_matrix(m: mat3): quat; +pub def quat::conjugate(&this): quat; # also inverse, normalize, dot, length +pub def quat::slerp(&this, to: &quat, t: T): quat; +pub def quat::nlerp(&this, to: &quat, t: T): quat; +pub def quat::matrix(&this): mat3; # also matrix4 +pub def quat::axis(&this): vec3; # also angle, euler +``` + +**Transforms and helpers:** + +```sakura +a * b # b, then a +pub def transform::identity(): transform; +pub def transform::inverse(&this): transform; +pub def transform::matrix(&this): mat4; +pub def transform::apply(&this, point: vec3): vec3; # also apply_direction +pub def transform::lerp(&this, to: &transform, t: T): transform; + +pub def radians(degrees: T): T where T: real; # also degrees +pub def lerp(from: T, to: T, t: T): T where T: real; +pub def smoothstep(edge0: T, edge1: T, x: T): T where T: real; +pub def remap(x: T, from_low: T, from_high: T, to_low: T, to_high: T): T where T: real; +``` + +## Using it + +**A camera's matrices for Vulkan:** + +```sakura +import std; +import std::math; + +val view := mat4f::look_at(eye, vec3f::zero(), vec3f::y_axis()); +val projection := mat4f::perspective(math::radians(60.0f), width / height, 0.1, 100); +val model := transform::{ translation = at, rotation = facing, scale = vec3f::one() }.matrix(); +push.mvp = projection * view * model; # a mat4f, as the shader's mat4 reads it +``` + +**Turning, and easing between two turns:** + +```sakura +val quarter := quatf::of_axis_angle(vec3f::y_axis(), math::pi as f32 / 2); +val ahead := quarter * vec3f{ x = 0, y = 0, z = -1 }; # now (-1, 0, 0) +val halfway := facing.slerp(&target, 0.5); +``` + +**A grid:** + +```sakura +var tiles := dict::::new(); +val east := vec2i{ x = 1, y = 0 }; +tiles.set(position + east, tile::grass); +``` + +## How each part works + +- **Layout (decision 4):** + - Each type is its fields one after another, as C's arrays are. A `vec3` is 12 + bytes, and a `mat4` 64, as Vulkan's vertex formats, glm and SPIR-V's storage + buffers take them. + - std140 uniform blocks align a `vec3` to 16. Matching that is the program's to do, as + with any struct a shader reads. + - A `vec4f` is laid out as an `f32x4` is, so it can be read as one (decision 11). +- **Indexing** reads the fields as a fixed array, through a pointer to the first, + `&this.x`, so an index out of range stops the program as any array's does, and needs + no `contract`. (`&this` is a `&&vec3`, a reference to the reference, so it isn't + the vector's address.) +- **A number on the left** is a method on that number: `f32::mul`, `f64::mul` and + `i32::mul`, each taking a vector, matrix or quaternion, for the aliases above. Other + number types put the number on the right. +- **Reals alone:** + - `length`, `normalize` and the rest are bounded `where T: real`, so asking them of a + `vec3i` is a mistake where it's written, naming the bound. + - Matrices' inverses, rotations and projections do the same. `quat` and `transform` + are bounded `real` on the type, since a turn of integers means nothing. +- **Named vectors** are static functions, as `vec3f::zero()` and `vec3f::y_axis()`, + since a generic type has no associated variables. +- **Matrices (decision 5):** + - Column `c` is `m[c]`, and the element in row `r` of it is `m[c][r]`, as in GLSL. + - `m * v` treats `v` as a column, and `m * n` applies `n` first. So `projection * + view * model` reads right to left, as shaders do. + - `inverse` is by cofactors, giving `nothing` where the determinant is exactly zero. +- **Projections (decision 6):** + - View space is right-handed: the camera looks down -Z, with +Y up, in every case. + - Only the projection differs by `clip_space`: + - `vulkan` maps near to 0 and far to 1, and negates y, since Vulkan's y points down; + - `opengl` maps them to -1 and 1; + - `direct3d` maps them to 0 and 1, with y up. +- **Quaternions (decision 8):** + - Hamilton's: `i * j` is `k`. + - `q * r` rotates by `r` first, as matrices compose. + - `q * v` rotates `v` by `q`, as `v + 2w(u × v) + 2u × (u × v)`, where `u` is + `(x, y, z)`. That needs no matrix. + - `slerp` takes the shorter way, negating one where their dot is negative. It falls + back to `nlerp` where they're nearly the same, where `acos` loses precision. + - `of_euler(yaw, pitch, roll)` turns by `roll` about Z, then `pitch` about X, then + `yaw` about Y, for +Y up. `euler` gives them back, with pitch from -π/2 to π/2. +- **Transforms** apply scale, then rotation, then translation. `a * b` applies `b` + first. + - `inverse` is exact where the scale is the same on every axis. + - Otherwise the true inverse shears, which a transform can't hold. So `inverse` + gives the nearest transform, and `matrix().inverse()` the exact matrix. +- **Equality** is exact, so a vector holding a NaN equals nothing, itself included. + `near` compares within a tolerance. +- **Printing:** interpolation shows the fields, as `vec3{x = 1, y = 2, z = 3}`. + `describe` gives `(1, 2, 3)`. + +## Performance (decision 11) + +What 2026-10-14 asked of the rebuild's code generator is half done, after its +optimizer's passes of 2026-10-18 ([performance.md](performance.md)): small methods +returning a struct are inlined, and nothing in the probe's loop is zeroed or checked for +null. What's left is for `f32` and other 4-byte numbers: +- **`f32` arithmetic in single precision** (built 2026-10-28, see the + [CHANGELOG](../CHANGELOG.md)): + - `addss`, `subss`, `mulss`, `divss` and `sqrtss` round exactly as computing in double + and rounding does, since a double holds more than twice a float's bits. + - So the results are the same bits, and the VM needn't change. + - That's 1 instruction for 3, and removes the conversions' latency from every chain. + It speeds every `f32`, not only vectors: written as fields, `f32` took twice `f64`'s + time. +- **Vectors of 4-byte numbers in registers,** as those of 8-byte ones are. A + `vec3`'s and a `vec3`'s fields go to the stack and back each step, where a + `vec3`'s stay in registers. This phase finds what keeps them in memory. +- **Lanes for `vec4`, in std:** + - Where `lanes_held()`, `add`, `sub`, `mul` and the rest of a `vec4` of 4-byte numbers + read its fields as one `simd`, through `&this.x`, since an `f32x4` is laid out + as a packed `vec4f` is. Elsewhere, in the VM, constants and C's executables, they + take the fields. + - The probe's `vec4` took 73 ms so, against 67 written as fields. + - A `mat4`'s columns are `vec4`s, so its products would be four lanes' multiplies and + adds. + - `vec2` and `vec3` of `f32` aren't 16 or 32 bytes, and wait for the code generator. +- **The target:** vector arithmetic within 1.5 times the same written as fields, at + `-O2`, measured by the probe. + +C's code isn't sped up here. The rebuild is the compiler that's going forward, and C's +results are already right. + +## Testing + +- **`test/std/linear.sakura`, written with `std::testing`,** covers: + - **vectors:** every operator for `f32`, `f64` and `i32`, a number on each side, + indexing past the end stopping a forked copy, swizzles, `cast`, `hash` in a `dict`, + and the identities: `a × b` perpendicular to both, `a · a` its length squared, and + `normalize` of zero giving NaNs; + - **matrices:** products against values worked out by hand, `inverse` round trips to + within a tolerance, a singular matrix's `nothing`, and `determinant` of rotations + being 1; + - **projections:** for each `clip_space`, a point on the near plane mapping to its + near depth and one on the far plane to its far depth, and y's direction; + - **quaternions:** rotating a vector agreeing with `matrix()` doing it, `of_matrix` + back again, `slerp` at 0, 1 and halfway, the shorter way, Euler angles round trips + away from the poles, and `between` of opposite vectors; + - **transforms:** `matrix()` agreeing with `apply`, and `inverse` undoing it; + - **constants:** `const forward := vec3f::x_axis().cross(&vec3f::y_axis())` and a + constant projection, the same in both compilers. +- **A program of the corpus** prints the bits of many results, so the VM, executables + and both compilers are compared exactly. +- **Where they run:** in the VM, as executables at `-O0` and `-O2`, and with + `run --checks`. The rebuild's analyzer must check them with 0 notes. +- **The probe's timings** are run before and after decision 11's work. + +## Phases + +About 1,700 lines of std and 900 of tests. Every program's check would grow by about 5%: +a copy of std/simd.sakura's 1,075 lines of generic methods, added to std, cost 3% of a +one-line program's check in both compilers (2026-10-20, a busy machine). Decision 11 is +work in the rebuild's code generator, sized once its first part, finding what keeps +4-byte fields in memory, is done. + +1. **Vectors,** with everything that needs no `sqrt`: operators, `dot`, `cross`, + indexing, swizzles, `min` and `max`, and hashing. +2. **Matrices,** with products, `transpose`, `determinant`, `inverse`, `translation` and + `scaling`. +3. **What needs `std::math`:** lengths, normalizing, interpolating, `look_at`, rotations, + projections, quaternions and transforms, and the helpers. +4. **Lanes for `vec4` and `mat4`, and the rebuild's code generator (decision 11).** +5. **A "Vectors and matrices" section in the README,** beside its "Vectors" of `simd`. + +Each can begin now: `std::math` was built the day this was written. + +## Fixed along the way + +These were found by the probes and fixed on 2026-10-14. Both compilers passed every +check after. Both fixes still hold: the corpus program below gave its expected output +under both compilers, in the VM and at `-O2`, on 2026-10-20. +- **C passed 0 for a constant on the right of an operator whose method takes `&f32`.** + `v * 2.0` on a `vec3` gave a zero vector, since the constant was lent as the + `f64` it is alone. It's now lent as an `f32`, as a call's argument is, in `*`, in + `*=`, and in `*=` on a property. The rebuild was right already. +- **The rebuild called `def f32::mul(&this, v: &vec3)` a cycle.** That happened + where `vec3`'s bound asks for `mul`, since deciding that `f32` is `numeric` worked out + the program's methods on `f32` first, this one among them. It now asks the compiler's + own methods on a number first, as C does. +- **A program of the corpus covers both:** + `operators_lend_constants_as_their_methods_take_them_1`. + +## Found along the way + +- **`2.0 * v` is refused for an `f32` vector,** still, in both, since an untyped + constant on the left asks its own type, `f64`. `2.0f * v` and `v * 2.0` work. Letting + a constant on the left take the type of a method that fits would change the README's + rule for a number on the left (decision 2 here). +- **The rebuild does `f32` arithmetic in double precision,** rounding after each + operation, as C's executables do too: three instructions for one `addss`. +- **The rebuild keeps a struct of 4-byte numbers in memory** through a loop, where one + of 8-byte numbers stays in registers (Performance). +- **Generic types have no associated variables,** and the compilers differ in how they + say so. C refuses `val vec3::zero := ...`. The rebuild takes the declaration, but + reading it gives a `vec3` no instance made: `val z: vec3f = vec3f::zero` is a + mismatch, and interpolating it prints nothing. An alias's own, `val vec3f::zero := + ...`, works in both. +- **The rebuild doesn't report `compile_error` in a property's getter while checking.** + For `vec`'s `z`, guarded by `if const N < 3 { compile_error(...) }`, C reports + the error where a `vec2`'s `z` is read. The rebuild checks it clean, and `run` stops + with "Checking an instance lowering asked for made notes.", without the note. In a + method, as `cross`, both report it while checking. +- **"Vector" now names three things:** `vector`, the README's "Vectors" of `simd`, + and these. +- **No longer so** (2026-10-20): + - **Neither compiler inlined a small method returning a struct** at `-O2`. Both do. + - **C boxed an `f32` temporary lent by reference,** five times the cost of lending a + variable. It costs what a variable does. + - **C refused bounds on a generic type's methods,** where the rebuild took them, which + is why reals were checked inside the methods by `if const`. Both take them since + 2026-10-19. + +## Later, where wanted + +- **Geometry:** rays, planes, boxes, spheres and frustums, and the tests between them. +- **Rectangular matrices,** as 3×4 for affine transforms, and matrices of any size for + numerical work. Decision 3's (b) would bring them. +- **Lanes for `vec2` and `vec3` of `f32`,** which aren't 16 or 32 bytes. `vec4`'s are + in decision 11, now `simd` is built. +- **std140 and std430 layouts,** as types padded for uniform and storage buffers. +- **Reversed and infinite depth** in projections, for precision far away. +- **Dual quaternions,** for skinning, and rotors, from geometric algebra. +- **Writing vectors as arrays** in JSON, as glTF does, through a serial format option. +- **One `lerp` for numbers and vectors,** through a trait like the README's + `scales`, which std doesn't name. + +## Decisions for you + +1. **Where it lives:** + - **(a) `std::math`, beside its functions, in std/math/ (recommended).** One import + gives a program drawing in 3D everything it uses. + - **(b) `std::linear`, of its own.** A program wanting only `sqrt` doesn't see + `vec3`, but most that want one want both. Neither saves checking, since every + program is checked with all of std. +2. **The numbers inside:** + - **(a) Generic, as `vec3`, with aliases for `f32`, `f64` and `i32` + (recommended).** One body serves floats, doubles and grids. `2.0 * v` needs `2.0f` + for an `f32` vector, or the rule for a number on the left changes so a constant + there takes the type of a method that fits. + - **(b) `f32` alone,** as many game libraries default to, with `vec3d` and `vec3i` + written again where wanted. `2.0 * v` still needs `2.0f`. + - **(c) Generic, with no aliases.** +3. **Lengths,** open now that constant parameters and `for const` make the second + possible: + - **(a) A type for each, `vec2`, `vec3` and `vec4`, with fields (recommended).** + Literals name the fields, `vec3f{ x = 1, y = 2, z = 3 }`, reflection and `@serial` + see them, and `cross` and the swizzles are only where they mean something. + - **(b) One of any length, `vec` holding a `T[N]`, with the same + aliases.** One body serves every length, and matrices of any shape would come with + it. But `x` to `w` are properties, a literal is `vec3f{ c = [1, 2, 3] }`, and + `cross`, `z` and `w` refuse the wrong lengths by `if const N != 3 { + compile_error(...) }`, which the rebuild reports from a property only as it runs, + without the message. +4. **Layout:** + - **(a) Packed, as C's arrays (recommended).** Vertex buffers and C libraries read + them as they are, and a `vec4f` is laid out as an `f32x4` is. + - **(b) `vec3` and `vec4` aligned to 16,** as std140 likes them. A `vec3` would take + 16 bytes, and wouldn't match a vertex format of three floats. `simd` doesn't need + it: an `f32x4` is aligned to 4. +5. **Matrices:** + - **(a) Column by column, with vectors as columns, `m * v` (recommended).** As GLSL, + SPIR-V, Vulkan, OpenGL and glm have it, so a matrix goes to a shader as it is. + - **(b) Row by row, with vectors as rows, `v * m`,** as Direct3D's older math + libraries have it. +6. **Clip space:** + - **(a) A parameter naming the API, Vulkan by default (recommended).** + - **(b) Vulkan alone.** Simpler, but OpenGL and WebGPU programs would fix every + projection by hand. + - **(c) A function for each,** as `perspective_vulkan` and `perspective_gl`. +7. **Angles:** + - **(a) Radians, as plain numbers, with `radians` and `degrees` (recommended).** As + `math::sin` takes them, and every library has it. + - **(b) An `angle` type,** made by `degrees(90)` or `radians(x)`, as `duration` is + made of a unit. Degrees can't then be passed for radians, at the cost of + converting at every `sin`. +8. **Euler angles:** + - **(a) One order, yaw about Y, pitch about X and roll about Z, for +Y up + (recommended).** That's what cameras and characters want. + - **(b) Every order, chosen by an enum,** for tools reading other programs' + conventions. + - **(c) None:** axes and angles, and directions, alone. +9. **Swizzles:** + - **(a) The common ones as properties (recommended):** `xy`, `xz` and `yz` of a + `vec3` or `vec4`, and `xyz` of a `vec4`. + - **(b) Every one,** written by a tool: 336 for a `vec4`, of two to four components. + It's about 1,000 more lines of std, which every program's check pays about 3% for, + by the measure in "Phases". + - **(c) A method,** as `v.swizzle(2, 0, 1)`. +10. **What's in it:** + - **(a) Vectors, square matrices, quaternions, transforms and the helpers, with + geometry later (recommended).** + - **(b) Geometry now too:** rays, planes, boxes, spheres and frustums. + - **(c) Vectors and matrices alone.** +11. **Speed,** where inlining is settled and `f64` vectors are as fast as written out: + - **(a) Both, as part of this plan (recommended):** in the rebuild's code generator, + `f32` in single precision and 4-byte fields held in registers; in std, `vec4`'s + and `mat4`'s operations of 4-byte numbers through `simd` where `lanes_held()`. + `f32` vector code is otherwise 2.5 times slower than the same written out. + - **(b) Lanes alone, in std.** `vec4` is fast now, and `mat4`'s products would be + too, but `vec2` and `vec3` of `f32` stay 2.5 times slower until the code + generator's own plan. + - **(c) Left to the code generator's own plan,** with `f32` vectors slow until then. + - **(d) Accepted.** diff --git a/docs/logging.md b/docs/logging.md new file mode 100644 index 00000000..e2a9bce8 --- /dev/null +++ b/docs/logging.md @@ -0,0 +1,428 @@ +# Plan: logging + +Written 2026-10-07, and brought up to date 2026-10-20 for threads, owners and +`function`, `std::time`, and what probing both compilers showed. This is a proposal. +std is yours, so the decisions at the end are yours to make. Nothing of it is built +yet but the clock, which `std::time` brought on 2026-10-12. + +**Comes after the ffi plan, now built:** `std::sys` is `system`, and `@foreign` and +`@link` are `extern` sections. + +**Built in the rebuild alone** ([roadmap.md](roadmap.md), decision 1). Where this plan +says both compilers, C's half is left out. What was measured in C stays as measured. + +**What it is:** a program saying what it's doing, at levels a user can turn up or +down. Each record carries when and where it was written. Records go to the standard +error, or anywhere the program chooses. + +**Its users:** +- the build tool and the self-hosted compiler, saying what they run and how long it + takes; +- the rebuild's language server, `sakura lsp`, whose records go to the client as + `window/logMessage`, since its standard output belongs to the protocol; +- programs whose records other programs read, as JSON lines. + +**Probed:** +- **On 2026-10-07,** in the scratchpad (`logprobe/`): the clocks, which `std::sys` now + has; whether a handle is a terminal, through the `TCGETS` `ioctl`; and a floor, + `call_site()` as a default, and a sink held in a module's variable. +- **On 2026-10-20,** in the scratchpad (`plans/logging/`), under both compilers: in the + VM, as executables at `-O0` and `-O2`, with `run --checks`, and checked for Windows, + with 0 notes and 0 warnings. A sketch of `std::log` in a copy of std covered: + - `sys::is_terminal`, added to a copy of `std::sys`: false through a pipe, and true + under a pseudo-terminal; + - the floor, `log::to` with owned and borrowed sinks and nested guards, and the text + and JSON sinks; + - 400 records from four threads, all counted; + - `math::log` beside `log::info`, and the "Using it" program below. + +## What's there now + +- **`io::error_output()`,** the shared writer of the standard error, which writes at + once. `io::error_output_locked()` holds it for one thread across several writes, as + `print` and `println` hold the standard output for each call. +- **`call_site()`,** which, as a default, is filled in with where the call is + written: its file, line, column, and the function's signature, while compiling. +- **Interpolation,** which formats any value: enums by their member's name, and + structs field by field. +- **The clocks and the calendar:** `sys::clock(clock_kind::wall)` and `steady`, and in + `std::time`, `timestamp::now()`, `timestamp::at(zone)`, which gives the `date_time` + a zone's clocks show, and `rfc3339()`. That writes as many places of a second as + the moment has: `.372006452`, `.45`, or none for a whole second. +- **No way to tell whether a stream is a terminal:** `std::sys` has only a private + `is_console` on Windows. +- **Threads:** `std::thread`'s `mutex`, and `atomic`, so several threads may log at + once. A signal handler runs in the thread the program began with, at a safe point, + and std's own code has none. +- **`io::writer_of(stream)`,** which owns a stream given by value, as `move(f)`, and + borrows one given as `&mut f`. +- **Owning a value whatever its type:** `function` owns any callable of a signature + through a table of what its type does, and `sys::handle` keeps each handler in one + until another is set. A sink of any type can be owned the same way. +- **`json::writer`,** which writes into a string it keeps, `clear()`s to write the + next value in the same memory, and writes text that isn't UTF-8 once `set_lossy`. +- **`process::variable(name)`,** which reads the environment. +- **Programs print with `println`,** or write to `io::error_output()` directly. The + rebuild's language server sends `window/logMessage` through its own `server::log`. + +## What it needs + +1. **Levels:** trace, debug, info, warning and error, and a floor below which nothing + is written. +2. **Where and when:** each record's file, line and function, and the time. +3. **Cheap when off:** a record below the floor costs a load and a comparison. +4. **Sinks:** + - the standard error, by default; + - any `writable`, as a file; + - a program's own sink, as a language server's. +5. **Formats:** text for people, coloured on a terminal, and JSON lines for programs. +6. **Order kept with the rest of the output:** a record to the standard error is + written at once, as other writes to it are, and as one write, so lines don't + interleave. +7. **Threads:** records made by several threads at once are each written whole. + +## How it fits the rules + +- **One logger, shared, as `io::output()` is (decision 2).** + - Its floor is an `atomic` of `std::log`, read with `order::relaxed`, which in + an executable is a plain load. + - Its sink is behind a `thread::mutex`, so records from several threads are written + whole, one at a time, and each thread's in the order it made them. + - A record made while its own thread holds that lock, by a sink that logs, or by a + signal handler run at a safe point in a program's own sink, is dropped rather + than waited for. A thread holding `io::error_output_locked()` logs only after + letting go of it, as it may not `print` while holding `io::output_locked()`. +- **A sink is taken as `io::writer_of` takes a stream (decision 4).** `log::to(sink)` + owns a sink given by value, and borrows one given as `&mut mine`. It gives back a + guard that puts the previous sink back where it closes, closing one it owns. The + guard is `@nodiscard`, so `log::to(&mut mine);` on its own, which would put the old + sink back at once, is an error in both compilers (probed). +- **A record is plain data,** made of views. It's valid only while a sink writes it, + so a sink keeping one copies what it needs. +- **Logging never fails the program.** + - A write that fails is dropped. No `result` comes back from `log::info`, and a + sink's `write` gives `void`, where a stream's gives `result`. + - Writing to a closed standard error still stops the program quietly, by + `SIGPIPE`, as any write to the console does (status 141 in both compilers' VMs + and executables, probed). +- **Calls are written qualified, as `log::info(...)`.** Without the module, + `info` is ambiguous with `std::io::info` under `import std::io;`, in both compilers + (probed again), and `error` reads as `result`'s field. The logarithm doesn't clash: + under `import std::math;` and `import std::log;`, `log(x)` is `math::log` and + `log::info` the module, in both compilers (probed). + +## Layers + +### `std::sys` gains + +| Operation | Does | +|---|---| +| `is_terminal(handle: fd): bool` | Whether the handle is a terminal. Probed | +| `allow_colour(handle: fd): bool` | Whether the handle shows colour codes, letting it where it can | + +- **On Linux:** `is_terminal` is an `ioctl` with `TCGETS` (16 on x86-64), through + `syscall`, as `clock` calls `clock_gettime`. `allow_colour` is `is_terminal`. +- **On Windows:** `std::sys` already has a private `is_console`, which asks + `GetConsoleMode`, and `is_terminal` gives it the handle `handle_of` finds. A + console shows colour codes only once its virtual terminal processing is on, so + `allow_colour` turns it on with `SetConsoleMode`, and is false where that's refused. +- **The clock is built:** `sys::clock(which: clock_kind): i64`, of `clock_gettime` on + Linux, and of `GetSystemTimePreciseAsFileTime` and `QueryPerformanceCounter` on + Windows. `clock_kind` is in module `std`, in `std/time/clock.sakura`. +- **Records keep a `time::timestamp`.** `std::log` writes its text from the + `date_time` that `timestamp::at(zone::utc())` gives, to the millisecond, so every + line's time is one width, where `rfc3339()` would write as many places as the + moment has. The calendar is `std::time`'s. + +### `std::log` (decision 1) + +```sakura +module std::log; + +#! How much a record matters, from least to most. +pub enum level: u8 { + trace, #! Each step, for following the program closely. + debug, #! What a developer wants while looking into a problem. + info, #! What the program is doing, at a pace a user follows. + warning, #! Something unexpected that the program went on past. + error, #! Something that failed. + off, #! As a floor, nothing is written. +} + +#! What the program said, as a sink is given it. +pub struct record { + pub val level: level; #! How much it matters. + pub val time: time::timestamp; #! When, by the wall clock. + pub val at: site; #! Where it was written: file, line, column, and function. + pub val message: strview; #! What was said, valid only while the sink writes it. +} + +#! Where records go. +pub trait sink { + #! Writes a record. + def write(&mut this, entry: &record): void; + + #! Writes what it holds back, which a sink holding nothing back leaves as it is. + def flush(&mut this): void {} +} + +pub def trace(message: strview, at: site = call_site()): void; +pub def debug(message: strview, at: site = call_site()): void; +pub def info(message: strview, at: site = call_site()): void; +pub def warning(message: strview, at: site = call_site()): void; +pub def error(message: strview, at: site = call_site()): void; +pub def write(wanted: level, message: strview, at: site = call_site()): void; + +pub def enabled(wanted: level): bool; # whether a record at the level is written +pub def set_floor(lowest: level): void; # `info` until it's set +pub def floor(): level; + +#! Sends records to a sink until the guard closes. One given by value is the +#! logger's, and one given as `&mut mine` is borrowed, as `io::writer_of` takes a +#! stream. +pub def to(target: K): guard where K: sink; +pub def flush(): void; + +#! Puts the sink before it back where it closes, closing one the logger owns. +@nodiscard +pub struct guard : owning { ... } + +#! How text records are written. +pub struct style { + pub var time: bool = true; #! Whether the time is written. + pub var site: bool = true; #! Whether the file and line are written. + pub var colour: bool = false; #! Whether levels are coloured, for a terminal. +} + +#! Writes records as lines of text, to a stream it owns or borrows, as +#! `io::writer_of` does. +pub struct text_sink : sink, owning where S: writable { ... } +pub def text_to(stream: S, how: style = style {}): text_sink where S: writable; + +#! Writes each record as a line holding one JSON object. +pub struct json_sink : sink, owning where S: writable { ... } +pub def json_to(stream: S): json_sink where S: writable; +``` + +- **`flush` has an empty body, not `@optional`.** Neither compiler calls an + `@optional` method through a trait reference, which is how the logger reaches its + sink, while a default is taken even by a sink that doesn't name the trait (both + probed). + +## Using it + +```sakura +import std; +import std::args; +import std::io; +import std::log; + +@command{ help = "Builds things." } +struct options { + @option{ short = 'v', count = true, help = "Says more: -v for debug, -vv for trace." } + var verbose: u8; + @argument{ value = "FILE", help = "The files to build." } + var files: vector; +} + +def main(args: span): void { + val given := args::parse_or_exit::(args); + log::set_floor(given.verbose >= 2 ? log::level::trace + : given.verbose == 1 ? log::level::debug + : log::level::info); + + log::info($"building {given.files.length} files"); + if log::enabled(log::level::debug) { + log::debug(list_of(&given.files)); # built only where it's written + } + + # Records go to a file instead of the console until `using` closes. + val named := path::parse("build.log") else { return; }; + var file := io::file::create(&named) else { return; }; + val using := log::to(log::text_to(move(file))); + log::warning("this goes to build.log"); +} # `using` closes, closing the sink and the file +``` + +A language server sends records to its client, as the rebuild's `server::log` sends +`window/logMessage`: + +```sakura +struct client_log : log::sink { + var to: &mut server; +} + +def client_log::write(&mut this, entry: &log::record): void { + val kind: u32 = match entry.level { error => 1, warning => 2, info => 3, else => 4 }; + this.to.log(kind, entry.message); +} + +# In a method of `server`, for as long as it serves: +val using := log::to(client_log { to = this }); +``` + +## How each part works + +- **Below the floor:** + - `log::info` and the rest each compare the level with the floor before calling + what makes the record. They're small, so `-O2` inlines them where they're + called, and a record below the floor costs a load and a compare, besides its + arguments (probed in the rebuild; a test inside the one function they all call + wasn't copied out of it). + - Its message is still built by the caller, as any argument is. So a message costly + to build is written under `if log::enabled(...)` (decision 3). +- **Making a record:** the time is read by `time::timestamp::now()` only for a record + that's written, and the site comes from the default. +- **The default sink** writes text to the standard error, through + `io::error_output_locked()` for each record, so it mixes with nothing another + thread writes there holding it. + - It colours levels where `sys::allow_colour(sys::fd::stderr)` holds, asked once. + - It holds nothing of its own, so there's nothing to close. +- **Text:** one line per record, made in a `string`, then written as one write. + + ``` + 2026-10-07T12:42:03.451Z INFO main.sakura:16 building 12 files + 2026-10-07T12:42:03.517Z WARN plan.sakura:88 `old.sakura` is listed twice + ``` + + - The time is RFC 3339 in UTC, to the millisecond, always three places. A time + before 1970 is floored, as `std::time` floors it: 995 milliseconds before 1970 is + `1969-12-31T23:59:59.005Z` (probed). + - Levels are padded to five, as `TRACE`, `DEBUG`, ` INFO`, ` WARN` and `ERROR`. + - The path is as the compiler was given it. + - With `colour`, `TRACE` and `DEBUG` are dim, `WARN` is yellow and `ERROR` red. + - A message holding line breaks is written as it is, so its later lines begin + with nothing before them. +- **JSON:** one object per line, written through a `json::writer` the sink keeps, + cleared for each record, so the message is escaped. The writer is lossy, so a + message that isn't UTF-8 is written with U+FFFD where it breaks, rather than as + `null`. The level is its member's name, as interpolation writes it: + + ``` + {"time":"2026-10-07T12:42:03.451Z","level":"info","file":"main.sakura","line":16,"function":"def main(args: span): void","message":"building 12 files"} + ``` + +- **`log::to`** moves the sink it's given to the heap, as `function` holds a callable + too large for itself, keeps a `&mut sink` to it, and gives a guard holding the one + before. Given `&mut mine`, what it moves is only the reference. + - Guards closed in the reverse of the order they were made, as RAII closes them, + put back each sink in turn, holding the lock, so a record being written on + another thread is finished first. + - A guard then closes the sink it set where the logger owns it, which flushes what + the sink holds back. +- **`log::flush`** flushes the sink, where it flushes. A program stopping through + `sys::exit` flushes nothing and closes nothing, guards included, as now (probed in + both compilers), so a sink that holds records back is flushed first. The logger's + own variables are never closed, as no module's are when the program ends. + +## Testing + +- **`test/std/log.sakura`, written with `std::testing`,** covers: + - **the floor:** each level against each floor, `off`, and `enabled`; + - **sites:** the file and line a record gives are where `log::info` was written; + - **sinks:** + - a program's own sink collecting records, owned and borrowed; + - `log::to` guards, nested, putting each sink back as they close, and closing + those the logger owns; + - `log::flush` reaching a sink that flushes, and one that doesn't; + - **text:** records with a fixed time written by `text_to(&mut text)` into a + `string`, compared exactly, with and without the time, the site and colour; + - **times:** always three places, as `.000` and `.450`, and a time before 1970. + Dates themselves are `std::time`'s, tested in `test/std/time.sakura`; + - **JSON:** each line read back with `json::parse`, including a message with quotes + and line breaks, and one that isn't UTF-8; + - **threads:** several threads logging at once into one sink, every record whole + and counted; + - **a sink that logs,** whose record is dropped rather than waited for. + + Each test runs in a copy of the program, so a floor or sink one sets is gone for + the next. +- **In the shared corpus, `test/programs`,** which holds both compilers to one output: + records to `io::output()` between `println`s, written in the order they were made, + and records to the standard error beside them, with the time left out. +- **Where they run:** in the VM under both compilers, as executables at `-O0` and + `-O2`, and with `run --checks`. Both compilers must check them with 0 notes and 0 + warnings. + +## Phases + +About 30 lines of `std::sys`, 450 of `std::log`, and 300 of tests, in both std trees, +and no change to either compiler. The sketch probed was 200 lines of code without its +documentation. Each phase ends with its tests passing under both compilers. + +1. **`sys::is_terminal` and `sys::allow_colour`,** for Linux and Windows on x86-64. + `sys::clock` is built. +2. **`std::log`:** levels, records, the floor, `sink`, `log::to` and its guard, the + lock, and the text sink, with the default sink over the standard error. +3. **The JSON sink.** +4. **A "Logging" part of the README's standard library section,** and `std::log` in + its table of modules, in both READMEs. + +## Later, where wanted + +- **Fields:** pairs of names and values that the JSON sink writes as members, as in + `log::info("served", log::field("path", p), log::field("ms", ms))`. +- **Named loggers,** one for each part of a program, each with its own floor. +- **The floor from the environment,** as `SAKURA_LOG=debug`, and `NO_COLOR`. + `process::variable` exists now, so this waits only on choosing the names. +- **Several sinks at once,** as a sink that writes to two others. +- **A sink on a thread of its own,** handed records through a `thread::channel`, so a + slow sink doesn't hold up the threads logging. It would copy each record's message, + since a record's views last only while it's written. +- **A sink to `syslog`,** or to the systemd journal. + +Durations and dates as types, with the time zone from the system, were on this list. +`std::time` has them now. + +## Decisions for you + +1. **Where it lives:** + - **(a) `std::log`, in `std/log/` (recommended).** Calls read as `log::info(...)`. + - **(b) `std::logging`.** It was to leave the name `log` free for a logarithm, but + `std::math` has `log` now, and it lives beside a module `log` in both compilers + (probed). So it's only a longer name. +2. **The logger:** + - **(a) One, shared, as `io::output()` is (recommended).** Any function can log + without being given anything. Threads logging at once wait on its lock for each + record written. + - **(b) Logger values given to what logs.** That's explicit and easy to test, and a + value one thread holds needs no lock, but every function that logs needs a + parameter. +3. **Messages below the floor:** + - **(a) Built anyway, with `log::enabled` for messages costly to build + (recommended).** Interpolating a few values costs little next to what a program + does between records. + - **(b) Also overloads taking a function that builds the message,** as + `log::debug(def() => describe(&plan))`. It's shorter at the call, and the + closure costs only its two words now, since closures refer to what they use + rather than own it. But the rebuild calls a lambda written in place ambiguous + between `debug(strview)` and `debug(def(): string)`, typed or not, where C + chooses the second (probed 2026-10-20). A function value named first works in + both. + - **(c) Records below a floor the build sets are removed while compiling.** That + needs a new `when` key, as `log >= debug`, and a compiler option to set it. +4. **How a sink is held:** + - **(a) As `io::writer_of` holds a stream, until its guard closes (recommended).** + `log::to` owns a sink given by value, and borrows one given as `&mut mine`. The + guard keeps a borrowed sink from outliving it, and closes an owned one, flushing + what it holds back. Both were probed. + - **(b) Owned until another is set, with no guard,** as `sys::handle` keeps a + handler in a `function` until another handles the signal. It's one call for the + whole run, but nothing puts the old sink back, and nothing closes the logger as + the program ends, so a sink holding records back loses them unless the program + flushes first. + - **(c) Borrowed only, until its guard closes,** as `log::to(&mut mine)`. This was + the recommendation of 2026-10-07, before std owned values of any type, as + `function` does. It makes a program declare its sink before the guard, or the + sink closes first. +5. **The time a record gives:** + - **(a) The wall clock, in UTC, written as RFC 3339 to the millisecond + (recommended).** + - **(b) The wall clock in the local zone, with its offset,** from + `timestamp::at(zone::local())`. That's what a person nearby reads, but records + from machines in other zones, or from either side of a change of the clocks, + don't sort as text. + - **(c) Time since the program started,** from the steady clock, as an + `instant`'s `elapsed()`. That's easier to read in a short run, but means nothing + next to another program's records. + - **(d) None unless a style asks for it.** diff --git a/docs/performance.md b/docs/performance.md new file mode 100644 index 00000000..02b4ae5f --- /dev/null +++ b/docs/performance.md @@ -0,0 +1,395 @@ +# Performance + +Where the two compilers started, where they are now, and where they need work: how fast +they check and build, how much memory they take, how large they and what they make are, +and how fast the code each makes runs. + +"Start" is the two compilers as committed on 2026-10-08: C at `62644a5` ("Close to +self-hosted") and the rebuild at `e5b7636`, its first commit. "Now" is both working +trees on 2026-10-20. Every comparison of start and now was measured on 2026-10-20, all +four compilers on one machine in the same hour. The probes of other programs are dated +where they're given. + +## How it was measured + +- **The machine:** an i5-13420H, on battery, which caps its performance cores at + 2.1 GHz. Wall times are about half what the same runs take plugged in, so they compare + with each other and not with older notes. Instructions and cycles are the processor's + own counts of the program's work outside the kernel, and don't depend on the clock. +- **Each run** was pinned to CPU 2, a performance core, the runs of a group taken in + turns: the best of 5 for builds, 9 for checks, 21 for a one-line program, 3 for the + VMs. Peak memory is the largest resident size of any run. +- **The rebuild compiles on one thread here (`-j 1`),** as the start compilers and C do. + [Threads](#threads) gives what its default of up to eight does. +- **The compilers:** + - C, built by gcc with `-O3 -g`, by hand as chinook would; + - the rebuild, its own fixed point at `-O2`. "C-built" is the rebuild as C builds it, + the same program from other code. +- **The work:** each compiler checking and building the rebuild's sources of its day, as + the rebuild builds itself (`entry.sakura analyzer compiler machine native`, and + `server` now), against the rebuild's std. Those grew, so each result is also given per + 1,000 lines of what was read: + + | | Start | Now | | + |---|---|---|---| + | The rebuild's sources | 49,307 lines, 112 files | 76,816 lines, 160 files | +56% | + | std | 21,892 lines | 40,241 lines | +84% | + | All read, per build or check | 71,199 lines | 117,057 lines | +64% | + | C's own sources | 57,444 lines of C | 67,674 lines of C | +18% | + +## At a glance + +| | Rebuild, start | Rebuild, now | C, start | C, now | +|---|---|---|---|---| +| Building the rebuild | 1.78 s | 3.38 s | 1.71 s | 5.80 s | +| · instructions per 1,000 lines | 121M | 131M (+8%) | 103M | 213M (+106%) | +| · peak memory | 132 MB | 229 MB | 176 MB | 397 MB | +| Checking the rebuild | 0.256 s | 0.353 s | 0.259 s | 0.623 s | +| · instructions per 1,000 lines | 19.0M | 16.0M (−16%) | 13.0M | 18.2M (+40%) | +| · peak memory | 42 MB | 74 MB | 127 MB | 327 MB | +| Checking a one-line program | 0.061 s | 0.093 s | 0.066 s | 0.163 s | +| · instructions per 1,000 lines of std | 13.7M | 11.2M (−18%) | 10.0M | 13.2M (+32%) | +| · peak memory | 15 MB | 27 MB | 45 MB | 112 MB | +| The compiler's executable | 11.6 MB | 8.7 MB | 5.5 MB, 1.2 MB stripped | 6.3 MB, 1.4 MB stripped | +| A program printing a line | 274 KB | 155 KB | 588 KB | 739 KB | +| The rebuild as each builds it, building itself | 8.63G instructions | 15.39G | 10.57G (1.22×) | 29.84G (1.94×) | + +What it says: +- **The rebuild held its cost per line** while what it reads grew by two thirds: + checking costs less a line than it did, and building 8% more, which the 2026-10-18 + optimizer passes cost and pay back in the code they make. +- **C's cost per line doubled for a build** and grew 40% for a check, and its memory more + than doubled. It was level with the rebuild at the start, and is now 1.7 times its time + to build, 1.8 times to check, and 1.7 to 4.4 times its memory. +- **The code C makes has fallen behind:** the same program built by C ran 1.22 times + the instructions the rebuild's build of it did at the start, and 1.94 times now. The + rebuild gained the optimizer and back end work of 2026-10-08 to 10-18, and C only part + of it. + +## Speed + +Building and checking, each compiler on the sources of its day, at 2.1 GHz: + +| | Rebuild, start | Rebuild, now | C, start | C, now | +|---|---|---|---|---| +| Building: wall time, best | 1.778 s | 3.375 s | 1.710 s | 5.803 s | +| · median | 1.787 s | 3.388 s | 1.720 s | 5.823 s | +| · instructions | 8.63G | 15.39G | 7.36G | 24.91G | +| · cycles | 3.49G | 6.44G | 3.40G | 11.75G | +| Checking: wall time, best | 0.256 s | 0.353 s | 0.259 s | 0.623 s | +| · instructions | 1.36G | 1.88G | 0.93G | 2.13G | +| · cycles | 0.49G | 0.65G | 0.43G | 1.04G | +| A one-line program: wall time, best | 0.061 s | 0.093 s | 0.066 s | 0.163 s | +| · instructions | 300M | 451M | 219M | 532M | + +Every program is checked with the whole of std, so the one-line program is what std +costs each check: about 2.3 ms for each 1,000 lines in the rebuild now, and 4.1 ms in C, +at this clock. Generic code costs two to three times what plain code does, mostly in +C's instances (`checker__clone`), as `std/simd.sakura` measured on 2026-10-14. + +### The code each makes + +The same program, the rebuild's compiler, built by each compiler and then building the +same sources: + +| | Start | Now | +|---|---|---| +| Built by the rebuild | 1.778 s, 8.63G instructions | 3.375 s, 15.39G | +| Built by C | 2.154 s, 10.57G | 5.593 s, 29.84G | +| C's code against the rebuild's | 1.21× the time, 1.22× the instructions | 1.66×, 1.94× | + +Other programs, from the plans' probes, at `-O2`. These were measured as each plan was +built or brought up to date, on a busy machine, so the ratios are surer than the times: + +| What | Rebuild | C | C against the rebuild | Measured | +|---|---|---|---|---| +| `f32` `a * b + c`, scalar | 87.9 ms | 110.7 ms | 1.3× | 10-20 | +| The same, `f32x8` | 5.9 ms | 78.8 ms | 13× | 10-20 | +| Finding a byte, `u8x16` | 1.78 ms | 42.9 ms | 24× | 10-20 | +| `index_of`, a byte at the end of 1 MiB | 62 µs | 698 µs | 11× | 10-20 | +| `is_ascii` of 1 MiB | 62 µs | 86 µs | 1.4× | 10-20 | +| Vectors of three `f32`s, by operators | 166 ms | 417 ms | 2.5× | 10-20 | +| Random draws, 64 bits | 2.5 ns | 5.8 ns | 2.3× | 10-20 | +| A call through a function value | 2.72 ns | 4.61 ns | 1.7× | 10-20 | +| A generic `F`, inlined | 0.48 ns | 1.79 ns | 3.7× | 10-20 | +| A call through a `function` | 2.86 ns | 4.56 ns | 1.6× | 10-20 | +| A list of 1,000,000 `box`es, ten times | 539 ms | 675 ms | 1.25× | 10-19 | +| The same through `raw_allocate` | 414 ms | 563 ms | 1.36× | 10-19 | +| The same in a `pool` | 209 ms | 136 ms | 0.65× | 10-19 | +| Three relaxed atomics | 0.1 ns | 7.4 ns | 74× | 10-20 | +| Building a `u32[16000]` constant | 0.15 s | 5.77 s | 38× | 10-20 | + +What makes the difference: +- **Vectors in registers.** The rebuild's `-O2` holds `simd` values in registers and + picks AVX2 or SSE2 as the program runs. C lowers `lanes_held()` to `false`, so its + vectors and std's text functions go through memory or a word at a time. +- **What the rebuild's optimizer takes out:** checks of a view's data, indexes checked + again, bounds in counted loops, work on constants moved out of loops, small branches + as `cmov`, the stack's limit in small leaf functions, and the order of an atomic known + while compiling. +- **C's optimizer is quadratic** in a constant array's length. +- **C is ahead in one place:** a `pool`, 136 ms against 209. + +### The VMs + +Each compiler running the rebuild's compiler on its VM, which then checks a one-line +program. The time includes checking and lowering the compiler for the VM: + +| | Start | Now | +|---|---|---| +| The rebuild's VM | 2.69 s, 17.8G instructions, 122 MB | 5.00 s, 29.2G, 244 MB | +| C's VM | 1.99 s, 8.1G, 167 MB | 6.32 s, 27.7G, 403 MB | + +The rebuild's VM was a third slower than C's at the start, and is a fifth faster now. On +small calls it's still slower: a call through a function value takes 81.8 ns in the +rebuild's VM and 41.6 ns in C's, and an inlined generic call 24.5 ns and 10.8 ns. + +### Compiled code in the machine + +Since 2026-10-28 the machine compiles each function to x86-64 as it is first called, where +it runs as a Windows executable (`machine/jit.sakura`). Measured on a Ryzen 9 9950X3D, +plugged in, each benchmark a function of its own called through a value, so none is +inlined into another; `run --fast` against `build -O2`, the checksums alike: + +| Work | Built | Interpreted | Compiled by the machine | Compiled ÷ built | +|---|---|---|---|---| +| Multiplies and shifts mixing a word, 20M times | 9.4 ms | 93.6 ms | 9.1 ms | 0.97 | +| `fib(30)`, calls | 2.5 ms | 50.1 ms | 3.8 ms | 1.5 | +| 10,000 particles of `f32`, 300 steps | 5.5 ms | 148 ms | 19.8 ms | 3.6 | +| Methods of a struct of three `f32`s | 10.8 ms | 121 ms | 24.1 ms | 2.2 | +| A sieve of 20M bytes | 30.5 ms | 246 ms | 37.9 ms | 1.2 | +| A `dict` of 200,000, then 1M lookups | 26.0 ms | 102 ms | 26.3 ms | 1.0 | +| Sorting 1M words | 68.9 ms | 444 ms | 78.7 ms | 1.1 | +| Interpolating 200,000 texts | 13.5 ms | 33.4 ms | 36.4 ms | 2.7 | + +hearth's scripts, 2,000 entities each running a behavior (`hearth.scripting.bench`, run as +its executable): an `update` turning its transform took 311 ns an entity interpreted and +121 ns compiled, against 27 ns as a system of the program's own. + +Where it falls short of built code: +- **Words, not values.** The machine's code holds values in words of the frame shared by + values whose lives don't overlap, an `f32` and an `f64` alike, and compiled code keeps a + word a single only where every value in it is one. Splitting each word into the values + it holds, by liveness, would let `f32` arithmetic stay single throughout. +- **What the bytecode reloads.** A vector's data pointer is read from its cell each time + round a loop, which built code moves out of the loop. +- **Formatting** calls the machine's own code for each part of a text. +- **A function inlining many loops** shares its registers among the words its loops use + most: all eight benchmarks inlined into one `main` ran mix in 18.6 ms, not 9.1. + +### Threads + +The rebuild compiles on threads, one for each processor up to eight. Unpinned, on this +machine's twelve: + +| | `-j 1` | Default | | +|---|---|---|---| +| Building the rebuild | 3.34 s, 226 MB | 1.97 s, 257 MB | 1.70× | +| Checking it | 0.353 s | 0.301 s | 1.17× | + +Reading files, optimizing, and placing values run on threads. Checking, lowering, and +choosing code are one thread's. C compiles on one. + +## Memory + +Peak resident memory: + +| | Rebuild, start | Rebuild, now | C, start | C, now | +|---|---|---|---|---| +| Building the rebuild | 132 MB | 229 MB | 176 MB | 397 MB | +| · per 1,000 lines | 1.85 MB | 1.96 MB | 2.47 MB | 3.39 MB | +| Checking the rebuild | 42 MB | 74 MB | 127 MB | 327 MB | +| · per 1,000 lines | 0.59 MB | 0.63 MB | 1.78 MB | 2.79 MB | +| Checking a one-line program | 15 MB | 27 MB | 45 MB | 112 MB | + +The rebuild's memory grew as what it reads did, 6% to 7% more a line. C's grew 37% to +57% more a line, and a check by C takes 4.4 times the rebuild's memory. + +The rebuild has no collector since 2026-10-19, nor does C's runtime. Programs hold what +they allocate in owners, arenas and pools, and each thread keeps a cache of free blocks. + +## Size + +### The compilers + +| | Rebuild, start | Rebuild, now | C, start | C, now | +|---|---|---|---|---| +| Executable | 11,570,800 bytes | 8,730,512 | 5,504,368 | 6,337,928 | +| · code | 2.52 MB | 3.01 MB | 1.03 MB | 1.20 MB | +| · constant data | 0.60 MB | 1.02 MB | 0.07 MB | 0.08 MB | +| · line tables, or debugging information | 8.28 MB | 4.63 MB | 4.3 MB | 4.9 MB | +| The rebuild as C builds it | 17,064,568 bytes | 27,417,928 | | | +| · its code | 4.62 MB | 6.70 MB | | | + +The rebuild's executable carries its line tables, which fault traces read, as 53% of it. +C's carries DWARF from `-g`, and is 1.4 MB stripped. The rebuild's code is 2.5 times C's, +for a program 14% larger than C's in lines, with std's code in it too. As C builds the +rebuild, its code is 2.2 times what the rebuild makes of the same sources. + +### What they make + +A program printing a line, at `-O2`: + +| | Rebuild, start | Rebuild, now | C, start | C, now | +|---|---|---|---|---| +| Executable | 273,512 bytes | 154,856 | 588,032 | 738,760 | +| · code | 36,046 | 35,618 | 78,276 | 119,713 | +| · constant data | 24,128 | 30,616 | 199,048 | 251,784 | +| · line tables | 203,032 | 74,296 | 248,472 | 271,200 | + +The rebuild's 2026-10-18 optimizer drops every function nothing reaches, with its code, +lines and symbols. C's code for the same program is 3.4 times as large. + +## Where a build goes now + +Each compiler building the rebuild's sources of now, profiled with callgrind: the +rebuild on one thread, built with `-g`, 15.8G instructions in all; C, 25.8G. Shares are +of instructions, inclusive of what each phase calls: + +| Phase | Rebuild | C | +|---|---|---| +| Reading the files: lexing and parsing | 3.0% | about 2% | +| Checking | 7.9% | 6.3% | +| Evaluating constants | 0.9% | | +| Lowering, less what follows | 14.8% | about 1% | +| Working out what calls keep | 1.4%, within the rows around it | 43.9% | +| Optimizing, inlining included | 56.5% | 24.6% | +| Choosing code and placing values | 14.8% | 20.3% | +| Writing the executable, closing what's left | about 1% | about 1% | + +**C spends 44% of a build working out what each call keeps** (`compiler__find_boxes`, +through `compiler__keeps`, `compiler__scan_body` and `compiler__receives`), which the +rebuild does in 1.4%. C scans functions that call one another by assuming what each +keeps and scanning again until that stops growing, and what it found within such a cycle +is forgotten each time an enclosing one is scanned again. The compiler's checker and +emitter are large cycles of recursive functions, so their scans repeat. The rebuild has +worked out each group of recursive functions once, as one, since 2026-10-18. That is +most of why C's cost per line doubled since the start: about 11 of its 26 billion +instructions. + +**In the rebuild, optimizing is over half of a build,** and no pass stands out: the +optimizer's files take 23% of the instructions by themselves, and the code they walk and +edit (`compiler/intermediate/`) another 14%. Spread through every phase: +- **indexing vectors** (`vector::at`) is 13% of all instructions, and appending 4%. The + checks on them are about 3% of a build, as the checks plan measured; +- **`dict`** is 2.8%, `memset` and `memcpy` 3.5%, and the heap 1.8%; +- **the checker's own lifetime warnings** are 1.8%. + +## Where work is needed + +In order of what each would gain. + +1. **What calls keep, in C.** It's 44% of C's build, against 1.4% of the rebuild's. + Working each function out once, and recursive ones as a group, as the rebuild does, + would take about 40% off C's builds. C's checking costs 1.4 times a line what it did + too, and its memory 1.4 to 1.6 times a line. See + [Where a build goes now](#where-a-build-goes-now). +2. **The code C makes.** The rebuild's optimizer of 2026-10-14 to 10-18 has no C + counterpart: vectors in registers, check removal, `select`, moving work out of loops, + dropping what nothing reaches, and the orders of atomics. C's executables run 1.94 + times the instructions, with 2.2 to 3.4 times the code. C's frames copy a word at + a time, which keeps its AVX code slower than its SSE2 code. +3. **Optimizing in the rebuild.** It's 56% of a build, and the 2026-10-18 passes cost 13% + of a build for code 10.5% faster. No pass stands out; what the passes walk and index + does, as `vector::at` at 13% of all instructions. Code held in fewer, denser arrays, + or walked without an index checked at each step, would serve every pass. +4. **The rebuild's threads.** Eight give 1.7 times one. Checking, lowering and choosing + code run on one thread, which caps what more processors give. +5. **std's cost to every check.** Before the std plan, a one-line program cost a check + of 40,241 lines of std: 93 ms and 27 MB in the rebuild at this clock, 163 ms and + 112 MB in C. The std plan, built on 2026-10-20, made `core`, a library of the + language's own that every program reads, and reads std's modules only where a program + refers to them. In the rebuild an empty `main` now checks in 21.4 ms and 7.3 MB, and a + program printing a line in 42.2 ms and 11.0 MB, since `std::io` still reads std's + root. The plan had probed 30.1 ms for it. What's read still costs about 2.3 ms each + 1,000 lines, and two to three times that for generic code. +6. **Line tables,** 53% of the rebuild's executable and 48% of a small program's. +7. **The rebuild's VM on calls,** at twice C's VM's time for small calls. +8. **Smaller costs that programs meet** ([later.md](later.md)): + - reading the clock on Linux is a system call, 211 ns, where the vDSO takes 25; + - lambdas given to adapters cost 3 to 4 times functors; + - `box` is 1.31 to 1.38 times `raw_allocate`. + +## How it got here + +Each step as it was measured then, on the machine and clock of its day. + +| Date | What | Measured | +|---|---|---| +| 10-05 | The rebuild's analyzer, built by C | Checking 23,574 lines: 0.09 s, 19 MB, 495M instructions; C's checker 0.11 s, 54 MB, 363M | +| 10-08 | The scratch arena | The rebuild compiling itself: 5.34G to 4.84G instructions, 100 MB to 89 MB | +| 10-08 | First self-build | 15.4G instructions, about 3 s; then 8.37G, 1.65 s, 129 MB, an 11.3 MB executable; C 7.72G, 2.01 s, 175 MB | +| 10-08 | The back end's remaining work | Code 2,644,785 to 2,517,459 bytes; building 9.42G to 8.96G | +| 10-14 | Simplifying and speeding up | Building 11.10G to 8.31G, 2.20 s to 1.66 s; checking 0.31 s to 0.21 s; executable 14.4 MB to 6.8 MB | +| 10-14 | Vectors in registers | Building 8.61G to 7.99G; checking 1.36G to 1.27G; `f32x8` loop 21.6 ms to 8.7 ms | +| 10-16 | Compiling on threads | On 32 processors under load: building 838 ms to 564 ms on eight threads | +| 10-16 | One-word references, text by words | Building 8.37G to 7.85G, 171 MB to 166 MB; checking 1.355G to 1.302G | +| 10-18 | The optimizer's new passes | Code 10.5% faster; building the old sources 13% slower; executable 9.51 MB to 8.17 MB | +| 10-19 | Iterators | The fixed point 7.80 MB to 8.67 MB, from inlining `next` | +| 10-19 | Memory without a collector | A list of a million nodes, ten times: 3,046 ms collected in the plan's probe, 539 ms in `box`es released one by one as built; four threads allocating, 8.5 s to 0.29 s with caches | +| 10-20 | `std::function` and `void` | The fixed point 8,730,512 bytes | +| 10-20 | `core`, and std read as it's imported | Checking an empty `main` 93.1 ms to 21.4 ms, 27.7 MB to 7.3 MB; a program printing a line 93.3 ms to 42.2 ms; the compiler checking itself 352.5 ms to 338.6 ms, 72.4 MB to 54.0 MB | +| 10-20 | Contracts as statements | A contract that holds costs 0.11 ns more than a plain `if`, with the blocks that only stop the program laid out last; it was 5.7 ns as a call into std | +| 10-20 | Checks in checked programs only | One frozen copy built with `--checks` and without: building 3,523 ms to 3,372 ms (16.2G to 14.0G instructions), checking 350.8 ms to 323.5 ms, executable 9,209,216 to 8,732,296 bytes | +| 10-20 | The rules settled (roadmap step 5) | The compiler checking itself on one thread, step 4's checker against step 5's: 324.7 ms and 323.9 ms, no difference; the fixed point 8,770,256 bytes | +| 10-20 | Accessors with `this` and `value` implied (step 6) | Checking itself: 324.5 ms with step 5's checker on its form of the sources, 324.4 ms with step 6's; the fixed point 8,773,288 bytes | +| 10-28 | `f32` in single precision, instructions chosen by the processor, stores merged into vectors, spilling the value read furthest ahead, a loop's head that jumps through a table at a multiple of 64 | In cycles at this machine's low-power clock: `linear`'s `cross` 30 to 12, `quat * quat` 35 to 18, `normalized` 34 to 6; a loop of `vec3` 17 ms to 11 ms; the machine's loop 1,264M to 1,017M cycles, and no longer 1,180M when the code before it moves | + +What made the rebuild faster, in the order of what each saved: +- a build optimized every function twice (12% of building); +- dependencies recorded only for the language server, and results held per slot rather + than in dictionaries (13% of checking); +- what calls keep worked out, so receivers and locals stay off the heap: boxes made + while building itself fell from 4.7M to 30K; +- the scratch arena for each pass's temporaries; +- one-word references; +- the per-thread caches of blocks, and the blocks kept for reuse over 2 KiB; +- vectors in registers, and `memset`, `memcpy` and frames zeroed 16 bytes at a time; +- the lexer interning through an open table of hashes, finding punctuators by tables, + and skipping comment lines eight bytes at a time; +- line tables of 16-byte rows (10.2 MB to 3.0 MB then); +- leaving the checks of indexes and the rest to checked programs, and null and division + by zero to the processor's faults (4% of building, 8% of checking). + +Tried and dropped, so they needn't be tried again: +- an open-addressing `dict`, at loads of 3/4 and 1/2: 0.5–1.7% slower to check; +- inline limits of 20 and 24: checking 8–11% faster, building 1–4% slower, code 9–19% + larger; +- one arena for every function's code: more instructions and 122 MB; +- a radix sort for the register allocator, which ran more than the heap sort; +- another promotion pass late in the pipeline, which changed nothing; +- forwarding a call's result into the cell it's copied to, which saved nothing; +- waiting a while for the heap's lock before sleeping; +- a table of names for each file, which lexed every name again on each thread; +- compacting in the middle of the passes as well as at the end; +- inlining every function called once into callers of up to 6,000 instructions: 6% + more time; +- copying the test of `vector::close` into its callers: 400 KB more code; +- alias classes by type, which a reinterpreting cast would make wrong; +- words for trimming text, YAML's plain scalars, and the lexer's words and spacing, + each slower than bytes, as most runs are short; +- aligning every loop's head to 16 bytes, as functions are: the machine's loop took about + 10% more cycles, and no native loop gained. What its loop needed was the head that jumps + through the table of operations within one 64-byte line, which a 16-byte boundary + doesn't promise: such heads begin at a multiple of 64 since 2026-10-28. + +## Reproducing this + +The start compilers come from the commits: + +```sh +git -C malunal.sakura archive 62644a5 | tar -x -C c_start +git -C malunal.sakura.rebuild archive e5b7636 | tar -x -C r_start +# Build c_start's sources/*.c with the chinook dependencies, -std=c11 -O3 -g. +# Build r_start with it, then with that stage, to its fixed point: +c_start/sakura build --std r_start/std -O2 -o r_start_c ... +r_start_c build --std r_start/std -O2 -o r_start_s1 ... +``` + +`tools/profile/count.c` runs a command pinned to a processor and prints its wall time, +peak memory, instructions and cycles, and `tools/profile/measure.py` times each +compiler's work in turns through it. Its paths are at its top. `perf` isn't installed +here, and the counters need `perf_event_paranoid` at 2 or less. + +For where the time goes, build the compiler with `-g`, profile it with callgrind, and +read the profile with `tools/profile/costs.py`, as its header says. diff --git a/docs/random.md b/docs/random.md new file mode 100644 index 00000000..21aa46ae --- /dev/null +++ b/docs/random.md @@ -0,0 +1,469 @@ +# Plan: random numbers + +Written 2026-10-08, and brought up to date 2026-10-20 for what std has gained since: +ranges as values, `real` and `std::math`, threads and atomics, Windows, and checked runs +in place of the collector. This is a proposal. std is yours, so the decisions at the end +are yours to make. Nothing is built yet. + +**Comes after the ffi plan, now built:** `std::sys` is `system`, and `@foreign` and +`@link` are `extern` sections. + +**Built in the rebuild alone** ([roadmap.md](roadmap.md), decision 1). Where this plan +says both compilers, C's half is left out. What was measured in C stays as measured. + +**What it is:** generators of random numbers, numbers drawn from them in a range, +shuffling and picking, and the system's randomness for keys and seeds. + +**Its users:** +- games and simulations: dice, procedural worlds, and replays, which need the same + numbers from the same seed; +- tests whose inputs are made from a seed, so a failure can be repeated. std's own tests + of memory, vectors, words and threads each write a generator by hand today; +- programs with secrets: keys, tokens, and names nobody can guess; +- the algorithms plan ([algorithms.md](algorithms.md)), whose sorts are tested on random + orders, and which counts this plan's `shuffle` among the users of its `swap`; +- the grammars plan ([grammars.md](grammars.md)), whose tests make sentences and bytes + at random. + +**Probed:** on 2026-10-08, and again on 2026-10-20 against today's std, in the +scratchpad (`plans/random/`). Each part ran: +- with each compiler, in its machine and as executables at `-O0` and `-O2`; +- with the rebuild's `run --checks`; +- while compiling. + +The results agreed everywhere, except where noted. It covered: +- **The generator:** xoshiro256++ seeded through SplitMix64. Its first numbers for seed + 42, and those after a jump, matched a Python reference, including in a constant. A + generator was a constant too. +- **Numbers in a range** by Lemire's method, generic over every integer type through + `u64`. `i8` from −100 to 100 and the whole of `u64` matched the reference. 600,000 + draws from 0 to 5 each came within 0.3% of 100,000. +- **Ranges as values:** draws from `1..=6`, `-5..5` and a `range`. +- **Reals from 0 up to 1,** with `f32` ones made from their own 24 bits, the largest + being 0.99999994. Both compilers inferred the type from the declaration, and asked for + `fraction::<...>` where nothing gave it. +- **Shuffling** a vector of strings by swapping bytes, under `run --checks`. +- **The system's randomness:** 16 bytes from `getrandom`. Both compilers also built a + Windows executable calling `ProcessPrng`, which wasn't run. +- **Forking:** a page marked `MADV_WIPEONFORK`, where a forked child read 0 and its + parent read 12345. +- **Threads:** four threads, each handed a copy of one generator jumped between them, + summed the same in both compilers' machines and executables. +- **Speed in an `-O2` executable,** measured 2026-10-20 on a P-core, with bounds checked + as [How it fits the rules](#how-it-fits-the-rules) says. On 2026-10-08 the rebuild's + were 5.3, 11 and 5.4 ns. + + | A draw | Rebuild | C | + |---|---|---| + | 64 bits | 2.5 ns | 5.8 ns | + | A number below a bound | 6.8 ns | 12 ns | + | A real | 4.0 ns | 9.2 ns | + + In the machines, each draw took 76 to 250 ns. + +**Still so: a parameter taken by value draws from a copy.** Parameters belong to the +function, which may change them (README, "Functions"). So `def roll(g: generator)` can +call `g.next()`, and the caller's generator gives the same numbers again. Decision 5 +settles it for generators. + +**Found: `contract::expects` costs about 22 ns where it holds,** in either compiler's +`-O2` executables. A draw below a bound took 28.5 ns checked by it in the rebuild, +against 6.8 ns checked by a plain test and `sys::abort()`, and 33 to 36 ns against 12 ns +in C. Its default arguments, a `string` among them, are made at every call. + +**Found: C doesn't take a range's type from where the result goes.** `val b: u8 = +g.within(0..200)` draws a `u8` in the rebuild, while C makes `0..200` a `range` and +refuses it. Both take `g.within::(0..200)`, a `range` variable, and +`val b: u8 = g.below(200)`. + +## What's there now + +- **`hash` and `mix`** (`std/traits/hashable.sakura`), which scramble words but take no + seed. +- **No generator.** std's tests write their own: an xorshift in `test/std/mem.sakura`, + `simd.sakura` and `swar.sakura` and in the corpus's `simd_lanes_agree_everywhere_1`, + and a multiplying one in `test/std/threads.sakura`. +- **No system randomness, no shuffling, and no generic swap.** `sort` and `heap` move + elements' bytes themselves, and the algorithms plan proposes `swap`. +- **`std::sys`** has `syscall` and `fork` on Linux, but neither `getrandom` nor a way to + map memory; the runtime, `runtime`, maps its own. On Windows it calls the system's DLLs through + `@link`, and `fork` gives `unsupported`. +- **`real` and `integer`** (`std/traits`), which draws are bounded by. `std::math` has + `rotate_left` and the other integer operations, but no wide product. +- **Ranges are values:** `a..b` and `a..=b` make a `range` of integers + (`std/iterators/range.sakura`). +- **Threads and atomics:** `std::thread`, with `spawn_with`, `mutex` and `once`, and + `atomic` (`std/atomic.sakura`). Nothing gives a thread storage of its own. +- **Clocks:** `std::time`'s `instant::now()` and `timestamp::now()` read nanoseconds. Two + runs can read the same, and a clock is no secret, so seeds come from the system. +- **Constants** run any function, unless it reads a global variable, calls C, or turns + an address into a number (README, "Constants"). The rebuild runs a constant and stops + where it can't go on. C decides from the call graph, so it refuses anything that could + reach `contract::report` ([inconsistencies.md](inconsistencies.md), "Contracts in a + constant"). + +## What it needs + +1. **A fast generator** that gives the same numbers from the same seed, wherever it + runs, and in every version (decision 3). +2. **Integers in a range,** with no bias, of any integer type, given as a range (decision + 4). +3. **Reals** from 0 up to 1 and in a range, as `f32` and `f64`. +4. **Chances, shuffling and picking.** +5. **The system's randomness,** for secrets and seeds, on Linux and Windows. +6. **A generator ready to use with no setup,** seeded differently on each run, which + threads draw from at once (decision 6), and which a forked child doesn't share with + its parent (decision 7). +7. **Seeded generators in constants,** worked out while compiling, in both compilers. +8. **Portable above `std::sys`.** + +## How it fits the rules + +- **A generator is plain data (decision 5).** It's four words, so it copies freely, + compares through `equatable`, and can be a constant. Drawing takes `&mut this`, so + functions that draw take `&mut generator`. +- **The same numbers in the machine, in executables, and while compiling,** by + construction: + - the generator, and everything drawn from it, is integer arithmetic; + - reals are made from integers by conversions that are exact, so no rounding can + differ. + + It was probed in both compilers' machines and executables, under `run --checks`, and + in constants. +- **Nothing fails:** + - A bound of 0, or an empty range, stops the program, as indexing past an end does. + It's a plain test and `sys::abort()`, which reports where the program was, not + `contract::expects`. Through `contract`, C refuses every constant drawing in a range, + and such a draw takes three to four times as long (found above). + - The system's randomness doesn't fail on Linux 3.17 or later, nor on Windows, where + `ProcessPrng` never fails. Where it can't be had at all, the program stops, as Go + 1.24's `crypto/rand` does: no program should go on with keys it believes are + random. +- **Nothing allocates.** Shuffling swaps elements where they are. +- **Threads:** a generator belongs to whoever holds it, as any value does. Each thread is + handed its own, as `spawn_with` gives a value, and `jump` keeps their numbers apart. + The shared generator is drawn from by every thread at once (decision 6). +- **It isn't for secrets.** xoshiro256++'s state can be worked out from four of its + numbers, so keys and tokens come from `system_bytes`, as its documentation will say. +- **A build stays the same every time.** A seeded generator runs while compiling, in + both compilers. The system's randomness makes a system call, or calls C on Windows, + and the shared generator reads a global, so both compilers refuse a constant drawing + from either. Probed. + +## Layers + +### `std::sys` gains + +| Operation | Does | +|---|---| +| `getrandom(into: *mut u8, length: u64): i64` | Bytes from the system's generator, or the negated error number. Probed | +| `map_wiped(length: u64): *mut u8` | Zeroed memory of its own, which a forked child sees as zeros again, or null where the system can't. Probed. Decision 7 | + +- **On Linux:** + - `getrandom` (318 on x86-64); + - `mmap` (9), then `madvise` (28) with `MADV_WIPEONFORK` (18), from Linux 4.14. +- **On Windows:** `getrandom` is `ProcessPrng`, from `bcryptprimitives.dll`, as Go and + Rust use, linked as `std::sys` links `kernel32.dll`. Both compilers built an + executable calling it. There are no forks to guard against, so `map_wiped` is plain + zeroed memory. +- Both join the operations `std/system/system.sakura` lists for each system. + +### `std::random` (decision 1) + +```sakura +module std::random; + +#! A generator of random numbers, xoshiro256++ (decision 2), in four words. One made +#! from a seed gives the same numbers every time (decision 3). +pub struct generator : equatable { var _s: u64[4]; } + +pub def generator::seeded(seed: u64): generator; # SplitMix64 spreads the seed +pub def generator::from_system(): generator; # 32 bytes from the system +pub def generator::next(&mut this): u64; # 64 bits +pub def generator::equals(&this, other: &generator): bool; + +#! From 0 up to a bound, not including it. +pub def generator::below(&mut this, bound: T): T where T: integer; +#! From a range: `a..b` leaves its end out, and `a..=b` takes it in (decision 4). +pub def generator::within(&mut this, among: range): T where T: integer; +#! From 0 up to 1, not including 1. +pub def generator::fraction(&mut this): T where T: real; +#! From low up to high, not including high. +pub def generator::between(&mut this, low: T, high: T): T where T: real; +pub def generator::chance(&mut this, probability: f64): bool; +pub def generator::fill(&mut this, into: slice): void; +pub def generator::shuffle(&mut this, items: slice): void; +pub def generator::pick(&mut this, items: span): maybe<&T>; # none where empty +pub def generator::jump(&mut this): void; # 2^128 numbers ahead + +# The shared generator, seeded from the system when first drawn from, which every +# thread may draw from at once (decision 6). +pub def below(bound: T): T where T: integer; +pub def within(among: range): T where T: integer; +pub def fraction(): T where T: real; +pub def between(low: T, high: T): T where T: real; +pub def chance(probability: f64): bool; +pub def shuffle(items: slice): void; +pub def pick(items: span): maybe<&T>; + +# The system's randomness, for keys, tokens and seeds. +pub def system_bytes(into: slice): void; +pub def system_word(): u64; +``` + +```sakura +import std; +import std::random; +import std::thread; + +val roll := random::within(1..=6); # the shared generator +random::shuffle(deck.slice()); + +# The same level from the same seed, every time. +var world := random::generator::seeded(level.seed); +for _ in 0..level.trees { + val x := world.below(level.width); + val y := world.below(level.height); + val height: f32 = world.between(2.0, 9.0); + plant(x, y, height); +} + +# A generator for each thread, from one seed, whose numbers never overlap. +var source := random::generator::seeded(run.seed); +var workers := vector::>::new(); +for _ in 0..thread::cpu_count() { + var started := thread::spawn_with(simulate, source) else (e) { return; }; + workers.append(move(started)); + source.jump(); +} + +var key: u8[32]; +random::system_bytes(key[:]); # a secret +``` + +## How each part works + +- **The generator (decision 2):** xoshiro256++, by Blackman and Vigna. + - Its four words change by adding, shifting, rotating and xor, with no + multiplication, so it's quick in the machine too. It writes its rotations as two + shifts, since `math::rotate_left` takes any width, and so a remainder and a branch. + - Its period is 2^256 − 1, and it passes BigCrush and PractRand. + - Its reference code is public domain. It's Julia's default generator, and Rust's + `SmallRng` on 64-bit processors. +- **Seeding:** + - `seeded` fills the four words from SplitMix64 run from the seed, as the authors + advise. Nearby seeds then give unrelated numbers. + - The state is never all zeros, xoshiro's one forbidden state, since at most one of + SplitMix64's four words can be zero. + - `from_system` takes 32 bytes from the system, and takes them again if all were + zero. +- **Integers in a range:** Lemire's method (2019). + - A 64-bit number is multiplied by the count of numbers in the range, and the high + word of the 128-bit product is the result. + - A number is drawn again only when the low word falls below 2^64 mod the count. + That happens with a chance below the count divided by 2^64, and the division that + works it out happens only then. + - **Every integer type goes through `u64`.** `end as u64 - start as u64` wraps to the + right count for signed types too, so nothing asks whether a type is signed. A range + covering all of `u64` or `i64` takes a number as it is. Probed. + - **A range** counts `end − start` numbers, and one more where it takes its end in, as + `a..=b` does. Probed with both. + - **The 128-bit product** is made of four 32-bit products today. A 64-bit `mul` gives + both halves in one instruction, but `std::math` gave no wide product among its + integer operations, and there are no 128-bit integers ([later.md](later.md), + "128-bit integers"). An intrinsic for its high word would cut most of the 4 ns a + draw in a range adds to `next`, and give the same bits. +- **Reals:** + - An `f64` is the top 53 bits times 2^−53, and an `f32` is the top 24 bits times + 2^−24. The values are evenly spaced and never reach 1. + - Each width has its own because `fraction::() as f32` can round up to 1.0. + `if const size_of::() == 4` chooses between them in both compilers, where C + refuses `T is f32` ([inconsistencies.md](inconsistencies.md), "Testing a type + against another type"). + - **The type comes from where the result goes,** as `val x: f32 = g.fraction();`. + With nothing to say, both compilers ask for `fraction::<...>()`. Probed. + - **The bound is `real`,** which std has had since 2026-10-14. + - **`between`** gives low + (high − low) × a fraction. In the rare case where rounding + reaches high, it draws again. It takes two ends, since a `range` holds integers. +- **`chance(p)`** is a fraction below `p`: never at 0, always at 1, and exactly the top + bit at 0.5. +- **`shuffle`** is Fisher–Yates from the end, swapping elements' bytes. An element is + moved, never copied, so strings and other owning values shuffle safely. Probed under + `run --checks`. It uses the algorithms plan's `swap` if that's built first, and + otherwise swaps bytes itself, as `heap` does. +- **`pick`** takes the element at `below(length)`, or none where there are none. A + `maybe<&T>` is one word. +- **`fill`** writes each number's 8 bytes from the lowest, so a seed gives the same bytes + on every processor. +- **`jump`** is the authors' jump, 2^128 numbers ahead. A generator jumped once for each + thread, and handed to it by `spawn_with`, gives every thread numbers from one seed that + never overlap. Probed. +- **The shared generator (decision 6):** + - Its state is kept in memory from `sys::map_wiped`, mapped and seeded from the + system the first time it's drawn from. A program that never draws from it pays + nothing. Threads that race to map it agree through `compare_exchange`, and the one + that loses gives its page back. + - **Threads draw from it at once.** Under 6(a) it's SplitMix64 over one `atomic` + counter: each draw is one `fetch_add` and a mix. No thread waits, and since the mix + gives each count its own number, no two draws are the same. Alone, a draw took + 14 ns in the rebuild's executables and 18 ns in C's. With four threads drawing at + once in the rebuild's, 40 million draws took 27 ns each by the clock, where + xoshiro256++ behind a lock took 370 to 400 ns. + - **The draws are written once,** generic over where their words come from, so + `random::within` and `world.within` count a range alike. + - **A forked child** finds it zeroed and seeds its own (decision 7), whatever forked: + `sys::fork`, `process::command`'s child before it runs the new program, or C code a + program calls. +- **The system's randomness:** + - `getrandom` with no flags waits only at boot, until the kernel's pool is first + ready. + - A read of up to 256 bytes is never cut short, longer ones are read in a loop, and an + interrupted call is made again. + - Before Linux 3.17, the call is missing, so `/dev/urandom` is read instead. Where + neither works, the program stops. + - On Windows, `ProcessPrng` fills any length in one call. + +## Testing + +- **`test/std/random.sakura`, written with `std::testing`,** in both repositories, + covers: + - **known answers:** xoshiro256++, its jump, and SplitMix64, checked against the + authors' C code, which is run once in the scratchpad; + - **ranges at each width's edges:** all of `i8` and of `u64`, `a..b` and `a..=b`, and + the bounds 1 and 2^63 + 1, which is the worst for drawing again. A bound of 0, or an + empty range, stops a forked copy, on Linux; + - **evenness:** + - chi-squared over a small bound and a large one; + - the mean of reals; + - never 1, for `f32` and `f64`. + + Every check uses a fixed seed, so none can fail by chance; + - **shuffling:** every order of 4 elements appearing about equally, strings, and + runs of none and one; + - **`pick`** of nothing giving none; + - **the system:** two reads differing, and, on Linux, a forked child's shared numbers + differing from its parent's; + - **threads:** four drawing from the shared generator at once, with no number given + twice under 6(a); + - **while compiling:** + - a constant from a seeded generator, drawing in a range and shuffling, equalling + what running gives, in both compilers; + - a constant from the system or the shared generator being refused, in both + compilers' tests. +- **Where they run:** in each compiler's machine, as executables at `-O0` and `-O2`, and + with `run --checks`. They're also built for `windows-x86_64`. The C compiler must + still accept std, since it builds the rebuild. + +## Phases + +About 50 lines of `std::sys`, for Linux and Windows, 600 of `std::random`, and 400 of +tests, with no change to either compiler. + +1. **`sys::getrandom`, and the generator:** + - `seeded`, `from_system` and `next`; + - `below`, `within`, `fraction`, `chance` and `fill`; + - also `system_bytes` and `system_word`. +2. **`between`, `shuffle`, `pick` and `jump`.** +3. **`sys::map_wiped`,** with the shared generator and its functions. +4. **The README:** a `std::random` row in its table of modules, and a paragraph with an + example under "The standard library", as `std::time` and `std::math` have. +5. **std's tests moved onto it:** `mem`, `simd`, `swar` and `threads` drop the + generators they write by hand. The corpus's `simd_lanes_agree_everywhere_1` keeps + its own, since its expected output is made of its numbers. +6. **Distributions,** if decision 8 is (a): + - normal, by the ziggurat method, with its tables made while compiling. A table of + `math::exp` and `math::log` in a constant agreed in both compilers; + - exponential, Poisson and binomial; + - picks by weight, by the alias method. + +## Later, where wanted + +- **Samples:** k different elements out of n. +- **An iterator of draws,** as `world.draws(1..=6).take(10).to_vector()`, for the + adapters and consumers every iterator has. +- **A wide product,** as an intrinsic among `std::math`'s integer operations, or + 128-bit integers, for Lemire's method and for hashing. +- **A generator per thread behind the free functions,** in place of the atomic counter, + once threads have storage of their own ([later.md](later.md), "Thread-local + variables"). A draw would then cost what `next` does, with nothing shared. +- **Text:** tokens, and version 4 UUIDs. +- **Seeding `dict`'s hashes on each run,** against inputs crafted to collide. Its + entries keep their places as it grows, so the order it gives them in wouldn't change. +- **A strong generator in the program,** such as ChaCha, for a program that draws secrets + too often for a system call each. `std::simd`'s `u32x4` and `u32x8` would work four or + eight of its blocks at once in the rebuild's executables. +- **macOS,** once `std::sys` has it. + +## Decisions for you + +1. **Where it lives:** + - **(a) `std::random`, in `std/random/` (recommended),** as `std::time`, + `std::math` and `std::thread` are modules of their own. + - **(b) In module `std`.** Names such as `generator`, `below` and `shuffle` would + then be taken in every program that imports `std`. +2. **The generator:** + - **(a) xoshiro256++ (recommended).** + - It's 32 bytes and 2.5 ns here (5.8 ns in C's executables), with no + multiplication, so it's also quick in the machine. + - `jump` gives each thread its own numbers. + - It isn't for secrets, which is why the system's randomness is separate. + - **(b) PCG64 DXSM,** a variant of NumPy's default, PCG64. Each step multiplies + 128-bit numbers. Without 128-bit integers, that takes several of the four-multiply + products, so it's slower here and much slower in the machine. + - **(c) ChaCha8,** Go 1.22's default. Its numbers can't be predicted, so a program + that wrongly makes tokens from it is still safe. But it keeps 64 bytes of state and + a buffer, and it's many times slower per number in the machines, which work vector + lanes one at a time. `std::simd` would speed it only in the rebuild's executables. +3. **Numbers from a seed:** + - **(a) The same in every version of std (recommended).** This covers the generator + and every method drawing from it, for replays, saved worlds, and tests with seeds. + The methods' algorithms then belong to the contract: Lemire's, 53 bits, and + Fisher–Yates from the end. A faster way later needs a new name. + - **(b) Only `next` stays the same.** Ranges, reals and shuffling may change between + versions, as Rust's `rand` allows for `StdRng`. +4. **How a range is given:** + - **(a) As a `range` (recommended),** as `within(1..=6)` and `within(0..n)`. `..` + and `..=` say whether the end is in, as they do in `for`, so one name serves both. + `below(n)` stays, for indexes. C needs a range of a narrow type written as one, as + `within::(0..200)`, until it takes the type from the declaration (found + above). + - **(b) Two ends, both included,** as `within(1, 6)`, as this plan first had it. It + reads the same in both compilers, but a range leaving its end out is + `within(0, n - 1)`. +5. **Copying a generator:** + - **(a) Plain data, copying freely (recommended).** + - A copy is a saved state to replay from. + - It can be a constant, and it can be held in structs and arrays without making + them close. + - But `roll(g)` draws from a copy, as noted above, so the documentation says to + take `&mut generator`. + - **(b) `owning`, with a `close` that does nothing, and `copyable`,** as `atomic` + is `owning` so that it isn't copied by accident. + - `roll(g)` is refused in both compilers, and copies are named, as `copy(&g)`, + which asks for `copy_of`. + - A constant still works through `copy(&kept)`. All three were probed again. + - But everything holding a generator then closes. +6. **The shared generator:** + - **(a) Yes, behind the free functions, as SplitMix64 over one atomic counter + (recommended).** `random::within(1..=6)` needs no setup, which is what most + programs want. It's seeded only when first drawn from. Threads draw from it at once + without waiting: 14 ns a draw alone, and 27 ns by the clock with four drawing at + once. Its numbers aren't xoshiro's, but nobody can seed it, so nothing can depend + on them. + - **(b) Yes, as xoshiro256++ behind a lock.** It's one generator throughout, and + 14 ns a draw alone, but 370 to 400 ns by the clock with four threads drawing at + once. + - **(c) Only generators a program makes.** There's no state in std, but every program + makes and passes its own. +7. **Forked children,** under 6(a) or 6(b): + - **(a) Its state in memory a forked child sees as zeros (recommended).** This + catches every fork, including C's, for one 4 KiB page, from Linux 4.14. `std::sys` + gains `map_wiped`. Windows can't fork, so there it's plain memory. + - **(b) A count of forks that `sys::fork` keeps, checked at each draw.** There's no + page, but forks made by C code are missed. + - **(c) Nothing.** A child repeats its parent's numbers, as the documentation would + say. +8. **Distributions:** + - **(a) The uniform ones first, and normal, exponential and the rest in phase 6 + (recommended).** `std::math`'s `exp` and `log`, which they waited on, are built. + - **(b) The uniform ones only.** Programs write their own. diff --git a/docs/roadmap.md b/docs/roadmap.md new file mode 100644 index 00000000..5fb2a7d8 --- /dev/null +++ b/docs/roadmap.md @@ -0,0 +1,741 @@ +# Roadmap: one compiler, and a language that holds + +Written 2026-10-20. The same day you chose the recommended answer to every decision at +the end, and steps 1 to 6 were built. Steps 1 and 2 are commit `5a6de39`, 3 and 4 +`c61f9cd`, and 5 `f9d3a2b`. Step 6 isn't committed. + +**What it is:** the way from today to a rebuild whose language stops changing under the +programs written in it, and with it the end of the C compiler. Eight steps: +1. `extern` and the `system` library (the ffi plan, built); +2. `core`, and a std read as it's imported (the std plan, built); +3. contracts in the language (the contracts plan, built); +4. what the checks do (the checks plan, built); +5. the rules the two compilers disagreed on, settled (built); +6. properties as C# writes them, with `this` and `value` implied (built); +7. lambdas that own what they use: the last change to the syntax; +8. the freeze. + +- **The C compiler gets only what it needs to build the rebuild,** as you said on + 2026-10-20. Decision 1 says whether that's nothing past today, or whatever each step's + std needs until the freeze. +- **Plans that only add come after the freeze:** [freestanding.md](freestanding.md), the + library plans, [blossom.md](blossom.md) (built on 2026-10-24, at your asking), and the + compilers' own speed (decision 5). +- **Each step is a plan here,** except: + - 5, 6 and 8, which are written out below; + - 7, which gets its own plan once you've chosen a direction (decisions 2 and 3). + +## What "stable" means + +From the freeze on, a program the rebuild accepts: +- is accepted by every later rebuild; +- means what it meant. + +So a change after the freeze can only add: +- modules, functions and types in std, `core` and `system`; +- attributes and intrinsics; +- warnings; +- words that mean something only where they stand, as `ensures` does at the start of a + statement; +- accepting what was refused. + +Adding a name can't break a program, since a program's own declaration hides a name of +`core`'s and a built-in type. A program's `struct u32` hides the built-in one today +(probed). + +Methods are the exception. `core` might later add a method to one of its own types with +the same name as one a program declared on that type. Step 5 settles that the program's +wins, as it does for names. + +Anything that would refuse a program, or change what one does, comes before the freeze +or not at all. **Where it's unclear, refuse:** accepting something later is an addition, +but refusing it later is a break. + +That sorts everything open today: + +| Before the freeze: it would break programs later | After, or whenever: it only adds | +|---|---| +| `@foreign`, `@link` and `std::sys` going (step 1) | freestanding.md: a target, attributes, `core::x86_64` | +| Which names a file sees, `core`'s root, the types the syntax makes (step 2) | The library plans: algorithms, benchmarks, grammars, linear, logging, random, tui | +| `std::contract` going, and what `ensures` does (step 3) | blossom.md | +| What `x[k]` checks, zero values, and `raw_allocate` no longer clearing (step 4) | `type_of(f)::name()`, thread-locals, 128-bit integers, documentation as an intrinsic | +| Three rules the rebuild gets wrong, two awaiting you, and which method wins (step 5) | Constants without a type, inferring through a reference, `==` of `maybe`, `equatable` for `void` | +| `m is nothing` and `(&mut x) as u64` refused; `+=` in place (decision 7) | Rules the rebuild refuses that could be accepted (step 5) | +| Properties with `this` and `value` implied, and the old forms refused (step 6) | A property of the type itself, marked, if one's wanted (decision 9) | +| How a lambda owns, and whether every lambda has a type of its own (step 7) | Warnings: lambdas returned through a call, handles outliving, reading a moved local | +| | `+` joining text, more operator traits, and the compilers' speed | + +**The freeze doesn't cover** (decision 4): +- std's modules and their names, which change as a library's do, std being a repository + of its own, versioned apart from the compiler, since 2026-10-26; +- the compiler's options, IR and messages; +- how an ordinary struct is laid out. An extern section's layout is promised, and so + will be freestanding.md's `@packed` and `@align`; +- the calling convention between Sakura functions; +- speed. + +## Where it stands + +**Probed** on 2026-10-20, with the repository's `sakura-v1.0.0`, built from the working +tree that morning: +- **The language has 30 keywords.** The plans add one, `extern`, which nothing in std, + the compiler, its tests or its tools uses as a name. Every other word they add means + something only where it stands: + - `expects`, `asserts`, `ensures` and `old`, from step 3. std has + `contract::expects` and `contract::asserts` today. + - `undefined`, from step 4. It has to stay that way, since the rebuild's checker + names an error kind `ec::undefined`. + - `none` as an `os`, from freestanding.md, inside a `when`. +- **What each plan changes for programs:** + + | Plan | The grammar | What else programs see | + |---|---|---| + | Step 1, ffi | `extern import`, `extern module ... when`. `@foreign` and `@link` go | `std::sys` is `system` | + | Step 2, std | Nothing | Which names a file sees (decisions 4–6 and 8). The eight types the syntax makes, held by the compiler. A module's files found by its path (decision 3) | + | Step 3, contracts | `expects`, `asserts`, `ensures` statements, `old(e)`, `r:` | `std::contract` goes | + | Step 4, checks | `= undefined` | What `x[k]` checks (decision 1). Zero values (decision 4). `raw_allocate` stops clearing (decision 6) | + | freestanding.md | Nothing: attributes and a target | `@interrupt`, `@align`, `@packed`, `core::x86_64`, `os == none` | + | The seven library plans | Nothing: attributes std declares, and `keep` | std gains | + | blossom.md | Nothing | A tool beside the compiler | + +- **Lambdas:** there are about 340 in std, the compiler, its tests and its tools. Each + refers to the locals it uses, and none can own a value. + - std has eight functors: `function`, six adapters, and `carrying`. + `carrying` stands in for a lambda that owns what it's given: it's how + `spawn_with` works. + - The compiler's own sources start threads with `spawn_with` three times. + - 13 test files write a functor by hand. +- **Properties:** there are 183, in std (115), the compiler's own sources (38) and the + tests (30). Three are declared in traits. + - All 184 getters are `get(&this)`. + - All 15 setters are `set(&mut this, to)`. Four give `to` a type, always the + property's own. + - The only accessors that don't use `this` are one test's stub, `dot::width`. + - No property belongs to a type rather than a value, since accessors must take + `this`. What belongs to a type is one of 52 associated variables, as + `val permissions::owner_read := 0o400;`. +- **The rules the compilers disagree on:** inconsistencies.md's "Rules of the language" + lists 15. The rebuild was wrong about 3 of them, and 2 waited on your decision. Step 5 + settled all of them. + +## The steps + +| # | Step | Size, rebuild only, from each plan | Two-step bootstrap | +|---|---|---|---| +| 0 | C's last build (decision 1) | None | — | +| 1 | The ffi plan, all of it | About 300 lines; 4,100 moved | Yes. The attributes stay valid beside `extern` for one step (its decision 4) | +| 2 | The std plan, phases 1 to 5 and 7 | About 700 lines; 10,000 moved | Yes, for phases 2 and 3 | +| 3 | The contracts plan, all of it | About 400 lines | Yes, when std's `contract::` calls become statements | +| 4 | The checks plan, all of it | Not estimated in the plan; about 1,200 lines as built | Yes, as `core` gains `checking()` and `raw_allocate_zeroed` | +| 5 | The rules | Three fixes, a rule for methods, two decisions, three items from later.md; about 470 lines as built | None was needed: nothing std or the sources use was refused | +| 6 | Properties | Small: the parser and checker give accessors their parameters, and a script rewrites the 183; about 150 lines as built | Yes: a first stage from copies whose accessors are written as before (later.md) | +| 6½ | References and values, one rule | About 450 lines as built, and 130 places given `&` | Plain: today's sources build with `sakura-v1.0.0`, then with themselves | +| 7 | Lambdas that own what they use | Its own plan | Yes, when std's `spawn` starts taking them | +| 8 | The freeze | The README, a corpus, the bootstrap rule | — | + +**Steps 1 to 6 are built, and so is the rule for references and values between 6 and 7.** The plans of steps 1 to 4 were deleted once built, as +earlier plans were, and [later.md](later.md) holds what they left. Steps 5 and 6 have +their "As built" below. later.md's "The repository's compiler" says how step 5's compiler, which +`sakura-v1.0.0` is since it was rebuilt at 20:01, builds today's sources, and where the +chain from the seed has a gap. + +**The order:** +- **The ffi plan comes first,** as each plan says. +- **The std plan comes next.** Contracts fail through its `fault`, and every later step adds + to the std it lays out. +- **The checks plan follows the contracts plan.** Its decision 5 shrinks to the containers' faults + once contracts are statements. +- **Step 5 can run beside steps 2 to 4.** Its fixes are small, and only decisions 6 and + 7 hold it up. +- **Step 6 can come any time after step 1.** It's small and mechanical, and only + decisions 8 and 9 hold it up. +- **Step 7 is last,** as you asked. + +**The std plan's phase 6 is left until after the freeze.** That's the one moving +`std::regex`, `std::uri`, `std::version` and the formats. It's std's business, and +blossom fetches the packages. + +### 0. The C compiler's last build (decision 1) + +**Decided: (a), and done.** The seed is the rebuild's commit `420783d`, which your +working tree matched when step 1 began. Checked on 2026-10-20: +- C's working tree builds it; +- that stage builds it again, and that one builds it a third time, the same to the byte. + +C's working tree isn't committed, so commit it: the seed's builder should be a commit +too. + +**Under (a),** the seed is the last commit C builds. +- From then on, each stage is built by the one before. A step that changes what std or + the sources are written in leaves a commit that its successor is built from, as the + bootstraps since 10-09 have. +- `tools/bootstrap.sh` would walk that chain from C. Each link is a commit you make. + Until it exists, the notes in later.md's "The repository's compiler" are the recipe. +- The C repository stays as it is, with a README line saying what it builds. +- Nothing more is mirrored into its std. + +**Under (b),** C learns what the rebuild's own sources and the std they read use, on +Linux, and nothing else. That means no optimizer, Windows, language-server or +freestanding work: +- step 1: `extern` sections, and `system`'s new paths in its table of intrinsics; +- step 2: `core` found beside its executable, `core`'s names seen everywhere, the eight + types, and the rules of decisions 4 to 6. That's most of the std plan's half for C, since + the rebuild's sources read `core`; +- step 3: the statements parsed and left out, as `--contracts off` does; +- step 4: what std's code uses; +- step 6: properties' new form; +- step 7: lambdas that own, where std's `spawn` takes them. + +The freeze's commit is then the seed. + +### 5. The rules, settled + +When C stops, the rebuild's behavior becomes the language unless it's changed here. +inconsistencies.md's "Rules of the language": + +| Rule | What the rebuild does | Settled as | +|---|---|---| +| Redeclaring in the same scope | Takes it | Decision 6 | +| `&` of a union's owning field | Takes it | Decision 6 | +| `&mut` of a union's field | Takes it | Decision 6 | +| Returning an owning local into a union | Takes it, and closes it once | The rebuild's | +| A function ending in `while true` | Refuses it | The rebuild's, for now. Accepting one with no `break` is an addition | +| Type arguments given to overloads | Picks by the receiver | The rebuild's | +| Inferring from a lambda through overloads | Refuses it | The rebuild's, for now. Accepting is an addition, and step 7 removes `spawn_with`, the reason it was wanted | +| A range's type from where it goes | Takes the declared type | The rebuild's | +| A float constant where `T: numeric` | Takes it | The rebuild's | +| Comparing a `string` with a `strview` | Takes it, and answers wrong | **Fixed: refused,** as the README says | +| A property of type `void` | Takes it | **Fixed: refused,** as it was meant to be | +| A full path to a module not imported | Takes it | The rebuild's, by the std plan's decision 6 | +| A generic type's own variables | Takes the declaration, and reads it wrong | **Fixed: the declaration refused.** Making it work is an addition | +| A property as a value | Refuses it | The rebuild's. Accepting is an addition | +| `cfn` as a key | Not hashable | The rebuild's. Making it hashable is an addition | + +**A method a program declares on a type of `core`'s** wins over one `core` adds later +with the same name. That makes adding methods an addition. It sits beside the std plan's +decision 5, which says where such methods are seen. + +**A library's child sees its root's names without an import,** as it does today. You +decided this on 2026-10-20, the question the std plan had left open. Where the root's +code isn't there, that must be an error that's easy to catch. + +From later.md, decision 7 takes the items that would break programs if done later: +- **`m is nothing` refused.** It's never true of a `maybe`, so any program writing it + has a mistake. +- **`(&mut x) as u64` refused.** An integer conversion of a reference written `&x` or + `&mut x` gives the value, not the address. Converting to a pointer stays the way to + the address. +- **`+=` in place.** `x += y` calls the type's `add_assign`, where it has one, and is + `x = x + y` otherwise. Done after the freeze, it would start calling a method that a + program had named `add_assign` for its own reasons. + +**Set aside for good:** references that are never moved. Refusing a `var` reference +given another one would break programs walking a chain (later.md). + +**As built,** on 2026-10-20, in the rebuild only: +- **Refused, each with a note where it's written:** + - **A name declared twice in one block,** including one an `is not` test names for the + rest of the block. A parameter, a block within, a loop's body and a function within + may still declare it again, as C has it. Each block keeps where its names begin + (`checker::check_redeclared`). + - **`&mut` of a union's field,** or of anything within one, and **`&`** where what it + refers to closes (`checker::check_lends_field`). A C union's fields are lent as + before, since it holds no tag. + - **A property of type `void`,** and **a variable declared through a generic type.** + - **`x is T` of a union where `T` is one of its fields' types,** as `m is nothing`. The + note names the field. In generic code it's asked of the template, not of each + instance. + - **`&x as` a number, `bool` or enum.** A reference held in a variable still converts + as its value. + - **A `string` compared with a view,** either way round. A literal still compares with + either. +- **A member a program declares on `core`'s type** with a name `core` gives the type too + is kept in a chain of its own (`decls.added`), and isn't a duplicate of `core`'s, even + with the same parameters. Wherever it's seen, it's chosen. `core`'s overloads are tried + only where none of the program's takes the arguments, for calls, operators and paths + alike (`checker::overloads_for`). `core`'s own code never sees the program's, and a + trait's conformance looks at both chains. A method and a property may share a name + this way too. So may a type a program declares through `core`'s, as `type + bool::storage = bit;` for a trait asking for one, which the corpus does, and a member + or type `core` gives that name. +- **`+=` in place:** ten names, `add_assign` to `shift_right_assign`. Where the target's + type has one taking the value, the compound assignment calls it on the target, through + a property or an element too, and writes nothing back. Through a property, `set` takes + what `get` gave, changed. Elsewhere it's `x = x + y`, as before. One giving a value is + refused. Nothing in std has one yet: `string`'s would + come with joining text by `+` ([later.md](later.md#joining-text-with-)). +- **A child module sees the names of those holding it,** as before. Where no file of one + was read, as a library's root left out, "`helper` is not declared where it is used" + goes on to say which module has no file. +- **Almost nothing in the tree was refused:** std, the compiler, its tests and its tools + check clean under every new rule, and one corpus program compared a `string` with a + view, which now writes `view()`. So step 4's compiler builds step 5's sources, and no + bootstrap step was needed. +- **Measured:** the compiler checking itself on one core at 2.1 GHz takes 324 ms with + step 4's checker and with step 5's alike. +- **Checked:** the fixed point, and one built on one thread is the one built on eight; + `sakura-v1.0.0` builds it in two steps; the unit tests, 266; the corpus, 144, in the + VM, natively at `-O0` to `-O2`, with `run --checks` and built with `--checks`; + `test/checked` and `test/memory`, 12 each; std's tests, 259, in the VM and natively, + checked and not, and under `run --checks`. The compiler and std's tests build for + Windows, where nothing was run. +- **Tests:** seven checker tests, and a corpus program, + `compound_assignments_change_in_place_where_a_type_can_1`, which grows a `string` in + place through a property too. +- **Found and fixed while building it:** `+=` in place through a property of a type + that closes closed what `get` gave after `set` had taken it, a double free that + `run --checks` and valgrind showed. + +### 6. Properties, as C# writes them (decisions 8 and 9) + +A getter always takes `&this`. A setter always takes `&mut this` and a value of the +property's type. Nothing else is possible, so writing them out says nothing. + +Today: + +```sakura +var rect::width: f32 { + get(&this) { return this.w; } + set(&mut this, to) { this.w = to; } +} +``` + +After: + +```sakura +var rect::width: f32 { + get => this.w; + set { this.w = value; } +} + +var rect::height: f32 { + get => this.h; + set => this.h = value; +} + +val rect::area: f32 { get => this.width * this.height; } + +trait sized { + val size: u64 { get; } +} +``` + +- **`get` has `this`, as `&this`.** **`set` has `this`, as `&mut this`, and `value`, of + the property's type.** They're there whether the body uses them or not. +- **An accessor has a body, `=> expression;`, or `;`,** `get` and `set` alike. The `;` is + for a trait, as now. `=> expression` is how a lambda and a match arm already give one + value. A setter's `set => this.h = value;` takes it too, as you asked on 2026-10-20, + since assigning is an expression. +- **`value` is a word only inside a `set`,** and acts as a parameter's name would. + `result`'s field is untouched: with a parameter named `value`, `r is value(&p)` and a + match's `value(n) =>` still work (probed). +- **`pub get` and `pub set` keep their own visibility,** as now. +- **The old forms, `get(&this)` and `set(&mut this, to)`,** are accepted beside the new + for one bootstrap step, then refused (decision 8). +- **No getter takes `&mut this`,** and none of the 184 does today. If one's wanted later, + a written `get(&mut this)` would be an addition. +- **Methods keep `&this` written.** A method may take `&this`, `&mut this` or neither, + and the first two may overload each other, so there the receiver says something. + +**A property that doesn't use `this`** (decision 9). You suggested that where neither +accessor uses `this`, the property could also be reached through its type, as +`rect::unit`, without being required to. The trouble is that what a property is to its +callers would then hang on its bodies: +- A getter that starts using `this`, say to read a field, would take `rect::unit` away + from every caller reaching it that way. That's an edit inside a body breaking + programs, which the freeze promise rules out. +- A trait's `{ get; }` has no body to look at. +- The language server would have to read bodies to offer `rect::` completions. + +Nothing needs it yet: nothing in the tree is a property of a type, and its associated +variables, trait constants and static functions do that job. So the recommendation is +that a property always belongs to a value. + +If a type's own property is wanted, it's better said in the declaration, the way a +method without `&this` is static. For example, `get()` with an empty list takes nothing, +so it's the type's. That can come after the freeze as an addition, or now. + +**As built,** on 2026-10-20, in the rebuild only, with decisions 8(a) and 9(a): +- **`get` and `set` take nothing in parentheses.** The body is a block, `=> expression;`, + or `;` in a trait. `=>` gives what a `get` returns, and is what a `set` does, as `set => + this.w = value;`. The parser makes it a block holding that `return` or statement, as + it does for `return x if c;`, so nothing after it changed. +- **The parameters are implied:** the parser makes `this` and a `set`'s `value` itself, + marked `implied`, with the `get` or `set` for their token, since a name comes from a + token. `checker::param_name` gives their names where they're bound, in debugging + information and in reflection. The language server's `local_text` gives them where it + shows a local: hover gives `value: int` and `this: &r`, completion offers both, and + renaming refuses both. The `get` or `set` itself is never taken for them. +- **`value` is a word only inside a `set`.** Elsewhere it's an ordinary name, and a + `result`'s field keeps it. +- **The written form is refused,** with a note at its `(` showing the form now, as "A + `set` takes no parameters written: it has `this`, and `value` of the property's type, + as `set => this.w = value;` or `set { this.w = value; }`." It's still read, so what + follows it is checked as it means. +- **Rewritten by a script,** in 64 files of `core`, std, the sources, the tests and the + corpus: 192 getters, 163 of them to `=>`, 25 blocks and 4 `get;`, and 18 setters, 14 + to `=>`, 2 blocks and 2 `set;`, with `to` renamed `value`. Nothing needed rewriting by + hand. +- **The decision 8 step was done another way.** Rather than one compiler accepting both + forms, the bootstrap writes copies back to the old form for the first stage, so the + compiler refuses the old form from the start. later.md's "The repository's compiler" + has the recipe from `sakura-v1.0.0`, checked to reach the fixed point. +- **No getter takes `&mut this`,** and decision 9 leaves every property a value's. +- **Measured:** checking the compiler takes 324 ms with step 5's checker on its form of + the sources and with step 6's on theirs. +- **Checked:** the fixed point, one thread or eight alike; the unit tests, 268; the + corpus, 144, in the VM, natively at `-O0` to `-O2`, with `run --checks` and built with + `--checks`; `test/checked` and `test/memory`, 12 each; std's tests, 259, everywhere. + The compiler and std's tests build for Windows, where nothing was run. +- **Tests:** a parser test of both forms of body and of the written form refused, a + checker test of `this`, `value` and their types, and a language server test of hover + and renaming. + +### 6½. References and values, one rule (asked on 2026-10-21) + +Copies and moves followed one rule already: a value that closes is never copied +implicitly. References followed two. They were read through, and taken at a call +without `&`, as in C++, but they were also types that stacked (`&&T`), were inferred +for `T`, were pointed elsewhere by `r = s`, and were carried along by `:=`, as in Rust. +So `val e := v[0]` referred to the element while `val e := a[0]` of a fixed array and +`val y := v[0].x` copied, `max(v[0], v[1])` gave a reference into `v`, and a function +taking `&T` wasn't accepted where one taking `T`, `&mut T` or `&&T` was asked. + +**The rule:** where a value goes says what happens to it. A reference type lends it, +and any other type gives it: a new value moves, a place is copied where it closes +nothing, and one that closes is refused. Only `&` or `&mut` written, or a reference +parameter at a call, makes a reference. + +1. **Giving:** `:=`, a `T` parameter, a field, an element, `return`, `=`, `is some(v)`, + `for x in`, and what a lambda's `=>` gives. +2. **Lending:** a `&T` or `&mut T` parameter, result or field, `val r := &x`, + `is some(&v)`, `for &x in`. `&mut` needs what can be written, or what `&mut` reaches. +3. **References never stack:** `&` of a reference is that reference. +4. **Inference sees values:** a `T` parameter given `v[0]` takes an `i64`, and `f(&x)` + a reference. +5. **Assigning writes through:** `r = s` writes what `s` reaches; `r = &y` points `r` + at `y`. +6. **Function values are called as the type asks:** a named function given where a + function type it doesn't match is expected is called by a function made for it, + as a call would call it: defaults filled, arguments lent or read through, the + overload a call chooses. + +Asked on 2026-10-22, with it: a reference written as one is a pointer where one is +expected, and `core` has `address(x)`, `*mut T` or `*T`, beside `through(p)`. + +**As built,** on 2026-10-22, in the rebuild only: +- **One decision per node.** Each place a reference is taken as its value, or `&` of + a reference is that reference, notes it on the node (`rf::valued`, `rf::relent`). + An instance takes the template's decision, so where `T` is a reference, a `T` is + still the value the template meant: `vector<&T>::append` stores the reference, and + `move(&mut x)` of a `T` moves it. Collapsing `&&T` in the types themselves broke + exactly this, and was dropped. +- **A reference to a trait** is taken as it is wherever a value would be, since no + value is of a trait. Refusing it instead would have changed every + `some(held)` of a `maybe<&mut allocator>`. +- **Adapters** are functions the emitter makes for each place a function is named + so: `function_value` gives one where the checker marks the node `rf::adapted`. + `call_site()` in a default is where the function is named. +- **Overloads:** a writable argument is better lent to a `&mut` parameter than a `&` + one, as receivers already were, so `address(x)` of a `var` gives a `*mut`. +- **Found by the change:** `dict`'s key and value cursors returned `&entry.key` of a + copy once `is some(entry)` copied, which `run --checks` stopped at; they name the + entry with `&` now. Temporary warnings listed every `var` that had held a reference, + every assignment that had pointed one elsewhere, and every `&` of a copy, and each + was read. +- **Rewritten:** 120 bindings and patterns in the sources, `core`, std and the tests + gained `&` or `&mut`, as `val syntax := &this.units[file].syntax;`, and 12 loops + became `for &x`. The compiler errors named each of them. + `integer::parse` and `real::parse` could take `strview` again, which is yours to + change back. +- **Measured:** checking the compiler takes 0.35 s, and building it at `-O2` 3.4 s, + with the compiler from before and with this one. Built under the rule, the + compiler is 13 KB larger, 0.15%, from the copies its bindings make now. +- **Checked:** the two steps from `sakura-v1.0.0` to the fixed point; the unit tests, + 271, but for gdb's, which failed the same way before; the corpus, 148, in the VM, + natively at `-O0` to `-O2`, with `run --checks` and built with `--checks`; + `test/checked` and `test/memory`, 12 each; std's tests, 259, everywhere. The + compiler and std's tests build for Windows, where nothing was run. +- **Tests:** two checker tests, of the rule and of the functions called as a type + asks, and two corpus programs, `references_are_lent_and_values_given_1` and + `named_functions_are_called_as_the_type_asks_1`. Seven tests written for the old + rule now say the new one, as `indexing_gives_the_reference_at_gives_1`. + +What it left is in [later.md](later.md#references-and-values-what-the-rule-left). + +### 7. Lambdas that own what they use (decisions 2 and 3) + +**What can't be written today:** +- a lambda that keeps state, returned; +- a thread given a lambda that owns what it uses. A loop's variable goes through + `spawn_with`; +- a lambda kept in a `function` past the frame that made it. + +Today the first and third take a functor, which is three declarations, and the second +takes `spawn_with`: + +```sakura +struct counter : invokable { var count: i64; } +def counter::invoke(&mut this): i64 { this.count++; return this.count; } +def make_counter(): function { return function::new(counter{}); } + +thread::spawn_with(def(i: i64) { work(i); }, i) +``` + +**Already turned down, on 2026-10-19:** +- a list in brackets, as C++ has, either of initializers (`[count = 0]`) or of words + (`[move log, level]`); +- `move def`, as Rust has. + +**What any direction needs:** +- **A lambda that owns a value has a type of its own,** a struct of what it holds that + implements `invokable`. In effect it's a functor the compiler writes. It can't be a + function value, since a function value owns nothing. +- **It's moved, not copied,** once it holds something that closes, and it closes what it + holds. +- **Where a `function` is expected, it becomes one.** That's later.md's "Converting + where a function is expected", now that `core` holds `function` and only one compiler + has to know it. +- **`spawn` takes anything `invokable`.** `spawn_with` and `carrying` go. +- **A lambda that refers to locals keeps today's rules,** and today's warnings. + +**The directions** (decision 2): + +**(a) The lambda's own values in its parameter list, declared as locals are.** A +parameter written `val` or `var` belongs to the lambda: +- it's made where the lambda is written, from the scope around it; +- it's kept from call to call; +- a call doesn't give it. + +```sakura +def counter(): function { + return def(var count := 0): i64 { count++; return count; }; +} + +for i in 0..4 { + val made := thread::spawn(def(val i := i) { work(i); }) else (e) { return; }; + handles.append(made); +} + +var lines := read_lines(path); +thread::spawn(def(var lines := move(&mut lines)) { write_all(&lines); }); + +val scaled := def(x: i64, val k := factor * 2) => x * k; # k is worked out once +``` + +```ebnf +lambda_param = ident [ ":" type ] [ "=" expression ] + | ( "val" | "var" ) ident ":" [ type ] "=" expression ; (* the lambda's own *) +``` + +- **The signature leaves them out:** the lambdas above are `def(): i64`, `def(): void` + and `def(i64): i64`. They come after the parameters a call gives. +- **There's no new word and no brackets.** `val`, `var` and `:=` already mean "a value + made here", and a `val` can't change while a `var` can, as for locals. +- **A lambda with none of them is today's.** It still refers to anything else it uses. +- **The parser is ready for it:** a parameter starts with a name today, so `val` and + `var` there are free. + +**(b) Values bound by std, with no syntax.** `bind(f, values...)` gives a functor that +holds the values and passes them by `&mut`, ahead of the call's arguments: `spawn_with` +for any lambda. + +```sakura +return function::new(bind(def(count: &mut i64): i64 { count++; return count; }, 0)); +thread::spawn(bind(def(lines: &mut vector) { write_all(lines); }, move(&mut lines))); +``` + +The language doesn't change at all. The lambda's parameter types are written, as they +are for `spawn_with` today. It could be built as well as (a), or before it. + +**(c) Declared in the body, with a word saying they're made with the lambda:** + +```sakura +return def(): i64 { + own var count := 0; + count++; return count; +}; +``` + +It reads like the body, but it runs at a different time than the lines under it. +`own` would mean something only before `val` or `var`, since std uses it as a name. + +**(d) Functors, as now.** + +Recommended: **(a)**. It's the smallest change to the language: one rule on a list +every lambda already has, in words the language already uses. + +**Which lambdas get a type of their own** (decision 3): +- Under every direction, a lambda that owns needs one. +- Giving one to every lambda would let generic code take each lambda as its own type, so + a lambda would cost what a functor does: + - the adapters, which cost 4 to 9 times functors today (later.md, "Lambdas given to + adapters"); + - a sort's order, which no optimization reaches otherwise (algorithms.md, + decision 4). + +A lambda would still convert to a function type wherever one is expected. What it +refuses is two lambdas given to one variable that isn't declared with a function type: + +```sakura +var pick := def(x: i64) => x + 1; +pick = def(x: i64) => x * 2; # refused: two lambdas, two types +var chosen: def(i64): i64 = def(x) => x + 1; +chosen = def(x) => x * 2; # both convert +``` + +Each place in the tree that gives a lambda to a variable already declares a function +type (probed), so nothing in the tree is refused. It changes what programs mean, so it's +now or never. + +**Its own plan,** written once steps 5 and 6 are done, measures and builds the +direction you choose. + +### 8. The freeze (decision 4) + +- **The README's grammar and rules are the language.** A line says from which version. +- **A corpus of the grammar:** a program for each rule of the README's grammar that none + of `test/programs` uses yet, each with its `.out`. A change that breaks one fails a + test. +- **inconsistencies.md goes.** Its rules are settled by step 5. Its VMs and code + generation are C's, which decision 1 retires. +- **The bootstrap rule from then on:** + - the compiler's own sources use only the language and std of the release before; + - a release is built in two steps: the release before, with its own std, builds a + first stage from the new sources, and that stage, with the new std, builds the + release; + - so the chain from C stops growing at the freeze. +- **std is found as `core` is,** and `--std` and `SAKURA_STD` go. Built on 2026-10-26, + as the README says: `--lib std=DIR`, + else beside or above the compiler, else where `blossom install` puts it. There's one compiler by then, under + either answer to decision 1. + +## What this changes in the other plans + +- **Each plan's phases say "in both compilers".** Each plan now says, beside its + ffi line, that it's built in the rebuild alone. +- **The bootstrapping lines change.** The std and contracts plans said "C builds the + rebuild directly throughout". Under 1(a), the chain did that. +- **The plans that only add** wait for the freeze (decision 5). Their "Comes after the + ffi plan" lines still hold. +- **inconsistencies.md:** its "What runs while compiling", "The VMs" and "The code each + makes" stop mattering under 1(a). Only its rules are left, for step 5. + +## Found along the way + +- **A program's own type named as a built-in hides it.** `struct u32 { var lo: u64; }` + builds and runs. So a built-in type, such as `i128`, can come after the freeze. +- **`undefined` is a name in the rebuild,** `ec::undefined`, so the checks plan's + `= undefined` must be a word only where it stands. +- **A parameter named `value` hides nothing a setter needs.** `r is value(&p)` and a + match's `value(n) =>` on a `result` still work beside it, so `set`'s implied `value` + can be a plain name. +- **Every lambda the tree gives to an existing variable goes to one declared with a + function type:** + - fields of a `def` type; + - `var fib: transform`; + - a `maybe`; + - a `val maybe: def(): int` chosen by `?:`. + + No array holds lambdas. So decision 3(a) refuses nothing in the tree. +- **The built-in types are read as `module core`,** and a program with no `module` line + is module 0, which holds every module. So a program's member on a built-in type was + "seen" from `core`'s own code too, which step 5 had to keep to `core`'s own members. +- **The comparison of a `string` with a view had answered right since the std plan,** by + making a `string` of the view, which allocates. Step 5 refuses it all the same. +- **A program's method named as a property of `core`'s,** as `string::is_empty`, was a + duplicate reported at `core`'s line, before step 5. + +## Decisions for you + +**Decided 2026-10-20:** the recommended answer to each. + +1. **Where the C compiler stops:** + - **(a) At a seed today:** your next commit of the working tree. It's the last commit + C builds, and the rebuild builds each one after it. + - **(b) At the freeze,** learning until then what the rebuild's own sources and the + std they read use, on Linux. + + Recommended: **(a)**. + - It saves the C half of every step: about 300 lines for the ffi plan, 700 for the std + plan, 400 for the contracts plan, and keeping C's std in step with the rebuild's. + - What's lost is the corpus run under two compilers, which found most of + inconsistencies.md. The `.out` files still hold every answer. + - Two-step bootstraps are what each change since 10-09 has needed anyway. +2. **How a lambda owns what it uses:** + - **(a) `val` and `var` parameters, made where the lambda is written.** + - **(b) std's `bind`,** with no syntax. + - **(c) `own val` and `own var` in the body.** + - **(d) Functors, as now.** + + Recommended: **(a)**, with (b) worth building beside it if a library wants it. +3. **Which lambdas have a type of their own:** + - **(a) Every lambda,** converting to a function type where one is expected. + - **(b) Only those holding values of their own.** + + Recommended: **(a)**. Owning lambdas need the machinery anyway, and it makes every + lambda cost what a functor does. What it refuses doesn't occur in the tree, and it's + now or never. The cost is an instance of generic code for each lambda given to it, + which step 7's plan would measure. +4. **What the freeze promises:** + - **(a) Additions only, from then on.** A program accepted keeps being accepted and + keeps its meaning. New words mean something only where they stand. + - **(b) Editions:** (a) within an edition, while a new edition may change things. A + file or blossomfile names its edition, so old programs build as they did. + - **(c) Nothing until a 1.0 tag.** The freeze is a candidate, and changes stay + possible while you write programs in it. + + Recommended: **(a)**. Editions can come later without breaking it, since a file that + names none would be of the first. +5. **When the plans that only add are built:** + - **(a) After the freeze.** They're then written against the language as it stays. + - **(b) freestanding.md before the freeze, and the rest after.** It's what you want + the language for, and it changes nothing that's there. + - **(c) Whenever wanted,** once the std plan is built. + + Recommended: **(a)**. Each one built first puts the freeze further off, and none of + them needs it to wait. +6. **Rules the rebuild accepts that C refused,** where refusing is the safer side: + - **(a) Refuse them, as C does:** + - `val x` declared twice in one scope; + - `&` and `&mut` of a union's field, which lend the field without asking which + field the union holds. + + `is value(&p)` and `is some(&mut q)` stay the way in. Accepting either later is an + addition. + - **(b) Keep the rebuild's:** names redeclared in the same scope, as Rust has it, + and a union's field lent as it is. + - **(c) Split:** redeclaring kept, the union's fields refused. + + Recommended: **(a)**. Step 5 counts the places std and the sources use them, and + changes them. +7. **later.md's items that would break programs if done later:** + - **(a) All three before the freeze:** + - `m is nothing` refused; + - `(&mut x) as u64` refused; + - `+=` calling `add_assign` where a type has one. + - **(b) The two refusals only.** `+=` stays `x = x + y` for good. + - **(c) None.** + + Recommended: **(a)**. Otherwise `+=` on a `string`, or on anything else that owns + memory, allocates every time, and building text with `+=` is common. +8. **How accessors are written:** + - **(a) `get` and `set` with nothing in parentheses,** and a body, `=> expression;` + or `;`. The old forms are accepted for one bootstrap step, then refused. + - **(b) The same, with the old forms kept** as a longer spelling. + - **(c) Without `=>`:** bodies and `;` only. + + Recommended: **(a)**. There's one way to write it, and `=>` is how the language + already writes a body that gives one value. +9. **A property that doesn't use `this`:** + - **(a) It still belongs to a value.** What belongs to a type is an associated + variable, a trait's constant, or a static function. A marked form, as (c), can be + added after the freeze. + - **(b) Inferred, as you suggested:** where no accessor uses `this`, it may be + reached through its type as well. + - **(c) Marked now:** `get()`, with an empty list, takes nothing, so the property is + its type's, reached as `rect::unit`. + + Recommended: **(a)**. Under (b), an edit inside a body could break callers, and a + trait's property has no body to tell by. Nothing in the tree needs a type's property + yet, and (c) stays open. diff --git a/docs/tui.md b/docs/tui.md new file mode 100644 index 00000000..b98a4b37 --- /dev/null +++ b/docs/tui.md @@ -0,0 +1,843 @@ +# Plan: terminal interfaces + +Written 2026-10-13, and brought up to date 2026-10-20 for what std has gained since: +`poll`'s timeout, Windows, threads, `strview::chars`, `std::swar`, signal handlers held +as `function`s, and `result`. This is a proposal. std is yours, so the +decisions at the end are yours to make. Nothing is built yet. + +**Comes after the ffi plan, now built:** `std::sys` is `system`, and `@foreign` and +`@link` are `extern` sections. + +**Built in the rebuild alone** ([roadmap.md](roadmap.md), decision 1). Where this plan +says both compilers, C's half is left out. What was measured in C stays as measured. + +**What it is:** a library for writing to a terminal: +- **color and style:** text in sixteen, 256 or 16 million colors, bold, italic, + underlined and the rest, written only where the output shows them; +- **the cursor:** moving it, saving and restoring it, hiding it, and changing its + shape, and clearing the screen; +- **box drawing:** boxes and lines in light, heavy, double or rounded strokes, which + join where they meet; +- **full-screen programs:** raw mode, the alternate screen, keys, the mouse, pasting + and resizing, and a canvas the program draws a frame on, of which only what changed + is written. + +**Its users:** +- the logging plan ([logging.md](logging.md)), whose levels are colored on a terminal. + Its `sys::is_terminal` is this plan's; +- `std::args` (the README's "Arguments"), whose help is written in columns padded by + bytes. It could be wrapped to the terminal's width and padded by `width_of`. A + program's own `--no-color` would give its painters abilities of its choosing; +- `std::testing`, which could color what passed and failed and keep one line of + progress; +- the compilers' notes, which could color their places and underlines; +- the build tool's progress; +- full-screen programs, such as a profile viewer, a debugger's front end, or a + program that picks from a list. + +**Probed:** in the scratchpad on 2026-10-13 (`tuiprobe/`), and again on 2026-10-20 +against today's std (`plans/tui/`). A small driver ran the probe under a +pseudo-terminal of 24×80, resized it, and typed into it. The probe was built by both +compilers and run as an executable and in each VM, and all four gave the same results +both times: +- `TCGETS`, made through `sys::syscall`, worked on the terminal and gave -25 + (`ENOTTY`) on a pipe; +- `TIOCGWINSZ` gave 24×80, and 40×120 once the driver resized it; +- raw mode was set through `TCSETS`, as `cfmakeraw` sets it. The mode put back + afterward matched the saved one byte for byte; +- `sys::poll` with a timeout, std's own now, was ended by the resize with -4. The + handler given to `sys::handle(signal::resized, ...)`, a closure counting into a + local, had run by then; +- an up arrow arrived as one read of `ESC [ A`. A lone Escape was told apart from the + start of a sequence by 30 ms of quiet; +- `sys::raise(signal::suspend)` stopped the program, which went on from there once it + was continued (2026-10-20); +- bold red, 256-color and 24-bit color, hiding and moving the cursor, and a rounded + box with `┬`, `┼` and `┴` were all written from literals, with `\x1b` and UTF-8 text, + and reached the terminal as written (2026-10-13). No terminal showed them, so how + they look wasn't probed; +- the sketches under "Using it", over stubs of the API, checked and ran in both + compilers (2026-10-20), once union fields were `pub` and `attribute` was renamed + `effect` (see "Found along the way"). + +Nothing was probed on Windows. + +**Measured** on 2026-10-20: every program is checked with all of std, whatever it +imports, and std is 40,200 lines now. The processor was held at 2.1 GHz, on battery, +so the times are slower than 2026-10-13's, whose clock wasn't noted, and the two don't +compare. Each is the best of 15 runs or more, interleaved, on one core. +- A one-line program takes about 93 ms to check in the rebuild and 165 ms in C. +- `std/yaml`'s 4,498 lines cost 12 ms of that in the rebuild and 24 ms in C, and + `std/time`'s and `std/thread`'s 1,965 lines 5 and 13 ms. That's about 2.6 ms per + 1,000 lines in the rebuild, and 5 to 7 in C. +- So the 2,500 or so lines this plan adds to std would add about 6.5 ms to checking + every program in the rebuild, and 13 to 17 ms in C, at that clock: 7% of a one-line + program's check in the rebuild, and 8 to 10% in C. + +## What's there now + +- **Writers:** `io::output()` writes at line breaks, `io::error_output()` writes at + once, and `io::writer_of` buffers anything `writable`. A write gives + `result`. `print` and `println` hold the standard output for each + call, so two threads' lines never mix, and `io::output_locked()` holds it across + several. +- **Text:** literals take `\x1b` and UTF-8, and `strview` and `string` are bytes. + - `strview::chars()` decodes UTF-8 lazily into code points, giving `U+FFFD` for each + byte that begins none. `serial::is_utf8` checks text, and `serial::utf8_length` + measures a sequence. + - `index_of`, `find_any` and `is_ascii` go eight bytes at a time, and `std::swar` + gives the words themselves, for passing over runs of plain ASCII. + - Nothing knows how wide a character is. +- **`std::sys`,** on Linux and, since 2026-10-19, on Windows: + - it reads and writes handles; + - `poll(handles, ready, wait)` waits on several handles for at most `wait` + milliseconds, or forever where it's -1, and gives 0 where the wait ran out. On + Windows it peeks pipes, so a console always reads as ready; + - it handles signals, `resized` (`SIGWINCH`) among them. `handle` takes any + callable, which it keeps as a `function`, the type + `sys::handler`. A handler runs at a safe point, in the thread the program began + with, and ends the wait it interrupts. `watch` and `watched` note a signal with no + handler, and the waits it interrupts go on. `raise` sends a signal to the program + itself; + - it reads the environment, through `sys::environment()` and `process::variable`. +- **Nothing knows the terminal on Linux:** whether a handle is one, its size, or its + mode. There's no `ioctl`, though `sys::syscall` reaches it, as the probe did. +- **On Windows,** `std::sys` asks `GetConsoleMode` whether a handle is a console, but + only for itself. It reads and writes a console as UTF-16, through `ReadConsoleW` and + `WriteConsoleW`, so UTF-8 shows whatever the code page. Nothing sets a console's + mode, so a sequence written reaches it as text unless its virtual terminal + processing is on already. The console's Ctrl-C, Ctrl-Break and closing are noted as + `interrupt`, `quit` and `hangup`, no `resized` ever comes, and `raise(suspend)` gives + `unsupported`. +- **Nothing runs as the program stops,** besides `close` where a scope ends. `exit` + and a fault from any thread, `abort` and a failed contract end in `exit_group`, or + `ExitProcess` on Windows, through the runtime in `runtime/start.sakura` or + through the VM. +- **`flags32`** is a set of flags named by an enum, which fits a style's effects. +- **std::time's `duration`** fits a wait for input. +- **`function`** holds any callable of a signature, and owns it. It's moved, never + copied. + +## What it needs + +1. **Colors and styles:** + - the sixteen named colors, the 256 indexed ones, and 24-bit colors; + - bold, dim, italic, underline, blink, reverse, hidden and strikethrough; + - colors brought down to what the terminal shows, and nothing written where the + output isn't a terminal or the user asked for no color. +2. **The cursor:** moved to a place or by an amount, saved and restored, hidden and + shown, and given a shape. +3. **The screen:** + - clearing it, a line, or the rest of either; + - the alternate screen; + - a scrolling region; + - the window's title. +4. **Box drawing:** + - light, heavy, double and rounded strokes; + - lines that meet joined into `├`, `┬` and `┼`; + - boxes in a full-screen frame, and in ordinary output, as a table printed at the + end of a build. +5. **The terminal itself:** + - whether a handle is one, and its size; + - raw mode, and putting back the mode it was in; + - resizing, and suspending with Ctrl-Z and resuming. +6. **Input:** + - keys, with Shift, Alt and Ctrl; + - text, the mouse, pasting and focus; + - reading with a timeout. +7. **A canvas** the program draws a whole frame on, of which only the cells that + changed are written. +8. **The width of text** in columns, so that `中` takes two and an accent joining a + letter none. +9. **Tests without a terminal,** with one where it matters. +10. **Portable above `std::sys`,** which has Windows now. Its console takes the same + sequences once its virtual terminal processing is on. Every operation `std::sys` + gains must exist there too, since std is checked whole for an executable for + Windows (decision 11). + +## How it fits the rules + +- **A terminal is `owning`.** Closing it, on any way out of its scope, puts back what + it changed: + - the mode, and the screen; + - the cursor; + - mouse and paste reporting; + - what the program did with `resized`. + + Decision 5 is what happens when the program stops some other way. +- **A painter borrows or owns its stream,** as `io::writer_of`'s writer does, so + `painter_of(&mut text)` writes to a `string` and closes nothing. +- **Colors, styles, keys, events and cells are plain data.** They copy freely and are + `equatable`. A `maybe` has no `==`, so `style::equals` compares its colors itself. A + pasted text views the terminal's buffer, and is good until the next event is read, + as a `dir_entry`'s name is good until the next entry. +- **Errors are values.** Anything that can fail gives `result`, or + `result` where only whether it failed comes back. `io_error` gains + `not_a_terminal`, for `ENOTTY`, which `error_of` gives as `other` today. +- **Everything is written through `writable`,** so tests read what a painter wrote + from a `string`. +- **Signals stay the program's:** + - in raw mode, Ctrl-C and Ctrl-Z are keys, so the program decides what they do; + - while a terminal is open, it handles `resized`, and the program reads + `event::resized`. On close, what the program did with `resized` comes back: its + handler, or ignoring it, watching for it, or the default. A handler is a + `function`, moved and never copied, so `std::sys` gains a way to take it and give + it back. +- **Interpolation formats a value by its fields,** so `$"{style}"` can't write a + sequence. `paint` gives a `string` to interpolate instead. +- **What's shared is made on first use,** as `io::output()` is: `term::output()` and + `term::error_output()`, the standard streams' painters. + - Each paints `term::standard`, a stream writing through `io::output()` or + `io::error_output()` at each write, so painted text keeps its order with + `println`'s. It can't hold a `&mut writer`, since a module's variable + needs a zero value and a reference has none (probed in both compilers). + - As `io::output()` doesn't, it takes no lock. A thread painting several pieces + holds `io::output_locked()` around them. + +## Layers + +### `std::sys` gains + +| Operation | Does | +|---|---| +| `is_terminal(handle: fd): bool` | Whether the handle is a terminal, through `TCGETS`, and on Windows `GetConsoleMode`, which `std::sys` asks already for itself. The logging plan's. Probed on Linux | +| `terminal_size(handle: fd, columns: &mut u16, rows: &mut u16): i32` | Its size, through `TIOCGWINSZ`, and on Windows `GetConsoleScreenBufferInfo`'s window. Probed on Linux | +| `terminal_mode` | The mode a terminal is in, as the system keeps it: 36 bytes on Linux, and the input's and output's modes on Windows, which nothing above reads | +| `get_mode(handle: fd, into: &mut terminal_mode): i32` | Reads it, through `TCGETS`, or `GetConsoleMode`. Probed on Linux | +| `set_mode(handle: fd, mode: &terminal_mode): i32` | Sets it, through `TCSETS`, or `SetConsoleMode`. Probed on Linux | +| `terminal_mode::make_raw(&mut this): void` | Raw: no echo, no lines, no signals from keys, and every byte as it comes, with virtual terminal processing and input on Windows. Probed on Linux, as `cfmakeraw` sets it | +| `take_handling(which: signal): handling`, `give_handling(which: signal, back: handling): i32` | What the program does with a signal, taken so that a library can handle it for a while and give it back: the default, ignoring it, watching for it, or its handler, moved out | +| `restore_at_stop(...)`, `forget_at_stop()` | Decision 5's record, which the runtime and the VMs keep | + +- **`poll`'s timeout is there already,** in milliseconds, so `next` turns its + `duration` into them. The plan had it gain one in nanoseconds. +- **On Linux:** `ioctl` is 16 on x86-64. Its requests are `TCGETS` 0x5401, `TCSETS` + 0x5402 and `TIOCGWINSZ` 0x5413. They differ on a few processors, so they go in + `linux_x86_64.sakura`, beside the other calls' numbers. +- **`io_error::not_a_terminal`** is what `error_of` gives for -25. +- **On Windows (decision 11):** `SetConsoleMode`, with + `ENABLE_VIRTUAL_TERMINAL_PROCESSING` on the output, and for raw mode + `ENABLE_VIRTUAL_TERMINAL_INPUT` on the input, without line input, echo or processed + input. Windows sends no `resized`, so the terminal reads the size again each time + `next` returns, or reads `ReadConsoleInput`'s window events. `poll` peeks pipes, so + waiting for a console's input needs a wait on the console's own handle. None of it + is probed. + +### `std` gains nothing now + +- **`decode_utf8` isn't needed:** `strview::chars()` decodes, and the canvas writes + each character's UTF-8 into its cell itself. +- The input decoder keeps a sequence cut short at the end of a read for the next one. + It tells one from a wrong sequence by its first byte, which neither `chars` nor + `serial::utf8_length` does. + +### `std::term` (decision 1) + +``` +std/term/ + style.sakura color, ansi, effect, style + abilities.sakura color_depth, abilities, abilities_of + painter.sakura painter, standard, output, error_output, paint, and the cursor and screen + boxes.sakura line_style, and the glyph each meeting of lines takes + widths.sakura width_of, over a table tools/widths.sakura writes + canvas.sakura size, rect, cell, canvas + input.sakura event, key, key_code, modifier, mouse, and the decoder + terminal.sakura terminal, settings, show, next, suspend +``` + +**Styles:** + +```sakura +#! One of the sixteen colors every color terminal has, which its theme decides. +pub enum ansi: u8 { + black, red, green, yellow, blue, magenta, cyan, white, + bright_black, bright_red, bright_green, bright_yellow, + bright_blue, bright_magenta, bright_cyan, bright_white, +} + +#! A color of text, or of what's behind it. +pub union color : equatable { + pub var ansi: ansi; #! One of the sixteen. + pub var indexed: u8; #! One of 256: the sixteen, a 6×6×6 cube, and 24 grays. + pub var rgb: u8[3]; #! Any, as red, green and blue. +} + +pub val color::red := color{ ansi = ansi::red }; # and the other fifteen +pub def color::hex(value: u32): color; # color::hex(0xFF8800) + +#! What text looks like besides its colors. +pub enum effect: u32 { + bold = 1, dim = 2, italic = 4, underline = 8, + blink = 16, reverse = 32, hidden = 64, strike = 128, +} + +#! How text is drawn. A color that's `nothing` is the terminal's own. +pub struct style : equatable { + pub var fg: maybe; + pub var bg: maybe; + pub var effects: flags32; +} +``` + +**What a stream shows (decision 3):** + +```sakura +#! How many colors a stream shows. +pub enum color_depth: u8 { none, basic, indexed, full } + +#! What a stream shows of what a painter writes. +pub struct abilities : equatable { + pub var colors: color_depth; #! How many colors, if any. + pub var controls: bool; #! Whether cursor moves, clearing and modes are written. +} + +#! What a handle shows, from whether it's a terminal and from the environment. +pub def abilities_of(handle: sys::fd, environment: span = sys::environment()): abilities; +``` + +**Painting, in ordinary output (decision 4):** + +```sakura +#! Writes text in styles to any stream, and moves the cursor, writing only what the +#! stream shows. Colors are brought down to its depth, and where it shows none, only +#! the text is written. A style's sequence is written only where the style changes. +pub struct painter : owning, writable, flushable where W: writable { ... } + +#! The standard output or error, written through the writer `std::io` shares for it. +pub struct standard : writable { ... } + +pub def painter_of(sink: W, shows: abilities): painter; +pub def output(): &mut painter; # the standard output's +pub def error_output(): &mut painter; # the standard error's +pub val painter::shows: abilities; + +pub def painter::write(&mut this, text: strview): result; # in the style set +pub def painter::write(&mut this, text: strview, with: style): result; # in a style, then back +pub def painter::set(&mut this, with: style): void; +pub def painter::reset(&mut this): void; + +#! Text in a style, as a string to interpolate, for a stream showing what `shows` says. +pub def paint(text: strview, with: style, shows: abilities = output().shows): string; +``` + +The cursor and the screen, each written only where `controls` holds: + +| Method | Writes | +|---|---| +| `move_to(column: i32, row: i32)` | `CSI row;col H`, from 0 here and from 1 there (decision 10) | +| `move_by(columns: i32, rows: i32)` | `CSI n A`, `B`, `C` and `D` | +| `to_column(column: i32)` | `CSI n G` | +| `save_cursor()`, `restore_cursor()` | `ESC 7` and `ESC 8`, which more terminals take than `CSI s` | +| `show_cursor(shown: bool)` | `CSI ?25h` or `l` | +| `cursor_shape(shape: cursor_shape)` | `CSI n SP q`: block, underline or bar, blinking or steady | +| `clear(what: clearing)` | The screen, its rest, the line or its rest: `CSI 2J`, `CSI J`, `CSI 2K` or `CSI K` | +| `scroll_region(top: i32, bottom: i32)`, `scroll(rows: i32)` | `CSI t;b r`, and `CSI n S` or `T` | +| `title(text: strview)` | `OSC 2;text BEL` | + +**The terminal:** + +```sakura +#! What a terminal is set to while it's open. +pub struct settings { + pub var alternate := true; #! Draw on the alternate screen, leaving the shell's as it was. + pub var mouse := mouse_mode::none; #! none, buttons, drags, or every move. + pub var paste := true; #! Report pasted text as one event, not as keys. + pub var focus := false; #! Report the window gaining and losing focus. + pub var escape := milliseconds(50); #! How long a lone Escape waits for a sequence. +} + +#! The terminal the program runs in, in raw mode. Closing it puts back everything it +#! changed. +pub struct terminal : owning { ... } + +pub def terminal::open(with: settings = settings{}): result; # not_a_terminal through a pipe +pub val terminal::size: size; +pub val terminal::out: &mut painter<...>; # for drawing without a canvas +pub def terminal::show(&mut this, frame: &canvas): result; +pub def terminal::next(&mut this, wait: maybe = nothing{}): result, io_error>; +pub def terminal::suspend(&mut this): void; # for Ctrl-Z: put back, stop, and on resuming, take again +``` + +**Input (decision 6):** + +```sakura +pub union event { + pub var key: key; #! A key, with the modifiers held. + pub var mouse: mouse; #! A button pressed or let go, the wheel, or a move. + pub var paste: strview; #! Text pasted, good until the next event is read. + pub var resized: size; #! The terminal's new size. + pub var focused: bool; #! Whether the window gained focus or lost it. +} + +pub enum modifier: u32 { shift = 1, alt = 2, control = 4 } + +pub struct key : equatable { + pub var code: key_code; #! Which key. + pub var character: u32; #! The character, where `code` is `character`. + pub var modifiers: flags32; +} + +pub enum key_code: u8 { + character, enter, tab, backspace, escape, + up, down, left, right, home, end, page_up, page_down, insert, delete, + f1, f2, f3, f4, f5, f6, f7, f8, f9, f10, f11, f12, +} + +pub struct mouse : equatable { + pub var action: mouse_action; #! press, release, drag, move, wheel_up or wheel_down. + pub var button: mouse_button; #! left, middle, right, or none. + pub var column: i32; + pub var row: i32; + pub var modifiers: flags32; +} +``` + +**The canvas (decisions 7 to 9):** + +```sakura +pub struct size : equatable { pub var columns: i32; pub var rows: i32; } +pub struct position : equatable { pub var column: i32; pub var row: i32; } +pub struct rect : equatable { pub var left: i32; pub var top: i32; pub var width: i32; pub var height: i32; } + +#! Light, heavy or double strokes, or light ones with rounded corners. +pub enum line_style: u8 { light, heavy, double, rounded } + +#! A grid of cells to draw a frame on. +pub struct canvas : owning { ... } + +pub def canvas::new(of: size): canvas; +pub val canvas::size: size; +pub def canvas::resize(&mut this, to: size): void; +pub def canvas::clear(&mut this, with: style = style{}): void; +pub def canvas::put(&mut this, column: i32, row: i32, text: strview, with: style = style{}): i32; # columns used +pub def canvas::fill(&mut this, area: rect, character: u32, with: style = style{}): void; +pub def canvas::draw_box(&mut this, area: rect, lines: line_style = line_style::light, with: style = style{}): void; +pub def canvas::draw_across(&mut this, row: i32, from: i32, to: i32, lines: line_style = line_style::light, with: style = style{}): void; +pub def canvas::draw_down(&mut this, column: i32, from: i32, to: i32, lines: line_style = line_style::light, with: style = style{}): void; +pub var canvas::cursor: maybe; # where the cursor shows after the frame, or hidden +pub def canvas::write_to(&this, into: &mut painter): result; # as lines, in ordinary output + +pub def width_of(character: u32): u8; # 0, 1 or 2 +pub def width_of(text: strview): u64; +``` + +## Using it + +**Color in ordinary output,** which is plain text through a pipe: + +```sakura +import std; +import std::io; +import std::term; + +def main(args: span): void { + val out := term::output(); + val warn := style{ fg = color::yellow, effects = effect::bold }; + _ = out.write("note: "); + _ = out.write("`x` is never read", warn); + _ = out.write("\n"); + + println($"{term::paint("ok", style{ fg = color::green })} 12 tests"); +} +``` + +**A line of progress,** written over itself: + +```sakura +val out := term::output(); +for i in 0u..total { + out.to_column(0); + out.clear(clearing::line); + _ = out.write($"building {i + 1} of {total}"); + _ = out.flush(); + build(i); +} +_ = out.write("\n"); +``` + +**A box in ordinary output:** + +```sakura +var table := canvas::new(size{ columns = 32, rows = 4 }); +table.draw_box(rect{ left = 0, top = 0, width = 32, height = 4 }); +table.draw_down(16, 0, 3); +table.put(2, 1, "files"); +table.put(18, 1, "1,204"); +table.put(2, 2, "notes"); +table.put(18, 2, "0", style{ fg = color::green }); +_ = table.write_to(term::output()); +``` + +``` +┌───────────────┬──────────────┐ +│ files │ 1,204 │ +│ notes │ 0 │ +└───────────────┴──────────────┘ +``` + +**A full-screen program:** + +```sakura +import std; +import std::io; +import std::term; +import std::time; + +def main(args: span): void { + val names: strview[3] = ["build", "test", "clean"]; + var tty := terminal::open() else (e) { println("not a terminal"); return; }; + var frame := canvas::new(tty.size); + var chosen := 0u; + + while true { + frame.clear(); + frame.draw_box(rect{ left = 0, top = 0, width = frame.size.columns, height = frame.size.rows }, line_style::rounded); + frame.put(2, 0, " Pick one ", style{ effects = effect::bold }); + for i, name in names { + frame.put(2, 1 + i as i32, name, i == chosen ? style{ effects = effect::reverse } : style{}); + } + _ = tty.show(&frame); + + val came := tty.next(milliseconds(250)) else (e) { return; }; + val ev := came else { continue; }; # nothing came within the wait + if ev is resized(to) { + frame.resize(to); + } else if ev is key(k) { + val typed := k.code == key_code::character; + if k.code == key_code::up && chosen > 0 { chosen--; } + if k.code == key_code::down && chosen + 1 < names.length { chosen++; } + if k.code == key_code::enter || (typed && k.character == 'q') { return; } + if typed && k.character == 'z' && k.modifiers.get(modifier::control) { tty.suspend(); } + } + } +} # tty closes: the shell's screen, its mode and its cursor come back +``` + +## How each part works + +- **What it knows of terminals (decision 2):** the sequences of ECMA-48, and xterm's + private modes, which the terminals in use today share. These include xterm, VTE's + (GNOME Terminal), Konsole, kitty, Alacritty, WezTerm, foot, iTerm2, Windows + Terminal, tmux and screen. Synchronized output (`CSI ?2026h`) is written around + every frame, and terminals that don't know it ignore it. +- **Detecting what a stream shows (decision 3):** + - **Controls** are written where the handle is a terminal and `TERM` isn't `dumb`. + - **Colors,** the first of these that holds: + 1. `NO_COLOR` set and not empty gives `none`. no-color.org allows keeping bold + and the rest, but `none` drops them too, so it always means plain text; + 2. a handle that isn't a terminal, or `TERM=dumb`, gives `none`, unless + `FORCE_COLOR` is set and not empty; + 3. `COLORTERM` of `truecolor` or `24bit` gives `full`; + 4. a `TERM` ending in `256color` gives `indexed`; + 5. on Windows, a console whose virtual terminal processing is on gives `full`; + 6. anything else gives `basic`. + - It reads only the environment it's given, so tests pass their own. +- **Bringing colors down:** + - 24-bit becomes the nearest of the 6×6×6 cube and the 24 grays, as xterm's + palette sets them; + - either of those becomes the nearest of the sixteen, by xterm's default colors; + - nothing is written at `none`. +- **Writing a style:** + - Where the style only gains something, only that is written. + - Where anything turns off, `CSI 0m` is written, then the whole style. Bold and dim + share their "off", so the shorter way isn't always right. + - A painter remembers the style it last wrote, so a run of text in one style + writes it once. +- **Raw mode** is `cfmakeraw`'s, but for output: + - a `\n` still begins a line, so the program's own `println` still works; + - the canvas moves the cursor itself and never writes one. +- **Reading input:** + - The terminal polls its input with the wait given, reads what has come into a + buffer, and decodes one event at a time. + - **Keys** come as xterm writes them: + - `CSI A` to `D` and `SS3 A` to `D` for the arrows; + - `CSI H` and `CSI F` for Home and End, and `CSI n ~` for them too, and for + Insert, Delete, PageUp, PageDown and F5 to F12; + - `SS3 P` to `S` for F1 to F4; + - `CSI 1;m X` with the modifiers, as `m - 1` holds Shift 1, Alt 2 and Ctrl 4; + - `CSI Z` for Shift-Tab; + - ESC before a key for Alt; + - bytes 1 to 26 for Ctrl with a letter, but 9 is Tab and 13 is Enter; + - 127 and 8 for Backspace, as terminals differ, so Ctrl-H reads as Backspace; + - UTF-8 for any other character. + - **A lone Escape** is told from the start of a sequence by waiting `escape` for + more: 50 ms by default, as Neovim waits. The probe used 30. + - **The mouse:** `mouse_mode`'s buttons, drags and moves turn on xterm's modes 1000, + 1002 and 1003, always with 1006. That's SGR's encoding (`CSI < b;x;y M` or `m`), + whose places have no limit, unlike the original encoding's 223 columns. + - **Pasting** comes between `CSI 200~` and `CSI 201~`, as one event. + - **Focus** comes as `CSI I` and `CSI O`. + - A sequence it doesn't know is passed over whole, and bytes that aren't UTF-8 + become `U+FFFD`. +- **Resizing:** + - While open, the terminal handles `resized` with a function that notes it in a + variable of `std::term`. A closure won't do: the terminal moves once it's opened, + and a closure would refer to where it was. + - A wait the signal interrupts ends with -4, and `next` then reads the size again + and gives `event::resized`. Watching for the signal instead wouldn't end the wait. + - Handlers run only in the thread the program began with, so `next` called in + another thread sees a resize only once its wait ends. + - The program resizes its canvas, and the next `show` writes every cell. + - On Windows, where no signal comes, `next` reads the size each time it returns + (decision 11). +- **Suspending:** + - `suspend` puts the terminal back, as closing it would, then raises `suspend`, so + the program stops as Ctrl-Z would stop it. Probed. + - When the shell resumes it, the terminal is taken again, and `next` gives + `event::resized` with the size, which may have changed meanwhile. That makes the + next frame whole. + - Windows has no such stopping, and `raise(suspend)` gives `unsupported` there, so + `suspend` does nothing. +- **Showing a frame:** + - The terminal keeps the last frame it wrote, and compares the new one with it cell + by cell. + - For each run of changed cells, it moves the cursor only where the cursor isn't + already, writes the style only where it changes, then writes the text. + - All of it goes into one `string`, kept between frames, which is written in one + write inside synchronized output, so a frame never shows half drawn. + - The first frame, and the first after a resize, are written whole. +- **Cells:** + - A cell holds the UTF-8 of one character and of the marks joining it, up to 16 + bytes, with its style and its lines. + - A character two columns wide takes the next cell too, which is marked as its + second half. Drawing over either half clears the other. + - A cluster longer than 16 bytes, as some emoji sequences are, keeps its first + character. + - A tab moves to the next column that's a multiple of eight. Other control + characters are drawn as `�`. +- **Width (decision 7):** + - `width_of` follows Unicode 16. A character is two columns where its East Asian + width is `W` or `F`. It's none where it's a mark (`Mn`, `Me`), a format + character (`Cf`) other than the soft hyphen, a Hangul vowel or final + (U+1160 to U+11FF), or U+200B. Any other character is one column. + - The table is 369 ranges of none and 123 of two, about 4 KB. + - `tools/widths.sakura` writes it into `std/term/widths.sakura`, from Unicode's + `EastAsianWidth.txt` and `DerivedGeneralCategory.txt`, when Unicode changes. + - `width_of(text)` passes over printable ASCII, a column a byte, eight bytes at a + time with `std::swar`, and looks up only the rest. +- **Lines that meet (decision 9):** + - A cell holds, for each of its four sides, whether a line leaves by it, and how + heavy: light, heavy or double. That's two bits a side, and a ninth bit for a + rounded corner. + - Drawing a line adds to what the cell holds, and the glyph is looked up from all + four sides. So a line drawn down through a box's top edge gives `┬`, and two + boxes sharing an edge give `├`, `┤` and `┼` where they meet. + - A line's end leaves its last cell by one side only, so a line drawn down from a + box's top edge meets it as `┬`, not `┼`. A cell with a line leaving by one side + only is still drawn as a whole `─` or `│`, so a line standing alone looks whole. + - Every one of the 80 meetings of light and heavy strokes has a glyph in + U+2500–U+257F. + - Double strokes have glyphs only where the two sides along a line agree. Elsewhere, + and where double meets heavy, the double sides are drawn light. + - A rounded corner becomes square once a third line joins it. + - Text put on a cell clears its lines. +- **Ordinary output:** `canvas::write_to` writes each row's cells with their styles, + then a line break, with no cursor moves. So it works through a pipe, where it + writes only the text. +- **When the program stops some other way (decision 5):** + - Opening the terminal gives the runtime one record: the handle, the mode to put + back, the text that undoes the screen, and the process that made it. + - `exit` and a fault from any thread, `abort` and a failed contract put them back + before anything else, with two system calls. A fault's report then shows on the + shell's screen, not on the alternate one about to vanish. + - Closing the terminal forgets the record. A copy made by `fork` leaves it alone, + since the process isn't the one that made it. + - The terminal also handles `terminate` and `hangup` while open, where the program + doesn't, putting things back and then stopping as the signal would have. + +## Testing + +- **`test/std/term.sakura`, written with `std::testing`,** covers: + - **detection,** from environments the tests give: a pipe, `TERM=dumb`, `NO_COLOR`, + `FORCE_COLOR`, `COLORTERM` and `256color`; + - **painting:** every sequence, written to a `string` and compared exactly, at each + depth. Also styles that only gain, styles that lose something, and nothing at all + where the stream shows nothing; + - **bringing colors down,** against a table, with the cube's and the grays' edges; + - **decoding input,** from bytes the tests give, not from a terminal: + - every key, with and without modifiers; + - UTF-8 split across reads; + - mouse reports, and pasting; + - sequences it doesn't know, and bytes that aren't UTF-8; + - **width,** of ASCII, `é` both composed and decomposed, `中`, `😀`, U+200B and + U+0301; + - **boxes:** each meeting of strokes, boxes sharing edges, a line through a box, + double meeting light and heavy, and rounded corners joined; + - **the canvas:** text clipped at its edges, wide characters at the last column, and + drawing over half of one; + - **showing frames:** a small terminal emulator in the test reads what `show` wrote, + handling cursor moves, styles and text. The tests check its screen against the + canvas, after a first frame, a changed one, a resize, and wide characters; + - **a real terminal,** on Linux: the tests open a pseudo-terminal through + `/dev/ptmx`, as the probe's driver did through Python, and run the terminal on it: + - raw mode taken and put back; + - the size, and a resize, from a `resized` the test raises; + - keys written to it and read back as events; + - a forked copy that opens the terminal and then faults, after which the mode is + the one it found (decision 5). +- **A program of the corpus** writes a box and a colored table to its output, a pipe, + where it's plain text, under both compilers. +- **Where they run:** in the VM, under `run --checks`, and as executables at `-O0` and + `-O2`. The rebuild's analyzer must check them with 0 notes, and std must still check + for `--target windows-x86_64`. The time to check a one-line program is measured + before and after. + +## Phases + +About 130 lines of `std::sys` for Linux and 80 for Windows (decision 11), 2,300 of +`std::term` (150 of them written by the tool), 150 for the tool, and 1,000 of tests. +Decision 5's record adds two intrinsics to each compiler, and a few lines to each +runtime's ways of stopping. + +1. **`std::sys`:** `is_terminal`, `terminal_size`, the modes, `take_handling` and + `give_handling`, and `io_error::not_a_terminal`, on Linux and Windows. The logging + plan can then color its levels. +2. **Styles and painting:** `style`, `abilities_of`, `painter`, `paint`, and the cursor + and screen. +3. **Width:** the tool and the table. +4. **The canvas and boxes,** with `write_to`. +5. **The terminal:** raw mode, input, resizing, suspending, and `show`. +6. **Putting it back on every way out (decision 5),** in both compilers and both + runtimes. +7. **A "Terminals" section in the README.** + +## Found along the way + +- **`sys::poll` couldn't time out:** settled. It has taken a wait in milliseconds + since 2026-10-19. +- **`io_error` has nothing for `ENOTTY`,** which becomes `other`. +- **Nothing runs when a program stops** but `close`. A module's variable is never + closed, so a terminal kept in one would be left raw even when `main` returns. +- **A signal's handler can't be read back,** so a library that handles a signal for a + while can't give the program's own back. A handler is a `function` now, moved and + never copied, so it can't be read and left in place either. This plan adds + `sys::take_handling` and `sys::give_handling`, where it had `sys::handler_of`. +- **Interpolation can't call a type's method** to format it. A trait for that, as + `describable`, would let `$"{warn}"` write a style's sequence. It would be a change + to the language, in both compilers, so this plan works around it with `paint`. +- **`attribute` is taken** (2026-10-20). It's std's trait for the structs written after + `@`, so a program importing `std::term` had to write `term::attribute::bold`, in both + compilers. The enum is `effect` now, and a style's field `effects`. +- **A module's variable can't hold a reference,** since it needs a zero value. So the + shared painters paint `term::standard`, not `&mut writer`. +- **Union fields need `pub`** for a program to test them, as `ev is key(k)`. The + sketches had left it out. +- **Windows' `poll` sees a console as always ready,** since it peeks pipes, and a + console isn't one. +- **A signal watched for doesn't end a wait,** so the terminal handles `resized` + rather than watching for it. + +## Later, where wanted + +- **Inline frames:** a canvas shown below the shell's prompt, not on the alternate + screen, as a picker or a progress display does. It needs the cursor's position, + read through `CSI 6n`, whose answer looks like F3 with modifiers, and is told apart + only by waiting for it. +- **Widgets:** + - lists, tables and text fields; + - scrolling views; + - layout that splits a rect by constraints; + - a line editor with history, as readline is. +- **The kitty keyboard protocol,** for keys xterm's encoding can't tell apart, as + Ctrl-I from Tab, and for keys let go. +- **Hyperlinks** through `OSC 8`. +- **The terminal's colors,** read through `OSC 10` and `11`, to tell a light theme from + a dark one. +- **Grapheme clusters,** by Unicode's segmentation rules, once terminals agree on how + wide they are. +- **ASCII boxes,** for terminals without UTF-8. Also the Linux console's font, which + lacks heavy and rounded strokes. +- **Images,** through sixel or kitty's graphics. +- **terminfo,** for a `TERM` the built-in sequences don't suit. +- **The terminal's input on Windows,** where decision 11 leaves it for later. +- **Events from a thread:** a thread reading the terminal and sending its events + through a `thread::channel`, so a program waits on its own work and on input at + once. Resizes would still be noted in the thread the program began with. + +## Decisions for you + +1. **Where it lives:** + - **(a) `std::term`, in `std/term/` (recommended).** One import gives a program all + of it. Every program is checked with all of std anyway, so splitting it saves + nothing. + - **(b) `std::term` for styles, painting and the terminal, and `std::tui` for the + canvas and boxes.** The names say more, at the cost of two imports for a + full-screen program. + - **(c) Styles, painting and the terminal in std, and the canvas, boxes and widths + left to a library outside it.** Every program's check would pay for about 850 + fewer lines: about 2 ms less in the rebuild and 4 to 6 in C, at the clock + measured above. +2. **What it knows of terminals:** + - **(a) xterm's sequences, built in (recommended).** It's what the terminals in use + share, and what crossterm and termenv do. + - **(b) The terminfo database,** as curses reads it. Its entries lag what terminals + do, as with 24-bit color, and its files are a compiled format to read. + - **(c) (a), with terminfo for a `TERM` it doesn't know.** +3. **How color is decided:** + - **(a) From the handle and the environment, as "How each part works" orders it, + with colors brought down to what's found (recommended).** + - **(b) The program says,** and std never looks. Every program then repeats the + same checks, or writes color into files. + - **(c) Ask the terminal,** through its replies to queries. It's exact, but slow + over a network, and impossible through a pipe. +4. **How styled text is written:** + - **(a) Through a painter over any stream, with `paint` for interpolating + (recommended).** A painter knows what its stream shows, and writes a style only + where it changes. + - **(b) Only as text to interpolate,** as `$"{term::red}x{term::reset}"`. It's the + easiest to write, but colors reach files and pipes unless each program checks, + and nothing brings them down. + - **(c) Only through a `terminal`.** Ordinary output, such as the logging plan's, + couldn't be colored. +5. **When the program stops without closing the terminal:** + - **(a) The runtime and both VMs put it back, from a record std keeps + (recommended).** This covers `exit`, faults, `abort`, failed contracts, and a + terminal kept in a module's variable. It adds two intrinsics to each compiler. + - **(b) Only `close`.** A fault leaves the shell in raw mode, on the alternate + screen, with the mouse reported, until the user types `reset`. + - **(c) (b), with `terminate` and `hangup` handled while the terminal is open.** + That covers being killed politely, but not faults. +6. **Input:** + - **(a) Keys, text, the mouse, pasting, focus and resizing, read with a timeout + (recommended).** + - **(b) Keys and resizing only,** with the mouse and pasting later. + - **(c) None:** output only. Full-screen programs would read bytes themselves. +7. **How wide text is:** + - **(a) A table of each character's width, from Unicode 16 (recommended).** It's + what `wcwidth` does and what terminals do, for about 4 KB. + - **(b) Every character is one column.** No table is needed, but Chinese, + Japanese, Korean and emoji break the layout. + - **(c) Grapheme clusters,** with Unicode's segmentation rules too. It's more + exact where terminals agree, which they don't yet for emoji sequences, and it + needs a second, larger table. +8. **What draws the screen:** + - **(a) A canvas the program draws whole each frame, of which std writes only the + changes (recommended).** It's as ratatui and tcell work. The program keeps its + own state, and draws from it. + - **(b) Widgets std keeps,** which the program changes, and which redraw what they + cover, as curses' windows do. It's more API, and state in two places. + - **(c) No canvas:** programs draw with the painter's cursor moves. There's less to + build, but every program works out what changed itself, and boxes can't join. +9. **Boxes that meet:** + - **(a) Joined, from the lines each cell holds (recommended).** + - **(b) Each box writes its own glyphs, and the last drawn wins.** It's simpler, + but boxes sharing an edge show broken corners. +10. **Places on the screen:** + - **(a) From 0, column first, as `rect` is (recommended).** It's as drawing in + most libraries is, and the sequences' rows and columns from 1 stay inside std. + - **(b) From 1, row first, as the sequences number them.** It matches what a + terminal's documentation says, but not `rect`, `size` or the mouse's columns. +11. **Windows,** which std has supported since 2026-10-19. Whatever is chosen, each + operation `std::sys` gains exists there too, since std is checked whole for an + executable for Windows, and one missing there is an error in every such check + (probed in both compilers): + - **(a) Output now, input later (recommended).** `is_terminal`, the size, and + virtual terminal processing, so painters and `canvas::write_to` color a console + as they do a terminal, and the logging plan's levels with them. `terminal::open` + gives `io_error::unsupported` there until raw input, a wait on the console, and + resizing are built. About 80 lines. + - **(b) All of it now,** with raw input through `ENABLE_VIRTUAL_TERMINAL_INPUT`, a + wait on the console's handle, and resizes found by reading the size at each + `next`. It's more code, and none of it can be probed here. + - **(c) Linux only.** Each new operation gives `unsupported` on Windows, and + `is_terminal` false, so nothing is colored there. diff --git a/entry.sakura b/entry.sakura new file mode 100644 index 00000000..1100b018 --- /dev/null +++ b/entry.sakura @@ -0,0 +1,864 @@ +#! @file entry.sakura +#! @author John Christman (sorakatadzuma@gmail.com) +#! @copyright Malunal Studios, LLC. +#! @license MIT +#! +#! Contains the entry of the rebuild as a program, whose subcommands lex, parse, +#! and check the files they are given as one program, print what they note, +#! and where asked, lower it to intermediate code, run it, or build it, or serve +#! the language server protocol. It reads its arguments through `std::args`, +#! so `sakura --help`, and `--help` after each subcommand, say what each takes: +#! +#! sakura check [OPTIONS] FILE... +#! sakura run [OPTIONS] FILE... [-- ARGUMENT...] +#! sakura build [OPTIONS] -o OUTPUT FILE... +#! sakura lsp [OPTIONS] +#! +#! The rebuild runs itself as `sakura run LIBS entry.sakura -- COMMAND ...`. +#! LIBS gives a `--lib` for each library it reads: its own `sakura::analyzer`, +#! `sakura::compiler`, `sakura::machine`, `sakura::native`, and +#! `sakura::server`, in the folders of their names; the standard library, as +#! `std`, in its repository beside this one; and the back end's +#! `binary::amd64`, `binary::elf`, `binary::dwarf`, `binary::pe`, and +#! `binary::pdb`, as `docs/later.md` lists them. +#! +#! A program reads the modules of the standard library its files refer to, +#! from the folder `--lib std=DIR` names, else a `std` folder beside the +#! executable or in the nearest folder above it, as `core` is found, else the +#! libraries of std in the `share/sakura` folder nearest above it, where +#! `blossom install` puts them, as `std.io`. The runtime, the module and folder +#! `runtime` found beside the compiler or above it as `core` and `system` are, +#! is only part of executables, as its files say with `when backend == native`. +#! `--lib NAME=DIR` names another library, the module `NAME` as the directory, +#! which may be within another module, as `std::yaml` or `sakura::analyzer`; +#! its modules are read where the files refer to them, as the standard +#! library's are, and `lsp` takes it too. +#! Programs are checked for the system the rebuild runs on, Linux or Windows, +#! or with `--target` for an executable of the target. +#! +#! `check` says how many notes it made; `--lower` also lowers the program, +#! verifies each function's code, and says how much it made and what it could +#! not lower, `--ir` prints the code of each function too, `--bytecode` the +#! machine's code of each, and `--only NAME` only that of the functions of the +#! name, each leaving out the functions nothing reaches once the program is +#! optimized, as a build makes no code of them. `--all` lowers every function, +#! not only those `main` reaches, and keeps them all. The code is checked as +#! `run`'s is, or, with `--target`, as `build`'s is, unless `--checks` or +#! `--fast` says otherwise. `--checks-report` lowers the program checked and +#! optimized, and lists the checks the optimizer could not leave out, in the +#! program's own functions, by line: where an unchecked build trusts the +#! program. +#! +#! A program is checked or not. A checked one stops at an index past the end, +#! the wrong field of a union read, an integer converted to an enum none of +#! whose members has its value, and a `match` finding no arm, with what went +#! wrong and where, as std's containers stop where they are asked for what they +#! do not hold. One that is not checked does none of that, as C does, which +#! `checking()` tells the program. Every program stops at null reached through, +#! at a division by zero, and as its stack runs out; only a checked executable +#! compares an address with null where it reaches past the first page. `run` +#! checks, unless `--fast`, and `build` does not, unless `--checks`. +#! +#! `run` runs the program, giving it the arguments after `--`, and exits with +#! what it exits with. `--checks` also checks every read and write through a +#! reference or pointer, stopping where the program holds no memory there, +#! holds back the blocks it releases so that using one stops it, and reports +#! the blocks it never released as it ends, by where each was allocated. Its +#! code is optimized no more than `-O1` would, since inlining may leave out +#! the frames a dangling reference refers to. +#! +#! `build` writes an x86-64 executable of the program to the file `-o` names, +#! with the runtime compiled into it. One for Windows is named with `.exe` +#! added where `-o` names no extension. `-g` also writes the debugging +#! information debuggers such as gdb read to show where the program is, its +#! functions, those inlined, and, built with `-O0`, its variables: on Linux to +#! OUTPUT.petal, which the executable names, so debuggers find it beside it, +#! and on Windows into the executable itself. +#! +#! `lsp` serves the language server protocol over the standard input and +#! output, checking every `.sakura` file of the editor's workspace with the +#! standard library, as the files change. Where several files declare `main`, +#! the program of the one last opened, edited, or asked about is checked, +#! leaving out the others. +#! +#! `-O0`, `-O1` and `-O2` say how much the code is optimized, `-O2` where none +#! is given. `--inline N` inlines functions of up to N instructions rather than +#! 16. `--verify` verifies the code of each function once it is lowered and +#! after each pass, as `--lower` does, and in a build replays where each +#! function's values were placed. +#! +#! `--threads N`, or `-j N`, says how many threads compile the program: one on +#! each processor, up to eight, where it says 0 or nothing. They open and read +#! the files, each lexing and parsing a file of its own; optimize the functions, +#! each once those it calls are; assemble the machine's code of each function +#! for `run`; and place the values of the functions for `build`, ahead of the +#! one thread choosing their code. What is made is the same however many there +#! are. While the files are read and checked, a thread of its own reports what +#! is noted, as each thread making a note tells it, in the order the notes +#! would be made by one thread alone. `-j 1` starts no thread at all. + +import std::args; +import std::io; +import system; +import std::thread; +import sakura::analyzer; +import sakura::compiler; +import sakura::machine; +import sakura::native; +import sakura::server; + +#! The subcommands of the rebuild. +@args::command{ name = "sakura", help = "Checks, runs, and builds Sakura programs, and serves editors." } +union commands { + @args::command{ help = "Checks the files as one program, and lowers it where asked." } + var check: check_args; + @args::command{ help = "Checks the files, then runs their `main` on the machine." } + var run: run_args; + @args::command{ help = "Checks the files, then writes an executable of them." } + var build: build_args; + @args::command{ help = "Serves the language server protocol over the standard input and output." } + var lsp: lsp_args; +} + +#! How much the code is optimized. +enum optimization: u8 { + @choice{ name = "0", help = "Not at all but for copying `@inline` functions, keeping every named local in a cell of its own." } none, + @choice{ name = "1", help = "Within each function." } local, + @choice{ name = "2", help = "Inlining small functions too." } inlined, +} + +#! Whether a program's contracts are checked. +enum contracting: u8 { + @choice{ name = "on", help = "Each is checked where it is, as where none is said." } on, + @choice{ name = "off", help = "Each is left out, conditions and all." } off, +} + +#! What an executable is built for. +enum platform: u8 { + @choice{ name = "linux-x86_64", help = "Linux on x86-64." } linux, + @choice{ name = "windows-x86_64", help = "Windows on x86-64." } windows, +} + +#! Where a program's libraries are, and where the files it read are written, +#! which `check`, `run`, and `build` say alike. +@group +struct reading_args { + @option{ name = "lib", value = "NAME=DIR", help = "A library, the module of the name, as `json` or `std::yaml`, in the directory, as blossom gives a package; given again for each." } + var libraries: vector; + @option{ value = "FILE", help = "Writes the path of each file the program read to the file, one to a line." } + var deps: strview; +} + +#! What `check` takes. +@args::command +struct check_args { + @group + var reading: reading_args; + @option{ help = "Checks the files for an executable of the target, rather than the machine." } + var target: maybe; + @option{ short = 'O', value = "LEVEL", help = "How much the code is optimized where it is lowered." } + var optimize: optimization = optimization::inlined; + @option{ name = "inline", value = "N", help = "Inlines functions of up to N instructions." } + var inline_limit: u32 = compiler::inline_limit; + @option{ help = "Verifies the code of each function once it is lowered and after each pass." } + var verify: bool; + @option{ help = "Lowers the program, and says how much it made and what it could not lower." } + var lower: bool; + @option{ help = "Lowers the program, and prints the code of each function." } + var ir: bool; + @option{ help = "Lowers the program, and prints the machine's code of each function." } + var bytecode: bool; + @option{ help = "Lowers every function, not only those `main` reaches." } + var all: bool; + @option{ value = "NAME", help = "Prints only the code of the functions of the name." } + var only: strview; + @option{ value = "on|off", help = "Whether the contracts the code lowered has are checked, or left out." } + var contracts: contracting = contracting::on; + @option{ help = "Lowers the code checked, as `run` and `build --checks` make it, where `--target` would not." } + var checks: bool; + @option{ help = "Lowers the code unchecked, as `run --fast` and `build` make it, where it would be checked." } + var fast: bool; + @option{ help = "Lowers the program checked and optimized, and lists the checks left in its own functions, by line." } + var checks_report: bool; + @option{ short = 'j', value = "N", help = "How many threads compile the program at once, or 0 for one on each processor, up to 8." } + var threads: u32; + @argument{ value = "FILE", help = "The files of the program." } + var files: vector; +} + +#! How much the code is optimized, which `run` and `build` say alike. `check` +#! says it of the code it lowers, so it declares these options itself. +@group +struct optimizing { + @option{ short = 'O', value = "LEVEL", help = "How much the code is optimized." } + var optimize: optimization = optimization::inlined; + @option{ name = "inline", value = "N", help = "Inlines functions of up to N instructions." } + var inline_limit: u32 = compiler::inline_limit; +} + +#! What `run` takes. +@args::command +struct run_args { + @group + var reading: reading_args; + @group + var optimizing: optimizing; + @option{ help = "Verifies the code of each function once it is lowered and after each pass." } + var verify: bool; + @option{ help = "Also checks every read and write through a reference or pointer, stopping where the program holds no memory, and reports the blocks it never released as it ends." } + var checks: bool; + @option{ help = "Leaves out what a checked program checks, as indexes, as a build without `--checks` does." } + var fast: bool; + @option{ help = "Interprets every function, compiling none to the processor's code as the machine does where it runs on Windows." } + var interpret: bool; + @option{ value = "on|off", help = "Whether the program's contracts are checked as it runs, or left out." } + var contracts: contracting = contracting::on; + @option{ short = 'j', value = "N", help = "How many threads compile the program at once, or 0 for one on each processor, up to 8." } + var threads: u32; + @argument{ value = "FILE", help = "The files of the program." } + var files: vector; + @argument{ value = "ARGUMENT", rest = true, help = "What the program's `main` is given." } + var arguments: vector; +} + +#! What `build` takes. +@args::command +struct build_args { + @group + var reading: reading_args; + @option{ help = "What the executable is for, rather than the system the rebuild runs on." } + var target: maybe; + @group + var optimizing: optimizing; + @option{ help = "Verifies the code of each function, and replays where its values were placed." } + var verify: bool; + @option{ short = 'g', help = "Also writes debugging information: beside a Linux executable, and into a Windows one." } + var debug: bool; + @option{ help = "Checks indexes, the field a union holds, and the rest, as `run` does, stopping where one fails." } + var checks: bool; + @option{ value = "on|off", help = "Whether the program's contracts are checked as it runs, or left out." } + var contracts: contracting = contracting::on; + @option{ short = 'o', value = "OUTPUT", required = true, help = "Where the executable is written." } + var output: strview; + @option{ short = 'j', value = "N", help = "How many threads compile the program at once, or 0 for one on each processor, up to 8." } + var threads: u32; + @argument{ value = "FILE", help = "The files of the program." } + var files: vector; +} + +#! What `lsp` takes. +@args::command +struct lsp_args { + @option{ name = "lib", value = "NAME=DIR", help = "A library, the module of the name, as `json` or `std::yaml`, in the directory; given again for each." } + var libraries: vector; + @option{ help = "Checks the workspace for an executable of the target, rather than the machine." } + var target: maybe; + @option{ help = "Serves over the standard input and output, which is the only way it serves." } + var stdio: bool; +} + +def main(args: span): void { + # Windows cannot start a copy of the server, so the processes it works its + # jobs out in are this program started again: `lsp --base`, holding the + # workspace parsed, and `lsp --worker`, working out a job from nothing. + when os == windows { + if args.length == 2 && args[0] == "lsp" && (args[1] == "--base" || args[1] == "--worker") { + exit(serve_process(args[1] == "--base")); + } + } + + val chosen := args::parse_or_exit::(args); + match chosen { + check(&c) => exit(work(&job { + lowers = c.lower || c.ir || c.bytecode || c.checks_report, prints = c.ir, codes = c.bytecode, all = c.all, + verify = c.verify, native = c.target is some(_), system = system_of(c.target), + level = c.optimize as u32, inline_limit = c.inline_limit, only = c.only, contracts_off = c.contracts == contracting::off, + checks_off = !c.checks_report && (c.fast || (c.target is some(_) && !c.checks)), + reports = c.checks_report, opposed = c.checks && c.fast, + libraries = c.reading.libraries.view(), deps = c.reading.deps, threads = threads_of(c.threads), files = c.files.view() + })); + run(&r) => exit(work(&job { + runs = true, verify = r.verify, checks = r.checks, contracts_off = r.contracts == contracting::off, + checks_off = r.fast, opposed = r.checks && r.fast, interpret = r.interpret, + system = host_system, level = r.optimizing.optimize as u32, + inline_limit = r.optimizing.inline_limit, libraries = r.reading.libraries.view(), + deps = r.reading.deps, threads = threads_of(r.threads), files = r.files.view(), given = r.arguments.view() + })); + build(&b) => exit(work(&job { + builds = true, + verify = b.verify, + debug = b.debug, + contracts_off = b.contracts == contracting::off, + checks_off = !b.checks, + native = true, + system = system_of(b.target), + level = b.optimizing.optimize as u32, + inline_limit = b.optimizing.inline_limit, + libraries = b.reading.libraries.view(), + deps = b.reading.deps, + output = b.output, + threads = threads_of(b.threads), + files = b.files.view() + })); + lsp(&l) => exit(serve_lsp(&l)); + } +} + +#! What a subcommand asks of the files it is given, as its options say. +struct job { + var runs: bool; #! Whether the program is run. + var builds: bool; #! Whether an executable of it is written. + var lowers: bool; #! Whether it is lowered, and how much it made is said. + var prints: bool; #! Whether the code of each function is printed. + var codes: bool; #! Whether the machine's code of each function is printed. + var all: bool; #! Whether every function is lowered. + var verify: bool; #! Whether the code of each function is verified. + var checks: bool; #! Whether what references and pointers reach is checked as the program runs. + var interpret: bool; #! Whether the machine interprets every function, compiling none. + var checks_off: bool; #! Whether the program is lowered unchecked, leaving out indexes' checks and the rest. + var opposed: bool; #! Whether `--checks` and `--fast` were both given. + var reports: bool; #! Whether the checks the optimizer left are listed. + var contracts_off: bool; #! Whether contracts are left out, conditions and all. + var debug: bool; #! Whether debugging information is written. + var native: bool; #! Whether it is checked for an executable. + var system: strview; #! The operating system it is checked for, as `linux`. + var level: u32; #! How much the code is optimized. + var inline_limit: u32; #! The most instructions of a function inlined, or 0 for the default. + var threads: u32; #! How many threads compile the program, the first among them. + var only: strview; #! The name of the functions whose code alone is printed, or empty. + var libraries: span; #! The libraries `--lib` names, each as `NAME=DIR`. + var deps: strview; #! Where the path of each file read is written, or empty. + var output: strview; #! Where an executable is written. + var files: span; #! The files of the program. + var given: span; #! What the program's `main` is given. +} + +#! How many threads compile a program where `--threads` asks for none in +#! particular, at most. Every thread takes the same lock for the memory it +#! takes from the heap, so more than these mostly wait on one another. +val most_threads: u32 = 8; + +#! How many threads compile a program: those asked for, or one on each +#! processor, up to `most_threads`, where 0 is. +#! @param asked How many `--threads` asks for. +#! @returns How many. +def threads_of(asked: u32): u32 { + return asked if asked != 0; + val processors := thread::cpu_count(); + return processors < most_threads ? processors : most_threads; +} + +#! The operating system a target is for, or the one the rebuild runs on where +#! none is given. +#! @param chosen The target, or nothing. +#! @returns The system, as `linux`. +def system_of(chosen: maybe): strview { + if chosen is some(which) { + return which == platform::linux ? "linux" : "windows"; + } + return host_system; +} + +#! Checks the files of a program, and where a subcommand asks, lowers it, runs +#! it, or builds it. +#! @param asked What the subcommand asks. +#! @returns The status to exit with. +def work(asked: &job): i32 { + if asked.opposed { + system::fd::stderr.put("sakura: `--fast` leaves out the checks `--checks` asks for, so only one of them is given\n"); + return 2; + } + var paths := vector::::new(); + for &each in asked.files { + paths.append(string::from(each, nothing {})); + } + return 2 if !libraries_named(asked.libraries); + val found := found_std(asked.libraries); + val core := toolchain_folder("core"); + if core.length == 0 { + system::fd::stderr.put("sakura: no `core` folder is beside the compiler or above it, and every program reads one\n"); + return 2; + } + var output := string::from(asked.output, nothing {}); + # Windows runs a program by its name alone only where the name ends in `.exe`. + if asked.builds && asked.system == "windows" && !has_extension(output.view()) { + output.append(".exe"); + } + # The program's files are read, then `core`, whole, the types the syntax + # makes first, then the modules of `system`, those `--lib` names, and the + # standard library found, that the files read refer to, a round at a time, + # until a round refers to nothing new. A library given first is the one + # read, so one `--lib` names is read rather than one found. An executable + # has the runtime too, from the folder `runtime`, which needs nothing of the + # library. + val runtime := toolchain_folder("runtime"); + if asked.builds && runtime.length == 0 { + system::fd::stderr.put("sakura: no `runtime` folder is beside the compiler or above it, and every executable is built with its runtime\n"); + return 2; + } + var finder := resolver::new(); + finder.whole("core", core.view()); + val platform := toolchain_folder("system"); + if platform.length != 0 { + finder.add_library("system", platform.view()); + } + if runtime.length != 0 { + finder.add_library("runtime", runtime.view()); + } + for each in asked.libraries { + val split := each.index_of(&'=') else { continue; }; + finder.add_library(each.substr(0, split), each.substr(split + 1, each.length - split - 1)); + } + for &each in found { + val split := each.view().index_of(&'=') else { continue; }; + finder.add_library(each.view().substr(0, split), each.view().substr(split + 1, each.length - split - 1)); + } + paths.append(string::from(builtin_path, nothing {})); + every_file(core.view(), &mut paths); + for &each in paths { + finder.mark(each.view()); + } + if asked.builds { + finder.want("runtime", &mut paths); + } + + var names := names::new(); + var notes := vector::::new(); + var sources := vector::::new(); + var syntaxes := vector::::new(); + var roots := vector::::new(); + + # Each file's source and syntax stay where they are once the checker, and the + # thread reporting notes, refer to them, so there is room for every file the + # libraries hold before any is read. + val room := paths.length + finder.files_held(); + sources.resize(room); + syntaxes.reserve(room); + for _ in 0..room { + syntaxes.append(syntax::new()); + } + + # What reading and checking note is reported as it is noted, rather than + # kept: by a thread of its own, where there are threads, which the threads + # reading the files and the one checking them tell each note as they make + # it, and on the thread making it where there are none. + val errors := asked.runs || asked.builds; + var noted := atomic::::new(0); + var warned := atomic::::new(0); + var told := thread::channel::::new(0); + var reporting := vector::>::new(); + var alone := asked.threads <= 1; + if !alone { + alone = !start(def() { report_notes(&mut told, &sources, errors); }, &mut reporting); + } + val hear := def(made: &mut note): void { + _ = made.warning ? warned.fetch_add(1) : noted.fetch_add(1); + if alone { + report_note(made, &sources, errors); + } else { + _ = told.send(news { noted = move(made) }); + } + }; + val heard := listener { + noted = hear, + read = def(file: u32): void { + if !alone { + _ = told.send(news { read = file }); + } + } + }; + # Each round's sources are opened on as many threads as there are, each into + # its place, then read, and what they refer to is the next round. + var done: u64 = 0; + while done < paths.length { + val from := done; + val to := paths.length; + share_out(to - from, asked.threads, def(k: u64): void { + val j := from + k; + if paths[j].view() == builtin_path { + sources.set(j, source::from(builtin_path, builtin_text)); + } else { + sources.set(j, source::open(paths[j].view())); + } + }); + read_files(&sources, &mut syntaxes, &mut roots, &mut names, asked.threads, &heard, from, to); + for j in from..to { + finder.refer(syntaxes.at(j), &names, &mut paths); + } + done = to; + } + if asked.deps.length != 0 && !write_deps(asked.deps, paths.view()) { + system::fd::stderr.put($"sakura: the files read could not be written to {asked.deps}\n"); + } + + # A program is checked once, so what an edit would check again is not + # recorded. + var checker := checker::new(&mut names, &mut notes); + checker.sink.heard = hear; + checker.tracks = false; + checker.contracts_off = asked.contracts_off; + checker.checks_off = asked.checks_off; + target_checker(&mut checker, asked.system, asked.builds || asked.native); + for j in 0..paths.length { + checker.add(sources.at(j), syntaxes.at(j), roots.at(j)); + } + checker.check(); + + # What checking leaves to evaluating is evaluated once the program checks, + # which notes what goes wrong as checking does. + var results := outcomes::new(); + if noted.load() == 0 { + results = evaluate(&mut checker); + } + + # Nothing more is noted, so the reporting ends once it has reported what was. + # What the checking lowering asks for might note is kept rather than heard, + # as it was never reported, and lowering says what went wrong itself. + _ = told.send(news { ended = nothing {} }); + for &mut each in reporting { + each.join(); + } + checker.sink.heard = nothing {}; + val count := noted.load(); + + val runs := asked.runs; + val builds := asked.builds; + if (runs || builds) && count != 0 { + return 2; + } + if !runs && !builds { + println($"{count} notes, {warned.load()} warnings, {checker.skipped} unchecked, {checker.decls.count} declarations, {checker.types.count} types"); + } + # Notes end a check with 2, as they end a run or a build, so what runs it, as + # blossom does, knows it failed. + return 2 if count != 0; + return 0 if !asked.lowers && !runs && !builds; + + val options := lowering { + verify = asked.verify || asked.lowers, + checks = asked.checks, + everything = asked.all, + # A run checking its memory inlines nothing, so each function's locals end + # where its frame does, as a reference to one past it finds. + level = asked.checks && asked.level > 1 ? 1 : asked.level, + keep_locals = asked.level == 0, + describe = builds && asked.debug, + inline_limit = asked.inline_limit, + threads = asked.threads + }; + var lowered := lowerer::new(&mut checker, options); + lowered.evaluated = move(&mut results); + lowered.compile(); + if builds { + for &each in lowered.problems { + system::fd::stderr.put($"{each}\n"); + } + if lowered.problems.length != 0 { + return 2; + } + val made := build_executable(&mut lowered, build_options { + output = output.view(), verify = asked.verify, debug = asked.debug, windows = asked.system == "windows", + threads = asked.threads + }); + for &each in made { + system::fd::stderr.put($"sakura: {each}\n"); + } + return made.length != 0 ? 2 : 0; + } + if runs { + for &each in lowered.problems { + system::fd::stderr.put($"{each}\n"); + } + if lowered.problems.length != 0 { + return 2; + } + lowered.drop_unreached_functions(); + return run_program(&mut lowered, asked.given, asked.checks, asked.interpret); + } + + # What a run or a build would drop is left out, so what is said is what they + # would make code of. + lowered.drop_unreached_functions(); + if asked.reports { + report_checks(&mut lowered, &sources); + return 0; + } + if asked.codes { + lowered.assemble_all(); + } + var kept: u64 = 0; + var instructions: u64 = 0; + for &each in lowered.program.functions { + continue if !each.lowered; + kept++; + instructions += each.body.insts.length - 1; + continue if (!asked.prints && !asked.codes) || (asked.only.length != 0 && each.name.view() != asked.only); + println($"function {each.name}:"); + if asked.prints { + print(each.body.print()); + } + if asked.codes { + print(each.compiled.print()); + } + } + for &each in lowered.problems { + println(each); + } + println($"{kept} functions, {instructions} instructions, {lowered.program.layouts.length} layouts, {lowered.problems.length} problems"); + return 0; +} + +#! The words `--checks-report` names each kind of check by, one and many. +const check_names: strview[checked::count as u64] = ["index", "union field", "enum value", "fault"]; +const checks_names: strview[checked::count as u64] = ["indexes", "union fields", "enum values", "faults"]; + +#! Lists the checks the optimizer left in the program's own functions, as +#! `--checks-report` asks: a line for each line of a function's source that +#! makes any, with how many of each kind, then how many in all. +#! @param lowered The program, lowered and optimized. +#! @param sources The source of each file. +def report_checks(lowered: &mut lowerer, sources: &vector): void { + val left := lowered.checks_left(); + var total: u64 = 0; + var lines: u64 = 0; + var i: u64 = 0; + while i < left.length { + val first := left[i]; + val held := &sources.at(pair_high(first.at) as u64 - 1); + val line := held.lines.place_of(pair_low(first.at)).line; + var counts: u64[checked::count as u64]; + while i < left.length && left[i].function == first.function && left[i].at >> 32 == first.at >> 32 + && held.lines.place_of(pair_low(left[i].at)).line == line { + counts[left[i].kind as u64] += left[i].count as u64; + total += left[i].count as u64; + i++; + } + var text := $"{held.path}:{line}: {lowered.program.functions[first.function].name}:"; + var listed := false; + for k in 0..counts.length { + continue if counts[k] == 0; + text.append(listed ? ", " : " "); + text.append($"{counts[k]} {counts[k] == 1 ? check_names[k] : checks_names[k]}"); + listed = true; + } + println(text); + lines++; + } + println($"{total} {total == 1 ? "check" : "checks"} at {lines} {lines == 1 ? "line" : "lines"}"); +} + +#! What the thread reporting what reading and checking a program note is told. +union news { + var noted: note; #! A note, as it was made. + var read: u32; #! That the file of the index was read whole, so nothing more is noted of reading it. + var ended: nothing; #! That nothing more is noted. +} + +#! Reports what reading and checking a program note, as the threads making the +#! notes tell them, until told nothing more is. They are reported in the order +#! they would be were the files read one after another: those of each file +#! once every file before it was read whole, which holds those of a file read +#! beside an earlier one until that one is, and those of checking, which +#! begins once every file is read, as they come. +#! @param told What the threads making the notes tell. +#! @param sources The source of each file. +#! @param errors Whether they are reported to the standard error, rather +#! than the standard output. +def report_notes(told: &mut thread::channel, sources: &vector, errors: bool): void { + val count := sources.length; + var read := vector::::new(); + read.resize(count); + var next: u64 = 0; + var held := vector::::new(); + while true { + var item := told.receive() else { return; }; + if item is noted(&mut each) { + if each.file as u64 <= next { + report_note(each, sources, errors); + } else { + held.append(move(each)); + } + } else if item is read(file) { + read[file as u64] = true; + while next < count && read[next] { + next++; + var kept := vector::::new(); + for &mut each in held { + if each.file as u64 == next { + report_note(each, sources, errors); + } else { + kept.append(move(each)); + } + } + held = move(&mut kept); + } + } else { + return; + } + } +} + +#! Starts a thread running a function. +#! @param body What it runs. +#! @param into Where its handle is kept. +#! @returns Whether it started. +def start(body: def(): void, into: &mut vector>): bool { + var made := thread::spawn(body) else (_) { return false; }; + into.append(move(&mut made)); + return true; +} + +#! Reports a note: where it is, what kind of mistake it is about, and what it +#! says. +#! @param each The note. +#! @param sources The source of each file. +#! @param errors Whether it is reported to the standard error, rather than +#! the standard output. +def report_note(each: ¬e, sources: &vector, errors: bool): void { + val held := &sources.at(each.file); + val at := held.lines.place_of(each.offset); + var line := each.warning ? $"{held.path}:{at.line}:{at.column}: warning: {each.code}: " + : $"{held.path}:{at.line}:{at.column}: {each.code}: "; + val text := note_text(each, held); + line.append(text.view()); + if errors { + system::fd::stderr.put($"{line}\n"); + } else { + println(line); + } +} + +#! Serves the language server protocol, checking for the target given, or for +#! the machine. +#! @param asked What `lsp` takes. +#! @returns The status to exit with. +def serve_lsp(asked: &lsp_args): i32 { + return 2 if !libraries_named(asked.libraries.view()); + val found := found_std(asked.libraries.view()); + var libraries := vector::::new(); + for each in asked.libraries { + libraries.append(each); + } + for &each in found { + libraries.append(each.view()); + } + return serve(server_options { + native = asked.target is some(_), system = system_of(asked.target), libraries = libraries.view() + }); +} + +#! Whether each library `--lib` names is written `NAME=DIR`, of a module's name +#! and a directory, saying which is not. +#! @param given The libraries, as written. +#! @returns Whether each is. +def libraries_named(given: span): bool { + for each in given { + val split := each.index_of(&'=') else { + system::fd::stderr.put($"sakura: `--lib {each}` names no library: write `NAME=DIR`\n"); + return false; + }; + if !is_module_path(each.substr(0, split)) { + system::fd::stderr.put($"sakura: `--lib {each}` names no module: write its path, as `json` or `std::yaml`\n"); + return false; + } + if !is_folder(each.substr(split + 1, each.length - split - 1)) { + system::fd::stderr.put($"sakura: `--lib {each}` names no library: write `NAME=DIR`, of a directory\n"); + return false; + } + } + return true; +} + +#! Whether text is a module's path: names, each of letters, digits, and +#! underscores, not beginning with a digit, between `::`. +#! @param text The text. +#! @returns Whether it is. +def is_module_path(text: strview): bool { + var at: u64 = 0; + while true { + return false if at >= text.length || text[at].is_digit; + val start := at; + while at < text.length && (text[at].is_alnum || text[at] == '_') { + at++; + } + return false if at == start; + return true if at == text.length; + return false if text.length - at < 3 || text[at] != ':' || text[at + 1] != ':'; + at += 2; + } + return false; +} + +#! Whether the last name of a path has an extension, as `.exe`, which a name +#! only beginning with a dot does not. +#! @param at The path. +#! @returns Whether it does. +def has_extension(at: strview): bool { + var name := 0u; + for i in 0..at.length { + if at[i] == '/' || at[i] == '\\' { + name = i + 1; + } + } + for i in name + 1..at.length { + return true if at[i] == '.'; + } + return false; +} + +when os == linux { + # The system the rebuild runs on, which programs are checked for where no + # target is given. + val host_system: strview = "linux"; +} + +when os == windows { + # The system the rebuild runs on, which programs are checked for where no + # target is given. + val host_system: strview = "windows"; +} + +#! Runs a program lowered, reporting a fault as the C machine does. +#! @param lowered The program. +#! @param args The arguments `main` is given. +#! @param checks Whether its memory is checked, as `run --checks` asks. +#! @param interpret Whether every function is interpreted, as `run --interpret` asks. +#! @returns The status to exit with: what the program asked for, 1 where it +#! faulted, and 0 otherwise. +def run_program(lowered: &mut lowerer, args: span, checks: bool, interpret: bool): i32 { + var running := interpreter::new(lowered, interpreting { checks = checks, interpret = interpret }); + val why := running.run(args); + # Running with its memory checked, what the program never released is + # reported as it ends, by exiting or returning from `main`. + if checks && (why == halt::exited || why == halt::none) { + var leaks := string::new(nothing {}); + running.report_leaks(&mut leaks); + system::fd::stderr.put(leaks.view()); + } + if why == halt::exited { + return running.status; + } + if why != halt::none { + var text := string::new(nothing {}); + running.report(why, &mut text); + system::fd::stderr.put(text.view()); + return 1; + } + return 0; +} + +#! Writes the path of each file a program read, one to a line, as `--deps` asks. +#! @param at Where they are written. +#! @param paths The paths, of which the types the syntax makes, which no file +#! holds, are left out. +#! @returns Whether they were written. +def write_deps(at: strview, paths: span): bool { + var text := string::new(nothing {}); + for &each in paths { + continue if each.view() == builtin_path; + text.append(each.view()); + text.push('\n'); + } + var found := path::parse(at) else (_) { return false; }; + return io::write_file(&found, text.view()) is value(_); +} diff --git a/machine/README.md b/machine/README.md new file mode 100644 index 00000000..2d0d1ab6 --- /dev/null +++ b/machine/README.md @@ -0,0 +1,241 @@ +# sakura::machine + +`sakura::machine` is the virtual machine Sakura programs run on with +`sakura run`. It runs the code `sakura::compiler` assembles for each function. +It has its own stack of frames of words, the program's globals and data, and a +heap of the blocks the program allocates and releases. Addresses are real ones, +so a pointer reaches memory as it is, and the machine calls the system and C +as an executable does. The compiler also runs it to compute constants while +compiling. + +## Using it + +Require this repository, which exports each of the compiler's libraries, and name this +one among a target's `deps` with the analyzer and the compiler, which it reads itself: + +```yaml +requires: +- https://git.malunal.studio/sakura/std@v1.0.0 +- https://git.malunal.studio/sakura/sakurac@v1.0.0 + +targets: +- name: app + type: program + deps: [sakura.analyzer, sakura.compiler, sakura.machine, std.io] +``` + +Running a program as `sakura run` does: + +```sakura +import std::io; +import sakura::analyzer; +import sakura::compiler; +import sakura::machine; + +# Runs a program as `sakura run` does, and gives the status it ended with. Its +# files are read, then `core` whole, then the modules of `system` and `std` that +# they refer to, a round at a time. The program is checked, its constants +# evaluated, and it is lowered, optimized, and run on the machine. +def run(files: span, core: strview, system: strview, library: strview, args: span): i32 { + var finder := resolver::new(); + finder.whole("core", core); + finder.add_library("system", system); + finder.add_library("std", library); + var paths := vector::::new(); + for each in files { + paths.append(string::from(each, nothing {})); + } + paths.append(string::from(builtin_path, nothing {})); + every_file(core, &mut paths); + for &each in paths { + finder.mark(each.view()); + } + + var names := names::new(); + var notes := vector::::new(); + var sources := vector::::new(); + var syntaxes := vector::::new(); + var roots := vector::::new(); + # The checker refers to each source and syntax, so there is room for every + # file the libraries hold before any is read, and none moves. + val room := paths.length + finder.files_held(); + sources.reserve(room); + syntaxes.reserve(room); + for i in 0..room { + break if i == paths.length; + val at := paths[i].view(); + sources.append(at == builtin_path ? source::from(at, builtin_text) : source::open(at)); + syntaxes.append(syntax::new()); + var lexing := lexer::new(sources.at(i), &mut names, &mut notes, i as u32); + lexing.tokenize_all(syntaxes.at(i)); + var parsing := parser::new(syntaxes.at(i), &names, &mut notes, i as u32); + roots.append(parsing.parse()); + finder.refer(syntaxes.at(i), &names, &mut paths); # Adds the files it refers to. + } + + var checker := checker::new(&mut names, &mut notes); + for i in 0..paths.length { + checker.add(sources.at(i), syntaxes.at(i), roots.at(i)); + } + checker.check(); + var results := outcomes::new(); + if notes.length == 0 { + results = evaluate(&mut checker); + } + for &each in notes { + val held := &sources.at(each.file); + val at := held.lines.place_of(each.offset); + println($"{held.path}:{at.line}:{at.column}: {each.code}: {each.message(held)}"); + } + return 2 if notes.length != 0; + + var lowered := lowerer::new(&mut checker, lowering { level = 2 }); + lowered.evaluated = move(&mut results); + lowered.compile(); + for &each in lowered.problems { + println(each); + } + return 2 if lowered.problems.length != 0; + lowered.drop_unreached_functions(); + + var running := interpreter::new(&mut lowered, interpreting { checks = false }); + val why := running.run(args); + return running.status if why == halt::exited; + if why != halt::none { + var report := string::new(nothing {}); + running.report(why, &mut report); + print(report); + return 1; + } + return 0; +} +``` + +`core` and `system` are the folders beside the `sakura` executable, and `std` +is its standard library. The program is checked for Linux unless the checker's +`target` is given another system. + +## Embedding it + +A program embeds the machine to run code it compiles as it runs, as a game runs +its scripts. It compiles as `run` above does, lowering what it calls besides +`main`: every function, with `lowering::everything`, or those `main` gives the +host as values, which are kept. It then begins the program and calls its +functions itself, which call the host's own functions in turn: + +```sakura +# What the program calls the host by: a foreign declaration of a name, as C's +# are declared, which the host provides. +# extern module game when os == windows; +# pub def spawn_at(x: f64, y: f64): u64; + +def spawn_at(x: f64, y: f64): u64 { ... } # the host's own + +var running := interpreter::new(&mut lowered, interpreting{ capture = true, steps = 10000000 }); +val given: cfn = spawn_at; +running.provide("spawn_at", given as u64); # before `begin`, or after, which replaces it +if running.begin() != halt::none { ... } # the C it calls found, the globals given their values + +var args: u64[2] = [state, f64_bits(0.016)]; # a word each: integers, pointers, references, a float's f64 bits +val why := running.call(update, args[:]); # or `call_value`, given a function value's two words +if why != halt::none { + var report := string::new(nothing {}); + running.report(why, &mut report); # the fault, and where each function was +} +val got := running.result(0); # the first word it returned +val said := running.take_output(); # what it printed +``` + +- **Calls**: `call` calls a function by its index among the program's, given + the words of its parameters as a call passes them: a word for each integer, + bool, pointer, and reference, an `f64` for each float, `f32`s too, the words + of a value held in words, and the address of the bytes of one passed in + memory, which is copied. A result held in memory is written where `call` is + told; one held in words is `result`'s. A function value's first word is one + more than its function, and its second what a closure uses, which + `call_value` takes, so a program gives its host a function as a value. +- **The host's functions**: `provide` gives a foreign declaration's name an + address of the host's, found before any library's, which the program calls as + it calls C, so a `cfn` of a function of the host's own is one. A host function + may call back into the program: that call runs above the calls under way, and + where it faults they stop too, as the host returns to them, the trace naming + each. The machine calls C only where the system running it is Windows. +- **Steps**: `interpreting::steps` stops `begin`, `run`, and each call the host + makes once it takes that many steps, jumps and calls, with `step_limit`, as a + program looping forever would; the next call has as many again. +- **Output**: with `interpreting::capture`, what the program writes to its + output and error is kept for `take_output`, on Windows through `WriteFile` + and `WriteConsoleW` too. +- **Memory**: the program and its host share their memory, so a host may lend + the program its own data, as a pointer, and read what the program made. What + the program allocates the machine releases as it closes, so the host keeps no + block of the program's past it, and the program releases none of the host's. + +`hearth::scripting`, of hearth, embeds the machine this way. + +## What it holds + +- **The machine**: `interpreter`, made of a lowered program and its + `interpreting` options. `run` calls `main` with the arguments given, and + `begin`, `call`, and `call_value` let a host call the program's functions + itself. The result is a `halt`: how the program stopped, as by `exit` or a + fault, with `status` holding its exit status. + - `report` writes a fault and where each running function was, in the same + form as an executable's fault report. + - With `checks`, as `run --checks` asks, each read and write through a + reference or pointer is checked, and `report_leaks` lists the blocks + nothing reaches. +- **Compiled code**: where the machine runs as an executable on Windows, as + `sakurac` and a host embedding it do, `jit.sakura` compiles each function to + x86-64 the first time it is called, through the encoder in `x86.sakura`, and + runs that rather than interpreting it. It is interpreted instead while + constants are evaluated, where memory is checked, and where + `interpreting::interpret` asks, as `run --interpret` does. + - Compiled code keeps the interpreter's frames, call records, and halts, so + compiled and interpreted functions call each other, a fault's trace is the + same, and a host's calls, C calling back, threads, and `steps` work as they + do interpreted. + - Each operation becomes the instructions doing its work. The words a + function reads and writes most, loops weighing most, are held in registers + over the code from where each is first used to where it is last: integers + in `rsi`, `rdi`, `r13`, and `rbp`, and reals in `xmm6` to `xmm15`, a word + every value of which is a single's held as the single, so `f32` arithmetic + is the processor's arithmetic of singles. + - Calls of compiled functions are calls of the processor. A call of C whose + arguments and result are each a word calls C directly; other calls of C, + and what the interpreter runs rarely, as formatting, allocating, and the + system, call the machine's own `slow_op`, as the interpreter does, through + code keeping `xmm6` to `xmm15`, which the machine's own code does not keep. + - Steps are counted in a register, settled with what the host allows and a + thread's turn as they run out and around calls of the machine's own code. + - Where the system's stack of the thread running is within 128 KiB of its + end, calls are interpreted, which take only the machine's stack. + - On the benchmarks of `docs/performance.md`, compiled code runs integer and + memory work within 1.0 to 1.5 times built code's time, and `f32` work + within 2 to 4 times, where the interpreter takes 4 to 27 times. +- **The heap**: the blocks the program allocates and releases. With checks, + released blocks are held back a while, so a late use still finds them + released. +- **Threads**: each thread of the program is a thread of the system. They take + turns running code, so they run at the same time but not in parallel. +- **The system and C**: the program's system calls, its environment, and its + signals, whose handlers run at the program's safe points. On Windows, it + calls C through code it makes that follows Microsoft's x86-64 ABI. +- **Constants**: `evaluate` runs the program that computes a checked + program's constants, each constant once, before the ones that read it, and + gives the `outcomes` that lowering takes. + +## Testing + +From the repository's root, `blossom test` runs them as `sakura.machine.tests`, or: + +```sh +sakurac run --lib sakura::analyzer=analyzer --lib sakura::compiler=compiler \ + --lib sakura::machine=machine tests/main.sakura tests/machine/*.sakura +``` + +The tests are declared within the module. Each runs a small program, written +over a small `core` of its own, and compares what it wrote and how it stopped +with what is expected. `sakura.machine.native` runs the same tests built as an +executable, where the machine compiles what it runs, and the corpus, +`sakurac.corpus`, runs every program of `tests/programs` compiled so too. diff --git a/machine/atomics.sakura b/machine/atomics.sakura new file mode 100644 index 00000000..67cf5de6 --- /dev/null +++ b/machine/atomics.sakura @@ -0,0 +1,65 @@ +#! @file atomics.sakura +#! @author John Christman (sorakatadzuma@gmail.com) +#! @copyright Malunal Studios, LLC. +#! @license MIT +#! +#! Contains the atomics the machine works on the program's memory, with +#! `core::atomic`, so that they are atomic where processes share the memory, as +#! the program built as an executable's are. The machine runs one thread, so it +#! works every order as `seq_cst`, which is never weaker than what is asked. + +import sakura::compiler; +module sakura::machine; + + +#! Works an atomic operation on the integer at an address. +#! @param address The address. +#! @param operation The operation, as `atomic_` numbers them. +#! @param imm The access and sign, as an `atomic` instruction holds them. +#! @param a The first operand, of a store, an exchange, or a +#! combining operation, or what a compare-exchange expects. +#! @param b What a compare-exchange writes. +#! @returns What the address held, as a word the machine holds the access as. +pub def atomically(address: u64, operation: u32, imm: u64, a: u64, b: u64): u64 { + val signed := atomic_signed(imm); + return match atomic_access(imm) { + access::i8, access::u8 => signed ? atomic_on::(address, operation, a, b) : atomic_on::(address, operation, a, b), + access::i16, access::u16 => signed ? atomic_on::(address, operation, a, b) : atomic_on::(address, operation, a, b), + access::i32, access::u32 => signed ? atomic_on::(address, operation, a, b) : atomic_on::(address, operation, a, b), + else => signed ? atomic_on::(address, operation, a, b) : atomic_on::(address, operation, a, b) + }; +} + +# Works an atomic operation on the `T` at an address, giving what it held, +# widened to a word by its sign, as the machine holds it. +def atomic_on(address: u64, operation: u32, a: u64, b: u64): u64 where T: integer, lockfree { + val cell := address as *mut atomic; + var got: T = 0; + if operation == atomic_load { + got = cell[0].load(); + } else if operation == atomic_store { + cell[0].store(a as T); + } else if operation == atomic_exchange { + got = cell[0].exchange(a as T); + } else if operation == atomic_compare_exchange { + match cell[0].compare_exchange(a as T, b as T) { + value(held) => got = held; + error(held) => got = held; + } + } else if operation == atomic_add { + got = cell[0].fetch_add(a as T); + } else if operation == atomic_sub { + got = cell[0].fetch_sub(a as T); + } else if operation == atomic_and { + got = cell[0].fetch_and(a as T); + } else if operation == atomic_or { + got = cell[0].fetch_or(a as T); + } else if operation == atomic_xor { + got = cell[0].fetch_xor(a as T); + } else if operation == atomic_min { + got = cell[0].fetch_min(a as T); + } else { + got = cell[0].fetch_max(a as T); + } + return (got as i64) as u64; +} diff --git a/machine/evaluation.sakura b/machine/evaluation.sakura new file mode 100644 index 00000000..f866da63 --- /dev/null +++ b/machine/evaluation.sakura @@ -0,0 +1,548 @@ +#! @file evaluation.sakura +#! @author John Christman (sorakatadzuma@gmail.com) +#! @copyright Malunal Studios, LLC. +#! @license MIT +#! +#! Contains constant evaluation, which runs once a program checks: a program +#! computing its constants, and the conditions of the `if const` statements the +#! checker left undecided, is lowered and run in the machine, as +#! `sources/evaluator.c` does. Each `compile_error` the checker left to it is +#! then reported where the branches around it are those chosen, with its text +#! worked out last, where the checker could not read it. +#! +#! Each evaluation runs from its start. Reading a constant not yet evaluated +#! stops it, so that constant is evaluated first and the run begins again. A +#! constant keeps its value, and the memory it points into, which the program +#! is given as data; what a run allocated and the value does not keep must have +#! been released, since nothing of the program would hold it. What goes wrong is +#! noted at the constant, as the checker notes what it finds. + +import sakura::analyzer; +import sakura::compiler; +module sakura::machine; + + +#! How far each evaluation got. +enum progress : u8 { + pending, #! Not run yet. + running, #! Running, or waiting for another it reads. + done, #! Done, its value kept. + failed, #! Stopped, which was noted. +} + +#! How deeply constants may depend on one another, and values point into +#! memory pointing into memory. +const deepest_chain: u64 = 256; + +#! The steps, as jumps and calls, each run of an evaluation may take. +const evaluation_budget: u64 = 16777216; + +#! Evaluates what checking left to evaluating, noting what goes wrong as the +#! checker notes what it finds. +#! @param checker The checker, which checked the program without notes. +#! @returns What was worked out. +pub def evaluate(checker: &mut checker): outcomes { + var made := outcomes::new(); + var lowered := lowerer::new(checker, lowering { verify = true, evaluating = true }); + lowered.compile(); + return made if lowered.evaluations.length == 0; + if lowered.problems.length != 0 { + for i in 0..lowered.problems.length { + var text := string::from("Evaluating could not lower this program: ", nothing {}); + text.append(lowered.problems[i].view()); + lowered.report_evaluation(0xFFFFFFFF, &mut text); + } + return made; + } + + var running := interpreter::new(&mut lowered, interpreting { evaluating = true }); + val count := running.c.evaluations.length; + running.ready.resize(count); + var states := vector::::new(); + states.resize(count); + for i in 0..count { + # The text of a `compile_error` waits for the branches around it. + continue if running.c.evaluations[i].text; + running.evaluate_one(i as u32, 0, &mut states, &mut made); + } + running.report_held(&mut states, &mut made); + return made; +} + +#! Reports each `compile_error` the checker left to evaluating whose branches +#! of `if const` are each the one its condition chose, evaluating its text +#! first where the checker could not read it. +#! @param this The machine. +#! @param states How far each evaluation got. +#! @param out What was worked out. +def interpreter::report_held(&mut this, states: &mut vector, out: &mut outcomes): void { + for i in 0..this.c.checker.held_errors.length { + val held := &this.c.checker.held_errors[i]; + var chosen := true; + for b in held.first..held.first + held.count { + val branch: checker::branch = this.c.checker.held_branches[b as u64]; + if out.decisions.get(&node_key(branch.table, branch.node)) is some(holds) { + chosen = chosen && holds == branch.holds; + } else { + chosen = false; + } + } + continue if !chosen; + + var text := string::new(nothing {}); + if held.computed { + val key := node_key(held.table, held.node); + val index := this.c.evaluation_ids.get(&key) else { continue; }; + continue if !this.evaluate_one(index, 0, states, out); + text.append(out.texts[key].view()); + } + this.c.checker.report_held(i as u32, &mut text); + } +} + +#! Notes what went wrong evaluating, at the constant or condition. +#! @param this The compiler of the program evaluating. +#! @param index The evaluation, or `none` for none in particular. +#! @param text What the note says. +pub def lowerer::report_evaluation(&mut this, index: u32, text: &mut string): void { + val saved := this.checker.at; + var file: u32 = 0; + var node: u32 = 0; + if (index as u64) < this.evaluations.length { + val held: evaluation = this.evaluations[index]; + if held.decl != 0 { + file = this.checker.decls.files.p[held.decl]; + node = this.checker.decls.nodes.p[held.decl]; + } else { + file = this.checker.tables.p[held.table].file; + node = held.node; + } + } + this.checker.at.instance = 0; + this.checker.report_in(file, node, ec::constant, text.view()); + this.checker.at = saved; +} + +#! What a note names an evaluation as: a constant by its name, or the +#! condition of `if const`. +#! @param this The compiler. +#! @param index The evaluation. +#! @returns The name. +def lowerer::evaluation_name(&mut this, index: u32): string { + val held: evaluation = this.evaluations[index]; + return string::from("the condition of `if const`", nothing {}) if held.condition; + return string::from("the text of `compile_error`", nothing {}) if held.text; + return $"`{this.program.functions[held.function].name}`"; +} + +#! Evaluates one constant or condition, evaluating first those its run stops +#! at, and keeps what it worked out. +#! @param this The machine. +#! @param index The evaluation. +#! @param depth How many evaluations wait for it. +#! @param states How far each evaluation got. +#! @param out Where what is worked out is kept. +#! @returns Whether it was evaluated. +def interpreter::evaluate_one(&mut this, index: u32, depth: u64, states: &mut vector, out: &mut outcomes): bool { + val state: progress = states[index]; + return state == progress::done if state == progress::done || state == progress::failed; + if depth > deepest_chain { + var text := string::from("Constants depend on one another too deeply to evaluate.", nothing {}); + this.c.report_evaluation(index, &mut text); + states[index] = progress::failed; + return false; + } + + states[index] = progress::running; + val held: evaluation = this.c.evaluations[index]; + var kept := evaluated { + bytes = vector::::new(), + addresses = vector::::new(), + blocks = vector::::new() + }; + while true { + this.budget = evaluation_budget; + val why := this.invoke(held.function, span::::empty()); + + # A run that finished keeps its value before anything is released, since + # the memory the value points into is memory the run still holds. + if why == halt::none && !held.condition { + if !this.keep_value(index, &mut kept) { + this.release_unkept(); + states[index] = progress::failed; + return false; + } + } + + # What a run allocated and its value does not keep, nothing of the program + # holds once it is done. + val leaked := this.release_unkept(); + if why == halt::none && leaked != 0 { + var text := $"Evaluating {this.c.evaluation_name(index)} allocated memory it neither released nor kept, {leaked} block"; + text.append(leaked == 1 ? "" : "s"); + text.append(" of it, which only a running program could hold."); + this.c.report_evaluation(index, &mut text); + states[index] = progress::failed; + return false; + } + break if why == halt::none; + + # A constant it reads is evaluated first, then it runs again from its start. + if why == halt::not_evaluated && (this.waiting as u64) < states.length { + if states[this.waiting] == progress::running { + var text := $"{this.c.evaluation_name(index)} depends on its own value, through the constants it reads."; + this.c.report_evaluation(index, &mut text); + states[index] = progress::failed; + return false; + } + if !this.evaluate_one(this.waiting, depth + 1, states, out) { + states[index] = progress::failed; + return false; + } + continue; + } + + var text := $"Evaluating {this.c.evaluation_name(index)} stopped: {this.why_text(why)}"; + for &each in this.trace { + text.append($"\n at {each.function} ({each.path}:{each.line}:{each.column})"); + } + this.c.report_evaluation(index, &mut text); + this.fault_text.clear(); + states[index] = progress::failed; + return false; + } + + # A constant keeps its value, a condition whether it holds, and text what + # it says, read through the memory its value kept. + if held.condition { + val word := ((this.globals as u64 + held.offset) as *u8)[0]; + out.decisions.set(held.key, word != 0); + } else if held.text { + out.texts.set(held.key, this.text_at(this.globals as u64 + held.offset, held.kind)); + } else { + out.values.set(held.key, move(&mut kept)); + } + this.ready[index] = true; + states[index] = progress::done; + return true; +} + +#! The text a value holds, as a `strview` or a `string` does, copied from where +#! its bytes are. +#! @param this The machine. +#! @param at Where the value is. +#! @param kind Its type. +#! @returns The text, or empty text where the value holds none. +def interpreter::text_at(&mut this, at: u64, kind: u32): string { + var made := string::new(nothing {}); + val layout := this.c.layout_of(kind); + val shape := this.c.layout_at(layout); + return made if !shape.texts; + val begins := this.c.field_at(layout, shape.text); + val many := this.c.field_at(layout, shape.text + 1); + val data := ((at + begins.offset) as *u64)[0]; + if data != 0 { + made.append(span::::over(data as *u8, ((at + many.offset) as *u64)[0])); + } + return made; +} + +#! Releases the blocks a run allocated that no value evaluated keeps. +#! @param this The machine. +#! @returns How many were released. +def interpreter::release_unkept(&mut this): u64 { + var gone := vector::::new(); + for &entry in this.blocks { + if !this.kept.contains(&entry.key) { + gone.append(entry.key); + } + } + for &each in gone { + this.release(each); + } + return gone.length; +} + +#! What keeping a value finds: the units of memory it reaches, the value first. +struct keeping { + var units: vector; #! The value, then each block of memory it points into. + var bases: vector; #! Where each unit's memory was, so memory reached twice is kept once. + var blocks: vector; #! Whether each unit is memory the run allocated. + var failed: bool; #! Whether the value cannot be kept, which was noted. +} + +#! Keeps the value an evaluation computed: its bytes, laid out as its type is, +#! with the memory it points into. +#! @param this The machine. +#! @param index The evaluation. +#! @param out Where the value is kept. +#! @returns Whether it could be, which a note says where it could not. +def interpreter::keep_value(&mut this, index: u32, out: &mut evaluated): bool { + val held: evaluation = this.c.evaluations[index]; + val layout := this.c.layout_of(held.kind); + val size := this.c.layout_at(layout).size; + var work := keeping { + units = vector::::new(), + bases = vector::::new(), + blocks = vector::::new() + }; + this.add_unit(&mut work, this.globals as u64 + held.offset, size, 0, false); + this.walk(index, &mut work, 0, 0, layout, 0); + return false if work.failed; + + # Addresses name the blocks past the value, which is not one of them. + for &mut unit in work.units { + for &mut each in unit.addresses { + if each.block != no_block && each.block != in_constant { + each.block = each.block - 1; + } + } + } + out.bytes = move(&mut work.units[0].bytes); + out.addresses = move(&mut work.units[0].addresses); + out.blocks.clear(); + for u in 1..work.units.length { + out.blocks.append(move(&mut work.units[u])); + } + return true; +} + +#! Adds a unit holding a copy of memory. +#! @param this The machine. +#! @param work What keeping found so far. +#! @param from Where the memory is. +#! @param size How many bytes it holds. +#! @param base Where it begins, so memory reached twice is kept once, or 0. +#! @param block Whether it is memory the run allocated. +#! @returns The unit's index. +def interpreter::add_unit(&mut this, work: &mut keeping, from: u64, size: u64, base: u64, block: bool): u32 { + var bytes := vector::::new(); + bytes.resize(size); + if size != 0 { + memcpy(bytes.slice().data, from as *u8, size); + } + work.units.append(kept_block { bytes = move(&mut bytes), addresses = vector::::new() }); + work.bases.append(base); + work.blocks.append(block); + return (work.units.length - 1) as u32; +} + +#! Notes that a value holds the address of memory only the compiler has. +#! @param this The machine. +#! @param index The evaluation. +#! @param work What keeping found so far. +def interpreter::escaped(&mut this, index: u32, work: &mut keeping): void { + return if work.failed; + work.failed = true; + var text := this.c.evaluation_name(index); + text.append(" holds the address of memory only the compiler has, such as a variable of the value being computed or memory already released, which goes away once it has run. A constant keeps the memory it allocated and still holds, and the bytes of text, which the program is given again."); + this.c.report_evaluation(index, &mut text); +} + +#! Whether values of a layout hold addresses, so their bytes are walked rather +#! than simply kept. +#! @param this The machine. +#! @param layout The layout. +#! @param depth How deeply within values it is. +#! @returns Whether they do. +def interpreter::holds_addresses(&mut this, layout: u32, depth: u64): bool { + return false if depth > deepest_chain; + val shape := this.c.layout_at(layout); + return match shape.kind { + lk::pointer, lk::reference, lk::trait_reference, lk::function => true, + lk::fixed => this.holds_addresses(shape.element - 1, depth + 1), + lk::record, lk::variant => this.fields_hold_addresses(layout, &shape, depth), + else => false + }; +} + +#! Whether any field of a struct or union holds addresses. +#! @param this The machine. +#! @param layout The layout. +#! @param shape The layout itself. +#! @param depth How deeply within values it is. +#! @returns Whether any does. +def interpreter::fields_hold_addresses(&mut this, layout: u32, shape: &layout, depth: u64): bool { + for i in 0..shape.count { + val field := this.c.field_at(layout, i as u32); + return true if this.holds_addresses(field.layout, depth + 1); + } + return false; +} + +#! Walks bytes of a unit laid out as a layout, keeping the memory each address +#! within them points into, and noting where each address is. +#! @param this The machine. +#! @param index The evaluation. +#! @param work What keeping found so far. +#! @param unit The unit. +#! @param at Where the value is within it. +#! @param layout The value's layout. +#! @param depth How deeply within values it is. +def interpreter::walk(&mut this, index: u32, work: &mut keeping, unit: u32, at: u64, layout: u32, depth: u64): void { + return if work.failed; + if depth > deepest_chain { + work.failed = true; + var text := string::from("The value points into memory that points into memory too deeply to keep.", nothing {}); + this.c.report_evaluation(index, &mut text); + return; + } + + val shape := this.c.layout_at(layout); + val bytes := work.units[unit].bytes.view().data; + match shape.kind { + lk::pointer, lk::reference => { + val word := ((bytes as u64 + at) as *u64)[0]; + return if word == 0; + var addend: u64 = 0; + + # Another constant's value is data of the program already, so an address + # into it is kept as one into that data, which keeps nothing more. + var other: u32 = 0; + if this.constant_at(index, word, &mut other, &mut addend) { + val held: evaluation = this.c.evaluations[other]; + work.units[unit].addresses.append(kept_address { + at = at, block = in_constant, addend = addend, decl = held.decl, table = held.table, node = held.node + }); + return; + } + val target := this.promote(index, work, word, shape.element, depth, &mut addend); + return if work.failed; + work.units[unit].addresses.append(kept_address { at = at, block = target, addend = addend }); + } + # A trait reference holds a vtable of the program evaluating, and a function + # value a closure's locals, neither of which outlives the run. + lk::trait_reference => this.escaped(index, work); + lk::function => { + val function := ((bytes as u64 + at) as *u64)[0]; + if ((bytes as u64 + at + word_size) as *u64)[0] != 0 { + this.escaped(index, work); + return; + } + return if function == 0 || function - 1 >= this.c.program.functions.length; + val named := &this.c.program.functions[function - 1]; + var made := kept_address { at = at, block = no_block, decl = named.decl, instance = named.instance }; + if named.decl == 0 { + made.table = named.table; + made.node = named.node; + made.file = named.file; + } + work.units[unit].addresses.append(made); + } + lk::fixed => { + val size := this.c.layout_at(shape.element - 1).size; + for i in 0..shape.count { + this.walk(index, work, unit, at + i as u64 * size, shape.element - 1, depth + 1); + } + } + lk::record => { + for i in 0..shape.count { + val field := this.c.field_at(layout, i as u32); + this.walk(index, work, unit, at + field.offset, field.layout, depth + 1); + } + } + lk::variant => { + # A union holds the one its tag gives, and the bytes of the rest mean nothing. + val tag := held_field(&shape, ((bytes as u64 + at) as *u64)[0]); + if tag < shape.count as u64 { + val field := this.c.field_at(layout, tag as u32); + this.walk(index, work, unit, at + field.offset, field.layout, depth + 1); + } + } + else => {} + } +} + +#! Whether an address points into the value of another constant, one evaluated +#! already, giving which and how far into it, where it does. An address just +#! past the end of one, as an empty view's may be, is of that one where no value +#! holds it. +#! @param this The machine. +#! @param index The evaluation whose value holds the address. +#! @param address The address. +#! @param found Where the constant's evaluation is written. +#! @param addend Where how far into its value the address points is written. +#! @returns Whether it does. +def interpreter::constant_at(&mut this, index: u32, address: u64, found: &mut u32, addend: &mut u64): bool { + var past := false; + for i in 0..this.c.evaluations.length { + continue if i == index as u64 || !this.ready[i]; + val other: evaluation = this.c.evaluations[i]; + continue if other.condition; + val base := this.globals as u64 + other.offset; + val size := this.c.layout_at(this.c.layout_of(other.kind)).size; + if address >= base && address < base + size { + found = i as u32; + addend = address - base; + return true; + } + if !past && address == base + size && size != 0 { + found = i as u32; + addend = size; + past = true; + } + } + return past; +} + +#! Keeps the memory an address points into, giving the unit it became and how +#! far into it the address points: memory the run allocated and still holds, +#! which stays held for the rest of the evaluating, or the bytes of a datum. +#! Memory anywhere else is the compiler's own, which is noted. +#! @param this The machine. +#! @param index The evaluation. +#! @param work What keeping found so far. +#! @param address The address. +#! @param element One more than the layout of what it points at, or 0. +#! @param depth How deeply within values it is. +#! @param addend Where how far into the memory it points is written. +#! @returns The unit. +def interpreter::promote(&mut this, index: u32, work: &mut keeping, address: u64, element: u32, depth: u64, addend: &mut u64): u32 { + var base: u64 = 0; + var size: u64 = 0; + var block := false; + for &entry in this.blocks { + if address >= entry.key && address < entry.key + entry.value + 1 { + base = entry.key; + size = entry.value; + block = true; + break; + } + } + if !block { + for i in 0..this.data.length { + val data: u64 = this.data[i]; + val length := this.c.program.data[i].bytes.length; + if address >= data && address < data + length { + base = data; + size = length == 0 ? 0 : length - 1; + break; + } + } + } + if base == 0 { + this.escaped(index, work); + return 0; + } + + addend = address - base; + for u in 1..work.units.length { + return u as u32 if work.bases[u] == base; + } + val unit := this.add_unit(work, base, size, base, block); + if block { + this.kept.set(base, true); + } + + # What the memory holds is read as a run of the elements the address gives, + # since memory of no elements, as that of text, holds no addresses. + return unit if element == 0; + val shape := this.c.layout_at(element - 1); + return unit if shape.size == 0 || !this.holds_addresses(element - 1, 0); + var at: u64 = 0; + while at + shape.size <= size && !work.failed { + this.walk(index, work, unit, at, element - 1, depth + 1); + at += shape.size; + } + return unit; +} diff --git a/machine/foreign.sakura b/machine/foreign.sakura new file mode 100644 index 00000000..a255183f --- /dev/null +++ b/machine/foreign.sakura @@ -0,0 +1,846 @@ +#! @file foreign.sakura +#! @author John Christman (sorakatadzuma@gmail.com) +#! @copyright Malunal Studios, LLC. +#! @license MIT +#! +#! Contains how the machine calls C, where the system running it is Windows, as +#! the C machine calls C there: with Microsoft's ABI of x86-64. A program +#! checked for Windows reaches the system through C, as `system` does there, +#! so the machine must call C to run it. +#! +#! C only calls an address, so the machine makes code of its own that a call of +#! C goes through: it loads the arguments the frame holds into the registers and +#! the stack as the ABI wants, calls the C function, and keeps the result. The +#! code is made once, in memory that is then only executed, and every signature +#! is called through the one block of code, since Microsoft's ABI is positional: +#! each of the first four arguments is loaded into both the integer register and +#! the SSE register of its position, so a float or an integer is where C reads +#! it either way. +#! +#! The libraries a program links are opened, and the C functions it calls by +#! name found, before it runs, in the library their file's `extern import` names, +#! or among what the machine's own process has where it names none. A library and a function +#! that cannot be found stop the program before it starts, at the declaration. +#! +#! Other threads run while C does, which C may wait for, so the machine lets go +#! of its turn around a call of C, as it does around a call of the system. Each +#! thread keeps what the last C function it called left for `GetLastError`, since +#! the machine's own work between a program's calls of C may leave another. + +import std::containers; +import std::io; +import system; +import sakura::compiler; +import system::windows; + +module sakura::machine; + + +when os == windows { + # How a call reads the arguments the frame holds and writes back the result. + # Its words are at offsets the code a call goes through is written with, so + # its layout is kept as it is: a word, then four words, then four words, then + # a word, a word, and four words. + struct c_call { + var function: u64; #! The C function called. + var integers: u64[4]; #! The argument of each position, as an integer. + var floats: u64[4]; #! The argument of each position, as a float. + var stack: u64; #! The arguments past the fourth, which the code copies to the stack. + var words: u64; #! How many. + var results: u64[4]; #! What C left in `rax`, `rdx`, `xmm0`, and `xmm1`. + } + + # The memory a call's stubs are committed in is read, written, then executed. + const page_commit: u32 = 0x3000; #! `MEM_COMMIT | MEM_RESERVE`. + const page_release: u32 = 0x8000; #! `MEM_RELEASE`. + const page_write: u32 = 0x04; #! `PAGE_READWRITE`. + const page_execute: u32 = 0x20; #! `PAGE_EXECUTE_READ`. + + # The code a call of C goes through: it takes the arguments a `c_call` holds, + # calls the C function at `function`, and writes the result back to `results`. + # The pointer to the `c_call` is in `rcx`, as the first argument is. The + # callee-saved registers Windows has C keep, `rbx`, `rsi`, and `rdi`, are kept, + # and `rsi` and `rdi` copy the stack. The stack is aligned to 16 bytes, with + # the 32 bytes C may keep its register arguments in left below the arguments. + const call_stub_code: u8[137] = [ + 0x55, 0x53, 0x56, 0x57, # push rbp; push rbx; push rsi; push rdi + 0x48, 0x89, 0xE5, # mov rbp, rsp + 0x48, 0x89, 0xCB, # mov rbx, rcx + 0x48, 0x8B, 0x4B, 0x50, # mov rcx, [rbx+80] ; words + 0x48, 0x89, 0xC8, # mov rax, rcx + 0x48, 0xC1, 0xE0, 0x03, # shl rax, 3 + 0x48, 0x29, 0xC4, # sub rsp, rax + 0x48, 0x83, 0xE4, 0xF0, # and rsp, -16 + 0x48, 0x8B, 0x73, 0x48, # mov rsi, [rbx+72] ; stack + 0x48, 0x89, 0xE7, # mov rdi, rsp + 0x48, 0xC1, 0xE1, 0x03, # shl rcx, 3 + 0xF3, 0xA4, # rep movsb + 0x48, 0x83, 0xEC, 0x20, # sub rsp, 32 ; the bytes C may keep registers in + 0x48, 0x8B, 0x43, 0x28, 0x66, 0x48, 0x0F, 0x6E, 0xC0, # mov rax,[rbx+40]; movq xmm0, rax + 0x48, 0x8B, 0x43, 0x30, 0x66, 0x48, 0x0F, 0x6E, 0xC8, # mov rax,[rbx+48]; movq xmm1, rax + 0x48, 0x8B, 0x43, 0x38, 0x66, 0x48, 0x0F, 0x6E, 0xD0, # mov rax,[rbx+56]; movq xmm2, rax + 0x48, 0x8B, 0x43, 0x40, 0x66, 0x48, 0x0F, 0x6E, 0xD8, # mov rax,[rbx+64]; movq xmm3, rax + 0x48, 0x8B, 0x4B, 0x08, # mov rcx, [rbx+8] + 0x48, 0x8B, 0x53, 0x10, # mov rdx, [rbx+16] + 0x4C, 0x8B, 0x43, 0x18, # mov r8, [rbx+24] + 0x4C, 0x8B, 0x4B, 0x20, # mov r9, [rbx+32] + 0x4C, 0x8B, 0x1B, # mov r11, [rbx] ; function + 0x41, 0xFF, 0xD3, # call r11 + 0x48, 0x89, 0x43, 0x58, # mov [rbx+88], rax + 0x48, 0x89, 0x53, 0x60, # mov [rbx+96], rdx + 0x66, 0x48, 0x0F, 0x7E, 0xC0, # movq rax, xmm0 + 0x48, 0x89, 0x43, 0x68, # mov [rbx+104], rax + 0x66, 0x48, 0x0F, 0x7E, 0xC8, # movq rax, xmm1 + 0x48, 0x89, 0x43, 0x70, # mov [rbx+112], rax + 0x48, 0x89, 0xEC, # mov rsp, rbp + 0x5F, 0x5E, 0x5B, 0x5D, # pop rdi; pop rsi; pop rbx; pop rbp + 0xC3 # ret + ]; + + # Writes text of ASCII, zero at its end, as C reads a name. + # @param text The text. + # @param into Where it is written, long enough for its bytes and a zero. + def c_name(text: strview, into: *mut u8): void { + for i in 0..text.length { + into[i] = text[i]; + } + into[text.length] = 0; + } + + # Writes text of UTF-8 as UTF-16, zero at its end, as C reads a wide name. + # @param text The text. + # @param into Where it is written. + # @param cap How many units it holds. + # @returns Whether it fit. + def wide_name(text: strview, into: *mut u16, cap: i32): bool { + val count := MultiByteToWideChar(65001, 0, text.data, text.length as i32, into, cap - 1); + return false if count <= 0 || count >= cap; + into[count as u64] = 0; + return true; + } + + # Finds a C function among what the machine's own process has: what its + # executable exports, then what each library loaded into it does. The library + # beneath the rest, `ntdll`, has a part of C's own that programs never link, so + # it is passed over. + # @param name The function's name, zero at its end. + # @returns Its address, or 0. + def find_symbol(name: *u8): u64 { + var found := GetProcAddress(GetModuleHandleW(null), name); + return found if found != 0; + + var wide: u16[16]; + val ntdll := wide_name("ntdll.dll", (&mut wide) as *mut u16, 16) ? GetModuleHandleW((&mut wide) as *u16) : 0; + var modules: u64[512]; + var needed: u32 = 0; + val process := GetCurrentProcess(); + if K32EnumProcessModules(process, (&mut modules) as *mut u64, 512 * 8, &mut needed) != 0 { + var count := needed as u64 / 8; + count = count < 512 ? count : 512; + for i in 0..count { + continue if modules[i] == ntdll; + found = GetProcAddress(modules[i], name); + break if found != 0; + } + } + return found; + } + + #! Finds each C function the program calls by name, before the program runs: + #! among those the host provides, then in the library its file's `extern + #! import` names, or among what the machine's own process has where it names + #! none. The first that cannot be found stops the program, with a trace at its + #! declaration. + #! @param this The machine. + #! @returns `none` where every one was found, `foreign_missing` where one was + #! not, or `out_of_memory`. + pub def interpreter::link_foreign(&mut this): halt { + return halt::none if this.foreign_found; + this.foreign_found = true; + val count := this.c.program.linked.length; + return halt::none if count == 0; + + this.symbols.resize(count); + this.libraries.resize(count); + var name_buffer: u8[1024]; + var wide: u16[1024]; + val name_ptr := (&mut name_buffer) as *mut u8; + val wide_ptr := (&mut wide) as *mut u16; + var libraries := interner::::new(); + var first_of := vector::::new(); # The first function of each library, by its ID. + for i in 0..count { + val entry := &this.c.program.linked[i]; + val name := this.c.checker.names.text(entry.name); + c_name(name, name_ptr); + + # What the host provides is found first, whatever library is named. + val given := this.provided_address(name); + val library := entry.library.view(); + if given != 0 { + this.symbols[i] = given; + } else if library.length == 0 { + this.symbols[i] = find_symbol(name_ptr); + } else { + # A library already opened for an earlier function is shared. + val id := libraries.intern_view(library) as u64; + if id == first_of.length { + first_of.append(i); + } + var handle: u64 = first_of[id] != i ? this.libraries[first_of[id]] : 0; + if handle == 0 && wide_name(library, wide_ptr, 1024) { + handle = LoadLibraryW(wide_ptr as *u16); + this.libraries[i] = handle; + } + this.symbols[i] = handle != 0 ? GetProcAddress(handle, name_ptr) : 0; + } + if name == "VirtualAlloc" { + this.maps_at = this.symbols[i]; + } else if name == "VirtualFree" { + this.unmaps_at = this.symbols[i]; + } else if name == "WriteFile" { + this.writes_at = this.symbols[i]; + } else if name == "WriteConsoleW" { + this.console_writes_at = this.symbols[i]; + } + continue if this.symbols[i] != 0; + + # The function, or the library holding it, was not found. + this.report_missing(entry.decl, name); + return halt::foreign_missing; + } + return halt::none; + } + + # Records a one frame trace at a foreign declaration, where its function was + # not found, as the C machine reports it. + # @param this The machine. + # @param decl The declaration. + # @param name The function's name. + def interpreter::report_missing(&mut this, decl: u32, name: strview): void { + this.trace.clear(); + var made := trace_frame { function = string::from(name, nothing {}) }; + val file: u32 = this.c.checker.decls.files.p[decl]; + if (file as u64) < this.c.checker.units.length { + val node: u32 = this.c.checker.decls.nodes.p[decl]; + val offset := this.c.node_offset(file, node); + val source := &this.c.checker.units[file].source; + val place := source.lines.place_of(offset); + made.path = source.path; + made.line = place.line; + made.column = place.column; + } + this.trace.append(move(&mut made)); + } + + # The head of the code C calls a function of the program through, up to the + # machine and the function it is baked with: it keeps the frame, takes 96 + # bytes, and spills the four register arguments, integer and SSE, into the + # words `machine_callback_entry` reads them from. + const callback_head: u8[71] = [ + 0x55, # push rbp + 0x48, 0x89, 0xE5, # mov rbp, rsp + 0x48, 0x81, 0xEC, 0x60, 0x00, 0x00, 0x00, # sub rsp, 96 + 0x48, 0x89, 0x4C, 0x24, 0x20, # mov [rsp+32], rcx + 0x48, 0x89, 0x54, 0x24, 0x28, # mov [rsp+40], rdx + 0x4C, 0x89, 0x44, 0x24, 0x30, # mov [rsp+48], r8 + 0x4C, 0x89, 0x4C, 0x24, 0x38, # mov [rsp+56], r9 + 0x66, 0x48, 0x0F, 0x7E, 0xC0, 0x48, 0x89, 0x44, 0x24, 0x40, # movq rax,xmm0; mov [rsp+64],rax + 0x66, 0x48, 0x0F, 0x7E, 0xC8, 0x48, 0x89, 0x44, 0x24, 0x48, # movq rax,xmm1; mov [rsp+72],rax + 0x66, 0x48, 0x0F, 0x7E, 0xD0, 0x48, 0x89, 0x44, 0x24, 0x50, # movq rax,xmm2; mov [rsp+80],rax + 0x66, 0x48, 0x0F, 0x7E, 0xD8, 0x48, 0x89, 0x44, 0x24, 0x58 # movq rax,xmm3; mov [rsp+88],rax + ]; + + # The tail: `machine_callback_entry` is called with the machine, the function, + # the registers, and the stack, then what it left where the registers were is + # given back to C in `rax` and `xmm0`. + const callback_tail: u8[19] = [ + 0xFF, 0xD0, # call rax + 0x48, 0x8B, 0x44, 0x24, 0x40, # mov rax, [rsp+64] + 0x66, 0x48, 0x0F, 0x6E, 0xC0, # movq xmm0, rax + 0x48, 0x8B, 0x44, 0x24, 0x20, # mov rax, [rsp+32] + 0xC9, # leave + 0xC3 # ret + ]; + + # Adds the code C calls a function of the program through: the head, the + # machine and the function baked in as `machine_callback_entry` takes them, + # where the registers and the stack are, the entry's address, then the tail. + # @param code The code made so far. + # @param machine The machine running the program. + # @param index The function. + # @param entry The address of `machine_callback_entry`. + def emit_callback(code: &mut byte_writer, machine: u64, index: u64, entry: u64): void { + var head := callback_head; + code.put(head[:]); + code.byte(0x48); code.byte(0xB9); code.u64(machine); # mov rcx, machine + code.byte(0x48); code.byte(0xBA); code.u64(index); # mov rdx, index + code.byte(0x4C); code.byte(0x8D); code.byte(0x44); code.byte(0x24); code.byte(0x20); # lea r8, [rsp+32] + code.byte(0x4C); code.byte(0x8D); code.byte(0x4D); code.byte(0x30); # lea r9, [rbp+48] + code.byte(0x48); code.byte(0xB8); code.u64(entry); # mov rax, entry + var tail := callback_tail; + code.put(tail[:]); + } + + # Makes the code a call of C goes through, and the code C calls each function + # of the program through, in memory that is then only executed, once it is + # first needed. + # @param this The machine. + # @returns Whether it was made. + def interpreter::make_stubs(&mut this): bool { + return true if this.call_stub != 0; + var code := byte_writer::new(); + var stub := call_stub_code; + code.put(stub[:]); + + val functions := this.c.program.functions.length; + this.callbacks.resize(functions); + val machine := this as *mut interpreter as u64; + val entry := callback_entry_address(); + for i in 0..functions { + continue if !this.c.program.functions[i].callback; + this.callbacks[i] = code.length; + emit_callback(&mut code, machine, i, entry); + } + + val size := round_up(code.length, 4096); + val memory := VirtualAlloc(0, size, page_commit, page_write); + if memory == 0 { + code.close(); + return false; + } + memcpy(memory as *mut u8, code.view().data, code.length); + code.close(); + var was: u32 = 0; + if VirtualProtect(memory, size, page_execute, &mut was) == 0 { + _ = VirtualFree(memory, 0, page_release); + return false; + } + _ = FlushInstructionCache(GetCurrentProcess(), memory, size); + this.call_stub = memory; + this.foreign_memory = memory; + this.foreign_size = size; + for i in 0..functions { + if this.c.program.functions[i].callback { + this.callbacks[i] = this.callbacks[i] + memory; + } + } + return true; + } + + #! Gives back the executable memory the stubs are in, and closes the libraries + #! opened, unless a thread is left waiting in C, which would come back through + #! the code and the library it called. + #! @param this The machine. + pub def interpreter::unlink_foreign(&mut this): void { + return if this.threads != null; + for i in 0..this.libraries.length { + if this.libraries[i] != 0 { + _ = FreeLibrary(this.libraries[i]); + } + } + if this.foreign_memory != 0 { + _ = VirtualFree(this.foreign_memory, 0, page_release); + this.foreign_memory = 0; + this.call_stub = 0; + } + } + + #! The address of a C function the program calls by name. + #! @param this The machine. + #! @param index The function among those the program links. + #! @returns Its address, or 0. + pub def interpreter::c_address(&mut this, index: u32): u64 { + return (index as u64) < this.symbols.length ? this.symbols[index] : 0; + } + + #! The address C calls a function of the program through, which was given + #! where a `cfn` is expected. + #! @param this The machine. + #! @param index The function. + #! @returns Its address, or 0 where the code could not be made. + pub def interpreter::callback_address(&mut this, index: u32): u64 { + return 0 if !this.make_stubs(); + return (index as u64) < this.callbacks.length ? this.callbacks[index] : 0; + } + + # The address C calls `machine_callback_entry` through, which the code C calls + # each function of the program through calls in turn. + def callback_entry_address(): u64 { + val entry: cfn = machine_callback_entry; + return entry as u64; + } + + #! Runs a function of the program that C calls, on the thread C calls it on, + #! which is the one the program called C on. It is given as a `cfn`, so the + #! machine's own compiler gives C the address of an entry calling it, and C + #! reaches it the same whether the machine is built into an executable or run + #! by another machine. + #! @param machine The machine, as the code baked it in. + #! @param index The function. + #! @param registers The four register arguments, integer then SSE. + #! @param stack The arguments past the fourth. + def machine_callback_entry(machine: u64, index: u64, registers: *mut u64, stack: *mut u64): void { + val running := machine as *mut interpreter; + running[0].run_callback(index as u32, registers, stack); + } + + # Runs a function of the program C called, in a turn of the thread's, which C + # called it without, as the C machine runs it: on the strand of the thread C + # called it on, or, on a thread C started itself, that of the thread the + # program began with, which the function leaves as it found it. The function + # finds what C left for `GetLastError`, and C finds what the function's own + # calls of C left once it returns. Where the program has no threads of its own + # and is calling no C, nothing is there to run it on, which stops the program. + # @param this The machine. + # @param index The function. + # @param registers The register arguments: four integers, then four floats. + # @param stack The arguments past the fourth. + def interpreter::run_callback(&mut this, index: u32, registers: *mut u64, stack: *mut u64): void { + # A function that faulted already stopped the program, so no later one runs. + return if this.foreign_fault != halt::none; + val left := GetLastError(); + if this.threads == null && this.calling_c == 0 { + system::fd::stderr.put($"sakura: runtime error: {halt::callback.describe()}\n"); + system::exit(1); + } + + val turns := this.threads != null; + if turns { + val stop := this.take_turn_on(system::thread_id()); + if stop != halt::none { + this.foreign_fault = stop; + this.pause(); + return; + } + } + this.last_error = left; + this.called_back(index, registers, stack); + val after := this.last_error; + if turns { + this.pause(); + } + SetLastError(after); + } + + # Takes the turn for C calling a function of the program back on a thread of + # the system, after every thread that asked before, then holds the strand of + # the program's thread it is, or, where C started the thread itself, that of + # the thread the program began with. + # @param this The machine. + # @param thread The number the system knows the thread by. + # @returns `elsewhere` where the program stopped meanwhile, or `none`. + def interpreter::take_turn_on(&mut this, thread: u64): halt { + val shared := this.threads; + val ticket := shared[0].next.fetch_add(1); + while true { + val now := shared[0].serving.load(); + if now == ticket { + break; + } + _ = system::futex_wait(((&mut shared[0].serving) as *mut atomic) as *mut u32, now, -1); + } + var mine := shared[0].strands[0]; + for i in 0..shared[0].strands.length { + if shared[0].strands[i][0].thread == thread { + mine = shared[0].strands[i]; + break; + } + } + this.restore(mine); + return shared[0].stopped ? halt::elsewhere : halt::none; + } + + # Runs a function of the program C called, placing the arguments C passed into + # its frame, and leaving its result where C reads it. A fault is kept, to stop + # the program once C comes back. + # @param this The machine. + # @param index The function. + # @param registers The register arguments: four integers, then four floats. + # @param stack The arguments past the fourth. + def interpreter::called_back(&mut this, index: u32, registers: *mut u64, stack: *mut u64): void { + val held := this.routines[index]; + val frame := this.top as *mut u64; + if this.top + held.frame > this.stack_end { + if this.foreign_fault == halt::none { + this.foreign_fault = halt::stack_overflow; + } + return; + } + memset(frame as *mut u8, 0, held.frame); + + val signature := this.c.program.functions[index].signature; + val sig := &this.c.program.signatures[signature]; + val result_shape := this.c.program.layouts[sig.result]; + val result_memory := in_memory(&result_shape); + val returned_memory := result_memory && result_shape.size != 0; + val result_hidden := result_memory && !micro_by_value(result_shape.size); + + var position: u64 = result_hidden ? 1 : 0; + for i in 0..sig.params.length { + val shape := this.c.program.layouts[sig.params[i]]; + val slot := this.params[held.params as u64 + i]; + val sse := shape.kind == lk::floating; + var eightbyte: u64 = 0; + if position < 4 { + eightbyte = sse ? registers[4 + position] : registers[position]; + } else { + eightbyte = stack[position - 4]; + } + this.store_param(&shape, frame as u64 + slot.offset, eightbyte); + position++; + } + + # A result held in memory is written to a buffer, whose address a hidden + # argument gave, or which the machine gives and reads the result from. + var buffer: u64 = 0; + var dst: u64 = 0; + if returned_memory { + buffer = result_hidden ? registers[0] : raw_allocate_zeroed(round_up(result_shape.size, 16)) as u64; + dst = buffer; + } + + val saved_top := this.top; + val base := this.calls.length; + this.calls.append(call_record { function = index, fp = frame, back = 0, site = 0, results = none, dst = dst }); + this.top = frame as u64 + held.frame; + # Called back within compiled code calling C, the steps that code took are + # settled first, and it is given more after. + val within := this.jit_batch != 0; + if within { + this.jit_settle(); + } + val why := this.execute(base); + if within { + this.jit_arm(); + } + this.top = saved_top; + + if why != halt::none { + if this.foreign_fault == halt::none { + this.foreign_fault = why; + } + if this.threads != null { + this.stop_with(why); + } + if buffer != 0 && !result_hidden { + raw_release(buffer as *mut u8); + } + return; + } + + if returned_memory { + if result_hidden { + registers[0] = buffer; + } else { + var out: u64 = 0; + memcpy((&mut out) as *mut u8, buffer as *u8, result_shape.size); + registers[0] = out; + raw_release(buffer as *mut u8); + } + } else if result_shape.kind == lk::floating { + registers[4] = result_shape.size == 4 ? narrow_single(this.results[0]) : this.results[0]; + } else if result_shape.kind != lk::empty { + registers[0] = this.results[0]; + } + } + + # Writes an argument C passed into the frame of the function C called: an + # aggregate's bytes, from the address a large one was passed by, or the value + # of a smaller one, a scalar widened from its bits as the frame holds it, or a + # reference's pointer. + # @param this The machine. + # @param shape The parameter's layout. + # @param at Where it goes in the frame. + # @param eightbyte What C passed. + def interpreter::store_param(&mut this, shape: &layout, at: u64, eightbyte: u64): void { + if in_memory(shape) { + val size := shape.size; + if micro_by_value(size) { + var held := eightbyte; + memcpy(at as *mut u8, (&mut held) as *u8, size); + } else if eightbyte != 0 { + memcpy(at as *mut u8, eightbyte as *u8, size); + } + return; + } + if shape.kind == lk::floating && shape.size == 4 { + var bits := eightbyte & 0xFFFFFFFF; + val narrow := ((&mut bits) as *mut f32)[0]; + (at as *mut f64)[0] = narrow as f64; + return; + } + (at as *mut u64)[0] = eightbyte; + } + + # The eightbyte a value held in a frame is passed to C as: the word the frame + # holds, narrowed from a double where it is an `f32`, the bytes of an aggregate + # as large as an integer read through its address, or the address of a copy of + # a larger one, which the call frees. + # @param this The machine. + # @param shape The layout. + # @param operand The word the frame holds. + # @param copies Where the address of a copy made is kept, to free. + # @returns The eightbyte. + def interpreter::c_eightbyte(&mut this, shape: &layout, operand: u64, copies: &mut vector): u64 { + if !in_memory(shape) { + return narrow_single(operand) if shape.kind == lk::floating && shape.size == 4; + return operand; + } + val size := shape.size; + if micro_by_value(size) { + var out: u64 = 0; + if operand != 0 { + memcpy((&mut out) as *mut u8, operand as *u8, size); + } + return out; + } + return 0 if operand == 0; + val copy := raw_allocate(round_up(size, 16)) as u64; + memcpy(copy as *mut u8, operand as *u8, size); + copies.append(copy); + return copy; + } + + # The bits of the `f32` a word holds as a double. + # @param word The word. + # @returns The bits. + def narrow_single(word: u64): u64 { + var held := word; + val wide := ((&mut held) as *mut f64)[0]; + val narrow := wide as f32; + var out: u64 = 0; + ((&mut out) as *mut f32)[0] = narrow; + return out; + } + + # The word a frame holds a scalar C gave in as: a float widened from a single + # to a double, an integer extended from its bits, which C leaves unspecified + # past them, or the word as it is. + # @param shape The result's layout. + # @param c What C left. + # @returns The word. + def widen_result(shape: &layout, c: &c_call): u64 { + if shape.kind == lk::floating { + return c.results[2] if shape.size != 4; + var bits := c.results[2] & 0xFFFFFFFF; + val narrow := ((&mut bits) as *mut f32)[0]; + val wide := narrow as f64; + var out: u64 = 0; + ((&mut out) as *mut f64)[0] = wide; + return out; + } + var word := c.results[0]; + return word & 0xFF if shape.kind == lk::boolean; + return word if shape.size >= 8 || shape.kind == lk::pointer || shape.kind == lk::reference; + val bits := shape.size * 8; + val mask := (1u << bits) - 1; + word = word & mask; + if shape.kind == lk::signed && (word >> (bits - 1)) != 0 { + word = word | ~mask; + } + return word; + } + + #! Calls a C function with the arguments a frame holds, as Microsoft's ABI of + #! x86-64 passes them, leaving its result where the frame keeps it. Other + #! threads run while C does, so the machine lets go of its turn around the + #! call, and keeps what C left for `GetLastError` across its own work. + #! @param this The machine. + #! @param code The code running. + #! @param pc Where the call is. + #! @param fp The frame. + #! @returns Why it stopped, or `none`. + pub def interpreter::call_foreign(&mut this, code: *u32, pc: u64, fp: *mut u64): halt { + val signature := code[pc + 1]; + val argc := code[pc + 2] as u64; + val base := pc + 3; + val address := fp[code[base]]; + return halt::null_reference if address == 0; + + val held := &this.c.program.signatures[signature]; + val result_shape := this.c.program.layouts[held.result]; + val result_memory := in_memory(&result_shape); + val returned_memory := result_memory && result_shape.size != 0; + val result_hidden := result_memory && !micro_by_value(result_shape.size); + + var c := c_call { function = address }; + var stack: u64[64]; + var stack_count: u64 = 0; + var copies := vector::::new(); + + var position: u64 = result_hidden ? 1 : 0; + val dst := returned_memory ? fp[code[base + argc - 1]] : 0; + if result_hidden { + c.integers[0] = dst; + } + + var k: u64 = 1; + for i in 0..held.params.length { + val shape := this.c.program.layouts[held.params[i]]; + val operand := fp[code[base + k]]; + k += argument_words(&shape); + val eightbyte := this.c_eightbyte(&shape, operand, &mut copies); + if position < 4 { + c.integers[position] = eightbyte; + c.floats[position] = eightbyte; + } else if stack_count < 64 { + stack[stack_count] = eightbyte; + stack_count++; + } + position++; + } + c.stack = (&mut stack) as *mut u64 as u64; + c.words = stack_count; + + # What the program writes to its output or error is kept rather than + # written, where the machine is asked to, as it keeps what Linux's call + # writes there. + var after := halt::none; + if !this.options.capture || !this.captured(&mut c) { + if !this.make_stubs() { + this.free_copies(&mut copies); + return halt::out_of_memory; + } + val mine := this.strand; + val saved := this.last_error; + this.calling_c++; + this.pause(); + SetLastError(saved); + val stub := this.call_stub as cfn; + stub((&mut c) as *mut c_call as u64); + val error := GetLastError(); + after = this.resume(mine); + this.calling_c--; + this.last_error = error; + } + this.free_copies(&mut copies); + + # A function C called back faulted, which the machine sees once C is back, + # since it cannot leave C where it is. + if this.foreign_fault != halt::none { + val why := this.foreign_fault; + this.foreign_fault = halt::none; + return why; + } + return after if after != halt::none; + if this.options.checks { + this.note_foreign_mapping(&c); + } + + if returned_memory { + if !result_hidden && dst != 0 { + memcpy(dst as *mut u8, (&mut c.results[0]) as *u8, result_shape.size); + } + return halt::none; + } + if result_shape.kind != lk::empty { + val resc := code[base + argc] as u64; + if resc != 0 { + fp[code[base + argc + 1]] = widen_result(&result_shape, &c); + } + } + return halt::none; + } + + # Keeps what a call of `WriteFile` or `WriteConsoleW` writes to the + # program's output or error, rather than calling it, as it succeeds: the + # bytes, or the UTF-16 units as UTF-8, and how many were written where it's + # asked. + # @param this The machine. + # @param c The call, its arguments ready. + # @returns Whether it was kept. + def interpreter::captured(&mut this, c: &mut c_call): bool { + val console := c.function == this.console_writes_at; + return false if c.function == 0 || (c.function != this.writes_at && !console); + val handle := c.integers[0]; + return false if handle != GetStdHandle(0xFFFFFFF5) && handle != GetStdHandle(0xFFFFFFF4); + val count := c.integers[2] & 0xFFFFFFFF; + if console { + val units := c.integers[1] as *u16; + var i: u64 = 0; + while i < count { + var code := units[i] as u32; + if code >= 0xD800 && code < 0xDC00 && i + 1 < count { + code = 0x10000 + ((code - 0xD800) << 10) + (units[i + 1] as u32 - 0xDC00); + i++; + } + this.output_code(code); + i++; + } + } else { + val bytes := c.integers[1] as *u8; + for i in 0..count { + this.output.append(bytes[i]); + } + } + if c.integers[3] != 0 { + (c.integers[3] as *mut u32)[0] = count as u32; + } + c.results[0] = 1; + return true; + } + + # Keeps a code point written to the output, as UTF-8. + def interpreter::output_code(&mut this, code: u32): void { + if code < 0x80 { + this.output.append(code as u8); + } else if code < 0x800 { + this.output.append((0xC0 | (code >> 6)) as u8); + this.output.append((0x80 | (code & 0x3F)) as u8); + } else if code < 0x10000 { + this.output.append((0xE0 | (code >> 12)) as u8); + this.output.append((0x80 | ((code >> 6) & 0x3F)) as u8); + this.output.append((0x80 | (code & 0x3F)) as u8); + } else { + this.output.append((0xF0 | (code >> 18)) as u8); + this.output.append((0x80 | ((code >> 12) & 0x3F)) as u8); + this.output.append((0x80 | ((code >> 6) & 0x3F)) as u8); + this.output.append((0x80 | (code & 0x3F)) as u8); + } + } + + # Notes the memory a call of C maps or gives back, running with its memory + # checked, as the call of Linux doing the same is noted: what `VirtualAlloc` + # gives as what `mmap` does, and what `VirtualFree` releases, all that was + # mapped from where it is given, as what `munmap` gives back. + # @param this The machine. + # @param c The call, made. + def interpreter::note_foreign_mapping(&mut this, c: &c_call): void { + if c.function == this.maps_at && c.results[0] != 0 { + this.note_mapping(9, c.integers[0], c.integers[1], 0, c.results[0]); + } else if c.function == this.unmaps_at && (c.results[0] & 0xFFFFFFFF) != 0 && (c.integers[2] & 0x8000) != 0 { + val bytes := this.mapped_from(c.integers[0]); + if bytes != 0 { + this.note_mapping(11, c.integers[0], bytes, 0, 0); + } + } + } + + # The bytes of the most memory the program mapped from an address, or 0 where + # it mapped none from there. + # @param this The machine. + # @param at The address. + # @returns The bytes. + def interpreter::mapped_from(&mut this, at: u64): u64 { + var most: u64 = 0; + for i in 0..this.mapped.length / 2 { + val first: u64 = this.mapped[2 * i]; + val size: u64 = this.mapped[2 * i + 1]; + if first == at && size > most { + most = size; + } + } + return most; + } + + # Frees the copies a call made of the aggregates it passed by address. + # @param this The machine. + # @param copies The addresses. + def interpreter::free_copies(&mut this, copies: &mut vector): void { + for &each in copies { + val address: u64 = each; + raw_release(address as *mut u8); + } + copies.close(); + } +} diff --git a/machine/format.sakura b/machine/format.sakura new file mode 100644 index 00000000..b6a07948 --- /dev/null +++ b/machine/format.sakura @@ -0,0 +1,336 @@ +#! @file format.sakura +#! @author John Christman (sorakatadzuma@gmail.com) +#! @copyright Malunal Studios, LLC. +#! @license MIT +#! +#! Contains what the machine does with values as its layouts describe them: +#! writes them as text, as interpolated strings ask, and compares them part by +#! part, as `==` of a struct, union, or fixed array asks, each as +#! `sources/machine.c` does. + +import sakura::compiler; +module sakura::machine; + + +#! How deeply a value within values is written before `...` stands for the rest. +const deepest: u64 = 8; + +#! Adds bytes to the text being formatted. +#! @param this The machine. +#! @param address The first byte, or 0. +#! @param length How many bytes. +pub def interpreter::add_text(&mut this, address: u64, length: u64): void { + return if this.depth == 0 || address == 0; + val bytes := address as *u8; + val top := this.depth - 1; + for i in 0..length { + this.texts[top].append(bytes[i]); + } +} + +#! Adds text the machine wrote itself to the text being formatted. +#! @param this The machine. +#! @param text The text. +pub def interpreter::add_view(&mut this, text: strview): void { + return if this.depth == 0; + val top := this.depth - 1; + for &each in text { + this.texts[top].append(each); + } +} + +#! Begins text, which the texts made before keep the memory of. +#! @param this The machine. +pub def interpreter::begin_text(&mut this): void { + if this.depth == this.texts.length { + this.texts.append(vector::::new()); + } else { + this.texts[this.depth].clear(); + } + this.depth++; +} + +#! Ends the text being formatted, giving it in a block the program gives back. +#! @param this The machine. +#! @returns The block's first byte, or 0 where the text is empty. +pub def interpreter::owned_text(&mut this): u64 { + return 0 if this.depth == 0; + this.depth--; + val length := this.texts[this.depth].length; + return 0 if length == 0; + val made := this.allocate(length, false); + memcpy(made as *mut u8, this.texts[this.depth].view().data, length); + this.wrote(made, length); + return made; +} + +#! Adds a value an instruction formats: the words it is, or the address of the +#! memory holding it. +#! @param this The machine. +#! @param layout The value's layout. +#! @param fp The frame. +#! @param code The code. +#! @param at Where the instruction's operand words begin. +#! @param count How many there are. +pub def interpreter::format_operands(&mut this, layout: u32, fp: *mut u64, code: *u32, at: u64, count: u64): void { + val shape := this.c.layout_at(layout); + if in_memory(&shape) { + this.format(fp[code[at]], layout, false, 0); + return; + } + var words: u64[3] = [0, 0, 0]; + for i in 0..count { + break if i >= 3; + words[i] = fp[code[at + i]]; + } + this.format((&mut words) as *mut u64 as u64, layout, true, 0); +} + +#! Reads a scalar from memory as a frame holds it, widened to a word. +#! @param at The address. +#! @param how How it is read. +#! @returns The word. +pub def read_scalar(at: u64, how: access): u64 { + return match how { + access::i8 => ((at as *i8)[0] as i64) as u64, + access::u8 => (at as *u8)[0] as u64, + access::i16 => ((at as *i16)[0] as i64) as u64, + access::u16 => (at as *u16)[0] as u64, + access::i32 => ((at as *i32)[0] as i64) as u64, + access::u32 => (at as *u32)[0] as u64, + access::f32 => bits_of_real((at as *f32)[0] as f64), + else => (at as *u64)[0] + }; +} + +#! Adds a value to the text being formatted, as its layout says it is written. +#! @param this The machine. +#! @param at Where the value is. +#! @param layout Its layout. +#! @param frame Whether it is held as a frame holds it, a scalar widened to a +#! word, rather than as memory holds it. +#! @param depth How deeply within values it is. +pub def interpreter::format(&mut this, at: u64, layout: u32, frame: bool, depth: u64): void { + if depth > deepest { + this.add_view("..."); + return; + } + + val shape := this.c.layout_at(layout); + match shape.kind { + lk::signed, lk::unsigned => { + val value := frame ? (at as *u64)[0] : read_scalar(at, shape.how); + # An enum is the name of the member of the value. + for i in 0..shape.count { + val member := this.c.field_at(layout, i as u32); + if member.offset == value { + this.add_view(this.c.checker.names.text(member.name)); + return; + } + } + if shape.kind == lk::signed { + this.add_view($"{value as i64}"); + } else { + this.add_view($"{value}"); + } + } + lk::boolean => { + val value := frame ? (at as *u64)[0] : read_scalar(at, shape.how); + this.add_view(value != 0 ? "true" : "false"); + } + lk::floating => { + val value := real_of(frame ? (at as *u64)[0] : read_scalar(at, shape.how)); + if shape.bits <= 32 { + this.add_view($"{value as f32}"); + } else { + this.add_view($"{value}"); + } + } + lk::fixed => { + val element := shape.element - 1; + val inner := this.c.layout_at(element); + # A fixed array of bytes is the text it holds. + if (inner.kind == lk::signed || inner.kind == lk::unsigned) && inner.size == 1 && inner.count == 0 { + this.add_text(at, shape.count as u64); + return; + } + this.add_view("["); + for i in 0..shape.count { + if i != 0 { + this.add_view(", "); + } + this.format(at + i as u64 * inner.size, element, false, depth + 1); + } + this.add_view("]"); + } + lk::reference => { + val pointer := (at as *u64)[0]; + if pointer == 0 || shape.element == 0 { + this.add_view("null"); + return; + } + this.format(pointer, shape.element - 1, false, depth + 1); + } + lk::trait_reference => { + val pointer := (at as *u64)[0]; + val vtable := (at as *u64)[1]; + if pointer == 0 || vtable >= this.c.program.vtables.length { + this.add_view("null"); + return; + } + this.format(pointer, this.c.program.vtables[vtable].layout, false, depth + 1); + } + lk::record => this.format_record(at, layout, &shape, depth); + lk::pointer => { + val address := (at as *u64)[0]; + if address == 0 { + this.add_view("null"); + return; + } + this.add_view("0x"); + this.add_view(hex(address).view()); + } + lk::function => { + val index := (at as *u64)[0]; + if index == 0 { + this.add_view("null"); + return; + } + if index - 1 >= this.c.program.functions.length { + this.add_view("def ?"); + return; + } + this.add_view("def "); + this.add_view(this.c.program.functions[index - 1].name.view()); + } + lk::variant => { + # A union is written as a struct holding the one field it holds. + val tag := held_field(&shape, (at as *u64)[0]); + if tag >= shape.count as u64 { + this.add_view("?"); + return; + } + val field := this.c.field_at(layout, tag as u32); + this.add_view(this.c.checker.names.text(shape.name)); + this.add_view("{"); + this.add_view(this.c.checker.names.text(field.name)); + this.add_view(" = "); + this.format(at + field.offset, field.layout, false, depth + 1); + this.add_view("}"); + } + else => {} + } +} + +#! Adds a struct to the text being formatted: text as the bytes it holds, any +#! other view as the elements it views, and the rest as its name and fields. +#! @param this The machine. +#! @param at Where it is. +#! @param layout Its layout. +#! @param shape The layout itself. +#! @param depth How deeply within values it is. +def interpreter::format_record(&mut this, at: u64, layout: u32, shape: &layout, depth: u64): void { + if shape.texts || (shape.views && shape.viewed != 0) { + val begins := this.c.field_at(layout, shape.text); + val many := this.c.field_at(layout, shape.text + 1); + val data := ((at + begins.offset) as *u64)[0]; + val length := data != 0 ? ((at + many.offset) as *u64)[0] : 0; + if shape.texts { + this.add_text(data, length); + return; + } + val element := shape.viewed - 1; + val size := this.c.layout_at(element).size; + this.add_view("["); + for i in 0..length { + if i != 0 { + this.add_view(", "); + } + this.format(data + i * size, element, false, depth + 1); + } + this.add_view("]"); + return; + } + + this.add_view(this.c.checker.names.text(shape.name)); + this.add_view("{"); + for i in 0..shape.count { + val field := this.c.field_at(layout, i as u32); + if i != 0 { + this.add_view(", "); + } + val name := this.c.checker.names.text(field.name); + if name.length != 0 { + this.add_view(name); + this.add_view(" = "); + } + this.format(at + field.offset, field.layout, false, depth + 1); + } + this.add_view("}"); +} + +#! The hexadecimal digits of a word, without leading zeros. +#! @param value The word. +#! @returns The digits. +def hex(value: u64): string { + var made := string::new(nothing {}); + var shift: u64 = 64; + var started := false; + while shift > 0 { + shift -= 4; + val digit := (value >> shift) & 0xF; + started = started || digit != 0 || shift == 0; + continue if !started; + made.push(digit < 10 ? ('0' + digit as u8) : ('a' + (digit - 10) as u8)); + } + return made; +} + +#! Whether the values at two addresses are equal: fixed arrays of what holds +#! no object by their bytes, and of anything else element by element, structs +#! field by field, unions by the field held and then its value, floats as +#! numbers, so `-0` equals `0` and `nan` equals nothing, and anything else by +#! its bytes. +#! @param this The machine. +#! @param a Where one is. +#! @param b Where the other is. +#! @param layout Their layout. +#! @param depth How deeply within values they are. +#! @returns Whether they are equal. +pub def interpreter::equal(&mut this, a: u64, b: u64, layout: u32, depth: u64): bool { + val shape := this.c.layout_at(layout); + match shape.kind { + lk::floating => { + val x := real_of(read_scalar(a, shape.how)); + val y := real_of(read_scalar(b, shape.how)); + return x == y; + } + lk::fixed => { + val element := shape.element - 1; + val inner := this.c.layout_at(element); + # Elements that are integers, `bool`, or pointers are equal where their + # bytes are; any other is compared as its type is. + if inner.kind == lk::signed || inner.kind == lk::unsigned || inner.kind == lk::boolean || inner.kind == lk::pointer { + return memcmp(a as *u8, b as *u8, shape.size) == 0; + } + for i in 0..shape.count { + return false if !this.equal(a + i as u64 * inner.size, b + i as u64 * inner.size, element, depth + 1); + } + return true; + } + lk::record => { + for i in 0..shape.count { + val field := this.c.field_at(layout, i as u32); + return false if !this.equal(a + field.offset, b + field.offset, field.layout, depth + 1); + } + return true; + } + lk::variant => { + val tag := held_field(&shape, (a as *u64)[0]); + return false if tag != held_field(&shape, (b as *u64)[0]) || tag >= shape.count as u64; + val field := this.c.field_at(layout, tag as u32); + return this.equal(a + field.offset, b + field.offset, field.layout, depth + 1); + } + else => return memcmp(a as *u8, b as *u8, shape.size) == 0; + } +} diff --git a/machine/heap.sakura b/machine/heap.sakura new file mode 100644 index 00000000..9bc34ea5 --- /dev/null +++ b/machine/heap.sakura @@ -0,0 +1,800 @@ +#! @file heap.sakura +#! @author John Christman (sorakatadzuma@gmail.com) +#! @copyright Malunal Studios, LLC. +#! @license MIT +#! +#! Contains the memory a program holds: the blocks it allocates and gives back +#! itself, as `raw_allocate` and `raw_release` do, which the machine knows by +#! where each begins and how large it is, so a release of what is no block is +#! found, and what a constant holds is told apart from what it may not keep. +#! +#! Running with its memory checked, as `run --checks` asks, the machine also +#! stops at a read or write through a reference or pointer where the program +#! holds no memory: in a block it released, which is held back a while before +#! its memory is used again so a late use still finds it released, and in a +#! stack past the frames in use. Where code of the program's own calls C, whose +#! memory the machine does not know, only those, and memory the program mapped +#! and gave back, stop it from then on. On Windows `system` is made of calls of +#! C, and what those give only its own code reads, so its calls alone do not +#! count. It stops at a read of memory nothing wrote, too: of a block +#! `raw_allocate` gave, the bytes `raw_resize` added, and a variable +#! `undefined`, until each byte is written, which a call of the system or of C +#! given an address into the memory counts as doing. As the program ends, the +#! blocks it still holds that nothing it keeps reaches are reported, with where +#! each was allocated. + +import sakura::analyzer; +import sakura::compiler; +import std::containers; +module sakura::machine; + + +#! Allocates a block the program gives back itself. +#! @param this The machine. +#! @param size The bytes it holds. +#! @param cleared Whether it is zeroed, as `raw_allocate_zeroed` gives it, +#! rather than holding what it may, as `raw_allocate` does. +#! @returns Its first byte. +pub def interpreter::allocate(&mut this, size: u64, cleared: bool): u64 { + val bytes := size == 0 ? 1u : size; + val made := (cleared ? raw_allocate_zeroed(bytes) : raw_allocate(bytes)) as u64; + this.blocks.set(made, size); + # Running with its memory checked, a block not cleared is never written, and + # holds bytes no address is made of, so the blocks it reaches are the same + # every run. + if this.options.checks { + this.index_block(made, size); + if !cleared { + memset(made as *mut u8, unwritten_byte, size); + this.forget(made, size); + } + } + return made; +} + +#! What each byte of memory never written holds, running with memory checked: +#! a word of them is no address the program holds. +const unwritten_byte: u8 = 0xA5; + +#! The bits of a page of `unwritten`, or null where none of its bytes is +#! unwritten: those last looked for, as reads and writes keep to a page mostly, +#! or else those the dictionary holds. Each page's bits stay where they are +#! once made, however the dictionary grows. +#! @param this The machine. +#! @param page The page's number. +#! @returns Its bits. +def interpreter::bits_of(&mut this, page: u64): *mut u64 { + return this.seen_bits if page == this.seen_page; + this.seen_page = page; + this.seen_bits = null; + if this.unwritten.get(&page) is some(&bits) { + this.seen_bits = bits.data; + } + return this.seen_bits; +} + +#! Marks bytes as never written, running with memory checked. +#! @param this The machine. +#! @param at The first. +#! @param size How many. +pub def interpreter::forget(&mut this, at: u64, size: u64): void { + var from := at; + val end := at + size; + while from < end { + val page := from / 4096; + val stop := end < (page + 1) * 4096 ? end : (page + 1) * 4096; + var bits := this.bits_of(page); + if bits == null { + var made := vector::::new(); + made.resize(64); + bits = made.data; + this.unwritten.set(page, move(&mut made)); + this.seen_bits = bits; + } + var byte := from - page * 4096; + while byte < stop - page * 4096 { + val word := byte / 64; + val mask := word_mask(byte, stop - page * 4096); + bits[word] = bits[word] | mask; + byte = (word + 1) * 64; + } + from = stop; + } +} + +#! The bits of a word of a page's bits that bytes from one up to another cover, +#! within the word the first is in. +#! @param byte The first byte, within its page. +#! @param end The byte after the last, within the page. +#! @returns The bits. +def word_mask(byte: u64, end: u64): u64 { + val word := byte / 64; + val last := end - word * 64 < 64 ? end - word * 64 : 64u; + val high := last == 64 ? 0xFFFFFFFFFFFFFFFFu : (1u << last) - 1; + return high & ~((1u << (byte % 64)) - 1); +} + +#! Marks bytes as written, running with memory checked. +#! @param this The machine. +#! @param at The first. +#! @param size How many. +pub def interpreter::wrote(&mut this, at: u64, size: u64): void { + return if this.unwritten.length == 0; + # A read or a write is a word of bits mostly. + val within := at % 64; + if within + size <= 64 && size < 64 { + val bits := this.bits_of(at / 4096); + if bits != null { + bits[at % 4096 / 64] = bits[at % 4096 / 64] & ~(((1u << size) - 1) << within); + } + return; + } + var from := at; + val end := at + size; + while from < end { + val page := from / 4096; + val stop := end < (page + 1) * 4096 ? end : (page + 1) * 4096; + val bits := this.bits_of(page); + if bits != null { + var byte := from - page * 4096; + while byte < stop - page * 4096 { + val word := byte / 64; + bits[word] = bits[word] & ~word_mask(byte, stop - page * 4096); + byte = (word + 1) * 64; + } + } + from = stop; + } +} + +#! Whether any of some bytes was never written, running with memory checked. +#! @param this The machine. +#! @param at The first. +#! @param size How many. +#! @returns Whether one was not. +pub def interpreter::unwritten_in(&mut this, at: u64, size: u64): bool { + return false if this.unwritten.length == 0; + val within := at % 64; + if within + size <= 64 && size < 64 { + val bits := this.bits_of(at / 4096); + return bits != null && (bits[at % 4096 / 64] & (((1u << size) - 1) << within)) != 0; + } + var from := at; + val end := at + size; + while from < end { + val page := from / 4096; + val stop := end < (page + 1) * 4096 ? end : (page + 1) * 4096; + val bits := this.bits_of(page); + if bits != null { + var byte := from - page * 4096; + while byte < stop - page * 4096 { + val word := byte / 64; + return true if (bits[word] & word_mask(byte, stop - page * 4096)) != 0; + byte = (word + 1) * 64; + } + } + from = stop; + } + return false; +} + +#! Copies which of some bytes were never written to where they are copied, +#! running with memory checked, as copying them copies what they hold: a copy +#! is no read, so what was never written stays so where it went. +#! @param this The machine. +#! @param to Where the first is copied to. +#! @param from The first. +#! @param size How many. +pub def interpreter::copy_unwritten(&mut this, to: u64, from: u64, size: u64): void { + return if this.unwritten.length == 0; + if !this.unwritten_in(from, size) { + this.wrote(to, size); + return; + } + # Byte by byte, from the end where the copy goes past where it comes from. + for k in 0..size { + val i := to > from ? size - 1 - k : k; + if this.unwritten_in(from + i, 1) { + this.forget(to + i, 1); + } else { + this.wrote(to + i, 1); + } + } +} + +#! Marks the memory an address the system or C is given points into as +#! written, running with memory checked, as what each writes there is not +#! known: a block the program holds, whole, or the frames from the address on. +#! @param this The machine. +#! @param at The address. +pub def interpreter::wrote_through(&mut this, at: u64): void { + return if this.unwritten.length == 0 || at < null_page; + if at >= this.stack as u64 && at < this.top { + this.wrote(at, this.top - at); + return; + } + val first := this.indexed_block(at); + if first != 0 { + this.wrote(first, this.blocks[first]); + } +} + +#! Notes a block on each page it is over, to the byte past its end, running +#! with its memory checked, so the block an address is within is found among +#! those of its page. +#! @param this The machine. +#! @param address The block's first byte. +#! @param size Its bytes. +def interpreter::index_block(&mut this, address: u64, size: u64): void { + for page in address / 4096..(address + size) / 4096 + 1 { + if this.pages.contains(&page) { + val held: &mut vector = this.pages[page]; + held.append(address); + } else { + var made := vector::::new(); + made.append(address); + this.pages.set(page, move(&mut made)); + } + } +} + +#! Takes a block off the pages it is over, as it is released. +#! @param this The machine. +#! @param address The block's first byte. +#! @param size Its bytes. +def interpreter::unindex_block(&mut this, address: u64, size: u64): void { + for page in address / 4096..(address + size) / 4096 + 1 { + if this.pages.contains(&page) { + val held: &mut vector = this.pages[page]; + for i in 0..held.length { + if held[i] == address { + held[i] = held.last(); + held.truncate(); + break; + } + } + } + } +} + +#! The block an address is within, to the byte past its end, among those of +#! its page, running with its memory checked: one it is before the end of +#! where an address is both the end of one and the start of the next. +#! @param this The machine. +#! @param at The address. +#! @returns The block's first byte, or 0. +def interpreter::indexed_block(&mut this, at: u64): u64 { + var found: u64 = 0; + if this.pages.get(&(at / 4096)) is some(&held) { + for &each in held.view() { + val first: u64 = each; + val size: u64 = this.blocks[first]; + if at >= first && at <= first + size { + return first if at < first + size; + found = first; + } + } + } + return found; +} + +#! Gives a block back. +#! @param this The machine. +#! @param address The block's first byte, or 0, which gives nothing back. +#! @returns `invalid_release` where the address is no block the program holds. +pub def interpreter::release(&mut this, address: u64): halt { + return halt::none if address == 0; + if !this.blocks.contains(&address) { + return halt::invalid_release; + } + val size: u64 = this.blocks[address]; + this.blocks.remove(&address); + this.kept.remove(&address); + if this.options.checks { + this.wrote(address, size); + this.unindex_block(address, size); + this.sites.remove(&address); + this.hold_back(address, size); + return halt::none; + } + raw_release(address as *mut u8); + return halt::none; +} + +#! The bytes of released blocks held back at most, and how many. +const held_back_bytes: u64 = 67108864; +const held_back_most: u64 = 65536; + +#! Holds a released block back from being used again, giving back the oldest +#! held back where too many are. +#! @param this The machine. +#! @param address The block's first byte. +#! @param size The bytes it holds. +def interpreter::hold_back(&mut this, address: u64, size: u64): void { + this.released.append(address); + this.released_sizes.append(size); + this.released_bytes += size; + while this.released_bytes > held_back_bytes || this.released.length - this.released_from > held_back_most { + val oldest: u64 = this.released[this.released_from]; + raw_release(oldest as *mut u8); + this.released_bytes -= this.released_sizes[this.released_from]; + this.released_from++; + } + # The list is moved down once half of it is let go of. + if this.released_from > 1024 && this.released_from * 2 > this.released.length { + var kept := vector::::new(); + var sizes := vector::::new(); + for i in this.released_from..this.released.length { + kept.append(this.released[i]); + sizes.append(this.released_sizes[i]); + } + this.released = move(&mut kept); + this.released_sizes = move(&mut sizes); + this.released_from = 0; + } +} + +#! Notes where a block was allocated, running with its memory checked: the +#! innermost frame of a function of the program's own rather than std's. +#! @param this The machine. +#! @param address The block's first byte. +#! @param pc Where the code running is. +pub def interpreter::note_site(&mut this, address: u64, pc: u64): void { + return if address == 0; + var i := this.calls.length; + while i > 0 { + i--; + val function: u32 = this.calls.at(i).function; + val at := i == this.calls.length - 1 ? pc : this.calls.at(i + 1).site; + if !this.in_std_function(function) || i == 0 { + this.sites.set(address, pair_key(function, at as u32)); + return; + } + } +} + +#! Keeps the words of the frames the running thread has in use as the program +#! ends by exiting, running with its memory checked, so that the leaks reported +#! count them as reaching what they hold: neither a thread stopped as `main` +#! returns nor one that exits releases what its locals hold. +#! @param this The machine. +pub def interpreter::keep_frames(&mut this): void { + var at := this.stack as u64; + while at + word_size <= this.top { + this.ended.append((at as *u64)[0]); + at += word_size; + } +} + +#! Whether a function is std's, or an anonymous function within one of std's. +#! @param this The machine. +#! @param function The function. +#! @returns Whether it is. +def interpreter::in_std_function(&mut this, function: u32): bool { + val held := &this.c.program.functions[function]; + val decl := held.decl != 0 ? held.decl : held.outer; + return decl != 0 && this.c.in_std(decl); +} + +#! Whether a function is `system`'s, or an anonymous function within one of +#! `system`'s. +#! @param this The machine. +#! @param function The function. +#! @returns Whether it is. +def interpreter::in_system_function(&mut this, function: u32): bool { + val held := &this.c.program.functions[function]; + val decl := held.decl != 0 ? held.decl : held.outer; + return decl != 0 && this.in_system(decl); +} + +#! Whether the code at a place in a function is `system`'s: that of a function +#! of `system`'s, or, in the code giving the globals their values, that giving +#! one of `system`'s its value, as the file it is written in says. +#! @param this The machine. +#! @param function The function. +#! @param pc Where in its code. +#! @returns Whether it is. +def interpreter::in_system_code(&mut this, function: u32, pc: u64): bool { + return this.in_system_function(function) if function != this.c.program.init; + var at: u64 = 0; + for &mark in this.c.program.functions[function].compiled.lines { + break if mark.pc as u64 > pc; + at = mark.at; + } + # A file of `system`'s declares only what is `system`'s, so any declaration + # of the file says whose the code is. + if at != 0 { + val file := pair_high(at) - 1; + for decl in 1..this.c.checker.decls.count { + continue if this.c.checker.decls.files.p[decl] != file || this.c.checker.decls.nodes.p[decl] == 0; + return this.in_system(decl as u32); + } + } + return true; +} + +#! Whether a declaration is `system`'s, which on Windows is made of calls of C +#! whose memory only its own code reads. +#! @param this The machine. +#! @param decl The declaration. +#! @returns Whether it is. +def interpreter::in_system(&this, decl: u32): bool { + var at: u32 = this.c.checker.decls.modules.p[decl]; + var steps := 0; + while at != 0 && this.c.checker.modules.parents[at] != 0 && steps < 64 { + at = this.c.checker.modules.parents[at]; + steps++; + } + return at != 0 && this.c.checker.modules.names[at] == word::system; +} + +#! Notes the memory a system call that succeeded maps or unmaps, running with +#! its memory checked, which the program holds as it does a block: what `mmap` +#! and `mremap` give, in whole pages, until `munmap` gives it back. Where the +#! program calls C, which takes memory the machine does not know as C's, what +#! it gave back is kept apart, so a late use still finds it given back. +#! @param this The machine. +#! @param number The call, as Linux numbers them. +#! @param a Its first argument. +#! @param b Its second. +#! @param c Its third. +#! @param result What it gave. +pub def interpreter::note_mapping(&mut this, number: u64, a: u64, b: u64, c: u64, result: u64): void { + if number == 9 { + this.add_run(result, (b + 4095) / 4096 * 4096); + } else if number == 11 { + val size := (b + 4095) / 4096 * 4096; + drop_runs(&mut this.mapped, a, size); + if this.calls_c { + drop_runs(&mut this.unmapped, a, size); + insert_run(&mut this.unmapped, a, size); + } + } else if number == 25 { + for i in 0..this.mapped.length / 2 { + if this.mapped[2 * i] == a { + this.mapped.remove_at(2 * i + 1); + this.mapped.remove_at(2 * i); + break; + } + } + this.add_run(result, (c + 4095) / 4096 * 4096); + } +} + +#! Notes memory the program was given, running with its memory checked, among +#! the runs kept in order of where each begins. +#! @param this The machine. +#! @param start Its first byte. +#! @param size Its bytes. +pub def interpreter::add_run(&mut this, start: u64, size: u64): void { + insert_run(&mut this.mapped, start, size); +} + +#! Puts a run of memory among runs kept in order of where each begins. +#! @param runs The runs, as pairs of where each begins and its bytes. +#! @param start Its first byte. +#! @param size Its bytes. +def insert_run(runs: &mut vector, start: u64, size: u64): void { + var at := runs.length; + while at > 0 && runs[at - 2] > start { + at -= 2; + } + runs.insert_at(at, size); + runs.insert_at(at, start); +} + +#! Takes the runs of memory lying within some memory from runs kept in order of +#! where each begins. +#! @param runs The runs, as pairs of where each begins and its bytes. +#! @param start The memory's first byte. +#! @param size Its bytes. +def drop_runs(runs: &mut vector, start: u64, size: u64): void { + var i := 0u; + while i < runs.length { + val first: u64 = runs[i]; + val bytes: u64 = runs[i + 1]; + if first >= start && first + bytes <= start + size { + runs.remove_at(i + 1); + runs.remove_at(i); + } else { + i += 2; + } + } +} + +#! Of runs of memory, as pairs of where each begins and its bytes in order of +#! where each begins, the one that may hold the address: the last beginning at +#! or before it, or the count of runs where none does. +#! @param runs The runs. +#! @param at The address. +#! @returns The run's index. +def find_run(runs: &vector, at: u64): u64 { + val count := runs.length / 2; + var low: u64 = 0; + var high := count; + while low < high { + val middle := (low + high) / 2; + if runs[2 * middle] <= at { + low = middle + 1; + } else { + high = middle; + } + } + return low == 0 ? count : low - 1; +} + +#! Puts where each datum is and its bytes in order, running with its memory +#! checked, so the one an address is within is found by halves. +#! @param this The machine. +def interpreter::order_data(&mut this): void { + for i in 0..this.data.length { + val data: u64 = this.data[i]; + this.data_runs.append(data); + this.data_runs.append(this.c.program.data[i].bytes.length); + } + # In order of where each begins, two words at a time. + for i in 1..this.data_runs.length / 2 { + var j := i; + while j > 0 && this.data_runs[2 * (j - 1)] > this.data_runs[2 * j] { + val start: u64 = this.data_runs[2 * j]; + val size: u64 = this.data_runs[2 * j + 1]; + this.data_runs[2 * j] = this.data_runs[2 * (j - 1)]; + this.data_runs[2 * j + 1] = this.data_runs[2 * (j - 1) + 1]; + this.data_runs[2 * (j - 1)] = start; + this.data_runs[2 * (j - 1) + 1] = size; + j--; + } + } +} + +#! Whether elements from a pointer lie where the program may read and write +#! them, running with its memory checked: in memory it holds or mapped, or, +#! where it calls C, anywhere but in a block released and held back, in a stack +#! past the frames in use, or in memory it mapped and gave back. That is so of +#! code of the program's own only once it has called C, since on Windows +#! `system` is made of calls of C, whose memory only `system`'s code reads. +#! @param this The machine. +#! @param pointer The first element. +#! @param count How many. +#! @param size The bytes of each. +#! @returns Whether they do. +pub def interpreter::checked_reach(&mut this, pointer: u64, count: u64, size: u64): bool { + # Within the first page, the read or the write itself stops the program, as + # one through null, as where memory is not checked. + return true if pointer < null_page; + return true if count == 0 || size == 0; + val bytes := count * size; + return false if bytes / count != size; + var start: u64 = 0; + val end := this.region(pointer, &mut start); + return end - pointer >= bytes if end != 0; + val run := find_run(&this.mapped, pointer); + if run < this.mapped.length / 2 { + val first: u64 = this.mapped[2 * run]; + val size: u64 = this.mapped[2 * run + 1]; + return first + size - pointer >= bytes if pointer < first + size; + } + return true if this.in_other_frames(pointer, bytes); + for i in this.released_from..this.released.length { + val first: u64 = this.released[i]; + return false if pointer >= first && pointer < first + this.released_sizes[i]; + } + return false if this.in_stacks(pointer); + val gone := find_run(&this.unmapped, pointer); + if gone < this.unmapped.length / 2 { + val first: u64 = this.unmapped[2 * gone]; + val size: u64 = this.unmapped[2 * gone + 1]; + return false if pointer < first + size; + } + return this.calls_c && (this.called_c || this.in_system_function(this.calls.last().function)); +} + +#! Writes what blocks the program allocated it still holds that nothing it +#! keeps reaches, as a run with its memory checked does once the program ends: +#! those neither a global, nor the frames a thread had in use as the program +#! exited, nor a block either reaches holds the address of, with where they were +#! allocated, those of each place together. +#! @param this The machine. +#! @param out Where it is written. +pub def interpreter::report_leaks(&mut this, out: &mut string): void { + # The blocks, by where each begins, to find the one an address is within. + var starts := vector::::new(); + for &entry in this.blocks { + starts.append(entry.key); + } + starts.sort(); + + # The blocks the globals reach, and those they reach in turn. + var reached := hashset::::new(); + var todo := vector::::new(); + this.reach_words(this.globals as u64, this.globals as u64 + this.c.program.globals, &starts, &mut reached, &mut todo); + if this.ended.length != 0 { + val words := (&this.ended[0]) as *u64 as u64; + this.reach_words(words, words + this.ended.length * word_size, &starts, &mut reached, &mut todo); + } + while todo.length != 0 { + val block: u64 = todo.last(); + todo.truncate(); + this.reach_words(block, block + this.blocks[block], &starts, &mut reached, &mut todo); + } + + # What is lost, by where it was allocated. + var places := vector::::new(); + var counts := vector::::new(); + var sizes := vector::::new(); + var blocks: u64 = 0; + var bytes: u64 = 0; + for &first in starts { + continue if reached.contains(&first) || this.kept.contains(&first); + val size: u64 = this.blocks[first]; + blocks++; + bytes += size; + var place := string::from("an unknown place", nothing {}); + if this.sites.get(&first) is some(site) { + val frame := this.site_frame(pair_high(site), pair_low(site) as u64); + place = $"{frame.function} ({frame.path}:{frame.line}:{frame.column})"; + } + var found := places.length; + for i in 0..places.length { + if places[i].view() == place.view() { + found = i; + break; + } + } + if found == places.length { + places.append(move(&mut place)); + counts.append(0); + sizes.append(0); + } + counts[found] += 1; + sizes[found] += size; + } + return if blocks == 0; + + # The places in order, so the report reads the same each run. + var order := vector::::new(); + for i in 0..places.length { + order.append(i); + } + for i in 1..order.length { + var j := i; + while j > 0 && places[order[j - 1]].compare(places[order[j]].view()) > 0 { + val held: u64 = order[j]; + order[j] = order[j - 1]; + order[j - 1] = held; + j--; + } + } + val noun := blocks == 1 ? "block" : "blocks"; + out.append($"sakura: {blocks} {noun} the program allocated, {bytes} bytes, were never released, and nothing it keeps reaches them:\n"); + for &i in order { + val count: u64 = counts[i]; + val each := count == 1 ? "block" : "blocks"; + out.append($" {count} {each}, {sizes[i]} bytes, allocated at {places[i]}\n"); + } +} + +#! Marks the blocks the words of memory hold the addresses of, or addresses +#! within, which are to have their own words read. +#! @param this The machine. +#! @param from The first byte. +#! @param to The byte past the last. +#! @param starts Where each block begins, in order. +#! @param reached The blocks marked. +#! @param todo The blocks marked whose words are to be read. +def interpreter::reach_words(&mut this, from: u64, to: u64, starts: &vector, reached: &mut hashset, todo: &mut vector): void { + return if starts.length == 0; + var at := (from + word_size - 1) / word_size * word_size; + while at + word_size <= to { + val word := (at as *u64)[0]; + at += word_size; + continue if word < starts[0]; + val index := starts.view().upper_bound(&word); + continue if index == 0; + val first: u64 = starts[index - 1]; + continue if word >= first + (this.blocks[first] == 0 ? 1 : this.blocks[first]); + if reached.insert(first) { + todo.append(first); + } + } +} + +#! Moves a block to one of another size, keeping what fits, and gives the old +#! one back. Resizing no block allocates one. +#! @param this The machine. +#! @param address The block's first byte, or 0. +#! @param size The bytes the new one holds. +#! @returns The new block's first byte. +pub def interpreter::resize(&mut this, address: u64, size: u64): u64 { + return this.allocate(size, false) if address == 0; + val had: u64 = this.blocks[address]; + val made := this.allocate(size, false); + val kept := had < size ? had : size; + memcpy(made as *mut u8, address as *u8, kept); + if this.options.checks { + this.copy_unwritten(made, address, kept); + } + this.release(address); + return made; +} + +#! The memory the program holds an address within, while compiling: the +#! globals, the frames in use, or a block, each up to the byte past its end. +#! @param this The machine. +#! @param at The address. +#! @param start Where the memory begins is written here. +#! @returns Where it ends, or 0 where the program holds no memory there. +def interpreter::region(&mut this, at: u64, start: &mut u64): u64 { + val globals := this.globals as u64; + if at >= globals && at <= globals + this.c.program.globals { + start = globals; + return globals + this.c.program.globals; + } + if at >= this.stack as u64 && at <= this.top { + start = this.stack as u64; + return this.top; + } + if this.options.checks { + val first := this.indexed_block(at); + if first != 0 { + start = first; + return first + this.blocks[first]; + } + } else { + for &entry in this.blocks { + if at >= entry.key && at <= entry.key + entry.value { + start = entry.key; + return entry.key + entry.value; + } + } + } + if this.options.checks { + val run := find_run(&this.data_runs, at); + if run < this.data_runs.length / 2 && at <= this.data_runs[2 * run] + this.data_runs[2 * run + 1] { + start = this.data_runs[2 * run]; + return start + this.data_runs[2 * run + 1]; + } + return 0; + } + for i in 0..this.data.length { + val data: u64 = this.data[i]; + val size := this.c.program.data[i].bytes.length; + if at >= data && at <= data + size { + start = data; + return data + size; + } + } + return 0; +} + +#! Whether elements from a pointer lie in memory the program holds, as reading +#! them while compiling asks. +#! @param this The machine. +#! @param pointer The first element. +#! @param count How many. +#! @param size The bytes of each. +#! @returns Whether they do. +pub def interpreter::reaches(&mut this, pointer: u64, count: u64, size: u64): bool { + return false if pointer == 0; + return true if count == 0; + var start: u64 = 0; + val end := this.region(pointer, &mut start); + return false if end == 0; + val bytes := count * size; + return bytes / count == size && end - pointer >= bytes; +} + +#! Whether two pointers are within the same memory, which comparing or +#! subtracting them while compiling asks, since where different memory is +#! changes from one build to the next. +#! @param this The machine. +#! @param a One pointer. +#! @param b The other. +#! @returns Whether they are. +pub def interpreter::same_memory(&mut this, a: u64, b: u64): bool { + return true if a == b; + return false if a == 0 || b == 0; + var start: u64 = 0; + val end := this.region(a, &mut start); + return end != 0 && b >= start && b <= end; +} diff --git a/machine/interpreter.sakura b/machine/interpreter.sakura new file mode 100644 index 00000000..5379b588 --- /dev/null +++ b/machine/interpreter.sakura @@ -0,0 +1,1297 @@ +#! @file interpreter.sakura +#! @author John Christman (sorakatadzuma@gmail.com) +#! @copyright Malunal Studios, LLC. +#! @license MIT +#! +#! Contains the interpreter: one loop over the operations of the machine's +#! code, each reading the words of the frame its operands name. A call copies +#! its arguments into the frame of the function it calls, which begins where +#! the caller's ends, and a return writes the words it gives into those the +#! call names for them. The operations run most are tested for first, and +#! those run least are `slow_op`'s, which the code `jit.sakura` compiles +#! calls too. A function compiled to the processor's code runs as that code, +#! whether the machine begins with it or calls it. + +import sakura::compiler; +module sakura::machine; + + +#! Spends a step of an evaluation's budget, of the steps the host allows a +#! call, or of a thread's turn, which ends once it has taken its share, letting +#! another run. +#! @param this The machine. +#! @returns Why the run stops, or `none` where it goes on. +def interpreter::spent(&mut this): halt { + if this.options.evaluating { + return this.exhausted() ? halt::evaluation_limit : halt::none; + } + return halt::step_limit if this.options.steps != 0 && this.exhausted(); + return halt::none if this.threads == null; + this.countdown--; + return halt::none if this.countdown != 0; + return this.next_turn(); +} + +#! Spends a step of an evaluation's budget, where any is left. +#! @param this The machine. +#! @returns Whether none was left. +def interpreter::exhausted(&mut this): bool { + return true if this.budget == 0; + this.budget--; + return false; +} + +#! Runs the call on top of the calls until it returns, leaving the calls +#! beneath it, of which there are `base`. A fault records where every call +#! was, and lets go of them all. +#! @param this The machine. +#! @param base How many calls are beneath the one run. +#! @returns Why it stopped, or `none` where the call returned. +pub def interpreter::execute(&mut this, base: u64): halt { + val routines := this.routines.view().data; + val first: call_record = this.calls.last(); + var current: u32 = first.function; + var code := routines[current].code; + var fp := first.fp; + var pc: u64 = 0; + var origin: u64 = 0; + var stop := halt::none; + val evaluating := this.options.evaluating; + # Steps are counted against an evaluation's budget, the steps the host + # allows, or a thread's turn. + var counting := evaluating || this.options.steps != 0 || this.threads != null; + + # A function compiled runs as the processor's code, unless the stack of the + # system's thread is too near its end, where it is interpreted. + if this.jit_on { + val entry := this.native_of(current); + if entry != 0 { + val ran := this.run_native(entry, fp); + if ran != jit_declined { + if ran == 0 { + this.leave(base); + return halt::none; + } + return this.stopped(halt_numbered(ran), this.jit_origin); + } + } + } + + # A case that stops the run says why in `stop` and leaves the loop, so `stop` + # is written only on the way out, and the loop carries it nowhere. + while true { + origin = pc; + val kind := code[pc]; + match kind { + bc::move as u32 => { + fp[code[pc + 1]] = fp[code[pc + 2]]; + pc += bc_widths[bc::move as u64]; + } + bc::konst as u32 => { + fp[code[pc + 1]] = code[pc + 2] as u64 | (code[pc + 3] as u64 << 32); + pc += bc_widths[bc::konst as u64]; + } + bc::load_i64 as u32 => { + val address := fp[code[pc + 2]]; + if address < null_page { + stop = halt::null_reference; + break; + } + fp[code[pc + 1]] = ((address + code[pc + 3] as u64) as *u64)[0]; + pc += bc_widths[bc::load_i64 as u64]; + } + bc::store_64 as u32 => { + val address := fp[code[pc + 1]]; + if address < null_page { + stop = halt::null_reference; + break; + } + ((address + code[pc + 2] as u64) as *mut u64)[0] = fp[code[pc + 3]]; + pc += bc_widths[bc::store_64 as u64]; + } + bc::cell as u32 => { + fp[code[pc + 1]] = fp as u64 + code[pc + 2] as u64; + pc += bc_widths[bc::cell as u64]; + } + bc::add as u32 => { + fp[code[pc + 1]] = fp[code[pc + 2]] + fp[code[pc + 3]]; + pc += bc_widths[bc::add as u64]; + } + bc::jump as u32 => { + if counting { + stop = this.spent(); + break if stop != halt::none; + } + pc = code[pc + 1] as u64; + } + bc::jump_if as u32 => { + if counting { + stop = this.spent(); + break if stop != halt::none; + } + pc = fp[code[pc + 1]] != 0 ? code[pc + 2] as u64 : pc + bc_widths[bc::jump_if as u64]; + } + bc::jump_zero as u32 => { + if counting { + stop = this.spent(); + break if stop != halt::none; + } + pc = fp[code[pc + 1]] == 0 ? code[pc + 2] as u64 : pc + bc_widths[bc::jump_zero as u64]; + } + bc::eq as u32 => { + fp[code[pc + 1]] = fp[code[pc + 2]] == fp[code[pc + 3]] ? 1 : 0; + pc += bc_widths[bc::eq as u64]; + } + bc::ne as u32 => { + fp[code[pc + 1]] = fp[code[pc + 2]] != fp[code[pc + 3]] ? 1 : 0; + pc += bc_widths[bc::ne as u64]; + } + bc::ltu as u32 => { + fp[code[pc + 1]] = fp[code[pc + 2]] < fp[code[pc + 3]] ? 1 : 0; + pc += bc_widths[bc::ltu as u64]; + } + bc::lts as u32 => { + fp[code[pc + 1]] = (fp[code[pc + 2]] as i64) < (fp[code[pc + 3]] as i64) ? 1 : 0; + pc += bc_widths[bc::lts as u64]; + } + bc::add_k as u32 => { + fp[code[pc + 1]] = fp[code[pc + 2]] + bc_constant(code[pc + 3]); + pc += bc_widths[bc::add_k as u64]; + } + bc::add_k_jump as u32 => { + if counting { + stop = this.spent(); + break if stop != halt::none; + } + fp[code[pc + 1]] = fp[code[pc + 2]] + bc_constant(code[pc + 3]); + pc = code[pc + 4] as u64; + } + bc::move_jump as u32 => { + if counting { + stop = this.spent(); + break if stop != halt::none; + } + fp[code[pc + 1]] = fp[code[pc + 2]]; + pc = code[pc + 3] as u64; + } + bc::load_u8_x as u32 => { + val address := fp[code[pc + 2]] + fp[code[pc + 3]]; + if address < null_page { + stop = halt::null_reference; + break; + } + fp[code[pc + 1]] = ((address + code[pc + 4] as u64) as *u8)[0] as u64; + pc += bc_widths[bc::load_u8_x as u64]; + } + bc::store_8_x as u32 => { + val address := fp[code[pc + 1]] + fp[code[pc + 2]]; + if address < null_page { + stop = halt::null_reference; + break; + } + ((address + code[pc + 3] as u64) as *mut u8)[0] = fp[code[pc + 4]] as u8; + pc += bc_widths[bc::store_8_x as u64]; + } + bc::jump_ltu as u32 => { + if counting { + stop = this.spent(); + break if stop != halt::none; + } + pc = fp[code[pc + 1]] < fp[code[pc + 2]] ? code[pc + 3] as u64 : pc + bc_widths[bc::jump_ltu as u64]; + } + bc::jump_leu as u32 => { + if counting { + stop = this.spent(); + break if stop != halt::none; + } + pc = fp[code[pc + 1]] <= fp[code[pc + 2]] ? code[pc + 3] as u64 : pc + bc_widths[bc::jump_leu as u64]; + } + bc::jump_eq as u32 => { + if counting { + stop = this.spent(); + break if stop != halt::none; + } + pc = fp[code[pc + 1]] == fp[code[pc + 2]] ? code[pc + 3] as u64 : pc + bc_widths[bc::jump_eq as u64]; + } + bc::jump_ne as u32 => { + if counting { + stop = this.spent(); + break if stop != halt::none; + } + pc = fp[code[pc + 1]] != fp[code[pc + 2]] ? code[pc + 3] as u64 : pc + bc_widths[bc::jump_ne as u64]; + } + bc::jump_lts as u32 => { + if counting { + stop = this.spent(); + break if stop != halt::none; + } + pc = (fp[code[pc + 1]] as i64) < (fp[code[pc + 2]] as i64) ? code[pc + 3] as u64 : pc + bc_widths[bc::jump_lts as u64]; + } + bc::jump_les as u32 => { + if counting { + stop = this.spent(); + break if stop != halt::none; + } + pc = (fp[code[pc + 1]] as i64) <= (fp[code[pc + 2]] as i64) ? code[pc + 3] as u64 : pc + bc_widths[bc::jump_les as u64]; + } + bc::jump_eq_k as u32 => { + if counting { + stop = this.spent(); + break if stop != halt::none; + } + pc = fp[code[pc + 1]] == bc_constant(code[pc + 2]) ? code[pc + 3] as u64 : pc + bc_widths[bc::jump_eq_k as u64]; + } + bc::jump_ne_k as u32 => { + if counting { + stop = this.spent(); + break if stop != halt::none; + } + pc = fp[code[pc + 1]] != bc_constant(code[pc + 2]) ? code[pc + 3] as u64 : pc + bc_widths[bc::jump_ne_k as u64]; + } + bc::jump_lts_k as u32 => { + if counting { + stop = this.spent(); + break if stop != halt::none; + } + pc = (fp[code[pc + 1]] as i64) < (bc_constant(code[pc + 2]) as i64) ? code[pc + 3] as u64 : pc + bc_widths[bc::jump_lts_k as u64]; + } + bc::jump_ltu_k as u32 => { + if counting { + stop = this.spent(); + break if stop != halt::none; + } + pc = fp[code[pc + 1]] < bc_constant(code[pc + 2]) ? code[pc + 3] as u64 : pc + bc_widths[bc::jump_ltu_k as u64]; + } + bc::jump_les_k as u32 => { + if counting { + stop = this.spent(); + break if stop != halt::none; + } + pc = (fp[code[pc + 1]] as i64) <= (bc_constant(code[pc + 2]) as i64) ? code[pc + 3] as u64 : pc + bc_widths[bc::jump_les_k as u64]; + } + bc::jump_leu_k as u32 => { + if counting { + stop = this.spent(); + break if stop != halt::none; + } + pc = fp[code[pc + 1]] <= bc_constant(code[pc + 2]) ? code[pc + 3] as u64 : pc + bc_widths[bc::jump_leu_k as u64]; + } + bc::jump_gts_k as u32 => { + if counting { + stop = this.spent(); + break if stop != halt::none; + } + pc = (fp[code[pc + 1]] as i64) > (bc_constant(code[pc + 2]) as i64) ? code[pc + 3] as u64 : pc + bc_widths[bc::jump_gts_k as u64]; + } + bc::jump_gtu_k as u32 => { + if counting { + stop = this.spent(); + break if stop != halt::none; + } + pc = fp[code[pc + 1]] > bc_constant(code[pc + 2]) ? code[pc + 3] as u64 : pc + bc_widths[bc::jump_gtu_k as u64]; + } + bc::jump_ges_k as u32 => { + if counting { + stop = this.spent(); + break if stop != halt::none; + } + pc = (fp[code[pc + 1]] as i64) >= (bc_constant(code[pc + 2]) as i64) ? code[pc + 3] as u64 : pc + bc_widths[bc::jump_ges_k as u64]; + } + bc::jump_geu_k as u32 => { + if counting { + stop = this.spent(); + break if stop != halt::none; + } + pc = fp[code[pc + 1]] >= bc_constant(code[pc + 2]) ? code[pc + 3] as u64 : pc + bc_widths[bc::jump_geu_k as u64]; + } + bc::check_ltu as u32 => { + if fp[code[pc + 1]] >= fp[code[pc + 2]] { + stop = halt_of(code[pc + 3] as u64); + break; + } + pc += bc_widths[bc::check_ltu as u64]; + } + bc::check_ltu_k as u32 => { + if fp[code[pc + 1]] >= bc_constant(code[pc + 2]) { + stop = halt_of(code[pc + 3] as u64); + break; + } + pc += bc_widths[bc::check_ltu_k as u64]; + } + bc::band_k as u32 => { + fp[code[pc + 1]] = fp[code[pc + 2]] & bc_constant(code[pc + 3]); + pc += bc_widths[bc::band_k as u64]; + } + bc::shl_k as u32 => { + fp[code[pc + 1]] = fp[code[pc + 2]] << bc_constant(code[pc + 3]); + pc += bc_widths[bc::shl_k as u64]; + } + bc::shru_k as u32 => { + fp[code[pc + 1]] = fp[code[pc + 2]] >> bc_constant(code[pc + 3]); + pc += bc_widths[bc::shru_k as u64]; + } + bc::shrs_k as u32 => { + fp[code[pc + 1]] = ((fp[code[pc + 2]] as i64) >> bc_constant(code[pc + 3])) as u64; + pc += bc_widths[bc::shrs_k as u64]; + } + bc::mul_k as u32 => { + fp[code[pc + 1]] = fp[code[pc + 2]] * bc_constant(code[pc + 3]); + pc += bc_widths[bc::mul_k as u64]; + } + bc::store_k64 as u32 => { + val address := fp[code[pc + 1]]; + if address < null_page { + stop = halt::null_reference; + break; + } + ((address + code[pc + 2] as u64) as *mut u64)[0] = code[pc + 3] as u64 | (code[pc + 4] as u64 << 32); + pc += bc_widths[bc::store_k64 as u64]; + } + bc::store_k8 as u32, bc::store_k16 as u32, bc::store_k32 as u32 => { + val address := fp[code[pc + 1]]; + if address < null_page { + stop = halt::null_reference; + break; + } + val at := address + code[pc + 2] as u64; + if kind == bc::store_k8 as u32 { + (at as *mut u8)[0] = code[pc + 3] as u8; + } else if kind == bc::store_k16 as u32 { + (at as *mut u16)[0] = code[pc + 3] as u16; + } else { + (at as *mut u32)[0] = code[pc + 3]; + } + pc += bc_widths[bc::store_k8 as u64]; + } + bc::load_u8 as u32 => { + val address := fp[code[pc + 2]]; + if address < null_page { + stop = halt::null_reference; + break; + } + fp[code[pc + 1]] = ((address + code[pc + 3] as u64) as *u8)[0] as u64; + pc += bc_widths[bc::load_u8 as u64]; + } + bc::call as u32 => { + val callee := code[pc + 1]; + val argc := code[pc + 2] as u64; + val results := pc + 3 + argc; + val back := results + 1 + code[results] as u64; + val held: routine = routines[callee]; + val next := (fp as u64 + routines[current].frame) as *mut u64; + if counting { + stop = this.spent(); + break if stop != halt::none; + } + if next as u64 + held.frame > this.stack_end { + stop = halt::stack_overflow; + break; + } + val k := this.pass(&held, next, fp, code, pc + 3, 0, 0); + val dst: u64 = held.returned != 0 ? fp[code[pc + 3 + k]] : 0; + this.enter(callee, &held, next, back, pc, results, dst); + if this.jit_on { + val ran := this.call_native(callee, next, fp, code, results, current); + if ran != jit_declined { + if ran != 0 { + stop = halt_numbered(ran); + origin = this.jit_origin; + break; + } + counting = evaluating || this.options.steps != 0 || this.threads != null; + pc = back; + continue; + } + } + current = callee; + code = held.code; + fp = next; + pc = 0; + } + bc::ret as u32 => { + val count := code[pc + 1] as u64; + val done: call_record = this.calls.last(); + if this.calls.length == base + 1 { + for i in 0..count { + this.results[i] = fp[code[pc + 2 + i]]; + } + this.leave(base); + return halt::none; + } + val caller: call_record = this.calls.at(this.calls.length - 2); + val back_code := routines[caller.function].code; + if done.results != none { + for i in 0..count { + caller.fp[back_code[done.results + 1 + i]] = fp[code[pc + 2 + i]]; + } + } + this.calls.truncate(); + current = caller.function; + code = back_code; + fp = caller.fp; + pc = done.back; + this.top = fp as u64 + routines[current].frame; + } + bc::sub as u32 => { + fp[code[pc + 1]] = fp[code[pc + 2]] - fp[code[pc + 3]]; + pc += bc_widths[bc::sub as u64]; + } + bc::leu as u32 => { + fp[code[pc + 1]] = fp[code[pc + 2]] <= fp[code[pc + 3]] ? 1 : 0; + pc += bc_widths[bc::leu as u64]; + } + bc::les as u32 => { + fp[code[pc + 1]] = (fp[code[pc + 2]] as i64) <= (fp[code[pc + 3]] as i64) ? 1 : 0; + pc += bc_widths[bc::les as u64]; + } + bc::mul as u32 => { + fp[code[pc + 1]] = fp[code[pc + 2]] * fp[code[pc + 3]]; + pc += bc_widths[bc::mul as u64]; + } + bc::band as u32 => { + fp[code[pc + 1]] = fp[code[pc + 2]] & fp[code[pc + 3]]; + pc += bc_widths[bc::band as u64]; + } + bc::bor as u32 => { + fp[code[pc + 1]] = fp[code[pc + 2]] | fp[code[pc + 3]]; + pc += bc_widths[bc::bor as u64]; + } + bc::wrap as u32 => { + var value := fp[code[pc + 2]]; + val bits := code[pc + 3] as u64; + if bits < 64 { + val mask := (1u << bits) - 1; + value = value & mask; + if code[pc + 4] != 0 && (value >> (bits - 1)) != 0 { + value = value | ~mask; + } + } + fp[code[pc + 1]] = value; + pc += bc_widths[bc::wrap as u64]; + } + bc::load_i32 as u32 => { + val address := fp[code[pc + 2]]; + if address < null_page { + stop = halt::null_reference; + break; + } + fp[code[pc + 1]] = (((address + code[pc + 3] as u64) as *i32)[0] as i64) as u64; + pc += bc_widths[bc::load_i32 as u64]; + } + bc::load_u32 as u32 => { + val address := fp[code[pc + 2]]; + if address < null_page { + stop = halt::null_reference; + break; + } + fp[code[pc + 1]] = ((address + code[pc + 3] as u64) as *u32)[0] as u64; + pc += bc_widths[bc::load_u32 as u64]; + } + bc::store_8 as u32 => { + val address := fp[code[pc + 1]]; + if address < null_page { + stop = halt::null_reference; + break; + } + ((address + code[pc + 2] as u64) as *mut u8)[0] = fp[code[pc + 3]] as u8; + pc += bc_widths[bc::store_8 as u64]; + } + bc::store_32 as u32 => { + val address := fp[code[pc + 1]]; + if address < null_page { + stop = halt::null_reference; + break; + } + ((address + code[pc + 2] as u64) as *mut u32)[0] = fp[code[pc + 3]] as u32; + pc += bc_widths[bc::store_32 as u64]; + } + bc::copy as u32 => { + val to := fp[code[pc + 1]]; + val from := fp[code[pc + 2]]; + val size := code[pc + 3] as u64; + if size != 0 && (to < null_page || from < null_page) { + stop = halt::null_reference; + break; + } + memcpy(to as *mut u8, from as *u8, size); + if this.options.checks { + this.copy_unwritten(to, from, size); + } + pc += bc_widths[bc::copy as u64]; + } + bc::clear as u32 => { + val to := fp[code[pc + 1]]; + val size := code[pc + 2] as u64; + if size != 0 && to < null_page { + stop = halt::null_reference; + break; + } + memset(to as *mut u8, 0, size); + if this.options.checks { + this.wrote(to, size); + } + pc += bc_widths[bc::clear as u64]; + } + bc::check as u32 => { + if fp[code[pc + 1]] == 0 { + stop = halt_of(code[pc + 2] as u64); + break; + } + pc += bc_widths[bc::check as u64]; + } + bc::global as u32 => { + fp[code[pc + 1]] = this.globals as u64 + code[pc + 2] as u64; + pc += bc_widths[bc::global as u64]; + } + bc::datum as u32 => { + fp[code[pc + 1]] = this.data[code[pc + 2]] + code[pc + 3] as u64; + pc += bc_widths[bc::datum as u64]; + } + bc::call_trait as u32 => { + val argc := code[pc + 3] as u64; + val args := pc + 4; + val results := args + argc; + val back := results + 1 + code[results] as u64; + val slot := code[pc + 2] as u64; + val vtable := fp[code[args + 1]]; + if vtable >= this.c.program.vtables.length || slot >= this.c.program.vtables[vtable].functions.length { + stop = halt::null_reference; + break; + } + val callee: u32 = this.c.program.vtables[vtable].functions[slot]; + if callee == no_function { + stop = halt::null_reference; + break; + } + if counting { + stop = this.spent(); + break if stop != halt::none; + } + val held: routine = routines[callee]; + val next := (fp as u64 + routines[current].frame) as *mut u64; + if next as u64 + held.frame > this.stack_end { + stop = halt::stack_overflow; + break; + } + + # `this` is the reference the trait reference holds, and a default of a + # trait this one composes is given the vtable whose slots it addresses. + var k: u64 = 2; + if held.count != 0 { + val taken: param_slot = this.params[held.params as u64]; + val at := taken.offset / word_size; + next[at] = fp[code[args]]; + if taken.words == 2 { + next[at + 1] = this.c.program.vtables[vtable].owners[slot] as u64; + } + k = this.pass(&held, next, fp, code, args, 2, 1); + } + val dst: u64 = held.returned != 0 ? fp[code[args + k]] : 0; + this.enter(callee, &held, next, back, pc, results, dst); + if this.jit_on { + val ran := this.call_native(callee, next, fp, code, results, current); + if ran != jit_declined { + if ran != 0 { + stop = halt_numbered(ran); + origin = this.jit_origin; + break; + } + counting = evaluating || this.options.steps != 0 || this.threads != null; + pc = back; + continue; + } + } + current = callee; + code = held.code; + fp = next; + pc = 0; + } + bc::call_value as u32 => { + val argc := code[pc + 2] as u64; + val args := pc + 3; + val results := args + argc; + val back := results + 1 + code[results] as u64; + val index := fp[code[args]] - 1; + if index >= this.routines.length { + stop = halt::null_reference; + break; + } + if counting { + stop = this.spent(); + break if stop != halt::none; + } + val callee := index as u32; + val held: routine = routines[callee]; + val next := (fp as u64 + routines[current].frame) as *mut u64; + if next as u64 + held.frame > this.stack_end { + stop = halt::stack_overflow; + break; + } + val k := this.pass(&held, next, fp, code, args, 2, 0); + if held.closure { + next[held.env / word_size] = fp[code[args + 1]]; + } + val dst: u64 = held.returned != 0 ? fp[code[args + k]] : 0; + this.enter(callee, &held, next, back, pc, results, dst); + if this.jit_on { + val ran := this.call_native(callee, next, fp, code, results, current); + if ran != jit_declined { + if ran != 0 { + stop = halt_numbered(ran); + origin = this.jit_origin; + break; + } + counting = evaluating || this.options.steps != 0 || this.threads != null; + pc = back; + continue; + } + } + current = callee; + code = held.code; + fp = next; + pc = 0; + } + bc::ret_memory as u32 => { + val address := fp[code[pc + 1]]; + val done: call_record = this.calls.last(); + val size := routines[current].returned; + if done.dst != 0 && address != 0 { + memcpy(done.dst as *mut u8, address as *u8, size); + } + if this.calls.length == base + 1 { + this.leave(base); + return halt::none; + } + val caller: call_record = this.calls.at(this.calls.length - 2); + this.calls.truncate(); + current = caller.function; + code = routines[current].code; + fp = caller.fp; + pc = done.back; + this.top = fp as u64 + routines[current].frame; + } + bc::shl as u32 => { + fp[code[pc + 1]] = fp[code[pc + 2]] << fp[code[pc + 3]]; + pc += bc_widths[bc::shl as u64]; + } + bc::shru as u32 => { + fp[code[pc + 1]] = fp[code[pc + 2]] >> fp[code[pc + 3]]; + pc += bc_widths[bc::shru as u64]; + } + bc::shrs as u32 => { + fp[code[pc + 1]] = ((fp[code[pc + 2]] as i64) >> fp[code[pc + 3]]) as u64; + pc += bc_widths[bc::shrs as u64]; + } + bc::bxor as u32 => { + fp[code[pc + 1]] = fp[code[pc + 2]] ^ fp[code[pc + 3]]; + pc += bc_widths[bc::bxor as u64]; + } + bc::divu as u32, bc::remu as u32, bc::divs as u32, bc::rems as u32 => { + val a := fp[code[pc + 2]]; + val b := fp[code[pc + 3]]; + if b == 0 { + stop = halt::division; + break; + } + var made: u64 = 0; + if kind == bc::divu as u32 { + made = a / b; + } else if kind == bc::remu as u32 { + made = a % b; + } else if (b as i64) == -1 { + made = kind == bc::divs as u32 ? 0 - a : 0; + } else if kind == bc::divs as u32 { + made = ((a as i64) / (b as i64)) as u64; + } else { + made = ((a as i64) % (b as i64)) as u64; + } + fp[code[pc + 1]] = made; + pc += bc_widths[bc::divu as u64]; + } + bc::eqsu as u32 => { + val a := fp[code[pc + 2]]; + val b := fp[code[pc + 3]]; + fp[code[pc + 1]] = (a as i64) >= 0 && a == b ? 1 : 0; + pc += bc_widths[bc::eqsu as u64]; + } + bc::ltsu as u32 => { + val a := fp[code[pc + 2]]; + val b := fp[code[pc + 3]]; + fp[code[pc + 1]] = (a as i64) < 0 || a < b ? 1 : 0; + pc += bc_widths[bc::ltsu as u64]; + } + bc::lesu as u32 => { + val a := fp[code[pc + 2]]; + val b := fp[code[pc + 3]]; + fp[code[pc + 1]] = (a as i64) < 0 || a <= b ? 1 : 0; + pc += bc_widths[bc::lesu as u64]; + } + bc::ltus as u32 => { + val a := fp[code[pc + 2]]; + val b := fp[code[pc + 3]]; + fp[code[pc + 1]] = (b as i64) >= 0 && a < b ? 1 : 0; + pc += bc_widths[bc::ltus as u64]; + } + bc::leus as u32 => { + val a := fp[code[pc + 2]]; + val b := fp[code[pc + 3]]; + fp[code[pc + 1]] = (b as i64) >= 0 && a <= b ? 1 : 0; + pc += bc_widths[bc::leus as u64]; + } + # Each arithmetic of reals is a case of its own, as code works them + # often, and each of `f32`s rounds what the `f64`s' gives. + bc::fadd as u32 => { + val reals := fp as *mut f64; + reals[code[pc + 1]] = reals[code[pc + 2]] + reals[code[pc + 3]]; + pc += bc_widths[bc::fadd as u64]; + } + bc::fsub as u32 => { + val reals := fp as *mut f64; + reals[code[pc + 1]] = reals[code[pc + 2]] - reals[code[pc + 3]]; + pc += bc_widths[bc::fsub as u64]; + } + bc::fmul as u32 => { + val reals := fp as *mut f64; + reals[code[pc + 1]] = reals[code[pc + 2]] * reals[code[pc + 3]]; + pc += bc_widths[bc::fmul as u64]; + } + bc::fdiv as u32 => { + val reals := fp as *mut f64; + reals[code[pc + 1]] = reals[code[pc + 2]] / reals[code[pc + 3]]; + pc += bc_widths[bc::fdiv as u64]; + } + bc::frem as u32 => { + val reals := fp as *mut f64; + reals[code[pc + 1]] = reals[code[pc + 2]] % reals[code[pc + 3]]; + pc += bc_widths[bc::frem as u64]; + } + bc::fadd_f32 as u32 => { + val reals := fp as *mut f64; + reals[code[pc + 1]] = ((reals[code[pc + 2]] + reals[code[pc + 3]]) as f32) as f64; + pc += bc_widths[bc::fadd_f32 as u64]; + } + bc::fsub_f32 as u32 => { + val reals := fp as *mut f64; + reals[code[pc + 1]] = ((reals[code[pc + 2]] - reals[code[pc + 3]]) as f32) as f64; + pc += bc_widths[bc::fsub_f32 as u64]; + } + bc::fmul_f32 as u32 => { + val reals := fp as *mut f64; + reals[code[pc + 1]] = ((reals[code[pc + 2]] * reals[code[pc + 3]]) as f32) as f64; + pc += bc_widths[bc::fmul_f32 as u64]; + } + bc::fdiv_f32 as u32 => { + val reals := fp as *mut f64; + reals[code[pc + 1]] = ((reals[code[pc + 2]] / reals[code[pc + 3]]) as f32) as f64; + pc += bc_widths[bc::fdiv_f32 as u64]; + } + bc::feq as u32, bc::fne as u32, bc::flt as u32, bc::fle as u32 => { + val reals := fp as *mut f64; + val x := reals[code[pc + 2]]; + val y := reals[code[pc + 3]]; + val holds := match kind { + bc::feq as u32 => x == y, + bc::fne as u32 => x != y, + bc::flt as u32 => x < y, + else => x <= y + }; + fp[code[pc + 1]] = holds ? 1 : 0; + pc += bc_widths[bc::feq as u64]; + } + bc::neg as u32 => { + fp[code[pc + 1]] = 0 - fp[code[pc + 2]]; + pc += bc_widths[bc::neg as u64]; + } + bc::bnot as u32 => { + fp[code[pc + 1]] = ~fp[code[pc + 2]]; + pc += bc_widths[bc::bnot as u64]; + } + bc::lnot as u32 => { + fp[code[pc + 1]] = fp[code[pc + 2]] == 0 ? 1 : 0; + pc += bc_widths[bc::lnot as u64]; + } + bc::fsingle as u32 => { + val reals := fp as *mut f64; + reals[code[pc + 1]] = (reals[code[pc + 2]] as f32) as f64; + pc += bc_widths[bc::fsingle as u64]; + } + bc::fneg as u32 => { + val reals := fp as *mut f64; + reals[code[pc + 1]] = -reals[code[pc + 2]]; + pc += bc_widths[bc::fneg as u64]; + } + bc::itof as u32, bc::utof as u32 => { + val reals := fp as *mut f64; + val word := fp[code[pc + 2]]; + reals[code[pc + 1]] = kind == bc::itof as u32 ? (word as i64) as f64 : word as f64; + pc += bc_widths[bc::itof as u64]; + } + bc::fsqrt as u32 => { + val reals := fp as *mut f64; + reals[code[pc + 1]] = root_of(reals[code[pc + 2]]); + pc += bc_widths[bc::fsqrt as u64]; + } + bc::ones as u32, bc::clz as u32, bc::ctz as u32, bc::bswap as u32 => { + val word := fp[code[pc + 2]]; + fp[code[pc + 1]] = match kind { + bc::ones as u32 => ones_of(word), + bc::clz as u32 => leading_zeros_of(word), + bc::ctz as u32 => trailing_zeros_of(word), + else => bytes_swapped(word) + }; + pc += bc_widths[bc::ones as u64]; + } + bc::ftoi as u32 => { + val reals := fp as *mut f64; + fp[code[pc + 1]] = (reals[code[pc + 2]] as i64) as u64; + pc += bc_widths[bc::ftoi as u64]; + } + bc::ftou as u32 => { + val reals := fp as *mut f64; + fp[code[pc + 1]] = reals[code[pc + 2]] as u64; + pc += bc_widths[bc::ftou as u64]; + } + bc::select as u32 => { + # A real is chosen by its bits, as a word is. + fp[code[pc + 1]] = fp[code[pc + 2]] != 0 ? fp[code[pc + 3]] : fp[code[pc + 4]]; + pc += bc_widths[bc::select as u64]; + } + bc::load_i8 as u32, bc::load_i16 as u32, bc::load_u16 as u32, bc::load_f32 as u32 => { + val address := fp[code[pc + 2]]; + if address < null_page { + stop = halt::null_reference; + break; + } + val at := address + code[pc + 3] as u64; + if kind == bc::load_f32 as u32 { + (fp as *mut f64)[code[pc + 1]] = (at as *f32)[0] as f64; + } else if kind == bc::load_i8 as u32 { + fp[code[pc + 1]] = ((at as *i8)[0] as i64) as u64; + } else if kind == bc::load_i16 as u32 { + fp[code[pc + 1]] = ((at as *i16)[0] as i64) as u64; + } else { + fp[code[pc + 1]] = (at as *u16)[0] as u64; + } + pc += bc_widths[bc::load_i8 as u64]; + } + bc::store_16 as u32, bc::store_f32 as u32 => { + val address := fp[code[pc + 1]]; + if address < null_page { + stop = halt::null_reference; + break; + } + val at := address + code[pc + 2] as u64; + if kind == bc::store_f32 as u32 { + (at as *mut f32)[0] = (fp as *mut f64)[code[pc + 3]] as f32; + } else { + (at as *mut u16)[0] = fp[code[pc + 3]] as u16; + } + pc += bc_widths[bc::store_16 as u64]; + } + bc::switch as u32 => { + val value := fp[code[pc + 1]]; + val cases := code[pc + 2] as u64; + var target := code[pc + 3 + 3 * cases] as u64; + for i in 0..cases { + val at := pc + 3 + 3 * i; + if (code[at] as u64 | (code[at + 1] as u64 << 32)) == value { + target = code[at + 2] as u64; + break; + } + } + if counting { + stop = this.spent(); + break if stop != halt::none; + } + pc = target; + } + bc::safepoint as u32 => { + # Handlers run in the thread the program began with. + if evaluating || (this.threads != null && this.strand != this.threads[0].strands[0]) || !signals_came() { + pc += bc_widths[bc::safepoint as u64]; + continue; + } + val callee := code[pc + 1]; + val held: routine = routines[callee]; + val next := (fp as u64 + routines[current].frame) as *mut u64; + if next as u64 + held.frame > this.stack_end { + stop = halt::stack_overflow; + break; + } + this.enter(callee, &held, next, pc + 2, pc, none, 0); + current = callee; + code = held.code; + fp = next; + pc = 0; + } + else => { + stop = this.slow_op(kind, fp, code, pc, current); + break if stop != halt::none; + # Starting a thread has the threads take turns, by steps. + counting = evaluating || this.options.steps != 0 || this.threads != null; + pc += op_width(code, pc); + } + } + } + return this.stopped(stop, origin); +} + +#! Ends a run that stopped: where another thread stopped the program, its +#! trace is the one reported, and otherwise where each call was is recorded. +#! @param this The machine. +#! @param stop Why it stopped. +#! @param origin Where in its code the innermost call was. +#! @returns Why it stopped. +def interpreter::stopped(&mut this, stop: halt, origin: u64): halt { + if stop == halt::elsewhere { + if this.options.checks && this.threads[0].stop == halt::exited { + this.keep_frames(); + } + this.calls.clear(); + this.depth = 0; + this.top = this.stack as u64; + return stop; + } + this.record(origin); + return stop; +} + +#! How many words an operation of the code takes, its operation and operands +#! together, as `bc_widths` says and the counts those followed by one give. +#! @param code The code. +#! @param pc Where the operation is. +#! @returns The words. +pub def op_width(code: *u32, pc: u64): u64 { + val kind := code[pc]; + val base := bc_widths[kind as u64]; + return match kind { + bc::call as u32, bc::call_value as u32, bc::call_c as u32 => base + code[pc + 2] as u64 + code[pc + 3 + code[pc + 2] as u64] as u64, + bc::call_trait as u32 => base + code[pc + 3] as u64 + code[pc + 4 + code[pc + 3] as u64] as u64, + bc::format_value as u32 => base + code[pc + 2] as u64, + bc::switch as u32 => base + 3 * code[pc + 2] as u64, + bc::ret as u32 => base + code[pc + 1] as u64, + else => base + }; +} + +#! Runs one of the operations code runs least: memory the program gives back +#! itself, text being formatted, the system, C, threads, atomics, what stops the +#! program, and what only a run checking its memory or evaluating constants +#! has. Neither the interpreter's loop nor compiled code holds these itself. +#! @param this The machine. +#! @param kind The operation. +#! @param fp The frame. +#! @param code The code of the function running. +#! @param pc Where the operation is. +#! @param current The function running. +#! @returns Why the run stops, or `none` where it goes on past the operation. +pub def interpreter::slow_op(&mut this, kind: u32, fp: *mut u64, code: *u32, pc: u64, current: u32): halt { + val evaluating := this.options.evaluating; + match kind { + bc::allocate as u32 => { + fp[code[pc + 1]] = this.allocate(fp[code[pc + 2]], code[pc + 3] == 0); + if this.options.checks { + this.note_site(fp[code[pc + 1]], pc as u64); + } + } + bc::release as u32 => { + return this.release(fp[code[pc + 1]]); + } + bc::resize as u32 => { + val address := fp[code[pc + 2]]; + return halt::invalid_release if address != 0 && !this.blocks.contains(&address); + # Running with its memory checked, the block keeps where it was allocated. + var site: u64 = none; + if this.options.checks && this.sites.get(&address) is some(was) { + site = was; + } + fp[code[pc + 1]] = this.resize(address, fp[code[pc + 3]]); + if this.options.checks { + if site == none { + this.note_site(fp[code[pc + 1]], pc as u64); + } else { + this.sites.set(fp[code[pc + 1]], site); + } + } + } + bc::equal as u32 => { + fp[code[pc + 1]] = this.equal(fp[code[pc + 2]], fp[code[pc + 3]], code[pc + 4], 0) ? 1 : 0; + } + bc::retrait as u32 => { + val map: u32 = code[pc + 3]; + val vtable := fp[code[pc + 2]]; + return halt::null_reference if vtable >= this.c.program.retraits[map].vtables.length; + fp[code[pc + 1]] = this.c.program.retraits[map].vtables[vtable] as u64; + } + bc::format as u32 => { + this.begin_text(); + } + bc::format_text as u32 => { + val index: u32 = code[pc + 1]; + val length := this.c.program.data[index].bytes.length; + this.add_text(this.data[index], length == 0 ? 0 : length - 1); + } + bc::format_value as u32 => { + this.format_operands(code[pc + 1], fp, code, pc + 3, code[pc + 2] as u64); + } + bc::format_bytes as u32 => { + this.add_text(fp[code[pc + 1]], fp[code[pc + 2]]); + } + bc::format_owned as u32 => { + val made := this.owned_text(); + if this.options.checks { + this.note_site(made, pc as u64); + } + fp[code[pc + 1]] = made; + fp[code[pc + 2]] = made == 0 ? 0 : this.blocks[made]; + } + bc::syscall as u32 => { + return halt::not_constant if evaluating; + # Other threads run while it waits in the system, but around starting a + # copy of the program, where none may hold the turn the copy needs. + val number := fp[code[pc + 2]]; + val copies := number == 56 || number == 57 || number == 58; + val mine := this.strand; + var spec: i64[2]; + val time := number == 202 ? this.wait_time(fp[code[pc + 4]], fp[code[pc + 6]], (&mut spec) as *mut i64) : fp[code[pc + 6]]; + if !copies { + this.pause(); + } + val result := system_call(number, fp[code[pc + 3]], fp[code[pc + 4]], fp[code[pc + 5]], + time, fp[code[pc + 7]], fp[code[pc + 8]], this); + if !copies { + val after := this.resume(mine); + return after if after != halt::none; + } + if copies && result == 0 { + this.forked(); + } + if this.options.checks && result as i64 >= 0 { + this.note_mapping(number, fp[code[pc + 3]], fp[code[pc + 4]], fp[code[pc + 5]], result); + } + # What the system wrote through an address it was given is not known, so + # all it may have reached counts as written. + if this.options.checks { + for k in 3..9u { + this.wrote_through(fp[code[pc + k]]); + } + } + fp[code[pc + 1]] = result; + } + bc::environ as u32 => { + return halt::not_constant if evaluating; + fp[code[pc + 1]] = this.environment(); + } + bc::signals as u32 => { + return halt::not_constant if evaluating; + _ = signals_came(); + fp[code[pc + 1]] = noted_signals; + noted_signals = 0; + } + bc::catch as u32 => { + return halt::not_constant if evaluating; + fp[code[pc + 1]] = catch_signal(fp[code[pc + 2]] as i64) as u64; + } + bc::exit as u32 => { + this.status = fp[code[pc + 1]] as i32; + if this.options.checks { + this.keep_frames(); + } + this.calls.clear(); + this.depth = 0; + this.top = this.stack as u64; + return halt::exited; + } + bc::abort as u32 => { + return halt::aborted; + } + bc::fault as u32 => { + # Another thread may have faulted first, whose text is kept. + if this.fault_text.length == 0 { + this.fault_text = string::from(span::::over(fp[code[pc + 1]] as *u8, fp[code[pc + 2]]), nothing {}); + } + return halt::faulted; + } + bc::trap as u32 => { + return halt_of(code[pc + 1] as u64); + } + bc::trap_word as u32 => { + return halt_of(fp[code[pc + 1]]); + } + bc::ready as u32 => { + val index := code[pc + 1] as u64; + if index >= this.ready.length || !this.ready[index] { + this.waiting = index as u32; + return halt::not_evaluated; + } + } + bc::reach as u32 => { + val held := evaluating ? this.reaches(fp[code[pc + 1]], fp[code[pc + 2]], code[pc + 3] as u64) + : this.checked_reach(fp[code[pc + 1]], fp[code[pc + 2]], code[pc + 3] as u64); + return halt::invalid_access if !held; + } + bc::same as u32 => { + return halt::address if !this.same_memory(fp[code[pc + 1]], fp[code[pc + 2]]); + } + bc::atomic as u32 => { + val operation := code[pc + 2]; + if operation == atomic_fence { + fence(order::seq_cst); + } else { + val address := fp[code[pc + 4]]; + return halt::null_reference if address < null_page; + # An operation taking fewer operands names the frame's scratch word for + # the others, which nothing need have written, so only those it takes + # are read. + val a := operation == atomic_load ? 0u : fp[code[pc + 5]]; + val b := operation == atomic_compare_exchange ? fp[code[pc + 6]] : 0u; + fp[code[pc + 1]] = atomically(address, operation, code[pc + 3] as u64, a, b); + if this.options.checks { + this.wrote(address, word_size); + } + } + } + bc::start as u32 => { + return halt::not_constant if evaluating; + val function := fp[code[pc + 2]]; + return halt::null_reference if function == 0 || function > this.routines.length; + fp[code[pc + 1]] = this.start_thread(function, fp[code[pc + 3]], fp[code[pc + 4]]) as u64; + } + bc::unreachable as u32 => { + return halt::unreachable; + } + bc::forget as u32 => { + this.forget(fp[code[pc + 1]], code[pc + 2] as u64); + this.framed_unwritten = true; + } + bc::watch_read as u32 => { + val address := fp[code[pc + 1]]; + return halt::unwritten if address >= null_page && this.unwritten_in(address + code[pc + 2] as u64, code[pc + 3] as u64); + } + bc::watch_write as u32 => { + this.wrote(fp[code[pc + 1]] + code[pc + 2] as u64, code[pc + 3] as u64); + } + bc::call_c as u32 => { + # Only the system running the machine, Windows, is called, as the C + # machine calls C there; elsewhere this machine does not call C. + when os == windows { + return halt::not_constant if evaluating; + val argc := code[pc + 2] as u64; + # What C gives `system` only its own code reads, so the program may + # hold memory of C's once code of its own calls C, even C `system` + # declares, as where a global of its own is given its value. + if this.options.checks && !this.called_c { + this.called_c = !this.in_system_code(current, pc); + } + val halted := this.call_foreign(code, pc, fp); + return halted if halted != halt::none; + if this.options.checks { + for k in 1..argc { + this.wrote_through(fp[code[pc + 3 + k]]); + } + } + } else { + return evaluating ? halt::not_constant : halt::unsupported; + } + } + bc::c_address as u32 => { + when os == windows { + return halt::not_constant if evaluating; + fp[code[pc + 1]] = this.c_address(code[pc + 2]); + } else { + return evaluating ? halt::not_constant : halt::unsupported; + } + } + bc::callback as u32 => { + when os == windows { + return halt::not_constant if evaluating; + val made := this.callback_address(code[pc + 2]); + return halt::out_of_memory if made == 0; + fp[code[pc + 1]] = made; + } else { + return evaluating ? halt::not_constant : halt::unsupported; + } + } + else => { + # What only an executable has, this machine does not do. + return evaluating ? halt::not_constant : halt::unsupported; + } + } + return halt::none; +} + +#! Copies the arguments of a call into the frame of the function it calls, as +#! the function's parameters say, from the operand and parameter given on. +#! @param this The machine. +#! @param held The function called. +#! @param next Its frame. +#! @param fp The caller's frame. +#! @param code The caller's code. +#! @param args Where the call's operands begin in the code. +#! @param from The first operand copied. +#! @param first The first parameter copied. +#! @returns The operand after the last copied. +def interpreter::pass(&mut this, held: &routine, next: *mut u64, fp: *mut u64, code: *u32, args: u64, from: u64, first: u32): u64 { + var k := from; + for p in first..held.count { + val slot: param_slot = this.params[held.params as u64 + p as u64]; + if slot.memory { + val source := fp[code[args + k]]; + if source != 0 { + memcpy((next as u64 + slot.offset) as *mut u8, source as *u8, slot.size); + } + k++; + continue; + } + val at := slot.offset / word_size; + for w in 0..slot.words { + next[at + w as u64] = fp[code[args + k]]; + k++; + } + } + return k; +} + +#! Begins a call: the cells of the frame of the function called that are read +#! before they are written are zeroed, and the call is recorded. +#! @param this The machine. +#! @param callee The function called. +#! @param held How the machine calls it. +#! @param next Its frame. +#! @param back Where the caller goes on. +#! @param site Where the call is in the caller's code. +#! @param results Where the caller's code lists the words of the results, or +#! `none`. +#! @param dst Where a result held in memory is written. +def interpreter::enter(&mut this, callee: u32, held: &routine, next: *mut u64, back: u64, site: u64, results: u64, dst: u64): void { + if held.zeroed > held.cells { + memset((next as u64 + held.cells) as *mut u8, 0, held.zeroed - held.cells); + } + # Running with its memory checked, what a frame before left never written is + # not this one's. + if this.framed_unwritten { + this.wrote(next as u64, held.frame); + } + this.calls.append(call_record { + function = callee, + fp = next, + back = back, + site = site, + results = results, + dst = dst + }); + this.top = next as u64 + held.frame; +} + +#! Ends the call the machine began, leaving those beneath it. +#! @param this The machine. +#! @param base How many calls are beneath it. +def interpreter::leave(&mut this, base: u64): void { + this.calls.truncate(); + if base == 0 { + this.top = this.stack as u64; + return; + } + val under: call_record = this.calls.at(base - 1); + this.top = under.fp as u64 + this.routines[under.function].frame; +} diff --git a/machine/jit.sakura b/machine/jit.sakura new file mode 100644 index 00000000..a9d5cd6d --- /dev/null +++ b/machine/jit.sakura @@ -0,0 +1,2523 @@ +#! @file jit.sakura +#! @author John Christman (sorakatadzuma@gmail.com) +#! @copyright Malunal Studios, LLC. +#! @license MIT +#! +#! Contains compiling functions to the processor's code as they are first +#! called, where the machine runs on Windows as an executable, which is where it +#! calls C too. Each operation of a function's code becomes the instructions +#! doing its work over the same frame of words the interpreter reads, so a +#! compiled function and an interpreted one call each other, and see each +#! other's frames, as two interpreted ones do. Running with memory checked, or +#! evaluating constants, every function is interpreted. +#! +#! Compiled code keeps the machine's own records: it pushes a call record for +#! each call and pops it as the call returns, and where it stops, every record +#! is left for the trace, with the place in the bytecode of the innermost +#! function in `jit_origin`. What the interpreter does rarely, as formatting, +#! allocating, the system, and C, compiled code has `slow_op` do, so each is +#! written once. +#! +#! While compiled code runs: +#! - `rbx` is the frame of the function running; +#! - `r12` the machine; +#! - `r14` the lowest the stack of the system's thread may reach before calls +#! are interpreted, which take only the machine's own stack; +#! - `r15` the steps left before compiled code settles what it took, as a jump +#! or a call takes one: `jit_arm` gives it as many as the host allows and a +#! thread's turn has, and `jit_tick` settles them as they run out; +#! - a function returns its words in `rdx`, `rcx`, and `r8`, and in `eax` 0, or +#! the halt it stopped with. + +import std::containers; +import system::windows; +import sakura::compiler; +module sakura::machine; + + +#! What `run_native` and `call_native` give where the function was not run as +#! compiled code, which the machine then interprets. No halt is numbered so. +pub const jit_declined: u64 = 0xFFFF; + +#! The halt a number compiled code gives stands for. +#! @param code The number, as `halt` numbers its members. +#! @returns The halt. +pub def halt_numbered(code: u64): halt { + return match code { + 0 => halt::none, 2 => halt::no_main, 3 => halt::unsupported, + 4 => halt::out_of_bounds, 5 => halt::null_reference, 6 => halt::division, + 7 => halt::not_held, 8 => halt::stack_overflow, 9 => halt::unreachable, + 11 => halt::invalid_release, 13 => halt::not_member, 15 => halt::not_constant, + 16 => halt::evaluation_limit, 17 => halt::not_evaluated, 18 => halt::invalid_access, + 19 => halt::address, 20 => halt::exited, 21 => halt::aborted, + 22 => halt::foreign_missing, 23 => halt::callback, 24 => halt::out_of_memory, + 25 => halt::elsewhere, 26 => halt::faulted, 27 => halt::unwritten, + 28 => halt::step_limit, + else => halt::unsupported + }; +} + +#! Where compiled code finds what it reads and writes of the machine, as the +#! bytes from the machine's first to each field's, and the functions it calls. +pub struct jit_layout { + var calls_data: u64; #! `calls`' records. + var calls_used: u64; #! How many calls are running. + var calls_capacity: u64; #! How many records fit. + var top: u64; #! `top`. + var stack_end: u64; #! `stack_end`. + var left: u64; #! `jit_left`. + var origin: u64; #! `jit_origin`. + var results: u64; #! `results`. + var table: u64; #! The address of `jit_table`. + var tick: u64; #! `jit_helper_tick`. + var slow: u64; #! `jit_helper_slow`. + var call: u64; #! `jit_helper_call`. + var grow: u64; #! `jit_helper_grow`. + var copy: u64; #! `jit_helper_copy`. + var zero: u64; #! `jit_helper_zero`. + var frem: u64; #! `jit_helper_frem`. + var guard: u64; #! The code a helper is called through, keeping `xmm6` to `xmm15`. + var quick: u64; #! `jit_helper_quick`. + var threads: u64; #! `threads`. + var writes_at: u64; #! `writes_at`. + var console_at: u64; #! `console_writes_at`. + var calling_c: u64; #! `calling_c`. + var last_error: u64; #! `last_error`. + var foreign_fault: u64; #! `foreign_fault`. +} + +#! As many steps as compiled code takes where nothing counts them. +const jit_unbounded: u64 = 0x4000000000000000; + +#! Gives compiled code the steps it may take before it settles them: as many as +#! the host still allows, the last of which stops it, and as a thread's turn +#! has left. +#! @param this The machine. +def interpreter::jit_arm(&mut this): void { + var batch := jit_unbounded; + if this.options.steps != 0 && this.budget < batch { + batch = this.budget + 1; + } + if this.threads != null && this.countdown < batch { + batch = this.countdown; + } + if batch == 0 { + batch = 1; + } + this.jit_batch = batch; + this.jit_left = batch; +} + +#! Takes the steps compiled code took from what the host allows and the turn, +#! none of them the last of either, so the machine's own code counts on. +#! @param this The machine. +def interpreter::jit_settle(&mut this): void { + val used := this.jit_batch - this.jit_left; + if this.options.steps != 0 { + this.budget = this.budget >= used ? this.budget - used : 0; + } + if this.threads != null { + this.countdown = this.countdown > used ? this.countdown - used : 1; + } + this.jit_batch = 0; + this.jit_left = 0; +} + +when backend == native && os == windows { + # What the stub entering compiled code leaves of the system's stack above its + # lowest, for the machine's own code and the host's to run in. + const jit_stack_margin: u64 = 0x20000; + + # The bytes of executable memory taken at once. + const jit_chunk: u64 = 0x100000; + + # The paths compiled code takes rarely, made after the function's own code. + const cold_fault: u8 = 0; # Stops with a halt: the place, the halt. + const cold_error: u8 = 1; # Stops with the halt in `eax`. + const cold_tick: u8 = 2; # Settles the steps taken, then goes back. + const cold_call: u8 = 3; # Calls as the interpreter does, then goes back. + const cold_grow: u8 = 4; # Makes room for more call records, then goes back. + const cold_pass: u8 = 5; # Stops with the halt a compiled callee gave, the place it left kept. + + # A path compiled code takes rarely. + struct jit_cold { + var kind: u8; #! What it does. + var from: u64; #! The displacement of the jump into it. + var back: u64; #! Where in the code it goes back to. + var pc: u64; #! Where the operation is in the bytecode. + var value: u64; #! The halt, for a fault. + } + + # Where a word of the frame is held while compiled code runs. A word held in + # a register is written to the frame only where the machine's own code reads + # it, and read back from it only where that code writes it. + const held_memory: u8 = 0; # In the frame. + const held_gpr: u8 = 1; # In a general register. + const held_real: u8 = 2; # In an XMM register, as the double the frame holds. + const held_single: u8 = 3; # In an XMM register, as the single the double is exactly. + + # The registers words are held in, which Microsoft's ABI has a callee keep, so + # calls of compiled code and of the machine's helpers leave them as they were. + const word_gprs: u8[4] = [rsi, rdi, r13, rbp]; + const word_xmms: u8[10] = [6, 7, 8, 9, 10, 11, 12, 13, 14, 15]; + + # The XMM register a word held as a single is widened in to be read as bits. + const xmm_scratch: u8 = 5; + + # What stands for no register. + const no_reg: u8 = 0xFF; + + # What compiling a function keeps track of. + struct jit_function : owning { + var out: machine_code; #! The code made. + var at: vector; #! Where each operation of the bytecode begins in it; the bytecode's end is the exit. + var jumps: vector; #! Pairs: where a displacement is, and the bytecode it jumps to. + var colds: vector; #! The paths taken rarely. + var function: u32; #! The function. + var frame: u64; #! The bytes of its frame. + var exit: u64; #! Where the bytecode ends, which jumps to the exit name. + var layout: jit_layout; #! Where it reaches the machine. + var places: vector; #! Where each word is held. + var regs: vector; #! The register of each word held in one. + var exact: vector; #! Whether each word only ever holds a double a single holds exactly. + var held: vector; #! The words held in registers. + var lows: vector; #! Where in the code each word's span begins, which a register holds it over. + var highs: vector; #! Where it ends. + var gprs: u64; #! How many of `word_gprs` it uses, which it keeps. + var xmms: u64; #! How many of `word_xmms` it uses, which it keeps. + var reserved: u64; #! The bytes it takes of the stack below what it pushes. + } + + def jit_function::close(&mut this): void { + this.out.close(); + this.at.close(); + this.jumps.close(); + this.colds.close(); + this.places.close(); + this.regs.close(); + this.exact.close(); + this.held.close(); + this.lows.close(); + this.highs.close(); + } + + # The displacement of a word of the frame. + def slot_at(index: u32): u64 { + return index as u64 * word_size; + } + + # Where a word is held. + def jit_function::place(&this, index: u32): u8 { + return (index as u64) < this.places.length ? this.places[index as u64] : held_memory; + } + + # The register a word is held in. + def jit_function::reg(&this, index: u32): u8 { + return this.regs[index as u64]; + } + + # The general register a word is held in, or `no_reg`. + def jit_function::gpr_of(&this, index: u32): u8 { + return this.place(index) == held_gpr ? this.reg(index) : no_reg; + } + + # The XMM register a word is held in as a double, or `no_reg`. + def jit_function::real_of(&this, index: u32): u8 { + return this.place(index) == held_real ? this.reg(index) : no_reg; + } + + # The XMM register a word is held in as a single, or `no_reg`. + def jit_function::single_of(&this, index: u32): u8 { + return this.place(index) == held_single ? this.reg(index) : no_reg; + } + + # The register holding an address a word holds: its own, where it is held in + # a general register, or `rax`, which it is read into. + def jit_function::address_in(&mut this, index: u32): u8 { + val held := this.gpr_of(index); + return held if held != no_reg; + this.get(rax, index); + return rax; + } + + # Whether a word only ever holds what a single holds exactly. + def jit_function::is_exact(&this, index: u32): bool { + return (index as u64) < this.exact.length && this.exact[index as u64]; + } + + # A word into a general register, as its bits. + def jit_function::get(&mut this, to: u8, index: u32): void { + val at := this.place(index); + if at == held_gpr { + if this.reg(index) != to { + this.out.mov(to, this.reg(index)); + } + } else if at == held_real { + this.out.movq_from_xmm(to, this.reg(index)); + } else if at == held_single { + this.out.sse_reg(0xF3, 0x5A, xmm_scratch, this.reg(index)); + this.out.movq_from_xmm(to, xmm_scratch); + } else { + this.out.load(to, rbx, slot_at(index)); + } + } + + # A general register's bits into a word. + def jit_function::put(&mut this, index: u32, from: u8): void { + val at := this.place(index); + if at == held_gpr { + if this.reg(index) != from { + this.out.mov(this.reg(index), from); + } + } else if at == held_real { + this.out.movq_to_xmm(this.reg(index), from); + } else if at == held_single { + this.out.movq_to_xmm(xmm_scratch, from); + this.out.sse_reg(0xF2, 0x5A, this.reg(index), xmm_scratch); + } else { + this.out.store(rbx, slot_at(index), from); + } + } + + # A word into `xmm`, as a double. + def jit_function::get_real(&mut this, xmm: u8, index: u32): void { + val at := this.place(index); + if at == held_gpr { + this.out.movq_to_xmm(xmm, this.reg(index)); + } else if at == held_real { + this.out.movaps(xmm, this.reg(index)); + } else if at == held_single { + this.out.sse_reg(0xF3, 0x5A, xmm, this.reg(index)); + } else { + this.out.sse_mem(0xF2, 0x10, xmm, rbx, slot_at(index)); + } + } + + # A double in `xmm` into a word. + def jit_function::put_real(&mut this, index: u32, xmm: u8): void { + val at := this.place(index); + if at == held_gpr { + this.out.movq_from_xmm(this.reg(index), xmm); + } else if at == held_real { + this.out.movaps(this.reg(index), xmm); + } else if at == held_single { + this.out.sse_reg(0xF2, 0x5A, this.reg(index), xmm); + } else { + this.out.sse_mem(0xF2, 0x11, xmm, rbx, slot_at(index)); + } + } + + # A word into `xmm`, as a single, rounded as converting the double rounds. + def jit_function::get_single(&mut this, xmm: u8, index: u32): void { + val at := this.place(index); + if at == held_single { + this.out.movaps(xmm, this.reg(index)); + } else if at == held_real { + this.out.sse_reg(0xF2, 0x5A, xmm, this.reg(index)); + } else if at == held_gpr { + this.out.movq_to_xmm(xmm, this.reg(index)); + this.out.sse_reg(0xF2, 0x5A, xmm, xmm); + } else { + this.out.sse_mem(0xF2, 0x5A, xmm, rbx, slot_at(index)); + } + } + + # A single in `xmm` into a word, as the double it is. + def jit_function::put_single(&mut this, index: u32, xmm: u8): void { + if this.place(index) == held_single { + this.out.movaps(this.reg(index), xmm); + return; + } + this.out.sse_reg(0xF3, 0x5A, xmm, xmm); + this.put_real(index, xmm); + } + + # One word into another, as its bits. + def jit_function::copy_word(&mut this, to: u32, from: u32): void { + val t := this.place(to); + val f := this.place(from); + if (t == held_real && f == held_real) || (t == held_single && f == held_single) { + this.out.movaps(this.reg(to), this.reg(from)); + } else if t == held_real && f == held_single { + this.out.sse_reg(0xF3, 0x5A, this.reg(to), this.reg(from)); + } else if t == held_single && f == held_real { + this.out.sse_reg(0xF2, 0x5A, this.reg(to), this.reg(from)); + } else if t == held_gpr && f == held_gpr { + if this.reg(to) != this.reg(from) { + this.out.mov(this.reg(to), this.reg(from)); + } + } else { + this.get(rax, from); + this.put(to, rax); + } + } + + # A word of 64 bits into a word of the frame. + def jit_function::put_imm(&mut this, index: u32, value: u64): void { + val at := this.place(index); + if at == held_gpr { + this.out.mov_imm(this.reg(index), value); + } else if at == held_memory && fits32(value) { + this.out.store_imm(rbx, slot_at(index), value); + } else if at == held_single { + this.out.mov_imm(rax, single_bits(value)); + this.out.movq_to_xmm(this.reg(index), rax); + } else { + this.out.mov_imm(rax, value); + this.put(index, rax); + } + } + + # An arithmetic of a general register and a word, the register written. A + # word held in an XMM register is read through `rcx`. + def jit_function::alu_word(&mut this, ext: u8, reg: u8, index: u32): void { + val at := this.place(index); + if at == held_gpr { + this.out.alu(ext, reg, this.reg(index)); + } else if at == held_memory { + this.out.alu_mem(ext, reg, rbx, slot_at(index)); + } else { + this.get(rcx, index); + this.out.alu(ext, reg, rcx); + } + } + + # `imul reg, word`. + def jit_function::imul_word(&mut this, reg: u8, index: u32): void { + val at := this.place(index); + if at == held_gpr { + this.out.imul(reg, this.reg(index)); + } else if at == held_memory { + this.out.imul_mem(reg, rbx, slot_at(index)); + } else { + this.get(rcx, index); + this.out.imul(reg, rcx); + } + } + + # Sets the flags as `test` of a word with itself does. + def jit_function::test_word(&mut this, index: u32): void { + val at := this.place(index); + if at == held_gpr { + this.out.test(this.reg(index), this.reg(index)); + } else if at == held_memory { + this.out.alu_mem_imm(alu_cmp, rbx, slot_at(index), 0); + } else { + this.get(rcx, index); + this.out.test(rcx, rcx); + } + } + + # An arithmetic of doubles, `xmm` and a word, `xmm` written. Neither is `xmm1`. + def jit_function::real_word(&mut this, opcode: u64, xmm: u8, index: u32): void { + val at := this.place(index); + if at == held_real { + this.out.sse_reg(0xF2, opcode, xmm, this.reg(index)); + } else if at == held_memory { + this.out.sse_mem(0xF2, opcode, xmm, rbx, slot_at(index)); + } else { + this.get_real(1, index); + this.out.sse_reg(0xF2, opcode, xmm, 1); + } + } + + # An arithmetic of singles, `xmm` and a word, `xmm` written. + def jit_function::single_word(&mut this, opcode: u64, xmm: u8, index: u32): void { + if this.place(index) == held_single { + this.out.sse_reg(0xF3, opcode, xmm, this.reg(index)); + } else { + this.get_single(1, index); + this.out.sse_reg(0xF3, opcode, xmm, 1); + } + } + + # Writes a word held in a register to the frame, for the machine's own code + # to read. + def jit_function::spill(&mut this, index: u32): void { + val at := this.place(index); + if at == held_gpr { + this.out.store(rbx, slot_at(index), this.reg(index)); + } else if at == held_real { + this.out.sse_mem(0xF2, 0x11, this.reg(index), rbx, slot_at(index)); + } else if at == held_single { + this.out.sse_reg(0xF3, 0x5A, xmm_scratch, this.reg(index)); + this.out.sse_mem(0xF2, 0x11, xmm_scratch, rbx, slot_at(index)); + } + } + + # Reads a word held in a register back from the frame, after the machine's + # own code wrote it. + def jit_function::reload(&mut this, index: u32): void { + val at := this.place(index); + if at == held_gpr { + this.out.load(this.reg(index), rbx, slot_at(index)); + } else if at == held_real { + this.out.sse_mem(0xF2, 0x10, this.reg(index), rbx, slot_at(index)); + } else if at == held_single { + this.out.sse_mem(0xF2, 0x5A, this.reg(index), rbx, slot_at(index)); + } + } + + # Every word held in a register over a place in the code to the frame. + def jit_function::spill_all(&mut this, pc: u64): void { + for i in 0..this.held.length { + val each: u32 = this.held[i]; + if this.lows[each as u64] <= pc && pc <= this.highs[each as u64] { + this.spill(each); + } + } + } + + # Every word held in a register over a place in the code back from the frame, + # which leaves alone a register held another word's there. + def jit_function::reload_all(&mut this, pc: u64): void { + for i in 0..this.held.length { + val each: u32 = this.held[i]; + if this.lows[each as u64] <= pc && pc <= this.highs[each as u64] { + this.reload(each); + } + } + } + + # The bits of the single a double's bits stand for exactly. + def single_bits(value: u64): u64 { + var wide := value; + val narrow := ((&mut wide) as *mut f64)[0] as f32; + var out: u32 = 0; + ((&mut out) as *mut f32)[0] = narrow; + return out as u64; + } + + # Whether a double's bits stand for what a single holds exactly. + def single_exact(value: u64): bool { + var wide := value; + val real := ((&mut wide) as *mut f64)[0]; + val back := (real as f32) as f64; + var out: u64 = 0; + ((&mut out) as *mut f64)[0] = back; + return out == value; + } + + # A jump, of a condition or none, to an operation of the bytecode. + def jit_function::jump_to(&mut this, cc: u8, target: u64, always: bool): void { + val at := always ? this.out.jmp() : this.out.jcc(cc); + this.jumps.append(at); + this.jumps.append(target); + } + + # A jump, of a condition, into a path taken rarely. + def jit_function::cold(&mut this, cc: u8, kind: u8, pc: u64, value: u64, always: bool): void { + val from := always ? this.out.jmp() : this.out.jcc(cc); + this.colds.append(jit_cold { kind = kind, from = from, back = this.out.length, pc = pc, value = value }); + } + + # Stops where a word in `reg` is an address in the null page. + def jit_function::null_check(&mut this, reg: u8, pc: u64): void { + this.out.alu_imm(alu_cmp, reg, null_page); + this.cold(cc_b, cold_fault, pc, halt::null_reference as u64, false); + } + + # Takes a step, as a jump or a call does. + def jit_function::step(&mut this, pc: u64): void { + this.out.byte(0x49); + this.out.byte(0xFF); + this.out.byte(0xCF); # dec r15 + this.cold(cc_e, cold_tick, pc, 0, false); + } + + # Keeps what the machine's own code reads of compiled code's: the steps left, + # and where the frames in use end, as the host and C calling back place + # frames past them. + def jit_function::sync(&mut this): void { + this.out.store(r12, this.layout.left, r15); + this.out.lea(rax, rbx, this.frame); + this.out.store(r12, this.layout.top, rax); + } + + # The words of the frame an operation the machine's own code runs reads and + # writes, as `slow_op` and `jit_call` reach them. + # @returns Whether they are known; where they are not, every word held in a + # register is written to the frame and read back. + def helper_words(code: *u32, pc: u64, reads: &mut vector, writes: &mut vector): bool { + reads.clear(); + writes.clear(); + val kind := code[pc]; + match kind { + bc::allocate as u32 => { + writes.append(code[pc + 1]); + reads.append(code[pc + 2]); + } + bc::release as u32, bc::exit as u32, bc::trap_word as u32 => { + reads.append(code[pc + 1]); + } + bc::resize as u32, bc::equal as u32 => { + writes.append(code[pc + 1]); + reads.append(code[pc + 2]); + reads.append(code[pc + 3]); + } + bc::retrait as u32, bc::catch as u32 => { + writes.append(code[pc + 1]); + reads.append(code[pc + 2]); + } + bc::format as u32, bc::format_text as u32, bc::safepoint as u32 => {} + bc::format_value as u32 => { + for i in 0..code[pc + 2] as u64 { + reads.append(code[pc + 3 + i]); + } + } + bc::format_bytes as u32, bc::fault as u32 => { + reads.append(code[pc + 1]); + reads.append(code[pc + 2]); + } + bc::format_owned as u32 => { + writes.append(code[pc + 1]); + writes.append(code[pc + 2]); + } + bc::syscall as u32 => { + writes.append(code[pc + 1]); + for k in 2..9u { + reads.append(code[pc + k]); + } + } + bc::environ as u32, bc::signals as u32, bc::c_address as u32, bc::callback as u32 => { + writes.append(code[pc + 1]); + } + bc::atomic as u32 => { + writes.append(code[pc + 1]); + reads.append(code[pc + 4]); + reads.append(code[pc + 5]); + reads.append(code[pc + 6]); + } + bc::start as u32 => { + writes.append(code[pc + 1]); + reads.append(code[pc + 2]); + reads.append(code[pc + 3]); + reads.append(code[pc + 4]); + } + bc::call as u32, bc::call_value as u32, bc::call_c as u32, bc::call_trait as u32 => { + # The arguments, then the count of the results and the words they go to. + val args := pc + (kind == bc::call_trait as u32 ? 4 : 3); + val argc := code[args - 1] as u64; + for i in 0..argc { + reads.append(code[args + i]); + } + val resc := code[args + argc] as u64; + for i in 0..resc { + writes.append(code[args + argc + 1 + i]); + } + } + else => { + return false; + } + } + return true; + } + + # Whether an operation the machine's own code runs may run code of the + # program's, or let another thread run, so the steps taken are settled + # around it and the frames in use known: the system, C, threads, signals' + # handlers, and calls. + def runs_code(kind: u32): bool { + return kind == bc::syscall as u32 || kind == bc::call_c as u32 || kind == bc::start as u32 + || kind == bc::safepoint as u32 || kind == bc::call as u32 || kind == bc::call_trait as u32 + || kind == bc::call_value as u32; + } + + # Writes to the frame the words a helper reads, then calls it with the + # machine, the frame, the function, and the place, reads back the words it + # wrote, and stops with the halt it gives, if any. An operation running no + # code of the program's is run by `jit_helper_quick`, which settles nothing. + def jit_function::call_helper(&mut this, helper: u64, code: *u32, pc: u64): void { + var reads := vector::::new(); + var writes := vector::::new(); + val known := helper_words(code, pc, &mut reads, &mut writes); + if known { + for i in 0..reads.length { + this.spill(reads[i]); + } + } else { + this.spill_all(pc); + } + val full := runs_code(code[pc]) || helper != this.layout.slow; + if full { + this.sync(); + } + this.out.mov(rcx, r12); + this.out.mov(rdx, rbx); + this.out.mov_imm(r8, this.function as u64); + this.out.mov_imm(r9, pc); + this.call_sakura(full ? helper : this.layout.quick); + if full { + this.out.load(r15, r12, this.layout.left); + } + if known { + for i in 0..writes.length { + this.reload(writes[i]); + } + } else { + this.reload_all(pc); + } + reads.close(); + writes.close(); + this.out.test_status(); + this.cold(cc_ne, cold_error, pc, 0, false); + } + + # Calls a helper of the machine's own, its arguments in `rcx`, `rdx`, `r8`, + # and `r9`, through the guard: the machine's code keeps no XMM register across + # a call, where Microsoft's ABI has a callee keep `xmm6` to `xmm15`, which + # compiled code holds words in. + def jit_function::call_sakura(&mut this, helper: u64): void { + this.out.mov_imm(rax, helper); + this.out.mov_imm(r10, this.layout.guard); + this.out.call_reg(r10); + } + + # Copies bytes from `[from + fd]` to `[to + td]`: through `rcx` where they + # are few, and otherwise by `jit_helper_copy`. Neither register is `rcx`. + def jit_function::copy(&mut this, to: u8, td: u64, from: u8, fd: u64, size: u64): void { + if size <= 128 { + var i: u64 = 0; + while i + 8 <= size { + this.out.load(rcx, from, fd + i); + this.out.store(to, td + i, rcx); + i += 8; + } + if i + 4 <= size { + this.out.load_narrow(0x8B, false, rcx, from, fd + i); + this.out.store_narrow(4, to, td + i, rcx); + i += 4; + } + if i + 2 <= size { + this.out.load_narrow(0x0FB7, false, rcx, from, fd + i); + this.out.store_narrow(2, to, td + i, rcx); + i += 2; + } + if i < size { + this.out.load_narrow(0x0FB6, false, rcx, from, fd + i); + this.out.store_narrow(1, to, td + i, rcx); + } + return; + } + this.out.lea(r8, from, fd); + this.out.lea(rcx, to, td); + this.out.mov(rdx, r8); + this.out.mov_imm(r8, size); + this.call_sakura(this.layout.copy); + } + + # Zeroes bytes from `[to + td]`, as `copy` copies them. `to` is not `rcx`. + def jit_function::zero(&mut this, to: u8, td: u64, size: u64): void { + if size <= 256 { + this.out.alu(alu_xor, rcx, rcx); + var i: u64 = 0; + while i + 8 <= size { + this.out.store(to, td + i, rcx); + i += 8; + } + if i + 4 <= size { + this.out.store_narrow(4, to, td + i, rcx); + i += 4; + } + if i + 2 <= size { + this.out.store_narrow(2, to, td + i, rcx); + i += 2; + } + if i < size { + this.out.store_narrow(1, to, td + i, rcx); + } + return; + } + this.out.lea(rcx, to, td); + this.out.mov_imm(rdx, size); + this.call_sakura(this.layout.zero); + } + + # A comparison's result in `rax` as a word, 1 or 0, into the frame. + def jit_function::put_condition(&mut this, cc: u8, index: u32): void { + this.out.set_rax(cc); + this.put(index, rax); + } + + # Readies compiling functions: where compiled code finds the machine's fields + # and its helpers, the table of compiled functions, and the stub the machine + # enters compiled code through. + def interpreter::jit_begin(&mut this): void { + this.jit_on = false; + return if this.options.evaluating || this.options.checks || this.options.interpret; + val count := this.routines.length; + return if count == 0; + + val base := this as *mut interpreter as u64; + this.jit_at.calls_data = (&mut this.calls) as *mut call_stack as u64 - base; + this.jit_at.calls_used = this.jit_at.calls_data + 8; + this.jit_at.calls_capacity = this.jit_at.calls_data + 16; + this.jit_at.top = (&mut this.top) as *mut u64 as u64 - base; + this.jit_at.stack_end = (&mut this.stack_end) as *mut u64 as u64 - base; + this.jit_at.left = (&mut this.jit_left) as *mut u64 as u64 - base; + this.jit_at.origin = (&mut this.jit_origin) as *mut u64 as u64 - base; + this.jit_at.results = (&mut this.results[0]) as *mut u64 as u64 - base; + val tick: cfn = jit_helper_tick; + val slow: cfn = jit_helper_slow; + val call: cfn = jit_helper_call; + val grow: cfn = jit_helper_grow; + val copy: cfn = jit_helper_copy; + val zero: cfn = jit_helper_zero; + val frem: cfn = jit_helper_frem; + val quick: cfn = jit_helper_quick; + this.jit_at.quick = quick as u64; + this.jit_at.threads = (&mut this.threads) as *mut *mut threading as u64 - base; + this.jit_at.writes_at = (&mut this.writes_at) as *mut u64 as u64 - base; + this.jit_at.console_at = (&mut this.console_writes_at) as *mut u64 as u64 - base; + this.jit_at.calling_c = (&mut this.calling_c) as *mut u64 as u64 - base; + this.jit_at.last_error = (&mut this.last_error) as *mut u32 as u64 - base; + this.jit_at.foreign_fault = (&mut this.foreign_fault) as *mut halt as u64 - base; + this.jit_at.tick = tick as u64; + this.jit_at.slow = slow as u64; + this.jit_at.call = call as u64; + this.jit_at.grow = grow as u64; + this.jit_at.copy = copy as u64; + this.jit_at.zero = zero as u64; + this.jit_at.frem = frem as u64; + + this.jit_table = raw_allocate_zeroed(count * word_size) as *mut u64; + this.jit_at.table = this.jit_table as u64; + this.jit_tried.resize(count, false); + + # The stub: it keeps the registers Microsoft's ABI has a callee keep, takes + # the machine, the frame, and the code in `rcx`, `rdx`, and `r8`, finds how + # low the thread's stack reaches from its TEB, and gives `jit_declined` + # where the stack is that low already. The words a function returns are + # kept in `results`. + var stub := machine_code::new(); + stub.push(rbx); stub.push(rbp); stub.push(rsi); stub.push(rdi); + stub.push(r12); stub.push(r13); stub.push(r14); stub.push(r15); + stub.alu_imm(alu_sub, rsp, 40); + stub.mov(r12, rcx); + stub.mov(rbx, rdx); + # mov r14, gs:[0x1478], the stack's lowest address, `DeallocationStack`. + stub.byte(0x65); stub.byte(0x4C); stub.byte(0x8B); stub.byte(0x34); stub.byte(0x25); stub.u32(0x1478); + stub.alu_imm(alu_add, r14, jit_stack_margin); + stub.alu(alu_cmp, rsp, r14); + val low := stub.jcc(cc_b); + stub.load(r15, r12, this.jit_at.left); + stub.call_reg(r8); + stub.store(r12, this.jit_at.left, r15); + stub.store(r12, this.jit_at.results, rdx); + stub.store(r12, this.jit_at.results + 8, rcx); + stub.store(r12, this.jit_at.results + 16, r8); + val done := stub.length; + stub.alu_imm(alu_add, rsp, 40); + stub.pop(r15); stub.pop(r14); stub.pop(r13); stub.pop(r12); + stub.pop(rdi); stub.pop(rsi); stub.pop(rbp); stub.pop(rbx); + stub.ret(); + stub.land(low, stub.length); + stub.mov_imm(rax, jit_declined); + val back := stub.jmp(); + stub.land(back, done); + this.jit_stub = this.jit_place(&stub); + stub.close(); + + # The guard: it keeps `xmm6` to `xmm15` around a call of the helper in + # `rax`, leaving the 32 bytes the helper may keep its arguments in below. + var guard := machine_code::new(); + guard.alu_imm(alu_sub, rsp, 32 + 16 * word_xmms.length + 8); + for i in 0..word_xmms.length { + guard.save_xmm(rsp, 32 + 16 * i, word_xmms[i]); + } + guard.call_reg(rax); + for i in 0..word_xmms.length { + guard.restore_xmm(word_xmms[i], rsp, 32 + 16 * i); + } + guard.alu_imm(alu_add, rsp, 32 + 16 * word_xmms.length + 8); + guard.ret(); + this.jit_at.guard = this.jit_place(&guard); + guard.close(); + this.jit_on = this.jit_stub != 0 && this.jit_at.guard != 0; + } + + # Gives back the code compiled and the table of it. + def interpreter::jit_end(&mut this): void { + for &each in this.jit_chunks { + val memory: u64 = each; + _ = VirtualFree(memory, 0, 0x8000); + } + this.jit_chunks.close(); + if this.jit_table != null { + raw_release(this.jit_table as *mut u8); + this.jit_table = null; + } + this.jit_tried.close(); + this.jit_on = false; + } + + # Places code made in executable memory, which it then stays in. + # @returns Where it begins, or 0 where no memory was given. + def interpreter::jit_place(&mut this, made: &machine_code): u64 { + val size := round_up(made.length, 16); + if this.jit_chunks.length == 0 || this.jit_used + size > this.jit_limit { + val taken := size > jit_chunk ? round_up(size, 65536) : jit_chunk; + val memory := VirtualAlloc(0, taken, 0x3000, 0x40); + return 0 if memory == 0; + this.jit_chunks.append(memory); + this.jit_used = memory; + this.jit_limit = memory + taken; + } + val at := this.jit_used; + memcpy(at as *mut u8, made.bytes.view().data, made.length); + _ = FlushInstructionCache(GetCurrentProcess(), at, made.length); + this.jit_used = at + size; + return at; + } + + #! Where a function's compiled code begins, compiling it the first time it is + #! asked for, or 0 where it is interpreted. + #! @param this The machine. + #! @param function The function. + #! @returns The address. + def interpreter::native_of(&mut this, function: u32): u64 { + val known := this.jit_table[function]; + return known if known != 0 || this.jit_tried[function as u64]; + this.jit_tried.set(function as u64, true); + val made := this.jit_compile(function); + this.jit_table[function] = made; + return made; + } + + #! Runs a function's compiled code, its frame ready, through the stub. + #! @param this The machine. + #! @param entry Where its code begins. + #! @param fp Its frame. + #! @returns 0 where it returned, the halt it stopped with, or `jit_declined`. + def interpreter::run_native(&mut this, entry: u64, fp: *mut u64): u64 { + this.jit_arm(); + val stub := this.jit_stub as cfn; + val ran := stub(this as *mut interpreter as u64, fp as u64, entry) & 0xFFFFFFFF; + this.jit_settle(); + return ran; + } + + #! Runs a function the interpreter calls as compiled code, where it has some, + #! its call begun, then writes what it returned into the caller's words and + #! ends the call. + #! @param this The machine. + #! @param callee The function called. + #! @param next Its frame. + #! @param fp The caller's frame. + #! @param code The caller's code. + #! @param results Where the caller's code lists the words of the results. + #! @param current The caller. + #! @returns 0 where it returned, the halt it stopped with, or `jit_declined`. + def interpreter::call_native(&mut this, callee: u32, next: *mut u64, fp: *mut u64, code: *u32, results: u64, current: u32): u64 { + val entry := this.native_of(callee); + return jit_declined if entry == 0; + val ran := this.run_native(entry, next); + return ran if ran != 0; + val count := code[results] as u64; + for i in 0..count { + fp[code[results + 1 + i]] = this.results[i]; + } + this.calls.truncate(); + this.top = fp as u64 + this.routines[current].frame; + return 0; + } + + # Calls a function as the interpreter's call, `call_trait`, or `call_value` + # does, but for the step compiled code took already, running it compiled or + # interpreted, then writes what it returned into the caller's words. + # @param this The machine. + # @param fp The caller's frame. + # @param current The caller. + # @param pc Where the call is in its code. + # @returns Why it stopped, or `none`. + def interpreter::jit_call(&mut this, fp: *mut u64, current: u32, pc: u64): halt { + val code := this.routines[current].code; + val kind := code[pc]; + val next := (fp as u64 + this.routines[current].frame) as *mut u64; + var callee: u32 = 0; + var results: u64 = 0; + var dst: u64 = 0; + if kind == bc::call as u32 { + callee = code[pc + 1]; + val argc := code[pc + 2] as u64; + results = pc + 3 + argc; + val held: routine = this.routines[callee]; + return halt::stack_overflow if next as u64 + held.frame > this.stack_end; + val k := this.pass(&held, next, fp, code, pc + 3, 0, 0); + dst = held.returned != 0 ? fp[code[pc + 3 + k]] : 0; + } else if kind == bc::call_trait as u32 { + val argc := code[pc + 3] as u64; + val args := pc + 4; + results = args + argc; + val slot := code[pc + 2] as u64; + val vtable := fp[code[args + 1]]; + if vtable >= this.c.program.vtables.length || slot >= this.c.program.vtables[vtable].functions.length { + return halt::null_reference; + } + callee = this.c.program.vtables[vtable].functions[slot]; + return halt::null_reference if callee == no_function; + val held: routine = this.routines[callee]; + return halt::stack_overflow if next as u64 + held.frame > this.stack_end; + # `this` is the reference the trait reference holds, and a default of a + # trait this one composes is given the vtable whose slots it addresses. + var k: u64 = 2; + if held.count != 0 { + val taken: param_slot = this.params[held.params as u64]; + val at := taken.offset / word_size; + next[at] = fp[code[args]]; + if taken.words == 2 { + next[at + 1] = this.c.program.vtables[vtable].owners[slot] as u64; + } + k = this.pass(&held, next, fp, code, args, 2, 1); + } + dst = held.returned != 0 ? fp[code[args + k]] : 0; + } else { + val argc := code[pc + 2] as u64; + val args := pc + 3; + results = args + argc; + val index := fp[code[args]] - 1; + return halt::null_reference if index >= this.routines.length; + callee = index as u32; + val held: routine = this.routines[callee]; + return halt::stack_overflow if next as u64 + held.frame > this.stack_end; + val k := this.pass(&held, next, fp, code, args, 2, 0); + if held.closure { + next[held.env / word_size] = fp[code[args + 1]]; + } + dst = held.returned != 0 ? fp[code[args + k]] : 0; + } + val held: routine = this.routines[callee]; + this.enter(callee, &held, next, 0, pc, results, dst); + val why := this.execute(this.calls.length - 1); + return why if why != halt::none; + val count := code[results] as u64; + for i in 0..count { + fp[code[results + 1 + i]] = this.results[i]; + } + return halt::none; + } + + # Runs a signal's handler where one came, as the interpreter's `safepoint` + # does, as a call of its own. + def interpreter::jit_safepoint(&mut this, fp: *mut u64, code: *u32, pc: u64, current: u32): halt { + return halt::none if (this.threads != null && this.strand != this.threads[0].strands[0]) || !signals_came(); + val callee := code[pc + 1]; + val held: routine = this.routines[callee]; + val next := (fp as u64 + this.routines[current].frame) as *mut u64; + return halt::stack_overflow if next as u64 + held.frame > this.stack_end; + this.enter(callee, &held, next, pc + 2, pc, none, 0); + return this.execute(this.calls.length - 1); + } + + # Where compiled code's steps ran out: every step of the batch is taken, the + # last now, which may stop the call or let another thread run. + def jit_helper_tick(machine: u64): u64 { + val m := machine as *mut interpreter; + m[0].jit_left = 1; + m[0].jit_settle(); + val why := m[0].spent(); + m[0].jit_arm(); + return why as u64; + } + + # Runs an operation compiled code has the machine's own code run. + def jit_helper_slow(machine: u64, fp: u64, function: u64, pc: u64): u64 { + val m := machine as *mut interpreter; + m[0].jit_settle(); + val code := m[0].routines[function].code; + val kind := code[pc]; + val why := kind == bc::safepoint as u32 ? m[0].jit_safepoint(fp as *mut u64, code, pc, function as u32) + : m[0].slow_op(kind, fp as *mut u64, code, pc, function as u32); + m[0].jit_arm(); + return why as u64; + } + + # Runs an operation compiled code has the machine's own code run that runs no + # code of the program's and lets no other thread run, so no step is settled. + def jit_helper_quick(machine: u64, fp: u64, function: u64, pc: u64): u64 { + val m := machine as *mut interpreter; + val code := m[0].routines[function].code; + return m[0].slow_op(code[pc], fp as *mut u64, code, pc, function as u32) as u64; + } + + # Calls as the interpreter does, where compiled code calls a function not + # compiled, through a value or a trait, or with the system's stack low. + def jit_helper_call(machine: u64, fp: u64, function: u64, pc: u64): u64 { + val m := machine as *mut interpreter; + m[0].jit_settle(); + val why := m[0].jit_call(fp as *mut u64, function as u32, pc); + m[0].jit_arm(); + return why as u64; + } + + # Makes room for more call records. + def jit_helper_grow(machine: u64): void { + val m := machine as *mut interpreter; + m[0].calls.grow(); + } + + # Copies bytes. + def jit_helper_copy(to: u64, from: u64, size: u64): void { + memcpy(to as *mut u8, from as *u8, size); + } + + # Zeroes bytes. + def jit_helper_zero(to: u64, size: u64): void { + memset(to as *mut u8, 0, size); + } + + # The remainder of two doubles, given and given back as their bits. + def jit_helper_frem(a: u64, b: u64): u64 { + var x := a; + var y := b; + var out: u64 = 0; + ((&mut out) as *mut f64)[0] = ((&mut x) as *mut f64)[0] % ((&mut y) as *mut f64)[0]; + return out; + } + + # How an operation reads or writes a word, which choosing where the word is + # held weighs: as an integer, as a double, as a single, or as bits only. + const use_int: u8 = 0; + const use_real: u8 = 1; + const use_single: u8 = 2; + const use_any: u8 = 3; + + # How a function's operations read and write each word of its frame, each + # read and write weighed by how deep in loops it is. + struct jit_uses : owning { + var ints: vector; #! Reads and writes as an integer. + var reals: vector; #! As a double. + var singles: vector; #! As a single. + var inexact: vector; #! Whether something written to it may be what no single holds. + var copies: vector; #! Pairs: a word, and a word whose value it is given as it is. + var lows: vector; #! Where in the code each word is first read or written. + var highs: vector; #! Where it is last. + var weight: u64; #! The weight of the operation counted. + var pc: u64; #! Where the operation counted is. + var ok: bool; #! Whether every operation's words are known. + } + + def jit_uses::close(&mut this): void { + this.ints.close(); + this.reals.close(); + this.singles.close(); + this.inexact.close(); + this.copies.close(); + this.lows.close(); + this.highs.close(); + } + + # Counts a read of a word. + def jit_uses::read(&mut this, index: u32, kind: u8): void { + val at := index as u64; + if at >= this.ints.length { + this.ok = false; + return; + } + if this.pc < this.lows[at] { + this.lows.set(at, this.pc); + } + if this.pc > this.highs[at] || this.highs[at] == none { + this.highs.set(at, this.pc); + } + if kind == use_int { + this.ints.set(at, this.ints[at] + this.weight); + } else if kind == use_real { + this.reals.set(at, this.reals[at] + this.weight); + } else if kind == use_single { + this.singles.set(at, this.singles[at] + this.weight); + } + } + + # Counts a write of a word, of what a single may not hold exactly unless + # `exact` says it does. + def jit_uses::write(&mut this, index: u32, kind: u8, exact: bool): void { + this.read(index, kind); + if !exact && (index as u64) < this.inexact.length { + this.inexact.set(index as u64, true); + } + } + + # Counts a word being given another's value, as a move gives it. + def jit_uses::carries(&mut this, to: u32, from: u32): void { + this.read(to, use_any); + this.read(from, use_any); + this.copies.append(to); + this.copies.append(from); + } + + # Where an operation jumps to, where it is a jump, or `none`. A switch's + # earliest case is given, which a loop is found by as well. + def jump_target(code: *u32, pc: u64): u64 { + val kind := code[pc]; + return match kind { + bc::jump as u32 => code[pc + 1] as u64, + bc::jump_if as u32, bc::jump_zero as u32 => code[pc + 2] as u64, + bc::jump_eq as u32, bc::jump_ne as u32, bc::jump_lts as u32, bc::jump_ltu as u32, + bc::jump_les as u32, bc::jump_leu as u32, bc::jump_eq_k as u32, bc::jump_ne_k as u32, + bc::jump_lts_k as u32, bc::jump_ltu_k as u32, bc::jump_les_k as u32, bc::jump_leu_k as u32, + bc::jump_gts_k as u32, bc::jump_gtu_k as u32, bc::jump_ges_k as u32, bc::jump_geu_k as u32, + bc::move_jump as u32 => code[pc + 3] as u64, + bc::add_k_jump as u32 => code[pc + 4] as u64, + else => none + }; + } + + # Counts the words an operation reads and writes. + def interpreter::jit_count(&mut this, u: &mut jit_uses, code: *u32, pc: u64): void { + val kind := code[pc]; + val a := code[pc + 1]; + val b := code[pc + 2]; + val c := code[pc + 3]; + match kind { + bc::move as u32, bc::move_jump as u32 => u.carries(a, b); + bc::konst as u32 => u.write(a, use_any, single_exact(b as u64 | (c as u64 << 32))); + bc::add as u32, bc::sub as u32, bc::mul as u32, bc::divs as u32, bc::divu as u32, + bc::rems as u32, bc::remu as u32, bc::band as u32, bc::bor as u32, bc::bxor as u32, + bc::shl as u32, bc::shrs as u32, bc::shru as u32, bc::eq as u32, bc::ne as u32, + bc::lts as u32, bc::ltu as u32, bc::les as u32, bc::leu as u32, bc::eqsu as u32, + bc::ltsu as u32, bc::lesu as u32, bc::ltus as u32, bc::leus as u32, + bc::load_u8_x as u32 => { + u.write(a, use_int, false); + u.read(b, use_int); + u.read(c, use_int); + } + bc::fadd as u32, bc::fsub as u32, bc::fmul as u32, bc::fdiv as u32, bc::frem as u32 => { + u.write(a, use_real, false); + u.read(b, use_real); + u.read(c, use_real); + } + bc::feq as u32, bc::fne as u32, bc::flt as u32, bc::fle as u32 => { + u.write(a, use_int, false); + u.read(b, use_real); + u.read(c, use_real); + } + bc::fadd_f32 as u32, bc::fsub_f32 as u32, bc::fmul_f32 as u32, bc::fdiv_f32 as u32 => { + u.write(a, use_single, true); + u.read(b, use_single); + u.read(c, use_single); + } + bc::neg as u32, bc::bnot as u32, bc::lnot as u32, bc::ones as u32, bc::clz as u32, + bc::ctz as u32, bc::bswap as u32, bc::wrap as u32, bc::add_k as u32, bc::mul_k as u32, + bc::band_k as u32, bc::shl_k as u32, bc::shru_k as u32, bc::shrs_k as u32, + bc::load_i8 as u32, bc::load_u8 as u32, bc::load_i16 as u32, bc::load_u16 as u32, + bc::load_i32 as u32, bc::load_u32 as u32, bc::load_i64 as u32, bc::add_k_jump as u32 => { + u.write(a, use_int, false); + u.read(b, use_int); + } + bc::fneg as u32 => { + # Negating keeps a single what it was. + u.write(a, use_real, true); + u.read(b, use_real); + u.carries(a, b); + } + bc::itof as u32, bc::utof as u32 => { + u.write(a, use_real, false); + u.read(b, use_int); + } + bc::ftoi as u32, bc::ftou as u32 => { + u.write(a, use_int, false); + u.read(b, use_real); + } + bc::fsingle as u32 => { + u.write(a, use_single, true); + u.read(b, use_real); + } + bc::fsqrt as u32 => { + u.write(a, use_real, false); + u.read(b, use_real); + } + bc::select as u32 => { + u.read(b, use_int); + u.carries(a, c); + u.carries(a, code[pc + 4]); + } + bc::cell as u32, bc::global as u32, bc::datum as u32 => u.write(a, use_int, false); + bc::load_f32 as u32 => { + u.write(a, use_single, true); + u.read(b, use_int); + } + bc::store_8 as u32, bc::store_16 as u32, bc::store_32 as u32, bc::store_64 as u32 => { + u.read(a, use_int); + u.read(c, use_int); + } + bc::store_f32 as u32 => { + u.read(a, use_int); + u.read(c, use_single); + } + bc::store_k8 as u32, bc::store_k16 as u32, bc::store_k32 as u32, bc::store_k64 as u32, + bc::clear as u32, bc::check as u32, bc::jump_if as u32, bc::jump_zero as u32, + bc::switch as u32, bc::ret_memory as u32, bc::check_ltu_k as u32, + bc::jump_eq_k as u32, bc::jump_ne_k as u32, bc::jump_lts_k as u32, bc::jump_ltu_k as u32, + bc::jump_les_k as u32, bc::jump_leu_k as u32, bc::jump_gts_k as u32, bc::jump_gtu_k as u32, + bc::jump_ges_k as u32, bc::jump_geu_k as u32 => u.read(a, use_int); + bc::copy as u32, bc::check_ltu as u32, bc::jump_eq as u32, bc::jump_ne as u32, + bc::jump_lts as u32, bc::jump_ltu as u32, bc::jump_les as u32, bc::jump_leu as u32 => { + u.read(a, use_int); + u.read(b, use_int); + } + bc::store_8_x as u32 => { + u.read(a, use_int); + u.read(b, use_int); + u.read(code[pc + 4], use_int); + } + bc::jump as u32, bc::trap as u32, bc::unreachable as u32, bc::abort as u32 => {} + bc::ret as u32 => { + for i in 0..a as u64 { + u.read(code[pc + 2 + i], use_any); + } + } + else => { + # Calls, and what the machine's own code runs: what it writes, written + # by the machine, may be anything. + var reads := vector::::new(); + var writes := vector::::new(); + if helper_words(code, pc, &mut reads, &mut writes) { + for i in 0..reads.length { + u.read(reads[i], use_any); + } + for i in 0..writes.length { + u.write(writes[i], use_any, false); + } + } else { + u.ok = false; + } + reads.close(); + writes.close(); + } + } + } + + # Chooses where each word of a function's frame is held: those read and + # written most, loops weighing most, in registers, as integers, as doubles, + # or, where every value written to one is a single's, as singles. + # + # A word is held over the code from where it is first read or written to + # where it is last, widened over each loop that code meets, since a loop may + # bring control back to where a word is read with what it held when the loop + # last went round. Words whose spans do not meet share a register. + # @returns How many words its parameters take, which the call writes. + def interpreter::jit_place_words(&mut this, j: &mut jit_function, held: &routine, code: *u32, length: u64): u64 { + val words := held.cells / word_size; + var params: u64 = 0; + for p in 0..held.count { + val slot: param_slot = this.params[held.params as u64 + p as u64]; + val end := slot.offset + (slot.memory ? slot.size : slot.words as u64 * word_size); + params = end > params ? end : params; + } + params = round_up(params, word_size) / word_size; + j.places.resize(words, held_memory); + j.regs.resize(words, 0); + j.exact.resize(words, false); + j.lows.resize(words, none); + j.highs.resize(words, none); + return params if words == 0; + + # The loops, as the jumps back and where they go, and how deep in them each + # operation is. + var loops := vector::::new(); + var depth := vector::::new(); + depth.resize(length + 1, 0); + var pc: u64 = 0; + while pc < length { + var targets := vector::::new(); + if code[pc] == bc::switch as u32 { + val cases := code[pc + 2] as u64; + for i in 0..cases + 1 { + targets.append(code[pc + 3 + 3 * i + (i == cases ? 0u : 2u)] as u64); + } + } else { + val target := jump_target(code, pc); + if target != none { + targets.append(target); + } + } + for &each in targets { + val target: u64 = each; + if target <= pc { + loops.append(target); + loops.append(pc); + depth.set(target, depth[target] + 1); + depth.set(pc + 1, depth[pc + 1] - 1); + } + } + targets.close(); + pc += op_width(code, pc); + } + + var u := jit_uses { + ints = vector::::new(), reals = vector::::new(), singles = vector::::new(), + inexact = vector::::new(), copies = vector::::new(), lows = vector::::new(), + highs = vector::::new(), ok = true + }; + u.ints.resize(words, 0); + u.reals.resize(words, 0); + u.singles.resize(words, 0); + u.inexact.resize(words, false); + u.lows.resize(words, none); + u.highs.resize(words, none); + # What the call gave as the parameters may be anything, and is held from + # the start. + val env := held.closure ? held.env / word_size : none; + for w in 0..words { + if w < params || w == env { + u.inexact.set(w, true); + u.lows.set(w, 0); + u.highs.set(w, 0); + } + } + var deep: i64 = 0; + var last: u64 = 0; + pc = 0; + while pc < length { + while last <= pc { + deep += depth[last]; + last++; + } + u.weight = deep <= 0 ? 1u : (deep == 1 ? 10u : (deep == 2 ? 100u : 1000u)); + u.pc = pc; + this.jit_count(&mut u, code, pc); + pc += op_width(code, pc); + } + depth.close(); + if !u.ok { + u.close(); + loops.close(); + return params; + } + + # A word given another's value may hold what it does. + var changed := true; + var rounds := 0; + while changed && rounds < 64 { + changed = false; + rounds++; + var i: u64 = 0; + while i < u.copies.length { + val to := u.copies[i] as u64; + val from := u.copies[i + 1] as u64; + if to < words && from < words && u.inexact[from] && !u.inexact[to] { + u.inexact.set(to, true); + changed = true; + } + i += 2; + } + } + + # Each word's span, widened over every loop it meets until none widens it. + for w in 0..words { + j.exact.set(w, !u.inexact[w]); + var low: u64 = u.lows[w]; + var high: u64 = u.highs[w]; + continue if low == none; + var widened := true; + while widened { + widened = false; + var i: u64 = 0; + while i < loops.length { + val start: u64 = loops[i]; + val end: u64 = loops[i + 1]; + if low <= end && start <= high && (start < low || end > high) { + low = start < low ? start : low; + high = end > high ? end : high; + widened = true; + } + i += 2; + } + } + j.lows.set(w, low); + j.highs.set(w, high); + } + loops.close(); + + # The words weighing most take a register of the kind they are read as that + # no word whose span meets theirs holds. + while true { + var best: u64 = 0; + var found: u64 = none; + for w in 0..words { + val total := u.ints[w] + u.reals[w] + u.singles[w]; + if total > best && j.places[w] == held_memory { + best = total; + found = w; + } + } + break if found == none; + val floating := u.reals[found] + u.singles[found] > u.ints[found]; + val count := floating ? word_xmms.length : word_gprs.length; + var chosen: u64 = none; + for r in 0..count { + val reg := floating ? word_xmms[r] : word_gprs[r]; + var free := true; + for k in 0..j.held.length { + val other := j.held[k] as u64; + if j.regs[other] == reg && j.lows[other] <= j.highs[found] && j.lows[found] <= j.highs[other] { + free = false; + break; + } + } + if free { + chosen = r; + break; + } + } + if chosen != none { + if floating { + val single := !u.inexact[found] && u.singles[found] >= u.reals[found]; + j.places.set(found, single ? held_single : held_real); + j.regs.set(found, word_xmms[chosen]); + j.xmms = chosen + 1 > j.xmms ? chosen + 1 : j.xmms; + } else { + j.places.set(found, held_gpr); + j.regs.set(found, word_gprs[chosen]); + j.gprs = chosen + 1 > j.gprs ? chosen + 1 : j.gprs; + } + j.held.append(found as u32); + } + # A word no register is free for stays in the frame. + u.ints.set(found, 0); + u.reals.set(found, 0); + u.singles.set(found, 0); + } + u.close(); + return params; + } + + # Compiles a function's code. + # @returns Where the code begins, or 0 where it is interpreted. + def interpreter::jit_compile(&mut this, function: u32): u64 { + val held: routine = this.routines[function]; + val length := this.c.program.functions[function].compiled.code.length; + return 0 if length == 0 || held.frame > 0x40000000; + var j := jit_function { + out = machine_code::new(), at = vector::::new(), jumps = vector::::new(), + colds = vector::::new(), function = function, frame = held.frame, exit = length, + layout = this.jit_at, places = vector::::new(), regs = vector::::new(), + exact = vector::::new(), held = vector::::new(), lows = vector::::new(), + highs = vector::::new() + }; + j.at.resize(length + 1, none); + val params := this.jit_place_words(&mut j, &held, held.code, length); + + # It keeps the registers it holds words in, and takes the 32 bytes a call of + # Microsoft's ABI may keep its register arguments in, the stack aligned to + # 16 bytes for the calls it makes. + for i in 0..j.gprs { + j.out.push(word_gprs[i]); + } + j.reserved = 32 + 16 * j.xmms + (j.gprs % 2 == 0 ? 8u : 0u); + j.out.alu_imm(alu_sub, rsp, j.reserved); + for i in 0..j.xmms { + j.out.save_xmm(rsp, 32 + 16 * i, word_xmms[i]); + } + # The frame's cells it zeroes as it starts, and the parameters it holds in + # registers, which the call left in the frame. + if held.zeroed > held.cells { + j.zero(rbx, held.cells, round_up(held.zeroed, 8) - held.cells); + } + for i in 0..j.held.length { + val each: u32 = j.held[i]; + if (each as u64) < params || (held.closure && each as u64 == held.env / word_size) { + j.reload(each); + } + } + + var pc: u64 = 0; + while pc < length { + j.at.set(pc, j.out.length); + if !this.jit_op(&mut j, held.code, pc) { + j.close(); + return 0; + } + pc += op_width(held.code, pc); + } + + # The exit, every return and stop leaving through it, which gives back the + # registers it kept: the halt is in `eax`, and the words returned in `rdx`, + # `rcx`, and `r8`. Then the paths taken rarely. + j.at.set(length, j.out.length); + for i in 0..j.xmms { + j.out.restore_xmm(word_xmms[i], rsp, 32 + 16 * i); + } + j.out.alu_imm(alu_add, rsp, j.reserved); + var g := j.gprs; + while g > 0 { + g--; + j.out.pop(word_gprs[g]); + } + j.out.ret(); + for i in 0..j.colds.length { + val each: jit_cold = j.colds[i]; + j.out.land(each.from, j.out.length); + if each.kind == cold_pass { + j.jump_to(0, j.exit, true); + } else if each.kind == cold_fault || each.kind == cold_error { + j.out.store_imm(r12, j.layout.origin, each.pc); + if each.kind == cold_fault { + j.out.mov_imm(rax, each.value); + } + j.jump_to(0, j.exit, true); + } else if each.kind == cold_grow { + j.out.mov(rcx, r12); + j.call_sakura(j.layout.grow); + val back := j.out.jmp(); + j.out.land(back, each.back); + } else { + if each.kind == cold_tick { + j.out.store(r12, j.layout.left, r15); + j.out.mov(rcx, r12); + j.call_sakura(j.layout.tick); + } else { + # The call's arguments to the frame, which it copies from, and its + # results back from it, which it writes. + var reads := vector::::new(); + var writes := vector::::new(); + _ = helper_words(held.code, each.pc, &mut reads, &mut writes); + for r in 0..reads.length { + j.spill(reads[r]); + } + j.sync(); + j.out.mov(rcx, r12); + j.out.mov(rdx, rbx); + j.out.mov_imm(r8, function as u64); + j.out.mov_imm(r9, each.pc); + j.call_sakura(j.layout.call); + for w in 0..writes.length { + j.reload(writes[w]); + } + reads.close(); + writes.close(); + } + j.out.load(r15, r12, j.layout.left); + j.out.test_status(); + val ok := j.out.jcc(cc_e); + j.out.land(ok, each.back); + j.out.store_imm(r12, j.layout.origin, each.pc); + j.jump_to(0, j.exit, true); + } + } + + # Each jump to the bytecode lands where its operation's code begins. + var i: u64 = 0; + while i < j.jumps.length { + val target: u64 = j.at[j.jumps[i + 1]]; + if target == none { + j.close(); + return 0; + } + j.out.land(j.jumps[i], target); + i += 2; + } + val placed := this.jit_place(&j.out); + j.close(); + return placed; + } + + # The condition a comparison of the code holds by, and whether it is signed. + def jump_condition(kind: u32): u8 { + return match kind { + bc::jump_eq as u32, bc::jump_eq_k as u32 => cc_e, + bc::jump_ne as u32, bc::jump_ne_k as u32 => cc_ne, + bc::jump_lts as u32, bc::jump_lts_k as u32 => cc_l, + bc::jump_ltu as u32, bc::jump_ltu_k as u32 => cc_b, + bc::jump_les as u32, bc::jump_les_k as u32 => cc_le, + bc::jump_leu as u32, bc::jump_leu_k as u32 => cc_be, + bc::jump_gts_k as u32 => cc_g, + bc::jump_gtu_k as u32 => cc_a, + bc::jump_ges_k as u32 => cc_ge, + else => cc_ae + }; + } + + # Compiles an operation. + # @returns Whether it could be, where the function is otherwise interpreted. + def interpreter::jit_op(&mut this, j: &mut jit_function, code: *u32, pc: u64): bool { + val kind := code[pc]; + val a := code[pc + 1]; + val b := code[pc + 2]; + val c := code[pc + 3]; + match kind { + bc::move as u32 => { + j.copy_word(a, b); + } + bc::konst as u32 => { + j.put_imm(a, b as u64 | (c as u64 << 32)); + } + bc::add as u32, bc::sub as u32, bc::band as u32, bc::bor as u32, bc::bxor as u32 => { + val ext := match kind { + bc::add as u32 => alu_add, + bc::sub as u32 => alu_sub, + bc::band as u32 => alu_and, + bc::bor as u32 => alu_or, + else => alu_xor + }; + # Into the register the result is held in where there is one, as two + # operands, the operation's own taken in either order where it may be. + val held := j.gpr_of(a); + if held != no_reg && a != c { + j.get(held, b); + j.alu_word(ext, held, c); + } else if held != no_reg && kind != bc::sub as u32 { + j.alu_word(ext, held, b); + } else { + j.get(rax, b); + j.alu_word(ext, rax, c); + j.put(a, rax); + } + } + bc::mul as u32 => { + val held := j.gpr_of(a); + if held != no_reg && a != c { + j.get(held, b); + j.imul_word(held, c); + } else if held != no_reg { + j.imul_word(held, b); + } else { + j.get(rax, b); + j.imul_word(rax, c); + j.put(a, rax); + } + } + bc::divu as u32, bc::remu as u32, bc::divs as u32, bc::rems as u32 => { + j.get(r8, c); + j.out.test(r8, r8); + j.cold(cc_e, cold_fault, pc, halt::division as u64, false); + j.get(rax, b); + if kind == bc::divu as u32 || kind == bc::remu as u32 { + j.out.alu(alu_xor, rdx, rdx); + j.out.unary(6, r8); + j.put(a, kind == bc::divu as u32 ? rax : rdx); + } else { + # By -1, the quotient is the negation, wrapping, and the remainder 0. + j.out.alu_imm(alu_cmp, r8, 0xFFFFFFFFFFFFFFFF); + val minus := j.out.jcc(cc_e); + j.out.cqo(); + j.out.unary(7, r8); + j.put(a, kind == bc::divs as u32 ? rax : rdx); + val done := j.out.jmp(); + j.out.land(minus, j.out.length); + if kind == bc::divs as u32 { + j.out.unary(3, rax); + j.put(a, rax); + } else { + j.put_imm(a, 0); + } + j.out.land(done, j.out.length); + } + } + bc::shl as u32, bc::shru as u32, bc::shrs as u32 => { + # A shift of 64 or more gives 0, or the sign, as built code's does. + val ext := kind == bc::shl as u32 ? shift_left : (kind == bc::shru as u32 ? shift_right : shift_arithmetic); + j.get(rcx, c); + j.get(rax, b); + j.out.alu_imm(alu_cmp, rcx, 64); + val within := j.out.jcc(cc_b); + if kind == bc::shrs as u32 { + j.out.shift_imm(shift_arithmetic, rax, 63); + } else { + j.out.alu(alu_xor, rax, rax); + } + val done := j.out.jmp(); + j.out.land(within, j.out.length); + j.out.shift_cl(ext, rax); + j.out.land(done, j.out.length); + j.put(a, rax); + } + bc::eq as u32, bc::ne as u32, bc::lts as u32, bc::ltu as u32, bc::les as u32, bc::leu as u32 => { + val cc := match kind { + bc::eq as u32 => cc_e, + bc::ne as u32 => cc_ne, + bc::lts as u32 => cc_l, + bc::ltu as u32 => cc_b, + bc::les as u32 => cc_le, + else => cc_be + }; + j.get(rax, b); + j.alu_word(alu_cmp, rax, c); + j.out.set_rax(cc); + j.put(a, rax); + } + bc::eqsu as u32, bc::ltsu as u32, bc::lesu as u32, bc::ltus as u32, bc::leus as u32 => { + # Comparisons of a signed word with an unsigned one, as the interpreter + # works them out. + j.get(rax, b); + j.get(rdx, c); + if kind == bc::ltsu as u32 || kind == bc::lesu as u32 { + j.out.mov_imm(r8, 1); + j.out.test(rax, rax); + val negative := j.out.jcc(cc_s); + j.out.alu(alu_xor, r8, r8); + j.out.alu(alu_cmp, rax, rdx); + val below := j.out.jcc(kind == bc::ltsu as u32 ? cc_ae : cc_a); + j.out.mov_imm(r8, 1); + j.out.land(below, j.out.length); + j.out.land(negative, j.out.length); + } else { + j.out.alu(alu_xor, r8, r8); + j.out.test(kind == bc::eqsu as u32 ? rax : rdx, kind == bc::eqsu as u32 ? rax : rdx); + val negative := j.out.jcc(cc_s); + j.out.alu(alu_cmp, rax, rdx); + val fails := j.out.jcc(kind == bc::eqsu as u32 ? cc_ne : (kind == bc::ltus as u32 ? cc_ae : cc_a)); + j.out.mov_imm(r8, 1); + j.out.land(fails, j.out.length); + j.out.land(negative, j.out.length); + } + j.put(a, r8); + } + bc::fadd as u32, bc::fsub as u32, bc::fmul as u32, bc::fdiv as u32 => { + val opcode: u64 = match kind { + bc::fadd as u32 => 0x58, + bc::fmul as u32 => 0x59, + bc::fsub as u32 => 0x5C, + else => 0x5E + }; + val commutes := kind == bc::fadd as u32 || kind == bc::fmul as u32; + val held := j.real_of(a); + if held != no_reg && a != c { + j.get_real(held, b); + j.real_word(opcode, held, c); + } else if held != no_reg && commutes { + j.real_word(opcode, held, b); + } else { + j.get_real(0, b); + j.real_word(opcode, 0, c); + j.put_real(a, 0); + } + } + bc::fadd_f32 as u32, bc::fsub_f32 as u32, bc::fmul_f32 as u32, bc::fdiv_f32 as u32 => { + val opcode: u64 = match kind { + bc::fadd_f32 as u32 => 0x58, + bc::fmul_f32 as u32 => 0x59, + bc::fsub_f32 as u32 => 0x5C, + else => 0x5E + }; + val commutes := kind == bc::fadd_f32 as u32 || kind == bc::fmul_f32 as u32; + val held := j.single_of(a); + if j.is_exact(b) && j.is_exact(c) && held != no_reg && (a != c || commutes) { + # Of singles, the single's arithmetic rounds as the double's rounded + # to a single does, into the register the result is held in. + if a != c { + j.get_single(held, b); + j.single_word(opcode, held, c); + } else { + j.single_word(opcode, held, b); + } + return true; + } + if j.is_exact(b) && j.is_exact(c) { + j.get_single(0, b); + j.single_word(opcode, 0, c); + } else { + j.get_real(0, b); + j.real_word(opcode, 0, c); + j.out.sse_reg(0xF2, 0x5A, 0, 0); + } + j.put_single(a, 0); + } + bc::frem as u32 => { + j.get(rcx, b); + j.get(rdx, c); + j.call_sakura(j.layout.frem); + j.put(a, rax); + } + bc::feq as u32, bc::fne as u32, bc::flt as u32, bc::fle as u32 => { + # Not a number is unordered: equal to nothing, and below nothing. + j.get_real(0, b); + j.get_real(1, c); + if kind == bc::feq as u32 || kind == bc::fne as u32 { + val equal := kind == bc::feq as u32; + j.out.sse_reg(0x66, 0x2E, 0, 1); + j.out.set_low(equal ? cc_e : cc_ne, rax); + j.out.set_low(equal ? cc_np : cc_p, rcx); + j.out.byte(equal ? 0x20 : 0x08); + j.out.byte(0xC8); # and al, cl or or al, cl + j.out.byte(0x0F); j.out.byte(0xB6); j.out.byte(0xC0); # movzx eax, al + j.put(a, rax); + } else { + j.out.sse_reg(0x66, 0x2E, 1, 0); + j.out.set_rax(kind == bc::flt as u32 ? cc_a : cc_ae); + j.put(a, rax); + } + } + bc::neg as u32, bc::bnot as u32 => { + j.get(rax, b); + j.out.unary(kind == bc::neg as u32 ? 3 : 2, rax); + j.put(a, rax); + } + bc::lnot as u32 => { + j.test_word(b); + j.out.set_rax(cc_e); + j.put(a, rax); + } + bc::fneg as u32 => { + if j.place(a) == held_single && j.place(b) == held_single { + # A single's sign is its 31st bit. + j.out.movq_from_xmm(rax, j.reg(b)); + j.out.alu_imm(alu_xor, rax, 0x80000000); + j.out.movq_to_xmm(j.reg(a), rax); + } else { + j.get(rax, b); + j.out.flip_sign(rax); + j.put(a, rax); + } + } + bc::itof as u32 => { + j.get(rax, b); + j.out.cvtsi2sd(0, rax); + j.put_real(a, 0); + } + bc::utof as u32 => { + # Past the largest signed word, half the value is converted and doubled, + # keeping its lowest bit, as built code converts it. + j.get(rax, b); + j.out.test(rax, rax); + val large := j.out.jcc(cc_s); + j.out.cvtsi2sd(0, rax); + val done := j.out.jmp(); + j.out.land(large, j.out.length); + j.out.mov(rcx, rax); + j.out.shift_imm(shift_right, rcx, 1); + j.out.alu_imm(alu_and, rax, 1); + j.out.alu(alu_or, rcx, rax); + j.out.cvtsi2sd(0, rcx); + j.out.sse_reg(0xF2, 0x58, 0, 0); + j.out.land(done, j.out.length); + j.put_real(a, 0); + } + bc::ftoi as u32 => { + # Not a number is 0, and values past the range saturate, as in built code. + j.get_real(0, b); + j.out.mov_imm(rax, 0); + j.out.sse_reg(0x66, 0x2E, 0, 0); + val nan := j.out.jcc(cc_p); + j.out.mov_imm(rdx, 0x43E0000000000000); + j.out.movq_to_xmm(1, rdx); + j.out.sse_reg(0x66, 0x2E, 0, 1); + val high := j.out.jcc(cc_ae); + j.out.cvttsd2si(rax, 0); + val done := j.out.jmp(); + j.out.land(high, j.out.length); + j.out.mov_imm(rax, 0x7FFFFFFFFFFFFFFF); + j.out.land(nan, j.out.length); + j.out.land(done, j.out.length); + j.put(a, rax); + } + bc::ftou as u32 => { + j.get_real(0, b); + j.out.mov_imm(rax, 0); + j.out.mov_imm(rdx, 0); + j.out.movq_to_xmm(1, rdx); + j.out.sse_reg(0x66, 0x2E, 0, 1); + val low := j.out.jcc(cc_be); + j.out.mov_imm(rdx, 0x43F0000000000000); + j.out.movq_to_xmm(1, rdx); + j.out.sse_reg(0x66, 0x2E, 0, 1); + val full := j.out.jcc(cc_ae); + j.out.mov_imm(rdx, 0x43E0000000000000); + j.out.movq_to_xmm(1, rdx); + j.out.sse_reg(0x66, 0x2E, 0, 1); + val upper := j.out.jcc(cc_ae); + j.out.cvttsd2si(rax, 0); + val done := j.out.jmp(); + j.out.land(upper, j.out.length); + j.out.sse_reg(0xF2, 0x5C, 0, 1); + j.out.cvttsd2si(rax, 0); + j.out.mov_imm(rcx, 0x8000000000000000); + j.out.alu(alu_xor, rax, rcx); + val finished := j.out.jmp(); + j.out.land(full, j.out.length); + j.out.mov_imm(rax, 0xFFFFFFFFFFFFFFFF); + j.out.land(low, j.out.length); + j.out.land(done, j.out.length); + j.out.land(finished, j.out.length); + j.put(a, rax); + } + bc::fsingle as u32 => { + if j.is_exact(b) { + j.get_single(0, b); + } else { + j.get_real(0, b); + j.out.sse_reg(0xF2, 0x5A, 0, 0); + } + j.put_single(a, 0); + } + bc::fsqrt as u32 => { + j.get_real(0, b); + j.out.sse_reg(0xF2, 0x51, 0, 0); + j.put_real(a, 0); + } + bc::ones as u32 => { + j.get(rcx, b); + j.out.bits(0xF3, 0xB8, rax, rcx); + j.put(a, rax); + } + bc::clz as u32, bc::ctz as u32 => { + # Of no bits set, there are 64. + j.get(rcx, b); + j.out.mov_imm(rax, 64); + j.out.test(rcx, rcx); + val empty := j.out.jcc(cc_e); + if kind == bc::clz as u32 { + j.out.bits(0, 0xBD, rdx, rcx); + j.out.mov_imm(rax, 63); + j.out.alu(alu_sub, rax, rdx); + } else { + j.out.bits(0, 0xBC, rax, rcx); + } + j.out.land(empty, j.out.length); + j.put(a, rax); + } + bc::bswap as u32 => { + j.get(rax, b); + j.out.bswap(rax); + j.put(a, rax); + } + bc::wrap as u32 => { + val bits := c as u64; + j.get(rax, b); + if bits < 64 { + return false if bits == 0; + j.out.shift_imm(shift_left, rax, 64 - bits); + j.out.shift_imm(code[pc + 4] != 0 ? shift_arithmetic : shift_right, rax, 64 - bits); + } + j.put(a, rax); + } + bc::select as u32 => { + j.get(rax, code[pc + 4]); + j.get(rdx, c); + j.get(r8, b); + j.out.test(r8, r8); + j.out.cmov(cc_ne, rax, rdx); + j.put(a, rax); + } + bc::cell as u32 => { + j.out.lea(rax, rbx, b as u64); + j.put(a, rax); + } + bc::global as u32 => { + j.put_imm(a, this.globals as u64 + b as u64); + } + bc::datum as u32 => { + j.put_imm(a, this.data[b as u64] + c as u64); + } + bc::load_i8 as u32, bc::load_u8 as u32, bc::load_i16 as u32, bc::load_u16 as u32, + bc::load_i32 as u32, bc::load_u32 as u32, bc::load_i64 as u32, bc::load_f32 as u32 => { + # Through the address's register, into the result's where there are. + val offset := c as u64; + return false if !fits32(offset); + val base := j.address_in(b); + j.null_check(base, pc); + if kind == bc::load_f32 as u32 { + val single := j.single_of(a); + j.out.sse_mem(0xF3, 0x10, single != no_reg ? single : 0, base, offset); + if single == no_reg { + j.put_single(a, 0); + } + } else { + val held := j.gpr_of(a); + val into := held != no_reg ? held : rax; + match kind { + bc::load_i8 as u32 => j.out.load_narrow(0x0FBE, true, into, base, offset); + bc::load_u8 as u32 => j.out.load_narrow(0x0FB6, false, into, base, offset); + bc::load_i16 as u32 => j.out.load_narrow(0x0FBF, true, into, base, offset); + bc::load_u16 as u32 => j.out.load_narrow(0x0FB7, false, into, base, offset); + bc::load_i32 as u32 => j.out.load_narrow(0x63, true, into, base, offset); + bc::load_u32 as u32 => j.out.load_narrow(0x8B, false, into, base, offset); + else => j.out.load(into, base, offset); + } + if held == no_reg { + j.put(a, rax); + } + } + } + bc::store_8 as u32, bc::store_16 as u32, bc::store_32 as u32, bc::store_64 as u32, bc::store_f32 as u32 => { + val offset := b as u64; + return false if !fits32(offset); + val base := j.address_in(a); + j.null_check(base, pc); + if kind == bc::store_f32 as u32 { + val single := j.single_of(c); + if single == no_reg { + j.get_single(0, c); + } + j.out.sse_mem(0xF3, 0x11, single != no_reg ? single : 0, base, offset); + } else { + var value := j.gpr_of(c); + if value == no_reg { + j.get(rdx, c); + value = rdx; + } + if kind == bc::store_64 as u32 { + j.out.store(base, offset, value); + } else { + j.out.store_narrow(kind == bc::store_8 as u32 ? 1 : (kind == bc::store_16 as u32 ? 2 : 4), base, offset, value); + } + } + } + bc::store_k8 as u32, bc::store_k16 as u32, bc::store_k32 as u32, bc::store_k64 as u32 => { + val offset := b as u64; + return false if !fits32(offset); + val base := j.address_in(a); + j.null_check(base, pc); + if kind == bc::store_k64 as u32 { + val value := c as u64 | (code[pc + 4] as u64 << 32); + if fits32(value) { + j.out.store_imm(base, offset, value); + } else { + j.out.mov_imm(rdx, value); + j.out.store(base, offset, rdx); + } + } else { + j.out.store_narrow_imm(kind == bc::store_k8 as u32 ? 1 : (kind == bc::store_k16 as u32 ? 2 : 4), base, offset, c as u64); + } + } + bc::load_u8_x as u32 => { + val offset := code[pc + 4] as u64; + return false if !fits32(offset); + j.get(rax, b); + j.alu_word(alu_add, rax, c); + j.null_check(rax, pc); + j.out.load_narrow(0x0FB6, false, rax, rax, offset); + j.put(a, rax); + } + bc::store_8_x as u32 => { + val offset := c as u64; + return false if !fits32(offset); + j.get(rax, a); + j.alu_word(alu_add, rax, b); + j.null_check(rax, pc); + j.get(rdx, code[pc + 4]); + j.out.store_narrow(1, rax, offset, rdx); + } + bc::copy as u32 => { + val size := c as u64; + if size != 0 { + j.get(rdx, a); + j.get(rax, b); + j.null_check(rdx, pc); + j.null_check(rax, pc); + j.copy(rdx, 0, rax, 0, size); + } + } + bc::clear as u32 => { + val size := b as u64; + if size != 0 { + j.get(rdx, a); + j.null_check(rdx, pc); + j.zero(rdx, 0, size); + } + } + bc::add_k as u32, bc::band_k as u32 => { + val held := j.gpr_of(a); + val into := held != no_reg ? held : rax; + j.get(into, b); + j.out.alu_imm(kind == bc::add_k as u32 ? alu_add : alu_and, into, bc_constant(c)); + if held == no_reg { + j.put(a, rax); + } + } + bc::mul_k as u32 => { + val held := j.gpr_of(a); + val into := held != no_reg ? held : rax; + var from := j.gpr_of(b); + if from == no_reg { + j.get(rdx, b); + from = rdx; + } + j.out.imul_imm(into, from, bc_constant(c)); + if held == no_reg { + j.put(a, rax); + } + } + bc::shl_k as u32, bc::shru_k as u32, bc::shrs_k as u32 => { + val count := bc_constant(c); + val held := j.gpr_of(a); + val into := held != no_reg ? held : rax; + j.get(into, b); + if count >= 64 { + if kind == bc::shrs_k as u32 { + j.out.shift_imm(shift_arithmetic, into, 63); + } else { + j.out.alu(alu_xor, into, into); + } + } else if count != 0 { + j.out.shift_imm(kind == bc::shl_k as u32 ? shift_left : (kind == bc::shru_k as u32 ? shift_right : shift_arithmetic), into, count); + } + if held == no_reg { + j.put(a, rax); + } + } + bc::check as u32 => { + j.test_word(a); + j.cold(cc_e, cold_fault, pc, halt_of(b as u64) as u64, false); + } + bc::check_ltu as u32 => { + val held := j.gpr_of(a); + if held != no_reg { + j.alu_word(alu_cmp, held, b); + } else { + j.get(rax, a); + j.alu_word(alu_cmp, rax, b); + } + j.cold(cc_ae, cold_fault, pc, halt_of(c as u64) as u64, false); + } + bc::check_ltu_k as u32 => { + val held := j.gpr_of(a); + if held != no_reg { + j.out.alu_imm(alu_cmp, held, bc_constant(b)); + } else { + j.get(rax, a); + j.out.alu_imm(alu_cmp, rax, bc_constant(b)); + } + j.cold(cc_ae, cold_fault, pc, halt_of(c as u64) as u64, false); + } + bc::jump as u32 => { + j.step(pc); + j.jump_to(0, a as u64, true); + } + bc::jump_if as u32, bc::jump_zero as u32 => { + j.step(pc); + j.test_word(a); + j.jump_to(kind == bc::jump_if as u32 ? cc_ne : cc_e, b as u64, false); + } + bc::jump_eq as u32, bc::jump_ne as u32, bc::jump_lts as u32, bc::jump_ltu as u32, + bc::jump_les as u32, bc::jump_leu as u32 => { + j.step(pc); + val held := j.gpr_of(a); + if held != no_reg { + j.alu_word(alu_cmp, held, b); + } else { + j.get(rax, a); + j.alu_word(alu_cmp, rax, b); + } + j.jump_to(jump_condition(kind), c as u64, false); + } + bc::jump_eq_k as u32, bc::jump_ne_k as u32, bc::jump_lts_k as u32, bc::jump_ltu_k as u32, + bc::jump_les_k as u32, bc::jump_leu_k as u32, bc::jump_gts_k as u32, bc::jump_gtu_k as u32, + bc::jump_ges_k as u32, bc::jump_geu_k as u32 => { + j.step(pc); + if j.place(a) == held_gpr { + j.out.alu_imm(alu_cmp, j.reg(a), bc_constant(b)); + } else { + j.get(rax, a); + j.out.alu_imm(alu_cmp, rax, bc_constant(b)); + } + j.jump_to(jump_condition(kind), c as u64, false); + } + bc::add_k_jump as u32 => { + j.step(pc); + if j.place(a) == held_gpr && a == b { + j.out.alu_imm(alu_add, j.reg(a), bc_constant(c)); + } else { + j.get(rax, b); + j.out.alu_imm(alu_add, rax, bc_constant(c)); + j.put(a, rax); + } + j.jump_to(0, code[pc + 4] as u64, true); + } + bc::move_jump as u32 => { + j.step(pc); + j.copy_word(a, b); + j.jump_to(0, c as u64, true); + } + bc::switch as u32 => { + j.step(pc); + j.get(rax, a); + val cases := b as u64; + for i in 0..cases { + val at := pc + 3 + 3 * i; + val value := code[at] as u64 | (code[at + 1] as u64 << 32); + if fits32(value) { + j.out.alu_imm(alu_cmp, rax, value); + } else { + j.out.mov_imm(rcx, value); + j.out.alu(alu_cmp, rax, rcx); + } + j.jump_to(cc_e, code[at + 2] as u64, false); + } + j.jump_to(0, code[pc + 3 + 3 * cases] as u64, true); + } + bc::call as u32 => { + return false if !this.jit_direct_call(j, code, pc); + } + bc::call_c as u32 => { + if !this.jit_c_call(j, code, pc) { + j.call_helper(j.layout.slow, code, pc); + } + } + bc::call_trait as u32, bc::call_value as u32 => { + val argc := code[pc + (kind == bc::call_trait as u32 ? 3 : 2)] as u64; + val results := pc + (kind == bc::call_trait as u32 ? 4 : 3) + argc; + return false if code[results] > 3; + j.step(pc); + j.call_helper(j.layout.call, code, pc); + } + bc::ret as u32 => { + val count := a as u64; + return false if count > 3; + val into: u8[3] = [rdx, rcx, r8]; + for i in 0..count { + j.get(into[i], code[pc + 2 + i]); + } + j.out.alu(alu_xor, rax, rax); + j.jump_to(0, j.exit, true); + } + bc::ret_memory as u32 => { + # The result is copied to where the call record says, of the function's + # bytes, where neither is null. + val size := this.routines[j.function].returned; + j.out.load(rax, r12, j.layout.calls_used); + j.out.lea_index(rax, rax, rax, 1); + j.out.shift_imm(shift_left, rax, 4); + j.out.alu_mem(alu_add, rax, r12, j.layout.calls_data); + j.out.load(rdx, rax, 0xFFFFFFFFFFFFFFF8); + j.out.test(rdx, rdx); + val no_dst := j.out.jcc(cc_e); + j.get(rax, a); + j.out.test(rax, rax); + val no_source := j.out.jcc(cc_e); + j.copy(rdx, 0, rax, 0, size); + j.out.land(no_dst, j.out.length); + j.out.land(no_source, j.out.length); + j.out.alu(alu_xor, rax, rax); + j.jump_to(0, j.exit, true); + } + bc::trap as u32, bc::unreachable as u32, bc::abort as u32 => { + val why := kind == bc::trap as u32 ? halt_of(a as u64) : (kind == bc::abort as u32 ? halt::aborted : halt::unreachable); + j.out.store_imm(r12, j.layout.origin, pc); + j.out.mov_imm(rax, why as u64); + j.jump_to(0, j.exit, true); + } + else => { + # The rest the machine's own code runs, as the interpreter's does. + j.call_helper(j.layout.slow, code, pc); + } + } + return true; + } + + # Whether a layout is one word a register passes to C or takes back. + def scalar_for_c(shape: &layout): bool { + return !in_memory(shape) && shape.size <= 8 && (shape.kind == lk::signed || shape.kind == lk::unsigned + || shape.kind == lk::floating || shape.kind == lk::boolean || shape.kind == lk::reference || shape.kind == lk::pointer); + } + + # Compiles a call of C taking at most four arguments and giving a result, if + # any, each of one word, as `call_foreign` makes it: the arguments in the + # registers of their positions, a real's in the SSE register, a double's in + # the general one too, as a variadic function reads it; the frames in use, the + # steps left, and the count of calls of C under way kept for C calling the + # program back; what the thread's last C call left for `GetLastError` given + # back in its TEB around the call; and a function C called back that stopped + # stopping this one. The machine's own code calls it where the program's + # threads take turns, and where it writes the output the machine keeps. + # @returns Whether it could be compiled so. + def interpreter::jit_c_call(&mut this, j: &mut jit_function, code: *u32, pc: u64): bool { + val signature := code[pc + 1]; + val argc := code[pc + 2] as u64; + val base := pc + 3; + val held := &this.c.program.signatures[signature]; + val count := held.params.length; + return false if count > 4 || argc != count + 1; + val result: layout = this.c.program.layouts[held.result]; + return false if result.kind != lk::empty && !scalar_for_c(&result); + for i in 0..count { + val shape: layout = this.c.program.layouts[held.params[i]]; + return false if !scalar_for_c(&shape); + } + + j.get(rax, code[base]); + j.out.test(rax, rax); + j.cold(cc_e, cold_fault, pc, halt::null_reference as u64, false); + var slow := vector::::new(); + j.out.alu_mem_imm(alu_cmp, r12, j.layout.threads, 0); + slow.append(j.out.jcc(cc_ne)); + if this.options.capture { + j.out.alu_mem(alu_cmp, rax, r12, j.layout.writes_at); + slow.append(j.out.jcc(cc_e)); + j.out.alu_mem(alu_cmp, rax, r12, j.layout.console_at); + slow.append(j.out.jcc(cc_e)); + } + + val gprs: u8[4] = [rcx, rdx, r8, r9]; + for i in 0..count { + val shape: layout = this.c.program.layouts[held.params[i]]; + val word := code[base + 1 + i]; + if shape.kind == lk::floating && shape.size == 4 { + j.get_single(i as u8, word); + } else if shape.kind == lk::floating { + j.get_real(i as u8, word); + j.out.movq_from_xmm(gprs[i], i as u8); + } else { + j.get(gprs[i], word); + } + } + j.out.lea(r10, rbx, j.frame); + j.out.store(r12, j.layout.top, r10); + j.out.store(r12, j.layout.left, r15); + j.out.load_narrow(0x8B, false, r11, r12, j.layout.last_error); + # mov gs:[0x68], r11d, the thread's `LastErrorValue`. + j.out.byte(0x65); j.out.byte(0x44); j.out.byte(0x89); j.out.byte(0x1C); j.out.byte(0x25); j.out.u32(0x68); + j.out.op_mem(0, true, 0xFF, 0, r12, j.layout.calling_c); + j.out.mov_imm(r10, j.layout.guard); + j.out.call_reg(r10); + j.out.op_mem(0, true, 0xFF, 1, r12, j.layout.calling_c); + # mov r11d, gs:[0x68]. + j.out.byte(0x65); j.out.byte(0x44); j.out.byte(0x8B); j.out.byte(0x1C); j.out.byte(0x25); j.out.u32(0x68); + j.out.store_narrow(4, r12, j.layout.last_error, r11); + j.out.load(r15, r12, j.layout.left); + + # A function C called back stopped, which stops this one once C is back. + j.out.op_mem(0, false, 0x83, 7, r12, j.layout.foreign_fault); + j.out.byte(0); + val fine := j.out.jcc(cc_e); + j.out.load_narrow(0x8B, false, rax, r12, j.layout.foreign_fault); + j.out.store_narrow_imm(4, r12, j.layout.foreign_fault, 0); + j.out.store_imm(r12, j.layout.origin, pc); + j.jump_to(0, j.exit, true); + j.out.land(fine, j.out.length); + + # The result, widened from its bits as the frame holds it. + val resc := code[base + argc] as u64; + if resc != 0 && result.kind != lk::empty { + val into := code[base + argc + 1]; + if result.kind == lk::floating { + if result.size == 4 { + j.out.sse_reg(0xF3, 0x5A, 0, 0); + } + j.put_real(into, 0); + } else { + if result.kind == lk::boolean || result.size == 1 { + j.out.op_reg(0, result.kind == lk::signed, result.kind == lk::signed ? 0x0FBE : 0x0FB6, rax, rax); + } else if result.size == 2 { + j.out.op_reg(0, result.kind == lk::signed, result.kind == lk::signed ? 0x0FBF : 0x0FB7, rax, rax); + } else if result.size == 4 && result.kind != lk::pointer && result.kind != lk::reference { + if result.kind == lk::signed { + j.out.op_reg(0, true, 0x63, rax, rax); + } else { + j.out.op_reg(0, false, 0x8B, rax, rax); + } + } + j.put(into, rax); + } + } + val done := j.out.jmp(); + for i in 0..slow.length { + j.out.land(slow[i], j.out.length); + } + slow.close(); + j.call_helper(j.layout.slow, code, pc); + j.out.land(done, j.out.length); + return true; + } + + # Compiles a call of a function by its index: a step, then where the callee + # is compiled and the system's stack has room, its frame is checked against + # the machine's stack, its arguments copied as `pass` copies them, its record + # pushed, and it is called, popping the record as it returns and taking its + # words; otherwise the machine calls it as the interpreter does. + # @returns Whether it could be compiled. + def interpreter::jit_direct_call(&mut this, j: &mut jit_function, code: *u32, pc: u64): bool { + val callee := code[pc + 1]; + val argc := code[pc + 2] as u64; + val results := pc + 3 + argc; + val resc := code[results] as u64; + return false if resc > 3; + val held: routine = this.routines[callee]; + val next := j.frame; + return false if !fits32(next + held.frame); + + j.step(pc); + j.out.load_rax_absolute(j.layout.table + callee as u64 * word_size); + j.out.test(rax, rax); + j.cold(cc_e, cold_call, pc, 0, false); + val slow := j.colds.length - 1; + j.out.alu(alu_cmp, rsp, r14); + j.cold(cc_b, cold_call, pc, 0, false); + val deep := j.colds.length - 1; + j.out.lea(rdx, rbx, next + held.frame); + j.out.alu_mem(alu_cmp, rdx, r12, j.layout.stack_end); + j.cold(cc_a, cold_fault, pc, halt::stack_overflow as u64, false); + + # The arguments, as `pass` copies them. + var k: u64 = 0; + for p in 0..held.count { + val slot: param_slot = this.params[held.params as u64 + p as u64]; + if slot.memory { + j.get(rax, code[pc + 3 + k]); + j.out.test(rax, rax); + val none_given := j.out.jcc(cc_e); + j.copy(rbx, next + slot.offset, rax, 0, slot.size); + j.out.land(none_given, j.out.length); + k++; + continue; + } + val at := slot.offset / word_size; + for w in 0..slot.words { + j.get(rcx, code[pc + 3 + k]); + j.out.store(rbx, next + (at + w as u64) * word_size, rcx); + k++; + } + } + + # Its record: the function, its frame, where it was called, and where its + # result held in memory goes. + val retry := j.out.length; + j.out.load(rcx, r12, j.layout.calls_used); + j.out.alu_mem(alu_cmp, rcx, r12, j.layout.calls_capacity); + j.cold(cc_ae, cold_grow, pc, 0, false); + j.colds.at(j.colds.length - 1).back = retry; + j.out.lea_index(rdx, rcx, rcx, 1); + j.out.shift_imm(shift_left, rdx, 4); + j.out.alu_mem(alu_add, rdx, r12, j.layout.calls_data); + j.out.store_narrow_imm(4, rdx, 0, callee as u64); + j.out.lea(r8, rbx, next); + j.out.store(rdx, 8, r8); + j.out.store_imm(rdx, 16, 0); + j.out.store_imm(rdx, 24, pc); + j.out.store_imm(rdx, 32, none); + if held.returned != 0 { + j.get(r8, code[pc + 3 + k]); + j.out.store(rdx, 40, r8); + } else { + j.out.store_imm(rdx, 40, 0); + } + j.out.alu_imm(alu_add, rcx, 1); + j.out.store(r12, j.layout.calls_used, rcx); + + j.out.load_rax_absolute(j.layout.table + callee as u64 * word_size); + j.out.alu_imm(alu_add, rbx, next); + j.out.call_reg(rax); + j.out.lea(rbx, rbx, 0 - next); + j.out.test_status(); + j.cold(cc_ne, cold_pass, pc, 0, false); + j.out.op_mem(0, true, 0xFF, 1, r12, j.layout.calls_used); # dec qword [calls_used] + val into: u8[3] = [rdx, rcx, r8]; + for i in 0..resc { + j.put(code[results + 1 + i], into[i]); + } + + # The calls the machine makes itself go on past the call. + j.colds.at(slow).back = j.out.length; + j.colds.at(deep).back = j.out.length; + return true; + } +} else { + def interpreter::jit_begin(&mut this): void { + this.jit_on = false; + } + + def interpreter::jit_end(&mut this): void {} + + def interpreter::native_of(&mut this, function: u32): u64 { + return 0; + } + + def interpreter::run_native(&mut this, entry: u64, fp: *mut u64): u64 { + return jit_declined; + } + + def interpreter::call_native(&mut this, callee: u32, next: *mut u64, fp: *mut u64, code: *u32, results: u64, current: u32): u64 { + return jit_declined; + } +} diff --git a/machine/machine.sakura b/machine/machine.sakura new file mode 100644 index 00000000..228ce33f --- /dev/null +++ b/machine/machine.sakura @@ -0,0 +1,840 @@ +#! @file machine.sakura +#! @author John Christman (sorakatadzuma@gmail.com) +#! @copyright Malunal Studios, LLC. +#! @license MIT +#! +#! Contains the machine, which runs a program's code, as the C machine does: +#! frames of words one after another on a stack of its own, globals, the +#! program's data, and memory the program gives back itself. Addresses are the machine's own, so what a program reads and +#! writes through a pointer is memory as it is. +#! +#! A fault stops the program, and the machine says where each function running +#! was, as the C machine does, so a fault reads the same in both. + +import sakura::analyzer; +import sakura::compiler; +import std::containers; +module sakura::machine; + + +#! Why the machine stopped, numbered as the C machine numbers its errors. +pub enum halt : u32 { + none = 0, #! It did not stop. + no_main = 2, #! The program has no `main`. + unsupported = 3, #! The program does what this machine cannot. + out_of_bounds = 4, #! An index or slice was out of bounds. + null_reference = 5, #! A null reference was unwrapped. + division = 6, #! A number was divided by zero. + not_held = 7, #! A union did not hold the field read. + stack_overflow = 8, #! The stack overflowed. + unreachable = 9, #! A function ended without returning a value. + invalid_release = 11, #! Memory released was not allocated, or was already released. + not_member = 13, #! A value is not a member of its enum. + not_constant = 15, #! What was run does not run while compiling. + evaluation_limit = 16, #! Evaluating took too many steps. + not_evaluated = 17, #! A constant read is not evaluated yet. + invalid_access = 18, #! A pointer reaches memory the program does not hold. + address = 19, #! Pointers into different memory are compared or subtracted. + exited = 20, #! The program asked to stop. + aborted = 21, #! The program aborted. + foreign_missing = 22, #! A C function the program calls, or the library holding it, was not found. + callback = 23, #! C called a function of the program while the program was not calling C. + out_of_memory = 24, #! The system gave no memory. + elsewhere = 25, #! Another thread stopped the program, which says why. + faulted = 26, #! The program stopped itself, saying why, as `fault` does. + unwritten = 27, #! Memory was read before anything wrote it, running with memory checked. + step_limit = 28, #! A call took more steps than its host allowed it. +} + +#! What a halt says, as the C machine says it. +#! @param this The halt. +#! @returns The sentence. +pub def halt::describe(&this): strview { + return match this { + halt::no_main => "Program has no `main` function.", + halt::unsupported => "Program uses a construct that cannot be compiled.", + halt::out_of_bounds => "Index or slice is out of bounds.", + halt::null_reference => "Null reference was unwrapped.", + halt::division => "Division by zero.", + halt::not_held => "Union does not hold the field that was read.", + halt::stack_overflow => "Stack overflowed.", + halt::unreachable => "Function ended without returning a value.", + halt::invalid_release => "Released memory that was not allocated, or was already released.", + halt::not_member => "Value is not a member of its enum.", + halt::not_constant => "Function does not run while compiling.", + halt::evaluation_limit => "Evaluation took too many steps, as an endless loop or recursion would.", + halt::not_evaluated => "Constant has not been evaluated yet.", + halt::invalid_access => "Pointer reaches memory the program does not hold, as past the end of what it points into, or memory released.", + halt::address => "Pointers into different memory are compared or subtracted, which depends on where the memory is.", + halt::exited => "Program exited.", + halt::aborted => "Program aborted.", + halt::foreign_missing => "C function could not be found, nor the library holding it.", + halt::callback => "C called a function of the program while the program was not calling C.", + halt::out_of_memory => "Out of memory.", + halt::elsewhere => "Another thread stopped the program.", + halt::faulted => "Program faulted.", + halt::unwritten => "Memory was read before anything wrote it, as memory `raw_allocate` gives or a variable `undefined`.", + halt::step_limit => "Call took more steps than it was allowed, as an endless loop or recursion would.", + else => "Unknown machine error" + }; +} + +#! The halt a number stands for, as a fault a program asks for names it. +#! @param code The number. +#! @returns The halt, or `unsupported` for a number no halt has. +pub def halt_of(code: u64): halt { + return match code { + 3 => halt::unsupported, 4 => halt::out_of_bounds, 5 => halt::null_reference, 6 => halt::division, + 7 => halt::not_held, 8 => halt::stack_overflow, 9 => halt::unreachable, 11 => halt::invalid_release, + 13 => halt::not_member, 15 => halt::not_constant, 16 => halt::evaluation_limit, + 17 => halt::not_evaluated, 18 => halt::invalid_access, 19 => halt::address, 21 => halt::aborted, + 26 => halt::faulted, + else => halt::unsupported + }; +} + +#! How a program is run. +pub struct interpreting { + pub var stack: u64; #! The bytes of the stack, or 0 for the default. + var evaluating: bool; #! Whether the program evaluates constants while compiling. + pub var capture: bool; #! Whether what the program writes to its output is kept rather than written, for `take_output`. + pub var checks: bool; #! Whether what references and pointers reach is checked, as `run --checks` asks, which the program's code must be lowered for. + pub var steps: u64; #! The steps, as jumps and calls, that `begin`, `run`, and each call the host makes may take before it stops with `step_limit`, or 0 for as many as it takes. + pub var interpret: bool; #! Whether every function is interpreted, none compiled to the processor's code as `jit.sakura` compiles them. +} + +#! A function the host gives the program to call by name. +struct provided { + var name: string; #! The name a foreign declaration of the program gives it. + var address: u64; #! Where C calls it. +} + +#! A function as the machine calls it. +pub struct routine { + var code: *u32; #! Its code. + var frame: u64; #! The bytes of its frame. + var cells: u64; #! Where its cells begin, the first of which are zeroed as it starts. + var zeroed: u64; #! Where the cells zeroed as it starts end. + var env: u64; #! Where a closure's environment is. + var params: u32; #! The first of its parameters in the machine's `params`. + var count: u32; #! How many parameters it takes. + var returned: u64; #! The bytes of the memory it returns, or 0. + var closure: bool; #! Whether its environment follows its parameters. +} + +#! A call running. +pub struct call_record { + var function: u32; #! The function called. + var fp: *mut u64; #! Its frame. + var back: u64; #! Where the caller goes on. + var site: u64; #! Where the call is in the caller's code. + var results: u64; #! Where the caller's code lists the words its results go to, or `none`. + var dst: u64; #! Where a result held in memory is written. +} + +#! The calls running, the innermost last. The machine's code pushes and pops +#! them, and so does the code `jit.sakura` compiles, which reaches the fields at +#! their offsets, so they stay in this order, a record 48 bytes. +pub struct call_stack : owning { + var data: *mut call_record = null; #! The records. + var used: u64; #! How many calls are running. + var capacity: u64; #! How many records fit before they move. +} + +#! An empty stack of calls. +#! @returns The stack. +pub def call_stack::new(): call_stack { + return call_stack {}; +} + +#! How many calls are running. +pub val call_stack::length: u64 { + get => this.used; +} + +#! Pushes a call. +#! @param this The stack. +#! @param record The call. +pub def call_stack::append(&mut this, record: call_record): void { + if this.used == this.capacity { + this.grow(); + } + this.data[this.used] = record; + this.used++; +} + +#! Makes room for twice as many records, at least 64. +#! @param this The stack. +pub def call_stack::grow(&mut this): void { + val wanted := this.capacity < 32 ? 64u : this.capacity * 2; + val made := raw_allocate(wanted * size_of::()) as *mut call_record; + if this.data != null { + memcpy(made as *mut u8, this.data as *u8, this.used * size_of::()); + raw_release(this.data as *mut u8); + } + this.data = made; + this.capacity = wanted; +} + +#! The innermost call. +#! @param this The stack, holding one at least. +#! @returns The call. +pub def call_stack::last(&this): call_record { + return this.data[this.used - 1]; +} + +#! A call, counting from the outermost. +#! @param this The stack. +#! @param index Which, below its length. +#! @returns The call. +pub def call_stack::at(&this, index: u64): call_record { + return this.data[index]; +} + +#! Pops the innermost call. +#! @param this The stack, holding one at least. +pub def call_stack::truncate(&mut this): void { + this.used--; +} + +#! Pops every call. +#! @param this The stack. +pub def call_stack::clear(&mut this): void { + this.used = 0; +} + +#! Gives back the records' memory. +#! @param this The stack. +pub def call_stack::close(&mut this): void { + if this.data != null { + raw_release(this.data as *mut u8); + } + this.data = null; + this.used = 0; + this.capacity = 0; +} + +#! A function a trace names, and where it was. +pub struct trace_frame { + var function: string; #! Its name. + var path: strview; #! The file. + var line: u32; #! The line. + var column: u32; #! The column. +} + +#! What stands for nothing where a place is wanted. +pub const none: u64 = 0xFFFFFFFFFFFFFFFF; + +#! The bytes of the stack, unless asked otherwise. +pub const default_stack: u64 = 8388608; + +#! The machine, which interprets the code of a program. +pub struct interpreter : owning { + var c: &mut lowerer; #! The compiler, whose program runs and whose checker knows the source. + var options: interpreting; #! How the program is run. + var routines: vector; #! Each function, as the machine calls it. + var params: vector; #! The parameters of every function, as runs `routines` say. + var stack: *mut u8; #! The frames. + var stack_end: u64; #! Where the stack ends. + var top: u64; #! Where the frames in use end. + var globals: *mut u8; #! The globals. + var data: vector; #! Where each datum is. + var blocks: dict; #! The memory the program gives back itself, and how large each is. + var kept: dict; #! The blocks a constant evaluated holds, which stay to the end. + var sites: dict; #! Running with its memory checked, where each block was allocated: the function and where in its code, by `pair_key`. + var released: vector; #! Running with its memory checked, the blocks released and held back from being used again, oldest first, from `released_from`. + var released_sizes: vector; #! How large each of them is. + var released_from: u64; #! The first of them still held back. + var released_bytes: u64; #! The bytes of those held back. + var calls_c: bool; #! Whether the program calls C, whose memory the machine does not know. + var called_c: bool = false; #! Whether code of the program's own, rather than `system`'s alone, calls C, which may give it memory of C's. + var pages: dict>; #! Running with its memory checked, the blocks over each page of 4096 bytes, by its number, which the block an address is within is found among. + var unwritten: dict>; #! Running with its memory checked, of each page of 4096 bytes holding any byte never written, by its number, which of its bytes are, a bit each. + var seen_page: u64 = 0xFFFFFFFFFFFFFFFF; #! The page whose bits of `unwritten` were last looked for. + var seen_bits: *mut u64 = null; #! Its bits, or null where it has none. + var framed_unwritten: bool = false; #! Whether a variable `undefined` was marked never written, in a frame, so each frame begun clears what one before left. + var mapped: vector; #! Running with its memory checked, the memory the program was given rather than allocated, as pairs of where each begins and its bytes, in order of where each begins: what it mapped, the variables it started with, and its arguments. + var unmapped: vector; #! Running with its memory checked, where the program calls C, the memory it mapped and gave back, likewise, which it holds no longer, though the machine takes what it does not know as C's. + var data_runs: vector; #! Running with its memory checked, where each datum is and its bytes, likewise in order. + var ended: vector; #! Running with its memory checked, the words of the frames each thread had in use as the program ended by exiting, which the leaks reported count as reaching what they hold. + var calls: call_stack; #! The calls running, the innermost last. + var texts: vector>; #! The texts being formatted, the innermost last, and those made before, whose memory is kept. + var depth: u64; #! How many texts are being formatted. + var results: u64[3]; #! The words the call the machine began returns. + var trace: vector; #! Where each function was, where the program faulted. + var fault_text: string; #! What `fault` said, where the program stopped by it. + pub var status: i32; #! What the program asked to exit with. + var output: vector; #! What the program wrote to its output, where it is kept. + var budget: u64; #! The steps an evaluation may still take. + var ready: vector; #! Whether each evaluation is done, while compiling. + var waiting: u32; #! The evaluation a run stopped at. + var environ: u64; #! The variables the program started with, as the system gives them. + var threads: *mut threading = null; #! What the program's threads share, once it starts one. + var strand: *mut strand = null; #! What the thread running has of its own, while threads run. + var countdown: u64 = 0; #! Steps until the running thread lets another run. + + # Calling C, where the system running the machine is Windows. The libraries + # the program links are opened and the C functions it calls by name found + # before it runs; the code a call of C goes through, and that C calls each + # function of the program through, is made once C is first called, since C + # only calls an address. The code and the libraries are the machine's, shared + # by every thread, while the last error a C call left is each thread's own. + var foreign_found: bool = false; #! Whether the C functions were looked for. + var provided: vector; #! The functions the host gives the program, which are found before C's. + var symbols: vector; #! The address of each C function the program links. + var libraries: vector; #! The libraries opened, to close, or 0 where an earlier one shares it. + var call_stub: u64 = 0; #! The code a call of C goes through, or 0. + var callbacks: vector; #! The address C calls each function through, or 0 where it is none. + var foreign_memory: u64 = 0; #! The executable memory the stubs are in, or 0. + var foreign_size: u64 = 0; #! The bytes of it. + var last_error: u32 = 0; #! The error the last C call left, kept across the machine's own work. + var foreign_fault: halt = halt::none; #! Why a function C called stopped, until C comes back and the machine stops. + var calling_c: u64 = 0; #! How many calls of C are under way, which C may call back within. + var maps_at: u64 = 0; #! The address of `VirtualAlloc`, where the program calls it, whose memory a run with its memory checked holds as what `mmap` maps. + var unmaps_at: u64 = 0; #! The address of `VirtualFree`, likewise, which gives that memory back as `munmap` does. + var writes_at: u64 = 0; #! The address of `WriteFile`, where the program calls it, whose writes to the output and error a run that `capture`s keeps. + var console_writes_at: u64 = 0; #! The address of `WriteConsoleW`, likewise. + + # Compiling functions to the processor's code, as `jit.sakura` does. Its code + # reads and writes the fields of the machine it names at their offsets. + var jit_on: bool = false; #! Whether functions are compiled as they are first called. + var jit_table: *mut u64 = null; #! Where each function's compiled code begins, or 0 where it has none. + var jit_tried: vector; #! Whether each function was compiled, or found not to compile. + var jit_chunks: vector; #! The executable memory the code is in. + var jit_used: u64 = 0; #! Where the next function's code goes, in the last chunk. + var jit_limit: u64 = 0; #! Where the last chunk ends. + var jit_stub: u64 = 0; #! The code a call of compiled code from the machine goes through. + var jit_at: jit_layout; #! Where compiled code finds the machine's fields, and the helpers it calls. + var jit_left: u64 = 0; #! The steps compiled code may take before it settles them, as its register holds them while it runs. + var jit_batch: u64 = 0; #! The steps it was given to take. + var jit_origin: u64 = 0; #! Where in its code a compiled function stopped, for the trace. +} + +#! Makes a machine running a program lowered, made into the machine's code. +#! @param c The compiler, whose program runs. +#! @param options How it is run. +#! @returns The machine. +pub def interpreter::new(c: &mut lowerer, options: interpreting): interpreter { + c.assemble_all(); + var made := interpreter { + c = c, + options = options, + routines = vector::::new(), + params = vector::::new(), + data = vector::::new(), + blocks = dict::::new(), + kept = dict::::new(), + sites = dict::::new(), + released = vector::::new(), + released_sizes = vector::::new(), + pages = dict::>::new(), + unwritten = dict::>::new(), + mapped = vector::::new(), + unmapped = vector::::new(), + data_runs = vector::::new(), + ended = vector::::new(), + calls = call_stack::new(), + texts = vector::>::new(), + trace = vector::::new(), + output = vector::::new(), + ready = vector::::new(), + provided = vector::::new(), + symbols = vector::::new(), + libraries = vector::::new(), + callbacks = vector::::new(), + jit_tried = vector::::new(), + jit_chunks = vector::::new() + }; + made.load(); + made.jit_begin(); + if options.checks { + made.order_data(); + } + var called_back := false; + for &each in made.c.program.functions { + called_back = called_back || each.callback; + } + made.calls_c = made.c.program.linked.length != 0 || called_back; + # On Windows `system` is made of calls of C, whose memory only its own code + # reads, so the program's own code may hold memory of C's from the start only + # where it links C of its own, which its globals may call as they begin, or C + # calls a function of it back. + var called_c := called_back; + for &each in made.c.program.linked { + called_c = called_c || !made.in_system(each.decl); + } + made.called_c = called_c; + return made; +} + +#! Lays out what the program runs with: each function as the machine calls it, +#! the stack, the globals, and the data, each address within which is written +#! as the machine placed what it points into. +#! @param this The machine. +def interpreter::load(&mut this): void { + for i in 0..this.c.program.functions.length { + val held := &this.c.program.functions[i]; + val first := this.params.length as u32; + this.params.extend(held.compiled.params.view()); + this.routines.append(routine { + code = held.compiled.code.view().data, + frame = held.compiled.frame, + cells = held.compiled.cells, + zeroed = held.compiled.zeroed, + env = held.compiled.env, + params = first, + count = held.compiled.params.length as u32, + returned = held.compiled.returned, + closure = held.closure + }); + } + + val size := this.options.stack != 0 ? this.options.stack : default_stack; + # Each frame clears what it reads before it writes, so the stack is not + # cleared first, but running with its memory checked: the frames in use are + # read whole as the program exits, for the blocks they reach, and a word of + # one nothing wrote, as the scratch word, holds no address. + this.stack = this.options.checks ? raw_allocate_zeroed(size) : raw_allocate(size); + this.stack_end = this.stack as u64 + size; + this.top = this.stack as u64; + this.globals = raw_allocate_zeroed(this.c.program.globals + word_size); + this.budget = evaluation_budget; + + for i in 0..this.c.program.data.length { + val bytes := &this.c.program.data[i].bytes; + val made := raw_allocate(bytes.length + 16); + memset(made, 0, bytes.length + 16); + memcpy(made, bytes.view().data, bytes.length); + this.data.append(made as u64); + } + for i in 0..this.c.program.data.length { + val held := &this.c.program.data[i]; + for &each in held.relocations { + val base: u64 = this.data[i]; + val target: u64 = this.data[each.target]; + val at := (base + each.at) as *mut u64; + at[0] = target + each.addend; + } + } +} + +#! Gives back everything the machine holds. +#! @param this The machine. +pub def interpreter::close(&mut this): void { + for &entry in this.blocks { + raw_release(entry.key as *mut u8); + } + this.blocks.clear(); + for i in this.released_from..this.released.length { + val held: u64 = this.released[i]; + raw_release(held as *mut u8); + } + this.released.clear(); + this.released_sizes.clear(); + this.pages.clear(); + this.mapped.clear(); + this.unmapped.clear(); + this.data_runs.clear(); + this.ended.clear(); + for &each in this.data { + val address: u64 = each; + raw_release(address as *mut u8); + } + this.data.clear(); + if this.stack != null { + raw_release(this.stack); + this.stack = null; + } + if this.globals != null { + raw_release(this.globals); + this.globals = null; + } + if this.environ != 0 { + raw_release(this.environ as *mut u8); + this.environ = 0; + } + this.jit_end(); + when os == windows { + this.unlink_foreign(); + } + this.provided.close(); + this.symbols.close(); + this.libraries.close(); + this.callbacks.close(); + this.fault_text.close(); +} + +#! Begins the program without calling `main`: the C functions it calls, and +#! those the host provides, are found, and the globals given their values, as a +#! host calling the program's functions itself does once, before it calls any. +#! @param this The machine. +#! @returns Why it stopped, or `none` where the globals have their values. +pub def interpreter::begin(&mut this): halt { + this.trace.clear(); + this.fault_text.clear(); + this.status = 0; + when os == windows { + # The C functions the program calls are found before it runs, as the system + # running the machine, Windows, is reached through C. + val linked := this.link_foreign(); + return linked if linked != halt::none; + } + memset(this.globals, 0, this.c.program.globals); + val preset := this.c.program.preset.view(); + if preset.length != 0 { + memcpy(this.globals, preset.data, preset.length); + } + this.budget = this.options.steps; + return this.invoke(this.c.program.init, span::::empty()); +} + +#! Runs the program: the code giving the globals their values, then `main`, +#! given a view of each argument's text. +#! @param this The machine. +#! @param args The arguments. +#! @returns Why it stopped: `none` where `main` returned, and `exited` where it +#! asked to, with the status it asked for in `status`. +pub def interpreter::run(&mut this, args: span): halt { + val main := this.c.program.main; + if main == no_function { + this.trace.clear(); + return halt::no_main; + } + val begun := this.begin(); + return begun if begun != halt::none; + this.budget = this.options.steps; + + # `main` is given a view of views of each argument's text, which the machine + # holds while the program runs. + var words := vector::::new(); + var views := vector::::new(); + if this.routines[main].count == 1 { + for &each in args { + views.append(each.data as u64); + views.append(each.length); + } + words.append(args.length == 0 ? 0 : views.view().data as u64); + words.append(args.length); + + # Running with its memory checked, the program holds the views and the + # text of each, as it does memory the system gave it. + if this.options.checks && args.length != 0 { + this.add_run(views.view().data as u64, args.length * 16); + for &each in args { + this.add_run(each.data as u64, each.length); + } + } + } + return this.end_threads(this.invoke(main, words.view())); +} + +#! Calls a function from the base of the stack, given the bytes of its +#! parameters, and runs it until it returns. +#! @param this The machine. +#! @param index The function. +#! @param args The words of its parameters, as its frame holds them. +#! @returns Why it stopped, or `none`. +pub def interpreter::invoke(&mut this, index: u32, args: span): halt { + val held: routine = this.routines[index]; + val fp := this.stack as *mut u64; + if this.stack as u64 + held.frame > this.stack_end { + return halt::stack_overflow; + } + memset(this.stack, 0, held.frame); + for i in 0..args.length { + fp[i] = args[i]; + } + this.calls.clear(); + this.depth = 0; + this.calls.append(call_record { function = index, fp = fp, back = 0, site = 0, results = none }); + this.top = this.stack as u64 + held.frame; + return this.execute(0); +} + +#! Calls a function of the program, as a host embedding the machine does once +#! the program has begun, and runs it until it returns. A call made while the +#! program is calling the host, as from within a function the host provided, +#! runs above the calls under way; where it faults, they stop too, as the host +#! returns to them, so the call the host made first gives the fault. +#! @param this The machine. +#! @param function The function. +#! @param args The words of its parameters, as a call passes them: a +#! word for each integer, bool, pointer, and reference, an +#! `f64` for each float, an `f32` as well, the words of a +#! value held in words, as a view's address and length, and +#! the address of the bytes of a value passed in memory. +#! @param result Where a result held in memory is written, or 0; one held +#! in words is given by `result`. +#! @returns Why it stopped, or `none` where it returned. +pub def interpreter::call(&mut this, function: u32, args: span, result: u64 = 0): halt { + return this.call_with(function, 0, args, result); +} + +#! Calls a function value of the program, as `call` calls a function: its first +#! word is one more than the function, and its second what a closure uses. +#! @param this The machine. +#! @param function The function value's first word. +#! @param environment Its second. +#! @param args The words of its parameters, as `call` takes them. +#! @param result Where a result held in memory is written, or 0. +#! @returns Why it stopped, or `none` where it returned. +pub def interpreter::call_value(&mut this, function: u64, environment: u64, args: span, result: u64 = 0): halt { + return halt::null_reference if function == 0 || function > this.routines.length; + return this.call_with((function - 1) as u32, environment, args, result); +} + +# Calls a function for the host, as `call` says, with what a closure uses. +def interpreter::call_with(&mut this, function: u32, environment: u64, args: span, result: u64): halt { + val base := this.calls.length; + if base == 0 { + this.trace.clear(); + this.fault_text.clear(); + this.depth = 0; + this.top = this.stack as u64; + this.budget = this.options.steps; + } + if (function as u64) >= this.routines.length { + return this.host_stop(base, halt::null_reference); + } + val held: routine = this.routines[function]; + val frame := this.top as *mut u64; + if this.top + held.frame > this.stack_end { + return this.host_stop(base, halt::stack_overflow); + } + # A frame's words are written before they are read, so only its cells are + # zeroed, as a call within the program zeroes them, but where memory is + # checked, where none of it is left as another call left it. + if this.options.checks { + memset(frame as *mut u8, 0, held.frame); + } else if held.zeroed > held.cells { + memset((frame as u64 + held.cells) as *mut u8, 0, held.zeroed - held.cells); + } + var k: u64 = 0; + for p in 0..held.count { + val slot: param_slot = this.params[held.params as u64 + p as u64]; + val words: u64 = slot.memory ? 1 : slot.words as u64; + if k + words > args.length { + return this.host_stop(base, halt::unsupported); + } + if slot.memory { + val source: u64 = args[k]; + if source != 0 { + memcpy((frame as u64 + slot.offset) as *mut u8, source as *u8, slot.size); + } + } else { + for w in 0..words { + frame[slot.offset / word_size + w] = args[k + w]; + } + } + k += words; + } + if held.closure { + frame[held.env / word_size] = environment; + } + this.calls.append(call_record { function = function, fp = frame, back = 0, site = 0, results = none, dst = held.returned != 0 ? result : 0 }); + this.top = frame as u64 + held.frame; + # Made from within compiled code calling the host, the steps that code took + # are settled first, and it is given more after. + val within := this.jit_batch != 0; + if within { + this.jit_settle(); + } + val why := this.execute(base); + if within { + this.jit_arm(); + } + if why != halt::none && base != 0 && this.foreign_fault == halt::none { + this.foreign_fault = why; + } + return why; +} + +# Stops a call the host made before it ran, which stops those under way where +# it was made within them. +def interpreter::host_stop(&mut this, base: u64, why: halt): halt { + if base != 0 && this.foreign_fault == halt::none { + this.foreign_fault = why; + } + return why; +} + +#! A word of what the last call the host made returned, where it was held in +#! words: the first is the value of a scalar, and a view's address, the second +#! its length. +#! @param this The machine. +#! @param index Which word, below 3. +#! @returns The word. +pub def interpreter::result(&this, index: u64): u64 { + return index < 3 ? this.results[index] : 0; +} + +#! Takes what the program wrote to its output and error since this was last +#! asked, where it runs with `capture`. +#! @param this The machine. +#! @returns The text. +pub def interpreter::take_output(&mut this): string { + var text := string::from(this.output.view(), nothing {}); + this.output.clear(); + return text; +} + +#! Gives the program a function of the host's to call: a foreign declaration of +#! that name, as a C function is declared, calls it, whatever library its file +#! names. The program calls it as C would, so the address is one C calls, as a +#! `cfn` of a function of the host's own is. Given after the program has begun, +#! it replaces what was found for the name. The machine calls C only where the +#! system running it is Windows. +#! @param this The machine. +#! @param name The name. +#! @param address Where C calls it. +pub def interpreter::provide(&mut this, name: strview, address: u64): void { + var found := false; + for &mut each in this.provided { + if each.name.view() == name { + each.address = address; + found = true; + } + } + if !found { + this.provided.append(provided { name = string::from(name, nothing {}), address = address }); + } + for i in 0..this.symbols.length { + if this.c.checker.names.text(this.c.program.linked[i].name) == name { + this.symbols[i] = address; + } + } +} + +#! The address the host gave for a function the program calls by name, or 0. +#! @param this The machine. +#! @param name The name. +#! @returns The address. +pub def interpreter::provided_address(&this, name: strview): u64 { + for &each in this.provided { + return each.address if each.name.view() == name; + } + return 0; +} + +#! Records where each function running was, from the innermost out, then lets +#! go of every call. Where none is running, as where a call within them stopped +#! first and let go of them, what that one recorded is kept. +#! @param this The machine. +#! @param pc Where the innermost was. +pub def interpreter::record(&mut this, pc: u64): void { + if this.calls.length == 0 { + this.depth = 0; + this.top = this.stack as u64; + return; + } + this.trace.clear(); + var i := this.calls.length; + while i > 0 { + i--; + val call: call_record = this.calls.at(i); + val at := i == this.calls.length - 1 ? pc : this.calls.at(i + 1).site; + this.frames_at(call.function, at); + } + this.calls.clear(); + this.depth = 0; + this.top = this.stack as u64; +} + +#! Records where a function's code was, as a trace names it: each function +#! inlined there, from the innermost out, where it was, then the function +#! itself, where the outermost was called. +#! @param this The machine. +#! @param function The function. +#! @param pc Where in its code. +def interpreter::frames_at(&mut this, function: u32, pc: u64): void { + val held := &this.c.program.functions[function]; + var at: u64 = 0; + var site: u32 = 0; + for &mark in held.compiled.lines { + break if mark.pc as u64 > pc; + at = mark.at; + site = mark.site; + } + var steps := 0; + while site != 0 && site as u64 <= held.compiled.sites.length && steps < 1024 { + val inlined: inline_site = held.compiled.sites[site - 1]; + this.trace.append(this.frame_at(inlined.function, at)); + at = inlined.at; + site = inlined.parent; + steps++; + } + this.trace.append(this.frame_at(function, at)); +} + +#! The frame a block's allocation is reported at, of the code of a function +#! where it was made: the innermost function inlined there that is the +#! program's own rather than std's, or else the function itself. +#! @param this The machine. +#! @param function The function. +#! @param pc Where in its code. +#! @returns The frame. +pub def interpreter::site_frame(&mut this, function: u32, pc: u64): trace_frame { + var at: u64 = 0; + var site: u32 = 0; + for &mark in this.c.program.functions[function].compiled.lines { + break if mark.pc as u64 > pc; + at = mark.at; + site = mark.site; + } + var steps := 0; + while site != 0 && site as u64 <= this.c.program.functions[function].compiled.sites.length && steps < 1024 { + val inlined: inline_site = this.c.program.functions[function].compiled.sites[site - 1]; + return this.frame_at(inlined.function, at) if !this.in_std_function(inlined.function); + at = inlined.at; + site = inlined.parent; + steps++; + } + return this.frame_at(function, at); +} + +#! A frame of a trace: a function, and where in the source it was. +#! @param this The machine. +#! @param function The function. +#! @param at Where in the source: one more than the file, then the +#! byte, or 0 for where the function is declared. +#! @returns The frame. +def interpreter::frame_at(&mut this, function: u32, at: u64): trace_frame { + val held := &this.c.program.functions[function]; + var file: u32 = held.file; + var offset: u32 = held.offset; + if at != 0 { + file = pair_high(at) - 1; + offset = pair_low(at); + } + var made := trace_frame { function = string::from(held.name.view(), nothing {}) }; + return made if file as u64 >= this.c.checker.units.length; + val source := &this.c.checker.units[file].source; + val place := source.lines.place_of(offset); + made.path = source.path; + made.line = place.line; + made.column = place.column; + return made; +} + +#! What a halt says: the text `fault` was given, where it stopped the program, +#! and otherwise the halt's own sentence. +#! @param this The machine. +#! @param why Why it stopped. +#! @returns The text. +pub def interpreter::why_text(&this, why: halt): strview { + return this.fault_text.view() if why == halt::faulted && this.fault_text.length != 0; + return why.describe(); +} + +#! Writes why the program stopped, and the trace, as the C machine does. +#! @param this The machine. +#! @param why Why it stopped. +#! @param out Where it is written. +pub def interpreter::report(&this, why: halt, out: &mut string): void { + out.append("sakura: runtime error: "); + out.append(this.why_text(why)); + out.append("\n"); + for &each in this.trace { + out.append($" at {each.function} ({each.path}:{each.line}:{each.column})\n"); + } +} diff --git a/machine/system.sakura b/machine/system.sakura new file mode 100644 index 00000000..84e3ffe2 --- /dev/null +++ b/machine/system.sakura @@ -0,0 +1,138 @@ +#! @file system.sakura +#! @author John Christman (sorakatadzuma@gmail.com) +#! @copyright Malunal Studios, LLC. +#! @license MIT +#! +#! Contains what a program asks of the system: its calls, which the machine +#! makes as they are asked through `system::linux::syscall`, the variables it +#! started with, and the signals it handles, which the machine has `system` +#! note for it, so that the program's handlers run at its own safe points. + +import system; +module sakura::machine; + + +#! The number of the call that writes. +const call_write: u64 = 1; + +#! Makes a system call a program asks for, failing as the kernel does, with +#! the negated error number. What a program writes to its output or error is +#! kept instead where the machine is asked to. +#! @param number The call. +#! @param a Its first argument. +#! @param b Its second. +#! @param c Its third. +#! @param d Its fourth. +#! @param e Its fifth. +#! @param f Its sixth. +#! @param running The machine. +#! @returns What the call gives. +pub def system_call(number: u64, a: u64, b: u64, c: u64, d: u64, e: u64, f: u64, running: &mut interpreter): u64 { + if running.options.capture && number == call_write && (a == 1 || a == 2) { + val bytes := b as *u8; + for i in 0..c { + running.output.append(bytes[i]); + } + return c; + } + return host_call(number, a, b, c, d, e, f); +} + +when os == linux { + # Makes the call, as the system running the machine is Linux. + def host_call(number: u64, a: u64, b: u64, c: u64, d: u64, e: u64, f: u64): u64 { + return system::linux::syscall(number as i64, a, b, c, d, e, f) as u64; + } +} + +when os == windows { + # Windows has no calls a program makes itself, so a program checked for it + # calls C instead, as `system` does there. What a program writes to its + # output or error through the call of Linux is written still, as the + # machine's tests write it, and every other call fails as Linux fails one it + # does not have. + def host_call(number: u64, a: u64, b: u64, c: u64, d: u64, e: u64, f: u64): u64 { + if number == call_write && (a == 1 || a == 2) { + val to: system::fd = a == 1 ? system::fd::stdout : system::fd::stderr; + return to.write(b as *u8, c) as u64; + } + return (-38 as i64) as u64; + } +} + +#! Where the system put the variables the program started with: pointers to +#! text ending in a zero, then a null pointer, made once. +#! @param this The machine. +#! @returns The address of the first pointer. +pub def interpreter::environment(&mut this): u64 { + return this.environ if this.environ != 0; + val each := system::environment(); + val made := raw_allocate_zeroed((each.length + 1) * 8) as *mut u64; + for i in 0..each.length { + made[i] = each[i].data as u64; + } + this.environ = made as u64; + + # Running with its memory checked, the program holds the pointers and the + # text of each, to the zero ending it, as it does memory it mapped. + if this.options.checks { + this.add_run(made as u64, (each.length + 1) * 8); + for i in 0..each.length { + this.add_run(each[i].data as u64, each[i].length + 1); + } + } + return this.environ; +} + +#! The signals that came since the program last asked, one bit each by the +#! system's number, as `system` noted them for the machine. +pub var noted_signals: u64; + +#! Gathers the signals `system` noted for the machine since it last asked. +#! @returns Whether any came that the program has not asked for. +pub def signals_came(): bool { + noted_signals = noted_signals | system::watched(); + return noted_signals != 0; +} + +when os == linux { + #! Has a signal of the system's number noted when it comes, as a program asks. + #! The machine asks itself whether one came, at the program's safe points, so + #! no handler runs, and the machine's own code has no safe points. + #! @param number The signal's number. + #! @returns Zero, or the negated error number. + pub def catch_signal(number: i64): i64 { + return match system::signal_of(number) { + some(which) => system::watch(which) as i64, + else => -22 + }; + } +} + +when os == windows { + #! Has a signal of the system's number noted when it comes, thrown away, done + #! as the system does by default, noted now, or gives the handle of the event + #! the system sets where a signal is noted, as the bits above the number say, + #! as a program asks. The machine asks the system running it to do each, so a + #! signal reaches a program the machine runs as it does an executable, and a + #! wait of the program's ends on one as the machine's own waits do. No handler + #! of the machine's own runs, and the machine's own code has no safe points. + #! @param number The signal's number, with what to do in the bits above it: + #! 0 note it, 1 throw it away, 2 do as the system does, 3 note + #! it now, 4 give the event's handle. + #! @returns Zero, the event's handle, or the negated error number. + pub def catch_signal(number: i64): i64 { + val action := (number >> 8) & 0xFF; + return match system::signal_of(number & 0xFF) { + some(which) => match action { + 0 => system::watch(which) as i64, + 1 => system::ignore(which) as i64, + 2 => system::restore(which) as i64, + 3 => system::raise(which) as i64, + 4 => system::signal_event() as i64, + else => -22 + }, + else => action == 4 ? system::signal_event() as i64 : -22 + }; + } +} diff --git a/machine/threads.sakura b/machine/threads.sakura new file mode 100644 index 00000000..9c735537 --- /dev/null +++ b/machine/threads.sakura @@ -0,0 +1,399 @@ +#! @file threads.sakura +#! @author John Christman (sorakatadzuma@gmail.com) +#! @copyright Malunal Studios, LLC. +#! @license MIT +#! +#! Contains the threads of a program the machine runs, each a thread of the +#! system the machine starts with `std::thread`. They take turns running +#! bytecode, in the order they asked, so the machine and its heap are only ever +#! used by one: a thread lets the next run as it waits in the system, and every +#! few thousand steps where another waits. So threads run at the same time but +#! not in parallel, while an executable's run in parallel; a program right in +#! one is right in the other. +#! +#! What a thread has of its own, its stack, calls, texts being formatted, and +#! trace, is a strand, which the machine holds while the thread has its turn, +#! and the strand keeps while it has none. +#! +#! A thread that exits, or faults, stops the program: the others stop at their +#! next turn, and a wait in the system ends within a tenth of a second while +#! threads run, as the machine gives a futex's wait without a time one, so each +#! sees it. A fault is reported with the trace of the thread that faulted. + +import system; +import std::thread; +import std::time; +import sakura::compiler; +module sakura::machine; + + +#! The steps a thread takes before it lets another waiting run. +const turn_steps: u64 = 4096; + +#! How long a wait in the system lasts at most while threads run, so a thread +#! sees the program stop. +const longest_wait: i64 = 100000000; + +#! What a thread has of its own, which the machine holds while it has its turn. +struct strand { + var stack: *mut u8; + var stack_end: u64; + var top: u64; + var calls: call_stack; + var texts: vector>; + var depth: u64; + var trace: vector; + var countdown: u64; + var last_error: u32; #! The error the thread's last C call left, kept across the machine's own work. + var thread: u64; #! The number the system knows the thread by, which C calling back on it finds its strand by. + var active: bool; #! Whether the machine holds it. + var function: u32; #! The function the thread runs, what its closure uses, and the context it is given. + var environment: u64; + var context: u64; +} + +#! What a thread of the system is given to run a thread of the program: the +#! machine, and the thread's strand. +struct strand_start { + var machine: *mut interpreter; + var mine: *mut strand; +} + +#! What the threads of a program share, which the machine holds once one starts. +struct threading { + var next: atomic; #! Turns asked for. + var serving: atomic; #! The turn being taken. + var strands: vector<*mut strand>; #! Every thread's, the first's among them. + var handles: vector>; #! The threads of the system running them. + var running: u64; #! Threads started and not yet ended. + var stopped: bool; #! Whether the program stopped, exiting or faulting. + var stop: halt; #! Why. + var trace: vector; #! Where the thread that faulted was. +} + +#! Starts a thread running a function value, given a context, a thread of the +#! system taking turns with the others. The first thread started makes what +#! they share, the thread running holding the turn. +#! @param this The machine. +#! @param function The function's index, one more than it. +#! @param environment What a closure uses. +#! @param context The word the function is given. +#! @returns The thread's number, or a negative error number. +pub def interpreter::start_thread(&mut this, function: u64, environment: u64, context: u64): i64 { + if this.threads == null { + val shared := raw_allocate_zeroed(size_of::()) as *mut threading; + shared[0].strands = vector::<*mut strand>::new(); + shared[0].handles = vector::>::new(); + shared[0].trace = vector::::new(); + shared[0].next.store(1); + val mine := raw_allocate_zeroed(size_of::()) as *mut strand; + mine[0].active = true; + when os == windows { + mine[0].thread = system::thread_id(); + } + shared[0].strands.append(mine); + this.threads = shared; + this.strand = mine; + this.countdown = turn_steps; + } + + val shared := this.threads; + val made := raw_allocate_zeroed(size_of::()) as *mut strand; + # Its stack is cleared where the one the program began with is. + val size := this.stack_end - this.stack as u64; + made[0].stack = this.options.checks ? raw_allocate_zeroed(size) : raw_allocate(size); + made[0].stack_end = made[0].stack as u64 + size; + made[0].top = made[0].stack as u64; + made[0].calls = call_stack::new(); + made[0].texts = vector::>::new(); + made[0].trace = vector::::new(); + made[0].countdown = turn_steps; + made[0].function = (function - 1) as u32; + made[0].environment = environment; + made[0].context = context; + shared[0].strands.append(made); + shared[0].running++; + + val given := strand_start { machine = this as *mut interpreter, mine = made }; + var started := thread::spawn_with(def(at: strand_start) { through(at.machine).thread_main(at.mine); }, given) else (e) { + shared[0].strands.truncate(); + shared[0].running--; + raw_release(made[0].stack); + raw_release(made as *mut u8); + return -11; + }; + val number := started.number() as i64; + shared[0].handles.append(move(started)); + return number; +} + +#! What a thread of the system runs for a thread of the program: its function, +#! in its turns. Where it stops the program, every thread sees it. +#! @param this The machine. +#! @param mine The thread's strand. +def interpreter::thread_main(&mut this, mine: *mut strand): void { + val shared := this.threads; + when os == windows { + mine[0].thread = system::thread_id(); + } + this.take_turn(mine); + if !shared[0].stopped { + val ran := this.invoke_value(mine[0].function, mine[0].environment, mine[0].context); + if ran != halt::none && ran != halt::elsewhere { + this.stop_with(ran); + } + } + # The thread is done: its strand goes, and the turn passes on. + this.save(mine); + for i in 0..shared[0].strands.length { + if shared[0].strands[i] == mine { + shared[0].strands.remove_at(i); + break; + } + } + shared[0].running--; + this.give_turn(); + raw_release(mine[0].stack); + mine[0].calls.close(); + for i in 0..mine[0].texts.length { + mine[0].texts[i].close(); + } + mine[0].texts.close(); + mine[0].trace.close(); + raw_release(mine as *mut u8); +} + +#! Calls a function value from the base of the stack, as a thread begins, and +#! runs it until it returns. +#! @param this The machine. +#! @param index The function. +#! @param environment What a closure uses. +#! @param context The word it is given. +#! @returns Why it stopped, or `none`. +def interpreter::invoke_value(&mut this, index: u32, environment: u64, context: u64): halt { + val held: routine = this.routines[index]; + val fp := this.stack as *mut u64; + if this.stack as u64 + held.frame > this.stack_end { + return halt::stack_overflow; + } + memset(this.stack, 0, held.frame); + # The context is the first parameter, where the function takes one. + if held.frame >= word_size { + fp[0] = context; + } + if held.closure { + fp[held.env / word_size] = environment; + } + this.calls.clear(); + this.depth = 0; + this.calls.append(call_record { function = index, fp = fp, back = 0, site = 0, results = none }); + this.top = this.stack as u64 + held.frame; + return this.execute(0); +} + +#! Says the program stopped, for why, where nothing stopped it before, keeping +#! the trace of a fault. +#! @param this The machine. +#! @param why Why. +def interpreter::stop_with(&mut this, why: halt): void { + val shared := this.threads; + return if shared[0].stopped; + shared[0].stopped = true; + shared[0].stop = why; + if why != halt::exited { + shared[0].trace = move(&mut this.trace); + } +} + +#! Where a thread's run of steps ends: it lets another waiting run. +#! @param this The machine. +#! @returns `elsewhere` where the program stopped meanwhile, or `none`. +def interpreter::next_turn(&mut this): halt { + this.countdown = turn_steps; + val shared := this.threads; + return halt::elsewhere if shared[0].stopped; + return halt::none if shared[0].next.load() - shared[0].serving.load() <= 1; + val mine := this.strand; + this.pause(); + return this.resume(mine); +} + +#! Ends a thread's turn, as it waits in the system or lets another run, keeping +#! what it has of its own in its strand. +#! @param this The machine. +pub def interpreter::pause(&mut this): void { + return if this.threads == null; + this.save(this.strand); + this.give_turn(); +} + +#! Takes a thread's next turn. +#! @param this The machine. +#! @param mine The thread's strand. +#! @returns `elsewhere` where the program stopped meanwhile, or `none`. +pub def interpreter::resume(&mut this, mine: *mut strand): halt { + return halt::none if this.threads == null; + this.take_turn(mine); + return this.threads[0].stopped ? halt::elsewhere : halt::none; +} + +# Waits for the turn, after every thread that asked before, then holds the +# thread's strand. +def interpreter::take_turn(&mut this, mine: *mut strand): void { + val shared := this.threads; + val ticket := shared[0].next.fetch_add(1); + while true { + val now := shared[0].serving.load(); + if now == ticket { + break; + } + _ = system::futex_wait(((&mut shared[0].serving) as *mut atomic) as *mut u32, now, -1); + } + this.restore(mine); +} + +# Lets the thread that asked next have its turn. +def interpreter::give_turn(&mut this): void { + val shared := this.threads; + _ = shared[0].serving.fetch_add(1); + _ = system::futex_wake(((&mut shared[0].serving) as *mut atomic) as *mut u32, 0x7FFFFFFF); +} + +# Keeps what the thread running has of its own in its strand. +def interpreter::save(&mut this, into: *mut strand): void { + into[0].stack = this.stack; + into[0].stack_end = this.stack_end; + into[0].top = this.top; + into[0].calls = move(&mut this.calls); + into[0].texts = move(&mut this.texts); + into[0].depth = this.depth; + into[0].trace = move(&mut this.trace); + into[0].countdown = this.countdown; + into[0].last_error = this.last_error; + into[0].active = false; +} + +# Holds a thread's strand as the thread running's. +def interpreter::restore(&mut this, from: *mut strand): void { + this.stack = from[0].stack; + this.stack_end = from[0].stack_end; + this.top = from[0].top; + this.calls = move(&mut from[0].calls); + this.texts = move(&mut from[0].texts); + this.depth = from[0].depth; + this.trace = move(&mut from[0].trace); + this.countdown = from[0].countdown; + this.last_error = from[0].last_error; + this.strand = from; + from[0].active = true; +} + +#! Whether bytes from an address lie within the frames another thread of the +#! program is using, which a reference into another's locals may reach. +#! @param this The machine. +#! @param at The address. +#! @param bytes How many bytes. +#! @returns Whether they do. +pub def interpreter::in_other_frames(&mut this, at: u64, bytes: u64): bool { + return false if this.threads == null; + val shared := this.threads; + for i in 0..shared[0].strands.length { + val each: *mut strand = shared[0].strands[i]; + continue if each == this.strand; + return true if at >= each[0].stack as u64 && at <= each[0].top && each[0].top - at >= bytes; + } + return false; +} + +#! Whether an address lies within the stack of any thread of the program. +#! @param this The machine. +#! @param at The address. +#! @returns Whether it does. +pub def interpreter::in_stacks(&mut this, at: u64): bool { + return true if at >= this.stack as u64 && at < this.stack_end; + return false if this.threads == null; + val shared := this.threads; + for i in 0..shared[0].strands.length { + val each: *mut strand = shared[0].strands[i]; + return true if at >= each[0].stack as u64 && at < each[0].stack_end; + } + return false; +} + +#! In a copy of the program a thread made, which holds that thread alone, the +#! other threads are gone. +#! @param this The machine. +pub def interpreter::forked(&mut this): void { + return if this.threads == null; + val shared := this.threads; + var kept := vector::<*mut strand>::new(); + kept.append(this.strand); + shared[0].strands = move(&mut kept); + shared[0].running = 0; + while shared[0].handles.length != 0 { + # Their threads of the system are gone with the copy, so none is waited for. + var gone := move(&mut shared[0].handles.last()); + val leaked := &mut vector::>::new(); + leaked.append(move(&mut gone)); + shared[0].handles.truncate(); + } +} + +#! A wait in the system the machine makes for a thread: a futex's wait without a +#! time lasts a tenth of a second at most while threads run, so the thread +#! sees the program stop. +#! @param this The machine. +#! @param op The futex's operation. +#! @param time Where the time it lasts is, or 0. +#! @param into Where a time of the machine's own may be written. +#! @returns Where the time is. +pub def interpreter::wait_time(&mut this, op: u64, time: u64, into: *mut i64): u64 { + return time if this.threads == null || (op & 0x7F) != 0 || time != 0; + into[0] = 0; + into[1] = longest_wait; + return into as u64; +} + +#! Once the program's `main` returns, or the program stops, the threads still +#! running stop too: each at its next turn. They are waited for, so nothing of +#! the machine is used once it is gone, but for one that never comes back from +#! the system. Gives why the program stopped, where a thread stopped it. +#! @param this The machine. +#! @param ran Why `main` stopped. +#! @returns Why the program stopped. +pub def interpreter::end_threads(&mut this, ran: halt): halt { + return ran if this.threads == null; + val shared := this.threads; + var result := ran; + if shared[0].stopped { + result = shared[0].stop; + if result != halt::exited { + this.trace = move(&mut shared[0].trace); + } + } else { + shared[0].stopped = true; + shared[0].stop = ran == halt::none ? halt::exited : ran; + } + + val mine := this.strand; + var tries := 0u; + while shared[0].running > 0 && tries < 3000 { + this.pause(); + time::sleep(time::milliseconds(1)); + _ = this.resume(mine); + tries++; + } + if shared[0].running > 0 { + return result; + } + # Every thread has ended, so joining each waits for no more than its end. + shared[0].handles.close(); + shared[0].strands.close(); + shared[0].trace.close(); + raw_release(mine as *mut u8); + raw_release(shared as *mut u8); + this.threads = null; + this.strand = null; + this.countdown = 0; + return result; +} diff --git a/machine/x86.sakura b/machine/x86.sakura new file mode 100644 index 00000000..e6845e46 --- /dev/null +++ b/machine/x86.sakura @@ -0,0 +1,496 @@ +#! @file x86.sakura +#! @author John Christman (sorakatadzuma@gmail.com) +#! @copyright Malunal Studios, LLC. +#! @license MIT +#! +#! Contains the instructions of x86-64 that `jit.sakura` compiles functions to, +#! each encoded into the bytes of the code being made: moves, arithmetic, and +#! comparisons of words in registers and in memory, through a base register and +#! a displacement; jumps and calls; and the SSE2 arithmetic of doubles. A +#! register is its number in the encoding, so `r8` to `r15` set a REX bit. + +module sakura::machine; + + +# The general registers, numbered as the encoding numbers them. +const rax: u8 = 0; +const rcx: u8 = 1; +const rdx: u8 = 2; +const rbx: u8 = 3; +const rsp: u8 = 4; +const rbp: u8 = 5; +const rsi: u8 = 6; +const rdi: u8 = 7; +const r8: u8 = 8; +const r9: u8 = 9; +const r10: u8 = 10; +const r11: u8 = 11; +const r12: u8 = 12; +const r13: u8 = 13; +const r14: u8 = 14; +const r15: u8 = 15; + +# The conditions of `jcc`, `setcc`, and `cmovcc`, as the encoding numbers them. +const cc_b: u8 = 0x2; #! Below, unsigned. +const cc_ae: u8 = 0x3; #! Above or equal, unsigned. +const cc_e: u8 = 0x4; #! Equal. +const cc_ne: u8 = 0x5; #! Not equal. +const cc_be: u8 = 0x6; #! Below or equal, unsigned. +const cc_a: u8 = 0x7; #! Above, unsigned. +const cc_s: u8 = 0x8; #! Sign. +const cc_p: u8 = 0xA; #! Parity, as an unordered comparison of reals sets. +const cc_np: u8 = 0xB; #! No parity. +const cc_l: u8 = 0xC; #! Less, signed. +const cc_ge: u8 = 0xD; #! Greater or equal, signed. +const cc_le: u8 = 0xE; #! Less or equal, signed. +const cc_g: u8 = 0xF; #! Greater, signed. + +# The extensions of the instructions of a register or memory and an immediate, +# which pick the operation. +const alu_add: u8 = 0; +const alu_or: u8 = 1; +const alu_and: u8 = 4; +const alu_sub: u8 = 5; +const alu_xor: u8 = 6; +const alu_cmp: u8 = 7; + +# The extensions of the shifts. +const shift_left: u8 = 4; +const shift_right: u8 = 5; +const shift_arithmetic: u8 = 7; + +#! The bytes of code being made. +struct machine_code : owning { + var bytes: vector; +} + +#! Empty code. +#! @returns The code. +def machine_code::new(): machine_code { + return machine_code { bytes = vector::::new() }; +} + +#! How many bytes the code has. +val machine_code::length: u64 { + get => this.bytes.length; +} + +def machine_code::close(&mut this): void { + this.bytes.close(); +} + +#! Adds a byte. +def machine_code::byte(&mut this, value: u64): void { + this.bytes.append(value as u8); +} + +#! Adds four bytes, the low first. +def machine_code::u32(&mut this, value: u64): void { + for i in 0..4u { + this.bytes.append((value >> (8 * i)) as u8); + } +} + +#! Adds eight bytes, the low first. +def machine_code::u64(&mut this, value: u64): void { + for i in 0..8u { + this.bytes.append((value >> (8 * i)) as u8); + } +} + +#! Writes four bytes over those at a place, the low first. +def machine_code::patch32(&mut this, at: u64, value: u64): void { + for i in 0..4u { + this.bytes.set(at + i, (value >> (8 * i)) as u8); + } +} + +#! Whether a word is a 32-bit immediate's sign extension. +def fits32(value: u64): bool { + val signed := value as i64; + return signed >= -2147483648 && signed <= 2147483647; +} + +#! Whether a word is an 8-bit immediate's sign extension. +def fits8(value: u64): bool { + val signed := value as i64; + return signed >= -128 && signed <= 127; +} + +# The REX prefix: `w` for 64 bits, then the high bits of the register field, the +# index, and the base. One is written where any is set, or where `byte` asks, +# as reaching `spl` to `dil` as bytes does. +def machine_code::rex(&mut this, w: bool, reg: u8, index: u8, base: u8, byte: bool): void { + var made: u64 = 0x40; + if w { made = made | 8; } + if reg >= 8 { made = made | 4; } + if index >= 8 { made = made | 2; } + if base >= 8 { made = made | 1; } + if made != 0x40 || (byte && (reg >= 4 || base >= 4)) { + this.byte(made); + } +} + +# The ModRM byte and what follows it for memory at a base and a displacement, +# the register field `reg`: the shortest displacement, a SIB byte for `rsp` and +# `r12`, and a displacement always for `rbp` and `r13`. +def machine_code::memory(&mut this, reg: u8, base: u8, disp: u64): void { + val r := (reg & 7) as u64; + val b := (base & 7) as u64; + if disp == 0 && b != 5 { + this.byte((r << 3) | b); + if b == 4 { this.byte(0x24); } + } else if fits8(disp) { + this.byte(0x40 | (r << 3) | b); + if b == 4 { this.byte(0x24); } + this.byte(disp & 0xFF); + } else { + this.byte(0x80 | (r << 3) | b); + if b == 4 { this.byte(0x24); } + this.u32(disp); + } +} + +# The ModRM byte of two registers. +def machine_code::registers(&mut this, reg: u8, rm: u8): void { + this.byte(0xC0 | (((reg & 7) as u64) << 3) | (rm & 7) as u64); +} + +# An instruction of a register and memory: its prefix, if any, REX, its opcode +# bytes, then the memory. +def machine_code::op_mem(&mut this, prefix: u64, w: bool, opcode: u64, reg: u8, base: u8, disp: u64): void { + if prefix != 0 { this.byte(prefix); } + this.rex(w, reg, 0, base, false); + if opcode > 0xFF { this.byte(opcode >> 8); } + this.byte(opcode & 0xFF); + this.memory(reg, base, disp); +} + +# An instruction of two registers, likewise. +def machine_code::op_reg(&mut this, prefix: u64, w: bool, opcode: u64, reg: u8, rm: u8): void { + if prefix != 0 { this.byte(prefix); } + this.rex(w, reg, 0, rm, false); + if opcode > 0xFF { this.byte(opcode >> 8); } + this.byte(opcode & 0xFF); + this.registers(reg, rm); +} + +#! `mov reg, [base + disp]`. +def machine_code::load(&mut this, reg: u8, base: u8, disp: u64): void { + this.op_mem(0, true, 0x8B, reg, base, disp); +} + +#! `mov [base + disp], reg`. +def machine_code::store(&mut this, base: u8, disp: u64, reg: u8): void { + this.op_mem(0, true, 0x89, reg, base, disp); +} + +#! `mov qword [base + disp], imm32`, sign extended. +def machine_code::store_imm(&mut this, base: u8, disp: u64, imm: u64): void { + this.op_mem(0, true, 0xC7, 0, base, disp); + this.u32(imm); +} + +#! `mov to, from`. +def machine_code::mov(&mut this, to: u8, from: u8): void { + this.op_reg(0, true, 0x89, from, to); +} + +#! A word into a register, by the shortest encoding. +def machine_code::mov_imm(&mut this, reg: u8, value: u64): void { + if value <= 0xFFFFFFFF { + this.rex(false, 0, 0, reg, false); + this.byte(0xB8 + (reg & 7) as u64); + this.u32(value); + } else if fits32(value) { + this.rex(true, 0, 0, reg, false); + this.byte(0xC7); + this.registers(0, reg); + this.u32(value); + } else { + this.rex(true, 0, 0, reg, false); + this.byte(0xB8 + (reg & 7) as u64); + this.u64(value); + } +} + +#! `mov rax, [address]`, of an address of 64 bits. +def machine_code::load_rax_absolute(&mut this, address: u64): void { + this.byte(0x48); + this.byte(0xA1); + this.u64(address); +} + +#! `lea reg, [base + disp]`. +def machine_code::lea(&mut this, reg: u8, base: u8, disp: u64): void { + this.op_mem(0, true, 0x8D, reg, base, disp); +} + +#! `lea reg, [base + index * 2^scale]`. +def machine_code::lea_index(&mut this, reg: u8, base: u8, index: u8, scale: u64): void { + this.rex(true, reg, index, base, false); + this.byte(0x8D); + if (base & 7) == 5 { + this.byte(0x44 | (((reg & 7) as u64) << 3)); + this.byte((scale << 6) | (((index & 7) as u64) << 3) | (base & 7) as u64); + this.byte(0); + } else { + this.byte(0x04 | (((reg & 7) as u64) << 3)); + this.byte((scale << 6) | (((index & 7) as u64) << 3) | (base & 7) as u64); + } +} + +#! An arithmetic of two registers: `add`, `or`, `and`, `sub`, `xor`, or `cmp`, by +#! its extension. +def machine_code::alu(&mut this, ext: u8, to: u8, from: u8): void { + this.op_reg(0, true, (ext as u64) * 8 + 1, from, to); +} + +#! An arithmetic of a register and memory, the register written. +def machine_code::alu_mem(&mut this, ext: u8, reg: u8, base: u8, disp: u64): void { + this.op_mem(0, true, (ext as u64) * 8 + 3, reg, base, disp); +} + +#! An arithmetic of a register and an immediate, sign extended from 32 bits. +def machine_code::alu_imm(&mut this, ext: u8, reg: u8, imm: u64): void { + this.rex(true, 0, 0, reg, false); + if fits8(imm) { + this.byte(0x83); + this.registers(ext, reg); + this.byte(imm & 0xFF); + } else { + this.byte(0x81); + this.registers(ext, reg); + this.u32(imm); + } +} + +#! An arithmetic of memory and an immediate, sign extended from 32 bits. +def machine_code::alu_mem_imm(&mut this, ext: u8, base: u8, disp: u64, imm: u64): void { + if fits8(imm) { + this.op_mem(0, true, 0x83, ext, base, disp); + this.byte(imm & 0xFF); + } else { + this.op_mem(0, true, 0x81, ext, base, disp); + this.u32(imm); + } +} + +#! `test a, b`. +def machine_code::test(&mut this, a: u8, b: u8): void { + this.op_reg(0, true, 0x85, b, a); +} + +#! `test eax, eax`. +def machine_code::test_status(&mut this): void { + this.byte(0x85); + this.byte(0xC0); +} + +#! `imul reg, from`. +def machine_code::imul(&mut this, reg: u8, from: u8): void { + this.op_reg(0, true, 0x0FAF, reg, from); +} + +#! `imul reg, [base + disp]`. +def machine_code::imul_mem(&mut this, reg: u8, base: u8, disp: u64): void { + this.op_mem(0, true, 0x0FAF, reg, base, disp); +} + +#! `imul reg, from, imm32`. +def machine_code::imul_imm(&mut this, reg: u8, from: u8, imm: u64): void { + this.op_reg(0, true, 0x69, reg, from); + this.u32(imm); +} + +#! A shift of a register by `cl`. +def machine_code::shift_cl(&mut this, ext: u8, reg: u8): void { + this.op_reg(0, true, 0xD3, ext, reg); +} + +#! A shift of a register by an immediate. +def machine_code::shift_imm(&mut this, ext: u8, reg: u8, count: u64): void { + this.op_reg(0, true, 0xC1, ext, reg); + this.byte(count & 0xFF); +} + +#! An operation of one register, `F7` and its extension: `not` 2, `neg` 3, `div` +#! 6, and `idiv` 7. +def machine_code::unary(&mut this, ext: u8, reg: u8): void { + this.op_reg(0, true, 0xF7, ext, reg); +} + +#! `cqo`. +def machine_code::cqo(&mut this): void { + this.byte(0x48); + this.byte(0x99); +} + +#! `setcc al`, then `movzx eax, al`. +def machine_code::set_rax(&mut this, cc: u8): void { + this.byte(0x0F); + this.byte(0x90 + cc as u64); + this.byte(0xC0); + this.byte(0x0F); + this.byte(0xB6); + this.byte(0xC0); +} + +#! `setcc` of the low byte of `rax`, `rcx`, or `rdx`. +def machine_code::set_low(&mut this, cc: u8, reg: u8): void { + this.byte(0x0F); + this.byte(0x90 + cc as u64); + this.byte(0xC0 + reg as u64); +} + +#! `cmovcc to, from`. +def machine_code::cmov(&mut this, cc: u8, to: u8, from: u8): void { + this.op_reg(0, true, 0x0F40 + cc as u64, to, from); +} + +#! `btc reg, 63`, which turns a double's sign. +def machine_code::flip_sign(&mut this, reg: u8): void { + this.op_reg(0, true, 0x0FBA, 7, reg); + this.byte(63); +} + +#! `popcnt`, `bsr`, or `bsf` of a register, by its second opcode byte. +def machine_code::bits(&mut this, prefix: u64, opcode: u64, to: u8, from: u8): void { + this.op_reg(prefix, true, 0x0F00 + opcode, to, from); +} + +#! `bswap reg`. +def machine_code::bswap(&mut this, reg: u8): void { + this.rex(true, 0, 0, reg, false); + this.byte(0x0F); + this.byte(0xC8 + (reg & 7) as u64); +} + +#! A load narrower than a word, by its opcode: `movzx` and `movsx` of bytes and +#! halves, `mov` of 32 bits, which clears the high half, or `movsxd`. +def machine_code::load_narrow(&mut this, opcode: u64, w: bool, reg: u8, base: u8, disp: u64): void { + this.op_mem(0, w, opcode, reg, base, disp); +} + +#! A store of the low bytes of a register: 1, 2, or 4. +def machine_code::store_narrow(&mut this, size: u64, base: u8, disp: u64, reg: u8): void { + if size == 2 { this.byte(0x66); } + this.rex(false, reg, 0, base, size == 1); + this.byte(size == 1 ? 0x88 : 0x89); + this.memory(reg, base, disp); +} + +#! A store of an immediate of 1, 2, or 4 bytes. +def machine_code::store_narrow_imm(&mut this, size: u64, base: u8, disp: u64, imm: u64): void { + if size == 2 { this.byte(0x66); } + this.rex(false, 0, 0, base, false); + this.byte(size == 1 ? 0xC6 : 0xC7); + this.memory(0, base, disp); + if size == 1 { + this.byte(imm & 0xFF); + } else if size == 2 { + this.byte(imm & 0xFF); + this.byte((imm >> 8) & 0xFF); + } else { + this.u32(imm); + } +} + +#! An SSE instruction of an XMM register and memory: `movsd` loads with `F2 10`, +#! stores with `F2 11`, and the arithmetic of doubles. +def machine_code::sse_mem(&mut this, prefix: u64, opcode: u64, xmm: u8, base: u8, disp: u64): void { + this.op_mem(prefix, false, 0x0F00 + opcode, xmm, base, disp); +} + +#! `movaps to, from`, copying the whole of an XMM register. +def machine_code::movaps(&mut this, to: u8, from: u8): void { + return if to == from; + this.op_reg(0, false, 0x0F28, to, from); +} + +#! `movdqu [base + disp], xmm`, keeping the whole of a register. +def machine_code::save_xmm(&mut this, base: u8, disp: u64, xmm: u8): void { + this.op_mem(0xF3, false, 0x0F7F, xmm, base, disp); +} + +#! `movdqu xmm, [base + disp]`. +def machine_code::restore_xmm(&mut this, xmm: u8, base: u8, disp: u64): void { + this.op_mem(0xF3, false, 0x0F6F, xmm, base, disp); +} + +#! An SSE instruction of two XMM registers. +def machine_code::sse_reg(&mut this, prefix: u64, opcode: u64, to: u8, from: u8): void { + this.op_reg(prefix, false, 0x0F00 + opcode, to, from); +} + +#! `movq xmm, reg`. +def machine_code::movq_to_xmm(&mut this, xmm: u8, reg: u8): void { + this.op_reg(0x66, true, 0x0F6E, xmm, reg); +} + +#! `movq reg, xmm`. +def machine_code::movq_from_xmm(&mut this, reg: u8, xmm: u8): void { + this.op_reg(0x66, true, 0x0F7E, xmm, reg); +} + +#! `cvtsi2sd xmm, reg`. +def machine_code::cvtsi2sd(&mut this, xmm: u8, reg: u8): void { + this.op_reg(0xF2, true, 0x0F2A, xmm, reg); +} + +#! `cvttsd2si reg, xmm`. +def machine_code::cvttsd2si(&mut this, reg: u8, xmm: u8): void { + this.op_reg(0xF2, true, 0x0F2C, reg, xmm); +} + +#! `jcc rel32` to a place not yet known, giving where its displacement is. +def machine_code::jcc(&mut this, cc: u8): u64 { + this.byte(0x0F); + this.byte(0x80 + cc as u64); + val at := this.length; + this.u32(0); + return at; +} + +#! `jmp rel32` to a place not yet known, giving where its displacement is. +def machine_code::jmp(&mut this): u64 { + this.byte(0xE9); + val at := this.length; + this.u32(0); + return at; +} + +#! Points the displacement of a jump at a place in the code. +def machine_code::land(&mut this, at: u64, target: u64): void { + this.patch32(at, (target - (at + 4)) & 0xFFFFFFFF); +} + +#! `call reg`. +def machine_code::call_reg(&mut this, reg: u8): void { + this.rex(false, 0, 0, reg, false); + this.byte(0xFF); + this.registers(2, reg); +} + +#! Calls a function at an address through `rax`. +def machine_code::call_absolute(&mut this, address: u64): void { + this.mov_imm(rax, address); + this.call_reg(rax); +} + +#! `ret`. +def machine_code::ret(&mut this): void { + this.byte(0xC3); +} + +#! `push reg`. +def machine_code::push(&mut this, reg: u8): void { + if reg >= 8 { this.byte(0x41); } + this.byte(0x50 + (reg & 7) as u64); +} + +#! `pop reg`. +def machine_code::pop(&mut this, reg: u8): void { + if reg >= 8 { this.byte(0x41); } + this.byte(0x58 + (reg & 7) as u64); +} diff --git a/native/README.md b/native/README.md new file mode 100644 index 00000000..3cc16029 --- /dev/null +++ b/native/README.md @@ -0,0 +1,171 @@ +# sakura::native + +`sakura::native` is the Sakura compiler's native backend: what a program's `when backend == +native` names, and what `sakura build` builds with. It takes a program `sakura::compiler` +has lowered and optimized and builds an x86-64 executable of it, for Linux as ELF or for +Windows as PE. It chooses the instructions of each function's intermediate code, places +its values in registers and its frame, and writes the file with its runtime, its start, +and the handlers of faults. With `-g`, it also writes what debuggers read: DWARF in a +`.petal` file beside a Linux executable, and a PDB file beside a Windows one. + +The encodings are those of the libraries it writes through, all of them `binary`'s: +`binary::amd64` for the instructions, and `binary::elf`, `binary::dwarf`, `binary::pe`, +and `binary::pdb` for the files. + +## Using it + +Require this repository, which exports each of the compiler's libraries, and name this +one among a target's `deps` with the analyzer and the compiler, which it reads itself. A +build evaluates the program's constants on the machine, so name the machine too: + +```yaml +requires: +- https://git.malunal.studio/sakura/std@v1.0.0 +- https://git.malunal.studio/sakura/sakurac@v1.0.0 + +targets: +- name: app + type: program + deps: [sakura.analyzer, sakura.compiler, sakura.machine, sakura.native, std.io] +``` + +Building a program as `sakura build` does: + +```sakura +import std::io; +import sakura::analyzer; +import sakura::compiler; +import sakura::machine; +import sakura::native; + +# Builds a program into a Linux executable, as `sakura build` does, and gives +# whether it could. Its files are read, then `core` whole, then the modules of +# `system`, `std`, and the runtime that they refer to, a round at a time. The +# program is checked for an executable, its constants are evaluated on the +# machine, and it is lowered, optimized, and built. +def build( + files: span, core: strview, system: strview, runtime: strview, library: strview, output: strview +): bool { + var finder := resolver::new(); + finder.whole("core", core); + finder.add_library("system", system); + finder.add_library("runtime", runtime); + finder.add_library("std", library); + var paths := vector::::new(); + for each in files { + paths.append(string::from(each, nothing {})); + } + paths.append(string::from(builtin_path, nothing {})); + every_file(core, &mut paths); + for &each in paths { + finder.mark(each.view()); + } + finder.want("runtime", &mut paths); # Every executable has the runtime. + + var names := names::new(); + var notes := vector::::new(); + var sources := vector::::new(); + var syntaxes := vector::::new(); + var roots := vector::::new(); + # The checker refers to each source and syntax, so there is room for every + # file the libraries hold before any is read, and none moves. + val room := paths.length + finder.files_held(); + sources.reserve(room); + syntaxes.reserve(room); + for i in 0..room { + break if i == paths.length; + val at := paths[i].view(); + sources.append(at == builtin_path ? source::from(at, builtin_text) : source::open(at)); + syntaxes.append(syntax::new()); + var lexing := lexer::new(sources.at(i), &mut names, &mut notes, i as u32); + lexing.tokenize_all(syntaxes.at(i)); + var parsing := parser::new(syntaxes.at(i), &names, &mut notes, i as u32); + roots.append(parsing.parse()); + finder.refer(syntaxes.at(i), &names, &mut paths); # Adds the files it refers to. + } + + var checker := checker::new(&mut names, &mut notes); + checker.target.os = checker.names.intern(&"linux"); + checker.target.backend = checker.names.intern(&"native"); + for i in 0..paths.length { + checker.add(sources.at(i), syntaxes.at(i), roots.at(i)); + } + checker.check(); + var results := outcomes::new(); + if notes.length == 0 { + results = evaluate(&mut checker); + } + for &each in notes { + val held := &sources.at(each.file); + val at := held.lines.place_of(each.offset); + println($"{held.path}:{at.line}:{at.column}: {each.code}: {each.message(held)}"); + } + return false if notes.length != 0; + + var lowered := lowerer::new(&mut checker, lowering { level = 2 }); + lowered.evaluated = move(&mut results); + lowered.compile(); + for &each in lowered.problems { + println(each); + } + return false if lowered.problems.length != 0; + + val made := build_executable(&mut lowered, build_options { output = output }); + for &each in made { + println(each); + } + return made.length == 0; +} +``` + +`core`, `system`, and `runtime` are the folders beside the `sakurac` executable, and `std` +is its standard library. For Windows, the checker's `os` is `windows` and the options' +`windows` is set. + +## What it holds + +- **Building**: `build_executable`, given a lowered program and its `build_options`, writes + the executable and gives what it couldn't build. + - `debug` writes the debugging information too, as `-g` asks; + - `windows` builds for Windows rather than Linux; + - `threads` places the values of that many functions at once; + - `verify`, as `--verify` asks, replays where each function's values were placed. +- **Instructions**: each operation of the intermediate code as a few instructions over + the registers and slots its operands are in. A `simd`'s lanes use SSE, AVX, or for 64 + bytes AVX-512 where the processor running the program has them, with the constants + they read written after each function, and atomics use the locked instructions. +- **Registers**: a linear scan over each function's values, in SSA form, which keeps a + value live across a call in a register the call keeps or in its slot. Where more + values live than registers hold, it spills the one read furthest ahead, or within a + loop the one read least often. A checker replays what it chose, symbolically, in the + tests and with `verify`. +- **Calls to C**: values cross as the System V ABI passes them on Linux, and as + Microsoft's x86-64 ABI does on Windows, both ways, for the functions C calls back. +- **Executables**: the image the runtime reads, the stubs reporting traps and faults, + the start the system runs, and jumps shortened once a function's code is written, with + the head of a loop jumping through a table begun at a multiple of 64 bytes. For + Windows, the functions imported from kernel32 and the program's libraries, the + handlers of faults and of the console, and how each function unwinds. +- **Debugging information**: each function's lines, the calls inlined into it, how its + frame unwinds, and where each variable is over its code, held in memory or, in + optimized code, in registers, slots, or as a constant. + +## Testing + +From the repository's root, `blossom test` runs them as `sakura.native.tests`, or, with +`std` and `binary` beside the repository: + +```sh +sakurac run --lib std=../std --lib sakura::analyzer=analyzer --lib sakura::compiler=compiler \ + --lib sakura::machine=machine --lib sakura::server=server \ + --lib binary::amd64=../binary/amd64 --lib binary::elf=../binary/elf \ + --lib binary::dwarf=../binary/dwarf --lib binary::pe=../binary/pe \ + --lib binary::pdb=../binary/pdb --lib sakura::native=native tests/main.sakura tests/native/*.sakura +``` + +The tests are declared within the module. They build programs over `core`, `system`, and +the runtime beside `sakura`, which they find as the language server does, and over the +standard library's repository beside this one, else the `std` beside `sakura`. They run +what they built and read the files written. They also call C and check what gdb and +valgrind make of the debugging information, where those are installed, which takes a few +minutes; where no standard library is found, those tests pass over what they test. diff --git a/native/abi.sakura b/native/abi.sakura new file mode 100644 index 00000000..002c77c8 --- /dev/null +++ b/native/abi.sakura @@ -0,0 +1,881 @@ +#! @file abi.sakura +#! @author John Christman (sorakatadzuma@gmail.com) +#! @copyright Malunal Studios, LLC. +#! @license MIT +#! +#! Contains how values cross to C on x86-64, as the System V ABI passes them, +#! and the code of calls of C and of the functions C calls. A value is split +#! into eightbytes, each passed in an integer or an SSE register, unless it is +#! larger than two of them, or too few registers are left for all of its +#! eightbytes, in which case the whole value is passed on the stack. A result +#! too large for two registers is written by C to memory whose address the +#! caller passes as a hidden first argument, and which C gives back. +#! +#! A frame holds a scalar widened to a word, and an `f32` as a double, where C +#! holds it as it is, so each crossing narrows or widens it. C is given a +#! reference as its address alone. + +import sakura::compiler; +import binary::amd64; +module sakura::native; + + +#! The registers C takes integers in, in order. +pub const c_integers: reg[6] = [reg::rdi, reg::rsi, reg::rdx, reg::rcx, reg::r8, reg::r9]; + +#! The class of an eightbyte. +pub enum abi_class : u8 { none, integer, sse } + +#! How one value crosses. +pub struct abi_value { + var parts: abi_class[2]; #! The class of each eightbyte. + var count: u64; #! Eightbytes, or 0 for `void`. + var memory: bool; #! Whether it is passed on the stack, or returned through memory. + var reference: bool; #! Whether it is a `&T`, of which C is given the address alone. +} + +#! Where an argument is placed. +pub struct abi_place { + var value: abi_value; + var registers: u8[2]; #! The register of each eightbyte, numbered within its class. + var stacked: bool; #! Whether it is on the stack. + var word: u64; #! The word of the stack it begins at, where it is. +} + +#! How a call passes each argument and takes back its result. +pub struct abi_call { + var args: vector; + var result: abi_value; + var integers: u64; #! Integer registers taken, the address of a result in memory included. + var floats: u64; #! SSE registers taken. + var words: u64; #! Words of the stack taken. +} + +#! Marks the class of what lies at an offset in its eightbyte: one holding +#! anything of an integer's class is passed as an integer. +#! @param parts The classes. +#! @param offset The offset. +#! @param class The class of what lies there. +def mark_part(parts: &mut abi_class[2], offset: u64, class: abi_class): void { + val index := offset / 8; + return if index >= 2; + parts[index] = parts[index] == abi_class::integer || class == abi_class::integer ? abi_class::integer : abi_class::sse; +} + +#! Marks the classes of what a layout holds, from an offset. +#! @param program The program. +#! @param index The layout. +#! @param offset Where it begins. +#! @param parts The classes. +#! @param depth How deeply structs nest so far. +def mark_leaves(program: &program, index: u32, offset: u64, parts: &mut abi_class[2], depth: u32): void { + return if depth > 64; + val shape: layout = program.layouts[index]; + match shape.kind { + lk::floating => mark_part(parts, offset, abi_class::sse); + lk::fixed => { + val element := shape.element - 1; + val size: u64 = program.layouts[element].size; + for i in 0..shape.count { + mark_leaves(program, element, offset + i as u64 * size, parts, depth + 1); + } + } + lk::record => { + for f in 0..shape.count { + val field: slot_field = program.fields[shape.fields as u64 + f as u64]; + mark_leaves(program, field.layout, offset + field.offset, parts, depth + 1); + } + } + else => mark_part(parts, offset, abi_class::integer); + } +} + +#! How a value of a layout crosses. +#! @param program The program. +#! @param index The layout. +#! @returns How. +pub def abi_classify(program: &program, index: u32): abi_value { + val shape: layout = program.layouts[index]; + var value := abi_value {}; + match shape.kind { + lk::empty => return value; + lk::signed, lk::unsigned, lk::boolean, lk::pointer => { + value.parts[0] = abi_class::integer; + value.count = 1; + return value; + } + lk::floating => { + value.parts[0] = abi_class::sse; + value.count = 1; + return value; + } + lk::reference => { + value.parts[0] = abi_class::integer; + value.count = 1; + value.reference = true; + return value; + } + else => {} + } + # A struct or an array is in memory where larger than two eightbytes, and + # else in an eightbyte of the class of what it holds there. + value.count = (shape.size + 7) / 8; + value.memory = shape.size > 16; + return value if value.memory; + mark_leaves(program, index, 0, &mut value.parts, 0); + for i in 0..value.count { + if value.parts[i] == abi_class::none { + value.parts[i] = abi_class::sse; + } + } + return value; +} + +#! Places the arguments of a call by a signature. +#! @param program The program. +#! @param signature The signature. +#! @returns How the call passes them. +pub def abi_place_call(program: &program, signature: u32): abi_call { + val held := &program.signatures[signature]; + var call := abi_call { args = vector::::new(scratch()) }; + call.result = abi_classify(program, held.result); + call.integers = call.result.memory ? 1 : 0; + for &each in held.params { + var place := abi_place { value = abi_classify(program, each) }; + var integers: u64 = 0; + var floats: u64 = 0; + if !place.value.memory { + for k in 0..place.value.count { + if place.value.parts[k] == abi_class::integer { + integers++; + } else { + floats++; + } + } + } + # A value is passed in registers only where all of its eightbytes fit. + if !place.value.memory && call.integers + integers <= 6 && call.floats + floats <= 8 { + for k in 0..place.value.count { + if place.value.parts[k] == abi_class::integer { + place.registers[k] = call.integers as u8; + call.integers++; + } else { + place.registers[k] = call.floats as u8; + call.floats++; + } + } + } else { + place.stacked = true; + place.word = call.words; + call.words += place.value.count; + } + call.args.append(place); + } + return call; +} + +#! How many words a frame takes for a value of a layout passed to a function +#! of the program: the address of one held in memory, or its words. +#! @param program The program. +#! @param index The layout. +#! @returns How many. +def frame_words(program: &program, index: u32): u64 { + val shape: layout = program.layouts[index]; + return argument_words(&shape); +} + + +# Calls of C. + +#! Loads an eightbyte of an argument into `rax`, as C is given it: the word a +#! frame holds, narrowed from a double where it is an `f32`, or the eightbyte +#! of what is held in memory at the address the word is, read through `r10` +#! without reading past it. +#! @param this The selector. +#! @param index The argument's layout. +#! @param operand Where the argument's word was kept on the stack. +#! @param e The eightbyte. +def selector::c_eightbyte(&mut this, index: u32, operand: mem, e: u64): void { + val shape: layout = this.b.c.program.layouts[index]; + if !in_memory(&shape) { + this.b.text.load(8, false, reg::rax, operand); + # Converted in a register C takes no argument in. + if shape.kind == lk::floating && shape.size == 4 { + this.b.text.movq_to_xmm(15, reg::rax); + this.b.text.cvtsd2ss(15, 15); + this.b.text.movq_from_xmm(reg::rax, 15); + } + return; + } + this.b.text.load(8, false, reg::r10, operand); + val left := shape.size - 8 * e; + load_bytes(&mut this.b.text, reg::rax, at(reg::r10, (8 * e) as i32), left < 8 ? left : 8, reg::r11); +} + +#! Loads up to eight bytes into a register, as many as there are, without +#! reading past them, the bytes past them zero. +#! @param text The code. +#! @param into The register. +#! @param from The memory. +#! @param count How many bytes. +#! @param temp A register to put the pieces together in. +def load_bytes(text: &mut assembly, into: reg, from: mem, count: u64, temp: reg): void { + if count >= 8 { + text.load(8, false, into, from); + return; + } + text.mov_imm(into, 0); + var done: u64 = 0; + while done < count { + val left := count - done; + val width: u64 = left >= 4 ? 4 : left >= 2 ? 2 : 1; + text.load(width, false, temp, offset_by(from, done)); + if done != 0 { + text.shift_imm(shift::shl, temp, (8 * done) as u8); + } + text.alu(alu::bor, into, temp); + done += width; + } +} + +#! Stores up to eight bytes of a register to memory, as many as the value +#! there holds, without writing past them; the register is shifted away. +#! @param text The code. +#! @param to The memory. +#! @param from The register. +#! @param count How many bytes. +def store_bytes(text: &mut assembly, to: mem, from: reg, count: u64): void { + if count >= 8 { + text.store(8, to, from); + return; + } + var done: u64 = 0; + while done < count { + val left := count - done; + val width: u64 = left >= 4 ? 4 : left >= 2 ? 2 : 1; + text.store(width, offset_by(to, done), from); + if done + width < count { + text.shift_imm(shift::shr, from, (8 * width) as u8); + } + done += width; + } +} + +#! Widens a scalar C gave in `rax` as a frame holds it: an integer extended +#! from its bits, which C leaves unspecified past them, and an `f32` widened to +#! a double. +#! @param text The code. +#! @param program The program. +#! @param index The layout. +def widen_c(text: &mut assembly, program: &program, index: u32): void { + val shape: layout = program.layouts[index]; + if shape.kind == lk::floating { + if shape.size == 4 { + text.movq_to_xmm(0, reg::rax); + text.cvtss2sd(0, 0); + text.movq_from_xmm(reg::rax, 0); + } + return; + } + if shape.kind == lk::boolean { + text.extend(1, false, reg::rax, reg::rax); + return; + } + return if shape.size >= 8 || shape.kind == lk::pointer || shape.kind == lk::reference; + text.extend(shape.size, shape.kind == lk::signed, reg::rax, reg::rax); +} + +#! The code of a call of a C function through its address. Every operand is +#! first written to the stack, so placing the arguments in C's registers +#! overwrites none still to be read; then the arguments C takes on the stack +#! and in SSE registers are placed, and those it takes in integer registers +#! last, each read through `r10` and `r11`, which C takes none in. +#! @param this The selector. +#! @param index The call. +#! @param held The call. +def selector::call_c(&mut this, index: u32, held: &inst): void { + if this.b.options.windows { + this.call_microsoft(index, held); + return; + } + val program := &this.b.c.program; + val call := abi_place_call(program, held.aux); + val signature := &program.signatures[held.aux]; + val result_shape: layout = program.layouts[signature.result]; + + # The operands, at the stack's bottom past the words C takes there. + val operands := held.argc as u64; + val stack_words := call.words; + val kept := 8 * stack_words; + val area := round_up(8 * (stack_words + operands), 16); + this.b.text.alu_imm(alu::sub, reg::rsp, area as i32); + for a in 0..operands { + val from := this.read(this.body.arg(index, a as u32), index); + this.move_one(&transfer { from = from, to = loc { kind = place::out, value = (stack_words + a) as u32 } }); + } + + for pass in 0..2u { + var k: u64 = 1; + for i in 0..call.args.length { + val placed: abi_place = call.args[i]; + val param: u32 = signature.params[i]; + val operand := at(reg::rsp, (kept + 8 * k) as i32); + for e in 0..placed.value.count { + val integer := !placed.stacked && placed.value.parts[e] == abi_class::integer; + continue if integer != (pass == 1); + this.c_eightbyte(param, operand, e); + if placed.stacked { + this.b.text.store(8, at(reg::rsp, (8 * (placed.word + e)) as i32), reg::rax); + } else if integer { + this.b.text.mov(c_integers[placed.registers[e] as u64], reg::rax); + } else { + this.b.text.movq_to_xmm(placed.registers[e], reg::rax); + } + } + k += frame_words(program, param); + } + } + + this.c_function(kept, index); + val returned := this.mark_c_call(); + val last := kept + 8 * (operands - 1); + if call.result.memory { + this.b.text.load(8, false, reg::rdi, at(reg::rsp, last as i32)); + } + this.b.text.mov_imm(reg::rax, call.floats); + this.call_c_function(&call, returned, &result_shape, last); + this.b.text.alu_imm(alu::add, reg::rsp, area as i32); + this.take_c_result(&call, held); +} + +#! Loads the C function a call calls into `r11`, from its first operand, with a +#! trap where it is null. +#! @param this The selector. +#! @param first Where the first operand is above `rsp`. +#! @param index The call. +def selector::c_function(&mut this, first: u64, index: u32): void { + this.b.text.load(8, false, reg::r11, at(reg::rsp, first as i32)); + this.b.text.test(reg::r11, reg::r11); + this.trap_if(cc::equal, fault::null_reference as u32, index); +} + +#! Marks where the program calls C, for a function C calls back to find, to +#! walk a trace back through: the frame, and the address the call returns to, +#! which `call_c_function` writes once the call is. +#! @param this The selector. +#! @returns Where the address the call returns to is in the text. +def selector::mark_c_call(&mut this): u64 { + val c_frame := this.b.own_word(state_c_frame); + this.b.text.store(8, c_frame, reg::rbp); + this.b.text.rex(true, 0, reg::none, reg::rax, false); + this.b.text.byte(0xB8); + val returned := this.b.text.length; + this.addresses.append(returned); + this.b.text.u64(0); + val c_return := this.b.own_word(state_c_return); + this.b.text.store(8, c_return, reg::rax); + return returned; +} + +#! Calls the C function in `r11`, where `mark_c_call` marked the call, after +#! which the program is no longer calling C. A result held in memory C gives in +#! registers is written where the call asked, whose address its last operand +#! kept; one C writes itself is there already. +#! @param this The selector. +#! @param call How the call passes its arguments and takes its result. +#! @param returned Where the address the call returns to is in the text. +#! @param result_shape The result's layout. +#! @param last Where the last operand is above `rsp`. +def selector::call_c_function(&mut this, call: &abi_call, returned: u64, result_shape: &layout, last: u64): void { + this.b.text.call_reg(reg::r11); + this.b.text.set_u64(returned, this.b.text_base + this.b.text.length); + val c_frame_clear := this.b.own_word(state_c_frame); + this.b.text.store_imm(c_frame_clear, 0); + return if !returned_in_memory(result_shape) || call.result.memory; + + this.b.text.load(8, false, reg::r10, at(reg::rsp, last as i32)); + var integers: u64 = 0; + var floats: u64 = 0; + for e in 0..call.result.count { + val left := result_shape.size - 8 * e; + var from := reg::r11; + if call.result.parts[e] == abi_class::sse { + this.b.text.movq_from_xmm(reg::r11, floats as u8); + floats++; + } else { + from = integers == 0 ? reg::rax : reg::rdx; + integers++; + } + store_bytes(&mut this.b.text, at(reg::r10, (8 * e) as i32), from, left < 8 ? left : 8); + } +} + +#! Takes a scalar result C gave in `rax` or `xmm0` as the frame holds it, once +#! the stack is as it was before the call. +#! @param this The selector. +#! @param call How the call passes its arguments and takes its result. +#! @param held The call. +def selector::take_c_result(&mut this, call: &abi_call, held: &inst): void { + val program := &this.b.c.program; + val result: u32 = program.signatures[held.aux].result; + val result_shape: layout = program.layouts[result]; + return if returned_in_memory(&result_shape) || call.result.count == 0; + if call.result.parts[0] == abi_class::sse { + this.b.text.movq_from_xmm(reg::rax, 0); + } + widen_c(&mut this.b.text, program, result); + this.results(held); +} + + +# Functions C calls. + +#! How C passes arguments and what it keeps, as far as the code C calls a +#! function of the program through differs by the ABI: System V's, or +#! Microsoft's on Windows. +struct c_convention { + var microsoft: bool; #! Whether it is Microsoft's ABI. + var kept: reg[7]; #! The registers C keeps that the program does not, in the order they are pushed. + var keeps: u64; #! How many of them there are. + var integers: u64; #! How many integer registers C passes arguments in. + var floats: u64; #! How many SSE registers C passes arguments in. + var home: u64; #! The bytes a caller leaves past the address C returns to, before the arguments on the stack. +} + +#! The convention C calls by on a target. +#! @param windows Whether the target is Windows. +#! @returns The convention. +def c_convention_of(windows: bool): c_convention { + if windows { + return c_convention { + microsoft = true, + kept = [reg::rbx, reg::rsi, reg::rdi, reg::r12, reg::r13, reg::r14, reg::r15], + keeps = 7, + integers = 4, + floats = 4, + home = 32 + }; + } + return c_convention { + microsoft = false, + kept = [reg::rbx, reg::r12, reg::r13, reg::r14, reg::r15, reg::none, reg::none], + keeps = 5, + integers = 6, + floats = 8, + home = 0 + }; +} + +#! Places the arguments of a call by a signature as the convention does. +#! @param this The convention. +#! @param program The program. +#! @param signature The signature. +#! @returns How the call passes them. +def c_convention::place(&this, program: &program, signature: u32): abi_call { + if this.microsoft { + return abi_place_microsoft(program, signature); + } + return abi_place_call(program, signature); +} + +#! Writes the code C calls a function of the program through: it keeps what C +#! keeps, `rsi` and `rdi` among them on Windows, takes each argument as the +#! program passes it, and makes a frame that leads back to where the program +#! called C, so a trace walks through the program alone. A function C calls +#! while the program is not calling C stops it. On Windows, a function C calls +#! on a thread the program never started has no record, and is reported as the +#! machine reports it. +#! @param this The building. +#! @param function The function. +#! @returns Where the code is in the text. +pub def building::callback_entry(&mut this, function: u32): u64 { + val conv := c_convention_of(this.options.windows); + val program := &this.c.program; + val signature_index: u32 = program.functions[function].signature; + val call := conv.place(program, signature_index); + val signature := &program.signatures[signature_index]; + val result_shape: layout = program.layouts[signature.result]; + val memory := returned_in_memory(&result_shape); + + # The frame, from the stack's bottom: the words passed on the stack, C's + # registers, the state kept, the frame made for traces, a buffer for each + # parameter held in memory C passed in registers, and one for the result. + var words: u64 = 0; + for &each in signature.params { + words += frame_words(program, each); + } + val out := words > arg_count ? words - arg_count : 0; + val saved := 8 * out; + val state := saved + 8 * (conv.integers + conv.floats); + val fake := state + 16; + val buffers := fake + 16; + val result_buffer := buffers + 16 * signature.params.length; + val size := round_up(result_buffer + 16 + 8, 16) - 8; + + val start := this.text.length; + this.text.push(reg::rbp); + this.text.mov(reg::rbp, reg::rsp); + for k in 0..conv.keeps { + this.text.push(conv.kept[k]); + } + this.text.alu_imm(alu::sub, reg::rsp, size as i32); + if conv.microsoft { + # C's rcx, rdx, r8, r9, then xmm0 to xmm3. + for k in 0..4u { + this.text.store(8, at(reg::rsp, (saved + 8 * k) as i32), micro_positions[k]); + this.text.movsd_store(at(reg::rsp, (saved + 32 + 8 * k) as i32), k as u8); + } + + # A thread the program never started has no record, so it cannot be run. + this.own_record(reg::rax); + this.text.test(reg::rax, reg::rax); + this.text.patch(this.text.jcc(cc::equal), this.stranger); + } else { + for k in 0..6u { + this.text.store(8, at(reg::rsp, (saved + 8 * k) as i32), c_integers[k]); + } + for k in 0..8u { + this.text.movsd_store(at(reg::rsp, (saved + 48 + 8 * k) as i32), k as u8); + } + } + + # C calls it only while the program is calling C. + val got_frame := this.own_word(state_c_frame); + this.text.load(8, false, reg::rax, got_frame); + this.text.test(reg::rax, reg::rax); + val calling := this.text.jcc(cc::not_equal); + this.text.mov_imm(reg::rbp, 0); + this.text.mov_imm(reg::rdi, 23); + this.text.patch(this.text.call(), this.trap_stub); + this.text.land(calling); + this.text.store(8, at(reg::rsp, state as i32), reg::rax); + this.text.store(8, at(reg::rsp, fake as i32), reg::rax); + val got_return := this.own_word(state_c_return); + this.text.load(8, false, reg::rax, got_return); + this.text.store(8, at(reg::rsp, (state + 8) as i32), reg::rax); + this.text.store(8, at(reg::rsp, (fake + 8) as i32), reg::rax); + + # Each argument, as the program passes it: an aggregate as the address of its + # bytes, and a scalar widened as a frame holds it. System V passes the bytes + # of an aggregate on the stack or in registers, copied to a buffer; Microsoft's + # ABI passes a large aggregate as the pointer C gave, and a small one's bytes, + # copied to a buffer. + var k: u64 = 0; + for i in 0..call.args.length { + val placed: abi_place = call.args[i]; + val param: u32 = signature.params[i]; + val shape: layout = program.layouts[param]; + if in_memory(&shape) { + val buffer := buffers + 16 * i; + if conv.microsoft { + this.c_part(&conv, &placed, 0, saved, reg::rax); + if !placed.value.memory { + store_bytes(&mut this.text, at(reg::rsp, buffer as i32), reg::rax, shape.size); + this.text.lea(reg::rax, at(reg::rsp, buffer as i32)); + } + } else if placed.stacked { + this.text.lea(reg::rax, at(reg::rbp, (16 + 8 * placed.word) as i32)); + } else { + for e in 0..placed.value.count { + this.c_part(&conv, &placed, e, saved, reg::rax); + this.text.store(8, at(reg::rsp, (buffer + 8 * e) as i32), reg::rax); + } + this.text.lea(reg::rax, at(reg::rsp, buffer as i32)); + } + this.pass_word(k, reg::rax); + k++; + continue; + } + this.c_part(&conv, &placed, 0, saved, reg::rax); + if placed.value.reference { + this.pass_word(k, reg::rax); + k++; + continue; + } + widen_c(&mut this.text, program, param); + this.pass_word(k, reg::rax); + k += frame_words(program, param); + } + if memory { + if call.result.memory { + this.text.load(8, false, reg::rdx, at(reg::rsp, saved as i32)); + } else { + this.text.lea(reg::rdx, at(reg::rsp, result_buffer as i32)); + } + } + this.text.lea(reg::rbp, at(reg::rsp, fake as i32)); + this.call_to(function); + + # The result, as C takes it: the pointer back for one it wrote itself, the + # eightbytes of one held in memory it takes in registers, or a scalar, a float + # in `xmm0`. + if memory && call.result.memory { + this.text.load(8, false, reg::rax, at(reg::rsp, saved as i32)); + } else if memory { + var integers: u64 = 0; + var floats: u64 = 0; + for e in 0..call.result.count { + val left := result_shape.size - 8 * e; + val from := at(reg::rsp, (result_buffer + 8 * e) as i32); + if call.result.parts[e] == abi_class::sse { + load_bytes(&mut this.text, reg::r11, from, left < 8 ? left : 8, reg::r10); + this.text.movq_to_xmm(floats as u8, reg::r11); + floats++; + } else { + load_bytes(&mut this.text, integers == 0 ? reg::rax : reg::rdx, from, left < 8 ? left : 8, reg::r10); + integers++; + } + } + } else if call.result.count != 0 && call.result.parts[0] == abi_class::sse { + this.text.movq_to_xmm(0, reg::rax); + if result_shape.size == 4 { + this.text.cvtsd2ss(0, 0); + } + } + + # What the program was calling C with is as it was, for the program, or + # another function C calls. + this.text.load(8, false, reg::rcx, at(reg::rsp, state as i32)); + val back_frame := this.own_word(state_c_frame); + this.text.store(8, back_frame, reg::rcx); + this.text.load(8, false, reg::rcx, at(reg::rsp, (state + 8) as i32)); + val back_return := this.own_word(state_c_return); + this.text.store(8, back_return, reg::rcx); + this.text.alu_imm(alu::add, reg::rsp, size as i32); + for j in 0..conv.keeps { + this.text.pop(conv.kept[conv.keeps - 1 - j]); + } + this.text.pop(reg::rbp); + this.text.ret(); + return start; +} + +#! Loads an eightbyte C gave of an argument into a register: from the +#! registers kept, or the stack C passed it on, past the caller's home area. +#! @param this The building. +#! @param conv The convention C called by. +#! @param placed Where C placed it. +#! @param e The eightbyte. +#! @param saved Where C's registers were kept. +#! @param into The register. +def building::c_part(&mut this, conv: &c_convention, placed: &abi_place, e: u64, saved: u64, into: reg): void { + if placed.stacked { + this.text.load(8, false, into, at(reg::rbp, (16 + conv.home + 8 * (placed.word + e)) as i32)); + return; + } + val number := placed.registers[e] as u64; + val offset := placed.value.parts[e] == abi_class::sse ? saved + 8 * conv.integers + 8 * number : saved + 8 * number; + this.text.load(8, false, into, at(reg::rsp, offset as i32)); +} + +#! Passes a word as the program passes a call's words: in a register, or on +#! the stack's bottom. +#! @param this The building. +#! @param k The word. +#! @param from The register holding it. +def building::pass_word(&mut this, k: u64, from: reg): void { + if k < arg_count { + this.text.mov(gprs[k], from); + return; + } + this.text.store(8, at(reg::rsp, (8 * (k - arg_count)) as i32), from); +} + + +# Calls of C with Microsoft's ABI, on Windows. + +#! The registers C takes the first four arguments in on Windows, by position. +pub const micro_positions: reg[4] = [reg::rcx, reg::rdx, reg::r8, reg::r9]; + +#! How a value of a layout crosses to C on Windows, where each value is one +#! eightbyte: a scalar, a reference, or `void` as the System V ABI has it, an +#! aggregate of 1, 2, 4, or 8 bytes as an integer, and any other aggregate as +#! the address of a copy, which the loader of the call makes. +#! @param program The program. +#! @param index The layout. +#! @returns How. +pub def abi_microsoft(program: &program, index: u32): abi_value { + val shape: layout = program.layouts[index]; + if !in_memory(&shape) { + return abi_classify(program, index); + } + var value := abi_value {}; + return value if shape.size == 0; + value.parts[0] = abi_class::integer; + value.count = 1; + value.memory = !micro_by_value(shape.size); + return value; +} + +#! Places the arguments of a call by a signature as Microsoft's ABI does: each +#! takes a position, the first four in registers and the rest on the stack, and +#! a result in memory takes the first position for its address. +#! @param program The program. +#! @param signature The signature. +#! @returns How the call passes them. +pub def abi_place_microsoft(program: &program, signature: u32): abi_call { + val held := &program.signatures[signature]; + var call := abi_call { args = vector::::new(scratch()) }; + call.result = abi_microsoft(program, held.result); + call.integers = call.result.memory ? 1 : 0; + var position := call.integers; + for &each in held.params { + var place := abi_place { value = abi_microsoft(program, each) }; + if position < 4 { + place.registers[0] = position as u8; + if place.value.parts[0] == abi_class::sse { + call.floats++; + } else { + call.integers++; + } + } else { + place.stacked = true; + place.word = call.words; + call.words++; + } + position++; + call.args.append(place); + } + return call; +} + +#! Copies an aggregate C is given by reference into a copy below the stack, +#! from the address in `r10`. +#! @param this The selector. +#! @param at Where the copy is, below `rsp`. +#! @param size How many bytes. +def selector::copy_aggregate(&mut this, below: u64, size: u64): void { + this.b.text.mov(reg::rsi, reg::r10); + this.b.text.lea(reg::rdi, at(reg::rsp, below as i32)); + this.b.text.mov_imm(reg::rcx, size); + this.b.text.rep_movsb(); +} + +#! Loads the eightbyte of an argument C is given into a register: a scalar's +#! word, narrowed from a double where it is an `f32`, or the bytes of a small +#! aggregate, read from the address an operand holds. +#! @param this The selector. +#! @param param The argument's layout. +#! @param operand Where the operand's word is below `rsp`. +#! @param into The register, which no scratch of this is. +def selector::micro_eightbyte(&mut this, param: u32, operand: u64, into: reg): void { + val shape: layout = this.b.c.program.layouts[param]; + if in_memory(&shape) { + this.b.text.load(8, false, reg::r10, at(reg::rsp, operand as i32)); + load_bytes(&mut this.b.text, into, at(reg::r10, 0), shape.size, reg::r11); + return; + } + this.b.text.load(8, false, into, at(reg::rsp, operand as i32)); + if shape.kind == lk::floating && shape.size == 4 { + this.b.text.movq_to_xmm(5, into); + this.b.text.cvtsd2ss(5, 5); + this.b.text.movq_from_xmm(into, 5); + } +} + +#! The code of a call of a C function on Windows, with Microsoft's ABI. Every +#! operand is first written to a scratch below the stack, so placing the +#! arguments in C's registers overwrites none still to be read; then the +#! aggregates C is given by reference are copied, and the arguments placed on +#! the stack and in registers, each one eightbyte. `rsp` is kept in the +#! frame's scratch around it. +#! @param this The selector. +#! @param index The call. +#! @param held The call. +def selector::call_microsoft(&mut this, index: u32, held: &inst): void { + val program := &this.b.c.program; + val call := abi_place_microsoft(program, held.aux); + val signature := &program.signatures[held.aux]; + val result_shape: layout = program.layouts[signature.result]; + + # The home area and the stacked words at the bottom, then a copy of each + # aggregate passed by reference, then the operands, one word each. + val operands := held.argc as u64; + val base_area := round_up(32 + 8 * call.words, 16); + var copy_at := vector::::new(scratch()); + copy_at.resize(call.args.length); + var copies: u64 = 0; + for i in 0..call.args.length { + continue if !call.args[i].value.memory; + copy_at[i] = base_area + copies; + copies += round_up(program.layouts[signature.params[i]].size, 16); + } + val operand_base := base_area + copies; + val area := round_up(operand_base + 8 * operands, 16); + + this.b.text.store(8, this.scratch_word(0), reg::rsp); + this.b.text.alu_imm(alu::band, reg::rsp, -16); + this.b.descend(area); + for a in 0..operands { + val from := this.read(this.body.arg(index, a as u32), index); + this.move_one(&transfer { from = from, to = loc { kind = place::out, value = (operand_base / 8 + a) as u32 } }); + } + + # The function, the first operand, and a trap where it is null. + this.c_function(operand_base, index); + val returned := this.mark_c_call(); + + # Copies of aggregates passed by reference, from the address each operand holds. + var k: u64 = 1; + for i in 0..call.args.length { + val param: u32 = signature.params[i]; + if call.args[i].value.memory { + this.b.text.load(8, false, reg::r10, at(reg::rsp, (operand_base + 8 * k) as i32)); + this.copy_aggregate(copy_at[i], program.layouts[param].size); + } + k += frame_words(program, param); + } + + # The words of the stack, then floats, then integers, so `rax`, which each + # word passes through, is never an argument's register. + k = 1; + for i in 0..call.args.length { + val placed: abi_place = call.args[i]; + val param: u32 = signature.params[i]; + if placed.stacked { + if placed.value.memory { + this.b.text.lea(reg::rax, at(reg::rsp, copy_at[i] as i32)); + } else { + this.micro_eightbyte(param, operand_base + 8 * k, reg::rax); + } + this.b.text.store(8, at(reg::rsp, (32 + 8 * placed.word) as i32), reg::rax); + } + k += frame_words(program, param); + } + k = 1; + for i in 0..call.args.length { + val placed: abi_place = call.args[i]; + val param: u32 = signature.params[i]; + if !placed.stacked && placed.value.parts[0] == abi_class::sse { + this.micro_eightbyte(param, operand_base + 8 * k, reg::rax); + this.b.text.movq_to_xmm(placed.registers[0], reg::rax); + this.b.text.mov(micro_positions[placed.registers[0] as u64], reg::rax); + } + k += frame_words(program, param); + } + k = 1; + for i in 0..call.args.length { + val placed: abi_place = call.args[i]; + val param: u32 = signature.params[i]; + if !placed.stacked && placed.value.parts[0] != abi_class::sse { + val reg := micro_positions[placed.registers[0] as u64]; + if placed.value.memory { + this.b.text.lea(reg, at(reg::rsp, copy_at[i] as i32)); + } else { + this.micro_eightbyte(param, operand_base + 8 * k, reg); + } + } + k += frame_words(program, param); + } + + # The hidden result pointer, where C writes a result in memory itself. A small + # aggregate result C gives in `rax` is written where the call asked. + val last := operand_base + 8 * (operands - 1); + if call.result.memory { + this.b.text.load(8, false, reg::rcx, at(reg::rsp, last as i32)); + } + this.b.text.load(8, false, reg::r11, at(reg::rsp, operand_base as i32)); + this.call_c_function(&call, returned, &result_shape, last); + this.b.text.load(8, false, reg::rsp, this.scratch_word(0)); + this.take_c_result(&call, held); +} diff --git a/native/atomics.sakura b/native/atomics.sakura new file mode 100644 index 00000000..adf02cf7 --- /dev/null +++ b/native/atomics.sakura @@ -0,0 +1,188 @@ +#! @file atomics.sakura +#! @author John Christman (sorakatadzuma@gmail.com) +#! @copyright Malunal Studios, LLC. +#! @license MIT +#! +#! Contains the code of atomics on x86-64, whose ordinary reads and writes are +#! already ordered as `acquire` and `release` ask. So a load is a `mov` at every +#! order, a store a `mov` but of `seq_cst`, which is an `xchg`, and a fence is +#! an `mfence` of `seq_cst` and nothing otherwise. An exchange is an `xchg`, +#! which locks by itself, a compare-exchange a `lock cmpxchg`, adding and +#! subtracting a `lock xadd`, and the rest a loop of `lock cmpxchg`, every one of +#! which orders as `seq_cst` does. An order not known while compiling is tested +#! where it matters, which costs a compare. +#! +#! They work in `rax`, `rcx`, and `rdx`, which hold no value between +#! instructions: `rdx` holds an address in none of its own, `rax` what the +#! memory held, as `cmpxchg` has it, and `rcx` what is written. + +import sakura::compiler; +import binary::amd64; +module sakura::native; + + +#! `atomic`: an operation on the integer at an address, or a fence, in one step. +#! @param this The selector. +#! @param index The instruction. +#! @param held The instruction. +def selector::atomic(&mut this, index: u32, held: &inst): void { + val operation := held.aux; + val order := this.body.arg(index, held.argc - 1); + if operation == atomic_fence { + val skip := this.unless_seq_cst(order, index); + if skip != never_patched { + this.b.text.mfence(); + this.end_unless(skip); + } + return; + } + + val how := atomic_access(held.imm); + val width := how.width(); + val sign := how == access::i8 || how == access::i16 || how == access::i32; + var direct := false; + val at := this.address(this.body.arg(index, 0), index, 0, reg::rdx, reg::rcx, &mut direct); + if !direct { + this.null_check(at.base, width, index); + } + val result := held.result; + + if operation == atomic_load { + val into := this.target(result, reg::rax); + this.b.text.load(width, sign, into, at); + this.put(result, into); + return; + } + if operation == atomic_store { + val value := this.word_reg(this.body.arg(index, 1), index, reg::rcx); + var bits: u64 = 0; + val known := this.constant_bits(order, &mut bits); + if known && bits != order_seq_cst { + this.b.text.store(width, at, value); + return; + } + var plain: u64 = never_patched; + if !known { + this.load_into(order, index, reg::rax); + this.b.text.alu_imm(alu::cmp, reg::rax, order_seq_cst as i32); + plain = this.b.text.jcc(cc::not_equal); + } + # `xchg` writes what the memory held into the register, which may hold the + # value past here. + if value != reg::rcx { + this.b.text.mov(reg::rcx, value); + } + this.b.text.xchg(width, at, reg::rcx); + if !known { + val done := this.b.text.jmp(); + this.b.text.land(plain); + this.b.text.store(width, at, value); + this.b.text.land(done); + } + return; + } + if operation == atomic_exchange || operation == atomic_add || operation == atomic_sub { + this.load_into(this.body.arg(index, 1), index, reg::rax); + if operation == atomic_exchange { + this.b.text.xchg(width, at, reg::rax); + } else { + if operation == atomic_sub { + this.b.text.unary(unary::neg, reg::rax); + } + this.b.text.lock_xadd(width, at, reg::rax); + } + this.b.text.extend(width, sign, reg::rax, reg::rax); + this.put(result, reg::rax); + return; + } + if operation == atomic_compare_exchange { + this.load_into(this.body.arg(index, 1), index, reg::rax); + val desired := this.word_reg(this.body.arg(index, 2), index, reg::rcx); + this.b.text.lock_cmpxchg(width, at, desired); + this.b.text.extend(width, sign, reg::rax, reg::rax); + this.put(result, reg::rax); + return; + } + this.combine(index, held, at, width, sign); +} + +#! The operations combining what the memory holds with an operand, as a loop +#! working out what to write from what it held, and writing it where nothing +#! wrote it since. A `cmpxchg` failing loads only the bytes it compares into +#! `rax`, so what it holds is widened again before the next turn. +#! @param this The selector. +#! @param index The instruction. +#! @param held The instruction. +#! @param at The memory. +#! @param width The bytes of the integer. +#! @param sign Whether it is widened by its sign. +def selector::combine(&mut this, index: u32, held: &inst, at: mem, width: u64, sign: bool): void { + val operation := held.aux; + # The operand stays where it is, or where it is in no register of its own, in + # the scratch of the frame, so `rcx` is free. + var operand := this.word_operand(this.body.arg(index, 1), index, reg::rcx); + val extreme := operation == atomic_min || operation == atomic_max; + if (operand.kind == 0 && operand.r == reg::rcx) || (operand.kind == 2 && extreme) { + if operand.kind == 2 { + this.b.text.mov_imm(reg::rcx, operand.imm as i64 as u64); + } + this.b.text.store(8, this.scratch_word(0), reg::rcx); + operand = operand_of { kind = 1, m = this.scratch_word(0) }; + } + + this.b.text.load(width, sign, reg::rax, at); + val top := this.b.text.length; + if extreme { + if operand.kind == 0 { + this.b.text.mov(reg::rcx, operand.r); + } else { + this.b.text.load(8, false, reg::rcx, operand.m); + } + this.b.text.extend(width, sign, reg::rcx, reg::rcx); + this.b.text.alu(alu::cmp, reg::rax, reg::rcx); + val signed := atomic_signed(held.imm); + val keeps := operation == atomic_min ? (signed ? cc::less : cc::below) : (signed ? cc::greater : cc::above); + this.b.text.cmov(keeps, reg::rcx, reg::rax); + } else { + this.b.text.mov(reg::rcx, reg::rax); + val kind := operation == atomic_and ? alu::band : operation == atomic_or ? alu::bor : alu::bxor; + this.apply(kind, reg::rcx, &operand); + } + this.b.text.lock_cmpxchg(width, at, reg::rcx); + val done := this.b.text.jcc(cc::equal); + this.b.text.extend(width, sign, reg::rax, reg::rax); + val again := this.b.text.jmp(); + this.b.text.patch(again, top); + this.b.text.land(done); + this.put(held.result, reg::rax); +} + +#! What stands for no jump to patch. +const never_patched: u64 = 0xFFFFFFFFFFFFFFFF; + +#! Begins code working only where an order is `seq_cst`: where it is known +#! while compiling to be another, none; where it is known to be `seq_cst`, all of +#! it, with nothing to skip; and otherwise a test of it, jumping past the code. +#! @param this The selector. +#! @param order The order. +#! @param index The instruction. +#! @returns The jump past it to patch, 0 where there is none, or +#! `never_patched` where the code is not written at all. +def selector::unless_seq_cst(&mut this, order: u32, index: u32): u64 { + var bits: u64 = 0; + if this.constant_bits(order, &mut bits) { + return bits == order_seq_cst ? 0 : never_patched; + } + this.load_into(order, index, reg::rax); + this.b.text.alu_imm(alu::cmp, reg::rax, order_seq_cst as i32); + return this.b.text.jcc(cc::not_equal); +} + +#! Ends code `unless_seq_cst` began. +#! @param this The selector. +#! @param skip The jump it gave. +def selector::end_unless(&mut this, skip: u64): void { + if skip != 0 { + this.b.text.land(skip); + } +} diff --git a/native/calls.sakura b/native/calls.sakura new file mode 100644 index 00000000..f6cab9ba --- /dev/null +++ b/native/calls.sakura @@ -0,0 +1,1192 @@ +#! @file calls.sakura +#! @author John Christman (sorakatadzuma@gmail.com) +#! @copyright Malunal Studios, LLC. +#! @license MIT +#! +#! Contains the code of calls, of the operations the runtime's helpers do, and +#! of the ends of blocks, and selects the code of a whole function: its +#! prologue, its blocks in the order the register allocator laid them out, and +#! the stubs reporting the checks that fail. +#! +#! A call passes the first words of its arguments in the registers `gprs` +#! names, `arg_count` of them, in order, and the rest on the stack, the first +#! at the bottom of the caller's frame; a parameter held in memory is passed as +#! the address of the caller's copy, and the function called copies it. A +#! function returning memory is given the address to write it to in `rdx`. +#! Words come back in `rax`, `rdx`, and `rcx`. A call keeps `rbx` and `r12` to +#! `r15`, which a function saves as it begins where it uses them, and gives +#! back before it returns. A call through a vtable passes the vtable as the +#! third word, which a method taking a plain reference never sees, since its +#! vtable's slot names code moving the words after it down one. + +import sakura::compiler; +import binary::amd64; +module sakura::native; + + +# Calls. + +#! Whether a signature's result is returned in memory, which a call writes to an +#! address its last operand gives. +#! @param this The selector. +#! @param signature The signature. +#! @returns Whether it is. +def selector::returns_memory(&this, signature: u32): bool { + val result: u32 = this.b.c.program.signatures[signature].result; + val shape: layout = this.b.c.program.layouts[result]; + return returned_in_memory(&shape); +} + +#! The place a word of a call's arguments is passed in. +#! @param k The word. +#! @returns The place. +def argument_place(k: u64): loc { + if k < arg_count { + return in_gpr(gprs[k]); + } + return loc { kind = place::out, value = (k - arg_count) as u32 }; +} + +#! How many words a call passes, and how many of them on the stack. +#! @param this The selector. +#! @param index The call. +#! @returns How many on the stack. +def selector::stacked_words(&this, index: u32): u64 { + val held: inst = this.body.insts[index]; + var words: u64 = held.argc as u64; + match held.kind { + op::call => { + val signature: u32 = this.b.c.program.functions[held.aux].signature; + if this.returns_memory(signature) { + words--; + } + } + op::call_trait, op::call_value => { + if this.returns_memory(held.aux) { + words--; + } + if held.kind == op::call_value { + words--; + } + } + else => return 0; + } + return words > arg_count ? words - arg_count : 0; +} + +#! The code of a call of a function of the program: directly, through a +#! vtable, or through a function value. +#! @param this The selector. +#! @param index The call. +#! @param held The call. +def selector::call(&mut this, index: u32, held: &inst): void { + var signature: u32 = held.aux; + if held.kind == op::call { + signature = this.b.c.program.functions[held.aux].signature; + } + val memory := this.returns_memory(signature); + var given := held.argc as u64; + if memory { + given--; + } + val tail := this.tail_call(index, held, memory); + + # The address called, found before any argument is moved, and kept in the + # frame's scratch. + # A program that checks compares the index with the table's size first, so a + # function value or vtable made from memory written by hand stops it. + if held.kind == op::call_value { + this.load_into(this.body.arg(index, 0), index, reg::rax); + if this.checking() { + this.b.text.alu_imm(alu::sub, reg::rax, 1); + this.b.text.mov_imm(reg::rcx, this.b.c.program.functions.length); + this.b.text.alu(alu::cmp, reg::rax, reg::rcx); + this.trap_if(cc::above_equal, fault::null_reference as u32, index); + this.b.text.load(8, false, reg::rax, indexed(reg::none, reg::rax, 8, this.b.function_table as i32)); + } else { + this.b.text.load(8, false, reg::rax, indexed(reg::none, reg::rax, 8, this.b.function_table as i32 - 8)); + } + this.b.text.store(8, this.scratch_word(2), reg::rax); + } else if held.kind == op::call_trait { + this.load_into(this.body.arg(index, 1), index, reg::rax); + if this.checking() { + this.b.text.mov_imm(reg::rcx, this.b.c.program.vtables.length); + this.b.text.alu(alu::cmp, reg::rax, reg::rcx); + this.trap_if(cc::above_equal, fault::null_reference as u32, index); + } + this.b.text.load(8, false, reg::rax, indexed(reg::none, reg::rax, 8, this.b.vtable_table as i32)); + this.b.text.load(8, false, reg::rax, at(reg::rax, (8 * held.imm) as i32)); + this.b.text.store(8, this.scratch_word(2), reg::rax); + } + + # The words: a function value's environment comes after the rest. + var moves := vector::::new(scratch()); + if held.kind == op::call_value { + for a in 2..given { + moves.append(transfer { from = this.read(this.body.arg(index, a as u32), index), to = argument_place(a - 2) }); + } + moves.append(transfer { from = this.read(this.body.arg(index, 1), index), to = argument_place(given - 2) }); + } else { + for a in 0..given { + moves.append(transfer { from = this.read(this.body.arg(index, a as u32), index), to = argument_place(a) }); + } + } + if memory && !tail { + moves.append(transfer { from = this.read(this.body.arg(index, held.argc - 1), index), to = in_gpr(reg::rdx) }); + } + this.parallel(moves.view()); + if tail { + this.tail_jump(held, memory); + return; + } + + if held.kind == op::call { + this.b.call_to(held.aux); + } else { + this.b.text.call_mem(this.scratch_word(2)); + } + this.results(held); +} + +#! Whether a call is made as a jump, once the frame is left, so the function +#! called returns to this one's caller: where the return straight after it +#! returns just what it gives, its words are all passed in registers, and none +#! of them points into the frame, which is gone by the time the function +#! jumped to runs. A result in memory is written straight to where this +#! function's caller asked for its own, which the return would copy it to. +#! @param this The selector. +#! @param index The call. +#! @param held The call. +#! @param memory Whether its result is returned in memory. +#! @returns Whether it is. +def selector::tail_call(&this, index: u32, held: &inst, memory: bool): bool { + return false if !this.tails || held.next == 0 || this.stacked_words(index) != 0; + val after: inst = this.body.insts[held.next]; + return false if after.kind != op::ret; + var passed := held.argc; + if memory { + var signature: u32 = held.aux; + if held.kind == op::call { + signature = this.b.c.program.functions[held.aux].signature; + } + val result: u32 = this.b.c.program.signatures[signature].result; + return false if this.returned == 0 || this.b.c.program.layouts[result].size != this.returned; + return false if held.count != 0 || after.argc != 1 || this.body.arg(held.next, 0) != this.body.arg(index, held.argc - 1); + passed--; + } else { + return false if this.returned != 0 || after.argc != held.count as u32; + for r in 0..held.count as u32 { + return false if this.body.arg(held.next, r) != held.result + r; + } + } + for a in 0..passed { + return false if this.framed[this.body.arg(index, a)]; + } + return true; +} + +#! Leaves the frame and jumps to the function a call calls, its words passed: +#! given the address this function's caller asked for a result in memory at, +#! and through the address a call through a vtable or a function value found, +#! which `rax` holds while the frame is left. +#! @param this The selector. +#! @param held The call. +#! @param memory Whether its result is returned in memory. +def selector::tail_jump(&mut this, held: &inst, memory: bool): void { + if memory { + this.b.text.load(8, false, reg::rdx, at(reg::rbp, -(this.dst_at as i64) as i32)); + } + if held.kind == op::call { + this.epilogue(5); + this.b.jump_to_function(held.aux); + } else { + this.b.text.load(8, false, reg::rax, this.scratch_word(2)); + this.epilogue(2); + this.b.text.jmp_reg(reg::rax); + } + this.tailed = held.next; +} + +#! Whether no pointer into the frame is kept anywhere a function jumped to, its +#! frame gone, could find it, as far as the code says, and so which values the +#! words a jump passes must not be: following which may point into the frame, +#! the addresses of cells and of parameters held in memory and what is +#! computed from them, and the parameters edges give them as, none is written +#! to memory, given to C, or given to a call as anything it might keep. A call +#! is lent them only as references, which a function never keeps, as its +#! referent would be on the heap rather than in a cell, as memory it only +#! copies or writes its result to, or as the environment of a function value +#! it calls, and what it gives may point into the frame too. The function +#! never reads `frame`. +#! @param this The selector. +#! @returns Whether it is. +def selector::frame_held(&mut this): bool { + val values := this.body.origins.length; + this.framed.resize(values); + for v in 0..values { + var below: u64 = 0; + this.framed[v] = this.p.remade[v] && this.frame_address(v as u32, &mut below); + } + var reads := this.body.reader(); + var changed := true; + while changed { + changed = false; + for k in 0..this.p.order.length { + var walk := this.body.walk(this.p.order[k]); + while walk.more() { + val at := walk.next(); + val held: inst = this.body.insts[at]; + return false if held.kind == op::frame; + var gives := false; + reads.start(at); + while reads.more() { + val value := reads.next(); + val a := reads.operand(); + continue if !this.framed[value] || a == no_operand; + val use := this.framed_use(at, &held, a); + return false if use == 2; + gives = gives || use == 1; + } + if gives { + for r in 0..held.count as u32 { + if !this.framed[held.result + r] { + this.framed[held.result + r] = true; + changed = true; + } + } + } + for e in 0..this.body.edge_count(at) { + val edge := held.aux + e; + val params := &this.body.blocks[this.body.edges[edge].target].params; + val args := &this.body.edges[edge].args; + for i in 0..args.length { + val param: u32 = params[i]; + if this.framed[args[i]] && !this.framed[param] { + this.framed[param] = true; + changed = true; + } + } + } + } + } + } + return true; +} + +#! What an instruction does with an operand that may point into the frame: 0 +#! where it only reads or writes through it, copies to or from it, clears it, +#! tests it, compares it, or formats what it points at, 1 where what it gives +#! may point into the frame too, as arithmetic's and a call's lent it does, and +#! 2 where it may keep it where the code cannot follow it. +#! @param this The selector. +#! @param index The instruction. +#! @param held The instruction. +#! @param a The operand. +#! @returns What. +def selector::framed_use(&this, index: u32, held: &inst, a: u32): u8 { + return match held.kind { + op::load, op::clear, op::copy, op::check, op::branch, op::switch, op::equal, op::format_value => 0, + op::store, op::atomic => a == 0 ? 0 : 2, + op::ret => this.returned != 0 ? 0 : 2, + op::eq, op::ne, op::lts, op::ltu, op::les, op::leu, op::eqsu, op::ltsu, op::lesu, op::ltus, op::leus, op::lnot => 0, + op::add, op::sub, op::band, op::bor, op::bxor, op::mul, op::shl, op::shrs, op::shru, op::neg, op::bnot, op::wrap => 1, + op::call, op::call_trait, op::call_value => this.lent_operand(index, a) ? 1 : 2, + else => 2 + }; +} + +#! Whether an operand of a call is lent to the function called, which keeps no +#! pointer to what it points at: a word of a reference, which a function never +#! keeps, as its referent would be on the heap rather than in a cell, the +#! address of a parameter held in memory, which it copies, or of where its +#! result goes, which it writes, or the environment of the function value +#! called, which it reads. +#! @param this The selector. +#! @param index The call. +#! @param a The operand. +#! @returns Whether it is. +def selector::lent_operand(&this, index: u32, a: u32): bool { + val held: inst = this.body.insts[index]; + var signature: u32 = held.aux; + if held.kind == op::call { + signature = this.b.c.program.functions[held.aux].signature; + } + return true if this.returns_memory(signature) && a == held.argc - 1; + # A function value's two words come before the arguments: what it is, then + # its environment. + var word: u32 = 0; + if held.kind == op::call_value { + return a != 0 if a < 2; + word = 2; + } + for &each in this.b.c.program.signatures[signature].params { + val shape: layout = this.b.c.program.layouts[each]; + val words: u32 = in_memory(&shape) ? 1 : word_count(&shape); + if a < word + words { + return in_memory(&shape) || shape.kind == lk::reference || shape.kind == lk::trait_reference; + } + word += words; + } + return false; +} + +#! Puts the words a call gave in `rax`, `rdx`, and `rcx` where its results go. +#! @param this The selector. +#! @param held The call. +def selector::results(&mut this, held: &inst): void { + val given: reg[3] = [reg::rax, reg::rdx, reg::rcx]; + for r in 0..held.count { + break if r >= 3; + val result := held.result + r as u32; + val to := this.p.made_at(result); + continue if to.kind == place::none; + this.move_one(&transfer { from = in_gpr(given[r as u64]), to = to }); + } +} + +#! Calls one of the runtime's helpers, given its arguments. +#! @param this The selector. +#! @param which The helper. +#! @param moves The moves of its arguments into the registers they are passed in. +def selector::helper_call(&mut this, which: helper, moves: span): void { + this.parallel(moves); + this.b.call_to(this.b.helper_of(which)); +} + +#! The move of an operand of an instruction into the register a helper's +#! argument is passed in. +#! @param this The selector. +#! @param index The instruction. +#! @param at The operand. +#! @param k The argument. +#! @returns The move. +def selector::passing(&this, index: u32, at: u32, k: u64): transfer { + return transfer { from = this.read(this.body.arg(index, at), index), to = in_gpr(gprs[k]) }; +} + +#! The move of a constant into the register a helper's argument is passed in. +#! @param value The constant. +#! @param k The argument. +#! @param this The selector. +#! @returns The move. +def selector::constant_arg(&mut this, value: u64, k: u64): void { + this.b.text.mov_imm(gprs[k], value); +} + +#! The code of the operations the runtime's helpers do. +#! @param this The selector. +#! @param index The instruction. +#! @param held The instruction. +def selector::runtime_op(&mut this, index: u32, held: &inst): void { + match held.kind { + op::allocate => { + var moves: transfer[1] = [this.passing(index, 0, 0)]; + this.helper_call(held.aux == 0 ? helper::allocate_zeroed : helper::allocate, moves[:]); + this.results(held); + } + op::release => { + var moves: transfer[1] = [this.passing(index, 0, 0)]; + this.helper_call(helper::release, moves[:]); + } + op::resize => { + var moves: transfer[2] = [this.passing(index, 0, 0), this.passing(index, 1, 1)]; + this.helper_call(helper::resize, moves[:]); + this.results(held); + } + op::equal => { + var moves: transfer[2] = [this.passing(index, 0, 0), this.passing(index, 1, 1)]; + this.parallel(moves[:]); + this.constant_arg(this.b.layout_address(held.aux), 2); + this.b.call_to(this.b.helper_of(helper::equal)); + this.results(held); + } + op::format => this.b.call_to(this.b.helper_of(helper::format_begin)); + op::format_text => { + this.constant_arg(this.b.datum_address(held.aux), 0); + this.constant_arg(this.b.datum_length(held.aux), 1); + this.b.call_to(this.b.helper_of(helper::format_text)); + } + op::format_bytes => { + var moves: transfer[2] = [this.passing(index, 0, 0), this.passing(index, 1, 1)]; + this.helper_call(helper::format_text, moves[:]); + } + op::format_value => { + val shape: layout = this.b.c.program.layouts[held.aux]; + if in_memory(&shape) { + var moves: transfer[1] = [this.passing(index, 0, 0)]; + this.parallel(moves[:]); + } else { + # The words, as a frame holds the value, go to the scratch of the frame. + for a in 0..held.argc { + break if a >= 3; + val from := this.read(this.body.arg(index, a), index); + this.move_one(&transfer { from = from, to = loc { kind = place::none } }); + this.store_scratch(from, a as u64); + } + this.b.text.lea(gprs[0], this.scratch_word(0)); + } + this.constant_arg(this.b.layout_address(held.aux), 1); + this.b.call_to(this.b.helper_of(helper::format_value)); + } + op::format_owned => { + this.b.text.lea(gprs[0], this.scratch_word(0)); + this.b.call_to(this.b.helper_of(helper::format_owned)); + this.b.text.load(8, false, reg::rax, this.scratch_word(0)); + this.b.text.load(8, false, reg::rdx, this.scratch_word(1)); + this.results(held); + } + op::exit => { + var moves: transfer[1] = [this.passing(index, 0, 0)]; + this.helper_call(helper::exit, moves[:]); + } + op::abort => this.b.call_to(this.b.helper_of(helper::abort)); + op::fault => { + var moves: transfer[2] = [this.passing(index, 0, 0), this.passing(index, 1, 1)]; + this.helper_call(helper::fault, moves[:]); + } + else => {} + } +} + +#! Writes where a value is to a word of the frame's scratch. +#! @param this The selector. +#! @param from Where the value is. +#! @param k The word. +def selector::store_scratch(&mut this, from: loc, k: u64): void { + val to := this.scratch_word(k); + match from.kind { + place::gpr => this.b.text.store(8, to, from.number as reg); + place::xmm => this.b.text.movsd_store(to, from.number); + place::remade => { + this.remake(from.value, reg::rax); + this.b.text.store(8, to, reg::rax); + } + place::none => this.b.text.store_imm(to, 0); + else => { + this.b.text.load(8, false, reg::rax, this.memory_of(&from)); + this.b.text.store(8, to, reg::rax); + } + } +} + + +# The system. + +#! The code of the operations of the system: system calls, signals, the +#! environment, and safe points. +#! @param this The selector. +#! @param index The instruction. +#! @param held The instruction. +def selector::system_op(&mut this, index: u32, held: &inst): void { + match held.kind { + op::syscall => { + if this.b.options.windows { + val decl := this.b.c.program.functions[this.index].decl; + this.b.problem_at(decl, "System calls are Linux's: an executable for Windows calls the system through C functions, as an `extern module` and `extern import \"kernel32.dll\"` declare them."); + return; + } + # Each operand is pushed, then popped into the register the kernel reads + # it from, so none is overwritten before it is read. + for a in 0..7u { + if a < held.argc as u64 { + this.push_operand(this.body.arg(index, a as u32), index); + } else { + this.b.text.mov_imm(reg::rax, 0); + this.b.text.push(reg::rax); + } + } + val kernel: reg[7] = [reg::rax, reg::rdi, reg::rsi, reg::rdx, reg::r10, reg::r8, reg::r9]; + for k in 0..7u { + this.b.text.pop(kernel[6 - k]); + } + this.b.text.syscall(); + this.results(held); + } + op::catch => { + # On Windows the console's events stand for signals, and what the program + # asks of `catch_signal` is done by code of its own, called as C is. + # `rsp` is kept in the frame's scratch around the call. + if this.b.options.windows { + this.load_into(this.body.arg(index, 0), index, reg::rcx); + this.b.text.store(8, this.scratch_word(0), reg::rsp); + this.b.text.alu_imm(alu::band, reg::rsp, -16); + this.b.text.patch(this.b.text.call(), this.b.catching); + this.b.text.load(8, false, reg::rsp, this.scratch_word(0)); + this.results(held); + return; + } + # `rt_sigaction`, giving the signal the handler noting it, without + # `SA_RESTART`, so a wait it interrupts ends. + this.load_into(this.body.arg(index, 0), index, reg::rdi); + this.b.text.alu_imm(alu::sub, reg::rsp, 32); + this.b.text.mov_imm(reg::rax, this.b.text_base + this.b.noting); + this.b.text.store(8, at(reg::rsp, 0), reg::rax); + this.b.text.mov_imm(reg::rax, 0x04000000); + this.b.text.store(8, at(reg::rsp, 8), reg::rax); + this.b.text.mov_imm(reg::rax, this.b.text_base + this.b.restorer); + this.b.text.store(8, at(reg::rsp, 16), reg::rax); + this.b.text.store_imm(at(reg::rsp, 24), 0); + this.b.text.mov_imm(reg::rax, 13); + this.b.text.mov(reg::rsi, reg::rsp); + this.b.text.mov_imm(reg::rdx, 0); + this.b.text.mov_imm(reg::r10, 8); + this.b.text.syscall(); + this.b.text.alu_imm(alu::add, reg::rsp, 32); + this.results(held); + } + op::safepoint => { + # The call is rare, so it is made after the function's body, which keeps + # every register around it. + # Only the first thread's record notes signals, so only it runs handlers. + val signals := this.b.own_word(state_signals); + this.b.text.alu_mem_imm(alu::cmp, signals, 0); + val patch := this.b.text.jcc(cc::not_equal); + this.safe_points.append(safe_site { + patch = patch, back = this.b.text.length, at = held.at, site = held.site, index = index + }); + } + op::signals => { + # On Windows the event is reset before the signals are taken, so that one + # noted between its reset and the exchange sets it again. Taking signals + # is no call, so the registers the cache may hold a value in that the + # reset would clobber are kept around it; `rsp` is a word of 16 within a + # function's body, so the call needs only the 32 bytes above it. + if this.b.options.windows { + this.b.text.load(8, false, reg::rcx, absolute(this.b.state_address(state_signalled))); + this.b.text.test(reg::rcx, reg::rcx); + val unasked := this.b.text.jcc(cc::equal); + this.b.text.push(reg::r8); + this.b.text.push(reg::r9); + this.b.text.push(reg::r10); + this.b.text.push(reg::r11); + this.b.text.alu_imm(alu::sub, reg::rsp, 32); + this.b.call_system(system_reset_event); + this.b.text.alu_imm(alu::add, reg::rsp, 32); + this.b.text.pop(reg::r11); + this.b.text.pop(reg::r10); + this.b.text.pop(reg::r9); + this.b.text.pop(reg::r8); + this.b.text.land(unasked); + } + val into := this.target(held.result, reg::rax); + this.b.text.mov_imm(into, 0); + this.b.text.xchg(8, absolute(this.b.state_address(state_signals)), into); + this.put(held.result, into); + } + op::environ => { + # The system leaves the variables on the first stack after `argv` and + # its null. + this.b.text.load(8, false, reg::rax, absolute(this.b.state_address(state_argc))); + this.b.text.load(8, false, reg::rcx, absolute(this.b.state_address(state_argv))); + val into := this.target(held.result, reg::rax); + this.b.text.lea(into, indexed(reg::rcx, reg::rax, 8, 8)); + this.put(held.result, into); + } + else => {} + } +} + +#! Pushes a word an instruction reads onto the stack. +#! @param this The selector. +#! @param value The word. +#! @param index The instruction. +def selector::push_operand(&mut this, value: u32, index: u32): void { + this.b.text.push(this.word_reg(value, index, reg::rax)); +} + + +# Ends of blocks. + +#! The code of an instruction ending a block: a jump, a branch, a switch, a +#! return, or a trap. +#! @param this The selector. +#! @param index The instruction. +#! @param held The instruction. +#! @param next The block laid out next, which a jump to needs no jump. +def selector::ending(&mut this, index: u32, held: &inst, next: u32): void { + val end := this.p.end_slots[held.block]; + match held.kind { + op::jump => { + this.gap(end); + this.edge(held.aux); + this.jump_to(this.body.edges[held.aux].target, next); + } + op::branch => this.branch(index, held, next, end); + op::switch => this.switch_on(index, held, next, end); + op::ret => this.ret(index, held); + op::trap => { + if held.argc != 0 { + this.load_into(this.body.arg(index, 0), index, reg::rdi); + } else { + this.b.text.mov_imm(reg::rdi, held.aux as u64); + } + this.b.text.patch(this.b.text.call(), this.b.trap_stub); + } + else => { + this.b.text.mov_imm(reg::rdi, fault::unreachable as u64); + this.b.text.patch(this.b.text.call(), this.b.trap_stub); + } + } +} + +#! Jumps to a block, unless it is laid out next. +#! @param this The selector. +#! @param target The block. +#! @param next The block laid out next. +def selector::jump_to(&mut this, target: u32, next: u32): void { + return if target == next; + this.jumps.add(this.b.text.jmp(), target); +} + +#! Jumps to a block where a condition holds. +#! @param this The selector. +#! @param condition The condition. +#! @param target The block. +def selector::jump_if(&mut this, condition: cc, target: u32): void { + this.jumps.add(this.b.text.jcc(condition), target); +} + +#! A branch: to its first edge where its condition holds, and to the second +#! otherwise, each moving what its block takes down a path of its own. +#! @param this The selector. +#! @param index The branch. +#! @param held The branch. +#! @param next The block laid out next. +#! @param end The place where its block's edges leave. +def selector::branch(&mut this, index: u32, held: &inst, next: u32, end: u32): void { + var condition := cc::not_equal; + val reader := this.p.reader_of(this.body, index); + if reader != index { + val kind: op = this.body.insts[reader].kind; + condition = this.compare(index, kind, this.body.arg(reader, 0), this.body.arg(reader, 1)); + } else { + val tested := this.word_reg(this.body.arg(index, 0), index, reg::rax); + this.b.text.test(tested, tested); + } + + # The moves of the place the edges leave from are only moves, which leave + # the flags as they are. + this.gap(end); + val then := held.aux; + val other := held.aux + 1; + val then_target: u32 = this.body.edges[then].target; + val other_target: u32 = this.body.edges[other].target; + val then_moves := this.moves_on(then); + val other_moves := this.moves_on(other); + if !then_moves && !other_moves { + if then_target == next { + this.jump_if(opposite(condition), other_target); + return; + } + this.jump_if(condition, then_target); + this.jump_to(other_target, next); + return; + } + if !then_moves { + this.jump_if(condition, then_target); + this.edge(other); + this.jump_to(other_target, next); + return; + } + if !other_moves { + this.jump_if(opposite(condition), other_target); + this.edge(then); + this.jump_to(then_target, next); + return; + } + val otherwise := this.b.text.jcc(opposite(condition)); + this.edge(then); + this.jump_to(then_target, never); + this.b.text.land(otherwise); + this.edge(other); + this.jump_to(other_target, next); +} + +#! A switch: compares the word with each case in turn, then goes to the +#! default, each edge moving what its block takes on a path of its own. +#! @param this The selector. +#! @param index The switch. +#! @param held The switch. +#! @param next The block laid out next. +#! @param end The place where its block's edges leave. +def selector::switch_on(&mut this, index: u32, held: &inst, next: u32, end: u32): void { + # `rdx` holds the word, which no move touches. + this.load_into(this.body.arg(index, 0), index, reg::rdx); + this.gap(end); + val edges := held.imm as u32; + return if this.switch_by_table(held, edges); + var paths := vector::::new(scratch()); + for e in 0..edges - 1 { + val edge := held.aux + e; + val case: u64 = this.body.edges[edge].case; + if case == 0 { + this.b.text.test(reg::rdx, reg::rdx); + } else if fits_i32(case) { + this.b.text.alu_imm(alu::cmp, reg::rdx, case as i32); + } else { + this.b.text.mov_imm(reg::rax, case); + this.b.text.alu(alu::cmp, reg::rdx, reg::rax); + } + if this.moves_on(edge) { + paths.append(this.b.text.jcc(cc::equal)); + } else { + paths.append(never as u64); + this.jump_if(cc::equal, this.body.edges[edge].target); + } + } + # Where the cases' moves come after, the fallback can't fall through to the + # block laid out next. + var landings := false; + for e in 0..edges - 1 { + landings = landings || paths[e as u64] != never as u64; + } + val fallback := held.aux + edges - 1; + this.edge(fallback); + this.jump_to(this.body.edges[fallback].target, landings ? never : next); + for e in 0..edges - 1 { + val path: u64 = paths[e as u64]; + continue if path == never as u64; + this.b.text.land(path); + this.edge(held.aux + e); + this.jump_to(this.body.edges[held.aux + e].target, never); + } +} + +# The fewest cases a switch jumps through a table for, the most entries a table +# has, and how many entries it may have for each case. +const table_least: u64 = 4; +const table_most: u64 = 1024; +const table_spread: u64 = 3; + +#! The lowest case of a switch, and how many entries its table has, where it +#! goes through one: where its cases are enough and close enough together. +#! @param this The selector. +#! @param held The switch. +#! @param low Where its lowest case is written. +#! @returns How many entries, or 0 where it compares each case instead. +def selector::table_size(&this, held: &inst, low: &mut i64): u64 { + val count := held.imm - 1; + return 0 if count < table_least; + low = this.body.edges[held.aux].case as i64; + var high := low; + for e in 0..count { + val case := this.body.edges[held.aux + e as u32].case as i64; + low = case < low ? case : low; + high = case > high ? case : high; + } + # Far enough apart that the difference overflows is too far. + return 0 if high - low < 0; + val size := (high - low) as u64 + 1; + return size > table_most || size > table_spread * count ? 0 : size; +} + +#! A switch whose cases are close enough together: the word, less the lowest +#! case, indexes a table of where each goes, written after the function's +#! code, and any word past the table goes where no case does. +#! @param this The selector. +#! @param held The switch. +#! @param edges How many edges it has, the last where no case matches. +#! @returns Whether it was, which it is not where the cases are too few or +#! too far apart. +def selector::switch_by_table(&mut this, held: &inst, edges: u32): bool { + val count := edges as u64 - 1; + var low: i64 = 0; + val size := this.table_size(held, &mut low); + return false if size == 0; + + if low != 0 { + if fits_i32(low as u64) { + this.b.text.alu_imm(alu::sub, reg::rdx, low as i32); + } else { + this.b.text.mov_imm(reg::rax, low as u64); + this.b.text.alu(alu::sub, reg::rdx, reg::rax); + } + } + this.b.text.alu_imm(alu::cmp, reg::rdx, (size - 1) as i32); + val fallback := held.aux + edges - 1; + var past: u64 = never as u64; + if this.moves_on(fallback) { + past = this.b.text.jcc(cc::above); + } else { + this.jump_if(cc::above, this.body.edges[fallback].target); + } + # Each entry is the address of where its case goes, which fits 32 bits, as + # every address of an executable's image does. + this.b.text.load(4, false, reg::rax, indexed(reg::none, reg::rdx, 4, 0)); + val patch := this.b.text.length - 4; + this.b.text.jmp_reg(reg::rax); + + # Where each case goes: its block, or the moves its edge makes first. + var going := vector::::new(scratch()); + for e in 0..edges { + val edge := held.aux + e; + val target: u32 = this.body.edges[edge].target; + if !this.moves_on(edge) { + going.append(table_entry { block = target, at = 0 }); + continue; + } + if e == edges - 1 { + this.b.text.land(past); + } + going.append(table_entry { block = never, at = this.b.text.length }); + this.edge(edge); + this.jump_to(target, never); + } + + val first := this.entries.length as u32; + for _ in 0..size { + this.entries.append(going[count]); + } + for e in 0..count { + val at := (this.body.edges[held.aux + e as u32].case as i64 - low) as u64; + this.entries[first as u64 + at] = going[e]; + } + this.tables.append(switch_table { patch = patch, first = first, count = size as u32 }); + return true; +} + +#! Writes the tables of the function's switches after its code, and points +#! the jumps through them at them. +#! @param this The selector. +def selector::write_tables(&mut this): void { + return if this.tables.length == 0; + this.b.text.align_to(4); + for t in 0..this.tables.length { + val table: switch_table = this.tables[t]; + this.b.text.set_u32(table.patch, this.b.text_base + this.b.text.length); + for k in table.first..table.first + table.count { + val entry: table_entry = this.entries[k as u64]; + val at := entry.block != never ? this.labels[entry.block] : entry.at; + this.b.text.u32(this.b.text_base + at); + } + } +} + +#! A return: the words in `rax`, `rdx`, and `rcx`, or the memory at the +#! address copied to where the caller asked, then back to the caller. +#! @param this The selector. +#! @param index The return. +#! @param held The return. +def selector::ret(&mut this, index: u32, held: &inst): void { + if this.returned != 0 { + # Every value is dead here, so any register may be used. + if held.argc != 0 { + this.load_into(this.body.arg(index, 0), index, reg::rsi); + this.b.text.load(8, false, reg::rdi, at(reg::rbp, -(this.dst_at as i64) as i32)); + this.b.text.test(reg::rdi, reg::rdi); + val no_dst := this.b.text.jcc(cc::equal); + this.b.text.test(reg::rsi, reg::rsi); + val no_src := this.b.text.jcc(cc::equal); + # Copied 16 bytes at a time, as the caller reads a vector of them back, + # which the processor forwards only from a store as wide. + if this.returned <= 128 { + this.b.text.copy_small(at(reg::rdi, 0), at(reg::rsi, 0), this.returned, reg::rax, true); + } else { + this.b.text.mov_imm(reg::rcx, this.returned); + this.b.text.rep_movsb(); + } + this.b.text.land(no_dst); + this.b.text.land(no_src); + } + } else { + val given: reg[3] = [reg::rax, reg::rdx, reg::rcx]; + var moves := vector::::new(scratch()); + for a in 0..held.argc { + break if a >= 3; + moves.append(transfer { from = this.read(this.body.arg(index, a), index), to = in_gpr(given[a as u64]) }); + } + this.parallel(moves.view()); + } + this.epilogue(1); + this.b.text.ret(); +} + +#! Leaves the frame before the instruction leaving the function: gives back +#! the registers a call keeps that it saved, clears the upper halves of the +#! vector registers where its code held 32 bytes in them, and puts back the +#! caller's frame and stack pointers. +#! @param this The selector. +#! @param bytes The bytes of the instruction leaving, which debugging +#! information notes. +def selector::epilogue(&mut this, bytes: u8): void { + for k in 0..this.save_count { + this.b.text.load(8, false, this.saved[k], at(reg::rbp, -((8 * (k + 1)) as i64) as i32)); + } + if this.body.wide || this.uses_upper { + this.b.text.vzeroupper(); + } + this.b.text.leave(); + if this.b.options.debug { + this.b.debug.returns.append((this.b.text.length - this.start) as u32); + this.b.debug.return_bytes.append(bytes); + } +} + + +# A function. + +#! The code of one instruction, but for those ending blocks. +#! @param this The selector. +#! @param index The instruction. +#! @param held The instruction. +def selector::emit(&mut this, index: u32, held: &inst): void { + val kind := held.kind; + val number := kind as u32; + # Code holding 32 bytes in registers clears their upper halves before a call, + # across which it holds nothing in registers, so the callee's SSE runs at + # speed. + if (this.body.wide || this.uses_upper) && calls(kind) { + this.b.text.vzeroupper(); + } + if number >= op::add as u32 && number <= op::fle as u32 { + this.binary(index, held); + return; + } + if number >= op::neg as u32 && number <= op::wrap as u32 { + this.unary_op(index, held); + return; + } + match kind { + op::select => this.choose(index, held); + op::load => this.load(index, held); + op::store => this.store(index, held); + op::copy => this.copy(index, held); + op::clear => this.clear(index, held); + op::call, op::call_trait, op::call_value => this.call(index, held); + op::call_c => this.call_c(index, held); + op::allocate, op::release, op::resize, op::equal, op::format, op::format_text, + op::format_value, op::format_bytes, op::format_owned, op::exit, op::abort, op::fault => this.runtime_op(index, held); + op::syscall, op::catch, op::safepoint, op::signals, op::environ => this.system_op(index, held); + op::retrait => this.retrait(index, held); + op::check => this.check(index, held); + op::ready, op::reach, op::same => this.trap_always(halt_unsupported, index); + op::cpu => { + val into := this.target(held.result, reg::rax); + this.b.text.load(8, false, into, absolute(this.b.state_address(state_features))); + this.put(held.result, into); + } + op::lanes => this.lanes(index, held); + op::vzero => this.zero_lanes(index, held); + op::atomic => this.atomic(index, held); + op::start => { + # The function value's words and the context go to the scratch of the frame, + # which the runtime copies into the thread's record. + for a in 0..3 { + val from := this.read(this.body.arg(index, a as u32), index); + this.move_one(&transfer { from = from, to = loc { kind = place::none } }); + this.store_scratch(from, a as u64); + } + this.b.text.lea(gprs[0], this.scratch_word(0)); + this.b.call_to(this.b.helper_of(helper::start_thread)); + this.results(held); + } + op::current => { + val into := this.target(held.result, reg::rax); + val itself := this.b.own_word(state_itself); + this.b.text.load(8, false, into, itself); + this.put(held.result, into); + } + op::clone => this.clone_thread(index, held); + else => {} + } +} + +#! `clone`: a thread of the system sharing everything the program has, on the +#! stack of the record, whose number the system writes in the record as it +#! starts and clears as it ends. The new thread points `gs` at its record, takes +#! the signals it may, which are its faults, every other going to the first +#! thread, and runs `runtime::thread_main`, then ends. +#! The record is kept in `r9`, which `clone` takes no argument in, and which no +#! system call changes. +#! @param this The selector. +#! @param index The instruction. +#! @param held The instruction. +def selector::clone_thread(&mut this, index: u32, held: &inst): void { + if this.b.options.windows { + this.clone_thread_windows(index, held); + return; + } + val record := this.word_reg(this.body.arg(index, 0), index, reg::rdx); + this.b.text.mov(reg::r9, record); + this.b.text.mov_imm(reg::rdi, 0x350F00); + this.b.text.load(8, false, reg::rsi, at(reg::r9, (8 * state_base) as i32)); + this.b.text.lea(reg::rdx, at(reg::r9, (8 * state_tid) as i32)); + this.b.text.mov(reg::r10, reg::rdx); + this.b.text.mov_imm(reg::r8, 0); + this.b.text.mov_imm(reg::rax, 56); + this.b.text.syscall(); + this.b.text.test(reg::rax, reg::rax); + val parent := this.b.text.jcc(cc::not_equal); + + this.b.text.mov_imm(reg::rax, 158); + this.b.text.mov_imm(reg::rdi, 0x1001); + this.b.text.mov(reg::rsi, reg::r9); + this.b.text.syscall(); + this.b.text.mov_imm(reg::rbp, 0); + val taken: u64 = (1u << 3) | (1u << 4) | (1u << 6) | (1u << 7) | (1u << 10); + this.b.text.alu_imm(alu::sub, reg::rsp, 16); + this.b.text.mov_imm(reg::rax, ~taken); + this.b.text.store(8, at(reg::rsp, 0), reg::rax); + this.b.text.mov_imm(reg::rax, 14); + this.b.text.mov_imm(reg::rdi, 2); + this.b.text.mov(reg::rsi, reg::rsp); + this.b.text.mov_imm(reg::rdx, 0); + this.b.text.mov_imm(reg::r10, 8); + this.b.text.syscall(); + this.b.text.alu_imm(alu::add, reg::rsp, 16); + this.b.call_to(this.b.helper_of(helper::thread_main)); + this.b.text.mov_imm(reg::rax, 60); + this.b.text.mov_imm(reg::rdi, 0); + this.b.text.syscall(); + + this.b.text.land(parent); + this.put(held.result, reg::rax); +} + +#! The error a construct executables cannot run stops them with. +pub const halt_unsupported: u32 = 3; + +#! Notes where in the source the code being written is from, where it changes. +#! @param this The selector. +#! @param held The instruction it is the code of. +def selector::mark(&mut this, at: u64, site: u32): void { + return if at == this.last_at && site == this.last_site; + this.last_at = at; + this.last_site = site; + this.b.rows.append(line_row { offset = this.b.text.length - this.start, at = at, site = site }); +} + +#! Writes the prologue: the frame is made, checked against the stack's limit, +#! the registers a call keeps that the function uses saved at its top, the +#! address a result in memory goes to kept, the parameters held in memory +#! copied, the cells zeroed, and each parameter moved to where its value is. +#! @param this The selector. +#! @param memory Whether each parameter of the entry is held in memory. +#! @param sizes The bytes of each one held in memory. +def selector::prologue(&mut this, memory: span, sizes: span): void { + this.b.text.push(reg::rbp); + this.b.text.mov(reg::rbp, reg::rsp); + if !this.leaf || this.frame > 4096 { + val limit := this.b.own_word(state_limit); + this.b.text.lea(reg::rax, at(reg::rsp, -(this.frame as i64) as i32)); + this.b.text.alu_load(alu::cmp, reg::rax, limit); + this.b.patch_jcc(cc::below, this.b.overflow_stub); + } + for k in 0..this.save_count { + this.b.text.push(this.saved[k]); + } + if this.b.options.debug || this.b.options.windows { + this.b.debug.saves[this.index] = this.saved_mask(); + this.b.debug.saved_at[this.index] = (this.b.text.length - this.start) as u32; + this.b.debug.frames[this.index] = this.frame as u32; + } + val rest := this.frame - 8 * this.save_count; + if rest != 0 { + # On Windows the stack grows by guard pages, so a frame larger than a page + # is made a page at a time, each touched so the system commits it. + if this.b.options.windows && rest > page_size { + this.b.descend(rest); + } else { + this.b.text.alu_imm(alu::sub, reg::rsp, rest as i32); + } + } + if this.returned != 0 { + this.b.text.store(8, at(reg::rbp, -(this.dst_at as i64) as i32), reg::rdx); + } + + # The copies of what is held in memory, from the addresses the caller gave. + for i in 0..memory.length { + continue if !memory[i]; + val from := i < arg_count ? in_gpr(gprs[i]) : loc { kind = place::incoming, value = i as u32 }; + this.move_one(&transfer { from = from, to = in_gpr(reg::rax) }); + this.b.text.test(reg::rax, reg::rax); + val none := this.b.text.jcc(cc::equal); + val size := sizes[i]; + val to := at(reg::rbp, -(this.copies[i] as i64) as i32); + if size <= 128 { + this.b.text.copy_small(to, at(reg::rax, 0), size, reg::rcx, false); + } else { + this.b.text.push(reg::rsi); + this.b.text.push(reg::rdi); + this.b.text.mov(reg::rsi, reg::rax); + this.b.text.lea(reg::rdi, to); + this.b.text.mov_imm(reg::rcx, size); + this.b.text.rep_movsb(); + this.b.text.pop(reg::rdi); + this.b.text.pop(reg::rsi); + } + this.b.text.land(none); + } + + # The cells the frame zeroes, sixteen bytes at a time from `xmm0`, which + # holds nothing as the function begins: written out where they are few, and + # by a loop down from the top otherwise, a word left at the bottom alone. + val bytes := this.zero_to - this.zero_from; + if bytes != 0 && bytes <= 256 { + this.b.text.zero_small(at(reg::rbp, -(this.zero_to as i64) as i32), bytes); + } else if bytes != 0 { + val pairs := bytes & ~15u; + this.b.text.packed(vec_pxor, 0, 0); + this.b.text.lea(reg::rax, at(reg::rbp, -(this.zero_to as i64) as i32)); + if pairs != bytes { + this.b.text.store_imm(at(reg::rax, pairs as i32), 0); + } + this.b.text.mov_imm(reg::rcx, pairs); + val loop := this.b.text.length; + this.b.text.packed_mem(vec_movdqu_store, 0, indexed(reg::rax, reg::rcx, 1, -16)); + this.b.text.alu_imm(alu::sub, reg::rcx, 16); + this.b.text.patch(this.b.text.jcc(cc::not_equal), loop); + } + + # Each parameter, from where the caller passed it to where its value is. + val entry := &this.body.blocks[0]; + var moves := vector::::new(scratch()); + for i in 0..entry.params.length { + val value: u32 = entry.params[i]; + continue if this.p.remade[value]; + val to := this.p.made_at(value); + continue if to.kind == place::none; + val from := i < arg_count ? in_gpr(gprs[i]) : loc { kind = place::incoming, value = i as u32 }; + moves.append(transfer { from = from, to = to }); + } + this.parallel(moves.view()); +} + +#! Writes the stubs the checks that fail jump to, each reporting its error from +#! where its check is. +#! @param this The selector. +def selector::stubs(&mut this): void { + # A safe point calls the code every function shares, which keeps the + # registers around the call of the handlers. + for i in 0..this.safe_points.length { + val site: safe_site = this.safe_points[i]; + this.b.text.land(site.patch); + val from := this.b.text.length - this.start; + this.mark(site.at, site.site); + this.b.text.patch(this.b.text.call(), this.b.safe_point); + this.b.text.patch(this.b.text.jmp(), site.back); + this.note_stub(from, site.index); + } + for i in 0..this.traps.length { + val site: trap_site = this.traps[i]; + this.b.text.land(site.patch); + val from := this.b.text.length - this.start; + this.mark(site.at, site.site); + this.b.text.mov_imm(reg::rdi, site.code as u64); + this.b.text.patch(this.b.text.call(), this.b.trap_stub); + this.note_stub(from, site.index); + } +} + +#! Notes where a stub's code is, for the debugging information, which shows +#! the variables there as they are where the instruction it is of is. +#! @param this The selector. +#! @param from Where its code begins within the function's. +#! @param index The instruction it is of. +def selector::note_stub(&mut this, from: u64, index: u32): void { + return if !this.b.options.debug; + this.stub_spans.append(from as u32); + this.stub_spans.append((this.b.text.length - this.start) as u32); + this.stub_spans.append(index); +} + diff --git a/native/check.sakura b/native/check.sakura new file mode 100644 index 00000000..36628f69 --- /dev/null +++ b/native/check.sakura @@ -0,0 +1,181 @@ +#! @file check.sakura +#! @author John Christman (sorakatadzuma@gmail.com) +#! @copyright Malunal Studios, LLC. +#! @license MIT +#! +#! Contains the checker of the register allocator, which replays what it chose +#! of a function, symbolically: which value each register and slot holds as +#! each move, call, and result changes them, block by block, confirming each +#! operand is read where its value is, and that each edge leaves every value +#! the block it goes to holds where that block expects it. The allocator and +#! the moves it finds are where such mistakes hide, so tests and `--verify` +#! run this on every function they build. + +import sakura::compiler; +import binary::amd64; +import std::containers; +module sakura::native; + + +#! What a register or slot holds as the replay goes, by place. +struct holding { + var gprs: u32[16]; #! The value each general register holds, or 0. + var xmms: u32[16]; #! The value each SSE register holds, or 0. + var slots: dict; #! The value each value's slot holds, where it holds one. +} + +#! A copy of what is held. +#! @param this What is held. +#! @returns The copy. +def holding::copied(&this): holding { + var made := holding { gprs = this.gprs, xmms = this.xmms, slots = dict::::new(scratch()) }; + for &each in this.slots { + made.slots.set(each.key, each.value); + } + return made; +} + +#! The value a place holds, or 0 where it holds none known. +#! @param this What is held. +#! @param spot The place. +#! @returns The value. +def holding::at(&this, spot: &loc): u32 { + if spot.kind == place::slot { + return this.slots.get_or(&spot.value, 0); + } + return match spot.kind { + place::gpr => this.gprs[spot.number as u64], + place::xmm => this.xmms[spot.number as u64], + place::remade => spot.value, + else => 0 + }; +} + +#! Says a place holds a value. +#! @param this What is held. +#! @param spot The place. +#! @param value The value. +def holding::set(&mut this, spot: &loc, value: u32): void { + match spot.kind { + place::gpr => this.gprs[spot.number as u64] = value; + place::xmm => this.xmms[spot.number as u64] = value; + place::slot => this.slots.set(spot.value, value); + else => {} + } +} + +#! Forgets what every register a call clobbers holds, as a call leaves them: +#! all but the general registers a call keeps. +#! @param this What is held. +def holding::clobber(&mut this): void { + for r in 0..16u { + if !keeps(r as u8) { + this.gprs[r] = 0; + } + this.xmms[r] = 0; + } +} + +#! Makes moves all at once: each reads what its place held before any wrote. +#! @param this What is held. +#! @param moves The moves. +def holding::parallel(&mut this, moves: span): void { + var values := vector::::new(scratch()); + for &each in moves { + values.append(this.at(&each.from)); + } + for i in 0..moves.length { + this.set(&moves[i].to, values[i]); + } +} + +#! Replays where a function's values were placed, giving what it finds wrong. +#! @param body The code. +#! @param p Where its values are. +#! @returns What is wrong, one problem each. +pub def check_placing(body: &code, p: &placing): vector { + var problems := vector::::new(); + for k in 0..p.order.length { + val block: u32 = p.order[k]; + var held := holding { slots = dict::::new(scratch()) }; + # What the block holds where it begins, which each edge into it is checked + # to leave. + for ¶m in body.blocks[block].params { + held.set(&p.made_at(param), param); + } + for &value in p.liveins.of(block) { + held.set(&p.located(value, 4 * p.start_slots[block]), value); + if p.slot_of[value] != never { + held.set(&in_slot(value), value); + } + } + replay_block(body, p, block, &mut held, &mut problems); + } + return problems; +} + +#! Replays a block from what it holds where it begins, then each edge leaving +#! it. +#! @param body The code. +#! @param p Where its values are. +#! @param block The block. +#! @param held What is held where it begins. +#! @param problems Where what is wrong is written. +def replay_block(body: &code, p: &placing, block: u32, held: &mut holding, problems: &mut vector): void { + var operands := vector::::new(scratch()); + var walk := body.walk(block); + while walk.more() { + val inst_at := walk.next(); + val instruction: inst = body.insts[inst_at]; + val slot: u32 = p.slots[inst_at]; + held.parallel(p.gap_moves.of(slot)); + continue if p.folded[inst_at]; + + # Each operand is where its value is, and what a select a comparison is + # folded into chooses between. + p.read_by(body, inst_at, &mut operands); + for &value in operands { + val spot := p.read_at(value, inst_at); + if held.at(&spot) != value && spot.kind != place::none { + problems.append($"b{block}: v{value}, read by i{inst_at}, is not spot it was placed"); + } + } + if calls(instruction.kind) { + held.clobber(); + } + for r in 0..instruction.count { + val result := instruction.result + r as u32; + held.set(&p.made_at(result), result); + } + } + + val end: u32 = p.end_slots[block]; + held.parallel(p.gap_moves.of(end)); + val last: u32 = body.blocks[block].last; + return if last == 0; + var outs := body.edges_of(last); + while outs.more() { + val edge := outs.next(); + val target: u32 = body.edges[edge].target; + continue if p.number[target] == never; + var after := held.copied(); + after.parallel(p.edge_moves_of(edge)); + # Each parameter's place holds the argument the edge gives it. + val params := &body.blocks[target].params; + for i in 0..params.length { + break if i >= body.edges[edge].args.length; + val param: u32 = params[i]; + val arg: u32 = body.edges[edge].args[i]; + val spot := p.made_at(param); + if spot.kind != place::none && after.at(&spot) != arg { + problems.append($"b{block}: edge {edge} leaves v{arg}, for parameter v{param} of b{target}, out of place"); + } + } + for &value in p.liveins.of(target) { + val spot := p.located(value, 4 * p.start_slots[target]); + if after.at(&spot) != value { + problems.append($"b{block}: edge {edge} leaves v{value}, live into b{target}, out of place"); + } + } + } +} diff --git a/native/codeview.sakura b/native/codeview.sakura new file mode 100644 index 00000000..05a194a4 --- /dev/null +++ b/native/codeview.sakura @@ -0,0 +1,753 @@ +#! @file codeview.sakura +#! @author John Christman (sorakatadzuma@gmail.com) +#! @copyright Malunal Studios, LLC. +#! @license MIT +#! +#! Contains the writer of an executable's debugging information for Windows' +#! debuggers, as a PDB file beside it holding CodeView: the types of the +#! variables, each function's code with its frame, its variables and where +#! each is over which code, the calls inlined into it with their lines, the +#! lines of its code, and the names a debugger finds each function by. It +#! describes what the DWARF in the executable does, which other debuggers read. +#! +#! Every function makes its frame of `rbp` as it begins, so each variable in +#! its frame is at an offset from `rbp`, sixteen bytes below where the DWARF +#! names it from, the caller's frame. The executable names the file, which is +#! named by a GUID made from what it holds once it is written. + +import std::io; +import sakura::compiler; +import binary::amd64; +import binary::elf; +import binary::pdb; +import binary::pe; +module sakura::native; + + +#! How far `rbp` is below the caller's frame, which the DWARF names variables +#! from: past the return address and the saved `rbp`. +const rbp_below_frame: i64 = 16; + +#! The most bytes of code one range of a variable holds. +const range_most: u64 = 0xFFFF; + +#! What writing the PDB file keeps. +struct codeview_writer { + var b: &building; + var file: pdb::writer; + var symbols: pdb::symbol_stream; + var checksums: pdb::file_checksums; + var inlinees: pdb::inlinee_lines; + var lines: byte_writer; #! The subsections of each function's lines. + var section: u16; #! The section holding the code, from 1. + var directory: strview; #! The directory the build was in. + var paths: vector; #! The path of each file named, as a debugger finds it. + var file_at: vector; #! Where each source's entry is among the checksums, or `never`. + var ids: vector; #! The ID of each function inlined somewhere, or 0. + var complete: vector; #! The index of each type, by key, or 0. + var declared: vector; #! The index of each struct's declaration, by key, or 0. + var procedure: u32; #! The type every function is given. +} + +#! The path of the PDB file an executable's debugging information is written +#! to: the executable's, with `.pdb` in place of `.exe`, within the directory +#! the build was in where it is relative. +#! @param output The executable's path. +#! @param directory The directory the build was in. +#! @returns The path. +pub def pdb_path_of(output: strview, directory: strview): string { + var stem := output; + if output.length >= 4 { + val ending := output.substr(output.length - 4, 4).lower(); + if ending.view() == ".exe" { + stem = output.substr(0, output.length - 4); + } + } + return $"{stem}.pdb" if is_absolute(stem); + return $"{directory}/{stem}.pdb"; +} + +#! Whether a path is absolute, on Linux or Windows. +#! @param path The path. +#! @returns Whether it is. +def is_absolute(path: strview): bool { + return false if path.length == 0; + return true if path[0] == '/' as u8 || path[0] == '\\' as u8; + return path.length > 1 && path[1] == ':' as u8; +} + +#! The key of the type of a word, which no layout is, of an address of nothing +#! the program says, and of an `f32` held as a real, as DWARF's are. +#! @param this The writer. +#! @returns The key. +def codeview_writer::word_key(&this): u64 { + return this.b.c.program.layouts.length; +} + +#! @copydoc codeview_writer::word_key +def codeview_writer::address_key(&this): u64 { + return this.b.c.program.layouts.length + 1; +} + +#! @copydoc codeview_writer::word_key +def codeview_writer::widened_key(&this): u64 { + return this.b.c.program.layouts.length + 2; +} + +#! Where a source's entry is among the checksums, naming it the first time: +#! its path, within the directory the build was in where it is relative. +#! @param this The writer. +#! @param source The source. +#! @returns Where its entry is. +def codeview_writer::checksum(&mut this, source: u32): u32 { + if this.file_at[source] != never { + return this.file_at[source]; + } + val written := this.b.c.checker.units[source].source.path; + var path := is_absolute(written) ? string::from(written, nothing {}) : $"{this.directory}/{written}"; + val name := this.file.names.offset_of(path.view()); + this.paths.append(move(&mut path)); + val at := this.checksums.file(name); + this.file_at[source] = at; + return at; +} + + +# Types. + +#! The type of an integer of a size. +#! @param size Its bytes. +#! @param signed Whether it is signed. +#! @returns The type. +def integer_type(size: u64, signed: bool): u32 { + if size == 1 { return signed ? pdb::t_int1 : pdb::t_uint1; } + if size == 2 { return signed ? pdb::t_int2 : pdb::t_uint2; } + if size == 4 { return signed ? pdb::t_int4 : pdb::t_uint4; } + return signed ? pdb::t_int8 : pdb::t_uint8; +} + +#! The name of a layout's type, as problems write it. +#! @param this The writer. +#! @param shape The layout. +#! @returns The name. +def codeview_writer::type_name(&this, shape: &layout): string { + if shape.type_id != 0 { + var text := this.b.c.checker.describe(shape.type_id); + if text.length != 0 { + return move(&mut text); + } + } + if shape.name != 0 { + return string::from(this.b.c.checker.names.text(shape.name), nothing {}); + } + return string::from("?", nothing {}); +} + +#! The unique name of a layout's type, which tells it apart from another of the +#! same name, as one generic's two instances. +#! @param key The type's key. +#! @returns The name. +def unique_name(key: u64): string { + return $"sakura@{key}"; +} + +#! Whether a layout is written as a struct, which a pointer names by its +#! declaration, so a struct reaching itself through one is written. +#! @param shape The layout. +#! @returns Whether it is. +def written_as_struct(shape: &layout): bool { + return shape.kind == lk::record || shape.kind == lk::variant || shape.kind == lk::trait_reference || shape.kind == lk::function; +} + +#! The index of a type, writing it and those it names the first time. +#! @param this The writer. +#! @param key The type's key: its layout, or one past the layouts or two or three. +#! @returns The index. +def codeview_writer::type_of(&mut this, key: u64): u32 { + return this.complete[key] if this.complete[key] != 0; + val made := this.make_type(key); + this.complete[key] = made; + return made; +} + +#! The index of what a pointer or reference reaches: a struct's declaration, +#! or the type itself. +#! @param this The writer. +#! @param key The key of what it reaches. +#! @returns The index. +def codeview_writer::reached(&mut this, key: u64): u32 { + val shape: layout = this.b.c.program.layouts[key]; + return this.type_of(key) if !written_as_struct(&shape); + if this.declared[key] == 0 { + val name := this.type_name(&shape); + val unique := unique_name(key); + this.declared[key] = this.file.types.structure(name.view(), unique.view(), 0, 0, 0, true); + } + return this.declared[key]; +} + +#! Adds the members of a struct or union: each field but those holding nothing, +#! at its offset. +#! @param this The writer. +#! @param shape The layout. +#! @param list The members. +def codeview_writer::fields(&mut this, shape: &layout, list: &mut pdb::field_list): void { + for f in 0..shape.count { + val field: slot_field = this.b.c.program.fields[shape.fields as u64 + f as u64]; + continue if field.layout == never || this.b.c.program.layouts[field.layout].kind == lk::empty; + val type_index := this.type_of(field.layout as u64); + list.member(type_index, field.offset, this.b.c.checker.names.text(field.name)); + } +} + +#! Adds a struct's record, its members given. +#! @param this The writer. +#! @param key The type's key. +#! @param shape The layout. +#! @param list The members. +#! @returns Its index. +def codeview_writer::structure(&mut this, key: u64, shape: &layout, list: &pdb::field_list): u32 { + val name := this.type_name(shape); + val unique := unique_name(key); + val members := this.file.types.fields(list); + return this.file.types.structure(name.view(), unique.view(), members, list.count, shape.size, false); +} + +#! Writes a type's record, and those it names. +#! @param this The writer. +#! @param key The type's key. +#! @returns Its index. +def codeview_writer::make_type(&mut this, key: u64): u32 { + return pdb::t_uint8 if key == this.word_key(); + return pdb::t_64p | pdb::t_void if key == this.address_key(); + return pdb::t_real64 if key == this.widened_key(); + + val program := &this.b.c.program; + val shape: layout = program.layouts[key]; + var list := pdb::field_list::new(); + match shape.kind { + # An enum is laid out as its integer, with a field for each member whose + # offset is the member's value. + lk::signed, lk::unsigned => { + val underlying := integer_type(shape.size, shape.kind == lk::signed); + return underlying if shape.name == 0 || shape.count == 0; + for f in 0..shape.count { + val field: slot_field = program.fields[shape.fields as u64 + f as u64]; + list.enumerate(field.offset as i64, this.b.c.checker.names.text(field.name)); + } + val name := this.type_name(&shape); + val unique := unique_name(key); + val members := this.file.types.fields(&list); + return this.file.types.enumeration(name.view(), unique.view(), underlying, members, list.count, false); + } + lk::floating => return shape.size == 4 ? pdb::t_real32 : pdb::t_real64; + lk::boolean => return pdb::t_bool08; + + # A reference is the address of what it refers to. + lk::pointer, lk::reference => { + if shape.element == 0 || program.layouts[shape.element - 1].kind == lk::empty { + return pdb::t_64p | pdb::t_void; + } + val reached := this.reached(shape.element as u64 - 1); + return this.file.types.pointer(reached, shape.kind == lk::reference); + } + + # A reference to a trait is a reference, then the index of the vtable. + lk::trait_reference => { + list.member(pdb::t_64p | pdb::t_void, 0, "address"); + list.member(pdb::t_uint8, 8, "vtable"); + return this.structure(key, &shape, &list); + } + + # A function value is its function's index plus one, then its environment. + lk::function => { + list.member(pdb::t_uint8, 0, "function"); + list.member(pdb::t_64p | pdb::t_void, 8, "environment"); + return this.structure(key, &shape, &list); + } + lk::fixed => { + val element := this.type_of(shape.element as u64 - 1); + return this.file.types.array(element, shape.size); + } + lk::record => { + this.fields(&shape, &mut list); + return this.structure(key, &shape, &list); + } + + # A union laid out without a tag is its fields over one another, the empty + # one held where the first word is null. One with a tag is the tag, then each + # field over one another past it, as a struct holding an unnamed union is. + lk::variant => { + if shape.niche == 0 { + var tags := pdb::field_list::new(); + for f in 0..shape.count { + val field: slot_field = program.fields[shape.fields as u64 + f as u64]; + tags.enumerate(f as i64, this.b.c.checker.names.text(field.name)); + } + val name := this.type_name(&shape); + val tag_name := $"{name}::tag"; + val tag_unique := $"sakura@{key}.tag"; + val members := this.file.types.fields(&tags); + val tag := this.file.types.enumeration(tag_name.view(), tag_unique.view(), pdb::t_uint8, members, tags.count, false); + list.member(tag, 0, "tag"); + } + this.fields(&shape, &mut list); + return this.structure(key, &shape, &list); + } + else => { + return this.structure(key, &shape, &list); + } + } + return pdb::t_notype; +} + +#! Writes the definition of each struct declared only, so each declaration is +#! found to one, and those their definitions declare in turn. +#! @param this The writer. +def codeview_writer::define_declared(&mut this): void { + var again := true; + while again { + again = false; + for key in 0..this.declared.length { + if this.declared[key] != 0 && this.complete[key] == 0 { + _ = this.type_of(key); + again = true; + } + } + } +} + + +# Variables. + +#! The code of a function from one offset to another, in ranges of at most +#! `range_most` bytes, each given to `each`. +#! @param this The writer. +#! @param index The function. +#! @param from Where it begins, within the function's code. +#! @param to Where it ends. +#! @param out The ranges, added. +def codeview_writer::ranges_of(&this, index: u32, from: u64, to: u64, out: &mut vector): void { + var at := from; + while at < to { + val length := to - at > range_most ? range_most : to - at; + out.append(pdb::code_range { section = this.section, offset = (this.b.starts[index] + at) as u32, length = length as u16 }); + at += length; + } +} + +#! Writes a variable its frame holds: its name and type, and where it is from +#! `rbp`, wherever its scope is, or over the code its scope covers. One of an +#! object of the heap is the address of that object, which the frame holds. +#! @param this The writer. +#! @param index The function. +#! @param each The variable. +#! @param scoped Whether it is where its scope's code is, rather than wherever +#! its scope is, as a parameter is. +def codeview_writer::framed_variable(&mut this, index: u32, each: &placed_variable, scoped: bool): void { + var type_index := this.type_of(each.layout as u64); + if each.boxed { + type_index = this.file.types.pointer(type_index, false); + } + this.symbols.local(type_index, each.param ? pdb::local_parameter : 0, this.b.c.checker.names.text(each.name)); + val offset := (rbp_below_frame + each.offset) as i32; + if !scoped { + this.symbols.in_frame_throughout(offset); + return; + } + var ranges := vector::::new(); + this.ranges_of(index, each.from as u64, each.to as u64, &mut ranges); + for &over in ranges { + this.symbols.in_frame(offset, over); + } +} + +#! Whether a word of a variable held in values can be named where it is over a +#! range: in a register, or, but for the address of an object of the heap, in +#! the frame. A word known, as a constant, can't be. +#! @param kind Where the word is, as a `word_spot`. +#! @param boxed Whether the word is the address of the object the variable is in. +#! @returns Whether it can. +def nameable(kind: u8, boxed: bool): bool { + return kind == word_spot::gpr as u8 || kind == word_spot::xmm as u8 || (kind == word_spot::frame as u8 && !boxed); +} + +#! Writes a variable held in values: its name and type, then where each of its +#! words is over each range of code it is somewhere in, where that can be +#! named. One named nowhere is said to be optimized out. +#! @param this The writer. +#! @param index The function. +#! @param each The variable. +def codeview_writer::listed_variable(&mut this, index: u32, each: &placed_variable): void { + val shape: layout = this.b.c.program.layouts[each.layout]; + val widened := !each.boxed && !each.narrow && shape.kind == lk::floating && shape.size == 4; + val type_index := this.type_of(widened ? this.widened_key() : each.layout as u64); + val words := each.boxed ? 1u : word_count(&shape) as u64; + + var named := false; + for r in each.ranges..each.ranges + each.count { + val range: located_range = this.b.debug.ranges[r as u64]; + for w in 0..words { + named = named || nameable(range.kinds[w], each.boxed); + } + } + var flags: u16 = each.param ? pdb::local_parameter : 0; + if !named { + flags = flags | 0x0100; # Optimized out. + } + this.symbols.local(type_index, flags, this.b.c.checker.names.text(each.name)); + + var ranges := vector::::new(); + for r in each.ranges..each.ranges + each.count { + val range: located_range = this.b.debug.ranges[r as u64]; + ranges.clear(); + this.ranges_of(index, range.from as u64, range.to as u64, &mut ranges); + for &over in ranges { + for w in 0..words { + val kind := range.kinds[w]; + val spot := range.spots[w]; + continue if !nameable(kind, each.boxed); + if words > 1 { + # Each word of a variable of several is a part of it, where it is in + # a register; the frame holds none of a part's. + if kind == word_spot::gpr as u8 { + this.symbols.part_in_register(pdb::amd64_register(spot as u8, 8), (8 * w) as u32, over); + } else if kind == word_spot::xmm as u8 { + this.symbols.part_in_register(pdb::amd64_xmm(spot as u8), (8 * w) as u32, over); + } + } else if kind == word_spot::gpr as u8 { + if each.boxed { + this.symbols.through_register(pdb::amd64_register(spot as u8, 8), 0, over); + } else { + val width := shape.size == 1 || shape.size == 2 || shape.size == 4 ? shape.size : 8; + this.symbols.in_register(pdb::amd64_register(spot as u8, width), over); + } + } else if kind == word_spot::xmm as u8 { + this.symbols.in_register(pdb::amd64_xmm(spot as u8), over); + } else { + this.symbols.in_frame((rbp_below_frame + spot as i64) as i32, over); + } + } + } + } +} + +#! Writes the variables of a function's own code, or of a site inlined into it: +#! its parameters, then its locals. +#! @param this The writer. +#! @param index The function. +#! @param site One more than the site, or 0 for the function's own code. +def codeview_writer::variables(&mut this, index: u32, site: u32): void { + val debug := &this.b.debug; + for v in debug.variable_first[index]..debug.variable_first[index + 1] { + val each: placed_variable = debug.variables[v as u64]; + continue if each.site != site || this.b.c.program.layouts[each.layout].kind == lk::empty; + if each.held { + this.listed_variable(index, &each); + } else if each.param || site != 0 { + this.framed_variable(index, &each, false); + } else if each.to > each.from { + this.framed_variable(index, &each, true); + } + } +} + + +# Inline sites. + +#! The ID of a function inlined somewhere, naming where it begins among the +#! inlinees' lines the first time. +#! @param this The writer. +#! @param function The function. +#! @returns Its ID. +def codeview_writer::inlinee(&mut this, function: u32): u32 { + return this.ids[function] if this.ids[function] != 0; + val inlined := &this.b.c.program.functions[function]; + val id := this.file.ids.function_id(0, this.procedure, inlined.name.view()); + var source: u32 = 0; + val located := this.b.source_of(function, 0, &mut source); + this.inlinees.add(id, this.checksum(source), located.line as u32); + this.ids[function] = id; + return id; +} + +#! The site inlined directly within another that a site is within, or the site +#! itself where it is directly within. +#! @param sites The function's inline sites. +#! @param site One more than the site. +#! @param outer One more than the other, or 0 for the function's own code. +#! @returns One more than the site directly within. +def directly_within(sites: &vector, site: u32, outer: u32): u32 { + var at := site; + var depth: u64 = 0; + while at != 0 && depth <= sites.length { + val parent := sites[at as u64 - 1].parent; + return at if parent == outer; + at = parent; + depth++; + } + return site; +} + +#! Whether a row of a function's line table holds code: no later one begins +#! where it does, so it is the line of the code there, as DWARF's readers take +#! the last row at an offset. +#! @param this The writer. +#! @param row The row. +#! @param last One past the function's last row. +#! @returns Whether it does. +def codeview_writer::holds_code(&this, row: u64, last: u64): bool { + return row + 1 >= last || this.b.rows[row + 1].offset != this.b.rows[row].offset; +} + +#! Writes the sites inlined directly within a site of a function, or within its +#! own code, each with the annotations of the code it is: each run of its code, +#! and the line of each, where the code of a site within it is at the line it +#! was called at. Each holds its variables and the sites within it. +#! @param this The writer. +#! @param index The function. +#! @param parent One more than the site, or 0. +def codeview_writer::sites(&mut this, index: u32, parent: u32): void { + val sites := &this.b.c.program.functions[index].body.sites; + val first := this.b.row_first[index] as u64; + val last := this.b.row_first[index + 1] as u64; + val size := this.b.ends[index] - this.b.starts[index]; + for k in 0..sites.length { + val site: inline_site = sites[k]; + continue if site.parent != parent; + val number := k as u32 + 1; + + # The rows holding code from the site's first to its last. A site with + # none is no code's, as the DWARF says too. + var begins := last; + var ends := last; + for r in first..last { + continue if !this.holds_code(r, last) || !within(sites, this.b.rows[r].site, number); + if begins == last { + begins = r; + } + ends = r + 1; + } + continue if begins == last; + + var file: u32 = 0; + val start := this.b.source_of(site.function, 0, &mut file); + val inlinee := this.inlinee(site.function); + var notes := pdb::annotations::new(this.checksum(file), start.line as u32); + for r in begins..ends { + continue if !this.holds_code(r, last); + val row: line_row = this.b.rows[r]; + if !within(sites, row.site, number) { + notes.away(row.offset as u32); + continue; + } + # Code of a site within this one is at the line that site was called at. + var at := row.at; + if row.site != number { + at = sites[directly_within(sites, row.site, number) as u64 - 1].at; + } + var source: u32 = 0; + val located := this.b.source_of(index, at, &mut source); + notes.at_line(row.offset as u32, this.checksum(source), located.line as u32); + } + val end := ends < last ? this.b.rows[ends].offset : size; + notes.finish(end as u32); + + this.symbols.inline_site(inlinee, notes.bytes.view()); + this.variables(index, number); + this.sites(index, number); + this.symbols.end(); + } +} + + +# Functions. + +#! A line of a function's code. +struct code_line { + var offset: u64; #! Where its code begins, within the function's. + var file: u32; #! Its file, as its entry among the checksums. + var line: u32; + var column: u32; +} + +#! Writes the lines of a function's code: each row of its own code at its own +#! line, and the code of each site inlined into it at the line it was called +#! at, once for each run. Each run of lines of one file is a part of the code +#! of its own, so a reader taking one file's lines alone finds each where the +#! code is, as a function whose globals are from several files has. +#! @param this The writer. +#! @param index The function. +def codeview_writer::function_lines(&mut this, index: u32): void { + val sites := &this.b.c.program.functions[index].body.sites; + val size := this.b.ends[index] - this.b.starts[index]; + var found := vector::::new(); + val rows_end := this.b.row_first[index + 1] as u64; + for r in this.b.row_first[index]..this.b.row_first[index + 1] { + continue if !this.holds_code(r as u64, rows_end); + val row: line_row = this.b.rows[r as u64]; + var at := row.at; + if row.site != 0 { + at = sites[directly_within(sites, row.site, 0) as u64 - 1].at; + } + var source: u32 = 0; + val located := this.b.source_of(index, at, &mut source); + val made := code_line { offset = row.offset, file = this.checksum(source), line = located.line as u32, column = located.column as u32 }; + if row.site != 0 && found.length != 0 { + val last := found.last(); + continue if made.file == last.file && made.line == last.line && made.column == last.column; + } + found.append(made); + } + + var first: u64 = 0; + while first < found.length { + var end := first + 1; + while end < found.length && found[end].file == found[first].file { + end++; + } + val begins := found[first].offset; + val ends := end < found.length ? found[end].offset : size; + var lines := pdb::function_lines::new(this.section, (this.b.starts[index] + begins) as u32, (ends - begins) as u32); + for k in first..end { + val each: code_line = found[k]; + lines.line(each.file, (each.offset - begins) as u32, each.line, each.column as u16); + } + lines.finish(); + pdb::subsection(&mut this.lines, pdb::debug_s_lines, lines.bytes.view()); + first = end; + } +} + +#! Writes a function: its procedure, with its frame, its variables, and the +#! sites inlined into it, the global naming it, and the lines of its code. +#! @param this The writer. +#! @param index The function. +def codeview_writer::function(&mut this, index: u32): void { + val function := &this.b.c.program.functions[index]; + val debug := &this.b.debug; + val size := this.b.ends[index] - this.b.starts[index]; + var leaving := size; + val returns := debug.return_first[index + 1]; + if returns > debug.return_first[index] { + leaving = debug.returns[returns as u64 - 1] as u64; + } + var saved: u32 = 0; + for &r in kept_gprs { + if (debug.saves[index] & (1u << r as u64) as u32) != 0 { + saved += 8; + } + } + val at := this.symbols.procedure( + true, function.name.view(), this.procedure, this.section, this.b.starts[index] as u32, size as u32, + debug.bodies[index], leaving as u32, pdb::proc_has_frame_pointer + ); + this.symbols.frame(debug.frames[index], saved, pdb::frame_locals_rbp | pdb::frame_params_rbp); + this.variables(index, 0); + this.sites(index, 0); + this.symbols.end(); + this.file.procedure(function.name.view(), 1, at, true); + this.function_lines(index); +} + + +# The file. + +#! Writes the PDB file of an executable's debugging information, then stamps +#! the executable, which names the file by its path already, with its GUID. +#! @param b The building. +#! @param exe The executable's file. +#! @param path The PDB file's path. +#! @param directory The directory the build was in. +#! @returns Whether the file was written. +pub def describe_pdb(b: &building, exe: &mut byte_writer, path: strview, directory: strview): bool { + val program := &b.c.program; + val keys := program.layouts.length + 3; + var w := codeview_writer { + b = b, + file = pdb::writer::new(), + symbols = pdb::symbol_stream::new(), + checksums = pdb::file_checksums::new(), + inlinees = pdb::inlinee_lines::new(), + lines = byte_writer::new(), + section = 0, + directory = directory, + paths = vector::::new(), + file_at = vector::::new(), + ids = vector::::new(), + complete = vector::::new(), + declared = vector::::new(), + procedure = 0 + }; + w.file_at.resize(b.c.checker.units.length); + for i in 0..w.file_at.length { + w.file_at[i] = never; + } + w.ids.resize(program.functions.length); + w.complete.resize(keys); + w.declared.resize(keys); + + # The sections, as the executable's headers say, and the one of the code. + w.file.sections = pe::section_headers(exe.view()); + for k in 0..w.file.sections.length / 40 { + if w.file.sections.get_u32(40 * k + 12) as u64 == b.text_base - base_address { + w.section = (k + 1) as u16; + } + } + return false if w.section == 0; + + # The module, compiled from the main file, its functions' type that of a + # function taking nothing, as a debugger can't call them anyway. + val main_file := program.functions[program.main].file; + _ = w.checksum(main_file); + val module_name := string::from(w.paths[0].view(), nothing {}); + w.symbols.object_name(module_name.view()); + val version: u16[3] = [1, 0, 0]; + w.symbols.compiler(pdb::language_cxx, pdb::cv_machine_x64, version, "sakura"); + val arguments := w.file.types.arguments(span::::empty()); + w.procedure = w.file.types.procedure(pdb::t_void, arguments, 0); + + for i in 0..program.functions.length { + continue if b.starts[i] == b.missing || b.ends[i] <= b.starts[i]; + w.function(i as u32); + } + w.define_declared(); + + # The module's lines: each function's, then the files they name, then where + # each function inlined begins. + pdb::subsection(&mut w.lines, pdb::debug_s_file_checksums, w.checksums.bytes.view()); + if w.inlinees.count != 0 { + pdb::subsection(&mut w.lines, pdb::debug_s_inlinee_lines, w.inlinees.bytes.view()); + } + var files := vector::::new(); + for &each in w.paths { + files.append(each.view()); + } + val ours := w.file.add_module(module_name.view(), module_name.view(), &mut w.symbols.bytes, &mut w.lines, files.view()); + + # The linker's module, naming each section. + var linker := pdb::symbol_stream::new(); + linker.object_name("* Linker *"); + linker.compiler(pdb::language_link, pdb::cv_machine_x64, version, "sakura"); + linker.sections(&w.file.sections); + var no_lines := byte_writer::new(); + _ = w.file.add_module("* Linker *", "", &mut linker.bytes, &mut no_lines, span::::empty()); + + # Every section the system keeps once loaded is the module's. + for k in 0..w.file.sections.length / 40 { + val characteristics := w.file.sections.get_u32(40 * k + 36); + continue if (characteristics & 0x02000000) != 0; + w.file.contribute(ours, (k + 1) as u16, 0, w.file.sections.get_u32(40 * k + 8), characteristics); + } + + # The names a debugger finds the code by, as disassemblers show them. + var named := vector::::new(); + b.name_code(&mut named); + for &each in named { + w.file.public(each.name, w.section, (each.address - b.text_base) as u32, pdb::public_function | pdb::public_code); + } + + val bytes := w.file.file(); + return false if !write_bytes(path, bytes.view(), 0o644); + return pe::stamp_codeview(exe, w.file.guid, w.file.signature); +} diff --git a/native/dwarf.sakura b/native/dwarf.sakura new file mode 100644 index 00000000..7aa44755 --- /dev/null +++ b/native/dwarf.sakura @@ -0,0 +1,1159 @@ +#! @file dwarf.sakura +#! @author John Christman (sorakatadzuma@gmail.com) +#! @copyright Malunal Studios, LLC. +#! @license MIT +#! +#! Contains the writer of debugging information, as DWARF 5: the line table of +#! the code, its functions and the calls inlined into them, how a debugger +#! unwinds their frames, and the variables of code built with its locals kept +#! in cells, with their types. It goes to a file of its own beside the +#! executable, OUTPUT.petal, which describes the executable's segments without +#! holding them. The executable names that file, with its checksum, and both +#! hold the note naming the build, which debuggers match the two by. +#! +#! Every function makes its frame of `rbp` as it begins, saving the registers +#! a call keeps that it uses just below it, and leaves it with `leave` just +#! before each `ret`, so a debugger unwinds each the same way, and a variable is +#! where it is from the frame's canonical address. + +import std::io; +import sakura::compiler; +import binary::amd64; +import binary::dwarf; +import binary::elf; +module sakura::native; + + +# Where every function's code has made its frame: past `push rbp`, then past +# `mov rbp, rsp`. +const framed_at: u64 = 1; +const based_at: u64 = 4; + +# The kinds of entries, each with the attributes it has, in order. +const ab_unit: u64 = 1; +const ab_subprogram: u64 = 2; +const ab_abstract: u64 = 3; +const ab_concrete: u64 = 4; +const ab_inlined: u64 = 5; +const ab_scattered: u64 = 6; +const ab_parameter: u64 = 7; +const ab_variable: u64 = 8; +const ab_block: u64 = 9; +const ab_base: u64 = 10; +const ab_struct: u64 = 11; +const ab_member: u64 = 12; +const ab_anonymous: u64 = 13; +const ab_pointer: u64 = 14; +const ab_address: u64 = 15; +const ab_reference: u64 = 16; +const ab_array: u64 = 17; +const ab_subrange: u64 = 18; +const ab_enum: u64 = 19; +const ab_enumerator: u64 = 20; +const ab_union: u64 = 21; +const ab_unspecified: u64 = 22; +const ab_listed_parameter: u64 = 23; #! A parameter held in values, where its location list says. +const ab_listed_variable: u64 = 24; #! A variable held in values, where its location list says. + +#! What debugging information needs of each function's code, noted as the code +#! is selected. +pub struct debugging { + var bodies: vector; #! Where each function's prologue ends, within its code. + var returns: vector; #! Past each `leave`, within its function's code, each function's after the one before. + var return_bytes: vector; #! The bytes of the instruction after each `leave`, which leaves the function. + var return_first: vector; #! Where each function's are in `returns`. + var saves: vector; #! The registers each function saves below its frame pointer, one bit each by number, in the order `kept_gprs` lists them from the highest. + var saved_at: vector; #! Where each function's code has saved them. + var frames: vector; #! The bytes of each function's frame below its frame pointer, those saved among them. + var variables: vector; #! The variables of each function, each function's after the one before. + var variable_first: vector; #! Where each function's are in `variables`. + var ranges: vector; #! The ranges of the variables held in values. +} + +#! A variable of a function's code: where its frame holds it, or, where it is +#! held in values, the ranges of code it is somewhere in. +pub struct placed_variable { + var name: u32; #! The ID of its name. + var at: u64; #! Where it is declared: one more than the file, then the byte. + var layout: u32; #! Its layout. + var offset: i64; #! Where its memory begins, from the frame's canonical address. + var param: bool; #! Whether it is a parameter. + var boxed: bool; #! Whether its memory, or its value, holds the address of the object of the heap holding it. + var held: bool; #! Whether it is held in values, where its ranges say. + var narrow: bool; #! Of an `f32` held in values, whether it is described as one, as most of its values are held, rather than as the `f64` they are held as. + var site: u32; #! One more than the inline site it was declared in, or 0. + var from: u32; #! Where the code its scope covers begins, within the function's code, + var to: u32; #! and where it ends. + var ranges: u32; #! Of one held in values, its first range in the ranges of debugging information, + var count: u32; #! and how many. +} + +#! Where a variable held in values is over a range of code: each of its words. +pub struct located_range { + var from: u32; #! Where the range begins, within the function's code, + var to: u32; #! and ends. + var kinds: u8[3]; #! Where each word is, as a `word_spot`. + var spots: u64[3]; #! The register, the offset from the frame's canonical address, or the bits. +} + +#! Where a word of a variable is. +pub enum word_spot : u8 { + nowhere, #! Nowhere known. + gpr, #! In a general register. + xmm, #! In an SSE register. + frame, #! In the frame, at an offset from its canonical address. + word, #! A word known. + real, #! A real known, by its bits. +} + +#! Makes what debugging information needs, with nothing noted yet. +#! @returns What it needs. +pub def debugging::new(): debugging { + return debugging { + bodies = vector::::new(), + returns = vector::::new(), + return_bytes = vector::::new(), + return_first = vector::::new(), + saves = vector::::new(), + saved_at = vector::::new(), + frames = vector::::new(), + variables = vector::::new(), + variable_first = vector::::new(), + ranges = vector::::new() + }; +} + +#! Makes room for what debugging information needs of each function. +#! @param this What it needs. +#! @param count How many functions there are. +pub def debugging::resize(&mut this, count: u64): void { + this.bodies.resize(count); + this.return_first.resize(count + 1); + this.saves.resize(count); + this.saved_at.resize(count); + this.frames.resize(count); + this.variable_first.resize(count + 1); +} + + +#! Writes the abbreviations: of each kind of entry, its tag, whether it has +#! children, and each attribute it has with its form, in order. +#! @param out The section. +def abbreviations(out: &mut byte_writer): void { + val unit_pairs: u64[14] = [ + dw_at_producer, dw_form_strp, + dw_at_language, dw_form_data2, + dw_at_name, dw_form_line_strp, + dw_at_comp_dir, dw_form_line_strp, + dw_at_low_pc, dw_form_addr, + dw_at_high_pc, dw_form_data8, + dw_at_stmt_list, dw_form_sec_offset + ]; + abbreviation(out, ab_unit, dw_tag_compile_unit, true, unit_pairs[:]); + val subprogram_pairs: u64[16] = [ + dw_at_name, dw_form_strp, + dw_at_decl_file, dw_form_udata, + dw_at_decl_line, dw_form_udata, + dw_at_external, dw_form_flag_present, + dw_at_calling_convention, dw_form_data1, + dw_at_low_pc, dw_form_addr, + dw_at_high_pc, dw_form_data8, + dw_at_frame_base, dw_form_exprloc + ]; + abbreviation(out, ab_subprogram, dw_tag_subprogram, true, subprogram_pairs[:]); + val abstract_pairs: u64[12] = [ + dw_at_name, dw_form_strp, + dw_at_decl_file, dw_form_udata, + dw_at_decl_line, dw_form_udata, + dw_at_external, dw_form_flag_present, + dw_at_calling_convention, dw_form_data1, + dw_at_inline, dw_form_data1 + ]; + abbreviation(out, ab_abstract, dw_tag_subprogram, false, abstract_pairs[:]); + val concrete_pairs: u64[8] = [ + dw_at_abstract_origin, dw_form_ref4, + dw_at_low_pc, dw_form_addr, + dw_at_high_pc, dw_form_data8, + dw_at_frame_base, dw_form_exprloc + ]; + abbreviation(out, ab_concrete, dw_tag_subprogram, true, concrete_pairs[:]); + val inlined_pairs: u64[12] = [ + dw_at_abstract_origin, dw_form_ref4, + dw_at_low_pc, dw_form_addr, + dw_at_high_pc, dw_form_data8, + dw_at_call_file, dw_form_udata, + dw_at_call_line, dw_form_udata, + dw_at_call_column, dw_form_udata + ]; + abbreviation(out, ab_inlined, dw_tag_inlined_subroutine, true, inlined_pairs[:]); + val scattered_pairs: u64[10] = [ + dw_at_abstract_origin, dw_form_ref4, + dw_at_ranges, dw_form_sec_offset, + dw_at_call_file, dw_form_udata, + dw_at_call_line, dw_form_udata, + dw_at_call_column, dw_form_udata + ]; + abbreviation(out, ab_scattered, dw_tag_inlined_subroutine, true, scattered_pairs[:]); + val local_pairs: u64[10] = [ + dw_at_name, dw_form_strp, + dw_at_decl_file, dw_form_udata, + dw_at_decl_line, dw_form_udata, + dw_at_type, dw_form_ref4, + dw_at_location, dw_form_exprloc + ]; + abbreviation(out, ab_parameter, dw_tag_formal_parameter, false, local_pairs[:]); + abbreviation(out, ab_variable, dw_tag_variable, false, local_pairs[:]); + val block_pairs: u64[4] = [ + dw_at_low_pc, dw_form_addr, + dw_at_high_pc, dw_form_data8 + ]; + abbreviation(out, ab_block, dw_tag_lexical_block, true, block_pairs[:]); + val base_pairs: u64[6] = [ + dw_at_name, dw_form_strp, + dw_at_encoding, dw_form_data1, + dw_at_byte_size, dw_form_udata + ]; + abbreviation(out, ab_base, dw_tag_base_type, false, base_pairs[:]); + val named_pairs: u64[4] = [ + dw_at_name, dw_form_strp, + dw_at_byte_size, dw_form_udata + ]; + abbreviation(out, ab_struct, dw_tag_structure_type, true, named_pairs[:]); + val member_pairs: u64[6] = [ + dw_at_name, dw_form_strp, + dw_at_type, dw_form_ref4, + dw_at_data_member_location, dw_form_udata + ]; + abbreviation(out, ab_member, dw_tag_member, false, member_pairs[:]); + val anonymous_pairs: u64[4] = [ + dw_at_type, dw_form_ref4, + dw_at_data_member_location, dw_form_udata + ]; + abbreviation(out, ab_anonymous, dw_tag_member, false, anonymous_pairs[:]); + val pointer_pairs: u64[4] = [ + dw_at_type, dw_form_ref4, + dw_at_byte_size, dw_form_udata + ]; + abbreviation(out, ab_pointer, dw_tag_pointer_type, false, pointer_pairs[:]); + val sized_pairs: u64[2] = [ + dw_at_byte_size, dw_form_udata + ]; + abbreviation(out, ab_address, dw_tag_pointer_type, false, sized_pairs[:]); + abbreviation(out, ab_reference, dw_tag_reference_type, false, pointer_pairs[:]); + val array_pairs: u64[2] = [ + dw_at_type, dw_form_ref4 + ]; + abbreviation(out, ab_array, dw_tag_array_type, true, array_pairs[:]); + val subrange_pairs: u64[2] = [ + dw_at_count, dw_form_udata + ]; + abbreviation(out, ab_subrange, dw_tag_subrange_type, false, subrange_pairs[:]); + abbreviation(out, ab_enum, dw_tag_enumeration_type, true, named_pairs[:]); + val enumerator_pairs: u64[4] = [ + dw_at_name, dw_form_strp, + dw_at_const_value, dw_form_sdata + ]; + abbreviation(out, ab_enumerator, dw_tag_enumerator, false, enumerator_pairs[:]); + abbreviation(out, ab_union, dw_tag_union_type, true, sized_pairs[:]); + val unspecified_pairs: u64[2] = [ + dw_at_name, dw_form_strp + ]; + abbreviation(out, ab_unspecified, dw_tag_unspecified_type, false, unspecified_pairs[:]); + val listed_pairs: u64[10] = [ + dw_at_name, dw_form_strp, + dw_at_decl_file, dw_form_udata, + dw_at_decl_line, dw_form_udata, + dw_at_type, dw_form_ref4, + dw_at_location, dw_form_sec_offset + ]; + abbreviation(out, ab_listed_parameter, dw_tag_formal_parameter, false, listed_pairs[:]); + abbreviation(out, ab_listed_variable, dw_tag_variable, false, listed_pairs[:]); + out.byte(0); +} + + +# The writer. + +#! What writing debugging information keeps. +struct dwarf_writer { + var b: &building; + var info: byte_writer; + var abbrev: byte_writer; + var lines: byte_writer; + var program: line_program; #! The line program, which follows the table of the files it names. + var strings: string_table; + var line_strings: string_table; + var frame: byte_writer; + var ranges: byte_writer; + var locations: byte_writer; #! The location lists of the variables held in values. + var files: vector; #! The source of each file numbered, from 1. + var numbers: vector; #! The number of each source, or 0. + var types: vector; #! Where the entry of each type is in `info`, by key, or 0. + var queued: vector; #! Whether the entry of each type is to be written. + var queue: vector; #! The types whose entries are to be written, by key. + var fixups: fixup_list; #! Where each reference to a type written before the type is in `info`, and the type's key. + var abstracts: vector; #! Where the abstract entry of each function inlined is in `info`, or 0. +} + +#! The key of the type of a word, which no layout is, and that of an address +#! of nothing the program says: one past the layouts, and two past. +#! @param this The writer. +#! @returns The key. +def dwarf_writer::word_key(&this): u64 { + return this.b.c.program.layouts.length; +} + +#! @copydoc dwarf_writer::word_key +def dwarf_writer::address_key(&this): u64 { + return this.b.c.program.layouts.length + 1; +} + +#! The key of the type of an `f32` held as a real, as optimized code holds one +#! in a register or a slot: the eight bytes of a double. +#! @param this The writer. +#! @returns The key. +def dwarf_writer::widened_key(&this): u64 { + return this.b.c.program.layouts.length + 2; +} + +#! Where a string is in a table of strings, adding it once. +#! @param this The writer. +#! @param line Whether the table is that of the line table's strings. +#! @param text The string. +#! @returns Where. +def dwarf_writer::string_of(&mut this, line: bool, text: strview): u32 { + return line ? this.line_strings.offset_of(text) : this.strings.offset_of(text); +} + +#! Writes a reference to a string. +#! @param this The writer. +#! @param text The string. +def dwarf_writer::name(&mut this, text: strview): void { + val at := this.string_of(false, text); + this.info.u32(at as u64); +} + +#! The number of a source among the files the line table names, from 1. +#! @param this The writer. +#! @param source The source. +#! @returns Its number. +def dwarf_writer::file(&mut this, source: u32): u64 { + if this.numbers[source] == 0 { + this.files.append(source); + this.numbers[source] = this.files.length as u32; + } + return this.numbers[source] as u64; +} + +#! Writes where something is declared: its file's number, then its line. +#! @param this The writer. +#! @param source The file. +#! @param byte Where in it. +def dwarf_writer::declared(&mut this, source: u32, byte: u32): void { + val number := this.file(source); + val line := this.b.c.checker.units[source].source.lines.place_of(byte).line; + uleb(&mut this.info, number); + uleb(&mut this.info, line as u64); +} + + +# Types. + +#! Writes a reference to the entry of a type, which is written later where it +#! is not yet. +#! @param this The writer. +#! @param key The type's key: its layout, or one past the layouts or two. +def dwarf_writer::type_ref(&mut this, key: u64): void { + if this.types[key] != 0 { + this.info.u32(this.types[key] as u64); + return; + } + this.fixups.add(this.info.length, key as u32); + this.info.u32(0); + return if this.queued[key]; + this.queued[key] = true; + this.queue.append(key as u32); +} + +#! Writes the name of a layout's type, as problems write it. +#! @param this The writer. +#! @param shape The layout. +def dwarf_writer::type_name(&mut this, shape: &layout): void { + if shape.type_id != 0 { + val text := this.b.c.checker.describe(shape.type_id); + if text.length != 0 { + this.name(text.view()); + return; + } + } + if shape.name != 0 { + this.name(this.b.c.checker.names.text(shape.name)); + return; + } + this.name("?"); +} + +#! Writes a member of a struct. +#! @param this The writer. +#! @param name Its name. +#! @param key The key of its type. +#! @param offset Where it begins. +def dwarf_writer::member(&mut this, name: strview, key: u64, offset: u64): void { + uleb(&mut this.info, ab_member); + this.name(name); + this.type_ref(key); + uleb(&mut this.info, offset); +} + +#! Writes the members of a struct or union: each field but those holding +#! nothing, at its offset less one. +#! @param this The writer. +#! @param shape The layout. +#! @param less What each offset is less. +def dwarf_writer::fields(&mut this, shape: &layout, less: u64): void { + val program := &this.b.c.program; + for f in 0..shape.count { + val field: slot_field = program.fields[shape.fields as u64 + f as u64]; + continue if field.layout == never || program.layouts[field.layout].kind == lk::empty; + this.member(this.b.c.checker.names.text(field.name), field.layout as u64, field.offset - less); + } +} + +#! Writes the entry of a type. +#! @param this The writer. +#! @param key The type's key. +def dwarf_writer::write_type(&mut this, key: u64): void { + this.types[key] = this.info.length as u32; + if key == this.word_key() { + uleb(&mut this.info, ab_base); + this.name("u64"); + this.info.byte(dw_ate_unsigned); + uleb(&mut this.info, 8); + return; + } + if key == this.address_key() { + uleb(&mut this.info, ab_address); + uleb(&mut this.info, 8); + return; + } + if key == this.widened_key() { + uleb(&mut this.info, ab_base); + this.name("f32"); + this.info.byte(dw_ate_float); + uleb(&mut this.info, 8); + return; + } + + val shape: layout = this.b.c.program.layouts[key]; + match shape.kind { + # An enum is laid out as its integer, with a field for each member whose + # offset is the member's value. + lk::signed, lk::unsigned => { + if shape.name != 0 && shape.count != 0 { + uleb(&mut this.info, ab_enum); + this.type_name(&shape); + uleb(&mut this.info, shape.size); + for f in 0..shape.count { + val field: slot_field = this.b.c.program.fields[shape.fields as u64 + f as u64]; + uleb(&mut this.info, ab_enumerator); + this.name(this.b.c.checker.names.text(field.name)); + sleb(&mut this.info, field.offset as i64); + } + this.info.byte(0); + return; + } + uleb(&mut this.info, ab_base); + this.type_name(&shape); + this.info.byte(shape.kind == lk::signed ? dw_ate_signed : dw_ate_unsigned); + uleb(&mut this.info, shape.size); + } + lk::floating, lk::boolean => { + uleb(&mut this.info, ab_base); + this.type_name(&shape); + this.info.byte(shape.kind == lk::floating ? dw_ate_float : dw_ate_boolean); + uleb(&mut this.info, shape.size); + } + + # A reference is the address of what it refers to. + lk::pointer, lk::reference => { + if shape.element == 0 || this.b.c.program.layouts[shape.element - 1].kind == lk::empty { + uleb(&mut this.info, ab_address); + uleb(&mut this.info, 8); + return; + } + uleb(&mut this.info, shape.kind == lk::pointer ? ab_pointer : ab_reference); + this.type_ref(shape.element as u64 - 1); + uleb(&mut this.info, 8); + } + + # A reference to a trait is a reference, then the index of the vtable. + lk::trait_reference => { + uleb(&mut this.info, ab_struct); + this.type_name(&shape); + uleb(&mut this.info, shape.size); + this.member("address", this.address_key(), 0); + this.member("vtable", this.word_key(), 8); + this.info.byte(0); + } + + # A function value is its function's index plus one, then its environment. + lk::function => { + uleb(&mut this.info, ab_struct); + this.type_name(&shape); + uleb(&mut this.info, shape.size); + this.member("function", this.word_key(), 0); + this.member("environment", this.address_key(), 8); + this.info.byte(0); + } + lk::fixed => { + uleb(&mut this.info, ab_array); + this.type_ref(shape.element as u64 - 1); + uleb(&mut this.info, ab_subrange); + uleb(&mut this.info, shape.count as u64); + this.info.byte(0); + } + lk::record => { + uleb(&mut this.info, ab_struct); + this.type_name(&shape); + uleb(&mut this.info, shape.size); + this.fields(&shape, 0); + this.info.byte(0); + } + + # A union laid out without a tag is its fields over one another, the empty one + # held where the first word is null. + lk::variant => { + if shape.niche != 0 { + uleb(&mut this.info, ab_struct); + this.type_name(&shape); + uleb(&mut this.info, shape.size); + this.fields(&shape, 0); + this.info.byte(0); + return; + } + uleb(&mut this.info, ab_struct); + this.type_name(&shape); + uleb(&mut this.info, shape.size); + val tag := this.info.length; + uleb(&mut this.info, ab_enum); + this.name("tag"); + uleb(&mut this.info, 8); + for f in 0..shape.count { + val field: slot_field = this.b.c.program.fields[shape.fields as u64 + f as u64]; + uleb(&mut this.info, ab_enumerator); + this.name(this.b.c.checker.names.text(field.name)); + sleb(&mut this.info, f as i64); + } + this.info.byte(0); + uleb(&mut this.info, ab_member); + this.name("tag"); + this.info.u32(tag); + uleb(&mut this.info, 0); + + val payload := this.info.length; + uleb(&mut this.info, ab_union); + uleb(&mut this.info, shape.size > 8 ? shape.size - 8 : 0); + this.fields(&shape, 8); + this.info.byte(0); + uleb(&mut this.info, ab_anonymous); + this.info.u32(payload); + uleb(&mut this.info, 8); + this.info.byte(0); + } + else => { + uleb(&mut this.info, ab_unspecified); + this.type_name(&shape); + } + } +} + + +# Functions. + +#! Whether code of an inline site is within another, or is that site. +#! @param sites The function's inline sites. +#! @param site One more than the site, or 0 for the function's own code. +#! @param outer One more than the other. +#! @returns Whether it is. +def within(sites: &vector, site: u32, outer: u32): bool { + var at := site; + var depth: u64 = 0; + while at != 0 && depth <= sites.length { + return true if at == outer; + at = sites[at as u64 - 1].parent; + depth++; + } + return false; +} + +#! Writes the sites inlined within a site of a function, or within its own +#! code, each with the code of the rows within it, as one range or several. +#! @param this The writer. +#! @param index The function. +#! @param parent One more than the site, or 0. +def dwarf_writer::sites(&mut this, index: u32, parent: u32): void { + val sites := &this.b.c.program.functions[index].body.sites; + val first := this.b.row_first[index] as u64; + val last := this.b.row_first[index + 1] as u64; + val address := this.b.text_base + this.b.starts[index]; + val size := this.b.ends[index] - this.b.starts[index]; + for k in 0..sites.length { + val site: inline_site = sites[k]; + continue if site.parent != parent; + var pieces: u64 = 0; + var low: u64 = 0; + var high: u64 = 0; + val list := this.ranges.length; + var r := first; + while r < last { + if !within(sites, this.b.rows[r].site, k as u32 + 1) { + r++; + continue; + } + val from := this.b.rows[r].offset; + var next := r + 1; + while next < last && within(sites, this.b.rows[next].site, k as u32 + 1) { + next++; + } + val to := next < last ? this.b.rows[next].offset : size; + r = next; + continue if to <= from; + if pieces == 0 { + low = from; + } + high = to; + this.ranges.byte(dw_rle_start_length); + this.ranges.u64(address + from); + uleb(&mut this.ranges, to - from); + pieces++; + } + this.ranges.byte(dw_rle_end_of_list); + continue if pieces == 0 || this.abstracts[site.function] == 0; + + uleb(&mut this.info, pieces == 1 ? ab_inlined : ab_scattered); + this.info.u32(this.abstracts[site.function] as u64); + if pieces == 1 { + this.info.u64(address + low); + this.info.u64(high - low); + } else { + this.info.u32(list); + } + var source: u32 = 0; + val located := this.b.source_of(index, site.at, &mut source); + uleb(&mut this.info, this.file(source)); + uleb(&mut this.info, located.line as u64); + uleb(&mut this.info, located.column as u64); + this.site_variables(index, k as u32 + 1); + this.sites(index, k as u32 + 1); + this.info.byte(0); + } +} + +#! Writes the variables of the function a site inlined. +#! @param this The writer. +#! @param index The function it was inlined into. +#! @param site One more than the site. +def dwarf_writer::site_variables(&mut this, index: u32, site: u32): void { + val debug := &this.b.debug; + for v in debug.variable_first[index]..debug.variable_first[index + 1] { + val each: placed_variable = debug.variables[v as u64]; + continue if each.site != site || this.b.c.program.layouts[each.layout].kind == lk::empty; + if each.held { + this.listed_variable(index, &each); + } else { + this.variable(&each); + } + } +} + +#! Writes a variable: its name, where it is declared, its type, and where its +#! frame holds it. +#! @param this The writer. +#! @param each The variable. +def dwarf_writer::variable(&mut this, each: &placed_variable): void { + uleb(&mut this.info, each.param ? ab_parameter : ab_variable); + this.name(this.b.c.checker.names.text(each.name)); + this.declared(pair_high(each.at) - 1, pair_low(each.at)); + this.type_ref(each.layout as u64); + var expression := byte_writer::new(); + expression.byte(dw_op_fbreg); + sleb(&mut expression, each.offset); + if each.boxed { + expression.byte(dw_op_deref); + } + uleb(&mut this.info, expression.length); + this.info.put(expression.view()); +} + +#! Writes where a word of a variable held in values is, over a range, as an +#! expression: a register, the frame, or a value known. One of an object of the +#! heap is that object, at the address the word is. +#! @param out Where. +#! @param kind Where the word is, as a `word_spot`. +#! @param spot The register, the offset from the frame's canonical address, or the bits. +#! @param boxed Whether the word is the address of the object of the heap the variable is in. +def word_location(out: &mut byte_writer, kind: u8, spot: u64, boxed: bool): void { + if kind == word_spot::gpr as u8 { + val number := amd64_registers[spot & 15]; + if boxed { + out.byte(dw_op_breg0 + number); + sleb(out, 0); + } else { + out.byte(dw_op_reg0 + number); + } + } else if kind == word_spot::xmm as u8 { + out.byte(dw_op_reg0 + amd64_xmm0 + (spot & 15) as u8); + } else if kind == word_spot::frame as u8 { + out.byte(dw_op_fbreg); + sleb(out, spot as i64); + if boxed { + out.byte(dw_op_deref); + } + } else if kind == word_spot::word as u8 { + out.byte(dw_op_constu); + uleb(out, spot); + if !boxed { + out.byte(dw_op_stack_value); + } + } else if kind == word_spot::real as u8 { + out.byte(dw_op_implicit_value); + uleb(out, 8); + out.u64(spot); + } +} + +#! Writes a variable held in values: its name, where it is declared, its type, +#! and the list of where it is over each range of code it is somewhere in. +#! @param this The writer. +#! @param index The function. +#! @param each The variable. +def dwarf_writer::listed_variable(&mut this, index: u32, each: &placed_variable): void { + uleb(&mut this.info, each.param ? ab_listed_parameter : ab_listed_variable); + this.name(this.b.c.checker.names.text(each.name)); + this.declared(pair_high(each.at) - 1, pair_low(each.at)); + val shape: layout = this.b.c.program.layouts[each.layout]; + val widened := !each.boxed && !each.narrow && shape.kind == lk::floating && shape.size == 4; + this.type_ref(widened ? this.widened_key() : each.layout as u64); + this.info.u32(this.locations.length); + + # Each word of a variable of several is a piece of it. + val words := each.boxed ? 1 : word_count(&shape); + val address := this.b.text_base + this.b.starts[index]; + var expression := byte_writer::new(); + for r in each.ranges..each.ranges + each.count { + val range: located_range = this.b.debug.ranges[r as u64]; + expression.clear(); + for w in 0..words { + word_location(&mut expression, range.kinds[w], range.spots[w], each.boxed); + if words > 1 { + expression.byte(dw_op_piece); + uleb(&mut expression, 8); + } + } + continue if expression.length == 0; + this.locations.byte(dw_lle_start_length); + this.locations.u64(address + range.from as u64); + uleb(&mut this.locations, (range.to - range.from) as u64); + uleb(&mut this.locations, expression.length); + this.locations.put(expression.view()); + } + this.locations.byte(dw_lle_end_of_list); +} + +#! Whether one variable's scope comes before another's: it begins first, or +#! ends later where they begin together, so a scope comes before those within +#! it. +#! @param a The one. +#! @param b The other. +#! @returns Whether it does. +def scope_before(a: &placed_variable, b: &placed_variable): bool { + return a.from < b.from || (a.from == b.from && a.to > b.to); +} + +#! Writes the variables of a function: its parameters, then its locals, each in +#! a block of the code its scope covers. Scopes nest, so the blocks do. +#! @param this The writer. +#! @param index The function. +def dwarf_writer::variables(&mut this, index: u32): void { + val debug := &this.b.debug; + val first := debug.variable_first[index] as u64; + val last := debug.variable_first[index + 1] as u64; + var locals := vector::::new(); + for v in first..last { + val each: placed_variable = debug.variables[v]; + continue if this.b.c.program.layouts[each.layout].kind == lk::empty || each.site != 0; + if each.held { + this.listed_variable(index, &each); + continue; + } + if each.param { + this.variable(&each); + continue; + } + continue if each.to <= each.from; + locals.append(each); + } + # Put in order of their scopes, those of one scope in the order they came. + locals.sort_by(scope_before); + + # The blocks open, the innermost last. + val address := this.b.text_base + this.b.starts[index]; + var open := vector::::new(); + for &each in locals { + while open.length != 0 && (each.from < open.last().from || each.to > open.last().to) { + this.info.byte(0); + open.truncate(); + } + if open.length == 0 || each.from != open.last().from || each.to != open.last().to { + uleb(&mut this.info, ab_block); + this.info.u64(address + each.from as u64); + this.info.u64((each.to - each.from) as u64); + open.append(each); + } + this.variable(&each); + } + for _ in 0..open.length { + this.info.byte(0); + } +} + +#! Writes the entry of a function's code: its name, or the abstract entry of +#! it where it was inlined somewhere too, then its variables and the calls +#! inlined into it. +#! @param this The writer. +#! @param index The function. +def dwarf_writer::function(&mut this, index: u32): void { + val function := &this.b.c.program.functions[index]; + if this.abstracts[index] != 0 { + uleb(&mut this.info, ab_concrete); + this.info.u32(this.abstracts[index] as u64); + } else { + uleb(&mut this.info, ab_subprogram); + this.name(function.name.view()); + this.declared(function.file, function.offset); + this.info.byte(dw_cc_nocall); + } + this.info.u64(this.b.text_base + this.b.starts[index]); + this.info.u64(this.b.ends[index] - this.b.starts[index]); + uleb(&mut this.info, 1); + this.info.byte(dw_op_call_frame_cfa); + this.variables(index); + this.sites(index, 0); + this.info.byte(0); +} + + +# Lines. + +#! Writes the line program of a function's code, as a sequence of its own. +#! @param this The writer. +#! @param index The function. +def dwarf_writer::line_program(&mut this, index: u32): void { + val size := this.b.ends[index] - this.b.starts[index]; + val body := this.b.debug.bodies[index] as u64; + this.program.begin(this.b.text_base + this.b.starts[index]); + var begun := false; + for r in this.b.row_first[index]..this.b.row_first[index + 1] { + val row: line_row = this.b.rows[r as u64]; + var source: u32 = 0; + val located := this.b.source_of(index, row.at, &mut source); + val number := this.file(source); + val prologue_end := !begun && body != 0 && row.offset >= body; + begun = begun || prologue_end; + this.program.row(row.offset, number, located.line as u64, located.column as u64, prologue_end); + } + this.program.end(size); +} + +#! Writes the line table: its header, naming the directories and the files, +#! then the program the functions wrote. +#! @param this The writer. +#! @param directory The directory the build was in, which relative paths are +#! within. +def dwarf_writer::line_table(&mut this, directory: strview): void { + var paths := vector::::new(); + for &each in this.files { + paths.append(this.b.c.checker.units[each].source.path); + } + write_line_table(&mut this.lines, directory, paths.view(), &mut this.line_strings, this.program.bytes.view()); +} + + +# Frames. + +#! Writes the rules of code that has made a frame of `rbp` by an offset: the +#! caller's stack is past `rbp`'s saved value and the return address, then +#! where `rbp` points. +#! @param out Where. +#! @param at The offset the rules apply from, moved. +#! @param framed Where `rbp` is pushed. +#! @param based Where the frame is made. +def frame_rules(out: &mut byte_writer, at: &mut u64, framed: u64, based: u64): void { + cfa_advance(out, at, framed); + cfa_def_cfa_offset(out, 16); + cfa_offset(out, amd64_rbp as u8, 2); + cfa_advance(out, at, based); + cfa_def_cfa_register(out, amd64_rbp); +} + +#! Writes the common entry each description of frames begins from, as a call +#! leaves them: the caller's stack just past the return address. +#! @param this The writer. +def dwarf_writer::cie(&mut this): void { + # Code is advanced by bytes, and offsets are of words. + val start := begin_cie(&mut this.frame, 1, -8, amd64_return_address); + cfa_def_cfa(&mut this.frame, amd64_rsp, 8); + cfa_offset(&mut this.frame, amd64_return_address as u8, 1); + end_entry(&mut this.frame, start); +} + +#! Writes how a function's frames unwind: through `rbp` from its prologue on, +#! with each register it saves below the frame pointer once it has, and +#! through `rsp` past each `leave`, until the instruction leaving the function, +#! where each register is as the caller had it. +#! @param this The writer. +#! @param index The function. +def dwarf_writer::function_frame(&mut this, index: u32): void { + val start := begin_fde(&mut this.frame, 0, this.b.text_base + this.b.starts[index], + this.b.ends[index] - this.b.starts[index]); + var at: u64 = 0; + frame_rules(&mut this.frame, &mut at, framed_at, based_at); + val saves := this.b.debug.saves[index] as u64; + if saves != 0 { + # The first is past the saved `rbp` and the return address, the third word + # below the canonical address. + cfa_advance(&mut this.frame, &mut at, this.b.debug.saved_at[index] as u64); + var word: u64 = 3; + for &r in kept_gprs { + continue if (saves & (1u << r as u64)) == 0; + cfa_offset(&mut this.frame, amd64_registers[r as u64], word); + word++; + } + } + for r in this.b.debug.return_first[index]..this.b.debug.return_first[index + 1] { + val left := this.b.debug.returns[r as u64] as u64; + cfa_advance(&mut this.frame, &mut at, left); + cfa_remember_state(&mut this.frame); + cfa_def_cfa(&mut this.frame, amd64_rsp, 8); + cfa_same_value(&mut this.frame, amd64_rbp); + for &kept in kept_gprs { + continue if (saves & (1u << kept as u64)) == 0; + cfa_same_value(&mut this.frame, amd64_registers[kept as u64] as u64); + } + cfa_advance(&mut this.frame, &mut at, left + this.b.debug.return_bytes[r as u64] as u64); + cfa_restore_state(&mut this.frame); + } + end_entry(&mut this.frame, start); +} + +#! Writes how the trap stub's frame unwinds, which it makes as a function +#! does, so a debugger stopped in the report unwinds to where the trap was. +#! @param this The writer. +def dwarf_writer::trap_frame(&mut this): void { + val stub := this.b.trap_stub; + val start := begin_fde(&mut this.frame, 0, this.b.text_base + stub, this.b.faults - stub); + var at: u64 = 0; + frame_rules(&mut this.frame, &mut at, this.b.trap_framed - stub, this.b.trap_based - stub); + end_entry(&mut this.frame, start); +} + + +# The program. + +#! Writes the debugging information of an executable's code. +#! @param b The building. +#! @param directory The directory the build was in. +#! @returns The writer, holding each section. +#! The directory the build was in, which relative paths are within, or `.` +#! where the system does not give it. +#! @returns The directory. +def build_directory(): string { + var at := working_directory() else (_) { return string::from(".", nothing {}); }; + return string::from(at.view(), nothing {}); +} + +def write_dwarf(b: &building, directory: strview): dwarf_writer { + val program := &b.c.program; + val keys := program.layouts.length + 3; + var w := dwarf_writer { + b = b, + info = byte_writer::new(), + abbrev = byte_writer::new(), + lines = byte_writer::new(), + program = line_program::new(), + strings = string_table::new(), + line_strings = string_table::new(), + frame = byte_writer::new(), + ranges = byte_writer::new(), + locations = byte_writer::new(), + files = vector::::new(), + numbers = vector::::new(), + types = vector::::new(), + queued = vector::::new(), + queue = vector::::new(), + fixups = fixup_list::new(nothing {}), + abstracts = vector::::new() + }; + w.numbers.resize(b.c.checker.units.length); + w.types.resize(keys); + w.queued.resize(keys); + w.abstracts.resize(program.functions.length); + abbreviations(&mut w.abbrev); + val ranges_length := begin_lists(&mut w.ranges); + val locations_length := begin_lists(&mut w.locations); + + # The main file is numbered 1, and names the unit. + val main_file := program.functions[program.main].file; + w.file(main_file); + val main_path := b.c.checker.units[main_file].source.path; + + # The unit, which every function and type is within. + val unit := begin_unit(&mut w.info, dw_ut_compile, 8, 0); + uleb(&mut w.info, ab_unit); + w.name("sakura"); + # The language debuggers read the program as, whose printing of structs, + # references, and names joined by `::` is Sakura's own; DWARF has no code for + # Sakura. Its functions can't be called by a debugger, whose calls follow C's + # conventions, so each says it takes no calls. + w.info.u16(dw_lang_c_plus_plus_14); + val name_at := w.string_of(true, main_path); + w.info.u32(name_at as u64); + val directory_at := w.string_of(true, directory); + w.info.u32(directory_at as u64); + w.info.u64(b.text_base); + w.info.u64(b.text.length); + w.info.u32(0); + + # What each function inlined somewhere is, which the code it was inlined as + # names. + for i in 0..program.functions.length { + continue if b.starts[i] == b.missing; + for &site in program.functions[i].body.sites { + val callee := site.function; + continue if w.abstracts[callee] != 0; + val inlined := &program.functions[callee]; + w.abstracts[callee] = w.info.length as u32; + uleb(&mut w.info, ab_abstract); + w.name(inlined.name.view()); + w.declared(inlined.file, inlined.offset); + w.info.byte(dw_cc_nocall); + w.info.byte(dw_inl_inlined); + } + } + + for i in 0..program.functions.length { + continue if b.starts[i] == b.missing || b.ends[i] <= b.starts[i]; + w.function(i as u32); + w.line_program(i as u32); + } + + # The types the variables named, and those their types name in turn. + var q: u64 = 0; + while q < w.queue.length { + w.write_type(w.queue[q] as u64); + q++; + } + w.fixups.resolve_words(&mut w.info, w.types.view()); + w.info.byte(0); + w.info.end_length(unit); + + w.line_table(directory); + w.cie(); + for i in 0..program.functions.length { + continue if b.starts[i] == b.missing || b.ends[i] <= b.starts[i]; + w.function_frame(i as u32); + } + w.trap_frame(); + w.ranges.end_length(ranges_length); + w.locations.end_length(locations_length); + return w; +} + +#! The sections of debugging information, by name, in the order an executable +#! holds them. +const debug_names: strview[8] = [ + ".debug_info", ".debug_abbrev", ".debug_line", ".debug_str", ".debug_line_str", ".debug_frame", + ".debug_rnglists", ".debug_loclists" +]; + +#! A section of debugging information a writer holds. +#! @param this The writer. +#! @param k Its place among `debug_names`. +#! @returns The section. +def dwarf_writer::section(&mut this, k: u64): &mut byte_writer { + if k == 0 { return &mut this.info; } + if k == 1 { return &mut this.abbrev; } + if k == 2 { return &mut this.lines; } + if k == 3 { return &mut this.strings.bytes; } + if k == 4 { return &mut this.line_strings.bytes; } + if k == 5 { return &mut this.frame; } + if k == 6 { return &mut this.ranges; } + return &mut this.locations; +} + +#! A section of debugging information, held but not loaded. +#! @param name Its name. +#! @param data What it holds, taken. +#! @param strings Whether it is strings, each ending with a zero. +#! @returns The section. +def debug_section(name: strview, data: &mut byte_writer, strings: bool): elf::section { + return elf::section { + name = name, + kind = elf::section_kind::progbits, + data = byte_writer::move_of(data), + align = 1, + flags = strings ? elf::merge | elf::strings : 0, + entry = strings ? 1 : 0 + }; +} + +#! Writes the debugging information of an executable to its own file, its path +#! with `.petal` added, and names that file in the executable, with its +#! checksum. +#! @param b The building. +#! @param image The executable, which holds the note naming its build. +#! @returns Whether the file was written. +pub def describe_build(b: &building, image: &mut elf::image): bool { + var directory := working_directory() else (_) { return false; }; + var w := write_dwarf(b, directory.view()); + + # The file describes the executable, holding its build's note to be matched + # by, and the sections. + var described := elf::image::new(image.entry); + described.described = true; + described.linked = image.linked; + described.segments.extend(image.segments.view()); + described.symbols.extend(image.symbols.view()); + for &each in image.sections { + var data := byte_writer::new(); + data.put(each.data.view()); + described.sections.append(elf::section { + name = each.name, kind = each.kind, data = byte_writer::move_of(&mut data), align = each.align, flags = each.flags, + entry = each.entry + }); + } + # The tables of strings, each ending with a zero, may be merged. + for k in 0..debug_names.length { + described.sections.append(debug_section(debug_names[k], w.section(k), k == 3 || k == 4)); + } + + val path := $"{b.options.output}.petal"; + val bytes := described.file(); + return false if !write_bytes(path.view(), bytes.view(), 0o644); + + # The executable names the file, its zeros padded to a multiple of four, + # then the file's checksum. + val whole := path.view(); + var slash := whole.length; + while slash > 0 && whole[slash - 1] != '/' as u8 { + slash--; + } + var link := byte_writer::new(); + link.put_terminated(whole.substr(slash, whole.length - slash)); + link.align_to(4); + link.u32(elf::crc32(bytes.view())); + image.sections.append(elf::section { + name = ".gnu_debuglink", kind = elf::section_kind::progbits, data = byte_writer::move_of(&mut link), align = 4, flags = 0, entry = 0 + }); + return true; +} diff --git a/native/evex.sakura b/native/evex.sakura new file mode 100644 index 00000000..f7d02d64 --- /dev/null +++ b/native/evex.sakura @@ -0,0 +1,370 @@ +#! @file evex.sakura +#! @author John Christman (sorakatadzuma@gmail.com) +#! @copyright Malunal Studios, LLC. +#! @license MIT +#! +#! Contains how an executable works 64 bytes of lanes with AVX-512, where +#! `lanes_needs` said the processor running it has it: AVX-512F, BW, DQ, and VL, +#! with the system keeping the registers' upper 384 bits and the mask +#! registers. Such a vector is held in its slot, never a register, as only code +#! that asked the processor may touch `zmm` registers. Each operation loads its +#! operands from their slots into `zmm16` and those after it, works them with +#! EVEX's encodings, and stores its result in its slot; comparing lanes gives a +#! mask in `k1`, which becomes the mask's lanes, and choosing lanes or taking a +#! mask's bits takes them back into `k1`. VEX names no register past `zmm15`, +#! so neither `vzeroupper` nor SSE's instructions meet those, and code working +#! 64 bytes clears nothing after. +#! +#! An instruction is a word as `binary::amd64` writes vector instructions: its +#! opcode, its map above it, its mandatory prefix above that, and `W` at bit 24. + +import sakura::compiler; +import binary::amd64; +module sakura::native; + + +# Moving 64 bytes, and 16 into every quarter of a register, or into one. +const z_movdqu64_load: u32 = 0x102016F; +const z_movdqu64_store: u32 = 0x102017F; +const z_broadcasti32x4: u32 = 0x01025A; +const z_inserti32x4: u32 = 0x010338; +# Integer arithmetic, by width: 16, 32, and 64 bits. +const z_paddw: u32 = 0x0101FD; +const z_paddd: u32 = 0x0101FE; +const z_paddq: u32 = 0x10101D4; +const z_psubw: u32 = 0x0101F9; +const z_psubd: u32 = 0x0101FA; +const z_psubq: u32 = 0x10101FB; +const z_pmullw: u32 = 0x0101D5; +const z_pmulld: u32 = 0x010240; +const z_pmullq: u32 = 0x1010240; +# Bitwise operations of 32-bit lanes, and of 64 with `W`; and AVX-512's of +# three operands by a table of eight bits. +const z_pandd: u32 = 0x0101DB; +const z_pord: u32 = 0x0101EB; +const z_pxord: u32 = 0x0101EF; +const z_pternlogd: u32 = 0x010325; +# The least, greatest, and absolute values of integers, by sign and width; `W` +# makes the 32-bit ones' 64-bit. +const z_pminsw: u32 = 0x0101EA; +const z_pmaxsw: u32 = 0x0101EE; +const z_pminuw: u32 = 0x01023A; +const z_pmaxuw: u32 = 0x01023E; +const z_pminsd: u32 = 0x010239; +const z_pmaxsd: u32 = 0x01023D; +const z_pminud: u32 = 0x01023B; +const z_pmaxud: u32 = 0x01023F; +const z_pabsw: u32 = 0x01021D; +const z_pabsd: u32 = 0x01021E; +const z_pabsq: u32 = 0x101021F; +# Rounding reals with how they round, and comparing lanes into a mask, by a +# predicate. +const z_rndscaleps: u32 = 0x010308; +const z_rndscalepd: u32 = 0x1010309; +const z_pcmpd: u32 = 0x01031F; +const z_pcmpud: u32 = 0x01031E; +const z_pcmpw: u32 = 0x101033F; +const z_pcmpuw: u32 = 0x101033E; +const z_cmpps: u32 = 0x0001C2; +# A mask's lanes from `k1`, and `k1` from a mask's lanes, of 16, 32, and 64-bit +# lanes; and lanes chosen by `k1`. +const z_pmovm2w: u32 = 0x1020228; +const z_pmovm2d: u32 = 0x020238; +const z_pmovm2q: u32 = 0x1020238; +const z_pmovw2m: u32 = 0x1020229; +const z_pmovd2m: u32 = 0x020239; +const z_pmovq2m: u32 = 0x1020239; +const z_pblendmw: u32 = 0x1010266; +const z_pblendmd: u32 = 0x010264; +const z_pblendmq: u32 = 0x1010264; +const z_blendmps: u32 = 0x010265; +const z_blendmpd: u32 = 0x1010265; +# Splatting a general register's lane, or a real's low lane. +const z_pbroadcastw_r: u32 = 0x01027B; +const z_pbroadcastd_r: u32 = 0x01027C; +const z_pbroadcastq_r: u32 = 0x101027C; +const z_broadcastss: u32 = 0x010218; +const z_broadcastsd: u32 = 0x1010219; +# A mask register's bits into a general register, written with VEX: 16 bits, +# and 32 with `F2`. +const k_movw: u32 = 0x000193; +const k_movd: u32 = 0x030193; + +# The registers 64 bytes are worked in. +const z16: u32 = 16; +const z17: u32 = 17; +const z18: u32 = 18; + +#! Writes EVEX's four bytes and an instruction's opcode, on 64 bytes: `r` the +#! register in ModRM's reg, `v` the one EVEX names, or 0 where the instruction +#! names none, `b` the base or register in ModRM's rm, and `k` the mask +#! register writing is masked by, or 0. A vector register is any of the 32, and +#! a general one, or the base of `memory`, any of the 16. +#! @param this The selector. +#! @param op The instruction. +#! @param r ModRM's reg. +#! @param v The register EVEX names. +#! @param b ModRM's rm. +#! @param k The mask register. +#! @param memory Whether `b` is the base of memory, which names no index. +def selector::evex_opcode(&mut this, op: u32, r: u32, v: u32, b: u32, k: u32, memory: bool): void { + val pp := (op >> 16) & 3; + val map := (op >> 8) & 3; + val w: u32 = (op & vec_wide) != 0 ? 1 : 0; + # R, X, B, and R' inverted: the fourth and fifth bits of `r` and `b`, where X + # is the fifth of a register `b`. + val x: u32 = memory ? 1 : ((b >> 4) & 1) ^ 1; + this.b.text.byte(0x62); + this.b.text.byte(((((r >> 3) & 1) ^ 1) << 7 | x << 6 | (((b >> 3) & 1) ^ 1) << 5 | (((r >> 4) & 1) ^ 1) << 4 | map) as u8); + this.b.text.byte((w << 7 | ((~v & 15) << 3) | 1 << 2 | pp) as u8); + # Of 512 bits, V' inverted, and the mask. + this.b.text.byte((2 << 5 | (((v >> 4) & 1) ^ 1) << 3 | (k & 7)) as u8); + this.b.text.byte((op & 0xFF) as u8); +} + +#! An instruction of registers on 64 bytes: `op dst, v, src`. +#! @param this The selector. +#! @param op The instruction. +#! @param dst ModRM's reg. +#! @param v The register EVEX names, or 0. +#! @param src ModRM's rm. +#! @param k The mask register, or 0. +def selector::evex(&mut this, op: u32, dst: u32, v: u32, src: u32, k: u32): void { + this.evex_opcode(op, dst, v, src, k, false); + this.b.text.byte((0xC0 | ((dst & 7) << 3) | (src & 7)) as u8); +} + +#! An instruction of registers on 64 bytes, with a byte after it. +#! @param this The selector. +#! @param op The instruction. +#! @param dst ModRM's reg. +#! @param v The register EVEX names, or 0. +#! @param src ModRM's rm. +#! @param imm The byte. +def selector::evex_imm(&mut this, op: u32, dst: u32, v: u32, src: u32, imm: u8): void { + this.evex(op, dst, v, src, 0); + this.b.text.byte(imm); +} + +#! An instruction of a register and memory on 64 bytes, as a load or store: the +#! memory a base register and a displacement, written whole, which EVEX does +#! not scale. +#! @param this The selector. +#! @param op The instruction. +#! @param r The register. +#! @param m The memory. +def selector::evex_mem(&mut this, op: u32, r: u32, m: mem): void { + val base := m.base as u32; + this.evex_opcode(op, r, 0, base, 0, true); + this.b.text.byte((0x80 | ((r & 7) << 3) | (base & 7)) as u8); + if (base & 7) == 4 { + this.b.text.byte(0x24); + } + this.b.text.u32(m.disp as u64 & 0xFFFFFFFF); +} + +#! An instruction of a register and memory on 64 bytes, with a byte after it. +#! @param this The selector. +#! @param op The instruction. +#! @param r The register, which EVEX also names. +#! @param m The memory. +#! @param imm The byte. +def selector::evex_mem_imm(&mut this, op: u32, r: u32, m: mem, imm: u8): void { + val base := m.base as u32; + this.evex_opcode(op, r, r, base, 0, true); + this.b.text.byte((0x80 | ((r & 7) << 3) | (base & 7)) as u8); + if (base & 7) == 4 { + this.b.text.byte(0x24); + } + this.b.text.u32(m.disp as u64 & 0xFFFFFFFF); + this.b.text.byte(imm); +} + +#! Loads an operand of the instruction, 64 bytes in its slot, into a register, +#! a quarter at a time, as `read_halves` reads 32: a value is copied into its +#! slot 16 bytes at a time, and one load reading four stores would wait for +#! them all to reach the cache. +#! @param this The selector. +#! @param index The instruction. +#! @param k Which operand. +#! @param z The register. +def selector::fetch_wide(&mut this, index: u32, k: u32, z: u32): void { + val held := this.read(this.body.arg(index, k), index); + if held.kind == place::none { + this.evex(z_pxord, z, z, z, 0); + return; + } + val from := this.memory_of(&held); + this.evex_mem(z_broadcasti32x4, z, from); + for q in 1..4u { + var part := from; + part.disp += (16 * q) as i32; + this.evex_mem_imm(z_inserti32x4, z, part, q as u8); + } +} + +#! Splats a word across a register of 64 bytes, from a general register. +#! @param this The selector. +#! @param z The register. +#! @param word The word. +def selector::splat_wide(&mut this, z: u32, word: u64): void { + this.b.text.mov_imm(reg::rax, word); + this.evex(z_pbroadcastq_r, z, 0, reg::rax as u32, 0); +} + +#! `lanes` of 64 bytes, as the file says. +#! @param this The selector. +#! @param index The instruction. +#! @param held The instruction. +def selector::lanes_wide(&mut this, index: u32, held: &inst): void { + val operation := held.aux; + val lane := (held.imm & 0xFF) as u32; + val result := held.result; + val real := lane >= lane_f32; + val bits := lane_bits(lane); + val doubles: u32 = lane == lane_f64 ? 0x10000 | vec_wide : 0; + val q: u32 = bits == 64 ? vec_wide : 0; + val to_mask := by_width(lane, 0, z_pmovw2m, z_pmovd2m, z_pmovq2m); + if operation == lanes_bits { + # `vpmov?2m` clears the bits of `k1` past the lanes. + this.fetch_wide(index, 0, z16); + this.evex(to_mask, 1, 0, z16, 0); + val into := this.target(result, reg::rax); + this.b.text.vex(bits == 16 ? k_movd : k_movw, false, into as u32, 0, 1); + this.put(result, into); + return; + } + if operation == lanes_splat { + val value := this.body.arg(index, 0); + if lane == lane_f32 { + this.evex(z_broadcastss, z16, 0, this.single_reg(value, index, 0) as u32, 0); + } else if lane == lane_f64 { + this.load_real_into(value, index, 0); + this.evex(z_broadcastsd, z16, 0, 0, 0); + } else { + val r := this.word_reg(value, index, reg::rax); + this.evex(by_width(lane, 0, z_pbroadcastw_r, z_pbroadcastd_r, z_pbroadcastq_r), z16, 0, r as u32, 0); + } + } else if operation == lanes_select { + # `k1` set where the mask is; each lane then the second operand's there, and + # the third's elsewhere. + this.fetch_wide(index, 0, z16); + this.fetch_wide(index, 1, z17); + this.fetch_wide(index, 2, z18); + this.evex(to_mask, 1, 0, z16, 0); + val blend := real ? (lane == lane_f64 ? z_blendmpd : z_blendmps) : by_width(lane, 0, z_pblendmw, z_pblendmd, z_pblendmq); + this.evex(blend, z16, z18, z17, 1); + } else if operation == lanes_fma { + # `zmm16 = zmm17 * zmm18 + zmm16`, as `lanes.sakura`'s is. + this.fetch_wide(index, 2, z16); + this.fetch_wide(index, 0, z17); + this.fetch_wide(index, 1, z18); + this.evex(vec_vfmadd231ps | (lane == lane_f64 ? vec_wide : 0), z16, z17, z18, 0); + } else if operation == lanes_shift_left || operation == lanes_shift_right { + # The count in the low word of `zmm17`, the same for every lane; a signed + # shift right of 64-bit lanes is AVX-512's own. + val count := this.word_reg(this.body.arg(index, 1), index, reg::rax); + this.evex(z_pbroadcastq_r, z17, 0, count as u32, 0); + this.fetch_wide(index, 0, z16); + val op := operation == lanes_shift_left ? by_width(lane, 0, vec_psllw, vec_pslld, vec_psllq) + : lane_signed(lane) ? by_width(lane, 0, vec_psraw, vec_psrad, vec_psrad) : by_width(lane, 0, vec_psrlw, vec_psrld, vec_psrlq); + this.evex(op | q, z16, z16, z17, 0); + } else if operation >= lanes_equal && operation <= lanes_greater_equal { + this.compare_wide(index, operation, lane); + } else { + this.arithmetic_wide(index, operation, lane, doubles, q); + } + val made := this.p.made_at(result); + if made.kind != place::none { + this.evex_mem(z_movdqu64_store, z16, this.memory_of(&made)); + } +} + +#! Compares 64 bytes of lanes into a mask: into `k1` by a predicate, of reals +#! as SSE's are, the greater ones with their operands swapped, then its lanes. +#! @param this The selector. +#! @param index The instruction. +#! @param operation The comparison. +#! @param lane The type of lane. +def selector::compare_wide(&mut this, index: u32, operation: u32, lane: u32): void { + val bits := lane_bits(lane); + this.fetch_wide(index, 0, z16); + this.fetch_wide(index, 1, z17); + if lane >= lane_f32 { + val swapped := operation == lanes_greater || operation == lanes_greater_equal; + val predicate: u8 = operation == lanes_equal ? 0 : operation == lanes_not_equal ? 4 + : operation == lanes_less || operation == lanes_greater ? 1 : 2; + val op := z_cmpps | (lane == lane_f64 ? 0x10000 | vec_wide : 0); + if swapped { + this.evex_imm(op, 1, z17, z16, predicate); + } else { + this.evex_imm(op, 1, z16, z17, predicate); + } + } else { + # 0 equal, 1 less, 2 at most, 4 not equal, 5 at least, 6 greater. + val predicate: u8 = operation == lanes_equal ? 0 : operation == lanes_not_equal ? 4 : operation == lanes_less ? 1 + : operation == lanes_less_equal ? 2 : operation == lanes_greater ? 6 : 5; + val signed := lane_signed(lane); + val op := bits == 16 ? (signed ? z_pcmpw : z_pcmpuw) : (signed ? z_pcmpd : z_pcmpud) | (bits == 64 ? vec_wide : 0); + this.evex_imm(op, 1, z16, z17, predicate); + } + this.evex(by_width(lane, 0, z_pmovm2w, z_pmovm2d, z_pmovm2q), z16, 0, 1, 0); +} + +#! The arithmetic, bitwise operations, and rounding of 64 bytes of lanes, into +#! `zmm16`. +#! @param this The selector. +#! @param index The instruction. +#! @param operation The operation. +#! @param lane The type of lane. +#! @param doubles What makes an instruction of `f32`s one of `f64`s. +#! @param q What makes one of 32-bit integers one of 64. +def selector::arithmetic_wide(&mut this, index: u32, operation: u32, lane: u32, doubles: u32, q: u32): void { + val real := lane >= lane_f32; + this.fetch_wide(index, 0, z16); + if operation == lanes_negate { + if real { + this.splat_wide(z17, sign_bits(lane)); + this.evex(z_pxord | vec_wide, z16, z16, z17, 0); + } else { + this.evex(z_pxord, z17, z17, z17, 0); + this.evex(by_width(lane, 0, z_psubw, z_psubd, z_psubq), z16, z17, z16, 0); + } + } else if operation == lanes_not { + this.evex_imm(z_pternlogd, z16, z16, z16, 0x0F); + } else if operation == lanes_abs { + if real { + this.splat_wide(z17, ~sign_bits(lane)); + this.evex(z_pandd | vec_wide, z16, z16, z17, 0); + } else if lane_signed(lane) { + this.evex(by_width(lane, 0, z_pabsw, z_pabsd, z_pabsq), z16, 0, z16, 0); + } + } else if operation == lanes_sqrt { + this.evex(vec_sqrtps | doubles, z16, 0, z16, 0); + } else if operation >= lanes_floor && operation <= lanes_round_even { + # Toward -∞, +∞, zero, or the nearest, even on a tie, as a whole number, + # with no exception for what is not exact. + val mode: u8 = operation == lanes_floor ? 9 : operation == lanes_ceil ? 10 : operation == lanes_trunc ? 11 : 8; + this.evex_imm(lane == lane_f64 ? z_rndscalepd : z_rndscaleps, z16, 0, z16, mode); + } else { + this.fetch_wide(index, 1, z17); + var op: u32 = 0; + if operation == lanes_add { + op = real ? vec_addps | doubles : by_width(lane, 0, z_paddw, z_paddd, z_paddq); + } else if operation == lanes_sub { + op = real ? vec_subps | doubles : by_width(lane, 0, z_psubw, z_psubd, z_psubq); + } else if operation == lanes_mul { + op = real ? vec_mulps | doubles : by_width(lane, 0, z_pmullw, z_pmulld, z_pmullq); + } else if operation == lanes_div { + op = vec_divps | doubles; + } else if operation == lanes_and || operation == lanes_or || operation == lanes_xor { + op = (operation == lanes_and ? z_pandd : operation == lanes_or ? z_pord : z_pxord) | vec_wide; + } else { + val least := operation == lanes_min; + val signed := lane_signed(lane); + op = lane_bits(lane) == 16 ? (signed ? (least ? z_pminsw : z_pmaxsw) : (least ? z_pminuw : z_pmaxuw)) + : (signed ? (least ? z_pminsd : z_pmaxsd) : (least ? z_pminud : z_pmaxud)) | q; + } + this.evex(op, z16, z16, z17, 0); + } +} diff --git a/native/lanes.sakura b/native/lanes.sakura new file mode 100644 index 00000000..674d1154 --- /dev/null +++ b/native/lanes.sakura @@ -0,0 +1,1250 @@ +#! @file lanes.sakura +#! @author John Christman (sorakatadzuma@gmail.com) +#! @copyright Malunal Studios, LLC. +#! @license MIT +#! +#! Contains how an executable works the lanes of a `simd` with vector +#! instructions, where `lanes_needs` said the processor running it has them: +#! vectors are values, held in the vector registers past `xmm4` or in their +#! slots, and each operation copies its operands into `xmm0` and those after it, +#! works on them, and puts the result where it goes. 16 bytes are worked with +#! SSE's encodings, 32 with AVX's, and 64 with AVX-512's, as `evex.sakura` says. +#! +#! Code for processors with AVX writes every vector instruction with VEX, so no +#! SSE instruction meets a register's upper half. Other code, which works on 32 +#! bytes only where it found AVX, clears the upper halves with `vzeroupper` +#! once no register holds 32 bytes, which SSE's instructions would be slowed by +#! on some processors, and before every call and return. + +import sakura::compiler; +import binary::amd64; +module sakura::native; + + +#! `lanes`: the operation `aux` on the lanes of its operands, giving a vector, +#! or for `lanes_bits` the word of a mask's bits. +#! @param this The selector. +#! @param index The instruction. +#! @param held The instruction. +def selector::lanes(&mut this, index: u32, held: &inst): void { + val operation := held.aux; + val lane := (held.imm & 0xFF) as u32; + val long := (held.imm >> 8) == 32; + val result := held.result; + return if !this.wanted(result); + + if (held.imm >> 8) < 16 { + this.lane_alone(index, operation, lane, result); + return; + } + if (held.imm >> 8) == 64 { + this.lanes_wide(index, held); + return; + } + if (operation & 0xFF) >= lanes_convert && (operation & 0xFF) <= lanes_gather { + this.reshape_lanes(index, held, lane, long); + return; + } + if operation >= lanes_sum && operation <= lanes_largest { + this.reduce_lanes(index, operation, lane, long, result); + } else if operation == lanes_bits { + this.mask_bits(index, held, lane, long); + } else if this.binary_in_place(index, operation, lane, long) { + # Worked in the registers the operands and result are in. + } else if operation == lanes_splat { + this.splat_lane(index, lane, long); + this.put_lanes(result, 0, long); + } else if operation == lanes_pack { + this.pack_lanes(index, held, lane); + this.put_lanes(result, 0, long); + } else if operation == lanes_select { + this.fetch_lanes(index, 0, 0, long); + this.fetch_lanes(index, 1, 1, long); + this.fetch_lanes(index, 2, 2, long); + this.vop(vec_andps, long, 1, 0); + this.vop(vec_andnps, long, 0, 2); + this.vop(vec_orps, long, 0, 1); + this.put_lanes(result, 0, long); + } else if operation == lanes_fma { + # `xmm0 = xmm1 * xmm2 + xmm0`, rounded once. Its NaN is a factor's, `xmm1`'s + # before `xmm2`'s, and otherwise the addend's, even where the product is NaN, + # as `∞ * 0` is, which `std::math::fma` gives worked a lane at a time too. + this.fetch_lanes(index, 2, 0, long); + this.fetch_lanes(index, 0, 1, long); + this.fetch_lanes(index, 1, 2, long); + this.b.text.vex(vec_vfmadd231ps | (lane == lane_f64 ? vec_wide : 0), long, 0, 1, 2); + this.put_lanes(result, 0, long); + } else if operation == lanes_shift_left || operation == lanes_shift_right { + this.shift_lanes(index, operation, lane, long); + this.put_lanes(result, 0, long); + } else if operation == lanes_shuffle { + this.shuffle_lanes(index, lane, long); + this.put_lanes(result, 0, long); + } else if operation >= lanes_equal && operation <= lanes_greater_equal { + this.put_lanes(result, this.compare_lanes(index, operation, lane, long), long); + } else if lane >= lane_f32 && (operation == lanes_min || operation == lanes_max) { + this.put_lanes(result, this.real_extreme(index, operation, lane, long), long); + } else { + this.unary_or_binary(index, operation, lane, long); + this.put_lanes(result, 0, long); + } + this.settle_upper(index, long); +} + +# The instructions of one real, written as `binary::amd64` writes vector +# instructions: `vfmadd231ss`, whose `sd` is the same with `W`, and `roundss` +# and `roundsd`, with how they round. +const vec_vfmadd231ss: u32 = 0x0102B9; +const vec_roundss: u32 = 0x01030A; +const vec_roundsd: u32 = 0x01030B; +const vec_sqrtsd: u32 = 0x030151; + +#! An operation on one real lane alone, as `std::math` works `fma` and rounding +#! of one number: the instruction of one number on the reals themselves, which +#! splats nothing. An `f32` is worked as one, as the instructions of `f32`s are +#! (see `singles.sakura`), and held as one where every reader takes it so. +#! @param this The selector. +#! @param index The instruction. +#! @param operation The operation. +#! @param lane The type of lane, `f32` or `f64`. +#! @param result The result. +def selector::lane_alone(&mut this, index: u32, operation: u32, lane: u32, result: u32): void { + val single := lane == lane_f32; + # `xmm0` is the addend of `fma`, `xmm1` and `xmm2` its factors, as `lanes` has + # them, and the operand of the others. + val count := lanes_operands(operation); + for k in 0..count { + val x: u8 = operation == lanes_fma ? (k == 2 ? 0 : (k + 1) as u8) : k as u8; + val value := this.body.arg(index, k); + if single { + val got := this.single_reg(value, index, x); + if got != x { + this.b.text.movaps(x, got); + } + } else { + this.load_real_into(value, index, x); + } + } + if operation == lanes_fma { + this.b.text.vex(vec_vfmadd231ss | (single ? 0 : vec_wide), false, 0, 1, 2); + } else if operation == lanes_sqrt { + this.b.text.packed(single ? ss_sqrt : vec_sqrtsd, 0, 0); + } else { + val mode: u8 = operation == lanes_floor ? 9 : operation == lanes_ceil ? 10 : operation == lanes_trunc ? 11 : 8; + this.b.text.packed_imm(single ? vec_roundss : vec_roundsd, 0, 0, mode); + } + if !single || this.single[result] { + this.put_real(result, 0); + return; + } + val wide := this.real_target(result); + this.b.text.cvtss2sd(wide, 0); + this.put_real(result, wide); +} + +#! Works an operation of two vectors in the register its result is given, +#! where it has one and the operation is one instruction: with VEX's three +#! registers where the code may use them, or SSE's two, the result's register +#! given the first operand first. The operations are arithmetic and bitwise +#! ones, the least and greatest of integers, and integers' equality, and `>` and +#! `<` of signed ones, which `pcmpgt` gives with its operands either way. +#! @param this The selector. +#! @param index The instruction. +#! @param operation The operation. +#! @param lane The type of lane. +#! @param long Whether it works on 32 bytes. +#! @returns Whether it did, where the scratch registers work it otherwise. +def selector::binary_in_place(&mut this, index: u32, operation: u32, lane: u32, long: bool): bool { + val real := lane >= lane_f32; + # What SSE2 works with a sequence: products of bytes and of 64 bits, and of 32 + # without SSE4.1's `pmulld`, which code for x86-64-v3 has, and the least and + # greatest of 64-bit lanes. + val bits := lane_bits(lane); + if !real && ((operation == lanes_mul && (bits == 8 || bits == 64 || (bits == 32 && !long && !this.body.wide))) + || (bits == 64 && (operation == lanes_min || operation == lanes_max))) { + return false; + } + var op: u32 = 0; + var swapped := false; + var commutes := false; + if operation == lanes_add || operation == lanes_mul || operation == lanes_and || operation == lanes_or + || operation == lanes_xor { + op = binary_of(operation, lane); + commutes = true; + } else if operation == lanes_sub || operation == lanes_div { + op = binary_of(operation, lane); + } else if !real && (operation == lanes_min || operation == lanes_max) { + op = binary_of(operation, lane); + commutes = true; + } else if !real && operation == lanes_equal { + op = by_width(lane, vec_pcmpeqb, vec_pcmpeqw, vec_pcmpeqd, vec_pcmpeqq); + commutes = true; + } else if !real && lane_signed(lane) && (operation == lanes_greater || operation == lanes_less) { + op = by_width(lane, vec_pcmpgtb, vec_pcmpgtw, vec_pcmpgtd, vec_pcmpgtq); + swapped = operation == lanes_less; + } else { + return false; + } + + val made := this.p.made_at(this.body.insts[index].result); + return false if made.kind != place::xmm; + val r := made.number; + val first: u32 = swapped ? 1 : 0; + val a := this.read(this.body.arg(index, first), index); + val b := this.read(this.body.arg(index, 1 - first), index); + if long || this.body.wide { + val x := this.lanes_reg(a, 0, long); + val y := this.lanes_reg(b, 1, long); + this.b.text.vex(op, long, r as u32, x as u32, y as u32); + return true; + } + if b.kind == place::xmm && b.number == r { + return false if !commutes; + this.b.text.packed(op, r as u32, this.lanes_reg(a, 0, long) as u32); + return true; + } + if a.kind != place::xmm || a.number != r { + val x := this.lanes_reg(a, 0, long); + this.vmove(long, r, x); + } + this.b.text.packed(op, r as u32, this.lanes_reg(b, 1, long) as u32); + return true; +} + +#! A register holding a vector where it is: its own, or a scratch register it +#! is loaded into. +#! @param this The selector. +#! @param held Where it is. +#! @param scratch The register it is loaded into where it is in none. +#! @param long Whether it is 32 bytes. +#! @returns The register. +def selector::lanes_reg(&mut this, held: loc, scratch: u8, long: bool): u8 { + return held.number if held.kind == place::xmm; + if held.kind == place::none { + this.vop(vec_xorps, long, scratch, scratch); + } else { + this.load_vector(scratch, this.memory_of(&held), long); + } + return scratch; +} + +#! Clears the registers' upper halves after an instruction working on 32 +#! bytes, in code that may run where SSE's instructions would meet them, once +#! no register holds 32 bytes of lanes. +#! @param this The selector. +#! @param index The instruction. +#! @param long Whether it worked on 32 bytes. +def selector::settle_upper(&mut this, index: u32, long: bool): void { + return if !long || this.body.wide; + val after := 4 * (this.p.slots[index] + 1); + for &part in this.upper_parts { + return if pair_high(part) < after && pair_low(part) > after; + } + this.b.text.vzeroupper(); +} + +#! Finds where registers hold 32 bytes of lanes, in code that may run without +#! AVX, which clears their upper halves where none does. +#! @param this The selector. +def selector::find_upper_parts(&mut this): void { + this.upper_parts.clear(); + this.uses_upper = false; + return if this.body.wide; + for v in 0..this.p.bytes.length { + continue if this.p.bytes[v] != 32; + this.uses_upper = true; + for c in this.p.child_first[v]..this.p.child_first[v + 1] { + if this.p.child_locs[c as u64].kind == place::xmm { + this.upper_parts.append(pair_key(this.p.child_starts[c as u64], this.p.child_ends[c as u64])); + } + } + } +} + +#! Copies a vector between places: registers, slots, and the stack. +#! @param this The selector. +#! @param from Where it is. +#! @param to Where it goes. +#! @param long Whether it is 32 bytes. +def selector::move_lanes(&mut this, from: loc, to: loc, long: bool): void { + if to.kind == place::xmm { + if from.kind == place::xmm { + this.vmove(long, to.number, from.number); + } else { + this.load_vector(to.number, this.memory_of(&from), long); + } + return; + } + var x: u8 = 0; + if from.kind == place::xmm { + x = from.number; + } else { + this.load_vector(0, this.memory_of(&from), long); + } + this.store_vector(this.memory_of(&to), x, long); +} + +#! Loads a vector from memory into a register. +#! @param this The selector. +#! @param x The register. +#! @param from The memory. +#! @param long Whether it is 32 bytes. +def selector::load_vector(&mut this, x: u8, from: mem, long: bool): void { + if long { + this.b.text.vex_mem(vec_movdqu_load, true, x as u32, from); + } else { + this.b.text.packed_mem(vec_movdqu_load, x as u32, from); + } +} + +#! Writes a register's vector to memory. +#! @param this The selector. +#! @param into The memory. +#! @param x The register. +#! @param long Whether it is 32 bytes. +def selector::store_vector(&mut this, into: mem, x: u8, long: bool): void { + if long { + this.b.text.vex_mem(vec_movdqu_store, true, x as u32, into); + } else { + this.b.text.packed_mem(vec_movdqu_store, x as u32, into); + } +} + +#! Copies an operand of the instruction, a vector, into a register. +#! @param this The selector. +#! @param index The instruction. +#! @param k Which operand. +#! @param x The register. +#! @param long Whether it is 32 bytes. +def selector::fetch_lanes(&mut this, index: u32, k: u32, x: u8, long: bool): void { + val held := this.read(this.body.arg(index, k), index); + if held.kind == place::xmm { + if held.number != x { + this.vmove(long, x, held.number); + } + return; + } + if held.kind == place::none { + this.vop(vec_xorps, long, x, x); + return; + } + this.load_vector(x, this.memory_of(&held), long); +} + +#! Puts a vector a register holds where a result goes. +#! @param this The selector. +#! @param value The result. +#! @param x The register. +#! @param long Whether it is 32 bytes. +def selector::put_lanes(&mut this, value: u32, x: u8, long: bool): void { + val held := this.p.made_at(value); + if held.kind == place::xmm { + if held.number != x { + this.vmove(long, held.number, x); + } + } else if held.kind != place::none { + this.store_vector(this.memory_of(&held), x, long); + } +} + +#! `load` of a vector: the lanes at an address. +#! @param this The selector. +#! @param index The instruction. +#! @param held The instruction. +#! @param from The memory. +def selector::load_lanes(&mut this, index: u32, held: &inst, from: mem): void { + val long := held.aux == access::v256 as u32; + val result := held.result; + val made := this.p.made_at(result); + if held.aux == access::v512 as u32 { + if made.kind != place::none { + this.move_wide(from, this.memory_of(&made)); + } + return; + } + if made.kind == place::xmm { + this.read_halves(made.number, from, long); + } else if made.kind != place::none { + this.read_halves(0, from, long); + this.store_vector(this.memory_of(&made), 0, long); + } + this.settle_upper(index, long); +} + +#! Copies 64 bytes of lanes between memory, 16 bytes at a time, as any +#! processor may, where they are held between the instructions working them. +#! @param this The selector. +#! @param from The memory they are in. +#! @param to The memory they go to. +def selector::move_wide(&mut this, from: mem, to: mem): void { + for k in 0..4u { + var a := from; + var b := to; + a.disp += (16 * k) as i32; + b.disp += (16 * k) as i32; + this.b.text.packed_mem(vec_movdqu_load, 0, a); + this.b.text.packed_mem(vec_movdqu_store, 0, b); + } +} + +# Reads 32 bytes of memory a half at a time: values are copied 16 bytes at a +# time, and one load reading two stores waits for both to reach the cache, +# which made AVX's loops twice as slow as SSE's. +def selector::read_halves(&mut this, x: u8, from: mem, long: bool): void { + if !long { + this.load_vector(x, from, false); + return; + } + var upper := from; + upper.disp += 16; + this.b.text.vex_mem(vec_movdqu_load, false, x as u32, from); + this.b.text.vex_mem_imm(vec_vinsertf128, true, x as u32, x as u32, upper, 1); +} + +#! `store` of a vector: writes its lanes at an address. +#! @param this The selector. +#! @param index The instruction. +#! @param held The instruction. +#! @param to The memory. +def selector::store_lanes(&mut this, index: u32, held: &inst, to: mem): void { + val long := held.aux == access::v256 as u32; + val value := this.body.arg(index, 1); + val from := this.read(value, index); + if held.aux == access::v512 as u32 { + if from.kind == place::none { + this.b.text.packed(vec_xorps, 0, 0); + for k in 0..4u { + var at := to; + at.disp += (16 * k) as i32; + this.b.text.packed_mem(vec_movdqu_store, 0, at); + } + } else { + this.move_wide(this.memory_of(&from), to); + } + return; + } + var x: u8 = 0; + if from.kind == place::xmm { + x = from.number; + } else if from.kind == place::none { + this.vop(vec_xorps, long, 0, 0); + } else { + this.load_vector(0, this.memory_of(&from), long); + } + this.store_vector(to, x, long); + this.settle_upper(index, long); +} + +#! `vzero`: a vector of zero bytes. +#! @param this The selector. +#! @param index The instruction. +#! @param held The instruction. +def selector::zero_lanes(&mut this, index: u32, held: &inst): void { + val result := held.result; + val long := this.body.type_of(result) == vt::v256; + val made := this.p.made_at(result); + if this.body.type_of(result) == vt::v512 { + if made.kind != place::none { + val to := this.memory_of(&made); + this.b.text.packed(vec_xorps, 0, 0); + for k in 0..4u { + var at := to; + at.disp += (16 * k) as i32; + this.b.text.packed_mem(vec_movdqu_store, 0, at); + } + } + return; + } + if made.kind == place::xmm { + this.vop(vec_xorps, long, made.number, made.number); + } else if made.kind != place::none { + this.vop(vec_xorps, long, 0, 0); + this.store_vector(this.memory_of(&made), 0, long); + } + this.settle_upper(index, long); +} + +# Shuffles, written as `binary::amd64` writes vector instructions: `shufps` and +# `pshufd` choosing each lane by two bits of a byte, `pshuflw` the low four +# 16-bit lanes so, `unpcklpd` putting a register's low `f64` in both halves, +# `punpcklbw` interleaving bytes, and AVX2's `vpbroadcastb` and `vpbroadcastw` +# splatting a register's low byte or 16 bits. +const vec_shufps: u32 = 0x0001C6; +const vec_pshufd: u32 = 0x010170; +const vec_pshuflw: u32 = 0x030170; +const vec_unpcklpd: u32 = 0x010114; +const vec_punpcklbw: u32 = 0x010160; +const vec_vpbroadcastb: u32 = 0x010278; +const vec_vpbroadcastw: u32 = 0x010279; + +#! Loads a vector of constant lanes into a register, from those written after +#! the function's code, each once: a word's bits repeated across the register. +#! @param this The selector. +#! @param x The register. +#! @param word The word. +#! @param long Whether it is 32 bytes. +def selector::load_constant(&mut this, x: u8, word: u64, long: bool): void { + var made: u8[32]; + for i in 0..32u { + made[i] = ((word >> (8 * (i % 8))) & 0xFF) as u8; + } + this.load_bytes(x, made, long); +} + +#! Loads 16 or 32 constant bytes into a register, as `load_constant` does. +#! @param this The selector. +#! @param x The register. +#! @param made The bytes, of which the first 16 are read where not `long`. +#! @param long Whether it is 32 bytes. +def selector::load_bytes(&mut this, x: u8, made: u8[32], long: bool): void { + var found := this.constants.length / 32; + for k in 0..this.constants.length / 32 { + var same := true; + for i in 0..32u { + same = same && this.constants[32 * k + i] == made[i]; + } + if same { + found = k; + break; + } + } + if found == this.constants.length / 32 { + for i in 0..32u { + this.constants.append(made[i]); + } + } + this.load_vector(x, absolute(0), long); + this.constant_uses.append(pair_key((this.b.text.length - 4) as u32, found as u32)); +} + +#! Writes the vectors of constant lanes the code loads after its tables, and +#! the address of each where the code loads it. +#! @param this The selector. +def selector::write_constants(&mut this): void { + return if this.constant_uses.length == 0; + this.b.text.align_to(32); + val base := this.b.text_base + this.b.text.length; + this.b.text.put(this.constants.view()); + for i in 0..this.constant_uses.length { + val use: u64 = this.constant_uses[i]; + this.b.text.set_u32(pair_high(use) as u64, base + 32 * pair_low(use) as u64); + } +} + +#! The word of a lane's bits repeated across it, where a value is a constant. +#! @param this The selector. +#! @param value The value. +#! @param lane The type of lane. +#! @param word Where the word is written. +#! @returns Whether it is a constant. +def selector::splat_word(&this, value: u32, lane: u32, word: &mut u64): bool { + var bits: u64 = 0; + return false if !this.p.remade[value] || !this.constant_bits(value, &mut bits); + if lane == lane_f32 { + val narrow: f32 = ((&bits) as *f64)[0] as f32; + bits = ((&narrow) as *u32)[0] as u64; + } + val width := lane_bits(lane); + if width < 64 { + bits = bits & ((1u << width) - 1); + } + var made := bits; + var filled := width; + while filled < 64 { + made = made | (made << filled); + filled = filled * 2; + } + word = made; + return true; +} + +#! Makes every lane of `xmm0` the lane the instruction's operand is: a constant +#! loaded whole, and otherwise shuffled within the register from where it is. +#! @param this The selector. +#! @param index The instruction. +#! @param lane The type of lane. +#! @param long Whether it is 32 bytes. +def selector::splat_lane(&mut this, index: u32, lane: u32, long: bool): void { + val value := this.body.arg(index, 0); + val bits := lane_bits(lane); + var word: u64 = 0; + if this.splat_word(value, lane, &mut word) { + this.load_constant(0, word, long); + return; + } + # A real is shuffled into every lane within the register: an `f32` as one, + # rounded where it is held as an `f64`, and an `f64` as it is. + if lane == lane_f32 || lane == lane_f64 { + if lane == lane_f32 { + val got := this.single_reg(value, index, 0); + if got != 0 { + this.b.text.movaps(0, got); + } + this.b.text.packed_imm(vec_shufps, 0, 0, 0); + } else { + this.load_real_into(value, index, 0); + this.b.text.packed(vec_unpcklpd, 0, 0); + } + if long { + this.b.text.vex_imm(vec_vinsertf128, true, 0, 0, 0, 1); + } + return; + } + if bits == 32 { + val r := this.word_reg(value, index, reg::rax); + this.b.text.movq_to_xmm(0, r); + this.b.text.packed_imm(vec_pshufd, 0, 0, 0); + if long { + this.b.text.vex_imm(vec_vinsertf128, true, 0, 0, 0, 1); + } + return; + } + # Bytes and 16-bit lanes: AVX2 splats the register's low lane, and SSE2 + # doubles a byte into 16 bits, then those into the low four lanes, then + # those into all. + this.b.text.movq_to_xmm(0, this.word_reg(value, index, reg::rax)); + if bits < 32 && this.body.wide { + this.b.text.vex(bits == 8 ? vec_vpbroadcastb : vec_vpbroadcastw, long, 0, 0, 0); + return; + } + if bits == 8 { + this.b.text.packed(vec_punpcklbw, 0, 0); + } + if bits < 32 { + this.b.text.packed_imm(vec_pshuflw, 0, 0, 0); + this.b.text.packed_imm(vec_pshufd, 0, 0, 0); + } else { + this.b.text.packed(vec_punpcklqdq, 0, 0); + } + if long { + this.b.text.vex_imm(vec_vinsertf128, true, 0, 0, 0, 1); + } +} + +# Interleaving the low lanes of two registers, written as `binary::amd64` +# writes vector instructions: `unpcklps` of `f32`s, `punpckldq` of 32-bit +# integers, and `movlhps`, a register's low 8 bytes into another's high. +const vec_unpcklps: u32 = 0x000114; +const vec_punpckldq: u32 = 0x010162; +const vec_movlhps: u32 = 0x000116; + +#! Packs the instruction's operands into the lanes of `xmm0`, lane 0 first: four +#! 4-byte lanes from `xmm0` to `xmm3`, two by two, then the pairs; or two 8-byte +#! ones. An `f32` is packed as one, rounded where it is held as an `f64`. +#! @param this The selector. +#! @param index The instruction. +#! @param held The instruction. +#! @param lane The type of lane. +def selector::pack_lanes(&mut this, index: u32, held: &inst, lane: u32): void { + for k in 0..held.argc { + val value := this.body.arg(index, k); + val x := k as u8; + if lane == lane_f32 { + val got := this.single_reg(value, index, x); + if got != x { + this.b.text.movaps(x, got); + } + } else if lane == lane_f64 { + this.load_real_into(value, index, x); + } else { + this.b.text.movq_to_xmm(x, this.word_reg(value, index, reg::rax)); + } + } + if held.argc == 4 { + val pairs := lane == lane_f32 ? vec_unpcklps : vec_punpckldq; + this.b.text.packed(pairs, 0, 1); + this.b.text.packed(pairs, 2, 3); + this.b.text.packed(lane == lane_f32 ? vec_movlhps : vec_punpcklqdq, 0, 2); + } else { + this.b.text.packed(lane == lane_f64 ? vec_movlhps : vec_punpcklqdq, 0, 1); + } +} + +# Products of 32-bit lanes into 64; the sums of bytes' differences, which of +# zero sum them; and the upper half of a register of 32 bytes into another, +# AVX2's of integers and AVX's of reals. +const vec_pmuludq: u32 = 0x0101F4; +const vec_psadbw: u32 = 0x0101F6; +const vec_vextracti128: u32 = 0x010339; +const vec_vextractf128: u32 = 0x010319; + +# The arithmetic of one real, `addss` and `mulss`, whose `sd` is `F2`'s. +const sd_add: u32 = 0x030158; +const sd_mul: u32 = 0x030159; + +# The least or greatest of 64-bit lanes, of `xmm0` and `xmm1`, into `xmm0`: +# which is greater, as `pcmpgtq` says of signed ones and of unsigned ones with +# their top bits flipped, chooses each. +def selector::extreme_wide(&mut this, least: bool, lane: u32, long: bool): void { + this.vmove(long, 2, 0); + if lane_signed(lane) { + this.vop(vec_pcmpgtq, long, 2, 1); + } else { + this.splat_bits(3, sign_bits(lane), long); + this.vmove(long, 4, 1); + this.vop(vec_pxor, long, 2, 3); + this.vop(vec_pxor, long, 4, 3); + this.vop(vec_pcmpgtq, long, 2, 4); + } + # `xmm2` is set where `a > b`: the least takes `b` there, the greatest `a`. + val there: u8 = least ? 1 : 0; + val elsewhere: u8 = least ? 0 : 1; + this.vmove(long, 3, there); + this.vop(vec_pand, long, 3, 2); + this.vop(vec_pandn, long, 2, elsewhere); + this.vop(vec_por, long, 2, 3); + this.vmove(long, 0, 2); +} + +#! The lanes of a vector worked together into one of the lane's type: integers +#! halved again and again, each half worked into the other, which adding and +#! the least and greatest of integers may be in any order, bytes summed by +#! `psadbw`; and reals a lane at a time, lane 0 first, each shuffled down into +#! the low lane, as `simd`'s own `sum` and `product` work them, which rounding +#! makes a matter of order. +#! @param this The selector. +#! @param index The instruction. +#! @param operation `lanes_sum`, `lanes_product`, `lanes_smallest`, or `lanes_largest`. +#! @param lane The type of lane. +#! @param long Whether it is 32 bytes. +#! @param result The result. +def selector::reduce_lanes(&mut this, index: u32, operation: u32, lane: u32, long: bool, result: u32): void { + val bits := lane_bits(lane); + this.fetch_lanes(index, 0, 0, long); + if lane >= lane_f32 { + val single := lane == lane_f32; + val each := 16 / (bits / 8); + if long { + this.b.text.vex_imm(vec_vextractf128, true, 0, 0, 2, 1); + } + this.b.text.movaps(1, 0); + val op := operation == lanes_sum ? (single ? ss_add : sd_add) : (single ? ss_mul : sd_mul); + for k in 1..(long ? 2 * each : each) { + val from: u8 = k < each ? 0 : 2; + val at := k % each; + if at == 0 { + this.b.text.movaps(3, from); + } else if single { + this.vop1_imm(vec_pshufd, false, 3, from, at as u8); + } else { + this.vop1_imm(vec_pshufd, false, 3, from, 0xEE); + } + this.b.text.packed(op, 1, 3); + } + if !single || this.single[result] { + this.put_real(result, 1); + return; + } + val wide := this.real_target(result); + this.b.text.cvtss2sd(wide, 1); + this.put_real(result, wide); + return; + } + # Integers: the upper 16 bytes into the lower, then halves of those. + if long { + this.b.text.vex_imm(vec_vextracti128, true, 0, 0, 1, 1); + this.reduce_step(operation, lane); + } + if bits == 8 && operation == lanes_sum { + this.b.text.packed(vec_pxor, 1, 1); + this.b.text.packed(vec_psadbw, 0, 1); + this.vop1_imm(vec_pshufd, false, 1, 0, 0x4E); + this.b.text.packed(vec_paddq, 0, 1); + } else { + this.vop1_imm(vec_pshufd, false, 1, 0, 0x4E); + this.reduce_step(operation, lane); + if bits <= 32 { + this.vop1_imm(vec_pshufd, false, 1, 0, 0xB1); + this.reduce_step(operation, lane); + } + if bits <= 16 { + this.b.text.packed(vec_movdqa, 1, 0); + this.shift_by(vec_psrld, false, 1, 16); + this.reduce_step(operation, lane); + } + if bits == 8 { + this.b.text.packed(vec_movdqa, 1, 0); + this.shift_by(vec_psrlw, false, 1, 8); + this.reduce_step(operation, lane); + } + } + val into := this.target(result, reg::rax); + this.b.text.movq_from_xmm(into, 0); + this.put(result, into); +} + +# Works `xmm1`'s lanes into `xmm0`'s, of 16 bytes, as a reduction's step does. +def selector::reduce_step(&mut this, operation: u32, lane: u32): void { + if operation == lanes_sum { + this.b.text.packed(by_width(lane, vec_paddb, vec_paddw, vec_paddd, vec_paddq), 0, 1); + } else if lane_bits(lane) == 64 { + this.extreme_wide(operation == lanes_smallest, lane, false); + } else { + this.b.text.packed(binary_of(operation == lanes_smallest ? lanes_min : lanes_max, lane), 0, 1); + } +} + +# `op x, y, imm` of an instruction reading only `y`, as `pshufd`, where VEX names +# no other register. +def selector::vop1_imm(&mut this, op: u32, long: bool, x: u8, y: u8, imm: u8): void { + if long || this.b.text.avx { + this.b.text.vex_imm(op, long, x as u32, 0, y as u32, imm); + } else { + this.b.text.packed_imm(op, x as u32, y as u32, imm); + } +} + +# Shifts each lane of a register by a constant count, given to the shift in +# `xmm4`. +def selector::shift_by(&mut this, op: u32, long: bool, x: u8, count: u64): void { + this.b.text.mov_imm(reg::rax, count); + this.b.text.movq_to_xmm(4, reg::rax); + this.vop(op, long, x, 4); +} + +#! A shift of lanes, by a count the same for every lane, given as a `u32`. 16, +#! 32, and 64-bit lanes have SSE2's instructions; bytes are shifted as 16-bit +#! lanes, then masked to what each byte keeps of itself; and a signed shift +#! right of bytes or 64-bit lanes shifts them as unsigned, then gives each the +#! sign it moved down, flipping and taking away the bit it came to. A signed +#! shift right of more than a lane's bits is one of all but one. +#! @param this The selector. +#! @param index The instruction. +#! @param operation The shift. +#! @param lane The type of lane. +#! @param long Whether it is 32 bytes. +def selector::shift_lanes(&mut this, index: u32, operation: u32, lane: u32, long: bool): void { + val bits := lane_bits(lane); + val left := operation == lanes_shift_left; + val signs := !left && lane_signed(lane) && (bits == 8 || bits == 64); + # The count, a `u32`, in the low word of `xmm1`, the same for every lane. + if signs { + this.load_into(this.body.arg(index, 1), index, reg::rax); + this.b.text.mov_imm(reg::rcx, bits - 1); + this.b.text.alu(alu::cmp, reg::rax, reg::rcx); + this.b.text.cmov(cc::above, reg::rax, reg::rcx); + this.b.text.movq_to_xmm(1, reg::rax); + } else { + this.b.text.movq_to_xmm(1, this.word_reg(this.body.arg(index, 1), index, reg::rax)); + } + this.fetch_lanes(index, 0, 0, long); + if bits == 64 && signs { + this.vop(vec_psrlq, long, 0, 1); + this.splat_bits(2, sign_bits(lane), long); + this.vop(vec_psrlq, long, 2, 1); + this.vop(vec_pxor, long, 0, 2); + this.vop(vec_psubq, long, 0, 2); + return; + } + if bits != 8 { + this.vop(shift_of(operation, lane), long, 0, 1); + return; + } + # Bytes: shifted as 16 bits, each keeps the bits `0xFF` shifted so keeps, the + # mask made from a 16-bit lane shifted, then its low byte splat. + this.vop(left ? vec_psllw : vec_psrlw, long, 0, 1); + this.splat_bits(2, 0x00FF00FF00FF00FF, long); + this.vop(left ? vec_psllw : vec_psrlw, long, 2, 1); + this.splat_low_byte(2, long); + this.vop(vec_pand, long, 0, 2); + if signs { + this.splat_bits(3, 0x0080008000800080, long); + this.vop(vec_psrlw, long, 3, 1); + this.splat_low_byte(3, long); + this.vop(vec_pxor, long, 0, 3); + this.vop(vec_psubb, long, 0, 3); + } +} + +# Choosing bytes by those of another register, SSSE3's; widening bytes into +# 32- or 64-bit lanes; and choosing 32-bit lanes across 32 bytes, AVX2's. +const vec_pshufb: u32 = 0x010200; +const vec_vpmovzxbd: u32 = 0x010231; +const vec_vpmovzxbq: u32 = 0x010232; +const vec_vpermd: u32 = 0x010236; + +#! Lanes in another order: lane `i` is the lane the operand's byte `i` names, +#! each one of the vector's, as `simd`'s `shuffle` checks in a checked program. +#! Of 16 bytes, each +#! lane's number is spread over its bytes, as `pshufb` takes it; of 32, 32-bit +#! lanes' numbers are widened, and 64-bit lanes' made two 32-bit lanes', as +#! `vpermd` takes them. +#! @param this The selector. +#! @param index The instruction. +#! @param lane The type of lane. +#! @param long Whether it is 32 bytes. +def selector::shuffle_lanes(&mut this, index: u32, lane: u32, long: bool): void { + val width := lane_bits(lane) / 8; + this.fetch_lanes(index, 1, 1, false); + this.fetch_lanes(index, 0, 0, long); + if long { + if width == 4 { + this.b.text.vex(vec_vpmovzxbd, true, 1, 0, 1); + } else { + this.b.text.vex(vec_vpmovzxbq, true, 1, 0, 1); + this.shift_by(vec_psllq, true, 1, 1); + this.vop1_imm(vec_pshufd, true, 1, 1, 0xA0); + this.load_constant(2, 0x0000000100000000, true); + this.vop(vec_paddd, true, 1, 2); + } + this.b.text.vex(vec_vpermd, true, 0, 1, 0); + return; + } + if width > 1 { + # Each lane's number into each of its bytes, times its width, plus where + # each byte is within it. + var spread: u8[32]; + for i in 0..32u { + spread[i] = ((i % 16) / width) as u8; + } + this.load_bytes(2, spread, false); + this.b.text.packed(vec_pshufb, 1, 2); + this.shift_by(vec_psllw, false, 1, width == 2 ? 1 : width == 4 ? 2 : 3); + var within: u64 = 0; + for i in 0..8u { + within = within | ((i % width) << (8 * i)); + } + this.load_constant(2, within, false); + this.b.text.packed(vec_paddb, 1, 2); + } + this.b.text.packed(vec_pshufb, 0, 1); +} + +# Makes every byte of a register its lowest, as it is in each 16-bit lane. +def selector::splat_low_byte(&mut this, x: u8, long: bool): void { + this.vop(vec_punpcklbw, long, x, x); + this.vop1_imm(vec_pshuflw, long, x, x, 0); + this.vop1_imm(vec_pshufd, long, x, x, 0); +} + +# `op x, y`: `x = x op y`, where VEX names `x` twice. +def selector::vop(&mut this, op: u32, long: bool, x: u8, y: u8): void { + if long { + this.b.text.vex(op, true, x as u32, x as u32, y as u32); + } else { + this.b.text.packed(op, x as u32, y as u32); + } +} + +# `op x, y` of an instruction of one operand, as `sqrtps`, where VEX names no +# other. +def selector::vop1(&mut this, op: u32, long: bool, x: u8, y: u8, imm: i32): void { + if long { + this.b.text.vex(op, true, x as u32, 0, y as u32); + } else { + this.b.text.packed(op, x as u32, y as u32); + } + if imm >= 0 { + this.b.text.byte(imm as u8); + } +} + +# `op x, y, imm`, as `cmpps` with its predicate. +def selector::vop_imm(&mut this, op: u32, long: bool, x: u8, y: u8, imm: u8): void { + if long { + this.b.text.vex_imm(op, true, x as u32, x as u32, y as u32, imm); + } else { + this.b.text.packed_imm(op, x as u32, y as u32, imm); + } +} + +# Copies a register. +def selector::vmove(&mut this, long: bool, x: u8, y: u8): void { + this.vop1(vec_movdqa, long, x, y, -1); +} + +# Makes every lane of a register its bits from a word repeated, loaded whole. +def selector::splat_bits(&mut this, x: u8, word: u64, long: bool): void { + this.load_constant(x, word, long); +} + +# Sets every bit of a register, which integers on 32 bytes have AVX2 for, and +# reals AVX, comparing by a predicate always true. +def selector::all_ones(&mut this, x: u8, long: bool, real: bool): void { + if long && real { + this.b.text.vex_imm(vec_cmpps, true, x as u32, x as u32, x as u32, 0x0F); + return; + } + this.vop(vec_pcmpeqd, long, x, x); +} + +# The words of a lane's top bit, and of all but it, for each width of lane. +def sign_bits(lane: u32): u64 { + val bits := lane_bits(lane); + return bits == 8 ? 0x8080808080808080 : bits == 16 ? 0x8000800080008000 + : bits == 32 ? 0x8000000080000000 : 0x8000000000000000; +} + +# Which of four instructions, one for each width of lane, a lane takes. +def by_width(lane: u32, eight: u32, sixteen: u32, thirty_two: u32, sixty_four: u32): u32 { + val bits := lane_bits(lane); + return bits == 8 ? eight : bits == 16 ? sixteen : bits == 32 ? thirty_two : sixty_four; +} + +# The shift of an operation, as the lane's sign takes it. +def shift_of(operation: u32, lane: u32): u32 { + if operation == lanes_shift_left { + return by_width(lane, 0, vec_psllw, vec_pslld, vec_psllq); + } + return lane_signed(lane) ? by_width(lane, 0, vec_psraw, vec_psrad, 0) : by_width(lane, 0, vec_psrlw, vec_psrld, vec_psrlq); +} + +# The arithmetic, bitwise operations, and rounding the rest are: those of two +# operands working into the first, and of one in place, into `xmm0`. +def selector::unary_or_binary(&mut this, index: u32, operation: u32, lane: u32, long: bool): void { + val real := lane >= lane_f32; + val doubles: u32 = lane == lane_f64 ? vec_doubles : 0; + if operation == lanes_negate { + if real { + # A real's sign flips. + this.splat_bits(1, sign_bits(lane), long); + this.fetch_lanes(index, 0, 0, long); + this.vop(vec_xorps | doubles, long, 0, 1); + } else { + this.fetch_lanes(index, 0, 1, long); + this.vop(vec_pxor, long, 0, 0); + this.vop(by_width(lane, vec_psubb, vec_psubw, vec_psubd, vec_psubq), long, 0, 1); + } + } else if operation == lanes_not { + this.all_ones(1, long, real); + this.fetch_lanes(index, 0, 0, long); + this.vop(real ? vec_xorps : vec_pxor, long, 0, 1); + } else if operation == lanes_abs { + if real { + this.splat_bits(1, ~sign_bits(lane), long); + this.fetch_lanes(index, 0, 0, long); + this.vop(vec_andps | doubles, long, 0, 1); + } else { + this.fetch_lanes(index, 0, 0, long); + if lane_signed(lane) && lane_bits(lane) == 64 { + # Each lane's sign, from its high half's, flips it and adds one where set. + this.vop1_imm(vec_pshufd, long, 1, 0, 0xF5); + this.shift_by(vec_psrad, long, 1, 31); + this.vop(vec_pxor, long, 0, 1); + this.vop(vec_psubq, long, 0, 1); + } else if lane_signed(lane) { + this.vop1(by_width(lane, vec_pabsb, vec_pabsw, vec_pabsd, 0), long, 0, 0, -1); + } + } + } else if !real && operation == lanes_mul && lane_bits(lane) != 16 && (lane_bits(lane) != 32 || (!long && !this.body.wide)) { + this.fetch_lanes(index, 0, 0, long); + this.fetch_lanes(index, 1, 1, long); + if lane_bits(lane) == 8 { + # The even bytes' products are the low bytes of the 16-bit lanes', and the + # odd ones', moved down and back, the high bytes. + this.vmove(long, 2, 0); + this.vmove(long, 3, 1); + this.vop(vec_pmullw, long, 0, 1); + this.shift_by(vec_psrlw, long, 2, 8); + this.shift_by(vec_psrlw, long, 3, 8); + this.vop(vec_pmullw, long, 2, 3); + this.shift_by(vec_psllw, long, 2, 8); + this.splat_bits(3, 0x00FF00FF00FF00FF, long); + this.vop(vec_pand, long, 0, 3); + this.vop(vec_por, long, 0, 2); + } else if lane_bits(lane) == 32 { + # The even lanes' products, and the odd ones' moved down, each of 64 bits, + # whose low halves are put back in order. + this.vmove(long, 2, 0); + this.vmove(long, 3, 1); + this.vop(vec_pmuludq, long, 0, 1); + this.shift_by(vec_psrlq, long, 2, 32); + this.shift_by(vec_psrlq, long, 3, 32); + this.vop(vec_pmuludq, long, 2, 3); + this.vop1_imm(vec_pshufd, long, 0, 0, 0x08); + this.vop1_imm(vec_pshufd, long, 2, 2, 0x08); + this.vop(vec_punpckldq, long, 0, 2); + } else { + # The low halves' product, and each high half by the other's low, added + # into the high half. + this.vmove(long, 2, 0); + this.vmove(long, 3, 1); + this.shift_by(vec_psrlq, long, 2, 32); + this.shift_by(vec_psrlq, long, 3, 32); + this.vop(vec_pmuludq, long, 2, 1); + this.vop(vec_pmuludq, long, 3, 0); + this.vop(vec_paddq, long, 2, 3); + this.shift_by(vec_psllq, long, 2, 32); + this.vop(vec_pmuludq, long, 0, 1); + this.vop(vec_paddq, long, 0, 2); + } + } else if !real && lane_bits(lane) == 64 && (operation == lanes_min || operation == lanes_max) { + this.fetch_lanes(index, 0, 0, long); + this.fetch_lanes(index, 1, 1, long); + this.extreme_wide(operation == lanes_min, lane, long); + } else if operation == lanes_round { + # Truncated, then a half or more left of each moves it one away from zero, + # as `math::round` gives it: the part left is exact, and a lane it does not + # move keeps its own sign, as `-0` does. + val doubles: u32 = lane == lane_f64 ? vec_doubles : 0; + val f64s := lane == lane_f64; + this.fetch_lanes(index, 0, 0, long); + this.vop1(f64s ? vec_roundpd : vec_roundps, long, 1, 0, 11); + this.vmove(long, 2, 0); + this.vop(vec_subps | doubles, long, 2, 1); + this.splat_bits(3, ~sign_bits(lane), long); + this.vop(vec_andps | doubles, long, 2, 3); + this.splat_bits(4, f64s ? 0x3FE0000000000000 : 0x3F0000003F000000, long); + this.vop_imm(vec_cmpps | doubles, long, 4, 2, 2); + this.splat_bits(3, sign_bits(lane), long); + this.vop(vec_andps | doubles, long, 3, 0); + this.splat_bits(2, f64s ? 0x3FF0000000000000 : 0x3F8000003F800000, long); + this.vop(vec_orps | doubles, long, 3, 2); + this.vop(vec_addps | doubles, long, 3, 1); + this.vop(vec_andps | doubles, long, 3, 4); + this.vop(vec_andnps | doubles, long, 4, 1); + this.vop(vec_orps | doubles, long, 4, 3); + this.vmove(long, 0, 4); + } else if operation == lanes_sqrt { + this.fetch_lanes(index, 0, 0, long); + this.vop1(vec_sqrtps | doubles, long, 0, 0, -1); + } else if operation >= lanes_floor && operation <= lanes_round_even { + # Rounding toward negative infinity, positive, zero, or the nearest, without + # noting it was inexact. + val mode: i32 = operation == lanes_floor ? 9 : operation == lanes_ceil ? 10 : operation == lanes_trunc ? 11 : 8; + this.fetch_lanes(index, 0, 0, long); + this.vop1(lane == lane_f64 ? vec_roundpd : vec_roundps, long, 0, 0, mode); + } else { + this.fetch_lanes(index, 0, 0, long); + this.fetch_lanes(index, 1, 1, long); + this.vop(binary_of(operation, lane), long, 0, 1); + } +} + +# The instruction of an operation of two operands on lanes of a type. +def binary_of(operation: u32, lane: u32): u32 { + val real := lane >= lane_f32; + val doubles: u32 = lane == lane_f64 ? vec_doubles : 0; + if operation == lanes_add { + return real ? vec_addps | doubles : by_width(lane, vec_paddb, vec_paddw, vec_paddd, vec_paddq); + } + if operation == lanes_sub { + return real ? vec_subps | doubles : by_width(lane, vec_psubb, vec_psubw, vec_psubd, vec_psubq); + } + if operation == lanes_mul { + return real ? vec_mulps | doubles : by_width(lane, 0, vec_pmullw, vec_pmulld, 0); + } + return vec_divps | doubles if operation == lanes_div; + # Of reals, as a mask's lanes, the bits are combined as reals', which AVX has + # for 32 bytes. + return (real ? vec_andps : vec_pand) if operation == lanes_and; + return (real ? vec_orps : vec_por) if operation == lanes_or; + return (real ? vec_xorps : vec_pxor) if operation == lanes_xor; + val least := operation == lanes_min; + return match lane { + 0 => least ? vec_pminsb : vec_pmaxsb, + 1 => least ? vec_pminub : vec_pmaxub, + 2 => least ? vec_pminsw : vec_pmaxsw, + 3 => least ? vec_pminuw : vec_pmaxuw, + 4 => least ? vec_pminsd : vec_pmaxsd, + else => least ? vec_pminud : vec_pmaxud + }; +} + +# Compares lanes into a mask. Reals compare by a predicate, the greater ones +# with their operands swapped. Integers have only equality and `>`, of signed +# lanes, so unsigned ones flip their top bits first, `<` is `>` swapped, and +# `<=`, `>=`, and `!=` are what their opposite is not. Gives the register +# holding the mask. +def selector::compare_lanes(&mut this, index: u32, operation: u32, lane: u32, long: bool): u8 { + val real := lane >= lane_f32; + val ordering := operation >= lanes_less; + if !real && ordering && !lane_signed(lane) { + this.splat_bits(2, sign_bits(lane), long); + } + this.fetch_lanes(index, 0, 0, long); + this.fetch_lanes(index, 1, 1, long); + if real { + val doubles: u32 = lane == lane_f64 ? vec_doubles : 0; + val swapped := operation == lanes_greater || operation == lanes_greater_equal; + val predicate: u8 = operation == lanes_equal ? 0 : operation == lanes_not_equal ? 4 + : operation == lanes_less || operation == lanes_greater ? 1 : 2; + if swapped { + this.vop_imm(vec_cmpps | doubles, long, 1, 0, predicate); + return 1; + } + this.vop_imm(vec_cmpps | doubles, long, 0, 1, predicate); + return 0; + } + + if ordering && !lane_signed(lane) { + this.vop(vec_pxor, long, 0, 2); + this.vop(vec_pxor, long, 1, 2); + } + val equal := by_width(lane, vec_pcmpeqb, vec_pcmpeqw, vec_pcmpeqd, vec_pcmpeqq); + val above := by_width(lane, vec_pcmpgtb, vec_pcmpgtw, vec_pcmpgtd, vec_pcmpgtq); + if operation == lanes_equal { + this.vop(equal, long, 0, 1); + } else if operation == lanes_not_equal { + this.vop(equal, long, 0, 1); + this.all_ones(1, long, false); + this.vop(vec_pxor, long, 0, 1); + } else if operation == lanes_greater { + this.vop(above, long, 0, 1); + } else if operation == lanes_less { + this.vop(above, long, 1, 0); + this.vmove(long, 0, 1); + } else if operation == lanes_less_equal { + this.vop(above, long, 0, 1); + this.all_ones(1, long, false); + this.vop(vec_pxor, long, 0, 1); + } else { + this.vop(above, long, 1, 0); + this.all_ones(0, long, false); + this.vop(vec_pxor, long, 0, 1); + } + return 0; +} + +# The least or greatest of real lanes, as IEEE 754's `minimum` and `maximum`, +# which `std::math` gives: `minps` gives the lesser where both are numbers and +# differ, equal lanes give the sign of either zero (`|` of their bits for the +# least, `&` for the greatest), and where either is NaN, `a + b`. Gives the +# register holding the result. +def selector::real_extreme(&mut this, index: u32, operation: u32, lane: u32, long: bool): u8 { + val doubles: u32 = lane == lane_f64 ? vec_doubles : 0; + val least := operation == lanes_min; + this.fetch_lanes(index, 0, 0, long); + this.fetch_lanes(index, 1, 1, long); + this.vmove(long, 2, 0); + this.vop((least ? vec_minps : vec_maxps) | doubles, long, 2, 1); + this.vmove(long, 3, 0); + this.vop_imm(vec_cmpps | doubles, long, 3, 1, 0); + this.vmove(long, 4, 0); + this.vop((least ? vec_orps : vec_andps) | doubles, long, 4, 1); + this.vop(vec_andps | doubles, long, 4, 3); + this.vop(vec_andnps | doubles, long, 3, 2); + this.vop(vec_orps | doubles, long, 3, 4); + this.vmove(long, 4, 0); + this.vop_imm(vec_cmpps | doubles, long, 4, 1, 3); + this.vmove(long, 2, 0); + this.vop(vec_addps | doubles, long, 2, 1); + this.vop(vec_andps | doubles, long, 2, 4); + this.vop(vec_andnps | doubles, long, 4, 3); + this.vop(vec_orps | doubles, long, 4, 2); + return 4; +} + +# The bits of the lanes a mask has set, as a word: each lane's top bit, as +# `movmskps` and `pmovmskb` gather them, 16-bit lanes packed into bytes first. +def selector::mask_bits(&mut this, index: u32, held: &inst, lane: u32, long: bool): void { + val bits := lane_bits(lane); + var x: u8 = 0; + if bits == 16 { + this.fetch_lanes(index, 0, 0, long); + this.b.text.packed(vec_packsswb, 0, 0); + } else { + x = this.lanes_reg(this.read(this.body.arg(index, 0), index), 0, long); + } + val op := bits == 32 ? vec_movmskps : bits == 64 ? vec_movmskps | vec_doubles : vec_pmovmskb; + val into := this.target(held.result, reg::rax); + if long { + this.b.text.vex(op, true, into as u32, 0, x as u32); + } else { + this.b.text.packed(op, into as u32, x as u32); + } + if bits == 16 { + this.b.text.alu_imm(alu::band, into, 0xFF); + } + this.put(held.result, into); +} diff --git a/native/native.sakura b/native/native.sakura new file mode 100644 index 00000000..f573f420 --- /dev/null +++ b/native/native.sakura @@ -0,0 +1,1909 @@ +#! @file native.sakura +#! @author John Christman (sorakatadzuma@gmail.com) +#! @copyright Malunal Studios, LLC. +#! @license MIT +#! +#! Contains the building of executables: the image the runtime reads, the code +#! of every function, the stubs a trap and a fault are reported through, the +#! entry the system starts the program at, and the file, a static x86-64 Linux +#! executable loaded at a fixed address as four segments: +#! +#! read the file headers, then the image the runtime reads +#! read, write the state of the runtime and the program's globals, zeroed +#! read, execute the stubs, `_start`, then every function +#! read the line tables of the functions +#! +#! Frames are on the stack, each below the caller's return address and frame +#! pointer, so a trap reports where it happened by walking the chain of `rbp`. +#! A function saves the registers a call keeps that it uses in its frame. The +#! runtime, the module `runtime` of the library found beside the compiler, is +#! compiled into each executable as the rest of the program is. + +import std::containers; +import std::io; +import std::thread; +import sakura::analyzer; +import sakura::compiler; +import binary::amd64; +import binary::elf; +import binary::pe; +module sakura::native; + + +#! The functions of `runtime` the generated code calls. +pub enum helper : u8 { + fail, #! Reports a trap, given its error, where, and the chain of frames. + arguments, #! Writes the arguments of `main`. + allocate_zeroed, #! Allocates a zeroed block. + allocate, #! Allocates a block not cleared. + release, #! Releases a block. + resize, #! Resizes a block. + equal, #! Whether values are equal. + format_begin, #! Begins text. + format_text, #! Adds bytes to text. + format_value, #! Adds a value to text. + format_owned, #! Takes the text made. + exit, #! Exits with a status. + abort, #! Stops the program, reporting where. + fault, #! Stops the program, reporting why and where. + processor, #! The vector instructions the program may use, of those the processor has. + start_thread, #! Starts a thread running a function. + thread_main, #! What a thread runs on its own stack. + count, #! How many there are; no helper itself. +} + +#! The name of each helper, as `runtime` declares it, and how many +#! parameters it takes. +const helper_names: strview[17] = [ + "fail", "arguments", "allocate_zeroed", "allocate", "release", "resize", "equal", + "format_begin", "format_text", "format_value", "format_owned", "exit", "abort", "fault", "processor", + "start_thread", "thread_main" +]; +const helper_arities: u32[17] = [3, 1, 1, 1, 1, 2, 3, 0, 2, 2, 1, 1, 0, 2, 1, 1, 0]; + +# The words of the runtime's state, as `runtime::state` declares them, +# and those the code keeps after them. +pub const state_base: u64 = 0; #! The top of the stack, where frames begin. +pub const state_limit: u64 = 1; #! The lowest a frame may reach. +pub const state_trap_frame: u64 = 2; #! The bottom of the stack, past the limit, which a trap's report may use. +pub const state_itself: u64 = 3; #! The record itself. +pub const state_argc: u64 = 4; #! The arguments the program started with. +pub const state_argv: u64 = 5; +pub const state_reporting: u64 = 6; #! Whether a trap is being reported, which another trap ends at once. +pub const state_c_top: u64 = 7; +pub const state_c_frame: u64 = 8; +pub const state_c_return: u64 = 9; +pub const state_features: u64 = 10; #! The vector instructions the program may use, as the processor running it has them. +pub const state_signals: u64 = 11; #! The signals the program handles that came since it last asked, one bit each; only the first thread's notes them. +pub const state_own: u64 = 12; #! On Windows, where the slot of the system's record of the thread holds the thread's own record: `0x1480 + 8 * TlsAlloc()`. +# Threads, each of which has a record of these words, which `gs` points at in it: +# the first thread's is the state, and holds what they all share. +pub const state_next: u64 = 13; #! The next thread's record. +pub const state_tid: u64 = 14; #! The system's number for the thread, which the system clears as it ends. +pub const state_body: u64 = 19; #! Two words: the function the thread runs, then a word: the context it is given. +pub const state_map: u64 = 22; #! Where the thread's stack is mapped, and its bytes. +pub const state_map_size: u64 = 23; +pub const state_handle: u64 = 24; #! On Windows, the thread's handle, which reaping it waits on. +pub const state_saved: u64 = 25; #! On Windows, where the stack the system started the thread on was, which it ends on. +pub const state_running: u64 = 26; #! 1 while the thread runs. +pub const state_signalled: u64 = 29; #! On Windows, of the first: the event the handler sets when it notes a signal, which a wait waits on, or 0. +pub const state_disposed: u64 = 30; #! On Windows, of the first: a signal caught in a bit, one ignored in the bit 32 above it, and the console's handler being set in bit 0. +pub const state_words: u64 = 32; + + +#! The slots the system's record of a thread holds its own slots in, as the base +#! `gs` points at, which the chosen slot is `8 *` its index past. +pub const tls_slots: u64 = 0x1480; +pub const tls_count: u64 = 64; + +#! The memory of a word of the running thread's own record. On Linux `gs` +#! points at it, so a word is at the offset through `gs`. On Windows `gs` +#! points at the system's record of the thread, a slot of which the start +#! chose for the thread's own record, so it is read from the slot into `rcx` +#! first, which no instruction keeps anything in across another. +#! @param this The building. +#! @param word The word. +#! @returns The memory. +pub def building::own_word(&mut this, word: u64): mem { + if !this.options.windows { + return own(8 * word); + } + this.own_record(reg::rcx); + return at(reg::rcx, (8 * word) as i32); +} + +#! Loads the address of the running thread's own record, on Windows, from the +#! slot of the system's record of the thread the state names. +#! @param this The building. +#! @param into The register, which is 0 on a thread the program never started. +pub def building::own_record(&mut this, into: reg): void { + this.text.load(8, false, into, amd64::absolute(this.state_address(state_own))); + this.text.load(8, false, into, own_at(into)); +} + +#! Where the executable is loaded, and the size of a page. +pub const base_address: u64 = 0x400000; +pub const page_size: u64 = 0x1000; + +#! Bytes of the stack past its limit, which a trap's report runs in. +pub const stack_reserve: u64 = 262144; + +#! The bytes of the stack, unless asked otherwise. +pub const default_stack: u64 = 33554432; + +#! How many texts the image holds: the descriptions of the machine's errors by +#! their codes, then the fragments of a report. +const text_count: u64 = 38; + +#! What a vtable's slot names where it names its function itself. +const direct_method: u64 = 0xFFFFFFFFFFFFFFFF; + +#! Where in a function's code the code from a place in the source begins. +pub struct line_row { + var offset: u64; #! From where the function begins. + var at: u64; #! Where in the source: one more than the file, then the byte, or 0 for the function's declaration. + var site: u32; #! One more than the inline site it is in, or 0. +} + +#! How an executable is built. +pub struct build_options { + pub var output: strview; #! The file it is written to. + pub var verify: bool; #! Whether where each function's values were placed is checked, by replaying it. + var stack: u64; #! The bytes of its stack, or 0 for the default. + pub var debug: bool; #! Whether its debugging information is written too, to OUTPUT.petal. + pub var windows: bool; #! Whether it is built for Windows, rather than Linux. + pub var threads: u32; #! How many threads place the values of functions at once, beside the one selecting their code; 0 or 1 for that one alone. +} + +#! What building an executable keeps. +pub struct building { + var c: &mut lowerer; #! The program, lowered and optimized. + var options: build_options; + var problems: vector; #! What could not be built. + + var rodata: byte_writer; #! The image, after the file headers. + var text: assembly; #! The code. + var late: byte_writer; #! The line tables. + + var rodata_base: u64; + var data_base: u64; + var data_size: u64; + var text_base: u64; + var late_base: u64; + var globals: u64; #! Where the globals are. + var got: u64; #! Where the words holding the addresses of C functions are. + var slots: vector; #! The word of each C function the code names, or `never`. + var linked_count: u64; #! How many C functions the code names, each given a word. + var dynamic: bool; #! Whether the executable calls C, so the system's loader runs it. + var dynamic_parts: elf::linking; #! Where what the loader reads is. + var relocations: u64; #! Within the image, where the loader is told of each word. + var entries: vector; #! Of each function C calls, the code C calls it through. + + # Windows: the functions imported, and the records the loader reads. + var imports_at: vector; #! Of each of the backend's own system imports, its word in the table of addresses. + var import_names: vector; #! Of each word of the table of addresses, where its function's name is, which the loader overwrites, or 0 for a library's terminator. + var import_firsts: vector; #! Of each library, its first word in the table of addresses. + var descriptors: u64; #! Within the image, the record of each library imported. + var library_count: u64; #! How many libraries are imported. + var import_words: u64; #! Words in the table of addresses, each library's and a terminator. + + # Where records are, as addresses, or offsets within the image. + var image_address: u64; + var image_at: u64; + var texts_at: u64; + var layouts_at: u64; + var function_table: u64; #! The address of each function, by index, as a function value holds it less one. + var vtable_table: u64; #! The address of each vtable's methods. + var records_at: u64; + var callbacks_at: u64; + var data_at: vector; #! Of each datum. + var vtable_methods: vector; #! Of each vtable's methods. + var retraits_at: vector; #! Of each map between traits' vtables. + var callback_slots: vector; #! Of each function C calls, its word among the callbacks', or `never`. + + var helpers: u32[17]; #! The function of each helper. + var system_start_function: u32; #! On Windows, `runtime::system_start`, which the start runs before the globals. + var runtime: vector; #! Whether each function is the runtime's, which traces leave out. + var starts: vector; #! Where each function's code begins in the text. + var ends: vector; #! Where it ends. + var calls: fixup_list; #! Each call or jump to a function, by where its displacement is, and the function. + var methods: vector; #! The code each vtable's slot names, by vtable then slot. + var rows: vector; #! Each function's rows of its line table, one after another. + var row_first: vector; #! Where each function's rows begin in `rows`. + var debug: debugging; #! What debugging information needs, where it is written. + + # Code every function shares. + var trap_stub: u64; + var trap_framed: u64; #! Where the trap stub has pushed `rbp`, + var trap_based: u64; #! and where it has made its frame. + var faults: u64; + var restorer: u64; + var noting: u64; + # Windows only. + var signalled: u64; #! Where a signal the program handles is noted, by its number in `rcx`. + var catching: u64; #! What `catch_signal` calls, with what it is asked in `rcx`. + var stranger: u64; #! What a callback on a thread the program never started reports through. + var beginning: u64; #! Where a thread the program starts begins, with its record in `rcx`. + var overflow_stub: u64; + var missing: u64; #! What a function never lowered begins at. + var missing_method: u64; #! What a slot of a vtable no function fills names. + var safe_point: u64; #! The code a safe point calls where a signal came, once written, or `never`. + var start: u64; + var entry_end: u64; #! Where `_start` ends. + var code_end: u64; #! Where the fault handler's comparison with the end of the code is. + var stack: u64; +} + +#! Builds an executable of a program, lowered and optimized, writing it to its +#! file. +#! @param c The program. +#! @param options How it is built. +#! @returns What could not be built, which is nothing where it was written. +pub def build_executable(c: &mut lowerer, options: build_options): vector { + var b := building { + c = c, + options = options, + problems = vector::::new(), + rodata = byte_writer::new(), + text = assembly::new(), + late = byte_writer::new(), + data_at = vector::::new(), + vtable_methods = vector::::new(), + retraits_at = vector::::new(), + callback_slots = vector::::new(), + slots = vector::::new(), + entries = vector::::new(), + imports_at = vector::::new(), + import_names = vector::::new(), + import_firsts = vector::::new(), + runtime = vector::::new(), + starts = vector::::new(), + ends = vector::::new(), + calls = fixup_list::new(nothing {}), + methods = vector::::new(), + rows = vector::::new(), + row_first = vector::::new(), + debug = debugging::new(), + stack = options.stack != 0 ? round_up(options.stack, page_size) : default_stack, + safe_point = never as u64 + }; + b.prepare(); + if b.problems.length != 0 { + return move(&mut b.problems); + } + + # The image and the data are placed before the code, which refers to them. + val headers := options.windows ? pe::headers_size : elf::headers_size(4, b.dynamic); + b.rodata_base = base_address + headers; + b.image(); + if options.windows { + b.imports(); + } else if b.dynamic { + b.dynamic_records(); + } + b.data_base = round_up(b.rodata_base + b.rodata.length, page_size); + b.globals = b.data_base + state_words * 8; + b.got = b.globals + round_up(b.c.program.globals, 8); + b.data_size = b.got - b.data_base + (options.windows ? b.import_words : b.linked_count) * 8; + if options.windows { + # The loader finds each library by its descriptor, whose words it fills from + # the table of addresses once that is placed. + b.relocate_imports(); + } else { + for i in 0..b.linked_count { + b.rodata.set_u64(b.relocations + 24 * i, b.got + 8 * i); + } + } + b.text_base = round_up(b.data_base + b.data_size, page_size); + b.image_address = b.rodata_base + b.image_at; + b.rodata.set_u64(b.image_at, b.data_base); + b.rodata.set_u64(b.image_at + 7 * 8, b.globals); + + b.shared_code(); + if options.windows { + b.entry_windows(); + } else { + b.entry(); + } + val count := b.c.program.functions.length; + b.starts.resize(count); + b.ends.resize(count); + b.row_first.resize(count + 1); + # How each prologue saves registers is noted for Windows, whose executables + # say how each function unwinds, as well as for debugging information. + if options.debug || options.windows { + b.debug.resize(count); + } + if options.debug { + b.lay_out_variables(); + } + b.select_all(count); + b.row_first[count] = b.rows.length as u32; + if options.debug { + b.debug.return_first[count] = b.debug.returns.length as u32; + b.debug.variable_first[count] = b.debug.variables.length as u32; + } + b.adapters(); + b.entries.resize(count); + for i in 0..count { + if b.callback_slots[i] != never { + b.entries[i] = b.callback_entry(i as u32); + } + } + b.calls.resolve(&mut b.text, b.starts.view()); + b.text.set_u32(b.code_end, b.text_base + b.text.length); + + b.late_base = round_up(b.text_base + b.text.length, page_size); + b.places(); + if b.problems.length == 0 { + b.write(); + } + return move(&mut b.problems); +} + +#! Works out the layout of each variable of each function, which debugging +#! information names its type by. It is done once the image is written, so the +#! layouts it makes leave the image as it is without debugging information. +#! @param this The building. +def building::lay_out_variables(&mut this): void { + for f in 0..this.c.program.functions.length { + for v in 0..this.c.program.functions[f].body.variables.length { + val kind: u32 = this.c.program.functions[f].body.variables[v].kind; + val layout := this.c.layout_of(kind); + this.c.program.functions[f].body.variables[v].layout = layout; + } + } +} + +#! Notes what could not be built. +#! @param this The building. +#! @param what What, said in words. +def building::problem(&mut this, what: strview): void { + this.problems.append(string::from(what, nothing {})); +} + + +# Preparing. + +#! Whether a declaration is the runtime's, of the module `runtime`. +#! @param this The building. +#! @param decl The declaration. +#! @returns Whether it is. +def building::in_runtime(&this, decl: u32): bool { + return false if decl == 0; + val owner: u32 = this.c.checker.decls.modules.p[decl]; + return owner != 0 && this.c.checker.modules.parents[owner] == 0 + && this.c.checker.names.text(this.c.checker.modules.names[owner]) == "runtime"; +} + +#! Finds the runtime's helpers, which every function lowered calls, and lowers +#! them where nothing else made them. +#! @param this The building. +def building::prepare(&mut this): void { + if this.c.program.main == no_function { + this.problem("Program has no `main` function."); + return; + } + val runtime := this.c.checker.modules.find(0, this.c.checker.names.intern(&"runtime")); + if runtime == 0 { + this.problem("The program has no runtime: no `runtime` folder is beside the compiler or above it."); + return; + } + for h in 0..helper::count as u64 { + val decl := this.c.checker.modules.decl(runtime, this.c.checker.names.intern(&helper_names[h])); + if decl == 0 || this.c.checker.decls.kinds.p[decl] != dk::function { + this.problem($"Declare `runtime::{helper_names[h]}`, taking {helper_arities[h]} parameters."); + continue; + } + this.helpers[h] = this.c.function_of(decl, 0); + } + # The start on Windows runs this before the globals, to find the arguments. + if this.options.windows { + val decl := this.c.checker.modules.decl(runtime, this.c.checker.names.intern(&"system_start")); + if decl == 0 || this.c.checker.decls.kinds.p[decl] != dk::function { + this.problem("Declare `runtime::system_start`, taking 0 parameters."); + } else { + this.system_start_function = this.c.function_of(decl, 0); + } + } + return if this.problems.length != 0; + # The helpers are called by name, so none is dropped, nor inlined away. + for h in 0..helper::count as u64 { + this.c.program.functions[this.helpers[h]].taken = true; + } + if this.options.windows { + this.c.program.functions[this.system_start_function].taken = true; + } + this.c.drain(); + this.c.optimize(); + this.c.drop_unreached_functions(); + for k in 0..this.c.problems.length { + this.problems.append(string::copy_of(&this.c.problems[k])); + } + + val count := this.c.program.functions.length; + this.runtime.resize(count); + for i in 0..count { + this.runtime[i] = this.in_runtime(this.c.program.functions[i].decl); + } + + # Only the C functions the code names are linked, each from the libraries its + # file names, since an executable has nothing else to find them in. + val linked := this.c.program.linked.length; + this.slots.resize(linked, never); + for i in 0..count { + val function := &this.c.program.functions[i]; + continue if !function.lowered; + var walk := function.body.walk_all(); + while walk.more() { + val held: inst = function.body.insts[walk.next()]; + if held.kind == op::c_address && this.slots[held.aux] == never { + this.slots[held.aux] = (linked + 1) as u32; + } + } + } + for l in 0..linked { + continue if this.slots[l] == never; + if this.c.program.linked[l].library.length == 0 { + val decl: u32 = this.c.program.linked[l].decl; + this.problem_at(decl, "An executable finds a C function in a library its file names with `extern import`, and this file names none."); + continue; + } + this.slots[l] = this.linked_count as u32; + this.linked_count++; + } + this.dynamic = this.linked_count != 0; +} + +#! Notes what could not be built at a declaration. +#! @param this The building. +#! @param decl The declaration. +#! @param what What, said in words. +def building::problem_at(&mut this, decl: u32, what: strview): void { + val file: u32 = this.c.checker.decls.files.p[decl]; + val node: u32 = this.c.checker.decls.nodes.p[decl]; + val held := &this.c.checker.units[file].source; + val syntax := &this.c.checker.units[file].syntax; + val offset := syntax.token_offsets[syntax.node_tokens[node]]; + val place := held.lines.place_of(offset); + this.problems.append($"{held.path}:{place.line}:{place.column}: {what}"); +} + +#! The function of a helper. +#! @param this The building. +#! @param which The helper. +#! @returns The function. +pub def building::helper_of(&this, which: helper): u32 { + return this.helpers[which as u64]; +} + + +# The image. + +#! Adds zeroed words to the image, giving where they begin. +#! @param this The building. +#! @param count How many. +#! @returns Where they begin. +def building::words(&mut this, count: u64): u64 { + val at := this.rodata.align_to(8); + for _ in 0..count { + this.rodata.u64(0); + } + return at; +} + +#! Adds bytes to the image, giving where they begin. +#! @param this The building. +#! @param data The bytes. +#! @returns Where they begin. +def building::bytes(&mut this, data: strview): u64 { + val at := this.rodata.length; + this.rodata.put(data); + return at; +} + +#! The address of a layout's record. +#! @param this The building. +#! @param index The layout. +#! @returns The address. +pub def building::layout_address(&this, index: u32): u64 { + return this.rodata_base + this.layouts_at + 12 * 8 * index as u64; +} + +#! The address of a datum. +#! @param this The building. +#! @param index The datum. +#! @returns The address. +pub def building::datum_address(&this, index: u32): u64 { + return this.rodata_base + this.data_at[index]; +} + +#! The bytes of a datum, but for the zero after them. +#! @param this The building. +#! @param index The datum. +#! @returns How many. +pub def building::datum_length(&this, index: u32): u64 { + val length := this.c.program.data[index].bytes.length; + return length == 0 ? 0 : length - 1; +} + +#! The address of a word of the runtime's state. +#! @param this The building. +#! @param word The word. +#! @returns The address. +pub def building::state_address(&this, word: u64): u64 { + return this.data_base + 8 * word; +} + +#! The address of a map between traits' vtables. +#! @param this The building. +#! @param map The map. +#! @returns The address. +pub def building::retrait_address(&this, map: u32): u64 { + return this.rodata_base + this.retraits_at[map]; +} + +#! How many vtables a map between traits' vtables maps. +#! @param this The building. +#! @param map The map. +#! @returns How many. +pub def building::retrait_count(&this, map: u32): u64 { + return this.c.program.retraits[map].vtables.length; +} + +#! The address of the word holding the address C calls a function through. +#! @param this The building. +#! @param function The function. +#! @returns The address. +pub def building::callback_word(&this, function: u32): u64 { + return this.rodata_base + this.callbacks_at + 8 * this.callback_slots[function] as u64; +} + +#! The address of the word the loader writes the address of a C function to. +#! @param this The building. +#! @param linked The C function. +#! @returns The address. +pub def building::got_word(&this, linked: u32): u64 { + return this.got + 8 * this.slots[linked] as u64; +} + +#! The text of a description of an error of the machine, by its code, as the +#! image holds them for the runtime's reports. +#! @param code The code. +#! @returns The text. +def error_text(code: u64): strview { + return match code { + 0 => "Machine input was null.", + 1 => "Context was not checked successfully.", + 2 => "Program has no `main` function.", + 3 => "Program uses a construct that cannot be compiled.", + 4 => "Index or slice is out of bounds.", + 5 => "Null reference was unwrapped.", + 6 => "Division by zero.", + 7 => "Union does not hold the field that was read.", + 8 => "Stack overflowed.", + 9 => "Function ended without returning a value.", + 10 => "Machine was not initialized.", + 11 => "Released memory that was not allocated, or was already released.", + 12 => "Context was checked for a target other than this machine.", + 13 => "Value is not a member of its enum.", + 14 => "Alignment of an allocation is not a power of two.", + 15 => "Function does not run while compiling.", + 16 => "Evaluation took too many steps, as an endless loop or recursion would.", + 17 => "Constant has not been evaluated yet.", + 18 => "Pointer reaches memory the program does not hold, as past the end of what it points into, or memory released.", + 19 => "Pointers into different memory are compared or subtracted, which depends on where the memory is.", + 20 => "Program exited.", + 21 => "Program aborted.", + 22 => "C function could not be found, nor the library holding it.", + 23 => "C called a function of the program while the program was not calling C.", + 26 => "Program faulted.", + 31 => "Allocator out of memory", + 32 => "sakura: runtime error: ", + 33 => " at ", + 34 => " (", + 35 => ":", + 36 => ")\n", + 37 => "\n", + else => "" + }; +} + +#! Writes the records of the image that do not depend on where code is: the +#! texts, the layouts, the data, and room for the tables of functions and +#! vtables, filled once the code is placed. +#! @param this The building. +def building::image(&mut this): void { + val program := &this.c.program; + this.image_at = this.words(14); + + # Texts: where each begins, and how long it is. + this.texts_at = this.words(2 * text_count); + for i in 0..text_count { + val text := error_text(i); + val at := this.bytes(text); + this.rodata.set_u64(this.texts_at + 16 * i, this.rodata_base + at); + this.rodata.set_u64(this.texts_at + 16 * i + 8, text.length); + } + + # Layouts, whose records come first, so they can refer to each other. + val layout_count := program.layouts.length; + this.layouts_at = this.words(12 * layout_count); + for i in 0..layout_count { + val shape: layout = program.layouts[i]; + val record := this.layouts_at + 12 * 8 * i; + val named := shape.kind != lk::fixed && shape.count != 0; + val enum_like := shape.kind == lk::signed || shape.kind == lk::unsigned || shape.kind == lk::boolean; + val fields := named ? this.words(4 * shape.count as u64) : 0; + for f in 0..(named ? shape.count : 0) { + val field: slot_field = program.fields[shape.fields as u64 + f as u64]; + val name := this.c.checker.names.text(field.name); + val name_at := this.bytes(name); + val at := fields + 32 * f as u64; + this.rodata.set_u64(at, enum_like ? 0 : this.layout_address(field.layout)); + this.rodata.set_u64(at + 8, field.offset); + this.rodata.set_u64(at + 16, this.rodata_base + name_at); + this.rodata.set_u64(at + 24, name.length); + } + + val name := shape.name != 0 ? this.c.checker.names.text(shape.name) : ""; + val name_at := this.bytes(name); + + val inner: u32 = shape.element != 0 ? shape.element : shape.viewed; + var flags: u64 = 0; + if shape.niche != 0 { flags = flags | 2; } + if shape.texts { flags = flags | 4; } + if shape.views { flags = flags | 8; } + if shape.texts || shape.views { flags = flags | (shape.text as u64 << 8); } + val values: u64[12] = [ + shape.kind as u64, shape.how as u64, shape.bits as u64, shape.size, shape.align, shape.frame, + inner != 0 ? this.layout_address(inner - 1) : 0, + named ? this.rodata_base + fields : 0, + shape.count as u64, + flags, + this.rodata_base + name_at, + name.length + ]; + for v in 0..12u { + this.rodata.set_u64(record + 8 * v, values[v]); + } + } + + # The data, then where they hold each other's addresses. + this.data_at.resize(program.data.length); + for i in 0..program.data.length { + val align: u64 = program.data[i].align; + this.rodata.align_to(align > 1 ? align : 1); + this.data_at[i] = this.rodata.length; + this.rodata.put(program.data[i].bytes.view()); + } + for i in 0..program.data.length { + for &each in program.data[i].relocations { + this.rodata.set_u64(this.data_at[i] + each.at, this.datum_address(each.target) + each.addend); + } + } + + # The tables of functions and vtables, known once the code is placed. + val count := program.functions.length; + this.function_table = this.rodata_base + this.words(count); + val vtables := program.vtables.length; + this.vtable_table = this.rodata_base + this.words(vtables); + this.vtable_methods.resize(vtables); + for v in 0..vtables { + this.vtable_methods[v] = this.words(program.vtables[v].functions.length); + this.rodata.set_u64(this.vtable_table - this.rodata_base + 8 * v, this.rodata_base + this.vtable_methods[v]); + } + + # The records of the functions, whose names are known now and places later. + this.records_at = this.words(7 * count); + for i in 0..count { + val name := program.functions[i].name.view(); + val at := this.bytes(name); + val record := this.records_at + 56 * i; + this.rodata.set_u64(record + 16, this.rodata_base + at); + this.rodata.set_u64(record + 24, name.length); + this.rodata.set_u64(record + 48, this.runtime[i] ? 1 : 0); + } + + # The vtable each vtable becomes as a reference to its trait converts. + this.retraits_at.resize(program.retraits.length); + for i in 0..program.retraits.length { + val held := &program.retraits[i]; + this.retraits_at[i] = this.words(held.vtables.length); + for v in 0..held.vtables.length { + this.rodata.set_u64(this.retraits_at[i] + 8 * v, held.vtables[v] as u64); + } + } + + # The layout of what each vtable's references refer to, for formatting. + val vtable_layouts := this.words(vtables); + for v in 0..vtables { + this.rodata.set_u64(vtable_layouts + 8 * v, this.layout_address(program.vtables[v].layout)); + } + + # A word for each function C calls, holding the address C calls it through. + this.callback_slots.resize(count); + var callbacks: u32 = 0; + for i in 0..count { + this.callback_slots[i] = never; + if program.functions[i].callback && program.functions[i].lowered { + this.callback_slots[i] = callbacks; + callbacks++; + } + } + this.callbacks_at = this.words(callbacks as u64); + + val image: u64[12] = [ + 0, + this.rodata_base + this.layouts_at, layout_count, + this.rodata_base + this.records_at, count, + this.rodata_base + this.texts_at, text_count, + 0, program.globals, + 0, + this.rodata_base + vtable_layouts, vtables + ]; + for v in 0..12u { + this.rodata.set_u64(this.image_at + 8 * v, image[v]); + } +} + + +#! The loader a dynamically linked executable is run by. +const interpreter: strview = "/lib64/ld-linux-x86-64.so.2"; + +#! Adds what the loader of a dynamically linked executable reads to the image: +#! its path, the names of the libraries and C functions, the symbols naming the +#! functions, a table for finding symbols the executable defines, which holds +#! none, the relocations writing each function's address to its word, and the +#! dynamic section pointing at all of them. Every address is written before the +#! program runs, so none is looked up late. +#! @param this The building. +def building::dynamic_records(&mut this): void { + val program := &this.c.program; + val path_at := this.bytes(interpreter); + this.rodata.byte(0); + + # Names: each library once, as the first function whose file names it names + # it, so the loader looks for each function in all of them. + val strings := this.rodata.length; + this.rodata.byte(0); + var name_at := vector::::new(); + name_at.resize(program.linked.length); + var libraries := interner::::new(); + var needed := vector::::new(); # Where the name of each library is, by its ID. + for l in 0..program.linked.length { + continue if this.slots[l] == never; + for &each in program.linked[l].libraries { + val library := each.view(); + if libraries.intern_view(library) == needed.length { + needed.append(this.rodata.length - strings); + this.bytes(library); + this.rodata.byte(0); + } + } + name_at[l] = this.rodata.length - strings; + this.bytes(this.c.checker.names.text(program.linked[l].name)); + this.rodata.byte(0); + } + val strings_size := this.rodata.length - strings; + + val count := this.linked_count + 1; + val symbols := this.words(3 * count); + for l in 0..program.linked.length { + continue if this.slots[l] == never; + val at := symbols + 24 * (this.slots[l] as u64 + 1); + this.rodata.set_u32(at, name_at[l]); + this.rodata.set_byte(at + 4, 0x12); # A global function, defined elsewhere. + } + + # One bucket, which no symbol the executable defines is in. + val hash := this.words((2 + 1 + count + 1) / 2); + this.rodata.set_u32(hash, 1); + this.rodata.set_u32(hash + 4, count); + + this.relocations = this.words(3 * this.linked_count); + for l in 0..program.linked.length { + continue if this.slots[l] == never; + val slot := this.slots[l] as u64; + this.rodata.set_u64(this.relocations + 24 * slot + 8, ((slot + 1) << 32) | 6); + } + + val section := this.words(0); + for &each in needed { + this.rodata.u64(1); + this.rodata.u64(each); + } + val entries: u64[24] = [ + 4, this.rodata_base + hash, + 5, this.rodata_base + strings, + 6, this.rodata_base + symbols, + 10, strings_size, + 11, 24, + 7, this.rodata_base + this.relocations, + 8, this.linked_count * 24, + 9, 24, + 24, 0, + 30, 8, + 0x6FFFFFFB, 1, + 0, 0 + ]; + for i in 0..24u { + this.rodata.u64(entries[i]); + } + this.dynamic_parts = elf::linking { + interpreter = this.rodata_base + path_at, + interpreter_size = interpreter.length + 1, + section = this.rodata_base + section, + section_size = this.rodata.length - section, + strings = this.rodata_base + strings, + strings_size = strings_size, + symbols = this.rodata_base + symbols, + symbols_size = count * 24 + }; +} + + +# Shared code. + +#! Calls a function, patched once every function is placed. +#! @param this The building. +#! @param function The function. +pub def building::call_to(&mut this, function: u32): void { + this.calls.add(this.text.call(), function); +} + +#! Jumps to a function, patched once every function is placed. +#! @param this The building. +#! @param function The function. +def building::jump_to_function(&mut this, function: u32): void { + this.calls.add(this.text.jmp(), function); +} + +#! Jumps where a condition holds to code already written. +#! @param this The building. +#! @param condition The condition. +#! @param target Where the code is in the text. +pub def building::patch_jcc(&mut this, condition: cc, target: u64): void { + this.text.patch(this.text.jcc(condition), target); +} + +#! Writes the code every function shares: the trap stub, the handler of faults +#! of the program, the code the kernel returns from signals through, the +#! handler noting signals the program handles, and the stubs of a stack +#! overflowing, a function never lowered, and a vtable's slot no function +#! fills. +#! @param this The building. +def building::shared_code(&mut this): void { + # The trap stub is called with the error in `rdi`. It reports through + # `runtime::fail`, given the address it was called from and the chain + # of `rbp` before it, in the stack past the limit, which the limit moves + # down to the stack's end for. A trap while reporting one exits at once. + # It makes a frame of its own, as a function does, so a debugger stopped in + # the report unwinds through it to where the trap was, and aligns `rsp` to + # 16 bytes, which a function calling nothing need not keep it to. + this.trap_stub = this.text.length; + this.text.mov(gprs[2], reg::rbp); + this.text.push(reg::rbp); + this.trap_framed = this.text.length; + this.text.mov(reg::rbp, reg::rsp); + this.trap_based = this.text.length; + this.text.alu_imm(alu::band, reg::rsp, -16); + this.text.load(8, false, reg::rsi, at(reg::rbp, 8)); + this.text.alu_mem_imm(alu::cmp, amd64::absolute(this.state_address(state_reporting)), 0); + val first := this.text.jcc(cc::equal); + if this.options.windows { + # Windows has no system calls: a trap while reporting one ends through `ExitProcess`. + this.text.mov_imm(reg::rcx, 1); + this.call_system(system_exit_process); + } else { + this.text.mov_imm(reg::rax, 231); + this.text.mov_imm(reg::rdi, 1); + this.text.syscall(); + } + this.text.land(first); + this.text.store_imm(amd64::absolute(this.state_address(state_reporting)), 1); + val trap_frame := this.own_word(state_trap_frame); + this.text.load(8, false, reg::rax, trap_frame); + val limit := this.own_word(state_limit); + this.text.store(8, limit, reg::rax); + this.call_to(this.helper_of(helper::fail)); + this.text.ud2(); + + if this.options.windows { + this.windows_handlers(); + this.shared_stubs(); + return; + } + + # Reading or writing through a null pointer faults at the page the kernel + # never maps, and dividing by zero faults too, so the code reads through + # pointers and divides without testing them, and the fault is reported as the + # test would have been: from the instruction faulting, with the chain of `rbp` + # it was in. The kernel gives the signal's number in `edi`: `SIGFPE`, 8, is a + # division, where the kernel sent it, and `SIGSEGV` is null where the address + # is in the first page. A fault anywhere else, or of code that is not the + # program's, takes back the kernel's own handling of the signal and faults + # again. + this.faults = this.text.length; + this.text.mov_imm(reg::r8, fault::null_reference as u64); + this.text.alu_imm(alu::cmp, reg::rdi, 8); + val segv := this.text.jcc(cc::not_equal); + this.text.load(4, true, reg::rax, at(reg::rsi, 8)); + this.text.alu_imm(alu::cmp, reg::rax, 0); + val sent := this.text.jcc(cc::less_equal); + this.text.mov_imm(reg::r8, fault::division as u64); + val division := this.text.jmp(); + this.text.land(segv); + this.text.load(8, false, reg::rax, at(reg::rsi, 16)); + this.text.alu_imm(alu::cmp, reg::rax, null_page as i32); + val elsewhere := this.text.jcc(cc::above_equal); + this.text.land(division); + this.text.load(8, false, reg::rax, at(reg::rdx, 168)); + this.text.mov_imm(reg::rcx, this.text_base); + this.text.alu(alu::cmp, reg::rax, reg::rcx); + val before := this.text.jcc(cc::below); + this.text.byte(0xB9); + this.code_end = this.text.length; + this.text.u32(0); + this.text.alu(alu::cmp, reg::rax, reg::rcx); + val after := this.text.jcc(cc::above_equal); + # The fault is made to look as though the faulting instruction called the + # trap stub. + this.text.load(8, false, reg::rbp, at(reg::rdx, 120)); + this.text.lea(reg::rsi, at(reg::rax, 1)); + this.text.alu_imm(alu::band, reg::rsp, -16); + this.text.push(reg::rsi); + this.text.mov(reg::rdi, reg::r8); + this.text.patch(this.text.jmp(), this.trap_stub); + this.text.land(sent); + this.text.land(elsewhere); + this.text.land(before); + this.text.land(after); + this.text.alu_imm(alu::sub, reg::rsp, 32); + for at_byte in 0..4u { + this.text.store_imm(at(reg::rsp, (8 * at_byte) as i32), 0); + } + this.text.mov_imm(reg::rax, 13); + this.text.mov(reg::rsi, reg::rsp); + this.text.mov_imm(reg::rdx, 0); + this.text.mov_imm(reg::r10, 8); + this.text.syscall(); + this.text.alu_imm(alu::add, reg::rsp, 32); + this.text.ret(); + + this.restorer = this.text.length; + this.text.mov_imm(reg::rax, 15); + this.text.syscall(); + + # A signal the program handles is only noted, as one bit of a word of the + # state, and handled at the program's next safe point. The kernel gives the + # number in `edi`, and puts every register back as the handler returns + # through the restorer. + this.noting = this.text.length; + this.text.mov(reg::rcx, reg::rdi); + this.text.mov_imm(reg::rax, 1); + this.text.shift_cl(shift::shl, reg::rax); + this.text.lock(); + this.text.alu_store(alu::bor, amd64::absolute(this.state_address(state_signals)), reg::rax); + this.text.ret(); + + this.shared_stubs(); +} + +#! Writes the stubs every function shares after the signal handlers: a stack +#! overflowing, a function never lowered, a vtable's slot no function fills, +#! and the code a safe point calls. +#! @param this The building. +def building::shared_stubs(&mut this): void { + # A stack overflowing is found entering the function called, whose frame + # pointer leads to its caller, which the report names first. + this.overflow_stub = this.text.length; + this.text.mov_imm(reg::rdi, 8); + this.text.patch(this.text.call(), this.trap_stub); + + this.missing = this.text.length; + this.text.ud2(); + + # A slot no function fills reports the caller's call, whose return address + # the trap stub takes. + this.missing_method = this.text.length; + this.text.mov_imm(reg::rdi, fault::null_reference as u64); + this.text.patch(this.text.jmp(), this.trap_stub); + + if this.c.dispatch != no_function { + this.safe_point_routine(this.c.dispatch); + } +} + +#! Writes the code a safe point calls where a signal the program handles came: +#! it makes a frame, so a trace walks out through the safe point's function, +#! keeps every register on the stack, and calls the function running the +#! handlers. The vector registers are kept +#! whole: 32 bytes each where the processor has AVX, and 16 otherwise. +#! @param this The building. +#! @param function The function running the handlers. +def building::safe_point_routine(&mut this, function: u32): void { + this.safe_point = this.text.length; + this.text.push(reg::rbp); + this.text.mov(reg::rbp, reg::rsp); + for k in 0..gpr_count { + this.text.push(gprs[k]); + } + val kept: u64 = 32 * 11 + 8; + this.text.alu_imm(alu::sub, reg::rsp, kept as i32); + this.vector_registers(true); + this.call_to(function); + this.vector_registers(false); + this.text.alu_imm(alu::add, reg::rsp, kept as i32); + for k in 0..gpr_count { + this.text.pop(gprs[gpr_count - 1 - k]); + } + this.text.pop(reg::rbp); + this.text.ret(); +} + +#! Keeps the vector registers values are held in on the stack, or gives them +#! back what was kept: 32 bytes each where the processor has AVX, and 16 +#! otherwise. +#! @param this The building. +#! @param store Whether they are kept, rather than given back. +def building::vector_registers(&mut this, store: bool): void { + this.text.load(8, false, reg::rax, amd64::absolute(this.state_address(state_features))); + this.text.alu_imm(alu::band, reg::rax, cpu_avx as i32); + val narrow := this.text.jcc(cc::equal); + for k in 0..11u { + val slot := at(reg::rsp, (32 * k) as i32); + if store { + this.text.vex_mem(vec_movdqu_store, true, xmms[k] as u32, slot); + } else { + this.text.vex_mem(vec_movdqu_load, true, xmms[k] as u32, slot); + } + } + val done := this.text.jmp(); + this.text.land(narrow); + for k in 0..11u { + val slot := at(reg::rsp, (32 * k) as i32); + if store { + this.text.packed_mem(vec_movdqu_store, xmms[k] as u32, slot); + } else { + this.text.packed_mem(vec_movdqu_load, xmms[k] as u32, slot); + } + } + this.text.land(done); +} + +#! Maps memory with `mmap`, leaving its address in `rax`, and exiting with 2 +#! where there is none. +#! @param this The building. +#! @param size The bytes. +def building::map(&mut this, size: u64): void { + this.text.mov_imm(reg::rax, 9); + this.text.mov_imm(reg::rdi, 0); + this.text.mov_imm(reg::rsi, size); + this.text.mov_imm(reg::rdx, 3); + this.text.mov_imm(reg::r10, 0x4022); + this.text.mov_imm(reg::r8, 0xFFFFFFFFFFFFFFFF); + this.text.mov_imm(reg::r9, 0); + this.text.syscall(); + this.text.mov_imm(reg::rcx, 0xFFFFFFFFFFFFF001); + this.text.alu(alu::cmp, reg::rax, reg::rcx); + val mapped := this.text.jcc(cc::below); + this.text.mov_imm(reg::rax, 231); + this.text.mov_imm(reg::rdi, 2); + this.text.syscall(); + this.text.land(mapped); +} + +#! Writes `_start`: it maps the stack, keeps the arguments, takes the faults of +#! the program, runs ``, then `main` with the arguments, then exits +#! with 0. +#! @param this The building. +def building::entry(&mut this): void { + this.start = this.text.length; + this.text.mov(reg::r14, reg::rsp); + # The first thread's record is the state, which `gs` points at, as each + # thread's points at its own. + this.text.mov_imm(reg::rax, 158); + this.text.mov_imm(reg::rdi, 0x1001); + this.text.mov_imm(reg::rsi, this.state_address(0)); + this.text.syscall(); + this.text.mov_imm(reg::rax, this.state_address(0)); + this.text.store(8, amd64::absolute(this.state_address(state_itself)), reg::rax); + this.text.store_imm(amd64::absolute(this.state_address(state_running)), 1); + this.text.mov_imm(reg::rax, 186); + this.text.syscall(); + this.text.store(8, amd64::absolute(this.state_address(state_tid)), reg::rax); + this.map(this.stack + stack_reserve); + this.text.store(8, amd64::absolute(this.state_address(state_trap_frame)), reg::rax); + this.text.lea(reg::rcx, at(reg::rax, stack_reserve as i32)); + this.text.store(8, amd64::absolute(this.state_address(state_limit)), reg::rcx); + this.text.mov_imm(reg::rcx, this.stack + stack_reserve); + this.text.alu(alu::add, reg::rax, reg::rcx); + this.text.store(8, amd64::absolute(this.state_address(state_base)), reg::rax); + this.text.mov(reg::rsp, reg::rax); + + this.text.load(8, false, reg::rax, at(reg::r14, 0)); + this.text.store(8, amd64::absolute(this.state_address(state_argc)), reg::rax); + this.text.lea(reg::rax, at(reg::r14, 8)); + this.text.store(8, amd64::absolute(this.state_address(state_argv)), reg::rax); + this.text.mov_imm(reg::rbp, 0); + + # Faults of the program are reported as traps: `rt_sigaction` of `SIGSEGV` + # and of `SIGFPE`, given the handler with its information and the code the + # kernel returns through. + this.text.alu_imm(alu::sub, reg::rsp, 32); + this.text.mov_imm(reg::rax, this.text_base + this.faults); + this.text.store(8, at(reg::rsp, 0), reg::rax); + this.text.mov_imm(reg::rax, 0x04000004); + this.text.store(8, at(reg::rsp, 8), reg::rax); + this.text.mov_imm(reg::rax, this.text_base + this.restorer); + this.text.store(8, at(reg::rsp, 16), reg::rax); + this.text.store_imm(at(reg::rsp, 24), 0); + for signal in [11u, 8u] { + this.text.mov_imm(reg::rax, 13); + this.text.mov_imm(reg::rdi, signal); + this.text.mov(reg::rsi, reg::rsp); + this.text.mov_imm(reg::rdx, 0); + this.text.mov_imm(reg::r10, 8); + this.text.syscall(); + } + this.text.alu_imm(alu::add, reg::rsp, 32); + + # The vector instructions the processor has, of which the runtime says which + # the program uses, before anything may use them. + this.probe(); + this.text.mov(gprs[0], reg::rax); + this.call_to(this.helper_of(helper::processor)); + this.text.store(8, amd64::absolute(this.state_address(state_features)), reg::rax); + + this.run_main(); + this.text.mov_imm(reg::rax, 231); + this.text.mov_imm(reg::rdi, 0); + this.text.syscall(); + this.entry_end = this.text.length; +} + +#! Runs the globals of the program, then `main`, giving it the arguments where +#! it takes them. The entry has found which vector instructions the program +#! uses, so this is the same whichever system it runs on. +#! @param this The building. +def building::run_main(&mut this): void { + val program := &this.c.program; + this.call_to(program.init); + val main := program.main; + val signature: u32 = program.functions[main].signature; + # The arguments are a view, which `main` takes as the address of the copy it + # makes, as any parameter held in memory, or as its two words. + if program.signatures[signature].params.length == 1 { + val shape: layout = program.layouts[program.signatures[signature].params[0]]; + this.text.alu_imm(alu::sub, reg::rsp, 16); + this.text.mov(gprs[0], reg::rsp); + this.call_to(this.helper_of(helper::arguments)); + if in_memory(&shape) { + this.text.mov(gprs[0], reg::rsp); + } else { + this.text.load(8, false, gprs[0], at(reg::rsp, 0)); + this.text.load(8, false, gprs[1], at(reg::rsp, 8)); + } + } + this.call_to(main); +} + + +#! Asks the processor which vector instructions it has, into `rax`, one bit each +#! as `cpu_sse2` and the rest name them: what `cpuid`'s first two leaves say, +#! with `popcnt`; BMI1 from the seventh leaf, where there is one, and `lzcnt` +#! from the extended leaf `0x80000001`; and AVX and what needs it only where the +#! system keeps the registers' upper halves too, as `xgetbv` says where +#! `OSXSAVE` lets it be asked, AVX2 from the seventh leaf; and AVX-512's F, DQ, +#! BW, and VL, from the seventh leaf too, where it also keeps the mask registers +#! and all 512 bits of the 32. +#! @param this The building. +def building::probe(&mut this): void { + this.text.mov_imm(reg::rax, 0); + this.text.mov_imm(reg::rcx, 0); + this.text.cpuid(); + this.text.mov(reg::r10, reg::rax); + this.text.mov_imm(reg::rax, 1); + this.text.mov_imm(reg::rcx, 0); + this.text.cpuid(); + this.text.mov(reg::r8, reg::rcx); + this.text.mov_imm(reg::r9, cpu_sse2); + this.feature(reg::r8, 9, cpu_ssse3); + this.feature(reg::r8, 19, cpu_sse41); + this.feature(reg::r8, 20, cpu_sse42); + this.feature(reg::r8, 23, cpu_popcnt); + + # The seventh leaf's `ebx`, kept in `r11`, or nothing where there is none. + this.text.mov_imm(reg::r11, 0); + this.text.alu_imm(alu::cmp, reg::r10, 7); + val no_leaf := this.text.jcc(cc::below); + this.text.mov_imm(reg::rax, 7); + this.text.mov_imm(reg::rcx, 0); + this.text.cpuid(); + this.text.mov(reg::r11, reg::rbx); + this.feature(reg::r11, 3, cpu_bmi1); + this.text.land(no_leaf); + + this.text.mov_imm(reg::rax, 0x80000000); + this.text.mov_imm(reg::rcx, 0); + this.text.cpuid(); + this.text.mov_imm(reg::rcx, 0x80000001); + this.text.alu(alu::cmp, reg::rax, reg::rcx); + val no_extended := this.text.jcc(cc::below); + this.text.mov_imm(reg::rax, 0x80000001); + this.text.mov_imm(reg::rcx, 0); + this.text.cpuid(); + this.feature(reg::rcx, 5, cpu_lzcnt); + this.text.land(no_extended); + + this.text.mov(reg::rax, reg::r8); + this.text.alu_imm(alu::band, reg::rax, 0x18000000); + this.text.alu_imm(alu::cmp, reg::rax, 0x18000000); + val no_avx := this.text.jcc(cc::not_equal); + this.text.mov_imm(reg::rcx, 0); + this.text.xgetbv(); + this.text.mov(reg::r10, reg::rax); + this.text.alu_imm(alu::band, reg::rax, 6); + this.text.alu_imm(alu::cmp, reg::rax, 6); + val no_state := this.text.jcc(cc::not_equal); + this.text.alu_imm(alu::bor, reg::r9, cpu_avx as i32); + this.feature(reg::r8, 12, cpu_fma); + this.feature(reg::r11, 5, cpu_avx2); + # The mask registers and the upper bits of all 32, then F, DQ, BW, and VL, + # bits 16, 17, 30, and 31, compared in a register, as an immediate of them + # would be widened with its sign. + this.text.mov(reg::rax, reg::r10); + this.text.alu_imm(alu::band, reg::rax, 0xE0); + this.text.alu_imm(alu::cmp, reg::rax, 0xE0); + val no_wide_state := this.text.jcc(cc::not_equal); + this.text.mov_imm(reg::rcx, 0xC0030000); + this.text.mov(reg::rax, reg::r11); + this.text.alu(alu::band, reg::rax, reg::rcx); + this.text.alu(alu::cmp, reg::rax, reg::rcx); + val no_wide := this.text.jcc(cc::not_equal); + this.text.alu_imm(alu::bor, reg::r9, cpu_avx512 as i32); + this.text.land(no_wide); + this.text.land(no_wide_state); + this.text.land(no_avx); + this.text.land(no_state); + this.text.mov(reg::rax, reg::r9); +} + +#! Adds an instruction set to those `r9` holds where a bit of a register is set. +#! @param this The building. +#! @param from The register. +#! @param bit The bit. +#! @param which The instruction set's bit. +def building::feature(&mut this, from: reg, bit: u32, which: u64): void { + this.text.mov(reg::rax, from); + this.text.alu_imm(alu::band, reg::rax, (1u << bit as u64) as i32); + val absent := this.text.jcc(cc::equal); + this.text.alu_imm(alu::bor, reg::r9, which as i32); + this.text.land(absent); +} + + +# Functions. + +#! How many words a function is called with: each word of its parameters, the +#! address of each held in memory, and a closure's environment. +#! @param this The building. +#! @param function The function. +#! @param memory Where whether each word is the address of one held in +#! memory is written. +#! @param sizes Where the bytes of each held in memory are written. +#! @returns How many. +def building::incoming(&this, function: u32, memory: &mut vector, sizes: &mut vector): u64 { + val held := &this.c.program.functions[function]; + val signature := &this.c.program.signatures[held.signature]; + for &each in signature.params { + val shape: layout = this.c.program.layouts[each]; + if in_memory(&shape) { + memory.append(true); + sizes.append(shape.size); + continue; + } + for _ in 0..word_count(&shape) { + memory.append(false); + sizes.append(0); + } + } + if held.closure { + memory.append(false); + sizes.append(0); + } + return memory.length; +} + +#! Selects the code of every function, in order. Where the options ask for +#! more threads than one, the others place the values of the functions after +#! the one whose code is being selected, as placing reads only the function's +#! code and what selecting leaves as it is, each into an arena of its own, +#! which is given back once the code is selected. +#! @param this The building. +#! @param count How many functions there are. +def building::select_all(&mut this, count: u64): void { + val helpers := crew_for(count, this.options.threads); + if helpers == 0 { + for i in 0..count { + this.select_function(i as u32); + } + return; + } + + # The arenas placing takes from wait in `free` while none uses them. A thread + # takes one before it takes a function, so the function the selecting waits + # for always has one, and gives it back where no function is left. The + # selecting gives each back once the code it held the placing of is chosen, + # which also says how far ahead of it the placing goes. + val arenas := 2 * helpers; + var slots := vector::::new(); + slots.resize(count); + var flags := vector::::new(); + flags.resize(count); + var gate := thread::mutex::>::new(move(&mut flags)); + var placed := thread::condition::new(); + var free := thread::channel::::new(0); + for k in 0..arenas { + _ = free.send(helpers + k); + } + var next := atomic::::new(0); + val building := &mut this; + gather_crew(helpers, helpers + arenas); + var started := vector::>::new(); + for k in 0..helpers { + var made := thread::spawn_with::(def(place: u32): void { + join_crew(place); + while free.receive() is some(arena) { + val index := next.fetch_add(1); + if index >= count { + _ = free.send(arena); + return; + } + if !building.c.program.functions[index].lowered { + _ = free.send(arena); + continue; + } + take_scratch_from(place, arena); + slots[index].made = building.place_function(index as u32); + slots[index].arena = arena; + take_scratch_from(place, place); + var held := gate.lock(); + held.value()[index] = true; + placed.notify_all(); + } + }, k) else (_) { break; }; + started.append(move(&mut made)); + } + + for i in 0..count { + val index := i as u32; + if started.length == 0 { + this.select_function(index); + continue; + } + this.begin_function(index); + continue if !this.c.program.functions[i].lowered; + wait_placed(&mut gate, &mut placed, i); + val point := mark_scratch(); + this.select_placed(index, &mut slots[i].made); + release_scratch(point); + close(&mut slots[i].made); + crew_arena(slots[i].arena).reset(); + _ = free.send(slots[i].arena); + } + free.close(); + for &mut handle in started { + handle.join(); + } + dismiss_crew(); +} + +#! Waits until the values of a function are placed. +#! @param gate Whether each function's values are placed. +#! @param placed What is notified where one's are. +#! @param index The function. +def wait_placed(gate: &mut thread::mutex>, placed: &mut thread::condition, index: u64): void { + var held := gate.lock(); + while !held.value()[index] { + placed.wait(&mut held); + } +} + +#! What placing the values of a function made, while its code waits to be +#! selected. +struct placed_slot { + var made: placed_function; #! What placing made. + var arena: u32; #! The crew's arena it was made in, which is given back once the code is selected. +} + +#! What placing the values of a function makes, which selecting its code reads. +struct placed_function { + var memory: vector; #! Whether each word it is called with is the address of a parameter held in memory. + var sizes: vector; #! The bytes of each one held in memory. + var placed: placing; #! Where each of its values is. + var found: vector; #! What replaying the placing found wrong, where the options ask for it. +} + +#! Notes where what is noted of a function begins, before its code is selected. +#! @param this The building. +#! @param index The function. +def building::begin_function(&mut this, index: u32): void { + this.row_first[index] = this.rows.length as u32; + if this.options.debug { + this.debug.return_first[index] = this.debug.returns.length as u32; + this.debug.variable_first[index] = this.debug.variables.length as u32; + } + if !this.c.program.functions[index].lowered { + this.starts[index] = this.missing; + this.ends[index] = this.missing; + } +} + +#! Selects the code of a function, or points it at the shared stop where it +#! was never lowered. +#! @param this The building. +#! @param index The function. +def building::select_function(&mut this, index: u32): void { + this.begin_function(index); + return if !this.c.program.functions[index].lowered; + val point := mark_scratch(); + var made := this.place_function(index); + this.select_placed(index, &mut made); + release_scratch(point); +} + +#! Places the values of a function, in scratch memory, replaying where it +#! placed them where the options ask for it. It reads only the function's code +#! and what building leaves as it is while selecting, so it may be done on any +#! thread. +#! @param this The building. +#! @param index The function. +#! @returns What placing made. +def building::place_function(&this, index: u32): placed_function { + var memory := vector::::new(scratch()); + var sizes := vector::::new(scratch()); + this.incoming(index, &mut memory, &mut sizes); + val body := &this.c.program.functions[index].body; + var placed := place_values(body, memory.view()); + var found := this.options.verify ? check_placing(body, &placed) : vector::::new(); + return placed_function { + memory = move(&mut memory), + sizes = move(&mut sizes), + placed = move(&mut placed), + found = move(&mut found) + }; +} + +#! Selects the code of a function whose values are placed. +#! @param this The building. +#! @param index The function. +#! @param made What placing its values made, whose placing it takes. +def building::select_placed(&mut this, index: u32, made: &mut placed_function): void { + for &each in made.found { + this.problems.append($"{this.c.program.functions[index].name}: {each}"); + } + + # Each function begins at a multiple of 16 bytes, as the processor fetches + # code, so how fast its loops run doesn't hang on the sizes of the functions + # before it. What lies between is never run. + while this.text.length % 16 != 0 { + this.text.byte(0xCC); + } + + val body := &this.c.program.functions[index].body; + val leaf := made.placed.clobbers.length == 0; + var chosen := selector { + b = this, + body = body, + p = move(&mut made.placed), + index = index, + start = this.text.length, + cells = vector::::new(scratch()), + copies = vector::::new(scratch()), + labels = vector::::new(scratch()), + jumps = fixup_list::new(scratch()), + traps = vector::::new(scratch()), + safe_points = vector::::new(scratch()), + tables = vector::::new(scratch()), + addresses = vector::::new(scratch()), + stub_spans = vector::::new(scratch()), + pads = vector::::new(scratch()), + constants = vector::::new(scratch()), + constant_uses = vector::::new(scratch()), + entries = vector::::new(scratch()), + upper_parts = vector::::new(scratch()), + framed = vector::::new(scratch()), + single = vector::::new(scratch()), + works = vector::::new(scratch()), + last_at = 0xFFFFFFFFFFFFFFFF, + returned = body.returned as u64, + leaf = leaf + }; + chosen.select(made.memory.view(), made.sizes.view()); +} + +#! Selects the code of the function: its prologue, its blocks, and its stubs. +#! @param this The selector. +#! @param memory Whether each word it is called with is the address of a +#! parameter held in memory. +#! @param sizes The bytes of each one held in memory. +def selector::select(&mut this, memory: span, sizes: span): void { + this.find_singles(); + for k in 0..this.p.order.length { + var walk := this.body.walk(this.p.order[k]); + while walk.more() { + val stacked := this.stacked_words(walk.next()); + if stacked > this.out_words { + this.out_words = stacked; + } + } + } + this.find_saved(); + this.lay_frame(memory, sizes); + this.tails = this.b.c.level >= 2 && this.frame_held(); + this.b.starts[this.index] = this.start; + + # Every displacement the function's code is given is noted, for `relax`. + this.calls_first = this.b.calls.length; + this.b.text.fixups.clear(); + this.b.text.logging = true; + + # The prologue is the line the function is declared on. + val function := &this.b.c.program.functions[this.index]; + this.mark(pair_key(function.file + 1, function.offset), 0); + + # A function with a version for x86-64-v3 goes to it first, where the + # processor has its instructions, which the version writes with VEX. + if function.version != 0 { + this.b.text.load(8, false, reg::rax, amd64::absolute(this.b.state_address(state_features))); + this.b.text.alu_imm(alu::band, reg::rax, cpu_v3 as i32); + this.b.text.alu_imm(alu::cmp, reg::rax, cpu_v3 as i32); + this.b.calls.add(this.b.text.jcc(cc::equal), function.version - 1); + } + this.b.text.avx = this.body.wide; + this.find_upper_parts(); + this.prologue(memory, sizes); + + # Where each instruction's code begins and ends, which the scopes of the + # variables debugging information shows are found by. + val describing := this.b.options.debug; + var spans := vector::::new(scratch()); + if describing { + this.b.debug.bodies[this.index] = (this.b.text.length - this.start) as u32; + if this.body.variables.length != 0 { + spans.resize(2 * this.body.insts.length); + } + } + + this.labels.resize(this.body.blocks.length); + for k in 0..this.p.order.length { + val block: u32 = this.p.order[k]; + val next: u32 = k + 1 < this.p.order.length ? this.p.order[k + 1] : never; + if k > 0 && this.dispatches(block) { + this.pad_head(); + } + this.labels[block] = this.b.text.length; + var walk := this.body.walk(block); + while walk.more() { + val at := walk.next(); + # A return a call jumped in place of is not reached. + continue if at == this.tailed; + val held: inst = this.body.insts[at]; + val from := this.b.text.length - this.start; + this.gap(this.p.slots[at]); + if !this.p.folded[at] { + this.mark(held.at, held.site); + if held.kind.ends() { + this.ending(at, &held, next); + } else { + this.emit(at, &held); + } + } + if spans.length != 0 { + spans[2 * at as u64] = from as u32; + spans[2 * at as u64 + 1] = (this.b.text.length - this.start) as u32; + } + } + } + this.stubs(); + this.b.text.avx = false; + this.jumps.resolve(&mut this.b.text, this.labels.view()); + this.b.text.logging = false; + this.relax(&mut spans); + this.write_tables(); + this.write_constants(); + this.b.ends[this.index] = this.b.text.length; + if spans.length != 0 { + this.place_variables(spans.view()); + } +} + +#! Writes the code each vtable's slot names: the function, or code moving the +#! words after a plain reference's down one, where the vtable passes itself as +#! the second, or giving a trait's default the vtable it addresses. +#! @param this The building. +def building::adapters(&mut this): void { + val program := &this.c.program; + for v in 0..program.vtables.length { + for m in 0..program.vtables[v].functions.length { + val function: u32 = program.vtables[v].functions[m]; + if function == no_function { + this.methods.append(this.missing_method); + continue; + } + if !program.functions[function].lowered { + this.methods.append(this.missing); + continue; + } + val signature := &program.signatures[program.functions[function].signature]; + val first: layout = program.layouts[signature.params[0]]; + if first.kind == lk::trait_reference { + val owner: u32 = program.vtables[v].owners[m]; + if owner == v as u32 { + this.methods.append(direct_method); + continue; + } + this.methods.append(this.text.length); + this.text.mov_imm(gprs[1], owner as u64); + this.jump_to_function(function); + continue; + } + + # The words after the reference move down one, over the vtable. + this.methods.append(this.text.length); + var memory := vector::::new(); + var sizes := vector::::new(); + val words := this.incoming(function, &mut memory, &mut sizes); + for j in 1..words { + val from := j + 1; + if j < arg_count && from < arg_count { + this.text.mov(gprs[j], gprs[from]); + } else if j < arg_count { + this.text.load(8, false, gprs[j], at(reg::rsp, (8 + 8 * (from - arg_count)) as i32)); + } else { + this.text.load(8, false, reg::rax, at(reg::rsp, (8 + 8 * (from - arg_count)) as i32)); + this.text.store(8, at(reg::rsp, (8 + 8 * (j - arg_count)) as i32), reg::rax); + } + } + this.jump_to_function(function); + } + } +} + + +# Placing. + +#! Writes what depends on where the code is: the tables of functions and +#! vtables, the functions' records, and their line tables. +#! @param this The building. +def building::places(&mut this): void { + val program := &this.c.program; + val count := program.functions.length; + for i in 0..count { + val start: u64 = this.text_base + this.starts[i]; + this.rodata.set_u64(this.function_table - this.rodata_base + 8 * i, start); + val record := this.records_at + 56 * i; + this.rodata.set_u64(record, start); + this.rodata.set_u64(record + 8, this.text_base + this.ends[i]); + } + + var k: u64 = 0; + for v in 0..program.vtables.length { + for m in 0..program.vtables[v].functions.length { + var code: u64 = this.methods[k]; + if code == direct_method { + code = this.starts[program.vtables[v].functions[m]]; + } + this.rodata.set_u64(this.vtable_methods[v] + 8 * m, this.text_base + code); + k++; + } + } + for i in 0..count { + val slot: u32 = this.callback_slots[i]; + continue if slot == never; + this.rodata.set_u64(this.callbacks_at + 8 * slot as u64, this.text_base + this.entries[i]); + } + this.line_tables(); +} + +#! Where in the source a place is: its file, and its line and column, from one +#! more than the file and the byte, or the function's declaration for 0. +#! @param this The building. +#! @param function The function. +#! @param at The place. +#! @param file Where the file is written. +#! @returns Its line and column. +def building::source_of(&this, function: u32, at: u64, file: &mut u32): sakura::analyzer::place { + var byte := pair_low(at); + if at == 0 { + file = this.c.program.functions[function].file; + byte = this.c.program.functions[function].offset; + } else { + file = pair_high(at) - 1; + } + return this.c.checker.units[file].source.lines.place_of(byte); +} + +#! Writes the line table of every function into the line tables: a row for each +#! place its code changes where in the source it is from, each naming its path +#! among the image's and the site of the function inlined there, then the sites +#! of every function, and the paths. Each function's record and the image point +#! at them. +#! @param this The building. +def building::line_tables(&mut this): void { + val program := &this.c.program; + + # The path of each file, numbered as rows name them, and the first site of each + # function among them all. + var path_ids := vector::::new(); + path_ids.resize(this.c.checker.units.length); + var files := vector::::new(); + var site_first := vector::::new(); + var total_sites: u32 = 0; + for i in 0..program.functions.length { + site_first.append(total_sites); + continue if this.row_first[i] == this.row_first[i + 1]; + total_sites += program.functions[i].body.sites.length as u32; + } + + for i in 0..program.functions.length { + val first: u32 = this.row_first[i]; + val last: u32 = this.row_first[i + 1]; + continue if first == last; + val table := this.late.align_to(8); + for r in first..last { + val row: line_row = this.rows[r as u64]; + var file: u32 = 0; + val place := this.source_of(i as u32, row.at, &mut file); + this.late.u32(row.offset); + this.late.u32(place.line as u64); + this.late.u16(place.column > 0xFFFF ? 0xFFFF : place.column as u64); + this.late.u16(numbered(&mut path_ids, &mut files, file) as u64); + this.late.u32(row.site != 0 ? site_first[i] as u64 + row.site as u64 : 0); + } + val record := this.records_at + 56 * i; + this.rodata.set_u64(record + 32, this.late_base + table); + this.rodata.set_u64(record + 40, (last - first) as u64); + } + + # Each site of a function inlined: the function, where it was called, and the + # site that call is within, which the trace walks out through. + val sites_at := this.late.align_to(8); + for i in 0..program.functions.length { + continue if this.row_first[i] == this.row_first[i + 1]; + for &each in program.functions[i].body.sites { + var file: u32 = 0; + val place := this.source_of(i as u32, each.at, &mut file); + this.late.u32(each.function as u64); + this.late.u32(place.line as u64); + this.late.u16(place.column > 0xFFFF ? 0xFFFF : place.column as u64); + this.late.u16(numbered(&mut path_ids, &mut files, file) as u64); + this.late.u32(each.parent != 0 ? site_first[i] as u64 + each.parent as u64 : 0); + } + } + + # The paths, each its text then where it is and how long. + var texts := vector::::new(); + for &file in files { + val path := this.c.checker.units[file].source.path; + texts.append(this.late.length); + this.late.put(path); + } + val paths_at := this.late.align_to(8); + for k in 0..files.length { + this.late.u64(this.late_base + texts[k]); + this.late.u64(this.c.checker.units[files[k]].source.path.length); + } + this.rodata.set_u64(this.image_at + 12 * 8, this.late_base + paths_at); + this.rodata.set_u64(this.image_at + 13 * 8, this.late_base + sites_at); +} + +#! The number of a file's path among those the line tables name, given one where +#! it has none yet. +#! @param ids One more than the number of each file's path, or 0. +#! @param files The file of each number. +#! @param file The file. +#! @returns The number. +def numbered(ids: &mut vector, files: &mut vector, file: u32): u32 { + if ids[file] == 0 { + files.append(file); + ids[file] = files.length as u32; + } + return ids[file] - 1; +} + + +# Writing. + +#! A part of the image an executable loads: a segment of an ELF file, or a +#! section of a PE file. +struct loaded_part { + var name: strview; #! Of its section, as `.text`. + var address: u64; #! Where its bytes are loaded. + var data: span; #! What it holds. + var size: u64; #! How many bytes. + var flags: u32; #! Its permissions, which ELF and PE number alike. +} + +#! The parts of the image an executable loads, in the order they are loaded: +#! the image only read, the data, the code, and the line tables. +#! @param this The building. +#! @param data The bytes of the data. +#! @returns The parts. +def building::loaded_parts(&this, data: span): loaded_part[4] { + return [ + loaded_part { name = ".rodata", address = this.rodata_base, data = this.rodata.view(), size = this.rodata.length, flags = elf::readable }, + loaded_part { name = ".data", address = this.data_base, data = data, size = this.data_size, flags = elf::readable | elf::writable }, + loaded_part { name = ".text", address = this.text_base, data = this.text.bytes.view(), size = this.text.length, flags = elf::readable | elf::executable }, + loaded_part { name = ".lines", address = this.late_base, data = this.late.view(), size = this.late.length, flags = elf::readable } + ]; +} + +#! Names the code, as debuggers and disassemblers show it: `_start`, the trap +#! stub, and each function placed, each by where it begins and how many bytes +#! it takes. +#! @param this The building. +#! @param symbols Where the names are added. +def building::name_code(&this, symbols: &mut vector): void { + symbols.append(elf::symbol { name = "_start", address = this.text_base + this.start, size = this.entry_end - this.start }); + symbols.append(elf::symbol { name = "", address = this.text_base + this.trap_stub, size = this.start - this.trap_stub }); + for i in 0..this.c.program.functions.length { + continue if this.starts[i] == this.missing; + symbols.append(elf::symbol { + name = this.c.program.functions[i].name.view(), address = this.text_base + this.starts[i], size = this.ends[i] - this.starts[i] + }); + } +} + +#! Writes the executable: its segments, its symbols, and a note naming its +#! build. +#! @param this The building. +def building::write(&mut this): void { + # The data is zeros, but for the bytes the globals begin with. + var zeros := byte_writer::new(); + zeros.zeros(this.data_size); + val preset := this.c.program.preset.view(); + if preset.length != 0 { + memcpy(zeros.slice().data + (this.globals - this.data_base), preset.data, preset.length); + } + if this.options.windows { + # The words of the functions imported hold where their names are until the + # loader writes their addresses. + for w in 0..this.import_words { + zeros.set_u64(this.got - this.data_base + 8 * w, this.import_names[w]); + } + this.write_pe(zeros.view()); + return; + } + + val headers := elf::headers_size(4, this.dynamic); + val data_offset := round_up(headers + this.rodata.length, page_size); + val text_offset := round_up(data_offset + this.data_size, page_size); + val late_offset := round_up(text_offset + this.text.length, page_size); + + var image := elf::image::new(this.text_base + this.start); + if this.dynamic { + image.dynamic = this.dynamic_parts; + image.linked = true; + } + # The first segment begins with the file's headers, before the image. + val parts := this.loaded_parts(zeros.view()); + val offsets: u64[4] = [0, data_offset, text_offset, late_offset]; + for k in 0..4u { + val part: loaded_part = parts[k]; + image.segment(part.name, k == 0 ? base_address : part.address, offsets[k], part.data, part.size, part.flags, k == 0); + } + this.name_code(&mut image.symbols); + image.build_id(); + if this.options.debug && !describe_build(this, &mut image) { + this.problem($"The debugging information could not be written to {this.options.output}.petal."); + return; + } + val bytes := image.file(); + val written := write_bytes(this.options.output, bytes.view(), 0o755); + if !written { + this.problem($"The executable could not be written to {this.options.output}."); + } +} diff --git a/native/operations.sakura b/native/operations.sakura new file mode 100644 index 00000000..e6d1e846 --- /dev/null +++ b/native/operations.sakura @@ -0,0 +1,1127 @@ +#! @file operations.sakura +#! @author John Christman (sorakatadzuma@gmail.com) +#! @copyright Malunal Studios, LLC. +#! @license MIT +#! +#! Contains the code of the operations that compute: arithmetic of words and +#! reals, comparisons, conversions, and reading, writing, copying, and clearing +#! memory. Each computes as the machine does, to the bit: division by zero and +#! of the least word by -1, shifts of 64 bits or more, and conversions of reals +#! past the range of words saturating. + +import sakura::compiler; +import binary::amd64; +module sakura::native; + + +#! Applies arithmetic to a register and an operand. +#! @param this The selector. +#! @param kind The arithmetic. +#! @param dst The register, written. +#! @param src The operand. +def selector::apply(&mut this, kind: alu, dst: reg, src: &operand_of): void { + match src.kind { + 0 => this.b.text.alu(kind, dst, src.r); + 1 => this.b.text.alu_load(kind, dst, src.m); + else => this.b.text.alu_imm(kind, dst, src.imm); + } +} + +#! Puts the word an instruction reads into a register. +#! @param this The selector. +#! @param value The value. +#! @param index The instruction reading it. +#! @param into The register. +def selector::load_into(&mut this, value: u32, index: u32, into: reg): void { + val held := this.read(value, index); + if held.kind == place::gpr { + if held.number as reg != into { + this.b.text.mov(into, held.number as reg); + } + return; + } + val got := this.word_reg(value, index, into); + if got != into { + this.b.text.mov(into, got); + } +} + +#! Puts the real an instruction reads into an SSE register. +#! @param this The selector. +#! @param value The value. +#! @param index The instruction reading it. +#! @param into The register's number. +def selector::load_real_into(&mut this, value: u32, index: u32, into: u8): void { + val got := this.real_reg(value, index, into); + if got != into { + this.b.text.movaps(into, got); + } +} + +#! Whether a value an instruction reads is in a general register. +#! @param this The selector. +#! @param value The value. +#! @param index The instruction reading it. +#! @param r The register. +#! @returns Whether it is. +def selector::is_in(&this, value: u32, index: u32, r: reg): bool { + val held := this.read(value, index); + return held.kind == place::gpr && held.number == r as u8; +} + +#! Whether a value an instruction reads is in an SSE register. +#! @param this The selector. +#! @param value The value. +#! @param index The instruction reading it. +#! @param x The register's number. +#! @returns Whether it is. +def selector::is_in_xmm(&this, value: u32, index: u32, x: u8): bool { + return false if this.single[value]; + val held := this.read(value, index); + return held.kind == place::xmm && held.number == x; +} + + +# Words. + +#! The code of an operator of two words. +#! @param this The selector. +#! @param index The instruction. +#! @param held The instruction. +def selector::binary(&mut this, index: u32, held: &inst): void { + val a := this.body.arg(index, 0); + val b := this.body.arg(index, 1); + val result := held.result; + match held.kind { + op::add => this.arithmetic(index, alu::add, a, b, result, true); + op::sub => this.arithmetic(index, alu::sub, a, b, result, false); + op::band => this.arithmetic(index, alu::band, a, b, result, true); + op::bor => this.arithmetic(index, alu::bor, a, b, result, true); + op::bxor => this.arithmetic(index, alu::bxor, a, b, result, true); + op::mul => this.multiply(index, a, b, result); + op::divs, op::divu, op::rems, op::remu => this.divide(index, held.kind, a, b, result); + op::shl, op::shrs, op::shru => this.shift_by(index, held.kind, a, b, result); + op::eq, op::ne, op::lts, op::ltu, op::les, op::leu => { + return if !this.wanted(result); + val condition := this.compare(index, held.kind, a, b); + val into := this.target(result, reg::rax); + this.b.text.setcc(condition, into); + this.put(result, into); + } + op::eqsu, op::ltsu, op::lesu, op::ltus, op::leus => this.mixed(index, held.kind, a, b, result); + op::fadd => this.real_arithmetic(index, sse::addsd, a, b, result, true); + op::fsub => this.real_arithmetic(index, sse::subsd, a, b, result, false); + op::fmul => this.real_arithmetic(index, sse::mulsd, a, b, result, true); + op::fdiv => this.real_arithmetic(index, sse::divsd, a, b, result, false); + op::frem => this.real_remainder(index, a, b, result); + op::feq, op::fne, op::flt, op::fle => this.real_compare(index, held.kind, a, b, result); + else => {} + } +} + +#! Arithmetic of two words in place: `add`, `sub`, `and`, `or`, and `xor`. +#! @param this The selector. +#! @param index The instruction. +#! @param kind The arithmetic. +#! @param a The first operand. +#! @param b The second. +#! @param result The result. +#! @param commutes Whether the operands may be swapped. +def selector::arithmetic(&mut this, index: u32, kind: alu, a: u32, b: u32, result: u32, commutes: bool): void { + return if !this.wanted(result); + val into := this.target(result, reg::rax); + + # A sum one of whose operands is a shift folded into it scales the word + # shifted as an index. + if kind == alu::add && this.scales(a, b) { + this.scaled_sum(index, result, into); + return; + } + + # A sum of a register and a constant, or of two registers, into a third. + if kind == alu::add && !this.is_in(a, index, into) && !this.is_in(b, index, into) { + var imm: i32 = 0; + val left := this.read(a, index); + val right := this.read(b, index); + if left.kind == place::gpr && this.immediate(b, &mut imm) { + this.b.text.lea(into, at(left.number as reg, imm)); + this.put(result, into); + return; + } + if left.kind == place::gpr && right.kind == place::gpr { + this.b.text.lea(into, indexed(left.number as reg, right.number as reg, 1, 0)); + this.put(result, into); + return; + } + } + + if this.is_in(a, index, into) { + val other := this.word_operand(b, index, reg::rcx); + this.apply(kind, into, &other); + } else if commutes && this.is_in(b, index, into) { + val other := this.word_operand(a, index, reg::rcx); + this.apply(kind, into, &other); + } else if this.is_in(b, index, into) { + # The second operand is where the result goes, so the first is computed + # in `rax`. + this.load_into(a, index, reg::rax); + this.b.text.alu(kind, reg::rax, into); + this.b.text.mov(into, reg::rax); + } else { + this.load_into(a, index, into); + val other := this.word_operand(b, index, reg::rcx); + this.apply(kind, into, &other); + } + this.put(result, into); +} + +#! Whether either of two operands is a shift folded into the sum reading them. +#! @param this The selector. +#! @param a One operand. +#! @param b The other. +#! @returns Whether it is. +def selector::scales(&this, a: u32, b: u32): bool { + for k in 0..2u { + val made := this.body.defining(k == 0 ? a : b); + if made != 0 && this.p.folded[made] && this.body.insts[made].kind == op::shl { + return true; + } + } + return false; +} + +#! A sum scaling the word a shift folded into it shifts, by `lea`: of the +#! other operand, a constant as the displacement, or the frame's or the +#! image's address as its own, and the index scaled. +#! @param this The selector. +#! @param index The sum. +#! @param result The result. +#! @param into The register the result is computed into. +def selector::scaled_sum(&mut this, index: u32, result: u32, into: reg): void { + var base: u32 = 0; + var scale: u8 = 1; + val scaled := this.sum_parts(index, &mut base, &mut scale); + val by := this.word_reg(scaled, index, reg::rcx); + var imm: i32 = 0; + var below: u64 = 0; + if this.immediate(base, &mut imm) { + this.b.text.lea(into, indexed(reg::none, by, scale, imm)); + } else if this.p.remade[base] && this.frame_address(base, &mut below) { + this.b.text.lea(into, indexed(reg::rbp, by, scale, -(below as i64) as i32)); + } else { + this.b.text.lea(into, indexed(this.word_reg(base, index, reg::rax), by, scale, 0)); + } + this.put(result, into); +} + +#! `mul` of two words. +#! @param this The selector. +#! @param index The instruction. +#! @param a The first operand. +#! @param b The second. +#! @param result The result. +def selector::multiply(&mut this, index: u32, a: u32, b: u32, result: u32): void { + return if !this.wanted(result); + val into := this.target(result, reg::rax); + var imm: i32 = 0; + if this.immediate(b, &mut imm) { + this.multiply_by(into, this.word_reg(a, index, reg::rcx), imm); + this.put(result, into); + return; + } + if this.immediate(a, &mut imm) { + this.multiply_by(into, this.word_reg(b, index, reg::rcx), imm); + this.put(result, into); + return; + } + var first := a; + var second := b; + if this.is_in(b, index, into) { + first = b; + second = a; + } + this.load_into(first, index, into); + val other := this.word_operand(second, index, reg::rcx); + if other.kind == 1 { + this.b.text.imul_load(into, other.m); + } else if other.kind == 0 { + this.b.text.imul(into, other.r); + } else { + this.b.text.imul_imm(into, into, other.imm); + } + this.put(result, into); +} + +#! Multiplies a register by a constant into another: a power of two by a +#! shift, or by `lea` adding it to itself for 2, and 3, 5, or 9 times a power +#! of two by `lea` adding it to itself scaled, then a shift, which are quicker +#! than `imul`; any other by `imul`. +#! @param this The selector. +#! @param into The register written. +#! @param from The register multiplied. +#! @param by The constant. +def selector::multiply_by(&mut this, into: reg, from: reg, by: i32): void { + if by > 0 { + var odd := by as u64; + var shift: u8 = 0; + while (odd & 1) == 0 { + odd = odd >> 1; + shift++; + } + if odd == 1 && shift == 1 { + this.b.text.lea(into, indexed(from, from, 1, 0)); + return; + } + if odd == 1 || odd == 3 || odd == 5 || odd == 9 { + if odd != 1 { + this.b.text.lea(into, indexed(from, from, (odd - 1) as u8, 0)); + } else if into != from { + this.b.text.mov(into, from); + } + if shift != 0 { + this.b.text.shift_imm(shift::shl, into, shift); + } + return; + } + } + this.b.text.imul_imm(into, from, by); +} + +#! Division of words, and what is left of it: by zero it stops the program, as +#! the processor faults, which the runtime reports, and by -1 a signed division +#! negates, leaving nothing over, without the hardware's overflow of the least +#! word. +#! @param this The selector. +#! @param index The instruction. +#! @param kind The operation. +#! @param a The dividend. +#! @param b The divisor. +#! @param result The result. +def selector::divide(&mut this, index: u32, kind: op, a: u32, b: u32, result: u32): void { + val signed := kind == op::divs || kind == op::rems; + val rest := kind == op::rems || kind == op::remu; + var bits: u64 = 0; + val constant := this.p.remade[b] && this.constant_bits(b, &mut bits); + if constant && bits == 0 { + this.trap_always(fault::division as u32, index); + return; + } + return if constant && !this.wanted(result); + + this.load_into(b, index, reg::rcx); + this.load_into(a, index, reg::rax); + if !signed { + this.b.text.mov_imm(reg::rdx, 0); + this.b.text.unary(unary::div, reg::rcx); + this.put(result, rest ? reg::rdx : reg::rax); + return; + } + if constant && bits == 0xFFFFFFFFFFFFFFFF { + if rest { + this.b.text.mov_imm(reg::rax, 0); + } else { + this.b.text.unary(unary::neg, reg::rax); + } + this.put(result, reg::rax); + return; + } + + var done: u64 = never as u64; + if !constant { + this.b.text.alu_imm(alu::cmp, reg::rcx, -1); + val normal := this.b.text.jcc(cc::not_equal); + if rest { + this.b.text.mov_imm(reg::rdx, 0); + } else { + this.b.text.unary(unary::neg, reg::rax); + } + done = this.b.text.jmp(); + this.b.text.land(normal); + } + this.b.text.cqo(); + this.b.text.unary(unary::idiv, reg::rcx); + if done != never as u64 { + this.b.text.land(done); + } + this.put(result, rest ? reg::rdx : reg::rax); +} + +#! Shifts of words, by 64 or more leaving nothing, or the sign. +#! @param this The selector. +#! @param index The instruction. +#! @param kind The shift. +#! @param a The word shifted. +#! @param b How far. +#! @param result The result. +def selector::shift_by(&mut this, index: u32, kind: op, a: u32, b: u32, result: u32): void { + return if !this.wanted(result); + val how := kind == op::shl ? shift::shl : kind == op::shru ? shift::shr : shift::sar; + var bits: u64 = 0; + if this.p.remade[b] && this.constant_bits(b, &mut bits) { + val into := this.target(result, reg::rax); + if bits >= 64 { + if kind == op::shrs { + this.load_into(a, index, into); + this.b.text.shift_imm(shift::sar, into, 63); + } else { + this.b.text.mov_imm(into, 0); + } + this.put(result, into); + return; + } + this.load_into(a, index, into); + if bits != 0 { + this.b.text.shift_imm(how, into, bits as u8); + } + this.put(result, into); + return; + } + + this.load_into(b, index, reg::rcx); + this.load_into(a, index, reg::rax); + this.b.text.alu_imm(alu::cmp, reg::rcx, 64); + val within := this.b.text.jcc(cc::below); + if kind == op::shrs { + this.b.text.shift_imm(shift::sar, reg::rax, 63); + } else { + this.b.text.mov_imm(reg::rax, 0); + } + val done := this.b.text.jmp(); + this.b.text.land(within); + this.b.text.shift_cl(how, reg::rax); + this.b.text.land(done); + this.put(result, reg::rax); +} + +#! The condition `cmp a, b` leaves for a comparison. +#! @param kind The comparison. +#! @returns The condition. +pub def condition_of(kind: op): cc { + return match kind { + op::eq => cc::equal, + op::ne => cc::not_equal, + op::lts => cc::less, + op::ltu => cc::below, + op::les => cc::less_equal, + op::leu => cc::below_equal, + op::flt => cc::above, + op::fle => cc::above_equal, + else => cc::equal + }; +} + +#! The condition holding where another does with the operands swapped. +#! @param condition The condition. +#! @returns The condition. +pub def swapped(condition: cc): cc { + return match condition { + cc::less => cc::greater, + cc::greater => cc::less, + cc::less_equal => cc::greater_equal, + cc::greater_equal => cc::less_equal, + cc::below => cc::above, + cc::above => cc::below, + cc::below_equal => cc::above_equal, + cc::above_equal => cc::below_equal, + else => condition + }; +} + +#! The condition holding where another does not. +#! @param condition The condition. +#! @returns The condition. +pub def opposite(condition: cc): cc { + return (condition as u8 ^ 1) as cc; +} + +#! Compares two values an instruction reads, as a comparison asks, leaving the +#! flags for a condition: words by `cmp`, and reals by `ucomisd`. +#! @param this The selector. +#! @param index The instruction reading the operands. +#! @param kind The comparison. +#! @param a The first operand. +#! @param b The second. +#! @returns The condition that holds where the comparison does. +def selector::compare(&mut this, index: u32, kind: op, a: u32, b: u32): cc { + if kind == op::flt || kind == op::fle { + # `a < b` is `b > a`, which holds only where neither is not a number. + val x := this.real_reg(b, index, 0); + val y := this.real_reg(a, index, 1); + this.b.text.ucomisd(x, y); + return condition_of(kind); + } + var first := a; + var second := b; + var condition := condition_of(kind); + var imm: i32 = 0; + if this.immediate(a, &mut imm) && !this.p.remade[b] { + first = b; + second = a; + condition = swapped(condition); + } + val left := this.word_reg(first, index, reg::rax); + val right := this.word_operand(second, index, reg::rcx); + if right.kind == 2 && right.imm == 0 { + return this.test_zero(left, condition); + } + this.apply(alu::cmp, left, &right); + return condition; +} + +#! Compares a register with 0 by `test`, which leaves the flags as `cmp` would, +#! the carry clear: so a word is at most 0 unsigned where it is 0, and above it +#! where it is not. +#! @param this The selector. +#! @param r The register. +#! @param condition The condition the comparison asks for. +#! @returns The condition that holds where it does. +def selector::test_zero(&mut this, r: reg, condition: cc): cc { + this.b.text.test(r, r); + return match condition { + cc::below_equal => cc::equal, + cc::above => cc::not_equal, + else => condition + }; +} + +#! Comparisons of a signed and an unsigned word as the numbers they are. +#! @param this The selector. +#! @param index The instruction. +#! @param kind The comparison. +#! @param a The first operand. +#! @param b The second. +#! @param result The result. +def selector::mixed(&mut this, index: u32, kind: op, a: u32, b: u32, result: u32): void { + return if !this.wanted(result); + this.load_into(b, index, reg::rcx); + this.load_into(a, index, reg::rax); + val signed_first := kind == op::eqsu || kind == op::ltsu || kind == op::lesu; + this.b.text.test(signed_first ? reg::rax : reg::rcx, signed_first ? reg::rax : reg::rcx); + val sign := kind == op::eqsu || kind == op::ltus || kind == op::leus ? cc::no_sign : cc::sign; + this.b.text.setcc(sign, reg::rdx); + this.b.text.alu(alu::cmp, reg::rax, reg::rcx); + val holds := match kind { + op::eqsu => cc::equal, + op::ltsu, op::ltus => cc::below, + else => cc::below_equal + }; + this.b.text.setcc(holds, reg::rax); + val joins := kind == op::ltsu || kind == op::lesu ? alu::bor : alu::band; + this.b.text.alu(joins, reg::rax, reg::rdx); + this.put(result, reg::rax); +} + +#! The code of an operator of one value. +#! @param this The selector. +#! @param index The instruction. +#! @param held The instruction. +def selector::unary_op(&mut this, index: u32, held: &inst): void { + val a := this.body.arg(index, 0); + val result := held.result; + return if !this.wanted(result); + match held.kind { + op::neg, op::bnot => { + val into := this.target(result, reg::rax); + this.load_into(a, index, into); + this.b.text.unary(held.kind == op::neg ? unary::neg : unary::bnot, into); + this.put(result, into); + } + op::lnot => { + val tested := this.word_reg(a, index, reg::rax); + this.b.text.test(tested, tested); + val into := this.target(result, reg::rax); + this.b.text.setcc(cc::equal, into); + this.put(result, into); + } + op::wrap => { + val bits := held.aux as u64; + val signed := held.imm != 0; + val into := this.target(result, reg::rax); + if bits == 8 || bits == 16 || bits == 32 { + this.b.text.extend(bits / 8, signed, into, this.word_reg(a, index, reg::rcx)); + } else { + this.load_into(a, index, into); + if bits < 64 { + this.b.text.shift_imm(shift::shl, into, (64 - bits) as u8); + this.b.text.shift_imm(signed ? shift::sar : shift::shr, into, (64 - bits) as u8); + } + } + this.put(result, into); + } + op::fneg => { + val into := this.real_target(result); + this.b.text.mov_imm(reg::rax, 0x8000000000000000); + this.b.text.movq_to_xmm(1, reg::rax); + this.load_real_into(a, index, into); + this.b.text.xorpd(into, 1); + this.put_real(result, into); + } + op::itof => { + val into := this.real_target(result); + this.b.text.cvtsi2sd(into, this.word_reg(a, index, reg::rax)); + this.put_real(result, into); + } + op::utof => { + # Past the largest signed word, half the value is converted and doubled, + # keeping its lowest bit so it rounds as the whole value would. + val into := this.real_target(result); + this.load_into(a, index, reg::rax); + this.b.text.test(reg::rax, reg::rax); + val large := this.b.text.jcc(cc::sign); + this.b.text.cvtsi2sd(into, reg::rax); + val done := this.b.text.jmp(); + this.b.text.land(large); + this.b.text.mov(reg::rcx, reg::rax); + this.b.text.shift_imm(shift::shr, reg::rcx, 1); + this.b.text.alu_imm(alu::band, reg::rax, 1); + this.b.text.alu(alu::bor, reg::rcx, reg::rax); + this.b.text.cvtsi2sd(into, reg::rcx); + this.b.text.sse(sse::addsd, into, into); + this.b.text.land(done); + this.put_real(result, into); + } + op::ftoi => { + # Not a number is 0, and values past the range saturate. + this.load_real_into(a, index, 0); + this.b.text.mov_imm(reg::rax, 0); + this.b.text.ucomisd(0, 0); + val nan := this.b.text.jcc(cc::parity); + this.b.text.mov_imm(reg::rdx, 0x43E0000000000000); + this.b.text.movq_to_xmm(1, reg::rdx); + this.b.text.ucomisd(0, 1); + val high := this.b.text.jcc(cc::above_equal); + this.b.text.cvttsd2si(reg::rax, 0); + val done := this.b.text.jmp(); + this.b.text.land(high); + this.b.text.mov_imm(reg::rax, 0x7FFFFFFFFFFFFFFF); + this.b.text.land(nan); + this.b.text.land(done); + this.put(result, reg::rax); + } + op::ftou => { + this.load_real_into(a, index, 0); + this.b.text.mov_imm(reg::rax, 0); + this.b.text.mov_imm(reg::rdx, 0); + this.b.text.movq_to_xmm(1, reg::rdx); + this.b.text.ucomisd(0, 1); + val low := this.b.text.jcc(cc::below_equal); + this.b.text.mov_imm(reg::rdx, 0x43F0000000000000); + this.b.text.movq_to_xmm(1, reg::rdx); + this.b.text.ucomisd(0, 1); + val full := this.b.text.jcc(cc::above_equal); + this.b.text.mov_imm(reg::rdx, 0x43E0000000000000); + this.b.text.movq_to_xmm(1, reg::rdx); + this.b.text.ucomisd(0, 1); + val upper := this.b.text.jcc(cc::above_equal); + this.b.text.cvttsd2si(reg::rax, 0); + val done := this.b.text.jmp(); + this.b.text.land(upper); + this.b.text.sse(sse::subsd, 0, 1); + this.b.text.cvttsd2si(reg::rax, 0); + this.b.text.mov_imm(reg::rcx, 0x8000000000000000); + this.b.text.alu(alu::bxor, reg::rax, reg::rcx); + val finished := this.b.text.jmp(); + this.b.text.land(full); + this.b.text.mov_imm(reg::rax, 0xFFFFFFFFFFFFFFFF); + this.b.text.land(low); + this.b.text.land(done); + this.b.text.land(finished); + this.put(result, reg::rax); + } + op::fsingle => this.round_single(index, a, result); + op::fsqrt => { + if this.works[index] { + this.single_root(index, a, result); + return; + } + val into := this.real_target(result); + this.b.text.sse(sse::sqrtsd, into, this.real_reg(a, index, 0)); + this.put_real(result, into); + } + op::ones => { + if this.body.wide { + this.count_bits(index, held, a, result); + return; + } + # Counted in pairs of bits, then nibbles, then bytes, whose counts a multiply + # sums into the top byte, since SSE2 alone has no `popcnt`. + this.load_into(a, index, reg::rax); + this.b.text.mov(reg::rcx, reg::rax); + this.b.text.shift_imm(shift::shr, reg::rcx, 1); + this.b.text.mov_imm(reg::rdx, 0x5555555555555555); + this.b.text.alu(alu::band, reg::rcx, reg::rdx); + this.b.text.alu(alu::sub, reg::rax, reg::rcx); + this.b.text.mov_imm(reg::rdx, 0x3333333333333333); + this.b.text.mov(reg::rcx, reg::rax); + this.b.text.shift_imm(shift::shr, reg::rcx, 2); + this.b.text.alu(alu::band, reg::rax, reg::rdx); + this.b.text.alu(alu::band, reg::rcx, reg::rdx); + this.b.text.alu(alu::add, reg::rax, reg::rcx); + this.b.text.mov(reg::rcx, reg::rax); + this.b.text.shift_imm(shift::shr, reg::rcx, 4); + this.b.text.alu(alu::add, reg::rax, reg::rcx); + this.b.text.mov_imm(reg::rdx, 0x0F0F0F0F0F0F0F0F); + this.b.text.alu(alu::band, reg::rax, reg::rdx); + this.b.text.mov_imm(reg::rdx, 0x0101010101010101); + this.b.text.imul(reg::rax, reg::rdx); + this.b.text.shift_imm(shift::shr, reg::rax, 56); + this.put(result, reg::rax); + } + op::clz, op::ctz => { + if this.body.wide { + this.count_bits(index, held, a, result); + return; + } + # `bsr` and `bsf` say nothing of zero, which is 64 of either. + this.load_into(a, index, reg::rax); + this.b.text.test(reg::rax, reg::rax); + val zero := this.b.text.jcc(cc::equal); + if held.kind == op::clz { + this.b.text.bsr(reg::rax, reg::rax); + this.b.text.alu_imm(alu::bxor, reg::rax, 63); + } else { + this.b.text.bsf(reg::rax, reg::rax); + } + val done := this.b.text.jmp(); + this.b.text.land(zero); + this.b.text.mov_imm(reg::rax, 64); + this.b.text.land(done); + this.put(result, reg::rax); + } + op::bswap => { + val into := this.target(result, reg::rax); + this.load_into(a, index, into); + this.b.text.bswap(into); + this.put(result, into); + } + else => {} + } +} + +# The instructions counting a word's bits, of x86-64-v3, as `F3 REX.W 0F` and +# these opcodes write them. +const count_popcnt: u8 = 0xB8; +const count_tzcnt: u8 = 0xBC; +const count_lzcnt: u8 = 0xBD; + +#! `ones`, `clz`, or `ctz` in a version for x86-64-v3: `popcnt`, `lzcnt`, or +#! `tzcnt`, each one instruction, which counts 64 bits of zero as the operations +#! do. +#! @param this The selector. +#! @param index The instruction. +#! @param held The instruction. +#! @param a The word. +#! @param result The count. +def selector::count_bits(&mut this, index: u32, held: &inst, a: u32, result: u32): void { + val into := this.target(result, reg::rax); + val from := this.word_reg(a, index, reg::rax); + val code := held.kind == op::ones ? count_popcnt : held.kind == op::clz ? count_lzcnt : count_tzcnt; + this.b.text.byte(0xF3); + this.b.text.rex(true, into as u32, reg::none, from, false); + this.b.text.byte(0x0F); + this.b.text.byte(code); + this.b.text.byte((0xC0 | ((into as u32 & 7) << 3) | (from as u32 & 7)) as u8); + this.put(result, into); +} + +#! `select`: a word chosen by `cmov` after testing the condition, or after +#! comparing for it where a comparison is folded into it, the other put where +#! the result goes first, or a real by a short branch, as SSE2 moves none on a +#! condition. +#! @param this The selector. +#! @param index The instruction. +#! @param held The instruction. +def selector::choose(&mut this, index: u32, held: &inst): void { + val result := held.result; + return if !this.wanted(result); + val cond := this.body.arg(index, 0); + val a := this.body.arg(index, 1); + val b := this.body.arg(index, 2); + val reader := this.p.reader_of(this.body, index); + if reader != index { + # The comparison sets the flags first, which moving and loading leave as + # they are, and what it compared is read no more. + val kind: op = this.body.insts[reader].kind; + val condition := this.compare(index, kind, this.body.arg(reader, 0), this.body.arg(reader, 1)); + var into := this.target(result, reg::rax); + if this.is_in(a, index, into) { + into = reg::rax; + } + this.load_into(b, index, into); + this.b.text.cmov(condition, into, this.word_reg(a, index, reg::rdx)); + this.put(result, into); + return; + } + if this.p.real[result] { + this.load_real_into(b, index, 0); + val tested := this.word_reg(cond, index, reg::rax); + this.b.text.test(tested, tested); + val skip := this.b.text.jcc(cc::equal); + this.load_real_into(a, index, 0); + this.b.text.land(skip); + this.put_real(result, 0); + return; + } + # The result is computed where it goes, unless the condition or the word + # chosen where it holds is there. + var into := this.target(result, reg::rax); + if this.is_in(cond, index, into) || this.is_in(a, index, into) { + into = reg::rax; + } + this.load_into(b, index, into); + val chosen := this.word_reg(a, index, reg::rdx); + val tested := this.word_reg(cond, index, reg::rcx); + this.b.text.test(tested, tested); + this.b.text.cmov(cc::not_equal, into, chosen); + this.put(result, into); +} + + +# Reals. + +#! Arithmetic of two reals in place. +#! @param this The selector. +#! @param index The instruction. +#! @param kind The arithmetic. +#! @param a The first operand. +#! @param b The second. +#! @param result The result. +#! @param commutes Whether the operands may be swapped. +def selector::real_arithmetic(&mut this, index: u32, kind: sse, a: u32, b: u32, result: u32, commutes: bool): void { + return if !this.wanted(result); + if this.works[index] { + this.single_arithmetic(index, kind, a, b, result, commutes); + return; + } + val into := this.real_target(result); + if this.is_in_xmm(a, index, into) { + this.b.text.sse(kind, into, this.real_reg(b, index, 1)); + } else if commutes && this.is_in_xmm(b, index, into) { + this.b.text.sse(kind, into, this.real_reg(a, index, 1)); + } else if this.is_in_xmm(b, index, into) { + this.load_real_into(a, index, 0); + this.b.text.sse(kind, 0, into); + this.b.text.movaps(into, 0); + } else if this.is_single_in(b, index, into) { + # The second held as an `f32` where the result goes, widened first, as + # loading the first there would lose it. + val second := this.real_reg(b, index, 1); + this.load_real_into(a, index, into); + this.b.text.sse(kind, into, second); + } else { + this.load_real_into(a, index, into); + this.b.text.sse(kind, into, this.real_reg(b, index, 1)); + } + this.put_real(result, into); +} + +#! What is left dividing reals, whose sign is the dividend's, through the +#! x87's exact `fprem`, which reads its operands from the stack. +#! @param this The selector. +#! @param index The instruction. +#! @param a The dividend. +#! @param b The divisor. +#! @param result The result. +def selector::real_remainder(&mut this, index: u32, a: u32, b: u32, result: u32): void { + return if !this.wanted(result); + val dividend := this.real_reg(a, index, 0); + val divisor := this.real_reg(b, index, 1); + this.b.text.alu_imm(alu::sub, reg::rsp, 16); + this.b.text.movsd_store(at(reg::rsp, 0), dividend); + this.b.text.movsd_store(at(reg::rsp, 8), divisor); + this.b.text.fmod_stack(); + val into := this.real_target(result); + this.b.text.movsd_load(into, at(reg::rsp, 0)); + this.b.text.alu_imm(alu::add, reg::rsp, 16); + this.put_real(result, into); +} + +#! Comparisons of reals, giving a word: false where either is not a number, +#! but for `!=`. +#! @param this The selector. +#! @param index The instruction. +#! @param kind The comparison. +#! @param a The first operand. +#! @param b The second. +#! @param result The result. +def selector::real_compare(&mut this, index: u32, kind: op, a: u32, b: u32, result: u32): void { + return if !this.wanted(result); + if kind == op::flt || kind == op::fle { + val condition := this.compare(index, kind, a, b); + this.b.text.setcc(condition, reg::rax); + this.put(result, reg::rax); + return; + } + val x := this.real_reg(a, index, 0); + val y := this.real_reg(b, index, 1); + this.b.text.ucomisd(x, y); + val equal := kind == op::feq; + this.b.text.setcc(equal ? cc::equal : cc::not_equal, reg::rax); + this.b.text.setcc(equal ? cc::no_parity : cc::parity, reg::rcx); + this.b.text.alu(equal ? alu::band : alu::bor, reg::rax, reg::rcx); + this.put(result, reg::rax); +} + + +# Memory. + +#! `load`: the value at an address. +#! @param this The selector. +#! @param index The instruction. +#! @param held The instruction. +def selector::load(&mut this, index: u32, held: &inst): void { + val how := held.aux as access; + val result := held.result; + var direct := false; + val from := this.address(this.body.arg(index, 0), index, held.imm, reg::rax, reg::rcx, &mut direct); + if !direct { + this.null_check(from.base, held.imm + how.width(), index); + } + if how.value_type().lanes() { + this.load_lanes(index, held, from); + return; + } + if this.p.real[result] { + val into := this.real_target(result); + if how == access::f32 { + this.b.text.movss_load(into, from); + if !this.single[result] { + this.b.text.cvtss2sd(into, into); + } + } else { + this.b.text.movsd_load(into, from); + } + this.put_real(result, into); + return; + } + val into := this.target(result, reg::rax); + match how { + access::i8 => this.b.text.load(1, true, into, from); + access::u8 => this.b.text.load(1, false, into, from); + access::i16 => this.b.text.load(2, true, into, from); + access::u16 => this.b.text.load(2, false, into, from); + access::i32 => this.b.text.load(4, true, into, from); + access::u32 => this.b.text.load(4, false, into, from); + else => this.b.text.load(8, false, into, from); + } + this.put(result, into); +} + +#! `store`: writes a value at an address. +#! @param this The selector. +#! @param index The instruction. +#! @param held The instruction. +def selector::store(&mut this, index: u32, held: &inst): void { + val how := held.aux as access; + val value := this.body.arg(index, 1); + var direct := false; + # The index of a sum folded into the address is in neither register the + # value is loaded into: `rcx` for a word, and `rdx` for a real made again. + val real := (how == access::f32 || how == access::f64) && this.p.real[value]; + val to := this.address(this.body.arg(index, 0), index, held.imm, reg::rax, real ? reg::rcx : reg::rdx, &mut direct); + if !direct { + this.null_check(to.base, held.imm + how.width(), index); + } + if how.value_type().lanes() { + this.store_lanes(index, held, to); + return; + } + if how == access::f32 || how == access::f64 { + if this.p.real[value] { + if how == access::f32 && this.single[value] { + this.b.text.movss_store(to, this.single_reg(value, index, 0)); + return; + } + val from := this.real_reg(value, index, 0); + if how == access::f32 { + this.b.text.cvtsd2ss(0, from); + this.b.text.movss_store(to, 0); + } else { + this.b.text.movsd_store(to, from); + } + return; + } + } + val width := how.width(); + var bits: u64 = 0; + if this.p.remade[value] && this.constant_bits(value, &mut bits) && (width < 8 || fits_i32(bits)) { + this.b.text.store_imm_width(width, to, bits); + return; + } + this.b.text.store(width, to, this.word_reg(value, index, reg::rcx)); +} + +#! `copy`: copies bytes from one address to another, a word at a time where +#! they are few, and by `rep movsb` otherwise, which `rsi` and `rdi` are kept +#! around. +#! @param this The selector. +#! @param index The instruction. +#! @param held The instruction. +def selector::copy(&mut this, index: u32, held: &inst): void { + val size := held.imm; + return if size == 0; + var to_direct := false; + var from_direct := false; + val to := this.address(this.body.arg(index, 0), index, 0, reg::rax, reg::rdx, &mut to_direct); + val from := this.address(this.body.arg(index, 1), index, 0, reg::rcx, reg::rdx, &mut from_direct); + if !to_direct { + this.null_check(to.base, size, index); + } + if !from_direct { + this.null_check(from.base, size, index); + } + if size <= 128 { + this.b.text.copy_small(to, from, size, reg::rdx, true); + return; + } + this.b.text.lea(reg::rax, to); + this.b.text.lea(reg::rdx, from); + this.b.text.push(reg::rsi); + this.b.text.push(reg::rdi); + this.b.text.mov(reg::rdi, reg::rax); + this.b.text.mov(reg::rsi, reg::rdx); + this.b.text.mov_imm(reg::rcx, size); + this.b.text.rep_movsb(); + this.b.text.pop(reg::rdi); + this.b.text.pop(reg::rsi); +} + +#! `clear`: zeroes bytes from an address. +#! @param this The selector. +#! @param index The instruction. +#! @param held The instruction. +def selector::clear(&mut this, index: u32, held: &inst): void { + val size := held.imm; + return if size == 0; + var direct := false; + val to := this.address(this.body.arg(index, 0), index, 0, reg::rax, reg::rcx, &mut direct); + if !direct { + this.null_check(to.base, size, index); + } + if size <= 128 { + this.b.text.zero_small(to, size); + return; + } + this.b.text.lea(reg::rdx, to); + this.b.text.push(reg::rdi); + this.b.text.mov(reg::rdi, reg::rdx); + this.b.text.mov_imm(reg::rax, 0); + this.b.text.mov_imm(reg::rcx, size); + this.b.text.rep_stosb(); + this.b.text.pop(reg::rdi); +} + +#! Memory a number of bytes further on. +#! @param m The memory. +#! @param bytes How many bytes. +#! @returns The memory. +pub def offset_by(m: mem, bytes: u64): mem { + return mem { base = m.base, index = m.index, scale = m.scale, disp = (m.disp as i64 + bytes as i64) as i32 }; +} + +#! Copies a few bytes, at most 128, through a register: sixteen at a time +#! through `xmm0` where it is free, then eight at a time, then as many as are +#! left of four, two, and one. Copying 16 bytes at once is what lets a vector +#! read back whole what was written whole, which the processor forwards. +#! @param this The code. +#! @param to Where they are copied to. +#! @param from Where they are copied from. +#! @param size How many there are. +#! @param temp The register they go through. +#! @param wide Whether `xmm0` is free to copy 16 bytes at a time through. +pub def assembly::copy_small(&mut this, to: mem, from: mem, size: u64, temp: reg, wide: bool): void { + var at_byte: u64 = 0; + while wide && size - at_byte >= 16 { + this.packed_mem(vec_movdqu_load, 0, offset_by(from, at_byte)); + this.packed_mem(vec_movdqu_store, 0, offset_by(to, at_byte)); + at_byte += 16; + } + while at_byte < size { + val width := piece_width(size - at_byte); + this.load(width, false, temp, offset_by(from, at_byte)); + this.store(width, offset_by(to, at_byte), temp); + at_byte += width; + } +} + +#! Zeroes a few bytes, at most 128, as `copy_small` copies them, sixteen at a +#! time through `xmm0`, which it is free to use. +#! @param this The code. +#! @param to Where they are. +#! @param size How many there are. +pub def assembly::zero_small(&mut this, to: mem, size: u64): void { + var at_byte: u64 = 0; + if size >= 16 { + this.packed(vec_pxor, 0, 0); + } + while size - at_byte >= 16 { + this.packed_mem(vec_movdqu_store, 0, offset_by(to, at_byte)); + at_byte += 16; + } + while at_byte < size { + val width := piece_width(size - at_byte); + this.store_imm_width(width, offset_by(to, at_byte), 0); + at_byte += width; + } +} + +#! How many of the bytes left a piece of a small copy moves. +#! @param left How many are left. +#! @returns 8, 4, 2, or 1. +def piece_width(left: u64): u64 { + return left >= 8 ? 8 : left >= 4 ? 4 : left >= 2 ? 2 : 1; +} + +#! `retrait`: the vtable a reference to another trait takes, from the map. +#! @param this The selector. +#! @param index The instruction. +#! @param held The instruction. +def selector::retrait(&mut this, index: u32, held: &inst): void { + this.load_into(this.body.arg(index, 0), index, reg::rax); + if this.checking() { + this.b.text.mov_imm(reg::rcx, this.b.retrait_count(held.aux)); + this.b.text.alu(alu::cmp, reg::rax, reg::rcx); + this.trap_if(cc::above_equal, fault::null_reference as u32, index); + } + val into := this.target(held.result, reg::rax); + this.b.text.load(8, false, into, indexed(reg::none, reg::rax, 8, this.b.retrait_address(held.aux) as i32)); + this.put(held.result, into); +} + +#! `check`: stops the program with an error where a condition is false, testing +#! a comparison folded into it for itself. +#! @param this The selector. +#! @param index The instruction. +#! @param held The instruction. +def selector::check(&mut this, index: u32, held: &inst): void { + val tested := this.body.arg(index, 0); + val reader := this.p.reader_of(this.body, index); + if reader != index { + # The kind is read through the code, as the C compiler passes a narrow field + # of a struct copied to the frame as the whole word holding it. + val kind: op = this.body.insts[reader].kind; + val condition := this.compare(index, kind, this.body.arg(reader, 0), this.body.arg(reader, 1)); + this.trap_if(opposite(condition), held.aux, index); + return; + } + var bits: u64 = 0; + if this.p.remade[tested] && this.constant_bits(tested, &mut bits) { + if bits == 0 { + this.trap_always(held.aux, index); + } + return; + } + val r := this.word_reg(tested, index, reg::rax); + this.b.text.test(r, r); + this.trap_if(cc::equal, held.aux, index); +} + +#! Stops the program with an error at once, jumping to the stub that reports +#! it. +#! @param this The selector. +#! @param code The error. +#! @param index The instruction, whose place the report names. +def selector::trap_always(&mut this, code: u32, index: u32): void { + val held: inst = this.body.insts[index]; + this.traps.append(trap_site { patch = this.b.text.jmp(), code = code, at = held.at, site = held.site, index = index }); +} diff --git a/native/output.sakura b/native/output.sakura new file mode 100644 index 00000000..9c378a66 --- /dev/null +++ b/native/output.sakura @@ -0,0 +1,52 @@ +#! @file output.sakura +#! @author John Christman (sorakatadzuma@gmail.com) +#! @copyright Malunal Studios, LLC. +#! @license MIT +#! +#! Contains how a build writes its files: each in place of any file there, as a +#! C compiler replaces what it writes over, even an executable a program is +#! running from. + +import std::io; +import system; +module sakura::native; + + +#! Writes bytes to a file, made with permissions, in place of any file there, +#! as `create_replacing` replaces it. +#! @param path The file. +#! @param bytes The bytes. +#! @param mode The permissions. +#! @returns Whether it was written. +pub def write_bytes(path: strview, bytes: span, mode: u32): bool { + var at_path := path::parse(path) else (_) { return false; }; + var made := create_replacing(&at_path, mode) else (_) { return false; }; + made.write(bytes) else (_) { return false; }; + made.close(); + set_permissions(&at_path, mode) else (_) { return false; }; + return true; +} + +#! Opens a file to write in place of any file at a path, as a C compiler +#! replaces what it writes over. One that cannot be opened where it is, as an +#! executable a program runs from, is moved aside first, to its path with +#! `.old` added, then removed from there. A program running from it keeps +#! running: Linux removes the file once the program ends, and Windows keeps it +#! until a file is next written in its place, which moves this one over it. +#! @param at The path of the file. +#! @param mode The permissions a file this makes is given, less the mask. +#! @returns The open file, or why it could not be opened. +pub def create_replacing(at: &path, mode: u32): result { + var made := file::create(at, mode) else (why) { + var aside := path::parse($"{at.view()}.old".view()) else (_) { return why; }; + io::rename(at, &aside) else (_) { return why; }; + var fresh := file::create(at, mode) else (again) { + _ = io::rename(&aside, at); + return again; + }; + _ = io::remove(&aside); + return move(&mut fresh); + }; + return move(&mut made); +} + diff --git a/native/registers.sakura b/native/registers.sakura new file mode 100644 index 00000000..e460c380 --- /dev/null +++ b/native/registers.sakura @@ -0,0 +1,1673 @@ +#! @file registers.sakura +#! @author John Christman (sorakatadzuma@gmail.com) +#! @copyright Malunal Studios, LLC. +#! @license MIT +#! +#! Contains the register allocator, which says where each value of a +#! function's code is held from where it is made to where it is last read: a +#! register, its slot of the frame, or nowhere, for a constant or an address +#! made again wherever it is read. +#! +#! The blocks are laid out in reverse postorder, and every value is live over +#! ranges of that order, as Wimmer and Franz's "Linear Scan Register Allocation +#! on SSA Form" builds them, with holes where it is not live. A linear scan +#! gives each value a register for as long as one is free, and splits it where +#! none is, or where a call is made: a call keeps only `rbx` and `r12` to `r15`, +#! which every function saves where it uses them, as C's conventions keep them +#! too, so a value live across a call is in one of those or in its slot. A +#! value with a slot is written to it once, where it is made, so moving it +#! there later costs nothing, and only reading it back into a register is a +#! move. +#! +#! 64 bytes of lanes are never in a register, but in their slot, as only code +#! knowing the processor has AVX-512 may hold them in one. +#! +#! Where no register is free, a value takes one from another read no more +#! often than it, counting its edges' arguments, so what a loop reads in every +#! arm keeps its register rather than making way for what one arm reads once. +#! Between values living in no loop, where the order is the order the code runs +#! in, the one read last makes way, whichever it is, so a value read at once is +#! never written to its slot only to be read back. +#! A value living across a call takes a register a call keeps at once where it +#! can, rather than another until the call, and one first read only after its +#! register would be taken back goes to its slot, so a loop's head holds each +#! value where its arms do, and its edges move nothing. +#! +#! Each instruction has four positions: its gap, where moves go before it, the +#! read of its operands, the clobber of a call, and the write of its results. +#! Each block begins with a place for its parameters and ends with one for the +#! arguments its edges give. + +import std::containers; +import sakura::compiler; +import binary::amd64; +module sakura::native; + + +#! What stands for no position, interval, or slot. +pub const never: u32 = 0xFFFFFFFF; + +#! What stands for no register. +pub const no_reg: u8 = 0xFF; + +#! Where a value is held. +pub enum place : u8 { + none, #! Nowhere: it is never read. + gpr, #! A general register. + xmm, #! An SSE register. + slot, #! The slot of the frame of the value `value`. + remade, #! Made again where it is read, as the value `value` is. + out, #! The word `value` of the arguments a call passes on the stack. + incoming, #! The word `value` of the arguments the function was called with, where it begins. +} + +#! Where a value is held at some position. +pub struct loc { + var kind: place; #! What holds it. + var number: u8; #! The register, of a register. + var value: u32; #! The value whose slot it is, which is made again, or the word of the arguments. +} + +#! Whether two places are the same. +#! @param this One place. +#! @param other The other. +#! @returns Whether they are. +pub def loc::same(&this, other: &loc): bool { + return this.kind == other.kind && this.number == other.number && this.value == other.value; +} + +#! A general register as a place. +#! @param r The register. +#! @returns The place. +pub def in_gpr(r: reg): loc { + return loc { kind = place::gpr, number = r as u8 }; +} + +#! An SSE register as a place. +#! @param x The register's number. +#! @returns The place. +pub def in_xmm(x: u8): loc { + return loc { kind = place::xmm, number = x }; +} + +#! A value's slot as a place. +#! @param value The value. +#! @returns The place. +pub def in_slot(value: u32): loc { + return loc { kind = place::slot, value = value }; +} + +#! A move of a value from one place to another. +pub struct transfer { + var from: loc; #! Where it is. + var to: loc; #! Where it goes. + var bytes: u8; #! How many bytes it moves: 16, 32, or 64 for a vector, and 8, or 0 meaning 8, otherwise. +} + +#! The general registers values are given, in the order they are chosen in: +#! those a call clobbers, in the order arguments are passed in, then those it +#! keeps. +pub const gprs: reg[11] = [ + reg::rdi, reg::rsi, reg::r8, reg::r9, reg::r10, reg::r11, reg::rbx, reg::r12, reg::r13, reg::r14, reg::r15 +]; + +#! How many general registers values are given. +pub const gpr_count: u64 = 11; + +#! The general registers a call keeps, as both of C's conventions keep them: a +#! function saves each it uses as it begins, and gives it back as it returns. +pub const kept_gprs: reg[5] = [reg::rbx, reg::r12, reg::r13, reg::r14, reg::r15]; + +#! The SSE registers values are given: all but `xmm0` to `xmm4`, which code +#! computes in, the operations on lanes all of them. A real is held in a +#! register's low 8 bytes, and a vector in its 16 or 32. A call keeps none. +pub const xmms: u8[11] = [5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15]; + +#! How many arguments a call passes in registers, the first of `gprs`, none of +#! them a register a call keeps; the rest it passes on the stack. +pub const arg_count: u64 = 6; + +#! Whether a call keeps a general register. +#! @param r The register's number. +#! @returns Whether it does. +pub def keeps(r: u8): bool { + return r == reg::rbx as u8 || (r >= reg::r12 as u8 && r <= reg::r15 as u8); +} + +#! Where moves before a position's instruction go: its gap. +#! @param at The position. +#! @returns The gap. +pub def gap_of(at: u32): u32 { + return at & 0xFFFFFFFC; +} + +#! A part of a value's life, held in one place. +struct interval { + var value: u32; #! The value. + var first: u32; #! Its first range, in `froms` and `tos`. + var last: u32; #! Its last range. + var start: u32; #! Where it begins, within its first range. + var end: u32; #! Where it ends, within its last range. + var use_lo: u32; #! Its first read, among its value's in `reads`. + var use_hi: u32; #! One past its last read. + var reg: u8; #! Its register, or `no_reg`. + var stacked: bool; #! Whether it is in its value's slot. + var next: u32; #! The part of the same value after it, or `never`. + var cursor: u32; #! The range the scan last found it in. +} + +#! Where each value of a function's code is held, and the moves between. +pub struct placing { + # The order of the code. + var order: vector; #! The blocks, in the order they are laid out. + var number: vector; #! Each block's place in that order. + var start_slots: vector; #! The place of each block's parameters. + var end_slots: vector; #! The place of each block's edges. + var slots: vector; #! The place of each instruction. + var folded: vector; #! Whether each instruction is folded into what reads it, giving no value: a comparison into a branch, a shift into the sum scaling it, or a sum into the loads and stores it addresses. + var remade: vector; #! Whether each value is made again where it is read. + var memory_params: vector; #! Whether each value is a parameter held in memory, the address of the function's own copy. + var clobbers: vector; #! The positions of the calls, where only the registers a call keeps keep what they held. + var loops: vector; #! The places each loop spans, from its head to the edge going back to it, by `pair_key(first, last)`. + var looped: vector; #! Whether each value lives within a loop: whether any range of its meets a loop's places. + var places: u32; #! How many places there are. + + # Reads, by value. + var reads: groups; #! The positions of each value's reads, in order. + var counts: vector; #! How many times each value is read, its edges' arguments included. + var def_at: vector; #! Where each value is made. + var real: vector; #! Whether each value is in the SSE registers: a real or a vector. + var bytes: vector; #! How many bytes each value is: 8, or 16, 32, or 64 for a vector. + + # Life. + var froms: vector; #! Where each range begins. + var tos: vector; #! Where each range ends, past its last position. + var intervals: vector; + var heads: vector; #! The first interval of each value, or `never`. + var liveins: groups; #! The values live where each block begins, but its parameters, by block. + + # What was chosen. + var slot_of: vector; #! The slot of each value that has one, or `never`. + var slot_count: u32; #! How many slots the values take. + var child_first: vector; #! Where each value's parts begin in `child_starts` and the rest, by value, and one more. + var child_starts: vector; + var child_ends: vector; + var child_locs: vector; + var gap_moves: groups; #! The moves in the gap of each place, by place, the stores of values made just before it first. + var edge_first: vector; #! Where each edge's moves begin in `edge_moves`, by edge, and one more. + var edge_moves: vector; #! The moves along each edge, made all at once. + + # Hints, which save moves where they are taken. + var hint: vector; #! The register each value is passed in, as an argument of a call or of the function, or `no_reg`. + var partners: groups; #! The values each would best share a register with, by value: the parameters it is given as and the arguments given as it, and the operand it is made from in place. +} + +#! Says where each value of a function's code is held. +#! @param body The code. +#! @param memory Whether each parameter of the entry is held in memory, the +#! address of the function's own copy of it. +#! @returns Where. +pub def place_values(body: &code, memory: span): placing { + var made := placing { + order = vector::::new(scratch()), + number = vector::::new(scratch()), + start_slots = vector::::new(scratch()), + end_slots = vector::::new(scratch()), + slots = vector::::new(scratch()), + folded = vector::::new(scratch()), + remade = vector::::new(scratch()), + memory_params = vector::::new(scratch()), + clobbers = vector::::new(scratch()), + loops = vector::::new(scratch()), + looped = vector::::new(scratch()), + reads = groups::::new(body.origins.length, scratch()), + counts = vector::::new(scratch()), + def_at = vector::::new(scratch()), + real = vector::::new(scratch()), + bytes = vector::::new(scratch()), + froms = vector::::new(scratch()), + tos = vector::::new(scratch()), + intervals = vector::::new(scratch()), + heads = vector::::new(scratch()), + liveins = groups::::new(body.blocks.length, scratch()), + slot_of = vector::::new(scratch()), + child_first = vector::::new(scratch()), + child_starts = vector::::new(scratch()), + child_ends = vector::::new(scratch()), + child_locs = vector::::new(scratch()), + gap_moves = groups::::new(0, scratch()), + edge_first = vector::::new(scratch()), + edge_moves = vector::::new(scratch()), + hint = vector::::new(scratch()), + partners = groups::::new(body.origins.length, scratch()) + }; + made.lay_out(body, memory); + made.count_reads(body); + made.read_all(body); + made.live(body); + made.find_looped(); + made.find_hints(body); + made.scan(false); + made.scan(true); + made.choose(body); + made.resolve(body); + return made; +} + + +# Laying out. + +#! Whether an operation calls, so only the registers a call keeps keep what +#! they held across it. A safe point calls only where a signal came, and keeps +#! every register itself. +#! @param kind The operation. +#! @returns Whether it does. +pub def calls(kind: op): bool { + return match kind { + op::call, op::call_trait, op::call_value, op::call_c, op::allocate, op::release, op::resize, + op::equal, op::syscall, op::catch, op::exit, op::abort, op::fault, op::format, op::format_text, + op::format_value, op::format_bytes, op::format_owned, op::start, op::clone => true, + else => false + }; +} + +#! Whether an operation's value is cheap enough to make again wherever it is +#! read rather than hold: a constant, or an address the code knows. +#! @param kind The operation. +#! @returns Whether it is. +pub def remakes(kind: op): bool { + return match kind { + op::iconst, op::fconst, op::cell, op::global, op::datum, op::image, op::callback, op::frame, op::c_address => true, + else => false + }; +} + +#! Whether an operation compares two values in a way one condition of the +#! flags tests, as a branch or a check may test for itself. +#! @param kind The operation. +#! @returns Whether it does. +pub def compares(kind: op): bool { + return match kind { + op::eq, op::ne, op::lts, op::ltu, op::les, op::leu, op::flt, op::fle => true, + else => false + }; +} + +#! Lays the blocks every way on from which stops the program after the rest, +#! each in the order it had, as where a contract fails makes its report: so +#! the code that runs is together, and the branch to such a block is taken +#! only where it stops. Each block is cold where it ends unreached past a +#! fault, a trap, or a call that never returns, or where every block it goes to +#! is, which a reverse walk of the order finds, as a loop never is. +#! @param this The placing. +#! @param body The code. +def placing::cold_last(&mut this, body: &code): void { + var cold := vector::::new(scratch()); + cold.resize(body.blocks.length); + var any := false; + var k := this.order.length; + while k > 0 { + k--; + val block: u32 = this.order[k]; + val last: u32 = body.blocks[block].last; + continue if last == 0; + if body.edge_count(last) == 0 { + val kind := body.insts[last].kind; + cold[block] = kind == op::unreachable || kind == op::trap; + } else { + var all := true; + var edges := body.edges_of(last); + while edges.more() { + if !cold[body.edges[edges.next()].target] { + all = false; + break; + } + } + cold[block] = all; + } + any = any || cold[block]; + } + return if !any || cold[this.order[0]]; + + var laid := vector::::new(scratch()); + for &each in this.order { + if !cold[each] { + laid.append(each); + } + } + for &each in this.order { + if cold[each] { + laid.append(each); + } + } + for i in 0..laid.length { + this.order[i] = laid[i]; + this.number[laid[i]] = i as u32; + } +} + +#! Lays the blocks out, gives each instruction its place, and finds what is +#! made again. +#! @param this The placing. +#! @param body The code. +#! @param memory Whether each parameter of the entry is held in memory. +def placing::lay_out(&mut this, body: &code, memory: span): void { + body.copy_order(&mut this.order, &mut this.number); + this.cold_last(body); + this.start_slots.resize(body.blocks.length); + this.end_slots.resize(body.blocks.length); + this.slots.resize(body.insts.length); + this.folded.resize(body.insts.length); + val values := body.origins.length; + this.remade.resize(values); + this.memory_params.resize(values); + this.real.resize(values); + this.bytes.resize(values); + this.def_at.resize(values); + for v in 0..values { + val kind := body.origins[v].kind; + this.real[v] = kind == vt::real || kind.lanes(); + this.bytes[v] = kind == vt::v512 ? 64 : kind == vt::v256 ? 32 : kind == vt::v128 ? 16 : 8; + } + + var slot: u32 = 0; + for k in 0..this.order.length { + val block: u32 = this.order[k]; + this.start_slots[block] = slot; + for ¶m in body.blocks[block].params { + this.def_at[param] = 4 * slot + 3; + } + slot++; + var walk := body.walk(block); + while walk.more() { + val at := walk.next(); + val held: inst = body.insts[at]; + this.slots[at] = slot; + for r in 0..held.count { + this.def_at[held.result as u64 + r as u64] = 4 * slot + 3; + this.remade[held.result as u64 + r as u64] = remakes(held.kind); + } + if calls(held.kind) { + this.clobbers.append(4 * slot + 2); + } + slot++; + } + this.end_slots[block] = slot; + slot++; + } + this.places = slot; + + # An edge to a block laid out at or before its own goes back round a loop. + for k in 0..this.order.length { + val block: u32 = this.order[k]; + val last: u32 = body.blocks[block].last; + continue if last == 0; + for e in 0..body.edge_count(last) { + val target: u32 = body.edges[body.insts[last].aux + e as u32].target; + if this.number[target] <= k as u32 { + this.loops.append(pair_key(this.start_slots[target], this.end_slots[block])); + } + } + } + + # A parameter held in memory is the address of the function's own copy, + # which is made again where it is read. + val entry := &body.blocks[0]; + for i in 0..entry.params.length { + if i < memory.length && memory[i] { + val value: u32 = entry.params[i]; + this.remade[value] = true; + this.memory_params[value] = true; + } + } +} + +#! Counts the reads of each value, then folds each comparison only the branch +#! or check after it reads into it, and the sums and shifts addresses are made +#! of into what reads them. +#! @param this The placing. +#! @param body The code. +def placing::count_reads(&mut this, body: &code): void { + this.counts.resize(body.origins.length); + var reads := body.reader(); + for k in 0..this.order.length { + var walk := body.walk(this.order[k]); + while walk.more() { + reads.start(walk.next()); + while reads.more() { + val value := reads.next(); + this.counts[value] = this.counts[value] + 1; + } + } + } + for k in 0..this.order.length { + var walk := body.walk(this.order[k]); + while walk.more() { + val at := walk.next(); + this.folded[at] = this.foldable(body, at); + } + } + this.fold_addresses(body); +} + +#! Folds what addresses are made of as x86 addresses memory, `[base + index * +#! scale + displacement]`: each sum read only as the address of one load or +#! store into it, as its base and index, and each shift left by one to three +#! read only by a sum into the sum, as its index's scale, which the sum +#! otherwise makes with `lea`. What is folded gives no value, and what reads it +#! reads what it is made of instead. A sum several accesses read stays, as +#! holding its base and index to each would hold two values for one. +#! @param this The placing. +#! @param body The code. +def placing::fold_addresses(&mut this, body: &code): void { + # How many times each value is read as the address of a load or store whose + # reach needs no test of it for null, which a fault makes. + var addressed := vector::::new(scratch()); + addressed.resize(body.origins.length); + for k in 0..this.order.length { + var walk := body.walk(this.order[k]); + while walk.more() { + val held: inst = body.insts[walk.next()]; + continue if held.kind != op::load && held.kind != op::store; + continue if held.imm + (held.aux as access).width() > null_page; + val address := body.operands[held.args as u64]; + addressed[address] = addressed[address] + 1; + } + } + for k in 0..this.order.length { + var walk := body.walk(this.order[k]); + while walk.more() { + val at := walk.next(); + val held: inst = body.insts[at]; + continue if held.kind != op::add || this.real[held.result]; + for a in 0..2u { + val shift := this.scaling(body, body.arg(at, a as u32)); + if shift != 0 { + this.folded[shift] = true; + break; + } + } + val result := held.result; + if this.counts[result] == 1 && addressed[result] == 1 && this.addresses(body, at) { + this.folded[at] = true; + } + } + } +} + +#! The shift a value is, of a word left by one to three, read only once, as a +#! sum reads it to scale its index, or 0. +#! @param this The placing. +#! @param body The code. +#! @param value The value. +#! @returns The shift. +def placing::scaling(&this, body: &code, value: u32): u32 { + val made := body.defining(value); + return 0 if made == 0 || this.counts[value] != 1; + val held: inst = body.insts[made]; + return 0 if held.kind != op::shl; + val by := body.arg(made, 1); + val count := body.defining(by); + return 0 if count == 0 || body.insts[count].kind != op::iconst; + val bits: u64 = body.insts[count].imm; + val shifted := body.arg(made, 0); + return 0 if bits < 1 || bits > 3 || this.remade[shifted] || this.real[shifted]; + return made; +} + +#! Whether a sum may be the address memory is reached at: neither operand a +#! constant, which is a displacement instead, and one of them held, rather +#! than made again, as its index. +#! @param this The placing. +#! @param body The code. +#! @param index The sum. +#! @returns Whether it may. +def placing::addresses(&this, body: &code, index: u32): bool { + var held_index := false; + for a in 0..2u { + val operand := body.arg(index, a as u32); + val made := body.defining(operand); + if made != 0 { + val kind: op = body.insts[made].kind; + return false if kind == op::iconst || kind == op::fconst; + } + held_index = held_index || !this.remade[operand]; + } + return held_index; +} + +#! Whether an instruction is a comparison read only by the branch, check, or +#! choice of words after it, which compares for itself, so the comparison +#! gives no value. +#! @param this The placing. +#! @param body The code. +#! @param index The instruction. +#! @returns Whether it is. +def placing::foldable(&this, body: &code, index: u32): bool { + val held: inst = body.insts[index]; + return false if !compares(held.kind) || held.next == 0 || this.counts[held.result] != 1; + val next: inst = body.insts[held.next]; + val tests := next.kind == op::branch || next.kind == op::check || (next.kind == op::select && !this.real[next.result]); + return tests && next.argc != 0 && body.operands[next.args as u64] == held.result; +} + +#! The instruction whose operands an instruction reads where it is: its own, +#! or for a branch, check, or select a comparison is folded into, the +#! comparison, though a select reads what it chooses between too. +#! @param this The placing. +#! @param body The code. +#! @param index The instruction. +#! @returns The instruction whose operands are read. +pub def placing::reader_of(&this, body: &code, index: u32): u32 { + val held: inst = body.insts[index]; + if (held.kind == op::branch || held.kind == op::check || held.kind == op::select) && held.argc != 0 { + val tested := body.operands[held.args as u64]; + val origin: origin = body.origins[tested]; + if !origin.param && this.folded[origin.from] { + return origin.from; + } + } + return index; +} + +#! The values an instruction reads where it is: its operands, or for one a +#! comparison is folded into, the comparison's, and for a select so folded what +#! it chooses between too, where each operand folded into it is what it is made +#! of. +#! @param this The placing. +#! @param body The code. +#! @param index The instruction. +#! @param into Where the values are written, emptied first. +pub def placing::read_by(&this, body: &code, index: u32, into: &mut vector): void { + into.clear(); + val reader := this.reader_of(body, index); + val read: inst = body.insts[reader]; + for i in 0..read.argc { + this.read_through(body, body.operands[read.args as u64 + i as u64], into); + } + if reader != index && body.insts[index].kind == op::select { + this.read_through(body, body.arg(index, 1), into); + this.read_through(body, body.arg(index, 2), into); + } +} + +#! Adds what reading a value reads: the value, or what it is made of where it +#! is folded into what reads it, the sum of an address its operands and a +#! shift the word it scales. +#! @param this The placing. +#! @param body The code. +#! @param value The value. +#! @param into Where the values are written. +def placing::read_through(&this, body: &code, value: u32, into: &mut vector): void { + val made := body.defining(value); + if made != 0 && this.folded[made] { + val kind: op = body.insts[made].kind; + if kind == op::add { + this.read_through(body, body.arg(made, 0), into); + this.read_through(body, body.arg(made, 1), into); + return; + } + if kind == op::shl { + into.append(body.arg(made, 0)); + return; + } + } + into.append(value); +} + +#! Finds where every value is read by an instruction: what it reads where it +#! is, as `read_by` says. Arguments of edges are not kept as reads, since a +#! move reads them from anywhere, though they keep a value live. +#! @param this The placing. +#! @param body The code. +def placing::read_all(&mut this, body: &code): void { + this.each_read(body); + this.reads.seal(); + this.each_read(body); +} + +#! Walks the reads of the instructions, in the order laid out, counting them +#! for each value, or, once `reads` is sealed, putting their positions. +#! @param this The placing. +#! @param body The code. +def placing::each_read(&mut this, body: &code): void { + val fill := this.reads.is_sealed; + var operands := vector::::new(scratch()); + for k in 0..this.order.length { + var walk := body.walk(this.order[k]); + while walk.more() { + val index := walk.next(); + continue if this.folded[index]; + val position := 4 * this.slots[index] + 1; + this.read_by(body, index, &mut operands); + for &value in operands { + if fill { + this.reads.put(value, position); + } else { + this.reads.count(value); + } + } + } + } +} + + +# Life. + +#! Finds the ranges each value is live over, and the values live where each +#! block begins: walking back from each read to the block making the value, as +#! the machine's assembler does. +#! @param this The placing. +#! @param body The code. +def placing::live(&mut this, body: &code): void { + val values := body.origins.length; + val blocks := body.blocks.length; + this.heads.resize(values, never); + + # Each block's reads by value: the arguments of edges, read where a block + # ends, as well as the operands. These are gathered value by value. + var args := groups::::new(values, scratch()); + var given := body.reader(); + for pass in 0..2u { + if pass == 1 { + args.seal(); + } + for k in 0..this.order.length { + val block: u32 = this.order[k]; + val last: u32 = body.blocks[block].last; + continue if last == 0; + given.start(last); + while given.more() { + val value := given.next(); + # Only what its edges give, as its operands are read where it is. + continue if given.operand() != no_operand; + if pass == 0 { + args.count(value); + } else { + args.put(value, block); + } + } + } + } + + # The block of each read, which an instruction's place gives. + var block_of_slot := vector::::new(scratch()); + block_of_slot.resize(this.places as u64); + for k in 0..this.order.length { + val block: u32 = this.order[k]; + for s in this.start_slots[block]..this.end_slots[block] + 1 { + block_of_slot[s as u64] = block; + } + } + + var walk := live_walk::new(blocks, scratch()); + var keys := vector::::new(scratch()); + var livein_pairs := vector::::new(scratch()); + + for v in 1..values { + continue if this.remade[v] || !this.made_somewhere(body, v as u32); + continue if this.reads.length(v) == 0 && args.length(v) == 0; + val home := body.home_of(v as u32); + continue if this.number[home] == never; + + # Each read: in its block up to where it is, and live into that block + # where it is not where the value is made, and back from there over the + # blocks laid out. + walk.begin(v as u32, home); + for &position in this.reads.of(v) { + walk.read(block_of_slot[(position / 4) as u64], position); + } + for &block in args.of(v) { + walk.read_out(block); + } + walk.walk(body, &this.number, true); + + # The ranges, in the order the blocks are laid out. + keys.clear(); + for &block in walk.touched { + keys.append(pair_key(this.number[block], block)); + } + keys.sort(); + val first := this.froms.length as u32; + for &key in keys { + val block := pair_low(key); + val held: block_reach = walk.reaches[block]; + val from := block == home ? this.def_at[v] : 4 * this.start_slots[block]; + val to := held.out ? 4 * this.end_slots[block] + 4 : held.ends; + continue if to <= from; + if held.into && block != home { + livein_pairs.append(pair_key(block, v as u32)); + } + val count := this.froms.length; + if count > first as u64 && this.tos[count - 1] == from { + this.tos[count - 1] = to; + continue; + } + this.froms.append(from); + this.tos.append(to); + } + continue if this.froms.length == first as u64; + val last := (this.froms.length - 1) as u32; + this.heads[v] = this.intervals.length as u32; + this.intervals.append(interval { + value = v as u32, + first = first, + last = last, + start = this.froms[first as u64], + end = this.tos[last as u64], + use_lo = 0, + use_hi = this.reads.length(v) as u32, + reg = no_reg, + next = never, + cursor = first + }); + } + + # The values live where each block begins, block by block, each block's in + # the order of the values, as they were found. + for &pair in livein_pairs { + this.liveins.count(pair_high(pair)); + } + this.liveins.seal(); + for &pair in livein_pairs { + this.liveins.put(pair_high(pair), pair_low(pair)); + } +} + +#! Whether a value is made by any instruction or block the layout holds. +#! @param this The placing. +#! @param body The code. +#! @param value The value. +#! @returns Whether it is. +def placing::made_somewhere(&this, body: &code, value: u32): bool { + return this.number[body.home_of(value)] != never; +} + +#! The moves along an edge, made all at once. +#! @param this The placing. +#! @param edge The edge. +#! @returns The moves. +pub def placing::edge_moves_of(&this, edge: u32): span { + val first: u32 = this.edge_first[edge as u64]; + return span::::over(this.edge_moves.view().data + first as u64, (this.edge_first[edge as u64 + 1] - first) as u64); +} + + +# Ranges. + +#! Where a range of an interval begins, as far as the interval holds it. +#! @param this The placing. +#! @param it The interval. +#! @param at The range. +#! @returns Where. +def placing::from_of(&this, it: &interval, at: u32): u32 { + return at == it.first ? it.start : this.froms[at as u64]; +} + +#! Where a range of an interval ends, as far as the interval holds it. +#! @param this The placing. +#! @param it The interval. +#! @param at The range. +#! @returns Where. +def placing::to_of(&this, it: &interval, at: u32): u32 { + return at == it.last ? it.end : this.tos[at as u64]; +} + +#! Whether an interval holds its value at a position the scan has reached, +#! moving its cursor on, since the scan's position only grows. +#! @param this The placing. +#! @param id The interval. +#! @param at The position. +#! @returns Whether it does. +def placing::covers_now(&mut this, id: u32, at: u32): bool { + val it: interval = this.intervals[id]; + var k := it.cursor; + while k < it.last && this.to_of(&it, k) <= at { + k++; + } + this.intervals[id].cursor = k; + return this.from_of(&it, k) <= at && at < this.to_of(&it, k); +} + +#! The first position two intervals both hold, or `never`. +#! @param this The placing. +#! @param a One interval. +#! @param b The other. +#! @returns The position. +def placing::intersection(&this, a: u32, b: u32): u32 { + val x: interval = this.intervals[a]; + val y: interval = this.intervals[b]; + var i := x.first; + var j := y.first; + while i <= x.last && j <= y.last { + val xf := this.from_of(&x, i); + val xt := this.to_of(&x, i); + val yf := this.from_of(&y, j); + val yt := this.to_of(&y, j); + val lo := xf > yf ? xf : yf; + val hi := xt < yt ? xt : yt; + if lo < hi { + return lo; + } + if xt <= yt { + i++; + } else { + j++; + } + } + return never; +} + +#! The first read of an interval at or after a position, or `never`. +#! @param this The placing. +#! @param id The interval. +#! @param at The position. +#! @returns Where. +def placing::next_use(&this, id: u32, at: u32): u32 { + val it: interval = this.intervals[id]; + val reads := span::::over(this.reads.of(it.value).data + it.use_lo, (it.use_hi - it.use_lo) as u64); + val next := reads.lower_bound(&at); + return next < reads.length ? reads[next] : never; +} + +#! The first call an interval holds its value across, at or after a position, +#! or `never`. +#! @param this The placing. +#! @param id The interval. +#! @param at The position. +#! @returns The call's clobber. +def placing::next_clobber(&this, id: u32, at: u32): u32 { + val it: interval = this.intervals[id]; + val count := this.clobbers.length; + return never if count == 0; + for k in it.first..it.last + 1 { + val to := this.to_of(&it, k); + continue if to <= at; + val from := this.from_of(&it, k); + val lo := from > at ? from : at; + val low := this.clobbers.view().lower_bound(&lo); + if low < count && this.clobbers[low] < to { + return this.clobbers[low]; + } + } + return never; +} + +#! Splits an interval at a position, the part from there on becoming one of +#! its own, which comes after it among its value's parts. +#! @param this The placing. +#! @param id The interval, which holds positions before and after the +#! position. +#! @param at The position. +#! @returns The part split off. +def placing::split(&mut this, id: u32, at: u32): u32 { + val it: interval = this.intervals[id]; + var k := it.first; + while k < it.last && this.to_of(&it, k) <= at { + k++; + } + var child := interval { + value = it.value, + first = k, + last = it.last, + end = it.end, + reg = no_reg, + next = it.next, + cursor = k + }; + if this.from_of(&it, k) < at { + child.start = at; + this.intervals[id].last = k; + this.intervals[id].end = at; + } else { + child.start = this.from_of(&it, k); + this.intervals[id].last = k - 1; + this.intervals[id].end = this.to_of(&it, k - 1); + } + if this.intervals[id].cursor > this.intervals[id].last { + this.intervals[id].cursor = this.intervals[id].last; + } + + # The reads before the part split off stay. + val reads := this.reads.of(it.value); + var mid := it.use_lo; + while mid < it.use_hi && reads[mid as u64] < child.start { + mid++; + } + child.use_lo = mid; + child.use_hi = it.use_hi; + this.intervals[id].use_hi = mid; + val made := this.intervals.length as u32; + this.intervals[id].next = made; + this.intervals.append(child); + return made; +} + + +# Hints. + +#! Works out the hints: the register each value is passed in, as an argument +#! of a call or of the function itself, and the values each would best share a +#! register with, so a move between them goes. +#! @param this The placing. +#! @param body The code. +def placing::find_hints(&mut this, body: &code): void { + val values := body.origins.length; + this.hint.resize(values, no_reg); + val entry := &body.blocks[0].params; + for i in 0..entry.length { + break if i >= arg_count; + this.hint[entry[i]] = gprs[i] as u8; + } + + # The pairs, each both ways round. + var pairs := vector::::new(scratch()); + for k in 0..this.order.length { + var walk := body.walk(this.order[k]); + while walk.more() { + val at := walk.next(); + continue if this.folded[at]; + val held: inst = body.insts[at]; + match held.kind { + # A function value's two words are not among the arguments it is + # passed in registers. + op::call, op::call_trait, op::call_value => { + val skip: u32 = held.kind == op::call_value ? 2 : 0; + for a in skip..held.argc { + break if (a - skip) as u64 >= arg_count; + val given := body.arg(at, a); + if this.hint[given] == no_reg && !this.real[given] { + this.hint[given] = gprs[(a - skip) as u64] as u8; + } + } + } + op::add, op::sub, op::band, op::bor, op::bxor, op::mul, op::shl, op::shrs, op::shru, + op::fadd, op::fsub, op::fmul, op::fdiv => { + pairs.append(pair_key(held.result, body.arg(at, 0))); + val commutes := held.kind == op::add || held.kind == op::band || held.kind == op::bor + || held.kind == op::bxor || held.kind == op::mul || held.kind == op::fadd || held.kind == op::fmul; + if commutes { + pairs.append(pair_key(held.result, body.arg(at, 1))); + } + } + else => {} + } + for e in 0..body.edge_count(at) { + val edge := held.aux + e as u32; + val params := &body.blocks[body.edges[edge].target].params; + val args := &body.edges[edge].args; + for i in 0..args.length { + val param: u32 = params[i]; + val arg: u32 = args[i]; + continue if param == arg; + pairs.append(pair_key(param, arg)); + pairs.append(pair_key(arg, param)); + } + } + } + } + + # Each value's partners, in the order they were found. + for &each in pairs { + this.partners.count(pair_high(each)); + } + this.partners.seal(); + for &each in pairs { + this.partners.put(pair_high(each), pair_low(each)); + } +} + + +# The scan. + +#! What the scan of one class of registers keeps. +struct scanning { + var heap: heap; #! The intervals not yet given a place, each its start and itself as a pair's key, least first. + var active: vector; #! Those holding a register where the scan is. + var inactive: vector; #! Those holding a register, in a hole where the scan is. + var real: bool; #! Whether the class is the SSE registers. +} + +#! Gives each value of one class a place, a register where one is free and its +#! slot otherwise, in the order the values begin. +#! @param this The placing. +#! @param real Whether the class is the reals, which SSE registers hold. +def placing::scan(&mut this, real: bool): void { + var work := scanning { + heap = heap::::new(scratch()), + active = vector::::new(scratch()), + inactive = vector::::new(scratch()), + real = real + }; + for v in 0..this.heads.length { + val head: u32 = this.heads[v]; + continue if head == never || this.real[v] != real; + work.heap.push(pair_key(this.intervals[head].start, head)); + } + + while work.heap.length != 0 { + val id := pair_low(work.heap.peek()); + work.heap.pop(); + val position: u32 = this.intervals[id].start; + + # Those that ended go, those in a hole wait, and those out of one hold + # their registers again. + this.sweep(&mut work.active, &mut work.inactive, position, false); + this.sweep(&mut work.inactive, &mut work.active, position, true); + this.assign(id, &mut work); + } +} + +#! Takes out of a list of intervals holding registers those that ended before +#! a position, and moves to another those whose cover of it is as asked. +#! @param this The placing. +#! @param from The intervals swept. +#! @param to Where those moved go. +#! @param position The position. +#! @param covered Whether those covering the position move, rather than +#! those in a hole there. +def placing::sweep(&mut this, from: &mut vector, to: &mut vector, position: u32, covered: bool): void { + var i: u64 = 0; + while i < from.length { + val held: u32 = from[i]; + val ended := this.intervals[held].end <= position; + if ended || this.covers_now(held, position) == covered { + if !ended { + to.append(held); + } + from[i] = from.last(); + from.truncate(); + continue; + } + i++; + } +} + +#! Gives an interval a place: a register for as long as one is free, or the +#! register held by what is read last, or its slot. Across a call, only a +#! register the call keeps holds it. +#! @param this The placing. +#! @param id The interval. +#! @param work What the scan keeps. +def placing::assign(&mut this, id: u32, work: &mut scanning): void { + val position: u32 = this.intervals[id].start; + val end: u32 = this.intervals[id].end; + # 64 bytes of lanes are held in their slot, as the instructions working them + # load and store them there. + if this.bytes[this.intervals[id].value] == 64 { + this.spill(id, work); + return; + } + + # Across a call in the place it begins, it can only be in a register the call + # keeps, which no SSE register is, or its slot. + val clobber := this.next_clobber(id, position); + val at_call := clobber != never && gap_of(clobber) <= position; + if at_call && work.real { + this.spill(id, work); + return; + } + + # Each register is free until another holds it, and one a call clobbers + # until the call. + var free: u32[16]; + val counted: u64 = 11; + for k in 0..counted { + val r := this.register_at(work.real, k); + free[r as u64] = this.call_free(work.real, r, clobber, at_call); + } + for &held in work.active { + free[this.intervals[held].reg as u64] = 0; + } + for &held in work.inactive { + val r := this.intervals[held].reg as u64; + continue if free[r] == 0; + val meets := this.intersection(held, id); + if meets < free[r] { + free[r] = meets; + } + } + + # A register a hint names, free for the whole interval, saves a move. + var wishes: u8[8]; + val wished := this.wishes_of(id, work.real, &mut wishes); + for w in 0..wished { + val r := wishes[w]; + if free[r as u64] >= end && free[r as u64] > position { + this.intervals[id].reg = r; + work.active.append(id); + return; + } + } + + # A register free for the whole interval, of those a call clobbers first, as + # the function saves one a call keeps, and the one free longest of them. + for pass in 0..2u { + var fits := no_reg; + for k in 0..counted { + val r := this.register_at(work.real, k); + continue if (!work.real && keeps(r)) != (pass == 1); + if free[r as u64] >= end && (fits == no_reg || free[r as u64] > free[fits as u64]) { + fits = r; + } + } + if fits != no_reg { + this.intervals[id].reg = fits; + work.active.append(id); + return; + } + } + + # Across a call, a register the call keeps holds it whole where what holds + # one now is read after it, so a value read in a loop holding a call keeps + # one register throughout, rather than another at the loop's head than in + # its body, with moves between on every edge. + if !work.real && clobber != never && clobber < end && this.take_kept(id, position, work) { + return; + } + + # Otherwise the one free longest holds it until it is not. + var best := this.register_at(work.real, 0); + for k in 1..counted { + val r := this.register_at(work.real, k); + if free[r as u64] > free[best as u64] { + best = r; + } + } + # Unless it is first read only after that, where it would only be moved to + # its slot: a block's parameter would then be moved into the register on + # every edge going to the block, as a loop's is on every way round it. + val until := free[best as u64]; + if until > position { + val at := gap_of(until); + if at > position && this.next_use(id, position) < at { + work.heap.push(pair_key(at, this.split(id, at))); + this.intervals[id].reg = best; + work.active.append(id); + return; + } + } + + # Every register is held: of those whose holders are read no more often than + # this, within a loop, or of all of them otherwise, the one whose holder is + # read last is taken, unless this is read later still and its holder no less + # often. So a value read in every arm of a loop keeps its register, rather + # than making way for one read once. + val looping := this.in_loop(position) || this.loop_live(id); + var used: u32[16]; + var heavy: u32[16]; + var loopy: bool[16]; + for k in 0..counted { + val r := this.register_at(work.real, k); + used[r as u64] = this.call_free(work.real, r, clobber, at_call); + heavy[r as u64] = 0; + loopy[r as u64] = false; + } + this.holders(id, position, work, &mut used, &mut heavy, &mut loopy); + val mine := this.weight(id); + var taken := no_reg; + for k in 0..counted { + val r := this.register_at(work.real, k); + continue if (looping || loopy[r as u64]) && heavy[r as u64] > mine; + if taken == no_reg || used[r as u64] > used[taken as u64] { + taken = r; + } + } + # A holder read less makes way even where it is read first, but a call does + # not, nor a register it clobbers before this is read. + val first := this.next_use(id, position); + val lighter := looping && taken != no_reg && heavy[taken as u64] < mine + && this.call_free(work.real, taken, clobber, at_call) > first; + if first == never || taken == no_reg || (used[taken as u64] <= first && !lighter) { + this.spill(id, work); + return; + } + + this.take(id, taken, position, work); + if clobber != never && clobber < this.intervals[id].end && (work.real || !keeps(taken)) { + val at := gap_of(clobber); + work.heap.push(pair_key(at, this.split(id, at))); + } + work.active.append(id); +} + +#! Gives an interval living across a call a register the call keeps, held now, +#! where what holds it is read no more often than it, and is next read after +#! it, or less often: of those, the one whose holder is read last. +#! @param this The placing. +#! @param id The interval. +#! @param position Where it begins. +#! @param work What the scan keeps. +#! @returns Whether it was given one. +def placing::take_kept(&mut this, id: u32, position: u32, work: &mut scanning): bool { + val first := this.next_use(id, position); + return false if first == never; + var used: u32[16]; + var heavy: u32[16]; + var loopy: bool[16]; + for r in 0..16u { + used[r] = never; + heavy[r] = 0; + } + this.holders(id, position, work, &mut used, &mut heavy, &mut loopy); + val mine := this.weight(id); + var taken := no_reg; + for &r in kept_gprs { + continue if heavy[r as u64] > mine; + if taken == no_reg || used[r as u64] > used[taken as u64] { + taken = r as u8; + } + } + return false if taken == no_reg || (used[taken as u64] <= first && heavy[taken as u64] >= mine); + this.take(id, taken, position, work); + work.active.append(id); + return true; +} + +#! Whether a block is the head of a loop, which an edge goes back to. +#! @param this The placing. +#! @param block The block. +#! @returns Whether it is. +pub def placing::heads_loop(&this, block: u32): bool { + val first := this.start_slots[block]; + for &span in this.loops { + return true if pair_high(span) == first; + } + return false; +} + +#! Whether a place is within a loop: between a loop's head and the edge going +#! back to it. +#! @param this The placing. +#! @param at The position. +#! @returns Whether it is. +def placing::in_loop(&this, at: u32): bool { + val place := at / 4; + for &span in this.loops { + return true if pair_high(span) <= place && place <= pair_low(span); + } + return false; +} + +#! Finds which values live within a loop, as `looped` says. +#! @param this The placing. +def placing::find_looped(&mut this): void { + this.looped.resize(this.heads.length); + return if this.loops.length == 0; + for v in 0..this.heads.length { + var part: u32 = this.heads[v]; + while part != never && !this.looped[v] { + val it: interval = this.intervals[part]; + for k in it.first..it.last + 1 { + val from := this.froms[k as u64] / 4; + val to := (this.tos[k as u64] + 3) / 4; + for &span in this.loops { + if from <= pair_low(span) && pair_high(span) <= to { + this.looped[v] = true; + } + } + } + part = it.next; + } + } +} + +#! Whether an interval's value lives within a loop. +#! @param this The placing. +#! @param id The interval. +#! @returns Whether it does. +def placing::loop_live(&this, id: u32): bool { + return this.looped[this.intervals[id].value]; +} + +#! How often an interval's value is read, its edges' arguments included: what +#! a value read less makes way for in a register. +#! @param this The placing. +#! @param id The interval. +#! @returns How often. +def placing::weight(&this, id: u32): u32 { + return this.counts[this.intervals[id].value]; +} + +#! Of each register, when what holds it, now or where it meets an interval, is +#! next read, how often the most read of those is, and whether any lives in a +#! loop. +#! @param this The placing. +#! @param id The interval. +#! @param position Where it begins. +#! @param work What the scan keeps. +#! @param used Each register's next read, lowered to its holders'. +#! @param heavy Each register's weight, raised to its holders'. +#! @param loopy Whether a holder of each lives in a loop. +def placing::holders(&this, id: u32, position: u32, work: &scanning, used: &mut u32[16], heavy: &mut u32[16], loopy: &mut bool[16]): void { + for &held in work.active { + val r := this.intervals[held].reg as u64; + val next := this.next_use(held, position); + if next < used[r] { + used[r] = next; + } + val weight := this.weight(held); + if weight > heavy[r] { + heavy[r] = weight; + } + loopy[r] = loopy[r] || this.loop_live(held); + } + for &held in work.inactive { + val r := this.intervals[held].reg as u64; + continue if this.intersection(held, id) == never; + val next := this.next_use(held, position); + if next < used[r] { + used[r] = next; + } + val weight := this.weight(held); + if weight > heavy[r] { + heavy[r] = weight; + } + loopy[r] = loopy[r] || this.loop_live(held); + } +} + +#! Gives an interval a register, moving what held it to its slot: what holds +#! it now, and what holds it later where the two meet. +#! @param this The placing. +#! @param id The interval. +#! @param taken The register. +#! @param position Where the interval begins. +#! @param work What the scan keeps. +def placing::take(&mut this, id: u32, taken: u8, position: u32, work: &mut scanning): void { + this.intervals[id].reg = taken; + var i: u64 = 0; + while i < work.active.length { + val held: u32 = work.active[i]; + if this.intervals[held].reg != taken { + i++; + continue; + } + work.active[i] = work.active.last(); + work.active.truncate(); + this.evict(held, position, work); + } + i = 0; + while i < work.inactive.length { + val held: u32 = work.inactive[i]; + val meets := this.intervals[held].reg == taken ? this.intersection(held, id) : never; + if meets == never { + i++; + continue; + } + # What is left of it in the register, before where they meet, may still + # hold it past here, so it stays. + this.evict(held, meets, work); + if this.intervals[held].reg == taken && this.intervals[held].end > position { + i++; + continue; + } + work.inactive[i] = work.inactive.last(); + work.inactive.truncate(); + } +} + +#! Until where a register may hold an interval, as far as calls go: past every +#! call for one a call keeps, and for another until the first call the +#! interval lives across, or not at all where it begins there. +#! @param this The placing. +#! @param real Whether the register is an SSE register. +#! @param r The register. +#! @param clobber The first call the interval lives across, or `never`. +#! @param at_call Whether the interval begins at that call. +#! @returns Where. +def placing::call_free(&this, real: bool, r: u8, clobber: u32, at_call: bool): u32 { + return never if !real && keeps(r); + return at_call ? 0 : clobber; +} + +#! The registers an interval would best be in, the best first: that of the +#! part of its value before it, the one its value is passed in, and those its +#! partners were given. +#! @param this The placing. +#! @param id The interval. +#! @param real Whether its class is the SSE registers. +#! @param wishes Where the registers are written. +#! @returns How many. +def placing::wishes_of(&this, id: u32, real: bool, wishes: &mut u8[8]): u64 { + var count: u64 = 0; + val value: u32 = this.intervals[id].value; + var part: u32 = this.heads[value]; + while part != never && part != id { + if this.intervals[part].next == id && this.intervals[part].reg != no_reg { + wishes[count] = this.intervals[part].reg; + count++; + } + part = this.intervals[part].next; + } + if !real && this.hint[value] != no_reg { + wishes[count] = this.hint[value]; + count++; + } + for &partner in this.partners.of(value) { + break if count == 8; + continue if this.real[partner] != real; + var each: u32 = this.heads[partner]; + while each != never && this.intervals[each].reg == no_reg { + each = this.intervals[each].next; + } + continue if each == never; + wishes[count] = this.intervals[each].reg; + count++; + } + return count; +} + +#! The register of a class at a place in the order registers are chosen in. +#! @param this The placing. +#! @param real Whether the class is the SSE registers. +#! @param k The place. +#! @returns The register's number. +def placing::register_at(&this, real: bool, k: u64): u8 { + return real ? xmms[k] : gprs[k] as u8; +} + +#! Puts an interval in its value's slot, until the first read past where it +#! begins, from which the rest is given a place of its own. +#! @param this The placing. +#! @param id The interval. +#! @param work What the scan keeps. +def placing::spill(&mut this, id: u32, work: &mut scanning): void { + this.intervals[id].reg = no_reg; + this.intervals[id].stacked = true; + val it: interval = this.intervals[id]; + val begins := gap_of(it.start); + val reads := this.reads.of(it.value); + for u in it.use_lo..it.use_hi { + val at := gap_of(reads[u as u64]); + continue if at <= begins; + if at > it.start && at < it.end { + work.heap.push(pair_key(at, this.split(id, at))); + } + return; + } +} + +#! Takes the register from an interval from a position on: the part from the +#! gap of that position goes to its value's slot, and its reads after are +#! given places of their own. +#! @param this The placing. +#! @param id The interval. +#! @param at The position. +#! @param work What the scan keeps. +def placing::evict(&mut this, id: u32, at: u32, work: &mut scanning): void { + val begins := gap_of(at); + if begins <= this.intervals[id].start { + this.spill(id, work); + return; + } + val child := this.split(id, begins); + this.spill(child, work); +} + + +# What was chosen. + +#! Gives each value with a part in its slot a slot, and lists each value's +#! parts, in order, with where each is. +#! @param this The placing. +#! @param body The code. +def placing::choose(&mut this, body: &code): void { + val values := body.origins.length; + this.slot_of.resize(values); + this.child_first.resize(values + 1); + for v in 0..values { + this.slot_of[v] = never; + this.child_first[v] = this.child_starts.length as u32; + var id: u32 = this.heads[v]; + while id != never { + val it: interval = this.intervals[id]; + var held_in := loc { kind = place::none }; + if it.stacked { + if this.slot_of[v] == never { + this.slot_of[v] = this.slot_count; + this.slot_count += (this.bytes[v] / 8) as u32; + } + held_in = in_slot(v as u32); + } else if it.reg != no_reg { + held_in = this.real[v] ? in_xmm(it.reg) : loc { kind = place::gpr, number = it.reg }; + } + this.child_starts.append(it.start); + this.child_ends.append(it.end); + this.child_locs.append(held_in); + id = it.next; + } + } + this.child_first[values] = this.child_starts.length as u32; +} + +#! Where a value is at a position. +#! @param this The placing. +#! @param value The value. +#! @param at The position. +#! @returns Where: made again, the part holding it there, or nowhere. +pub def placing::located(&this, value: u32, at: u32): loc { + if this.remade[value] { + return loc { kind = place::remade, value = value }; + } + val first: u32 = this.child_first[value]; + val last: u32 = this.child_first[value + 1]; + return loc { kind = place::none } if first == last; + # The last part beginning at or before the position, or the first. + val starts := span::::over(this.child_starts.view().data + first, (last - first) as u64); + val after := starts.upper_bound(&at); + return this.child_locs[first as u64 + (after == 0 ? 0 : after - 1)]; +} + +#! Where a value is read at an instruction. +#! @param this The placing. +#! @param value The value. +#! @param index The instruction. +#! @returns Where. +pub def placing::read_at(&this, value: u32, index: u32): loc { + return this.located(value, 4 * this.slots[index] + 1); +} + +#! Where an instruction's result goes. +#! @param this The placing. +#! @param value The result. +#! @returns Where: nowhere for one never read. +pub def placing::made_at(&this, value: u32): loc { + return this.located(value, this.def_at[value]); +} + + +# Moves. + +#! Finds the moves: where a value's part ends and the next begins within a +#! block, where a value made in a register is stored to its slot, and along +#! each edge, into what the block it goes to holds where it begins. +#! @param this The placing. +#! @param body The code. +def placing::resolve(&mut this, body: &code): void { + # The places that begin blocks, for telling the moves along edges from those + # within blocks. + var starts := vector::::new(scratch()); + starts.resize(this.places as u64); + for k in 0..this.order.length { + starts[this.start_slots[this.order[k]] as u64] = true; + } + + # Moves within blocks, gathered as the key of the pair of the place and the + # index of each move, then put in order of place, the stores first. + var keyed := vector::::new(scratch()); + var found := vector::::new(scratch()); + val values := body.origins.length; + for v in 0..values { + val first: u32 = this.child_first[v]; + val last: u32 = this.child_first[v + 1]; + continue if first == last; + val own := in_slot(v as u32); + + # A value with a slot is stored to it where it is made, unless it is made + # there. + if this.slot_of[v] != never { + val made: loc = this.child_locs[first as u64]; + if made.kind != place::slot { + val at := this.def_at[v] / 4 + 1; + keyed.append(pair_key(at, found.length as u32)); + found.append(transfer { from = made, to = own, bytes = this.bytes[v] }); + } + } + for c in first + 1..last { + val before: u32 = c - 1; + val at: u32 = this.child_starts[c as u64]; + continue if this.child_ends[before as u64] != at || starts[(at / 4) as u64]; + val to: loc = this.child_locs[c as u64]; + val from: loc = this.child_locs[before as u64]; + continue if to.same(&own) || to.same(&from); + # Reloads come after the stores of the same gap, which are keyed first. + keyed.append(pair_key(at / 4, 0x80000000 | found.length as u32)); + found.append(transfer { from = from, to = to, bytes = this.bytes[v] }); + } + } + # Each place's moves follow one another, its stores first, then its reloads, + # each in the order they were found. + this.gap_moves.reset(this.places as u64); + for &key in keyed { + this.gap_moves.count(pair_high(key)); + } + this.gap_moves.seal(); + for reloads in 0..2u { + for &key in keyed { + continue if ((key & 0x80000000) != 0) != (reloads == 1); + this.gap_moves.put(pair_high(key), found[pair_low(key) & 0x7FFFFFFF]); + } + } + + # Moves along each edge: each parameter of the block gone to takes its + # argument, and each value live into it goes where it is there. + this.edge_first.resize(body.edges.length + 1); + for e in 0..body.edges.length { + this.edge_first[e] = this.edge_moves.length as u32; + val edge: u32 = e as u32; + val target: u32 = body.edges[e].target; + val source := body.edge_source(edge); + continue if this.number[target] == never || this.number[source] == never; + val leaves := 4 * this.end_slots[source] + 1; + val enters := 4 * this.start_slots[target]; + val params := &body.blocks[target].params; + for i in 0..params.length { + break if i >= body.edges[e].args.length; + val param: u32 = params[i]; + val to := this.located(param, enters + 3); + continue if to.kind == place::none; + val arg: u32 = body.edges[e].args[i]; + val from := this.located(arg, leaves); + continue if from.same(&to); + this.edge_moves.append(transfer { from = from, to = to, bytes = this.bytes[arg] }); + } + for &value in this.liveins.of(target) { + val to := this.located(value, enters); + val from := this.located(value, leaves); + continue if to.same(&from) || to.same(&in_slot(value)); + this.edge_moves.append(transfer { from = from, to = to, bytes = this.bytes[value] }); + } + } + this.edge_first[body.edges.length] = this.edge_moves.length as u32; +} diff --git a/native/relax.sakura b/native/relax.sakura new file mode 100644 index 00000000..7a9a3082 --- /dev/null +++ b/native/relax.sakura @@ -0,0 +1,337 @@ +#! @file relax.sakura +#! @author John Christman (sorakatadzuma@gmail.com) +#! @copyright Malunal Studios, LLC. +#! @license MIT +#! +#! Contains the shortening of a function's jumps. Selection writes every jump +#! with a 32-bit displacement, since where it goes is often not known yet. Once +#! the function's code is written, each jump within it whose target is near +#! enough becomes one of a byte's displacement, 3 bytes shorter for a `jmp` and +#! 4 for a `jcc`. Shortening one brings others nearer, and no jump moves +#! farther, so every jump is first taken to be short and those that turn out +#! too far are made long again until none is. Then the code is written again, +#! and everything that named a place within it is moved with it. +#! +#! A loop whose head ends in a jump through a table, as a machine's loop over +#! its operations does, comes back to that block from each case, and runs as +#! fast as the processor fetches it, which is slower where it lies across two +#! lines of 64 bytes: the rebuild's own machine took 15% longer so. Selection +#! writes 63 bytes of `nop`s before such a head, and once the jumps are settled +#! each is cut to what starts the head at a multiple of 64. Cutting only brings +#! jumps nearer, so none settled is too far. + +import sakura::compiler; +import binary::amd64; +module sakura::native; + + +#! A displacement written within the function, and the jump holding it. +struct fixup { + var at: u64; #! Where the displacement is in the text. + var target: u64; #! Where it goes in the text. + var before: u64; #! How many displacements end at or before its target. + var kind: u8; #! 1 for a `jmp`, 2 for a `jcc`, 3 for the padding before a loop's head, ending where a displacement would, or 0 for what is not shortened. + var short: bool; #! Whether it is shortened. + var cut: u64; #! Of padding, how many of its bytes go. +} + +#! The bytes of padding before a loop's head. +const pad_bytes: u64 = 63; + +#! The `nop`s of each length up to 11 bytes, as Intel writes them, one after +#! another, from 1 byte. +const nops: u8[66] = [ + 0x90, + 0x66, 0x90, + 0x0F, 0x1F, 0x00, + 0x0F, 0x1F, 0x40, 0x00, + 0x0F, 0x1F, 0x44, 0x00, 0x00, + 0x66, 0x0F, 0x1F, 0x44, 0x00, 0x00, + 0x0F, 0x1F, 0x80, 0x00, 0x00, 0x00, 0x00, + 0x0F, 0x1F, 0x84, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x66, 0x0F, 0x1F, 0x84, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x66, 0x2E, 0x0F, 0x1F, 0x84, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x66, 0x66, 0x2E, 0x0F, 0x1F, 0x84, 0x00, 0x00, 0x00, 0x00, 0x00, +]; + +#! Writes `nop`s of so many bytes, of 11 bytes each but the last. +#! @param into Where. +#! @param count How many bytes. +def write_nops(into: *mut u8, count: u64): void { + var left := count; + var at: u64 = 0; + while left > 0 { + val length := left > 11 ? 11 : left; + val first := length * (length - 1) / 2; + for i in 0..length { + into[at + i] = nops[first + i]; + } + at += length; + left -= length; + } +} + +#! Whether a block heads a loop and ends in a jump through a table, whose +#! padding `relax` aligns. +#! @param this The selector. +#! @param block The block. +#! @returns Whether it does. +def selector::dispatches(&this, block: u32): bool { + val last: u32 = this.body.blocks[block].last; + return false if last == 0 || this.body.insts[last].kind != op::switch; + val held: inst = this.body.insts[last]; + var low: i64 = 0; + return this.table_size(&held, &mut low) != 0 && this.p.heads_loop(block); +} + +#! Writes the padding before a loop's head, for `relax` to cut. +#! @param this The selector. +def selector::pad_head(&mut this): void { + var made: u8[63]; + write_nops((&mut made) as *mut u8, pad_bytes); + this.pads.append(this.b.text.length); + for i in 0..pad_bytes { + this.b.text.byte(made[i]); + } +} + +#! The bytes of a jump's opcode before its displacement. +#! @param kind The jump's kind. +#! @returns How many. +def opcode_bytes(kind: u8): u64 { + return kind == 2 ? 2 : 1; +} + +#! Where a place of the text moves to once the jumps shortened before it are. +#! @param ends Where every displacement ends, in order of place. +#! @param saved How many bytes the jumps before each saved, and every jump +#! after the last. +#! @param place The place. +#! @returns Where it moves to. +def moved(ends: span, saved: &vector, place: u64): u64 { + return place - saved[ends.upper_bound(&place)]; +} + +#! Works out how many bytes the jumps before each saved, as they stand. +#! @param fixes Every displacement, in order of place. +#! @param saved Where how many is written for each, and for after the last. +def count_saved(fixes: &vector, saved: &mut vector): void { + var total: u64 = 0; + for i in 0..fixes.length { + saved[i] = total; + val each: fixup = fixes[i]; + if each.kind == 3 { + total += each.cut; + } else if each.short { + total += each.kind == 2 ? 4 : 3; + } + } + saved[fixes.length] = total; +} + +#! Shortens the function's jumps whose targets are near enough, then writes its +#! code again and moves everything naming a place within it. +#! @param this The selector. +#! @param spans Where each instruction's code begins and ends, moved too. +def selector::relax(&mut this, spans: &mut vector): void { + val start := this.start; + val end := this.b.text.length; + return if end == start; + + # The last displacement written at each place, in order of place: each + # written is sorted by its place, then by when it was written. + var keys := vector::::new(scratch()); + val logged := this.b.text.fixups.length / 2; + for k in 0..logged { + val at: u64 = this.b.text.fixups[2 * k]; + if at >= start && at + 4 <= end { + keys.append(pair_key((at - start) as u32, k as u32)); + } + } + # Each padding, its displacement taken to end where it does. + for p in 0..this.pads.length { + keys.append(pair_key((this.pads[p] + pad_bytes - 4 - start) as u32, (logged + p) as u32)); + } + this.pads.clear(); + keys.sort(); + var fixes := vector::::new(scratch()); + val bytes := this.b.text.bytes.view(); + for i in 0..keys.length { + continue if i + 1 < keys.length && pair_high(keys[i + 1]) == pair_high(keys[i]); + val k := pair_low(keys[i]) as u64; + val at := start + pair_high(keys[i]); + if k >= logged { + fixes.append(fixup { at = at, kind = 3, short = true }); + continue; + } + val target: u64 = this.b.text.fixups[2 * k + 1]; + var kind: u8 = 0; + if at >= start + 1 && bytes[at - 1] == 0xE9 { + kind = 1; + } else if at >= start + 2 && bytes[at - 2] == 0x0F && (bytes[at - 1] & 0xF0) == 0x80 { + kind = 2; + } + if target < start || target > end { + kind = 0; + } + fixes.append(fixup { at = at, target = target, kind = kind, short = kind != 0 }); + } + this.b.text.fixups.clear(); + return if fixes.length == 0; + + # How many displacements end at or before a place is how many of their ends + # are not past it. + var ending := vector::::new(scratch()); + for &each in fixes { + ending.append(each.at + 4); + } + val ends := ending.view(); + for i in 0..fixes.length { + fixes[i].before = ends.upper_bound(&fixes[i].target); + } + + # Every jump is taken to be short, and those too far made long, until none + # is. + var saved := vector::::new(scratch()); + saved.resize(fixes.length + 1); + var changed := true; + while changed { + changed = false; + count_saved(&fixes, &mut saved); + for i in 0..fixes.length { + val each: fixup = fixes[i]; + continue if !each.short || each.kind == 3; + # Every displacement before this one ends before its jump begins. + val from := each.at - opcode_bytes(each.kind) - saved[i] + 2; + val distance := (each.target - saved[each.before]) as i64 - from as i64; + if distance < -128 || distance > 127 { + fixes[i].short = false; + changed = true; + } + } + } + # Each padding is cut to what starts its head at a multiple of 64, once what + # comes before it is cut. + var total: u64 = 0; + for i in 0..fixes.length { + val each: fixup = fixes[i]; + if each.kind == 3 { + val opening := each.at + 4 - pad_bytes - total; + val kept := (64 - opening % 64) % 64; + fixes[i].cut = pad_bytes - kept; + total += pad_bytes - kept; + } else if each.short { + total += each.kind == 2 ? 4 : 3; + } + } + count_saved(&fixes, &mut saved); + return if saved[fixes.length] == 0; + + # The code again, each short jump written as one, what lies between copied + # whole. + var code := vector::::new(scratch()); + code.resize(end - start - saved[fixes.length]); + val into := code.slice().data; + var from := start; + var written: u64 = 0; + for i in 0..fixes.length { + val each: fixup = fixes[i]; + continue if !each.short; + if each.kind == 3 { + val opening := each.at + 4 - pad_bytes; + memcpy(into + written, bytes.data + from, opening - from); + written += opening - from; + write_nops(into + written, pad_bytes - each.cut); + written += pad_bytes - each.cut; + from = each.at + 4; + continue; + } + val opening := each.at - opcode_bytes(each.kind); + memcpy(into + written, bytes.data + from, opening - from); + written += opening - from; + code[written] = each.kind == 1 ? 0xEB : (0x70 | (bytes[each.at - 1] & 0x0F)); + written += 2; + from = each.at + 4; + } + memcpy(into + written, bytes.data + from, end - from); + + # Each displacement, from where its jump is now to where its target is. + for i in 0..fixes.length { + val each: fixup = fixes[i]; + continue if each.kind == 3; + val target := each.target >= start && each.target <= end ? moved(ends, &saved, each.target) : each.target; + if each.short { + val opening := moved(ends, &saved, each.at - opcode_bytes(each.kind)); + code[opening - start + 1] = ((target as i64 - (opening as i64 + 2)) & 0xFF) as u8; + continue; + } + val at := moved(ends, &saved, each.at); + val relative := (target as i64 - (at as i64 + 4)) as u64; + for b in 0..4u { + code[at - start + b] = ((relative >> (8 * b)) & 0xFF) as u8; + } + } + this.b.text.bytes.rewind(start); + this.b.text.put(code.view()); + + # What named places within the code names where they moved. + for i in 0..this.labels.length { + val label: u64 = this.labels[i]; + if label >= start && label <= end { + this.labels[i] = moved(ends, &saved, label); + } + } + for i in 0..this.entries.length { + if this.entries[i].block == never { + this.entries[i].at = moved(ends, &saved, this.entries[i].at); + } + } + for i in 0..this.tables.length { + this.tables[i].patch = moved(ends, &saved, this.tables[i].patch); + } + for i in 0..this.constant_uses.length { + val use: u64 = this.constant_uses[i]; + this.constant_uses[i] = pair_key(moved(ends, &saved, pair_high(use) as u64) as u32, pair_low(use)); + } + for i in 0..this.addresses.length { + val at := moved(ends, &saved, this.addresses[i]); + val address := this.b.text.get_u64(at) - this.b.text_base; + this.b.text.set_u64(at, this.b.text_base + moved(ends, &saved, address)); + this.addresses[i] = at; + } + # The calls and the rows come in order of place, so each is moved past the + # jumps before it in one walk. + var j: u64 = 0; + for i in this.calls_first..this.b.calls.length { + val call: u64 = this.b.calls.at[i]; + while j < fixes.length && fixes[j].at + 4 <= call { + j++; + } + this.b.calls.at[i] = call - saved[j]; + } + j = 0; + for r in this.b.row_first[this.index] as u64..this.b.rows.length { + val place := start + this.b.rows[r].offset; + while j < fixes.length && fixes[j].at + 4 <= place { + j++; + } + this.b.rows[r].offset = place - saved[j] - start; + } + for i in 0..spans.length { + spans[i] = (moved(ends, &saved, start + spans[i] as u64) - start) as u32; + } + var k: u64 = 0; + while k < this.stub_spans.length { + for j in 0..2u { + this.stub_spans[k + j] = (moved(ends, &saved, start + this.stub_spans[k + j] as u64) - start) as u32; + } + k += 3; + } + if this.b.options.debug || this.b.options.windows { + this.b.debug.bodies[this.index] = (moved(ends, &saved, start + this.b.debug.bodies[this.index] as u64) - start) as u32; + this.b.debug.saved_at[this.index] = (moved(ends, &saved, start + this.b.debug.saved_at[this.index] as u64) - start) as u32; + for r in this.b.debug.return_first[this.index] as u64..this.b.debug.returns.length { + this.b.debug.returns[r] = (moved(ends, &saved, start + this.b.debug.returns[r] as u64) - start) as u32; + } + } +} diff --git a/native/reshape.sakura b/native/reshape.sakura new file mode 100644 index 00000000..e7703db8 --- /dev/null +++ b/native/reshape.sakura @@ -0,0 +1,268 @@ +#! @file reshape.sakura +#! @author John Christman (sorakatadzuma@gmail.com) +#! @copyright Malunal Studios, LLC. +#! @license MIT +#! +#! Contains the operations on lanes giving lanes of another type or size, as +#! `lanes_needs` numbers them past `lanes_convert`: converting each lane, +#! widening half a vector's lanes and narrowing two vectors' into one, taking +#! 32 bytes apart into halves and joining two halves, and gathering lanes from +#! memory. Each is worked in `xmm0` and those after it, as `lanes.sakura`'s +#! operations are, the result put where it goes from `xmm0`. + +import sakura::compiler; +import binary::amd64; +module sakura::native; + + +# The instructions, written as `binary::amd64` writes vector instructions. +# Widening integers, each the signed form and the unsigned 16 on: bytes to 16, +# 32, and 64 bits, 16 to 32 and 64, and 32 to 64. +const vec_pmovsxbw: u32 = 0x010220; +const vec_pmovsxbd: u32 = 0x010221; +const vec_pmovsxbq: u32 = 0x010222; +const vec_pmovsxwd: u32 = 0x010223; +const vec_pmovsxwq: u32 = 0x010224; +const vec_pmovsxdq: u32 = 0x010225; +const vec_movzx_from_sx: u32 = 0x10; +# Packing two registers' lanes into one of half the width, saturating. +const vec_packuswb: u32 = 0x010167; +const vec_packssdw: u32 = 0x01016B; +const vec_packusdw: u32 = 0x01022B; +# Converting: `i32` to `f32`, `f32` to `i32` toward zero, `f32` to `f64` and +# back, and `i32` to `f64`. +const vec_cvtdq2ps: u32 = 0x00015B; +const vec_cvttps2dq: u32 = 0x02015B; +const vec_cvtps2pd: u32 = 0x00015A; +const vec_cvtpd2ps: u32 = 0x01015A; +const vec_cvtdq2pd: u32 = 0x0201E6; +const vec_cvttpd2dq: u32 = 0x0101E6; +# A register's high 8 bytes into another's low, and 64-bit lanes put in an +# order across 32 bytes, AVX2's. +const vec_movhlps: u32 = 0x000112; +const vec_vpermq: u32 = 0x1010300; + +#! An operation giving lanes of another type or size, as the file says. +#! @param this The selector. +#! @param index The instruction. +#! @param held The instruction. +#! @param lane The type of lane it is given. +#! @param long Whether what it is given is 32 bytes. +def selector::reshape_lanes(&mut this, index: u32, held: &inst, lane: u32, long: bool): void { + val operation := held.aux & 0xFF; + val target := lanes_target(held.aux); + val result := held.result; + val out_long := this.body.type_of(result) == vt::v256; + if operation == lanes_low { + this.fetch_lanes(index, 0, 0, true); + } else if operation == lanes_high { + this.fetch_lanes(index, 0, 0, true); + this.b.text.vex_imm(vec_vextractf128, true, 0, 0, 0, 1); + } else if operation == lanes_join { + this.fetch_lanes(index, 0, 0, false); + this.fetch_lanes(index, 1, 1, false); + this.b.text.vex_imm(vec_vinsertf128, true, 0, 0, 1, 1); + } else if operation == lanes_widen || operation == lanes_widen_high { + this.widen_lanes(index, operation == lanes_widen_high, lane, target, long); + } else if operation == lanes_narrow { + this.narrow_lanes(index, lane, target, long); + } else if operation == lanes_gather { + this.gather_lanes(index, lane, long || out_long); + } else { + this.convert_lanes(index, lane, target, long, out_long); + } + this.put_lanes(result, 0, out_long); + this.settle_upper(index, long || out_long); +} + +# An instruction reading only its second register, as a conversion: with VEX's +# form naming no other where the code is written with VEX. +def selector::vunary(&mut this, op: u32, long: bool, x: u8, y: u8): void { + if long || this.b.text.avx { + this.b.text.vex(op, long, x as u32, 0, y as u32); + } else { + this.b.text.packed(op, x as u32, y as u32); + } +} + +# The instruction widening integer lanes of `from` bits to `into` bits, by the +# sign or not. +def widening(from: u64, into: u64, signed: bool): u32 { + val sx := from == 8 ? (into == 16 ? vec_pmovsxbw : into == 32 ? vec_pmovsxbd : vec_pmovsxbq) + : from == 16 ? (into == 32 ? vec_pmovsxwd : vec_pmovsxwq) : vec_pmovsxdq; + return signed ? sx : sx + vec_movzx_from_sx; +} + +#! Half the lanes of `xmm0` widened to twice their width into `xmm0`: of 16 +#! bytes, the first half, or the second moved down; of 32, either half, into +#! all 32. Integers keep their value by their sign, as `as` does, and `f32`s +#! become `f64`s. +#! @param this The selector. +#! @param index The instruction. +#! @param high Whether it is the second half. +#! @param lane The type of lane. +#! @param target The type of lane it gives. +#! @param long Whether it is 32 bytes. +def selector::widen_lanes(&mut this, index: u32, high: bool, lane: u32, target: u32, long: bool): void { + this.fetch_lanes(index, 0, 0, long); + if long { + if high { + this.b.text.vex_imm(vec_vextractf128, true, 0, 0, 0, 1); + } + } else if high { + this.b.text.packed(vec_movhlps, 0, 0); + } + val op := lane >= lane_f32 ? vec_cvtps2pd : widening(lane_bits(lane), lane_bits(target), lane_signed(lane)); + this.vunary(op, long, 0, 0); +} + +#! Two vectors' lanes narrowed to half their width into `xmm0`, the first's +#! first: integers packed, saturating, those of unsigned lanes held at the +#! type's greatest first, and `f64`s rounded to `f32`s. 32 bytes are packed +#! within each half, then their 8-byte quarters put back in order. +#! @param this The selector. +#! @param index The instruction. +#! @param lane The type of lane. +#! @param target The type of lane it gives. +#! @param long Whether each is 32 bytes. +def selector::narrow_lanes(&mut this, index: u32, lane: u32, target: u32, long: bool): void { + this.fetch_lanes(index, 0, 0, long); + this.fetch_lanes(index, 1, 1, long); + if lane == lane_f64 { + this.vunary(vec_cvtpd2ps, long, 0, 0); + this.vunary(vec_cvtpd2ps, long, 1, 1); + if long { + this.b.text.vex_imm(vec_vinsertf128, true, 0, 0, 1, 1); + } else { + this.b.text.packed(vec_movlhps, 0, 1); + } + return; + } + val bits := lane_bits(lane); + val signed := lane_signed(target); + if !lane_signed(lane) { + # Held at the target's greatest, which packing then keeps. + val most: u64 = bits == 16 ? (signed ? 0x007F007F007F007F : 0x00FF00FF00FF00FF) : (signed ? 0x00007FFF00007FFF : 0x0000FFFF0000FFFF); + this.splat_bits(2, most, long); + this.vop(bits == 16 ? vec_pminuw : vec_pminud, long, 0, 2); + this.vop(bits == 16 ? vec_pminuw : vec_pminud, long, 1, 2); + } + val op := bits == 16 ? (lane_signed(lane) && signed ? vec_packsswb : vec_packuswb) + : (lane_signed(lane) && signed ? vec_packssdw : vec_packusdw); + this.vop(op, long, 0, 1); + if long { + this.b.text.vex_imm(vec_vpermq, true, 0, 0, 0, 0xD8); + } +} + +#! Each lane converted to another type of as many lanes into `xmm0`, as `as` +#! converts it: integers widened as `widen_lanes` widens them, or narrowed, by +#! the low bytes of each kept, from 32 bytes to 16; `i32`s to reals by the +#! instruction, and `u32`s as their high and low 16 bits, each exact, added +#! once; smaller integers to `f32` widened to `i32` first; `f32`s and `f64`s +#! to 32-bit integers toward zero, which `simd`'s `convert` gives only lanes +#! within `i32`'s range, where the instruction is exact, and an unsigned one +#! held at 0 below zero; and `f32`s to `f64`s and back. +#! @param this The selector. +#! @param index The instruction. +#! @param lane The type of lane. +#! @param target The type of lane it gives. +#! @param long Whether what it is given is 32 bytes. +#! @param out_long Whether what it gives is 32 bytes. +def selector::convert_lanes(&mut this, index: u32, lane: u32, target: u32, long: bool, out_long: bool): void { + val bits := lane_bits(lane); + val into := lane_bits(target); + val real := lane >= lane_f32; + val into_real := target >= lane_f32; + this.fetch_lanes(index, 0, 0, long); + if !real && !into_real { + if into > bits { + this.vunary(widening(bits, into, lane_signed(lane)), out_long, 0, 0); + } else if into < bits { + # Each lane's low bytes, of each half, into that half's low 8 bytes, then + # the halves' together. + var low: u8[32]; + val width := bits / 8; + val kept := into / 8; + for i in 0..32u { + val at := i % 16; + low[i] = at < 16 / width * kept ? ((at / kept) * width + at % kept) as u8 : 0x80; + } + this.b.text.vex_imm(vec_vextracti128, true, 0, 0, 1, 1); + this.load_bytes(2, low, false); + this.b.text.vex(vec_pshufb, false, 0, 0, 2); + this.b.text.vex(vec_pshufb, false, 1, 1, 2); + this.b.text.vex(vec_punpcklqdq, false, 0, 0, 1); + } + return; + } + if !real && into_real { + if target == lane_f64 { + this.vunary(vec_cvtdq2pd, true, 0, 0); + return; + } + if bits < 32 { + this.vunary(widening(bits, 32, lane_signed(lane)), out_long, 0, 0); + } + if lane == lane_u32 { + # The high 16 bits times 2^16, and the low 16, each exact, added once. + this.vmove(out_long, 1, 0); + this.shift_by(vec_psrld, out_long, 1, 16); + this.splat_bits(2, 0x0000FFFF0000FFFF, out_long); + this.vop(vec_pand, out_long, 0, 2); + this.vunary(vec_cvtdq2ps, out_long, 0, 0); + this.vunary(vec_cvtdq2ps, out_long, 1, 1); + this.splat_bits(2, 0x4780000047800000, out_long); + this.vop(vec_mulps, out_long, 1, 2); + this.vop(vec_addps, out_long, 0, 1); + return; + } + this.vunary(vec_cvtdq2ps, out_long, 0, 0); + return; + } + if real && !into_real { + if lane == lane_f32 { + this.vunary(vec_cvttps2dq, long, 0, 0); + } else { + this.b.text.vex(vec_cvttpd2dq, true, 0, 0, 0); + } + # An unsigned integer holds what is below zero at 0, as `as` does. + if !lane_signed(target) { + this.vop(vec_pcmpeqd, out_long, 1, 1); + this.vmove(out_long, 2, 0); + this.vop(vec_pcmpgtd, out_long, 2, 1); + this.vop(vec_pand, out_long, 0, 2); + } + return; + } + if lane == lane_f32 { + this.vunary(vec_cvtps2pd, true, 0, 0); + } else { + this.b.text.vex(vec_cvtpd2ps, true, 0, 0, 0); + } +} + +#! Lanes gathered from memory into `xmm0`, by AVX2's `vpgatherdd` and the rest: +#! the address in `rax`, the 32-bit places in `xmm1`, and a mask of every lane +#! in `xmm2`, which the instruction clears as it goes. `simd`'s `gather` checks +#! each place is within the view first. +#! @param this The selector. +#! @param index The instruction. +#! @param lane The type of lane. +#! @param long Whether the lanes gathered are 32 bytes. +def selector::gather_lanes(&mut this, index: u32, lane: u32, long: bool): void { + val bits := lane_bits(lane); + this.load_into(this.body.arg(index, 0), index, reg::rax); + this.fetch_lanes(index, 1, 1, bits == 32 && long); + this.b.text.vex(vec_pcmpeqd, long, 2, 2, 2); + this.b.text.vex(vec_pxor, long, 0, 0, 0); + # VEX's three bytes, of the map `0F 38`, the prefix `66`, `W` for 64-bit + # lanes, and `xmm2` the mask; then the opcode, `ModRM` naming a `SIB`, and the + # `SIB` of the lanes' scale, `xmm1` the index, and `rax` the base. + this.b.text.byte(0xC4); + this.b.text.byte(0xE2); + this.b.text.byte(((bits == 64 ? 0x80 : 0) | ((~2u & 15) << 3) | (long ? 4 : 0) | 1) as u8); + this.b.text.byte(lane >= lane_f32 ? 0x92 : 0x90); + this.b.text.byte(0x04); + this.b.text.byte(((bits == 64 ? 3 : 2) << 6 | 1 << 3) as u8); +} diff --git a/native/select.sakura b/native/select.sakura new file mode 100644 index 00000000..c5dff699 --- /dev/null +++ b/native/select.sakura @@ -0,0 +1,759 @@ +#! @file select.sakura +#! @author John Christman (sorakatadzuma@gmail.com) +#! @copyright Malunal Studios, LLC. +#! @license MIT +#! +#! Contains the selection of instructions: the x86-64 code of a function, made +#! from its intermediate code and where the register allocator put each value. +#! Each operation is written as a few instructions over the registers and +#! slots its operands are in, computing in `rax`, `rcx`, and `rdx`, and `xmm0` +#! and `xmm1`, which hold no value between instructions. Constants and the +#! addresses the code knows become immediates and addressing modes, and a +#! comparison only a branch reads is the branch's own test. +#! +#! A function's frame is on the stack, below the caller's frame pointer and +#! return address: the registers a call keeps that it saved, the address its +#! memory result goes to, the values' slots, words the runtime's helpers write, +#! where it calls anything, the copies of the parameters it takes in memory, +#! its cells, and the arguments it passes on the stack. Where a check +#! fails, the code jumps to a stub after the function's body, which calls the +#! trap stub with the error, so the check costs a compare and a jump never +#! taken. + +import sakura::compiler; +import binary::amd64; +module sakura::native; + + +#! A check's failure, written after the function's body. +struct trap_site { + var patch: u64; #! The jump to it. + var code: u32; #! The error it stops the program with. + var at: u64; #! Where in the source the check is. + var site: u32; #! The inline site the check is in. + var index: u32; #! The instruction checking. +} + +#! A safe point's call of the function running the handlers, written after +#! the function's body, where a signal the program handles came. +struct safe_site { + var patch: u64; #! The jump to it. + var back: u64; #! Where the code goes on. + var at: u64; #! Where in the source the safe point is. + var site: u32; #! The inline site it is in. + var index: u32; #! The safe point. +} + +#! An entry of a switch's table: where a case goes, a block or code leading to +#! one. +struct table_entry { + var block: u32; #! The block, or `never` where it is code. + var at: u64; #! Where the code is in the text. +} + +#! A switch's table of addresses, written after the function's body. +struct switch_table { + var patch: u64; #! Where the jump through it holds its address. + var first: u32; #! Its first entry in `entries`. + var count: u32; #! How many entries it has. +} + +#! A word operand: a register, memory, or an immediate. +struct operand_of { + var kind: u8; #! 0 for a register, 1 for memory, 2 for an immediate. + var r: reg; + var m: mem; + var imm: i32; +} + +#! What selecting the code of one function keeps, which makes the moves between +#! the places of its values. +pub struct selector : move_maker { + var b: &mut building; #! The executable being built. + var body: &code; #! The function's code. + var p: placing; #! Where its values are. + var index: u32; #! The function. + var start: u64; #! Where its code begins in the text. + + # The frame, as offsets below the frame pointer. + var frame: u64; #! The bytes of the frame below the frame pointer. + var dst_at: u64; #! Of the address a result held in memory is written to. + var slot_base: u64; #! Of the slots: slot `k` is at `slot_base + 8 * k + 8`, and a vector's of `n` words at that of its last. + var scratch_at: u64; #! Of three words the runtime's helpers write. + var cells: vector; #! Of each cell. + var copies: vector; #! Of the copy of each parameter of the entry held in memory, or 0. + var zero_from: u64; #! The cells zeroed as the function begins, from this offset + var zero_to: u64; #! up to this one. + var out_words: u64; #! How many words the calls it makes pass on the stack. + + var labels: vector; #! Where each block begins in the text. + var jumps: fixup_list; #! The jumps to blocks, and the block each goes to, to patch once every block is placed. + var traps: vector; + var safe_points: vector; + var tables: vector; + var entries: vector; #! The entries of every table, one table's after another's. + var addresses: vector; #! Where the code holds an address within itself, as a word. + var calls_first: u64; #! The first of the building's calls the function makes. + var stub_spans: vector; #! Of each stub written after the body, where its code begins and ends within the function's, then the instruction it is of. + var pads: vector; #! Where the padding before each loop's head that `relax` aligns begins. + var constants: vector; #! The vectors of constant lanes the code loads, 32 bytes each, written after its tables. + var constant_uses: vector; #! Where the code holds the address of each it loads, and which, by `pair_key(place, constant)`. + var last_at: u64; + var last_site: u32; + var returned: u64; #! The bytes of the memory it returns, or 0. + var leaf: bool; #! Whether it calls nothing. + var saved: reg[5]; #! The registers a call keeps that it saves below the frame pointer, in order, from the highest. + var save_count: u64; #! How many. + var aligned: bool; #! Whether its frame keeps `rsp` a multiple of 16, as calls, safe points, and taking signals need. + var tails: bool; #! Whether a call a return comes straight after may be a jump, made once the frame is left: in code optimized with inlining, where no pointer into the frame is kept where the code cannot follow it. + var framed: vector; #! Where tail calls may be made, whether each value may point into the frame. + var tailed: u32; #! The return a call before it took the place of, jumping, or 0. + var upper_parts: vector; #! Where registers hold 32 bytes of lanes, each its start and end as a pair's key, in code that may run without AVX. + var uses_upper: bool; #! Whether that code works on 32 bytes of lanes at all. + var single: vector; #! Whether each value is a real held as an `f32`, in its low four bytes, as `singles.sakura` says. + var works: vector; #! Whether each instruction works an arithmetic of `f32`s in single precision. +} + + +# Frames. + +#! Finds the registers a call keeps that the function holds values in, which +#! it saves as it begins and gives back as it returns. One reading `frame` +#! saves every one of them, so what its callers hold in them is in its frame, +#! where a reader of the stack from there up finds it. Finds too +#! whether its frame keeps `rsp` a multiple of 16: where it calls anything, as +#! C needs, or makes a safe point or takes signals, which call what does. +#! @param this The selector. +def selector::find_saved(&mut this): void { + var used: u64 = 0; + for &each in this.p.child_locs { + if each.kind == place::gpr && keeps(each.number) { + used = used | (1u << each.number as u64); + } + } + this.aligned = !this.leaf; + for k in 0..this.p.order.length { + var walk := this.body.walk(this.p.order[k]); + while walk.more() { + val kind: op = this.body.insts[walk.next()].kind; + if kind == op::frame { + used = 0xFFFF; + } + if kind == op::safepoint || kind == op::signals { + this.aligned = true; + } + } + } + for &r in kept_gprs { + if (used & (1u << r as u64)) != 0 { + this.saved[this.save_count] = r; + this.save_count++; + } + } +} + +#! The registers a function saves, one bit each by number. +#! @param this The selector. +#! @returns The bits. +def selector::saved_mask(&this): u32 { + var mask: u64 = 0; + for k in 0..this.save_count { + mask = mask | (1u << this.saved[k] as u64); + } + return mask as u32; +} + +#! Lays out the frame of the function. The scratch the runtime's helpers write +#! is only that of one calling anything. +#! @param this The selector. +#! @param memory Whether each parameter of the entry is held in memory. +#! @param sizes The bytes of each one held in memory. +def selector::lay_frame(&mut this, memory: span, sizes: span): void { + var below: u64 = 8 * this.save_count; + if this.returned != 0 { + below += 8; + this.dst_at = below; + } + this.slot_base = below; + below += 8 * this.p.slot_count as u64; + if !this.leaf { + below += 24; + } + this.scratch_at = below; + + this.copies.resize(memory.length); + for i in 0..memory.length { + continue if !memory[i]; + below = round_up(below + round_up(sizes[i], 8), 16); + this.copies[i] = below; + } + + # The cells the frame zeroes come together, then those it need not: those + # of functions inlined, whose code clears them, and those every read of + # which some write comes before. + val writes := this.b.c.result_writes(this.index); + val zeroed := zeroed_cells(this.body, this.p.order.view(), this.p.number.view(), writes.view()); + this.cells.resize(this.body.cells.length); + below = round_up(below, 8); + this.zero_from = below; + for pass in 0..2u { + for i in 0..this.body.cells.length { + val each: cell = this.body.cells[i]; + val zeroes := each.kind != ck::inlined && each.kind != ck::undefined && zeroed[i]; + continue if zeroes != (pass == 0); + val align := each.align < 8 ? 8 : (each.align > 16 ? 16 : each.align as u64); + below = round_up(below + round_up(each.size as u64, 8), align); + this.cells[i] = below; + } + if pass == 0 { + this.zero_to = below; + } + } + + # The arguments passed on the stack are at its bottom. + this.frame = round_up(below + 8 * this.out_words, this.aligned ? 16 : 8); +} + +#! The memory of a value's slot: the words it takes, from the lowest. +#! @param this The selector. +#! @param value The value. +#! @returns The memory. +def selector::slot(&this, value: u32): mem { + val k := this.p.slot_of[value] as u64 + (this.p.bytes[value] / 8) as u64 - 1; + return at(reg::rbp, -((this.slot_base + 8 * k + 8) as i64) as i32); +} + +#! The memory of a word the scratch of the frame holds. +#! @param this The selector. +#! @param k The word: 0, 1, or 2. +#! @returns The memory. +def selector::scratch_word(&this, k: u64): mem { + return at(reg::rbp, (8 * k as i64 - this.scratch_at as i64) as i32); +} + +#! The memory of a place a move reads or writes that is no register. +#! @param this The selector. +#! @param held The place. +#! @returns The memory. +def selector::memory_of(&this, held: &loc): mem { + if held.kind == place::slot { + return this.slot(held.value); + } + if held.kind == place::out { + return at(reg::rsp, (8 * held.value as u64) as i32); + } + # A word the function was called with past those in registers, above the + # return address and the caller's frame pointer. + return at(reg::rbp, (16 + 8 * (held.value as u64 - arg_count)) as i32); +} + + +# Values made again. + +#! The address a value made again is, where it is known while compiling: of the +#! globals, a datum, or the image. +#! @param this The selector. +#! @param value The value. +#! @param address Where the address is written. +#! @returns Whether it is known. +def selector::known_address(&this, value: u32, address: &mut u64): bool { + val made := this.body.defining(value); + return false if made == 0; + val held: inst = this.body.insts[made]; + if held.kind == op::global { + address = this.b.globals + held.imm; + return true; + } + if held.kind == op::datum { + address = this.b.datum_address(held.aux) + held.imm; + return true; + } + if held.kind == op::image { + address = this.b.image_address; + return true; + } + return false; +} + +#! Where in the frame a value made again points, where it is an address of the +#! frame: a cell, or the copy of a parameter held in memory. +#! @param this The selector. +#! @param value The value. +#! @param offset Where the offset below the frame pointer is written. +#! @returns Whether it is. +def selector::frame_address(&this, value: u32, offset: &mut u64): bool { + if this.p.memory_params[value] { + offset = this.copies[this.body.origins[value].index]; + return true; + } + val made := this.body.defining(value); + return false if made == 0; + val held: inst = this.body.insts[made]; + return false if held.kind != op::cell; + offset = this.cells[held.aux]; + return true; +} + +#! The bits of a value made again that is a constant. +#! @param this The selector. +#! @param value The value. +#! @param bits Where the bits are written. +#! @returns Whether it is a constant. +def selector::constant_bits(&this, value: u32, bits: &mut u64): bool { + val made := this.body.defining(value); + return false if made == 0 || this.p.memory_params[value]; + val held: inst = this.body.insts[made]; + return false if held.kind != op::iconst && held.kind != op::fconst; + bits = held.imm; + return true; +} + +#! Makes a value made again in a general register. +#! @param this The selector. +#! @param value The value. +#! @param into The register. +def selector::remake(&mut this, value: u32, into: reg): void { + var offset: u64 = 0; + if this.frame_address(value, &mut offset) { + this.b.text.lea(into, at(reg::rbp, -(offset as i64) as i32)); + return; + } + var address: u64 = 0; + if this.known_address(value, &mut address) { + this.b.text.mov_imm(into, address); + return; + } + val held: inst = this.body.insts[this.body.defining(value)]; + match held.kind { + op::iconst, op::fconst => this.b.text.mov_imm(into, held.imm); + op::callback => this.b.text.load(8, false, into, absolute(this.b.callback_word(held.aux))); + op::c_address => this.b.text.load(8, false, into, absolute(this.b.got_word(held.aux))); + op::frame => this.b.text.mov(into, reg::rsp); + else => this.b.text.mov_imm(into, 0); + } +} + + +# Moves. + +#! Makes a move: from a register, a slot, the stack, or a value made again, to +#! a register, a slot, or the stack. `rcx` carries a word between memory, and +#! `xmm0` a vector. +#! @param this The selector. +#! @param made The move. +pub def selector::move_one(&mut this, made: &transfer): void { + val from := made.from; + val to := made.to; + return if to.kind == place::none || from.same(&to); + if made.bytes == 64 { + this.move_wide(this.memory_of(&from), this.memory_of(&to)); + return; + } + if made.bytes > 8 { + this.move_lanes(from, to, made.bytes == 32); + return; + } + if to.kind == place::gpr { + val r := to.number as reg; + match from.kind { + place::gpr => this.b.text.mov(r, from.number as reg); + place::xmm => this.b.text.movq_from_xmm(r, from.number); + place::remade => this.remake(from.value, r); + else => this.b.text.load(8, false, r, this.memory_of(&from)); + } + return; + } + if to.kind == place::xmm { + match from.kind { + place::xmm => this.b.text.movaps(to.number, from.number); + place::gpr => this.b.text.movq_to_xmm(to.number, from.number as reg); + place::remade => { + this.remake(from.value, reg::rcx); + this.b.text.movq_to_xmm(to.number, reg::rcx); + } + else => this.b.text.movsd_load(to.number, this.memory_of(&from)); + } + return; + } + + # To memory. + val dst := this.memory_of(&to); + match from.kind { + place::gpr => this.b.text.store(8, dst, from.number as reg); + place::xmm => this.b.text.movsd_store(dst, from.number); + place::remade => { + var bits: u64 = 0; + if this.constant_bits(from.value, &mut bits) && fits_i32(bits) { + this.b.text.store_imm(dst, bits as i32); + return; + } + this.remake(from.value, reg::rcx); + this.b.text.store(8, dst, reg::rcx); + } + else => { + this.b.text.load(8, false, reg::rcx, this.memory_of(&from)); + this.b.text.store(8, dst, reg::rcx); + } + } +} + +#! Makes moves all at once: each place written is read first by any move +#! reading it, and a cycle saves one place in `rax`, or in `xmm0` for an SSE +#! register, before writing it. Each move made gives its place among those +#! waiting to the last. +#! @param this The selector. +#! @param given The moves, whose places written all differ. +def selector::parallel(&mut this, given: span): void { + var pending := vector::::new(scratch()); + for &each in given { + continue if each.to.kind == place::none || each.from.same(&each.to); + pending.append(each); + } + make_moves::(&mut pending, this, true); +} + +#! Whether a move reads the place another writes. +#! @param this The selector. +#! @param reader The move that may read it. +#! @param writer The move writing it. +#! @returns Whether it does. +pub def selector::move_reads(&this, reader: &transfer, writer: &transfer): bool { + return reader.from.same(&writer.to); +} + +#! The move saving what a move would write over, which a cycle of moves still +#! reads, in `rax`, or in `xmm0` for an SSE register. +#! @param this The selector. +#! @param written The move. +#! @param pending The moves waiting, among them those reading the place. +#! @returns The move saving it. +pub def selector::move_saving(&mut this, written: &transfer, pending: span): transfer { + # It holds the value a move reading it moves, which is as wide as that is. + val saved: loc = written.to; + var bytes: u8 = 8; + for &each in pending { + if each.from.same(&saved) { + bytes = each.bytes; + break; + } + } + val keep := saved.kind == place::xmm ? in_xmm(0) : in_gpr(reg::rax); + return transfer { from = saved, to = keep, bytes = bytes }; +} + +#! Has a move read what another saved from where it was saved. +#! @param this The selector. +#! @param reader The move. +#! @param saved The move saving what it reads. +pub def selector::move_reread(&this, reader: &mut transfer, saved: &transfer): void { + reader.from = saved.to; +} + +#! Makes the moves of the gap before a place. +#! @param this The selector. +#! @param at The place. +def selector::gap(&mut this, at: u32): void { + val moves := this.p.gap_moves.of(at); + return if moves.length == 0; + this.parallel(moves); +} + +#! Makes the moves along an edge. +#! @param this The selector. +#! @param edge The edge. +def selector::edge(&mut this, edge: u32): void { + val moves := this.p.edge_moves_of(edge); + return if moves.length == 0; + this.parallel(moves); +} + +#! Whether an edge moves anything. +#! @param this The selector. +#! @param edge The edge. +#! @returns Whether it does. +def selector::moves_on(&this, edge: u32): bool { + return this.p.edge_first[edge as u64] != this.p.edge_first[edge as u64 + 1]; +} + + +# Operands. + +#! Where a value is read by an instruction. +#! @param this The selector. +#! @param value The value. +#! @param index The instruction reading it. +#! @returns Where. +def selector::read(&this, value: u32, index: u32): loc { + return this.p.read_at(value, index); +} + +#! A general register holding a word an instruction reads: its own, or the +#! scratch register given, loaded with it. +#! @param this The selector. +#! @param value The value. +#! @param index The instruction reading it. +#! @param scratch The register it is loaded into where it is in none. +#! @returns The register. +def selector::word_reg(&mut this, value: u32, index: u32, scratch: reg): reg { + val held := this.read(value, index); + match held.kind { + place::gpr => return held.number as reg; + place::xmm => this.b.text.movq_from_xmm(scratch, held.number); + place::remade => this.remake(value, scratch); + place::none => this.b.text.mov_imm(scratch, 0); + else => this.b.text.load(8, false, scratch, this.memory_of(&held)); + } + return scratch; +} + +#! An SSE register holding a real an instruction reads: its own, or the +#! scratch register given, loaded with it. +#! @param this The selector. +#! @param value The value. +#! @param index The instruction reading it. +#! @param scratch The register it is loaded into where it is in none. +#! @returns The register's number. +def selector::real_reg(&mut this, value: u32, index: u32, scratch: u8): u8 { + val held := this.read(value, index); + return this.widened(&held, scratch) if this.single[value]; + match held.kind { + place::xmm => return held.number; + place::gpr => this.b.text.movq_to_xmm(scratch, held.number as reg); + place::remade => { + this.remake(value, reg::rdx); + this.b.text.movq_to_xmm(scratch, reg::rdx); + } + place::none => { + this.b.text.mov_imm(reg::rdx, 0); + this.b.text.movq_to_xmm(scratch, reg::rdx); + } + else => this.b.text.movsd_load(scratch, this.memory_of(&held)); + } + return scratch; +} + +#! A word an instruction reads as an operand of arithmetic: an immediate where +#! it is a constant a 32-bit immediate holds, memory where it is in its slot, +#! and a register otherwise. +#! @param this The selector. +#! @param value The value. +#! @param index The instruction reading it. +#! @param scratch The register it is loaded into where it is in none. +#! @returns The operand. +def selector::word_operand(&mut this, value: u32, index: u32, scratch: reg): operand_of { + var imm: i32 = 0; + if this.immediate(value, &mut imm) { + return operand_of { kind = 2, imm = imm }; + } + if this.read(value, index).kind == place::slot { + return operand_of { kind = 1, m = this.slot(value) }; + } + return operand_of { kind = 0, r = this.word_reg(value, index, scratch) }; +} + +#! Whether a word an instruction reads is a constant a 32-bit immediate holds. +#! @param this The selector. +#! @param value The value. +#! @param imm Where the constant is written. +#! @returns Whether it is. +def selector::immediate(&this, value: u32, imm: &mut i32): bool { + return false if !this.p.remade[value]; + var bits: u64 = 0; + return false if !this.constant_bits(value, &mut bits) && !this.known_address(value, &mut bits); + return false if !fits_i32(bits); + imm = bits as i32; + return true; +} + +#! The general register a word result is computed into: its own, or the +#! fallback where it goes to its slot or nowhere. +#! @param this The selector. +#! @param value The result. +#! @param fallback The register otherwise. +#! @returns The register. +def selector::target(&this, value: u32, fallback: reg): reg { + val held := this.p.made_at(value); + return held.kind == place::gpr ? held.number as reg : fallback; +} + +#! Puts a word result computed in a register where it goes. +#! @param this The selector. +#! @param value The result. +#! @param r The register. +def selector::put(&mut this, value: u32, r: reg): void { + val held := this.p.made_at(value); + match held.kind { + place::gpr => { + if held.number as reg != r { + this.b.text.mov(held.number as reg, r); + } + } + place::xmm => this.b.text.movq_to_xmm(held.number, r); + place::slot => this.b.text.store(8, this.slot(value), r); + else => {} + } +} + +#! The SSE register a real result is computed into: its own, or `xmm0`. +#! @param this The selector. +#! @param value The result. +#! @returns The register's number. +def selector::real_target(&this, value: u32): u8 { + val held := this.p.made_at(value); + return held.kind == place::xmm ? held.number : 0; +} + +#! Puts a real result computed in an SSE register where it goes. +#! @param this The selector. +#! @param value The result. +#! @param x The register. +def selector::put_real(&mut this, value: u32, x: u8): void { + val held := this.p.made_at(value); + match held.kind { + place::xmm => { + if held.number != x { + this.b.text.movaps(held.number, x); + } + } + place::gpr => this.b.text.movq_from_xmm(held.number as reg, x); + place::slot => this.b.text.movsd_store(this.slot(value), x); + else => {} + } +} + +#! Whether a result goes anywhere, so it is worth computing. +#! @param this The selector. +#! @param value The result. +#! @returns Whether it does. +def selector::wanted(&this, value: u32): bool { + return this.p.made_at(value).kind != place::none; +} + +#! The memory an address an instruction reads points at, from an offset: +#! addressing the frame or the image directly where the address is one of +#! theirs, through the base and index a sum folded into it is made of, and +#! otherwise through a register holding it. +#! @param this The selector. +#! @param value The address. +#! @param index The instruction reading it. +#! @param offset The bytes from the address. +#! @param scratch The register it is loaded into where it is in none. +#! @param second The register the index of a sum folded into it is loaded +#! into where it is in none. +#! @param direct Where whether it points into the frame or the image is +#! written, which is never null. +#! @returns The memory. +def selector::address(&mut this, value: u32, index: u32, offset: u64, scratch: reg, second: reg, direct: &mut bool): mem { + direct = false; + val made := this.body.defining(value); + if made != 0 && this.p.folded[made] && this.body.insts[made].kind == op::add { + return this.sum_address(made, index, offset, scratch, second, direct); + } + if this.p.remade[value] { + var below: u64 = 0; + if this.frame_address(value, &mut below) { + direct = true; + return at(reg::rbp, (offset as i64 - below as i64) as i32); + } + var known: u64 = 0; + if this.known_address(value, &mut known) { + direct = true; + return absolute(known + offset); + } + } + return at(this.word_reg(value, index, scratch), offset as i32); +} + +#! The base, index, and scale of a sum: the word a shift folded into it scales +#! as its index, or else the operand held rather than made again, the other +#! its base. +#! @param this The selector. +#! @param sum The sum. +#! @param base Where its base is written. +#! @param scale Where its index's scale is written. +#! @returns Its index. +def selector::sum_parts(&this, sum: u32, base: &mut u32, scale: &mut u8): u32 { + val a := this.body.arg(sum, 0); + val b := this.body.arg(sum, 1); + scale = 1; + for k in 0..2u { + val operand := k == 0 ? a : b; + val made := this.body.defining(operand); + continue if made == 0 || !this.p.folded[made] || this.body.insts[made].kind != op::shl; + base = k == 0 ? b : a; + scale = (1u << this.body.insts[this.body.defining(this.body.arg(made, 1))].imm) as u8; + return this.body.arg(made, 0); + } + if this.p.remade[b] { + base = b; + return a; + } + base = a; + return b; +} + +#! The memory a sum folded into the instruction reading it points at, from an +#! offset: its base and its index scaled, the base the frame's or the image's +#! own where it is an address of theirs. +#! @param this The selector. +#! @param sum The sum. +#! @param index The instruction reading it. +#! @param offset The bytes from the address. +#! @param scratch The register the base is loaded into where it is in none. +#! @param second The register the index is loaded into where it is in none. +#! @param direct Where whether it points into the frame or the image is +#! written. +#! @returns The memory. +def selector::sum_address(&mut this, sum: u32, index: u32, offset: u64, scratch: reg, second: reg, direct: &mut bool): mem { + var base: u32 = 0; + var scale: u8 = 1; + val scaled := this.sum_parts(sum, &mut base, &mut scale); + val by := this.word_reg(scaled, index, second); + if this.p.remade[base] { + var below: u64 = 0; + if this.frame_address(base, &mut below) { + direct = true; + return indexed(reg::rbp, by, scale, (offset as i64 - below as i64) as i32); + } + var known: u64 = 0; + if this.known_address(base, &mut known) { + direct = true; + return indexed(reg::none, by, scale, (known + offset) as i32); + } + } + return indexed(this.word_reg(base, index, scratch), by, scale, offset as i32); +} + +#! Stops the program with an error where a condition holds, jumping to a stub +#! after the function's body that reports it. +#! @param this The selector. +#! @param condition The condition. +#! @param code The error. +#! @param index The instruction checking, whose place the report names. +def selector::trap_if(&mut this, condition: cc, code: u32, index: u32): void { + val held: inst = this.body.insts[index]; + this.traps.append(trap_site { patch = this.b.text.jcc(condition), code = code, at = held.at, site = held.site, index = index }); +} + +#! Stops the program with an error where a register holding an address is +#! null, where reading at the offset would not fault on its own and the program +#! checks. +#! @param this The selector. +#! @param base The register. +#! @param reach How far past the address the access reaches. +#! @param index The instruction. +def selector::null_check(&mut this, base: reg, reach: u64, index: u32): void { + return if reach <= null_page || !this.checking(); + this.b.text.test(base, base); + this.trap_if(cc::equal, fault::null_reference as u32, index); +} + +#! Whether the program checks what only a checked build does, as `--checks` +#! asks: here, an address reached far past null, a function value's index, and +#! a trait's vtable, each compared with what it may be. +#! @param this The selector. +#! @returns Whether it does. +def selector::checking(&this): bool { + return !this.b.c.checker.checks_off; +} + diff --git a/native/singles.sakura b/native/singles.sakura new file mode 100644 index 00000000..fde02831 --- /dev/null +++ b/native/singles.sakura @@ -0,0 +1,392 @@ +#! @file singles.sakura +#! @author John Christman (sorakatadzuma@gmail.com) +#! @copyright Malunal Studios, LLC. +#! @license MIT +#! +#! Contains which `f32`s an executable works in single precision. The code +#! holds every real as an `f64`, and an `f32`'s arithmetic as the `f64`'s, +#! rounded to an `f32` where it is read: `fsingle`, or a store of four bytes. +#! `addss`, `subss`, `mulss`, `divss`, and `sqrtss` of `f32`s round exactly as +#! the `f64`'s, rounded again, do, since an `f64` holds more than twice an +#! `f32`'s bits, so the code gives the same bits worked either way. Worked in +#! single precision, it is one instruction for three, and the conversions +#! around each leave every chain of them. +#! +#! An operation is worked so where its operands are `f32`s exactly, and every +#! reader rounds what it gives. A value is held as an `f32`, its low four bytes, +#! where it is one, and every reader takes it so: those, comparisons, and the +#! edges giving it to a block whose parameter is held so too. Any other reader +#! reads it widened, as `real_reg` gives it; a splat of `f32` lanes takes it +#! as it is. What is held so is the same with debugging information as +#! without, which describes a variable as an `f32` where most of its values are +#! held so, and as the `f64` they are held as otherwise, leaving out where it is +#! held the other way. + +import sakura::compiler; +import binary::amd64; +module sakura::native; + + +# The instructions of `f32`s, written as the vector instructions are, with the +# prefix `F3`. +const ss_add: u32 = 0x020158; +const ss_sub: u32 = 0x02015C; +const ss_mul: u32 = 0x020159; +const ss_div: u32 = 0x02015E; +const ss_sqrt: u32 = 0x020151; + +#! Works out which operations are worked in single precision, and which values +#! are held as `f32`s, as the file says. +#! @param this The selector. +def selector::find_singles(&mut this): void { + val values := this.body.origins.length; + this.single.resize(values, false); + this.works.resize(this.body.insts.length, false); + + # Of each real, whether every reader takes it as an `f32`, and whether every + # reader rounds it to one, which passing it on does not. + var handled := vector::::new(scratch()); + var rounded := vector::::new(scratch()); + handled.resize(values, true); + rounded.resize(values, true); + var any := false; + for k in 0..this.p.order.length { + var walk := this.body.walk(this.p.order[k]); + while walk.more() { + val at := walk.next(); + val held: inst = this.body.insts[at]; + for a in 0..held.argc { + val value := this.body.arg(at, a); + continue if this.body.type_of(value) != vt::real; + # A splat or a pack of `f32` lanes rounds what it reads to an `f32`, as a + # store of one does. + val splats := held.kind == op::lanes && (held.aux == lanes_splat || held.aux == lanes_pack) && (held.imm & 0xFF) as u32 == lane_f32; + val rounds := held.kind == op::fsingle || (held.kind == op::store && held.aux as access == access::f32 && a == 1) || splats; + val alone := held.kind == op::lanes && (held.imm >> 8) == 4; + any = any || rounds || alone; + if !rounds { + rounded[value] = false; + } + if !rounds && !splats && !alone && !takes_single(held.kind) { + handled[value] = false; + } + } + for e in 0..this.body.edge_count(at) { + for &value in this.body.edges[held.aux + e as u32].args { + rounded[value] = false; + } + } + } + } + return if !any; + + # Which reals are `f32`s exactly: what is read or rounded as one, an + # operation worked as one, a constant one is, and a block's parameter every + # edge gives one, which each is taken to be until an edge gives another. The + # function's own parameters are passed widened, whichever they are. + var exact := vector::::new(scratch()); + exact.resize(values, false); + for k in 0..this.p.order.length { + val block: u32 = this.p.order[k]; + continue if block == 0; + for ¶m in this.body.blocks[block].params { + exact[param] = this.body.type_of(param) == vt::real; + } + } + var changed := true; + while changed { + changed = false; + for k in 0..this.p.order.length { + var walk := this.body.walk(this.p.order[k]); + while walk.more() { + val at := walk.next(); + val held: inst = this.body.insts[at]; + continue if held.count == 0 || this.body.type_of(held.result) != vt::real; + val result := held.result; + var one := false; + match held.kind { + op::load => one = held.aux as access == access::f32; + op::fsingle => one = true; + op::fconst => one = single_constant(held.imm); + op::fadd, op::fsub, op::fmul, op::fdiv => { + one = rounded[result] && exact[this.body.arg(at, 0)] && exact[this.body.arg(at, 1)]; + } + op::fsqrt => one = rounded[result] && exact[this.body.arg(at, 0)]; + # One `f32` lane alone, or `f32` lanes added or multiplied together, + # worked as `f32`s. + op::lanes => { + one = (held.imm >> 8) == 4 + || ((held.imm & 0xFF) as u32 == lane_f32 && (held.aux == lanes_sum || held.aux == lanes_product)); + } + else => {} + } + exact[result] = one; + this.works[at] = one && held.kind != op::load && held.kind != op::fsingle && held.kind != op::fconst; + } + } + for k in 0..this.p.order.length { + val block: u32 = this.p.order[k]; + val last: u32 = this.body.blocks[block].last; + continue if last == 0; + val ending: inst = this.body.insts[last]; + for e in 0..this.body.edge_count(last) { + val edge := ending.aux + e as u32; + val params := &this.body.blocks[this.body.edges[edge].target].params; + val args := &this.body.edges[edge].args; + for i in 0..args.length { + val param: u32 = params[i]; + if exact[param] && !exact[args[i] as u64] { + exact[param] = false; + changed = true; + } + } + } + } + } + + # Which are held as `f32`s: those every reader takes so, but for constants, + # which are made again where read, and the function's own parameters. A + # parameter and what each edge gives it are held alike, a constant of zero's + # bits being either's. + for v in 1..values { + continue if !handled[v] || !exact[v] || this.p.remade[v] || this.body.type_of(v as u32) != vt::real; + val made := this.body.defining(v as u32); + if made == 0 { + this.single[v] = this.body.origins[v].from != 0; + } else { + val kind := this.body.insts[made].kind; + this.single[v] = kind == op::load || kind == op::fsingle || kind == op::lanes || this.works[made]; + } + } + changed = true; + while changed { + changed = false; + for k in 0..this.p.order.length { + val block: u32 = this.p.order[k]; + val last: u32 = this.body.blocks[block].last; + continue if last == 0; + val ending: inst = this.body.insts[last]; + for e in 0..this.body.edge_count(last) { + val edge := ending.aux + e as u32; + val params := &this.body.blocks[this.body.edges[edge].target].params; + val args := &this.body.edges[edge].args; + for i in 0..args.length { + val param: u32 = params[i]; + val arg: u32 = args[i]; + continue if this.body.type_of(param) != vt::real; + val given := this.single[arg as u64] || this.zero_constant(arg); + if this.single[param] && !given { + this.single[param] = false; + changed = true; + } + if !this.single[param] && this.single[arg as u64] { + this.single[arg as u64] = false; + changed = true; + } + } + } + } + } +} + +#! Whether an operation takes a real it reads as an `f32` where it is held so: +#! the arithmetic and comparisons of reals, which widen it where they work in +#! double precision. +#! @param kind The operation. +#! @returns Whether it does. +def takes_single(kind: op): bool { + return match kind { + op::fadd, op::fsub, op::fmul, op::fdiv, op::fsqrt, op::feq, op::fne, op::flt, op::fle => true, + else => false + }; +} + +#! Whether the bits of an `f64` are an `f32`'s exactly. +#! @param bits The bits. +#! @returns Whether they are. +def single_constant(bits: u64): bool { + val real := ((&bits) as *f64)[0]; + return (real as f32) as f64 == real; +} + +#! Whether a value is the constant `0`, whose bits are the same as an `f32`'s +#! and an `f64`'s. +#! @param this The selector. +#! @param value The value. +#! @returns Whether it is. +def selector::zero_constant(&this, value: u32): bool { + var bits: u64 = 1; + return this.constant_bits(value, &mut bits) && bits == 0; +} + +#! The SSE register an instruction reads a real from as an `f32`: its own where +#! it is held as one in a register, and otherwise the scratch, which it is +#! loaded or rounded into, being one exactly. +#! @param this The selector. +#! @param value The value. +#! @param index The instruction reading it. +#! @param scratch The register it is put in where it is in none. +#! @returns The register's number. +def selector::single_reg(&mut this, value: u32, index: u32, scratch: u8): u8 { + var bits: u64 = 0; + if this.p.remade[value] && this.constant_bits(value, &mut bits) { + if bits == 0 { + this.b.text.packed(vec_xorps, scratch as u32, scratch as u32); + return scratch; + } + val real := ((&bits) as *f64)[0]; + val narrow: f32 = real as f32; + this.b.text.mov_imm(reg::rdx, ((&narrow) as *u32)[0] as u64); + this.b.text.movq_to_xmm(scratch, reg::rdx); + return scratch; + } + if !this.single[value] { + this.b.text.cvtsd2ss(scratch, this.real_reg(value, index, scratch)); + return scratch; + } + val held := this.read(value, index); + match held.kind { + place::xmm => return held.number; + place::gpr => this.b.text.movq_to_xmm(scratch, held.number as reg); + place::none => { + this.b.text.mov_imm(reg::rdx, 0); + this.b.text.movq_to_xmm(scratch, reg::rdx); + } + else => this.b.text.movss_load(scratch, this.memory_of(&held)); + } + return scratch; +} + +#! Widens a real held as an `f32` into a register, as `real_reg` gives every +#! real. +#! @param this The selector. +#! @param held Where it is. +#! @param scratch The register. +#! @returns The register's number. +def selector::widened(&mut this, held: &loc, scratch: u8): u8 { + match held.kind { + place::xmm => this.b.text.cvtss2sd(scratch, held.number); + place::gpr => { + this.b.text.movq_to_xmm(scratch, held.number as reg); + this.b.text.cvtss2sd(scratch, scratch); + } + place::none => { + this.b.text.mov_imm(reg::rdx, 0); + this.b.text.movq_to_xmm(scratch, reg::rdx); + } + else => { + this.b.text.movss_load(scratch, this.memory_of(held)); + this.b.text.cvtss2sd(scratch, scratch); + } + } + return scratch; +} + +#! The instruction of `f32`s an arithmetic of `f64`s is worked as. +#! @param kind The arithmetic. +#! @returns The instruction. +def single_of(kind: sse): u32 { + return match kind { + sse::addsd => ss_add, + sse::subsd => ss_sub, + sse::mulsd => ss_mul, + sse::divsd => ss_div, + else => ss_sqrt + }; +} + +#! An arithmetic of two reals worked in single precision, into the result's +#! register where it is held as an `f32` there, and otherwise into `xmm0`, +#! widened where it is held as an `f64`. +#! @param this The selector. +#! @param index The instruction. +#! @param kind The arithmetic, as its `f64`s' instruction. +#! @param a The first operand. +#! @param b The second. +#! @param result The result. +#! @param commutes Whether the operands may be swapped. +def selector::single_arithmetic(&mut this, index: u32, kind: sse, a: u32, b: u32, result: u32, commutes: bool): void { + val instruction := single_of(kind); + val narrow := this.single[result]; + val into := narrow ? this.real_target(result) : 0; + if into != 0 && this.is_single_in(a, index, into) { + this.b.text.packed(instruction, into as u32, this.single_reg(b, index, 1) as u32); + } else if into != 0 && commutes && this.is_single_in(b, index, into) { + this.b.text.packed(instruction, into as u32, this.single_reg(a, index, 1) as u32); + } else { + val second := this.single_reg(b, index, 1); + val first := this.single_reg(a, index, 0); + if first != 0 { + this.b.text.movaps(0, first); + } + this.b.text.packed(instruction, 0, second as u32); + if into != 0 { + this.b.text.movaps(into, 0); + } + } + if narrow { + this.put_real(result, into); + return; + } + val wide := this.real_target(result); + this.b.text.cvtss2sd(wide, 0); + this.put_real(result, wide); +} + +#! A square root worked in single precision, as `single_arithmetic` works the +#! others. +#! @param this The selector. +#! @param index The instruction. +#! @param a The operand. +#! @param result The result. +def selector::single_root(&mut this, index: u32, a: u32, result: u32): void { + val narrow := this.single[result]; + val into := narrow ? this.real_target(result) : 0; + this.b.text.packed(ss_sqrt, into as u32, this.single_reg(a, index, 1) as u32); + if narrow { + this.put_real(result, into); + return; + } + val wide := this.real_target(result); + this.b.text.cvtss2sd(wide, into); + this.put_real(result, wide); +} + +#! `fsingle` of a real: a copy of one held as an `f32` already, and otherwise +#! the real rounded; where the result is held as an `f64`, the rounded real +#! widened again. +#! @param this The selector. +#! @param index The instruction. +#! @param a The operand. +#! @param result The result. +def selector::round_single(&mut this, index: u32, a: u32, result: u32): void { + if this.single[result] { + val into := this.real_target(result); + val got := this.single_reg(a, index, into); + if got != into { + this.b.text.movaps(into, got); + } + this.put_real(result, into); + return; + } + val into := this.real_target(result); + if this.single[a] { + this.b.text.cvtss2sd(into, this.single_reg(a, index, 0)); + } else { + this.b.text.cvtsd2ss(0, this.real_reg(a, index, 0)); + this.b.text.cvtss2sd(into, 0); + } + this.put_real(result, into); +} + +#! Whether a value an instruction reads is held as an `f32` in an SSE register. +#! @param this The selector. +#! @param value The value. +#! @param index The instruction reading it. +#! @param x The register's number. +#! @returns Whether it is. +def selector::is_single_in(&this, value: u32, index: u32, x: u8): bool { + return false if !this.single[value]; + val held := this.read(value, index); + return held.kind == place::xmm && held.number == x; +} diff --git a/native/variables.sakura b/native/variables.sakura new file mode 100644 index 00000000..c83267a3 --- /dev/null +++ b/native/variables.sakura @@ -0,0 +1,466 @@ +#! @file variables.sakura +#! @author John Christman (sorakatadzuma@gmail.com) +#! @copyright Malunal Studios, LLC. +#! @license MIT +#! +#! Contains where the variables debugging information shows are in a +#! function's code once it is selected. A variable held in memory is where its +#! cell, or its copy of a parameter, is in the frame, over the code its scope +#! covers. One held in values, as optimized code holds a local of words, is +#! where the values it took are: each binding takes effect where it was made, +#! or where its block begins where optimizing took that out; a block begins +#! with what every block before it ended with where they agree, or with the +#! parameter they each give that; and where each value is at each instruction +#! is where the registers' placing put it, a register or its slot, while it +#! lives, or a constant, which is known anywhere, as is one a binding keeps +#! once its instruction went. + +import sakura::compiler; +import binary::amd64; +module sakura::native; + + +#! The most words a variable held in values has. +const held_words: u64 = 3; + +#! Notes where each variable of the function is, as the file says. +#! @param this The selector. +#! @param spans Where each instruction's code begins, then ends. +def selector::place_variables(&mut this, spans: span): void { + val size := (this.b.text.length - this.start) as u32; + var held := false; + for v in 0..this.body.variables.length { + val each: variable_info = this.body.variables[v]; + if each.held { + held = true; + continue; + } + # One whose cell went, as optimizing takes out a cell nothing reads, is + # nowhere. + var below: u64 = 0; + if each.cell != 0 { + below = this.cells[each.cell as u64 - 1]; + } else if each.given != 0 { + below = this.copies[each.given as u64 - 1]; + } + continue if below == 0; + var from: u32 = 0; + var to: u32 = size; + if !each.param && (each.first != 0 || each.end != 0) { + from = size; + to = 0; + val end := each.end != 0 ? each.end : this.body.insts.length as u32; + for i in each.first..end { + break if 2 * i as u64 + 1 >= spans.length; + val begins := spans[2 * i as u64]; + val ends := spans[2 * i as u64 + 1]; + continue if ends <= begins; + from = begins < from ? begins : from; + to = ends > to ? ends : to; + } + } + # The frame's canonical address is past the saved `rbp` and the return + # address. + this.b.debug.variables.append(placed_variable { + name = each.name, + at = each.at, + layout = each.layout, + offset = -(below as i64) - 16, + param = each.param, + boxed = each.boxed, + site = each.site, + from = from, + to = to + }); + } + if held { + this.place_held(spans); + } +} + +#! Where a value is while an instruction runs, as a word of a variable: where +#! a call is, where it is past the call, as what lives across a call is in a +#! register the call keeps, which the frames below say where they saved, or in +#! its slot. +#! @param this The selector. +#! @param value The value. +#! @param index The instruction. +#! @param kind Where the kind of place is written. +#! @returns The register, the offset from the frame's canonical address, or the +#! bits. +def selector::word_spot_of(&this, value: u32, index: u32, kind: &mut u8): u64 { + kind = word_spot::nowhere as u8; + + # A constant is known, made where it is read or not at all, as is one a + # binding keeps, which the binding, numbered past the values, stands for. + val values := this.body.origins.length; + if value as u64 >= values { + val bound: binding = this.body.bindings[value as u64 - values]; + kind = (bound.known == vt::real ? word_spot::real : word_spot::word) as u8; + return bound.bits; + } + val maker := this.body.defining(value); + if maker != 0 { + val made: inst = this.body.insts[maker]; + if made.kind == op::iconst { + kind = word_spot::word as u8; + return made.imm; + } + if made.kind == op::fconst { + kind = word_spot::real as u8; + return made.imm; + } + } + + # Elsewhere, it is where its part there is, and nowhere outside its life. + val position := 4 * this.p.slots[index] + (calls(this.body.insts[index].kind) ? 3 : 1); + val first: u32 = this.p.child_first[value]; + val past: u32 = this.p.child_first[value + 1]; + var part: u32 = past; + for c in first..past { + if this.p.child_starts[c as u64] <= position && position < this.p.child_ends[c as u64] { + part = c; + } + } + return 0 if part == past; + val held: loc = this.p.child_locs[part as u64]; + match held.kind { + place::gpr => { + kind = word_spot::gpr as u8; + return held.number as u64; + } + place::xmm => { + kind = word_spot::xmm as u8; + return held.number as u64; + } + place::slot => { + kind = word_spot::frame as u8; + return (this.slot(value).disp as i64 - 16) as u64; + } + else => {} + } + return 0; +} + +#! Notes the ranges of code each variable held in values is somewhere in, and +#! where each of its words is over each. +#! @param this The selector. +#! @param spans Where each instruction's code begins, then ends. +def selector::place_held(&mut this, spans: span): void { + val body := &this.body; + val program := &this.b.c.program; + + # Each word followed: those of each variable held in values, by slot. + var slot_first := vector::::new(scratch()); + var words := vector::::new(scratch()); + var slots: u32 = 0; + for v in 0..body.variables.length { + val each: variable_info = body.variables[v]; + var count: u64 = 0; + if each.held { + count = each.boxed ? 1 : word_count(&program.layouts[each.layout]); + } + if count > held_words { + count = 0; + } + slot_first.append(slots); + words.append(count as u32); + slots += count as u32; + } + return if slots == 0; + + # Of each `f32` held in values, whether it is described as one: where more of + # the values bound to it are held as `f32`s than as `f64`s, as `singles.sakura` + # says. Where it is held the other way, it is described as nowhere. + var narrow := vector::::new(scratch()); + var floats := vector::::new(scratch()); + var votes := vector::::new(scratch()); + narrow.resize(body.variables.length); + floats.resize(body.variables.length); + votes.resize(body.variables.length); + for v in 0..body.variables.length { + val each: variable_info = body.variables[v]; + val shape: layout = program.layouts[each.layout]; + floats[v] = each.held && !each.boxed && shape.kind == lk::floating && shape.size == 4; + } + for &bound in body.bindings { + continue if bound.variable as u64 >= floats.length || !floats[bound.variable as u64]; + continue if bound.value == 0 || bound.value as u64 >= body.origins.length || this.p.remade[bound.value]; + votes[bound.variable as u64] = votes[bound.variable as u64] + (this.single[bound.value] ? 1 : -1); + } + for v in 0..body.variables.length { + narrow[v] = floats[v] && votes[v] > 0; + } + + # What binds each slot, where: after the instruction it was bound after, + # where that is still in the code, or else where the block it was bound in + # begins, in the order bound. + var placed := vector::::new(scratch()); + placed.resize(body.insts.length); + for k in 0..this.p.order.length { + var walk := body.walk(this.p.order[k]); + while walk.more() { + placed[walk.next()] = true; + } + } + var at_inst := vector::::new(scratch()); + at_inst.resize(body.insts.length); + var at_block := vector::::new(scratch()); + at_block.resize(body.blocks.length); + var after := vector::::new(scratch()); + after.resize(body.bindings.length); + var b := body.bindings.length; + while b > 0 { + b--; + val bound: binding = body.bindings[b]; + continue if bound.variable as u64 >= words.length || bound.word >= words[bound.variable as u64]; + continue if (bound.value == 0 && bound.known == vt::none) || bound.value as u64 >= body.origins.length; + if bound.after != 0 && placed[bound.after] { + after[b] = at_inst[bound.after]; + at_inst[bound.after] = b as u32 + 1; + continue; + } + var block := bound.block; + if block == 0xFFFFFFFF || body.blocks[block].gone || this.p.number[block] == never { + block = bound.after != 0 ? body.insts[bound.after].block : 0xFFFFFFFF; + } + continue if block == 0xFFFFFFFF || body.blocks[block].gone || this.p.number[block] == never; + after[b] = at_block[block]; + at_block[block] = b as u32 + 1; + } + + # What each block begins with, by slot: what every block laid out before it + # ended with, where they agree, and nothing otherwise, until none changes. + # `never` stands for a block not yet worked out. + val blocks := body.blocks.length; + var begins := vector::::new(scratch()); + var ends := vector::::new(scratch()); + begins.resize(blocks * slots as u64); + ends.resize(blocks * slots as u64); + for i in 0..blocks * slots as u64 { + ends[i] = never; + } + var state := vector::::new(scratch()); + state.resize(slots as u64); + var split := vector::::new(scratch()); + split.resize(slots as u64); + var changed := true; + var rounds := 0u; + while changed && rounds < 32 { + changed = false; + rounds++; + for k in 0..this.p.order.length { + val block: u32 = this.p.order[k]; + for s in 0..slots as u64 { + state[s] = block == 0 ? 0 : never; + split[s] = false; + } + for &edge in body.blocks[block].preds.view() { + val from := body.edge_source(edge); + continue if this.p.number[from] == never; + for s in 0..slots as u64 { + val given: u32 = ends[from as u64 * slots as u64 + s]; + continue if given == never; + val now: u32 = state[s]; + if now != never && now != given { + split[s] = true; + } + state[s] = now == never || now == given ? given : 0; + } + } + # Where the blocks before differ, the variable is the parameter each + # gives what it ended with, where one is. + for s in 0..slots as u64 { + continue if !split[s]; + val params := &body.blocks[block].params; + for i in 0..params.length { + var all := true; + for &edge in body.blocks[block].preds.view() { + val from := body.edge_source(edge); + continue if this.p.number[from] == never; + val given: u32 = ends[from as u64 * slots as u64 + s]; + all = all && (given == never || body.edges[edge].args[i] == given); + } + if all { + state[s] = params[i]; + break; + } + } + } + for s in 0..slots as u64 { + if state[s] == never { + state[s] = 0; + } + begins[block as u64 * slots as u64 + s] = state[s]; + } + this.apply_bindings(at_block[block], &after, &slot_first, &mut state); + var walk := body.walk(block); + while walk.more() { + this.apply_bindings(at_inst[walk.next()], &after, &slot_first, &mut state); + } + for s in 0..slots as u64 { + val index := block as u64 * slots as u64 + s; + if ends[index] != state[s] { + ends[index] = state[s]; + changed = true; + } + } + } + } + + # The ranges: each instruction where a variable's words are somewhere other + # than before begins one. + val variables := body.variables.length; + var open := vector::::new(scratch()); + open.resize(variables); + var opened := vector::::new(scratch()); + opened.resize(variables); + var found := vector::>::new(scratch()); + for _ in 0..variables { + found.append(vector::::new(scratch())); + } + # The stubs of each instruction, written after the body, as a list through + # `stub_after`. + val stubs := this.stub_spans.length / 3; + var stub_head := vector::::new(scratch()); + var stub_after := vector::::new(scratch()); + stub_after.resize(stubs); + if stubs != 0 { + stub_head.resize(body.insts.length); + } + for t in 0..stubs { + val index: u32 = this.stub_spans[3 * t + 2]; + stub_after[t] = stub_head[index]; + stub_head[index] = t as u32 + 1; + } + + var last_end: u32 = 0; + for k in 0..this.p.order.length { + val block: u32 = this.p.order[k]; + for s in 0..slots as u64 { + state[s] = begins[block as u64 * slots as u64 + s]; + } + this.apply_bindings(at_block[block], &after, &slot_first, &mut state); + var walk := body.walk(block); + while walk.more() { + val at := walk.next(); + val from := spans[2 * at as u64]; + val to := spans[2 * at as u64 + 1]; + if to > from { + for v in 0..variables { + continue if words[v] == 0; + var here := located_range { from = from, to = to }; + var known := false; + for w in 0..words[v] as u64 { + val value: u32 = state[slot_first[v] as u64 + w]; + continue if value == 0; + var kind: u8 = 0; + here.spots[w] = this.word_spot_of(value, at, &mut kind); + if floats[v] && (kind == word_spot::real as u8 ? narrow[v] : this.single[value] != narrow[v]) { + kind = word_spot::nowhere as u8; + } + here.kinds[w] = kind; + known = known || kind != word_spot::nowhere as u8; + } + val same := opened[v] && same_spots(&open[v], &here); + continue if same; + if opened[v] { + open[v].to = from; + if open[v].to > open[v].from { + found[v].append(open[v]); + } + } + opened[v] = known; + open[v] = here; + } + last_end = to > last_end ? to : last_end; + } + + # A stub of the instruction has the variables where the instruction does. + var t: u32 = stubs != 0 ? stub_head[at] : 0; + while t != 0 { + val stub_from: u32 = this.stub_spans[3 * (t as u64 - 1)]; + val stub_to: u32 = this.stub_spans[3 * (t as u64 - 1) + 1]; + for v in 0..variables { + continue if words[v] == 0; + var here := located_range { from = stub_from, to = stub_to }; + var known := false; + for w in 0..words[v] as u64 { + val value: u32 = state[slot_first[v] as u64 + w]; + continue if value == 0; + var kind: u8 = 0; + here.spots[w] = this.word_spot_of(value, at, &mut kind); + if floats[v] && (kind == word_spot::real as u8 ? narrow[v] : this.single[value] != narrow[v]) { + kind = word_spot::nowhere as u8; + } + here.kinds[w] = kind; + known = known || kind != word_spot::nowhere as u8; + } + if known && stub_to > stub_from { + found[v].append(here); + } + } + t = stub_after[t as u64 - 1]; + } + this.apply_bindings(at_inst[at], &after, &slot_first, &mut state); + } + } + + for v in 0..variables { + continue if words[v] == 0; + if opened[v] { + open[v].to = last_end; + if open[v].to > open[v].from { + found[v].append(open[v]); + } + } + continue if found[v].length == 0; + val each: variable_info = body.variables[v]; + val first := this.b.debug.ranges.length as u32; + for &range in found[v] { + this.b.debug.ranges.append(range); + } + this.b.debug.variables.append(placed_variable { + name = each.name, + at = each.at, + layout = each.layout, + param = each.param, + boxed = each.boxed, + held = true, + narrow = narrow[v], + site = each.site, + ranges = first, + count = found[v].length as u32 + }); + } +} + +#! Gives each slot the value each binding of a list gives it, in order. One +#! keeping a constant gives what stands for it: the binding, numbered past the +#! values. +#! @param this The selector. +#! @param first One more than the first binding, or 0. +#! @param after One more than the binding after each, or 0. +#! @param slot_first The first slot of each variable. +#! @param state The value each slot holds. +def selector::apply_bindings(&this, first: u32, after: &vector, slot_first: &vector, state: &mut vector): void { + val values := this.body.origins.length; + var b := first; + while b != 0 { + val bound: binding = this.body.bindings[b as u64 - 1]; + val given := bound.known != vt::none ? (values + b as u64 - 1) as u32 : bound.value; + state[slot_first[bound.variable as u64] as u64 + bound.word as u64] = given; + b = after[b as u64 - 1]; + } +} + +#! Whether two ranges say each word is in the same place. +#! @param a The one. +#! @param b The other. +#! @returns Whether they do. +def same_spots(a: &located_range, b: &located_range): bool { + for w in 0..held_words { + return false if a.kinds[w] != b.kinds[w] || a.spots[w] != b.spots[w]; + } + return true; +} diff --git a/native/windows.sakura b/native/windows.sakura new file mode 100644 index 00000000..47037252 --- /dev/null +++ b/native/windows.sakura @@ -0,0 +1,1011 @@ +#! @file windows.sakura +#! @author John Christman (sorakatadzuma@gmail.com) +#! @copyright Malunal Studios, LLC. +#! @license MIT +#! +#! Contains what an executable for Windows needs beyond the code generation it +#! shares with one for Linux: the records the loader reads to import the +#! functions of the system and of the libraries the program names, the start +#! the system runs it at, the handler of faults and the one of the console's +#! events, the code `catch_signal` and a thread begin at, and the writer of the +#! PE file. +#! +#! Windows has no system calls a program makes itself. The generated code calls +#! the functions of kernel32 instead, as C functions the executable imports, +#! and finds each thread's record through a slot of the system's record of the +#! thread, which `gs` points at, rather than through `gs` itself, which Windows +#! keeps for its own. + +import std::containers; +import std::io; +import sakura::compiler; +import binary::amd64; +import binary::elf; +import binary::pe; +module sakura::native; + + +#! The functions of the system the generated code calls, all of kernel32, each +#! given a word of the table of addresses the loader writes. +pub enum system_import : u8 { + tls_alloc, + get_current_thread_id, + virtual_alloc, + get_current_thread_stack_limits, + exit_process, + add_vectored_exception_handler, + set_console_ctrl_handler, + create_event, + set_event, + reset_event, + close_handle, + open_thread, + cancel_synchronous_io, + sleep, + get_std_handle, + write_file, + create_thread, + count, +} + +pub const system_tls_alloc: system_import = system_import::tls_alloc; +pub const system_get_current_thread_id: system_import = system_import::get_current_thread_id; +pub const system_virtual_alloc: system_import = system_import::virtual_alloc; +pub const system_stack_limits: system_import = system_import::get_current_thread_stack_limits; +pub const system_exit_process: system_import = system_import::exit_process; +pub const system_add_veh: system_import = system_import::add_vectored_exception_handler; +pub const system_set_console_ctrl_handler: system_import = system_import::set_console_ctrl_handler; +pub const system_create_event: system_import = system_import::create_event; +pub const system_set_event: system_import = system_import::set_event; +pub const system_reset_event: system_import = system_import::reset_event; +pub const system_close_handle: system_import = system_import::close_handle; +pub const system_open_thread: system_import = system_import::open_thread; +pub const system_cancel_synchronous_io: system_import = system_import::cancel_synchronous_io; +pub const system_sleep: system_import = system_import::sleep; +pub const system_get_std_handle: system_import = system_import::get_std_handle; +pub const system_write_file: system_import = system_import::write_file; +pub const system_create_thread: system_import = system_import::create_thread; + +#! The name of each function of the system the generated code calls. +const system_import_names: strview[17] = [ + "TlsAlloc", "GetCurrentThreadId", "VirtualAlloc", "GetCurrentThreadStackLimits", "ExitProcess", + "AddVectoredExceptionHandler", "SetConsoleCtrlHandler", "CreateEventW", "SetEvent", "ResetEvent", + "CloseHandle", "OpenThread", "CancelSynchronousIo", "Sleep", "GetStdHandle", "WriteFile", "CreateThread" +]; + +#! The library the functions of the system are imported from. +const kernel32: strview = "kernel32.dll"; + +#! The numbers of the signals the console's events stand for, which are those +#! Linux gives them: Ctrl-C interrupts, Ctrl-Break quits, the console closing +#! hangs up, and the user leaving or the system shutting down terminates. +const signal_hangup: u64 = 1; +const signal_interrupt: u64 = 2; +const signal_quit: u64 = 3; +const signal_terminate: u64 = 15; + +#! What `catch_signal` is asked to do with a signal, above its number: note it +#! when it comes, throw it away, do with it what the system does by default, +#! note it now, or give the event set where a signal is noted. +const catch_note: i64 = 0; +const catch_ignore: i64 = 1; +const catch_default: i64 = 2; +const catch_now: i64 = 3; +const catch_event: i64 = 4; + +#! Calls a function the code imports of the system, as C is called on Windows: +#! with `rsp` aligned to 16 bytes and the 32 bytes above it, which C may keep +#! its arguments in, the caller's. Its arguments are placed by the caller. +#! @param this The building. +#! @param which The function. +pub def building::call_system(&mut this, which: system_import): void { + this.text.load(8, false, reg::rax, amd64::absolute(this.got + 8 * this.imports_at[which as u64] as u64)); + this.text.call_reg(reg::rax); +} + +#! Moves `rsp` down by some bytes, touching each page it passes in turn, as +#! Windows grows a thread's stack only into the page past the last it touched. +#! @param this The building. +#! @param bytes The bytes. +pub def building::descend(&mut this, bytes: u64): void { + var left := bytes; + while left > page_size { + this.text.alu_imm(alu::sub, reg::rsp, page_size as i32); + this.text.alu_mem_imm(alu::bor, at(reg::rsp, 0), 0); + left -= page_size; + } + if left != 0 { + this.text.alu_imm(alu::sub, reg::rsp, left as i32); + } +} + +#! Exits with 2 where a step of the start did not hold. +#! @param this The building. +#! @param condition The condition that holds where it did. +def building::exit_unless(&mut this, condition: cc): void { + val holds := this.text.jcc(condition); + this.text.mov_imm(reg::rcx, 2); + this.call_system(system_exit_process); + this.text.land(holds); +} + +#! Whether a name holds only ASCII, which the loader finds a library by whatever +#! the code page is. +#! @param name The name. +#! @returns Whether it does. +def ascii_only(name: strview): bool { + for i in 0..name.length { + return false if name[i] >= 0x80; + } + return true; +} + +#! The RVA of a place in the image, which every record the loader reads names +#! parts of the image by. +#! @param this The building. +#! @param at The offset within the read-only image. +#! @returns The address past the image's base. +def building::rva(&this, at: u64): u64 { + return this.rodata_base + at - base_address; +} + +#! Appends what the loader reads to the image: the name of each function +#! imported, the name of each library, a table naming each library's functions +#! as its words of the table of addresses will, and the record of each library, +#! then a record of zeros. The functions are the system's the code calls, then +#! the C functions it names, each library's words together and a word of zeros +#! after them, where a function a library is named for twice has one. +#! @param this The building. +def building::imports(&mut this): void { + val program := &this.c.program; + val system := system_import::count as u64; + val linked := program.linked.length; + val total := system + linked; + + # Each entry's library and name, of those named. A system import is of + # kernel32, and a C function of the library its file's `extern import` names. Each library + # is found by its name in lower case, as Windows names files whatever the + # case of their letters, and kept as it was first named. + var library_of := vector::::new(); + var name_of := vector::::new(); + var folded := interner::::new(); + var distinct := vector::::new(); + var decl_of := vector::::new(); + var word_of := vector::::new(); + for e in 0..total { + word_of.append(never as u64); + var library := kernel32; + var name := strview::empty(); + var decl: u32 = 0; + if e < system { + name = system_import_names[e]; + } else if this.slots[e - system] != never { + library = program.linked[e - system].library.view(); + name = this.c.checker.names.text(program.linked[e - system].name); + decl = program.linked[e - system].decl; + } else { + library_of.append(never as u64); + name_of.append(name); + decl_of.append(0); + continue; + } + val lowered := library.lower(); + val found := folded.intern_view(lowered.view()) as u64; + if found == distinct.length { + distinct.append(library); + } + library_of.append(found); + name_of.append(name); + decl_of.append(decl); + } + + # Each library's words of the table of addresses, with a terminator after, + # and the hint and name of each function, shared where a library names one + # twice. + var word: u64 = 0; + var functions := interner::::new(); + var words := vector::::new(); # The word of each function of the library, by its ID. + this.import_firsts.resize(distinct.length); + for l in 0..distinct.length { + this.import_firsts[l] = word; + functions.clear(); + words.clear(); + for e in 0..total { + continue if library_of[e] != l; + val id := functions.intern_view(name_of[e]) as u64; + if id < words.length { + word_of[e] = words[id]; + continue; + } + val at := this.rodata.align_to(2); + this.rodata.u16(0); + this.rodata.put_terminated(name_of[e]); + this.import_names.append(this.rva(at)); + words.append(word); + word_of[e] = word; + word++; + } + this.import_names.append(0); + word++; + } + this.import_words = word; + this.library_count = distinct.length; + + # The name of each library, noting one the loader could not find. + var named := vector::::new(); + for l in 0..distinct.length { + if !ascii_only(distinct[l]) { + var decl: u32 = 0; + for e in system..total { + if library_of[e] == l { + decl = decl_of[e]; + break; + } + } + this.problem_at(decl, "Windows finds the libraries of an executable by names of the code page of the system, which cannot hold this one."); + } + val at := this.bytes(distinct[l]); + this.rodata.byte(0); + named.append(this.rva(at)); + } + + # The table naming each function, which the import directory reads and the + # table of addresses begins as, until the loader writes each one's address. + val table := this.words(this.import_words); + for w in 0..this.import_words { + this.rodata.set_u64(table + 8 * w, this.import_names[w]); + } + + # The record of each library: where its names are, where its addresses go, + # patched once the table of addresses is placed, and its name. A record of + # zeros ends them. + this.rodata.align_to(4); + this.descriptors = this.rodata.length; + for l in 0..distinct.length { + this.rodata.u32(this.rva(table + 8 * this.import_firsts[l])); + this.rodata.u32(0); + this.rodata.u32(0); + this.rodata.u32(named[l]); + this.rodata.u32(0); + } + for _ in 0..5u { + this.rodata.u32(0); + } + + # Each entry's word, as the generated code reads it: a system import by its + # own number, and a C function where its slot was. + this.imports_at.resize(system); + for e in 0..total { + if e < system { + this.imports_at[e] = word_of[e] as u32; + } else if this.slots[e - system] != never { + this.slots[e - system] = word_of[e] as u32; + } + } +} + +#! Tells the loader the word each library's addresses are written to, once the +#! table of addresses is placed. +#! @param this The building. +def building::relocate_imports(&mut this): void { + for l in 0..this.library_count { + this.rodata.set_u32(this.descriptors + 20 * l + 16, this.got + 8 * this.import_firsts[l] - base_address); + } +} + + +# The start. + +#! Writes `_start` for Windows, which the system calls on the first thread's +#! stack. The native code runs on that stack, the size the file asks, as on +#! Linux it runs on one it maps, and a frame larger than a page is grown a page +#! at a time so the system commits each. It takes a +#! slot of the system's record of each thread for the thread's own record, +#! making the first thread's the state, finds where the stack ends, and has +#! `runtime::system_start` find the arguments and variables before the +#! program runs, then exits with 0. The system's calls are made with `rsp` +#! aligned to 16 bytes past the 32 they may use, and two words above those, +#! which the stack's limits are asked into. +#! @param this The building. +def building::entry_windows(&mut this): void { + this.start = this.text.length; + this.text.alu_imm(alu::sub, reg::rsp, 56); + + # The slot is one of the first 64, which the system's record holds itself. + this.call_system(system_tls_alloc); + this.text.extend(4, false, reg::rax, reg::rax); + this.text.alu_imm(alu::cmp, reg::rax, tls_count as i32); + this.exit_unless(cc::below); + this.text.shift_imm(shift::shl, reg::rax, 3); + this.text.alu_imm(alu::add, reg::rax, tls_slots as i32); + this.text.store(8, amd64::absolute(this.state_address(state_own)), reg::rax); + this.text.mov_imm(reg::rcx, this.state_address(0)); + this.text.store(8, own_at(reg::rax), reg::rcx); + this.text.store(8, amd64::absolute(this.state_address(state_itself)), reg::rcx); + this.text.store_imm(amd64::absolute(this.state_address(state_running)), 1); + this.call_system(system_get_current_thread_id); + this.text.extend(4, false, reg::rax, reg::rax); + this.text.store(8, amd64::absolute(this.state_address(state_tid)), reg::rax); + + # The vector instructions the processor has, kept until `processor` filters them. + this.probe(); + this.text.store(8, amd64::absolute(this.state_address(state_features)), reg::rax); + + # The stack the system made it: its top is where frames begin, and the + # reserve past the limit, which a trap's report runs in, is at its low end. + this.text.lea(reg::rcx, at(reg::rsp, 32)); + this.text.lea(reg::rdx, at(reg::rsp, 40)); + this.call_system(system_stack_limits); + this.text.load(8, false, reg::rax, at(reg::rsp, 32)); + this.text.store(8, amd64::absolute(this.state_address(state_trap_frame)), reg::rax); + this.text.alu_imm(alu::add, reg::rax, (stack_reserve + 65536) as i32); + this.text.store(8, amd64::absolute(this.state_address(state_limit)), reg::rax); + this.text.load(8, false, reg::rax, at(reg::rsp, 40)); + this.text.store(8, amd64::absolute(this.state_address(state_base)), reg::rax); + + # Faults of the program are reported as traps, by the first handler of + # exceptions. `rsp` keeps the 32 bytes above it the start reserved, which the + # call may keep its arguments in. + this.text.mov_imm(reg::rcx, 1); + this.text.mov_imm(reg::rdx, this.text_base + this.faults); + this.call_system(system_add_veh); + + this.text.mov_imm(reg::rbp, 0); + + # The arguments and variables, found as the system gives them, before the + # globals, since a trap before them could not be reported. + this.call_to(this.system_start_function); + + # The vector instructions the program uses, of those the processor has. + this.text.load(8, false, gprs[0], amd64::absolute(this.state_address(state_features))); + this.call_to(this.helper_of(helper::processor)); + this.text.store(8, amd64::absolute(this.state_address(state_features)), reg::rax); + + this.run_main(); + this.text.mov_imm(reg::rcx, 0); + this.call_system(system_exit_process); + this.text.ud2(); + this.entry_end = this.text.length; +} + + +# The handlers. + +#! Writes the code the signal handlers and the threads begin at, after the trap +#! stub, which Windows and C call, so each keeps what C keeps, `rsi` and `rdi` +#! among them, and uses only `rax`, `rcx`, `rdx`, `r8`, `r9`, and its own stack. +#! @param this The building. +def building::windows_handlers(&mut this): void { + this.fault_handler(); + this.signalled_handler(); + this.console_handler(); + this.catching_handler(); + this.stranger_handler(); + this.beginning_handler(); +} + +#! Writes the first handler of exceptions, which Windows calls with the context +#! of the fault in `rcx`. A fault of the program's code on a thread of the +#! program, where no trap is being reported, is reported as the test would have +#! been: the thread goes on at the trap stub, as though the instruction faulting +#! called it, with the chain of `rbp` it was in. Those faults are an access +#! within the first page, which is null reached through, and a division by +#! zero. Anything else is left to the next handler, and ends the process where +#! none handles it. +#! @param this The building. +def building::fault_handler(&mut this): void { + this.faults = this.text.length; + this.text.load(8, false, reg::rax, at(reg::rcx, 0)); # ExceptionRecord + this.text.load(4, false, reg::rdx, at(reg::rax, 0)); # ExceptionCode + this.text.mov_imm(reg::r9, fault::division as u64); + this.text.mov_imm(reg::r8, 0xC0000094); # EXCEPTION_INT_DIVIDE_BY_ZERO + this.text.alu(alu::cmp, reg::rdx, reg::r8); + val division := this.text.jcc(cc::equal); + this.text.mov_imm(reg::r9, fault::null_reference as u64); + this.text.mov_imm(reg::r8, 0xC0000005); # EXCEPTION_ACCESS_VIOLATION + this.text.alu(alu::cmp, reg::rdx, reg::r8); + val other := this.text.jcc(cc::not_equal); + this.text.load(8, false, reg::rdx, at(reg::rax, 0x28)); # The address accessed. + this.text.alu_imm(alu::cmp, reg::rdx, null_page as i32); + val elsewhere := this.text.jcc(cc::above_equal); + this.text.land(division); + this.text.load(8, false, reg::r8, at(reg::rcx, 8)); # ContextRecord + this.text.load(8, false, reg::rax, at(reg::r8, 0xF8)); # Rip + this.text.mov_imm(reg::rcx, this.text_base); + this.text.alu(alu::cmp, reg::rax, reg::rcx); + val before := this.text.jcc(cc::below); + this.text.byte(0xB9); # mov ecx, imm32 + this.code_end = this.text.length; + this.text.u32(0); + this.text.alu(alu::cmp, reg::rax, reg::rcx); + val after := this.text.jcc(cc::above_equal); + this.own_record(reg::rcx); + this.text.test(reg::rcx, reg::rcx); + val unknown := this.text.jcc(cc::equal); + this.text.alu_mem_imm(alu::cmp, at(reg::rcx, (8 * state_reporting) as i32), 0); + val reporting := this.text.jcc(cc::not_equal); + # The fault is made to look as though the faulting instruction called the + # trap stub, which reads the address it was called from off the stack. + this.text.lea(reg::rdx, at(reg::rax, 1)); + this.text.load(8, false, reg::rcx, at(reg::r8, 0x98)); # Rsp + this.text.alu_imm(alu::sub, reg::rcx, 8); + this.text.store(8, at(reg::rcx, 0), reg::rdx); # Rip + 1, as a call pushes it + this.text.store(8, at(reg::r8, 0x98), reg::rcx); # Rsp = below it + this.text.store(8, at(reg::r8, 0xB0), reg::r9); # Rdi = the fault + this.text.mov_imm(reg::rax, this.text_base + this.trap_stub); + this.text.store(8, at(reg::r8, 0xF8), reg::rax); # Rip = trap stub + this.text.mov_imm(reg::rax, 0xFFFFFFFFFFFFFFFF); # EXCEPTION_CONTINUE_EXECUTION + this.text.ret(); + this.text.land(other); + this.text.land(elsewhere); + this.text.land(before); + this.text.land(after); + this.text.land(unknown); + this.text.land(reporting); + this.text.mov_imm(reg::rax, 0); # EXCEPTION_CONTINUE_SEARCH + this.text.ret(); +} + +#! Writes the code that notes a signal the program handles, by its number in +#! `rcx`, as one bit of a word of the state, which the first thread's safe +#! points test, setting the event where there is one, which a wait waits on. +#! Where another thread notes it, what the first thread reads or writes in the +#! system ends, as a signal ends it on Linux. +#! @param this The building. +def building::signalled_handler(&mut this): void { + this.signalled = this.text.length; + this.text.alu_imm(alu::sub, reg::rsp, 40); + this.text.mov_imm(reg::rax, 1); + this.text.shift_cl(shift::shl, reg::rax); + this.text.lock(); + this.text.alu_store(alu::bor, amd64::absolute(this.state_address(state_signals)), reg::rax); + this.text.load(8, false, reg::rcx, amd64::absolute(this.state_address(state_signalled))); + this.text.test(reg::rcx, reg::rcx); + val unasked := this.text.jcc(cc::equal); + this.call_system(system_set_event); + this.text.land(unasked); + this.call_system(system_get_current_thread_id); + this.text.extend(4, false, reg::rax, reg::rax); + this.text.alu_load(alu::cmp, reg::rax, amd64::absolute(this.state_address(state_tid))); + val itself := this.text.jcc(cc::equal); + this.text.mov_imm(reg::rcx, 1); # THREAD_TERMINATE + this.text.mov_imm(reg::rdx, 0); + this.text.load(8, false, reg::r8, amd64::absolute(this.state_address(state_tid))); + this.call_system(system_open_thread); + this.text.test(reg::rax, reg::rax); + val unopened := this.text.jcc(cc::equal); + this.text.store(8, at(reg::rsp, 32), reg::rax); + this.text.mov(reg::rcx, reg::rax); + this.call_system(system_cancel_synchronous_io); + this.text.load(8, false, reg::rcx, at(reg::rsp, 32)); + this.call_system(system_close_handle); + this.text.land(itself); + this.text.land(unopened); + this.text.alu_imm(alu::add, reg::rsp, 40); + this.text.ret(); +} + +#! Writes the console's handler, which Windows calls for each event in `ecx`, +#! on a thread of its own with no record, so it reads only the state. The +#! signal the event stands for is noted where the program catches it, and +#! thrown away where it ignores it, which returns true; otherwise the next +#! handler, the system's, ends the process. The console closing or the user +#! leaving ends it anyway once this returns, so the program's handler runs, and +#! it exits, meanwhile. +#! @param this The building. +def building::console_handler(&mut this): void { + val events: u64[5] = [0, 1, 2, 5, 6]; + val numbers: u64[5] = [signal_interrupt, signal_quit, signal_hangup, signal_terminate, signal_terminate]; + this.noting = this.text.length; + this.text.alu_imm(alu::sub, reg::rsp, 40); + this.text.extend(4, false, reg::rcx, reg::rcx); + var mapped: u64[5]; + for i in 0..5u { + this.text.mov_imm(reg::rdx, numbers[i]); + this.text.alu_imm(alu::cmp, reg::rcx, events[i] as i32); + mapped[i] = this.text.jcc(cc::equal); + } + val unmapped := this.text.jmp(); + for i in 0..5u { + this.text.land(mapped[i]); + } + # The bit of a signal caught in `rax`, and of one ignored in `r8`. + this.text.load(8, false, reg::rax, amd64::absolute(this.state_address(state_disposed))); + this.text.lea(reg::rcx, at(reg::rdx, 32)); + this.text.mov(reg::r8, reg::rax); + this.text.shift_cl(shift::shr, reg::r8); + this.text.alu_imm(alu::band, reg::r8, 1); + val ignored := this.text.jcc(cc::not_equal); + this.text.mov(reg::rcx, reg::rdx); + this.text.shift_cl(shift::shr, reg::rax); + this.text.alu_imm(alu::band, reg::rax, 1); + val uncaught := this.text.jcc(cc::equal); + this.text.store(8, at(reg::rsp, 32), reg::rdx); + this.text.mov(reg::rcx, reg::rdx); + this.text.patch(this.text.call(), this.signalled); + this.text.load(8, false, reg::rdx, at(reg::rsp, 32)); + this.text.alu_imm(alu::cmp, reg::rdx, signal_hangup as i32); + val closing := this.text.jcc(cc::equal); + this.text.alu_imm(alu::cmp, reg::rdx, signal_terminate as i32); + val staying := this.text.jcc(cc::not_equal); + this.text.land(closing); + this.text.mov_imm(reg::rcx, 10000); # The VM's wait while closing. + this.call_system(system_sleep); + this.text.land(staying); + this.text.land(ignored); + this.text.mov_imm(reg::rax, 1); + val answered := this.text.jmp(); + this.text.land(unmapped); + this.text.land(uncaught); + this.text.mov_imm(reg::rax, 0); + this.text.land(answered); + this.text.alu_imm(alu::add, reg::rsp, 40); + this.text.ret(); +} + +#! Writes what `catch_signal` calls, with what it is asked in `rcx`: a signal's +#! number, and above it what to do. It gives in `rax` zero, the event set where +#! a signal is noted where that is asked for, or a negative number: -22 for a +#! number of no signal or an action not known, and -12 where the system has no +#! event to give. The console's handler is set once a signal is first caught or +#! ignored. +#! @param this The building. +def building::catching_handler(&mut this): void { + val event := amd64::absolute(this.state_address(state_signalled)); + val disposed := amd64::absolute(this.state_address(state_disposed)); + this.catching = this.text.length; + this.text.alu_imm(alu::sub, reg::rsp, 56); + this.text.extend(4, true, reg::rcx, reg::rcx); + this.text.mov(reg::rdx, reg::rcx); + this.text.shift_imm(shift::sar, reg::rdx, 8); + this.text.alu_imm(alu::band, reg::rcx, 0xFF); + this.text.alu_imm(alu::cmp, reg::rdx, catch_event as i32); + val signal := this.text.jcc(cc::not_equal); + + # The event, made once it is first asked for and kept while the process runs. + # Where two threads make one at once, the one kept first is given to both. + this.text.load(8, false, reg::rax, event); + this.text.test(reg::rax, reg::rax); + val made := this.text.jcc(cc::not_equal); + this.text.mov_imm(reg::rcx, 0); + this.text.mov_imm(reg::rdx, 1); # Reset only by the program. + this.text.mov_imm(reg::r8, 0); + this.text.mov_imm(reg::r9, 0); + this.call_system(system_create_event); + this.text.test(reg::rax, reg::rax); + val created := this.text.jcc(cc::not_equal); + this.text.mov_imm(reg::rax, (-12) as i64 as u64); + val none := this.text.jmp(); + this.text.land(created); + this.text.store(8, at(reg::rsp, 32), reg::rax); + this.text.mov(reg::rcx, reg::rax); + this.text.mov_imm(reg::rax, 0); + this.text.lock_cmpxchg(8, event, reg::rcx); + val raced := this.text.jcc(cc::not_equal); + this.text.mov(reg::rax, reg::rcx); + val kept := this.text.jmp(); + this.text.land(raced); + this.text.store(8, at(reg::rsp, 40), reg::rax); + this.text.load(8, false, reg::rcx, at(reg::rsp, 32)); + this.call_system(system_close_handle); + this.text.load(8, false, reg::rax, at(reg::rsp, 40)); + val lost := this.text.jmp(); + + this.text.land(signal); + this.text.lea(reg::rax, at(reg::rcx, -1)); + this.text.alu_imm(alu::cmp, reg::rax, 62); + val no_signal := this.text.jcc(cc::above); + this.text.alu_imm(alu::cmp, reg::rdx, catch_now as i32); + val no_action := this.text.jcc(cc::above); + val now := this.text.jcc(cc::equal); + + # The bit of a signal caught in `r8`, and of one ignored in `r9`, or none + # where the number is past those of the console's events. + this.text.mov_imm(reg::r8, 0); + this.text.alu_imm(alu::cmp, reg::rcx, 32); + val past := this.text.jcc(cc::above_equal); + this.text.mov_imm(reg::r8, 1); + this.text.shift_cl(shift::shl, reg::r8); + this.text.land(past); + this.text.mov(reg::r9, reg::r8); + this.text.shift_imm(shift::shl, reg::r9, 32); + this.text.alu_imm(alu::cmp, reg::rdx, catch_ignore as i32); + val ignoring := this.text.jcc(cc::equal); + this.text.alu_imm(alu::cmp, reg::rdx, catch_default as i32); + val defaulting := this.text.jcc(cc::equal); + + this.text.mov(reg::rax, reg::r9); + this.text.unary(unary::bnot, reg::rax); + this.text.lock(); + this.text.alu_store(alu::band, disposed, reg::rax); + this.text.lock(); + this.text.alu_store(alu::bor, disposed, reg::r8); + # A process may start with Ctrl-C ignored, which catching it undoes. + this.text.alu_imm(alu::cmp, reg::rcx, signal_interrupt as i32); + val caught := this.text.jcc(cc::not_equal); + this.text.mov_imm(reg::rcx, 0); + this.text.mov_imm(reg::rdx, 0); + this.call_system(system_set_console_ctrl_handler); + val heeded := this.text.jmp(); + + this.text.land(ignoring); + this.text.mov(reg::rax, reg::r8); + this.text.unary(unary::bnot, reg::rax); + this.text.lock(); + this.text.alu_store(alu::band, disposed, reg::rax); + this.text.lock(); + this.text.alu_store(alu::bor, disposed, reg::r9); + + # The handler is set by the first to set the lowest bit. + this.text.land(caught); + this.text.land(heeded); + this.text.load(8, false, reg::rax, disposed); + val again := this.text.length; + this.text.mov(reg::rcx, reg::rax); + this.text.alu_imm(alu::band, reg::rcx, 1); + val set := this.text.jcc(cc::not_equal); + this.text.lea(reg::rcx, at(reg::rax, 1)); + this.text.lock_cmpxchg(8, disposed, reg::rcx); + this.text.patch(this.text.jcc(cc::not_equal), again); + this.text.mov_imm(reg::rcx, this.text_base + this.noting); + this.text.mov_imm(reg::rdx, 1); + this.call_system(system_set_console_ctrl_handler); + this.text.land(set); + this.text.mov_imm(reg::rax, 0); + val handled := this.text.jmp(); + + this.text.land(defaulting); + this.text.mov(reg::rax, reg::r8); + this.text.alu(alu::bor, reg::rax, reg::r9); + this.text.unary(unary::bnot, reg::rax); + this.text.lock(); + this.text.alu_store(alu::band, disposed, reg::rax); + this.text.mov_imm(reg::rax, 0); + val restored := this.text.jmp(); + + this.text.land(now); + this.text.patch(this.text.call(), this.signalled); + this.text.mov_imm(reg::rax, 0); + val noted := this.text.jmp(); + + this.text.land(no_signal); + this.text.land(no_action); + this.text.mov_imm(reg::rax, (-22) as i64 as u64); + this.text.land(made); + this.text.land(none); + this.text.land(kept); + this.text.land(lost); + this.text.land(handled); + this.text.land(restored); + this.text.land(noted); + this.text.alu_imm(alu::add, reg::rsp, 56); + this.text.ret(); +} + +#! Writes what a callback on a thread the program never started reports +#! through: the machine's text for a callback it cannot run, to the standard +#! error, then it ends the process with 1. +#! @param this The building. +def building::stranger_handler(&mut this): void { + # The prefix `sakura: runtime error: `, the description of the callback error, + # and a new line, as the image holds its texts. + val report: u64[3] = [32, 23, 37]; + this.stranger = this.text.length; + this.text.alu_imm(alu::band, reg::rsp, -16); + this.text.alu_imm(alu::sub, reg::rsp, 64); + this.text.mov_imm(reg::rcx, 0xFFFFFFF4); # STD_ERROR_HANDLE + this.call_system(system_get_std_handle); + this.text.store(8, at(reg::rsp, 48), reg::rax); + for i in 0..3u { + val text := this.texts_at + 16 * report[i]; + this.text.load(8, false, reg::rcx, at(reg::rsp, 48)); + this.text.load(8, false, reg::rdx, amd64::absolute(this.rodata_base + text)); + this.text.load(8, false, reg::r8, amd64::absolute(this.rodata_base + text + 8)); + this.text.lea(reg::r9, at(reg::rsp, 40)); + this.text.store_imm(at(reg::rsp, 32), 0); + this.call_system(system_write_file); + } + this.text.mov_imm(reg::rcx, 1); + this.call_system(system_exit_process); + this.text.ud2(); +} + +#! Writes where a thread the program starts begins, as Windows begins one, with +#! its record in `rcx`. It runs on the stack the system made it, as the first +#! thread runs on the one the file asked. It points the thread's slot at the +#! record, finds where its stack ends, as the start does, runs +#! `runtime::thread_main` with no frame before it, and ends by returning. +#! @param this The building. +def building::beginning_handler(&mut this): void { + val kept: reg[8] = [reg::rbp, reg::rbx, reg::rsi, reg::rdi, reg::r12, reg::r13, reg::r14, reg::r15]; + this.beginning = this.text.length; + for k in 0..8u { + this.text.push(kept[k]); + } + this.text.alu_imm(alu::sub, reg::rsp, 56); + this.text.mov(reg::r15, reg::rcx); + this.text.load(8, false, reg::rax, amd64::absolute(this.state_address(state_own))); + this.text.store(8, own_at(reg::rax), reg::r15); + + # The stack grows down from its high end to its low; the reserve past the + # limit, which a trap's report runs in, is at the low end. + this.text.lea(reg::rcx, at(reg::rsp, 32)); + this.text.lea(reg::rdx, at(reg::rsp, 40)); + this.call_system(system_stack_limits); + this.text.load(8, false, reg::rax, at(reg::rsp, 32)); + this.text.store(8, at(reg::r15, (8 * state_trap_frame) as i32), reg::rax); + this.text.alu_imm(alu::add, reg::rax, (stack_reserve + 65536) as i32); + this.text.store(8, at(reg::r15, (8 * state_limit) as i32), reg::rax); + this.text.load(8, false, reg::rax, at(reg::rsp, 40)); + this.text.store(8, at(reg::r15, (8 * state_base) as i32), reg::rax); + this.text.mov_imm(reg::rbp, 0); + this.call_to(this.helper_of(helper::thread_main)); + this.text.alu_imm(alu::add, reg::rsp, 56); + for k in 0..8u { + this.text.pop(kept[8 - 1 - k]); + } + this.text.mov_imm(reg::rax, 0); + this.text.ret(); +} + +#! `clone`: a thread of the system, which runs `beginning` with the record. The +#! system makes its stack, which it reserves as large as the first thread's and +#! commits as it grows, and writes its number in the record. The thread's +#! handle, which reaping it waits on, is kept in the record. The record +#! and `rsp` are kept in `rsi` and `rdi`, which C keeps on Windows. +#! @param this The selector. +#! @param index The instruction. +#! @param held The instruction. +def selector::clone_thread_windows(&mut this, index: u32, held: &inst): void { + val record := this.word_reg(this.body.arg(index, 0), index, reg::rdx); + this.b.text.mov(reg::rsi, record); + this.b.text.mov(reg::rdi, reg::rsp); + this.b.text.alu_imm(alu::band, reg::rsp, -16); + this.b.text.alu_imm(alu::sub, reg::rsp, 48); + this.b.text.mov_imm(reg::rcx, 0); + this.b.text.load(8, false, reg::rdx, at(reg::rsi, (8 * state_map_size) as i32)); # The bytes of stack to reserve. + this.b.text.mov_imm(reg::r8, this.b.text_base + this.b.beginning); + this.b.text.mov(reg::r9, reg::rsi); + this.b.text.store_imm(at(reg::rsp, 32), 0x10000); # STACK_SIZE_PARAM_IS_A_RESERVATION + this.b.text.lea(reg::rax, at(reg::rsi, (8 * state_tid) as i32)); + this.b.text.store(8, at(reg::rsp, 40), reg::rax); + this.b.call_system(system_create_thread); + this.b.text.mov(reg::rsp, reg::rdi); + this.b.text.test(reg::rax, reg::rax); + val failed := this.b.text.jcc(cc::equal); + this.b.text.store(8, at(reg::rsi, (8 * state_handle) as i32), reg::rax); + this.b.text.load(8, false, reg::rax, at(reg::rsi, (8 * state_tid) as i32)); + val started := this.b.text.jmp(); + this.b.text.land(failed); + this.b.text.mov_imm(reg::rax, (-11) as i64 as u64); # EAGAIN, the VM's default. + this.b.text.land(started); + this.put(held.result, reg::rax); +} + + +# The file. + +#! Writes the executable as a PE file: its sections, then how each function +#! unwinds, which the system reads to unwind a thread's stack, as exceptions +#! and debuggers do. Where debugging information is asked for, the executable +#! names the PDB file written beside it, which Windows' debuggers read, and +#! holds the DWARF other debuggers read, in sections the system loads but only +#! debuggers read. +#! @param this The building. +#! @param data The bytes of the data segment, the globals and the table of +#! addresses among the zeros. +def building::write_pe(&mut this, data: span): void { + var image := pe::image::new(base_address, this.text_base + this.start); + image.stack_reserve = 4 * this.stack + 0x100000; + image.stack_commit = 0x10000; + image.imports = pe::directory { address = this.rodata_base + this.descriptors, size = 20 * (this.library_count + 1) }; + image.iat = pe::directory { address = this.got, size = this.import_words * 8 }; + val parts := this.loaded_parts(data); + for k in 0..4u { + val part: loaded_part = parts[k]; + image.section(part.name, part.address, part.data, part.size, part.flags); + } + + # How each function unwinds: the records, then the table naming each + # function's, which the exception directory names, each a page past the last. + var address := round_up(this.late_base + this.late.length, page_size); + var unwinding := pe::unwind_table::new(); + var functions := pe::function_table::new(); + this.unwind_functions(&mut unwinding, &mut functions, address); + image.section(".xdata", address, unwinding.bytes.view(), unwinding.bytes.length, pe::readable); + address = round_up(address + unwinding.bytes.length, page_size); + val table := functions.bytes(); + image.section(".pdata", address, table.view(), table.length, pe::readable); + image.exceptions = pe::directory { address = address, size = table.length }; + address = round_up(address + table.length, page_size); + if !this.options.debug { + val bytes := this.pe_file(&mut image); + this.write_executable(bytes.view()); + return; + } + + # The debug directory naming the PDB file, by its path and, once the file is + # written, its GUID, then the DWARF; the writers holding them live until the + # file is written. + val directory := build_directory(); + val pdb_path := pdb_path_of(this.options.output, directory.view()); + val record := pe::codeview_record(1, pdb_path.view()); + var named := byte_writer::new(); + pe::debug_entry(&mut named, pe::debug_codeview, (address + pe::debug_entry_bytes - base_address) as u32, record.length as u32); + named.put(record.view()); + image.section(".buildid", address, named.view(), named.length, pe::readable); + image.debug = pe::directory { address = address, size = pe::debug_entry_bytes }; + address = round_up(address + named.length, page_size); + var described := write_dwarf(this, directory.view()); + for k in 0..debug_names.length { + address = this.embed_section(&mut image, debug_names[k], address, described.section(k)); + } + var bytes := this.pe_file(&mut image); + if !describe_pdb(this, &mut bytes, pdb_path.view(), directory.view()) { + this.problem($"The debugging information could not be written to {pdb_path}."); + return; + } + this.write_executable(bytes.view()); +} + +#! Adds a section of debugging information at an address, giving where the next +#! would begin. +#! @param this The building. +#! @param image The executable. +#! @param name The section's name. +#! @param address Where it is loaded. +#! @param part Its bytes. +#! @returns Where a section after it would begin. +def building::embed_section(&this, image: &mut pe::image, name: strview, address: u64, part: &byte_writer): u64 { + image.section(name, address, part.view(), part.length, pe::readable | pe::discardable); + return round_up(address + part.length, page_size); +} + +#! The bytes of a PE executable, its functions named. +#! @param this The building. +#! @param image The executable. +#! @returns The bytes. +def building::pe_file(&this, image: &mut pe::image): byte_writer { + var named := vector::::new(); + this.name_code(&mut named); + for &each in named { + image.symbols.append(pe::symbol { name = each.name, address = each.address }); + } + return image.file(); +} + +#! Writes an executable's bytes to its file. +#! @param this The building. +#! @param bytes The bytes. +def building::write_executable(&mut this, bytes: span): void { + if !write_bytes(this.options.output, bytes, 0o755) { + this.problem($"The executable could not be written to {this.options.output}."); + } +} + + +# Unwinding. + +#! The register `rbp`, as unwinding numbers it. +const unwind_rbp: u8 = 5; + +#! Whether code at an offset is `sub rsp, BYTES`, as a handler's prologue is. +#! @param this The building. +#! @param at The offset, within the code. +#! @param bytes The bytes taken, below 128. +#! @returns Whether it is. +def building::takes_stack(&this, at: u64, bytes: u64): bool { + val code := &this.text.bytes; + return code.get_byte(at) == 0x48 && code.get_byte(at + 1) == 0x83 && code.get_byte(at + 2) == 0xEC && code.get_byte(at + 3) as u64 == bytes; +} + +#! Adds a piece of code's record of unwinding, and names it in the table. +#! @param this The building. +#! @param unwinding The records. +#! @param functions The table. +#! @param xdata Where the records are. +#! @param begin Where the code begins, within the code. +#! @param end Where it ends. +#! @param info Its record. +def building::unwinds(&this, unwinding: &mut pe::unwind_table, functions: &mut pe::function_table, xdata: u64, begin: u64, end: u64, info: &pe::unwind_info): void { + val at := unwinding.add(info); + val code := this.text_base - base_address; + functions.add((code + begin) as u32, (code + end) as u32, (xdata - base_address + at as u64) as u32); +} + +#! Writes how each piece of code that moves the stack unwinds: every function, +#! which pushes `rbp`, points it at its frame, then pushes the registers it +#! saves; the trap stub, which makes its frame as a function does; and the +#! start and the handlers Windows calls, which take bytes of the stack or push +#! the registers C keeps. A function's frame is found from `rbp` however the +#! stack moves within it. Its saved registers are below where `rbp` points, so +#! the record says `rbp` points past the frame's base, by as many bytes as +#! hold them, taken as the frame was made, which unwinding gives back before +#! popping `rbp`. Code whose bytes are not those this describes is left +#! undescribed. +#! @param this The building. +#! @param unwinding The records, added. +#! @param functions The table, added. +#! @param xdata Where the records are loaded. +def building::unwind_functions(&this, unwinding: &mut pe::unwind_table, functions: &mut pe::function_table, xdata: u64): void { + val code := &this.text.bytes; + val framed := this.trap_framed - this.trap_stub; + val based := this.trap_based - this.trap_stub; + if based < 256 { + var stub := pe::unwind_info::new(); + stub.pushed(framed as u8, unwind_rbp); + stub.framed(based as u8, unwind_rbp, 0); + this.unwinds(unwinding, functions, xdata, this.trap_stub, this.faults, &stub); + } + + # The handlers taking bytes of the stack, each until the next begins, and + # the start. + val begins: u64[4] = [this.signalled, this.noting, this.catching, this.start]; + val endings: u64[4] = [this.noting, this.catching, this.stranger, this.entry_end]; + val taken: u64[4] = [40, 40, 56, 56]; + for k in 0..4u { + continue if !this.takes_stack(begins[k], taken[k]); + var handler := pe::unwind_info::new(); + handler.allocated(4, taken[k]); + this.unwinds(unwinding, functions, xdata, begins[k], endings[k], &handler); + } + + # Where a thread begins pushes the registers C keeps, then takes bytes. + val kept: u8[8] = [5, 3, 6, 7, 12, 13, 14, 15]; + var beginning := pe::unwind_info::new(); + var at := this.beginning; + var pushes := true; + for k in 0..8u { + val wide := kept[k] >= 8; + if wide { + pushes = pushes && code.get_byte(at) == 0x41; + at++; + } + pushes = pushes && code.get_byte(at) == 0x50 + (kept[k] & 7); + at++; + beginning.pushed((at - this.beginning) as u8, kept[k]); + } + if pushes && this.takes_stack(at, 56) { + beginning.allocated((at + 4 - this.beginning) as u8, 56); + this.unwinds(unwinding, functions, xdata, this.beginning, this.overflow_stub, &beginning); + } + + for i in 0..this.c.program.functions.length { + val start := this.starts[i]; + continue if start == this.missing || this.ends[i] <= start; + val saved_at := this.debug.saved_at[i] as u64; + continue if saved_at > 255 || code.get_byte(start) != 0x55 || code.get_byte(start + 1) != 0x48 || code.get_byte(start + 2) != 0x89 || code.get_byte(start + 3) != 0xE5; + + # The registers saved, in the order they were pushed, the last ending where + # the saving does. + val saves := this.debug.saves[i]; + var registers: u8[5]; + var count: u64 = 0; + for &r in kept_gprs { + if (saves & (1u << r as u64) as u32) != 0 { + registers[count] = r as u8; + count++; + } + } + var ends: u64[5]; + var pushed := saved_at; + var k := count; + while k > 0 { + k--; + ends[k] = pushed; + pushed -= registers[k] >= 8 ? 2 : 1; + } + + val below := 16 * ((count + 1) / 2); + var info := pe::unwind_info::new(); + info.pushed(1, unwind_rbp); + if below != 0 { + info.allocated(4, below); + } + info.framed(4, unwind_rbp, below); + for s in 0..count { + info.saved(ends[s] as u8, registers[s], below - 8 * (s + 1)); + } + this.unwinds(unwinding, functions, xdata, start, this.ends[i], &info); + } +} diff --git a/runtime/abi.sakura b/runtime/abi.sakura new file mode 100644 index 00000000..2bc950f5 --- /dev/null +++ b/runtime/abi.sakura @@ -0,0 +1,224 @@ +#! @file abi.sakura +#! @author John Christman (sorakatadzuma@gmail.com) +#! @copyright Malunal Studios, LLC. +#! @license MIT +#! +#! Contains what the runtime of an executable shares with the code the compiler +#! generates: the intrinsics it calls the kernel and stops with, and the records +#! the compiler writes the program's layouts, functions, and globals in. +#! +#! The runtime of executables made by `sakura build`, which is compiled into +#! each of them. It is a library of its own, found beside the compiler as +#! `core` is, and needs nothing of std. Each of its files says +#! `when backend == native`, so it is no part of a program a machine runs, +#! which does what it does itself. It formats no text itself, since that is +#! what it does for the program, and works through pointers. Values may be +#! allocated before `` runs, so the runtime's `val`s are numbers known +#! while compiling, which globals begin with, and its `var`s begin as zeros and +#! are set up on first use. + +module runtime when backend == native; + +#! Calls the kernel, giving the negated error number when the call fails. +#! @param n The number of the system call. +#! @param a Its first argument. +#! @param b Its second argument. +#! @param c Its third argument. +#! @param d Its fourth argument. +#! @param e Its fifth argument. +#! @param f Its sixth argument. +#! @returns What the kernel gives, which is the negated error number where the +#! call fails. +@intrinsic def syscall(n: i64, a: u64, b: u64, c: u64, d: u64, e: u64, f: u64): i64; + +#! The frame of the calling function. +#! @returns The frame's first byte. +@intrinsic def frame(): *mut u8; + +# The record of the running thread, which `gs` points at. +@intrinsic def current(): *mut state; + +# Starts a thread of the system on the record's stack, which runs `thread_main` +# there, giving its number, or a negative error number. +@intrinsic def clone_thread(record: *mut state): i64; + +#! Stops the program with the error, reporting where it happened. +#! @param code The error, as the machine numbers them. +#! @remarks It does not return. +@intrinsic def trap(code: i64): void; + +#! An array of its parts, without copying them. + +#! The image the executable was built with. +#! @returns The image, which lives as long as the program does. +@intrinsic def executable(): *image; + +# The records an executable is built with, which `native/native.sakura` writes. +# Every field is a word, so the compiler places them where the builder does, but +# for those of the line tables, which are as narrow as what they hold allows. + +struct layout { + var kind: u64; #! A `layout_kind` of `sources/program.h`. + var access: u64; #! An `access` of `sources/program.h`. + var bits: u64; + var size: u64; + var align: u64; + var frame: u64; + var element: *layout; #! Of an array. + var fields: *field; + var count: u64; + var flags: u64; #! `layout_niche`, `layout_texts`, and `layout_views`. + var name: *u8; + var name_length: u64; +} + +#! Set where a union is laid out without a tag: it holds its field of bytes where +#! its first word is not null, and its empty one where it is. +val layout_niche := 2u; + +#! Set where the value is text, written as the bytes it holds rather than as its +#! fields. The field saying where they begin is at `flags >> 8`, and the one +#! saying how many there are is the field after it. +val layout_texts := 4u; +val layout_views := 8u; +val layout_text_at := 8u; + +struct field { + var layout: *layout; + var offset: u64; + var name: *u8; + var name_length: u64; +} + +# Where the code of a function from an offset on was written: the line and +# column, the path among the image's, and one more than the site of the function +# inlined there it was the code of, or 0. +struct line { + var offset: u32; + var line: u32; + var column: u16; + var path: u16; + var site: u32; +} + +# Where a function's code was inlined within another's: the function inlined, +# where it was called, and one more than the site that call is within, or 0 for +# the function's own code. +struct site { + var function: u32; + var line: u32; + var column: u16; + var path: u16; + var parent: u32; +} + +struct function { + var start: u64; + var end: u64; + var name: *u8; + var name_length: u64; + var lines: *line; + var line_count: u64; + var runtime: u64; #! Whether it belongs to the runtime, which traces leave out. +} + +struct text { + var bytes: *u8; + var length: u64; +} + +# A thread's record, which `gs` points at in the thread, as `native/native.sakura` +# lays it out: the first thread's is the executable's state, written by its start +# before the runtime starts, which also holds what every thread shares, and every +# other is mapped where the thread starts. The records are a list from the first. +struct state { + var shadow_base: *mut u8; #! The top of the stack, where frames begin. + var shadow_limit: *mut u8; #! The lowest a frame may reach. + var trap_frame: *mut u8; #! The bottom of the stack, past the limit, which a trap's report may use. + var itself: *mut state; #! The record itself. + var argc: u64; #! The arguments the program started with, in the first. + var argv: *mut u64; + var reporting: u64; #! Whether a trap is being reported, in the first. + var c_top: u64; + var c_frame: u64; #! Where the program called C last. + var c_return: u64; + var features: u64; #! The vector instructions the program uses, in the first. + var signals: u64; #! The signals noted, in the first, and none in the others. + var spare_word: u64; + var next: *mut state; #! The next thread's record. + var tid: u64; #! The system's number for the thread, cleared by the system as it ends. + var cache: *mut block_cache; #! The blocks it takes and gives back without the lock, once there are threads. + var builders: *mut builder; #! The text being formatted, innermost last. + var builder_count: u64; + var builder_capacity: u64; + var body: def(*mut u8): void; #! The function the thread runs, and the context it is given. + var context: *mut u8; + var map: *mut u8; #! Where its stack is mapped, and its bytes. + var map_size: u64; + var spare_map: u64[2]; + var running: u64; #! 1 while it runs, and 0 once its function has returned. + var spare: u64[5]; +} + +struct image { + var state: *mut state; + var layouts: *layout; + var layout_count: u64; + var functions: *function; + var function_count: u64; + var texts: *text; + var text_count: u64; + var globals: *mut u8; + var globals_size: u64; + var spare_image: u64; + var vtables: **layout; #! Of what each vtable's trait references refer to. + var vtable_count: u64; + var paths: *text; #! The paths the line tables name. + var sites: *site; #! Where the functions inlined were, which the line tables name. +} + +# The texts of an image, where those before `text_out_of_memory` describe the +# errors of `machine_error` in `include/malunal/sakura.h` by their codes. +val error_aborted: i64 = 21; # `MACHINE_ERROR_ABORTED`, what `abort` reports with. +val error_faulted: i64 = 26; # What `fault` reports with, before the text it was given. +val text_out_of_memory := 31u; +val text_prefix := 32u; # `sakura: runtime error: ` +val text_at := 33u; # ` at ` +val text_open := 34u; # ` (` +val text_colon := 35u; # `:` +val text_close := 36u; # `)` and a new line +val text_newline := 37u; + +# Errors the runtime traps with, the codes of `machine_error`. +val error_out_of_bounds: i64 = 4; +val error_null_reference: i64 = 5; +val error_division: i64 = 6; +val error_invalid_release: i64 = 11; +val error_invalid_alignment: i64 = 14; +val error_out_of_memory: i64 = 31; + +# The layout kinds of `sources/program.h`. +val kind_void := 0u; +val kind_int := 1u; +val kind_uint := 2u; +val kind_float := 3u; +val kind_bool := 4u; +val kind_reference := 5u; +val kind_trait := 6u; +val kind_fixed := 7u; +val kind_struct := 8u; +val kind_union := 9u; +val kind_function := 10u; +val kind_pointer := 11u; + +# The accesses of `sources/program.h`. +val access_i8 := 0u; +val access_u8 := 1u; +val access_i16 := 2u; +val access_u16 := 3u; +val access_i32 := 4u; +val access_u32 := 5u; +val access_i64 := 6u; +val access_f32 := 7u; +val access_f64 := 8u; +val access_bytes := 9u; diff --git a/runtime/float.sakura b/runtime/float.sakura new file mode 100644 index 00000000..6f75b539 --- /dev/null +++ b/runtime/float.sakura @@ -0,0 +1,592 @@ +#! @file float.sakura +#! @author John Christman (sorakatadzuma@gmail.com) +#! @copyright Malunal Studios, LLC. +#! @license MIT +#! +#! Contains how an executable formats a float, as the virtual machine does. +#! +#! Formats a float as `machine__format_float` of `sources/machine.c` does with +#! the C library: whole numbers below 1e15 as integers, and otherwise the +#! shortest `%.*g` text, from 1 to 17 digits, that reads back as the same value. +#! The digits are exact, from arithmetic on big integers, rounded half to even +#! as `printf` rounds them, and reading back rounds to the nearest double as +#! `strtod` does. + +module runtime when backend == native; + +# Big integers are words in memory: their number of limbs, then the limbs, each +# holding 32 bits from the least significant. +val limbs := 128u; +val limb := 4294967296u; + +var big_n: *mut u64; +var big_d: *mut u64; +var big_c: *mut u64; +var big_t: *mut u64; +var big_u: *mut u64; # The midpoint above the value, scaled as it is. +var big_l: *mut u64; # The midpoint below it. +var big_m: *mut u64; # A margin around the midpoints, for single precision. +var big_q: *mut u64; + +# Room for rounding a decimal exactly, apart from the digits being checked. +var exact_n: *mut u64; +var exact_d: *mut u64; +var exact_c: *mut u64; +var exact_t: *mut u64; + +# The digits of the value, which are 18 so any precision can be rounded, and +# whether any digit after them would not be zero. +var digits: *mut u8; +var sticky: bool; + +var float_bits: u64; + +def big(): *mut u64 { + return acquire((limbs + 1) * 8) as *mut u64; +} + +def big_trim(a: *mut u64): void { + while a[0] > 0 && a[a[0]] == 0 { + a[0] = a[0] - 1; + } +} + +def big_set(a: *mut u64, value: u64): void { + a[0] = 2; + a[1] = value % limb; + a[2] = value / limb; + big_trim(a); +} + +def big_copy(a: *mut u64, b: *mut u64): void { + for i in 0..b[0] + 1 { + a[i] = b[i]; + } +} + +def big_mul_small(a: *mut u64, factor: u64): void { + var carry := 0u; + for i in 1..a[0] + 1 { + val product := a[i] * factor + carry; + a[i] = product % limb; + carry = product / limb; + } + while carry > 0 { + a[0] = a[0] + 1; + a[a[0]] = carry % limb; + carry = carry / limb; + } +} + +def big_mul_ten(a: *mut u64, power: u64): void { + var left := power; + while left >= 9 { + big_mul_small(a, 1000000000); + left = left - 9; + } + while left > 0 { + big_mul_small(a, 10); + left--; + } +} + +def big_shl(a: *mut u64, bits: u64): void { + if a[0] == 0 { + return; + } + val words := bits / 32; + val shift := bits % 32; + var i := a[0] + words + 1; + while i > words { + val index := i - words; + val high := index <= a[0] ? a[index] : 0; + val low := index - 1 >= 1 && index - 1 <= a[0] ? a[index - 1] : 0; + a[i] = shift == 0 ? high : ((high << shift) | (low >> (32 - shift))) % limb; + i--; + } + while i > 0 { + a[i] = 0; + i--; + } + a[0] = a[0] + words + 1; + big_trim(a); +} + +def big_shr1(a: *mut u64): void { + for i in 1..a[0] + 1 { + val high := i < a[0] ? a[i + 1] : 0; + a[i] = (a[i] >> 1) | ((high & 1) << 31); + } + big_trim(a); +} + +def big_compare(a: *mut u64, b: *mut u64): i64 { + if a[0] != b[0] { + return a[0] < b[0] ? -1 : 1; + } + var i := a[0]; + while i > 0 { + if a[i] != b[i] { + return a[i] < b[i] ? -1 : 1; + } + i--; + } + return 0; +} + +# Subtracts `b` from `a`, which is at least `b`. +def big_sub(a: *mut u64, b: *mut u64): void { + var borrow := 0u; + for i in 1..a[0] + 1 { + val take := (i <= b[0] ? b[i] : 0) + borrow; + if a[i] >= take { + a[i] = a[i] - take; + borrow = 0; + } + else { + a[i] = a[i] + limb - take; + borrow = 1; + } + } + big_trim(a); +} + +def big_bits(a: *mut u64): u64 { + if a[0] == 0 { + return 0; + } + var top := a[a[0]]; + var count := (a[0] - 1) * 32; + while top > 0 { + count++; + top = top >> 1; + } + return count; +} + +def bits_of(value: f64): u64 { + ((&mut float_bits) as *mut f64)[0] = value; + return float_bits; +} + +def float_of(bits: u64): f64 { + float_bits = bits; + return ((&mut float_bits) as *mut f64)[0]; +} + +def start_float(): void { + if big_n != null { + return; + } + big_n = big(); + big_d = big(); + big_c = big(); + big_t = big(); + big_u = big(); + big_l = big(); + big_m = big(); + big_q = big(); + exact_n = big(); + exact_d = big(); + exact_c = big(); + exact_t = big(); + digits = acquire(32); +} + +# Writes the first 18 digits of a positive finite value, `n` units of two to +# `unit`, giving the decimal exponent of the first, so the value is `0.d1d2...` +# times ten to it plus one. The midpoints `u` and `l` and the margin `m`, in the +# same units, are scaled with the value, so they compare with it as it is written. +def decimal_digits(unit: i64, binary: i64): i64 { + big_set(big_d, 1); + if unit >= 0 { + big_shl(big_n, unit as u64); + big_shl(big_u, unit as u64); + big_shl(big_l, unit as u64); + big_shl(big_m, unit as u64); + } + else { + big_shl(big_d, (0 - unit) as u64); + } + + # An estimate of the decimal exponent, corrected so `1 <= n / d < 10`. + var power := ((binary as f64) * 0.30102999566398114) as i64; + if (binary as f64) * 0.30102999566398114 < power as f64 { + power--; + } + if power >= 0 { + big_mul_ten(big_d, power as u64); + } + else { + scale_value(0 - power); + } + + while big_compare(big_n, big_d) < 0 { + scale_value(1); + power--; + } + big_copy(big_t, big_d); + big_mul_small(big_t, 10); + while big_compare(big_n, big_t) >= 0 { + big_mul_small(big_d, 10); + big_copy(big_t, big_d); + big_mul_small(big_t, 10); + power++; + } + + big_copy(big_t, big_n); + for i in 0..18 { + var digit: u8 = 0; + while big_compare(big_t, big_d) >= 0 { + big_sub(big_t, big_d); + digit++; + } + digits[i] = digit; + big_mul_small(big_t, 10); + } + sticky = big_t[0] != 0; + return power; +} + +# Multiplies the value, its midpoints, and the margin by a power of ten. +def scale_value(power: i64): void { + big_mul_ten(big_n, power as u64); + big_mul_ten(big_u, power as u64); + big_mul_ten(big_l, power as u64); + big_mul_ten(big_m, power as u64); +} + +# Rounds the digits to a precision half to even, into `rounded`, giving whether +# they carried into a new first digit. +var rounded: *mut u8; + +def round_digits(precision: u64): bool { + for i in 0..precision { + rounded[i] = digits[i]; + } + + val next := digits[precision]; + var rest := sticky; + for i in precision + 1..18 { + rest = rest || digits[i] != 0; + } + val up := next > 5 || (next == 5 && (rest || rounded[precision - 1] % 2 == 1)); + if !up { + return false; + } + + var i := precision; + while i > 0 { + i--; + if rounded[i] < 9 { + rounded[i] = rounded[i] + 1; + return false; + } + rounded[i] = 0; + } + rounded[0] = 1; + return true; +} + +# The double nearest the decimal `0.r1r2...rp` times ten to `power` plus one, +# rounding half to even as `strtod` does. +def nearest_double(precision: u64, power: i64): f64 { + big_set(exact_n, 0); + for i in 0..precision { + big_mul_small(exact_n, 10); + val add := exact_c; + big_set(add, rounded[i] as u64); + add_into(exact_n, add); + } + big_set(exact_d, 1); + val scale := power - (precision as i64) + 1; + if scale >= 0 { + big_mul_ten(exact_n, scale as u64); + } + else { + big_mul_ten(exact_d, (0 - scale) as u64); + } + + # The binary exponent puts 53 bits in the quotient, unless it would pass the + # least exponent, which leaves a subnormal with fewer. + var binary := big_bits(exact_n) as i64 - big_bits(exact_d) as i64 - 53; + if binary < -1074 { + binary = -1074; + } + while true { + big_copy(exact_t, exact_d); + if binary >= 0 { + big_shl(exact_t, binary as u64); + } + val numerator := exact_c; + big_copy(numerator, exact_n); + if binary < 0 { + big_shl(numerator, (0 - binary) as u64); + } + + # The quotient must be below 2^53, and at least 2^52 unless subnormal. + val top := big(); + big_copy(top, exact_t); + big_shl(top, 53); + if big_compare(numerator, top) >= 0 { + dispose(top as *mut u8, (limbs + 1) * 8); + binary++; + continue; + } + big_shr1(top); + if big_compare(numerator, top) < 0 && binary > -1074 { + dispose(top as *mut u8, (limbs + 1) * 8); + binary--; + continue; + } + + # Divides a bit at a time, then rounds by the remainder. + big_shl(top, 1); + var quotient := 0u; + for i in 0..53 { + big_shr1(top); + quotient = quotient * 2; + if big_compare(numerator, top) >= 0 { + big_sub(numerator, top); + quotient++; + } + } + big_shl(numerator, 1); + val order := big_compare(numerator, exact_t); + dispose(top as *mut u8, (limbs + 1) * 8); + if order > 0 || (order == 0 && quotient % 2 == 1) { + quotient++; + } + if quotient == 9007199254740992 { + quotient = 4503599627370496; + binary++; + } + + if quotient < 4503599627370496 { + return float_of(quotient); + } + val biased := binary + 1075; + if biased >= 2047 { + return float_of(0x7FF0000000000000); + } + return float_of(((biased as u64) << 52) | (quotient - 4503599627370496)); + } + return 0.0; +} + +def add_into(a: *mut u64, b: *mut u64): void { + var carry := 0u; + var i := 1u; + while i <= a[0] || i <= b[0] || carry > 0 { + val sum := (i <= a[0] ? a[i] : 0) + (i <= b[0] ? b[i] : 0) + carry; + a[i] = sum % limb; + carry = sum / limb; + if i > a[0] { + a[0] = i; + } + i++; + } + big_trim(a); +} + +# Writes the rounded digits in the style `%g` chooses for the precision and the +# decimal exponent, without trailing zeros. +def put_general(into: *mut builder, precision: u64, power: i64): void { + var used := precision; + while used > 1 && rounded[used - 1] == 0 { + used--; + } + + if power < (precision as i64) && power >= -4 { + if power < 0 { + put(into, '0'); + put(into, '.'); + for i in 0..(0 - power - 1) as u64 { + put(into, '0'); + } + for i in 0..used { + put(into, '0' + rounded[i]); + } + return; + } + + val whole := power as u64 + 1; + for i in 0..whole { + put(into, i < used ? '0' + rounded[i] : '0'); + } + if used > whole { + put(into, '.'); + for i in whole..used { + put(into, '0' + rounded[i]); + } + } + return; + } + + put(into, '0' + rounded[0]); + if used > 1 { + put(into, '.'); + for i in 1..used { + put(into, '0' + rounded[i]); + } + } + put(into, 'e'); + put(into, power < 0 ? '-' : '+'); + val magnitude := power < 0 ? (0 - power) as u64 : power as u64; + if magnitude < 10 { + put(into, '0'); + } + put_unsigned(into, magnitude); +} + +def put_float(into: *mut builder, value: f64, single: bool): void { + if value != value { + put(into, 'n'); + put(into, 'a'); + put(into, 'n'); + return; + } + + val bits := bits_of(value); + val sign := (bits >> 63) != 0; + val field := (bits >> 52) & 2047; + if field == 2047 { + if sign { + put(into, '-'); + } + put(into, 'i'); + put(into, 'n'); + put(into, 'f'); + return; + } + + # Whole numbers are written without an exponent while they are exact. + if value > -1000000000000000.0 && value < 1000000000000000.0 && value == (value as i64) as f64 { + if sign && value == 0.0 { + put(into, '-'); + } + put_signed(into, value as i64); + return; + } + + start_float(); + if rounded == null { + rounded = acquire(32); + } + if sign { + put(into, '-'); + } + + # The value in units a quarter of its gap, with the midpoints to the values + # beside it, where the one below is nearer at a power of two. A single is + # measured in its own gaps, with a margin of the gaps of doubles beside it. + val magnitude := float_of(bits & 0x7FFFFFFFFFFFFFFF); + var unit: i64 = 0; + var binary: i64 = 0; + var even: bool = false; + if single { + ((&mut float_bits) as *mut f32)[0] = magnitude as f32; + val narrow := float_bits & 0xFFFFFFFF; + val exponent := (narrow >> 23) & 255; + val mantissa := exponent == 0 ? narrow & 0x7FFFFF : (narrow & 0x7FFFFF) | 0x800000; + val scale := exponent == 0 ? -149 : (exponent as i64) - 150; + big_set(big_n, mantissa); + big_shl(big_n, 30); + big_set(big_u, mantissa * 2 + 1); + big_shl(big_u, 29); + big_set(big_l, mantissa == 0x800000 && exponent > 1 ? mantissa * 4 - 1 : mantissa * 2 - 1); + big_shl(big_l, mantissa == 0x800000 && exponent > 1 ? 28 : 29); + big_set(big_m, 2); + unit = scale - 30; + binary = scale + big_bits(big_n) as i64 - 31; + even = mantissa % 2 == 0; + } + else { + val mantissa := field == 0 ? bits & 0xFFFFFFFFFFFFF : (bits & 0xFFFFFFFFFFFFF) | 0x10000000000000; + val scale := field == 0 ? -1074 : (field as i64) - 1075; + big_set(big_n, mantissa * 4); + big_set(big_u, mantissa * 4 + 2); + big_set(big_l, mantissa == 0x10000000000000 && field > 1 ? mantissa * 4 - 1 : mantissa * 4 - 2); + big_set(big_m, 0); + unit = scale - 2; + binary = scale + big_bits(big_n) as i64 - 3; + even = mantissa % 2 == 0; + } + val power := decimal_digits(unit, binary); + + # The shortest precision whose digits read back as the value: those strictly + # between the midpoints, or on one when ties go to the value, being even. + var precision := 1u; + while precision <= 17 { + val carried := round_digits(precision); + val shifted := carried ? power + 1 : power; + var digits_value := 0u; + for i in 0..precision { + digits_value = digits_value * 10 + rounded[i] as u64; + } + if carried { + digits_value = digits_value * 10; + } + big_set(big_q, digits_value); + big_copy(big_t, big_d); + big_mul_u64(big_t, big_q); + + val above := big_compare(big_t, big_u); + val below := big_compare(big_t, big_l); + var same := (above < 0 || (above == 0 && even)) && (below > 0 || (below == 0 && even)); + + # A single reads back through a double, whose rounding matters near a midpoint. + if single && !(above < 0 && below > 0 && clear_of_midpoints()) && !(above > 0 || below < 0) || single && near_outside() { + val back := nearest_double(precision, shifted); + same = (back as f32) == (magnitude as f32); + } + + if same || precision == 17 { + put_general(into, precision, shifted); + return; + } + + big_mul_small(big_u, 10); + big_mul_small(big_l, 10); + big_mul_small(big_m, 10); + precision++; + } +} + +# Whether the candidate in `t` is inside the midpoints by more than the margin. +def clear_of_midpoints(): bool { + big_copy(big_c, big_t); + add_into(big_c, big_m); + if big_compare(big_c, big_u) >= 0 { + return false; + } + big_copy(big_c, big_l); + add_into(big_c, big_m); + return big_compare(big_t, big_c) > 0; +} + +# Whether the candidate in `t` is outside the midpoints, but within the margin. +def near_outside(): bool { + big_copy(big_c, big_u); + add_into(big_c, big_m); + if big_compare(big_t, big_u) > 0 && big_compare(big_t, big_c) <= 0 { + return true; + } + big_copy(big_c, big_t); + add_into(big_c, big_m); + return big_compare(big_t, big_l) < 0 && big_compare(big_c, big_l) >= 0; +} + +# Multiplies by a number of at most 64 bits, held in `factor`. +def big_mul_u64(a: *mut u64, factor: *mut u64): void { + if factor[0] <= 1 { + big_mul_small(a, factor[0] == 0 ? 0 : factor[1]); + big_trim(a); + return; + } + big_copy(big_c, a); + big_mul_small(a, factor[1]); + big_mul_small(big_c, factor[2]); + big_shl(big_c, 32); + add_into(a, big_c); +} diff --git a/runtime/format.sakura b/runtime/format.sakura new file mode 100644 index 00000000..aa8a71c1 --- /dev/null +++ b/runtime/format.sakura @@ -0,0 +1,415 @@ +#! @file format.sakura +#! @author John Christman (sorakatadzuma@gmail.com) +#! @copyright Malunal Studios, LLC. +#! @license MIT +#! +#! Contains how an executable builds the text of an interpolation. +#! +#! Interpolation builds text in builders of memory the runtime manages, as +#! `machine__format` of `sources/machine.c` does, then makes a string of it. + +module runtime when backend == native; + +struct builder { + var data: *mut u8; + var length: u64; + var capacity: u64; +} + +val format_depth := 8u; + + +def append(into: *mut builder, bytes: *u8, length: u64): void { + if (*into).length + length > (*into).capacity { + var capacity := (*into).capacity == 0 ? 64 : (*into).capacity; + while capacity < (*into).length + length { + capacity = capacity * 2; + } + val grown := acquire(capacity); + copy_bytes(grown, (*into).data, (*into).length); + dispose((*into).data, (*into).capacity); + (*into).data = grown; + (*into).capacity = capacity; + } + copy_bytes((*into).data + (*into).length, bytes, length); + (*into).length = (*into).length + length; +} + +def put(into: *mut builder, byte: u8): void { + if (*into).length == (*into).capacity { + val capacity := (*into).capacity == 0 ? 64 : (*into).capacity * 2; + val grown := acquire(capacity); + copy_bytes(grown, (*into).data, (*into).length); + dispose((*into).data, (*into).capacity); + (*into).data = grown; + (*into).capacity = capacity; + } + (*into).data[(*into).length] = byte; + (*into).length = (*into).length + 1; +} + +def put_text(into: *mut builder, index: u64): void { + val text := (*executable()).texts + index; + append(into, (*text).bytes, (*text).length); +} + +def put_unsigned(into: *mut builder, value: u64): void { + var power := 1u; + while value / power >= 10 { + power = power * 10; + } + while power > 0 { + put(into, ('0' + value / power % 10) as u8); + power = power / 10; + } +} + +def put_signed(into: *mut builder, value: i64): void { + if value < 0 { + put(into, '-'); + put_unsigned(into, 0 - (value as u64)); + return; + } + put_unsigned(into, value as u64); +} + +def put_hex(into: *mut builder, value: u64): void { + put(into, '0'); + put(into, 'x'); + var shift := 60u; + while shift > 0 && (value >> shift) == 0 { + shift = shift - 4; + } + while true { + val digit := (value >> shift) & 15; + put(into, (digit < 10 ? '0' + digit : 'a' + digit - 10) as u8); + if shift == 0 { + break; + } + shift = shift - 4; + } +} + +def put_word(into: *mut builder, text: *u8, length: u64): void { + append(into, text, length); +} + +def put_name(into: *mut builder, name: *u8, length: u64): void { + append(into, name, length); +} + +# Writes `true`, `false`, `null`, and the other words formatting uses, a byte at a time. +def put_true(into: *mut builder): void { + put(into, 't'); + put(into, 'r'); + put(into, 'u'); + put(into, 'e'); +} + +def put_false(into: *mut builder): void { + put(into, 'f'); + put(into, 'a'); + put(into, 'l'); + put(into, 's'); + put(into, 'e'); +} + +def put_null(into: *mut builder): void { + put(into, 'n'); + put(into, 'u'); + put(into, 'l'); + put(into, 'l'); +} + +def put_separator(into: *mut builder): void { + put(into, ','); + put(into, ' '); +} + +def put_value(into: *mut builder, at: *mut u8, kind: *layout, frame: bool, depth: u64): void { + if depth > format_depth { + put(into, '.'); + put(into, '.'); + put(into, '.'); + return; + } + + val info := executable(); + if (*kind).kind == kind_int || (*kind).kind == kind_uint || (*kind).kind == kind_bool { + # A scalar in memory is read as wide as it is there, as a whole word past + # it may not be memory at all. + var value: u64 = 0; + if frame { + value = word(at); + } else { + read_scalar((&mut scalar_scratch) as *mut u8, at, (*kind).access); + value = scalar_scratch; + } + # An enum is the name of the member of the value. + for i in 0..(*kind).count { + val member := (*kind).fields + i; + if (*member).offset == value { + append(into, (*member).name, (*member).name_length); + return; + } + } + + if (*kind).kind == kind_bool { + if value != 0 { + put_true(into); + } + else { + put_false(into); + } + } + else if (*kind).kind == kind_int { + put_signed(into, value as i64); + } + else { + put_unsigned(into, value); + } + return; + } + + if (*kind).kind == kind_float { + var value := (at as *mut f64)[0]; + if !frame { + read_scalar((&mut scalar_scratch) as *mut u8, at, (*kind).access); + value = ((&mut scalar_scratch) as *mut f64)[0]; + } + put_float(into, value, (*kind).bits <= 32); + return; + } + + # A fixed array holds its elements where it is, and prints as they do. + if (*kind).kind == kind_fixed { + val element := (*kind).element; + if ((*element).kind == kind_int || (*element).kind == kind_uint) && (*element).size == 1 && (*element).count == 0 { + append(into, at, (*kind).count); + return; + } + + put(into, '['); + for i in 0..(*kind).count { + if i > 0 { + put_separator(into); + } + put_value(into, at + i * (*element).size, element, false, depth + 1); + } + put(into, ']'); + return; + } + + if (*kind).kind == kind_reference || (*kind).kind == kind_trait { + val pointer := resolved_pointer(at); + if (*kind).kind == kind_trait { + val vtable := word(at + 8); + if pointer == null || vtable >= (*info).vtable_count { + put_null(into); + return; + } + put_value(into, pointer, (*info).vtables[vtable], false, depth + 1); + return; + } + if pointer == null || (*kind).element == null { + put_null(into); + return; + } + put_value(into, pointer, (*kind).element, false, depth + 1); + return; + } + + if (*kind).kind == kind_struct { + # Text is written as the bytes it holds, not as where they are and how many. + if ((*kind).flags & layout_texts) != 0 { + val index := (*kind).flags >> layout_text_at; + val begins := (*kind).fields + index; + val counts := (*kind).fields + index + 1; + val data := word(at + (*begins).offset) as *u8; + val length := word(at + (*counts).offset); + if data != null && length > 0 { + append(into, data, length); + } + return; + } + + # Any other view is written as the elements it views, as an array of them is. + if ((*kind).flags & layout_views) != 0 { + val index := (*kind).flags >> layout_text_at; + val begins := (*kind).fields + index; + val counts := (*kind).fields + index + 1; + val data := word(at + (*begins).offset) as *mut u8; + val length := data != null ? word(at + (*counts).offset) : 0; + val element := (*kind).element; + put(into, '['); + for i in 0..length { + if i > 0 { + put_separator(into); + } + put_value(into, data + i * (*element).size, element, false, depth + 1); + } + put(into, ']'); + return; + } + + append(into, (*kind).name, (*kind).name_length); + put(into, '{'); + for i in 0..(*kind).count { + val field := (*kind).fields + i; + if i > 0 { + put_separator(into); + } + if (*field).name_length > 0 { + append(into, (*field).name, (*field).name_length); + put(into, ' '); + put(into, '='); + put(into, ' '); + } + put_value(into, at + (*field).offset, (*field).layout, false, depth + 1); + } + put(into, '}'); + return; + } + + if (*kind).kind == kind_function { + val index := word(at); + if index == 0 { + put_null(into); + return; + } + put(into, 'd'); + put(into, 'e'); + put(into, 'f'); + put(into, ' '); + if index - 1 >= (*info).function_count { + put(into, '?'); + return; + } + val function := (*info).functions + (index - 1); + append(into, (*function).name, (*function).name_length); + return; + } + + # A union is written as a struct holding the one field it holds. + if (*kind).kind == kind_union { + val tag := held_field(at, kind); + if tag >= (*kind).count { + put(into, '?'); + return; + } + val field := (*kind).fields + tag; + append(into, (*kind).name, (*kind).name_length); + put(into, '{'); + append(into, (*field).name, (*field).name_length); + put(into, ' '); + put(into, '='); + put(into, ' '); + put_value(into, at + (*field).offset, (*field).layout, false, depth + 1); + put(into, '}'); + return; + } + + if (*kind).kind == kind_pointer { + val address := word(at); + if address == 0 { + put_null(into); + return; + } + put_hex(into, address); + } +} + +# Room to read a scalar or a reference into, since the runtime takes no references to its locals. +struct scratch { + var first: u64; + var second: u64; +} + +var scalar_scratch: u64; +var reference_scratch: scratch; + +# The pointer a reference holds. +def resolved_pointer(at: *mut u8): *mut u8 { + return word(at) as *mut u8; +} + +#! `OP_FORMAT`: begins a string, in the running thread's builders. +def format_begin(): void { + if threaded { + hold(); + } + val me := current(); + if (*me).builder_count == (*me).builder_capacity { + val capacity := (*me).builder_capacity == 0 ? 8 : (*me).builder_capacity * 2; + val grown := acquire(capacity * size_of_builder()) as *mut builder; + copy_bytes(grown as *mut u8, (*me).builders as *mut u8, (*me).builder_count * size_of_builder()); + dispose((*me).builders as *mut u8, (*me).builder_capacity * size_of_builder()); + (*me).builders = grown; + (*me).builder_capacity = capacity; + } + (*((*me).builders + (*me).builder_count)).length = 0; + (*me).builder_count++; + if threaded { + let_go(); + } +} + +def size_of_builder(): u64 { + return size_of::(); +} + +# The builder the running thread appends to. +def innermost(): *mut builder { + val me := current(); + return (*me).builders + ((*me).builder_count - 1); +} + +#! `OP_FORMAT_TEXT`: appends constant text. +#! @param bytes The first byte of the text. +#! @param length How many bytes it holds. +def format_text(bytes: *mut u8, length: u64): void { + if threaded { + hold(); + } + append(innermost(), bytes, length); + if threaded { + let_go(); + } +} + +#! `OP_FORMAT_VALUE`: appends a value in its frame representation. +#! @param at The value, in its frame representation. +#! @param kind The layout of its type, which says how it is written. +def format_value(at: *mut u8, kind: *layout): void { + if threaded { + hold(); + } + put_value(innermost(), at, kind, true, 0); + if threaded { + let_go(); + } +} + +#! `OP_FORMAT_OWNED`: hands the text over in memory the program manages itself, +#! as where it begins and how many bytes it holds, which is what a `string` owns +#! and gives back where its scope ends. Its block is not cleared, as every byte +#! of it is written. +#! @param dst The slot of the `string` to fill: its first word takes where the +#! text begins, and its second how many bytes it holds. +def format_owned(dst: *mut u8): void { + if threaded { + hold(); + } + val me := current(); + (*me).builder_count--; + val done := (*me).builders + (*me).builder_count; + val data := (*done).length > 0 ? allocate((*done).length) : null; + copy_bytes(data, (*done).data, (*done).length); + + val words := dst as *mut u64; + words[0] = data as u64; + words[1] = (*done).length; + if threaded { + let_go(); + } +} diff --git a/runtime/linux_x86_64.sakura b/runtime/linux_x86_64.sakura new file mode 100644 index 00000000..0399de4f --- /dev/null +++ b/runtime/linux_x86_64.sakura @@ -0,0 +1,20 @@ +#! @file linux_x86_64.sakura +#! @author John Christman (sorakatadzuma@gmail.com) +#! @copyright Malunal Studios, LLC. +#! @license MIT +#! +#! Contains the numbers of the system calls the runtime makes on Linux, on +#! x86-64. +#! +#! What the runtime needs to know of Linux on x86-64: the numbers of the system +#! calls it makes. Another platform declares these names in a section of its +#! own. + +module runtime when backend == native && os == linux && arch == x86_64; + +val call_write: i64 = 1; +val call_mmap: i64 = 9; +val call_mprotect: i64 = 10; +val call_munmap: i64 = 11; +val call_mremap: i64 = 25; +val call_exit_group: i64 = 231; diff --git a/runtime/memory.sakura b/runtime/memory.sakura new file mode 100644 index 00000000..5e8e7b06 --- /dev/null +++ b/runtime/memory.sakura @@ -0,0 +1,809 @@ +#! @file memory.sakura +#! @author John Christman (sorakatadzuma@gmail.com) +#! @copyright Malunal Studios, LLC. +#! @license MIT +#! +#! Contains how an executable acquires memory from the kernel and gives it back: +#! the blocks `raw_allocate` takes, and those the runtime keeps for itself. +#! +#! Memory comes from the kernel in chunks, carved into blocks of classes of +#! sizes from 16 to 2048 bytes, which are reused once disposed. Larger blocks +#! are mapped on their own, and some given back are kept to be reused, as +#! `map_large` says. Chunks are opened one after another in a region of +#! address space reserved at once, so whether memory lies in a chunk is a +#! comparison. What is acquired is zeroed where it is asked to be: memory fresh +#! from the kernel already is, and a block reused is cleared for as many bytes +#! as were asked for. + +import system::windows; + +module runtime when backend == native; + +val chunk_size := 1048576u; +val region_size := 68719476736u; # 64 GiB of address space, which takes no memory until opened. +val largest := 2048u; +val classes := 19u; + +var chunk: *mut u8; # Where the next block is carved. +var chunk_left: u64; # The bytes open after it. +var free_lists: *mut *mut u8; + +# The region chunks are opened in: where it begins, where its open chunks end, +# and where it ends. A region that fills is followed by another, and where each +# before it begins and its chunks end are kept, in memory of their own. +var region_low: u64; +var region_high: u64; +var region_end: u64; +var old_regions: *mut u64; +var old_count: u64; +var old_capacity: u64; + +def word(at: *u8): u64 { + return (at as *u64)[0]; +} + +def set_word(at: *mut u8, value: u64): void { + (at as *mut u64)[0] = value; +} +module runtime when backend == native && os == linux; +def map(size: u64): *mut u8 { + val address := syscall(call_mmap, 0, size, 3, 0x22, 0xFFFFFFFFFFFFFFFF, 0); + if address < 0 { + trap(31); + } + return address as *mut u8; +} + +def unmap(address: *mut u8, size: u64): void { + syscall(call_munmap, address as u64, size, 0, 0, 0, 0); +} +module runtime when backend == native; +def pages(size: u64): u64 { + return (size + 4095) / 4096 * 4096; +} + +# Classes step by 16 bytes up to 256, then double up to 2048. +def class_of(size: u64): u64 { + if size <= 256 { + return size == 0 ? 0 : (size + 15) / 16 - 1; + } + if size <= 512 { + return 16; + } + return size <= 1024 ? 17 : 18; +} + +def class_size(class: u64): u64 { + return class < 16 ? (class + 1) * 16 : 512u << (class - 16); +} + +# The class of each size up to `largest`, by `(size + 15) / 16`, and the size of +# each class, worked out while compiling. Classes begin and end at multiples of 16 +# bytes, so the sizes that round up to the same multiple share a class. +const class_by_size: u8[129] = make_class_by_size(); +const size_of_class: u64[19] = make_size_of_class(); + +const def make_class_by_size(): u8[129] { + var made: u8[129]; + for each in 0..129 { + made[each] = class_of((each * 16) as u64) as u8; + } + return made; +} + +const def make_size_of_class(): u64[19] { + var made: u64[19]; + for each in 0..19 { + made[each] = class_size(each as u64); + } + return made; +} + +# The shift that leaves the bits of a hash a set of the capacity is indexed by, +# which is a power of 2. +def shift_for(capacity: u64): u64 { + var shift := 64u; + var rest := capacity; + while rest > 1 { + rest = rest >> 1; + shift--; + } + return shift; +} + +# Where a probe for the address begins in a set indexed by the bits `shift` leaves: +# the top bits of the address times the golden ratio, which spreads addresses that +# differ in any bits across the set. It is one expression, so it is inlined. +def hash(address: u64, shift: u64): u64 { + return (address * 0x9E3779B97F4A7C15) >> shift; +} + +# Carves every size up to 16 bytes, so each block is aligned for any value. +def carve(wanted: u64): *mut u8 { + val size := (wanted + 15) / 16 * 16; + if chunk_left < size { + open_chunk(); + } + val block := chunk; + chunk = chunk + size; + chunk_left = chunk_left - size; + return block; +} +module runtime when backend == native && os == linux; +# Opens the chunk after the last, which what is left of the last runs on into, +# or the first of a new region where this one is full. +def open_chunk(): void { + if region_high + chunk_size > region_end { + reserve(); + chunk = region_high as *mut u8; + chunk_left = 0; + } + if syscall(call_mprotect, region_high, chunk_size, 3, 0, 0, 0) < 0 { + trap(error_out_of_memory); + } + region_high = region_high + chunk_size; + chunk_left = chunk_left + chunk_size; +} + +# Reserves a region without access, so it takes no memory until chunks are opened +# in it: as large as the system allows, down to a chunk. The region before it is +# kept, for `in_chunk`. +def reserve(): void { + if region_low != 0 { + keep_region(); + } + + var size := region_size; + while size >= chunk_size { + val address := syscall(call_mmap, 0, size, 0, 0x4022, 0xFFFFFFFFFFFFFFFF, 0); + if address >= 0 { + region_low = address as u64; + region_high = address as u64; + region_end = address as u64 + size; + return; + } + size = size / 2; + } + trap(error_out_of_memory); +} +module runtime when backend == native; +def keep_region(): void { + if old_count == old_capacity { + val capacity := old_capacity == 0 ? 256u : old_capacity * 2; + val grown := map(pages(capacity * 16)) as *mut u64; + for i in 0..old_count * 2 { + grown[i] = old_regions[i]; + } + if old_regions != null { + unmap(old_regions as *mut u8, pages(old_capacity * 16)); + } + old_regions = grown; + old_capacity = capacity; + } + old_regions[2 * old_count] = region_low; + old_regions[2 * old_count + 1] = region_high; + old_count++; +} + +# Zeroes the words that hold the first `size` bytes of memory aligned to 8 bytes, +# which may run past `size` to the end of its word. Every block is a whole number +# of words, so that is still within it. `memset` does so sixteen bytes at a time +# where vectors are held in registers. +def clear(at: *mut u8, size: u64): void { + memset(at, 0, (size + 7) & ~7u); +} + +# Copies bytes that may overlap, as `memmove` does, which `memcpy` does, sixteen +# bytes at a time where vectors are held in registers. +def copy_bytes(dst: *mut u8, src: *u8, size: u64): void { + memcpy(dst, src, size); +} + +def compare_bytes(a: *u8, b: *u8, size: u64): i64 { + return 0 if size == 0; + return memcmp(a, b, size); +} + +#! The bytes acquired for memory of the size, rounded to its class or to pages. +#! @param size The number of bytes asked for. +#! @returns The bytes that many takes: the size of its class, or whole pages for +#! a large block. +def acquired(size: u64): u64 { + return size > largest ? pages(size) : size_of_class[class_by_size[(size + 15) >> 4]]; +} + +#! Acquires zeroed memory of at least the size. +#! @param size The number of bytes asked for. +#! @returns The first byte of the memory, a block of its class or pages of their +#! own. +def acquire(size: u64): *mut u8 { + if size > largest { + return map_large(pages(size), true); + } + return take(class_by_size[(size + 15) >> 4], size); +} + +#! Takes memory of a class: a block disposed of, which holds what it held but +#! for the bytes asked to be cleared, or one carved fresh, which the kernel +#! zeroed. +#! @param class The class. +#! @param cleared How many of its first bytes a block reused is cleared for. +#! @returns The first byte of the memory. +def take(class: u64, cleared: u64): *mut u8 { + if free_lists == null { + free_lists = carve(classes * 8) as *mut *mut u8; + } + + val found := free_lists[class]; + if found != null { + free_lists[class] = (found as *mut *mut u8)[0]; + if cleared != 0 { + clear(found, cleared); + } + return found; + } + return carve(size_of_class[class]); +} + +#! Disposes of memory acquired with the size. +#! @param at The first byte of the memory, or `null`, which does nothing. +#! @param size The number of bytes it was acquired with. +def dispose(at: *mut u8, size: u64): void { + if at == null { + return; + } + if size > largest { + unmap_large(at, pages(size)); + return; + } + + val class: u64 = class_by_size[(size + 15) >> 4]; + (at as *mut *mut u8)[0] = free_lists[class]; + free_lists[class] = at; +} + + +# Large memory given back is kept to be handed out again, rather than unmapped, +# as mapping memory and touching its pages for the first time costs far more +# than clearing it: up to `kept_most` pieces, of `kept_bytes_most` bytes in +# all, each of `kept_largest` bytes at most, past which clearing it, which is +# done holding the lock, costs more than it saves. Each is kept by where it is +# and how many bytes it is, and handed out for as many bytes alone. +val kept_most := 64u; +val kept_bytes_most := 33554432u; +val kept_largest := 1048576u; +var kept_at: u64[64]; +var kept_size: u64[64]; +var kept_count: u64; +var kept_bytes: u64; + +#! Maps memory of a number of bytes, which the kernel zeroed, or hands out +#! memory of as many that was kept. +#! @param size The number of bytes, a whole number of pages. +#! @param cleared Whether memory kept is cleared, as memory mapped is zeroed. +#! @returns The first byte of the memory. +def map_large(size: u64, cleared: bool): *mut u8 { + for i in 0..kept_count { + if kept_size[i] == size { + val at := kept_at[i] as *mut u8; + kept_count--; + kept_at[i] = kept_at[kept_count]; + kept_size[i] = kept_size[kept_count]; + kept_bytes = kept_bytes - size; + if cleared { + clear(at, size); + } + return at; + } + } + return map(size); +} + +#! Gives back memory `map_large` gave, keeping it where there is room. +#! @param at The first byte of the memory. +#! @param size The number of bytes it was given with. +def unmap_large(at: *mut u8, size: u64): void { + if size <= kept_largest && kept_count < kept_most && kept_bytes + size <= kept_bytes_most { + kept_at[kept_count] = at as u64; + kept_size[kept_count] = size; + kept_count++; + kept_bytes = kept_bytes + size; + return; + } + unmap(at, size); +} + +# Whether memory lies within a chunk: the newest region's open chunks, or those of +# a region before it. +def in_chunk(at: *mut u8): bool { + val address := at as u64; + if address - region_low < region_high - region_low { + return true; + } + for i in 0..old_count { + val low := old_regions[2 * i]; + if address - low < old_regions[2 * i + 1] - low { + return true; + } + } + return false; +} + + +# Blocks the program allocates and releases itself, each a header of its size and +# mark followed by its data. A live block's mark is made from its header's +# address, and releasing it takes the mark away, so a pointer never allocated or +# already released is recognized. A small block is carved from a chunk, so its +# header is safe to read wherever the pointer is within one; a large block is +# mapped on its own, and found in a set of the large blocks. Every block's data +# starts a multiple of 16 bytes into its memory, so it is aligned to 16 bytes as +# the memory is, which is wider than any type needs. +# +# The set is probed linearly. A block released leaves a tombstone where it was, +# unless nothing was ever placed past it, and a block allocated takes the first +# tombstone or empty slot it meets. + +struct block { + var size: u64; #! The bytes of its data, all of the memory after the header. + var mark: u64; #! Made from its address while it is live, and 0 once released. +} + +val block_header := 16u; # The size and mark before every block's data. +val tombstone := 1u; + +var block_set: *mut *mut block; # Of the large blocks. +var block_capacity: u64; +var block_used: u64; # Slots holding blocks or tombstones. +var block_shift: u64; # What `hash` shifts by for the set. +var large_count: u64; # Large blocks that are live. + +# What a live block's mark is its address mixed with. +val live_key := 0x6E69616C70657669u; + +# The slot holding the block, or the empty slot that ends its probe where the set +# does not hold it. +def block_slot(found: *mut block): u64 { + val mask := block_capacity - 1; + var i := hash(found as u64, block_shift); + while block_set[i] != null && block_set[i] != found { + i = (i + 1) & mask; + } + return i; +} + +# The slot a block the set does not hold goes in: the first tombstone or empty +# slot of its probe. +def open_slot(made: *mut block): u64 { + val mask := block_capacity - 1; + var i := hash(made as u64, block_shift); + while block_set[i] != null && block_set[i] != tombstone as *mut block { + i = (i + 1) & mask; + } + return i; +} + +# Makes room for one more large block, building the set again at a quarter full +# from the blocks it holds once blocks and tombstones fill half of it. +def block_room(): void { + if block_capacity > 0 && (block_used + 1) * 2 <= block_capacity { + return; + } + + var capacity := 64u; + while capacity < (large_count + 1) * 4 { + capacity = capacity * 2; + } + + val before := block_set; + val had := block_capacity; + block_set = acquire(capacity * 8) as *mut *mut block; + block_capacity = capacity; + block_shift = shift_for(capacity); + block_used = large_count; + for i in 0..had { + val each := before[i]; + if each != null && each != tombstone as *mut block { + block_set[block_slot(each)] = each; + } + } + dispose(before as *mut u8, had * 8); +} + +# Takes the block at the slot out of the set. Where the slot after it is empty, no +# probe goes on past it, so it and the tombstones before it are emptied instead. +def unset(slot: u64): void { + val mask := block_capacity - 1; + if block_set[(slot + 1) & mask] != null { + block_set[slot] = tombstone as *mut block; + return; + } + + var i := slot; + block_set[i] = null; + block_used--; + i = (i + mask) & mask; + while block_set[i] == tombstone as *mut block { + block_set[i] = null; + block_used--; + i = (i + mask) & mask; + } +} + +# Puts a large block in the set. +def remember_large(made: *mut block): void { + block_room(); + val slot := open_slot(made); + if block_set[slot] == null { + block_used++; + } + block_set[slot] = made; + large_count++; +} + +# The live block whose data begins at `data`, stopping the program where there is +# none: a pointer never allocated, already released, or within a block. +def block_of(data: *mut u8): *mut block { + if (data as u64) % 16 != 0 || (data as u64) < block_header { + trap(error_invalid_release); + } + val found := (data - block_header) as *mut block; + if !in_chunk(found as *mut u8) { + if block_capacity == 0 || block_set[block_slot(found)] != found { + trap(error_invalid_release); + } + } + if ((*found).mark ^ (found as u64)) != live_key { + trap(error_invalid_release); + } + return found; +} + +# Releases the block. +def unblock(found: *mut block): void { + if block_header + (*found).size > largest { + unset(block_slot(found)); + large_count--; + } + (*found).mark = 0; + dispose(found as *mut u8, block_header + (*found).size); +} + +#! Allocates a zeroed block for `core::raw_allocate_zeroed`, as the machine does. +#! @param size The number of bytes asked for. +#! @returns The first byte of the block, after its header. +#! @remarks A size no block can hold stops the program with `out of memory`. +def allocate_zeroed(size: u64): *mut u8 { + if threaded { + val cached := cached_allocate(size, true); + if cached != null { + return cached; + } + } + hold(); + val made := allocate_held(size, true); + let_go(); + return made; +} + +#! Allocates a block for `core::raw_allocate`, which is not cleared. +#! @param size The number of bytes asked for. +#! @returns The first byte of the block, after its header. +#! @remarks A size no block can hold stops the program with `out of memory`. +def allocate(size: u64): *mut u8 { + if threaded { + val cached := cached_allocate(size, false); + if cached != null { + return cached; + } + } + hold(); + val made := allocate_held(size, false); + let_go(); + return made; +} + +# Each thread's own free blocks of each class, once the program has threads, +# which it takes and gives back without the lock: as many as `cache_most` of a +# class, past which half go back to the lists every thread shares, and as many +# as `cache_batch` taken from those at once where it has none. A thread's +# blocks go back to the lists as it ends. +struct block_cache { + var heads: u64[19]; # The first block of each class, whose first word holds the next's address. + var counts: u64[19]; # How many blocks each class has. +} + +val cache_most := 64u; +val cache_batch := 16u; + +# The running thread's cache, made where it has none. +def own_cache(): *mut block_cache { + val me := current(); + var held := (*me).cache; + if held == null { + hold(); + held = acquire(size_of::()) as *mut block_cache; + let_go(); + (*me).cache = held; + } + return held; +} + +# Allocates a small block from the running thread's cache, taking a batch of the +# class from the lists every thread shares, under the lock, where it has none, +# or gives null for a large block, which `allocate_held` maps. +def cached_allocate(size: u64, cleared: bool): *mut u8 { + if size > largest - block_header { + return null; + } + val class: u64 = class_by_size[(block_header + size + 15) >> 4]; + val held := own_cache(); + if held[0].counts[class] == 0 { + hold(); + for _ in 0..cache_batch { + val each := take(class, 0); + set_word(each, held[0].heads[class]); + held[0].heads[class] = each as u64; + } + held[0].counts[class] = cache_batch; + let_go(); + } + + val made := held[0].heads[class] as *mut block; + held[0].heads[class] = word(made as *u8); + held[0].counts[class] -= 1; + val total: u64 = size_of_class[class]; + if cleared { + clear(made as *mut u8, total); + } + (*made).size = total - block_header; + (*made).mark = (made as u64) ^ live_key; + return (made as *mut u8) + block_header; +} + +# Gives a live block of the newest region's chunks back to the running thread's +# cache, handing half of its class back to the lists every thread shares, under +# the lock, past `cache_most`. Gives false for any other pointer, which +# `release_held` looks at under the lock. The region's bounds are read without +# the lock, the end first: another thread opening a chunk only moves the end +# past blocks the bounds read do not hold, and one reserving a region sets its +# start before its end. +def cached_release(data: *mut u8): bool { + val address := data as u64; + if address % 16 != 0 || address < block_header { + return false; + } + val found := (data - block_header) as *mut block; + val high := region_high; + val low := region_low; + if high < low || found as u64 - low >= high - low { + return false; + } + if ((*found).mark ^ (found as u64)) != live_key { + return false; + } + + val class: u64 = class_by_size[(block_header + (*found).size + 15) >> 4]; + val held := own_cache(); + (*found).mark = 0; + set_word(found as *mut u8, held[0].heads[class]); + held[0].heads[class] = found as u64; + held[0].counts[class] += 1; + if held[0].counts[class] > cache_most { + hold(); + while held[0].counts[class] > cache_most / 2 { + val each := held[0].heads[class] as *mut u8; + held[0].heads[class] = word(each); + held[0].counts[class] -= 1; + (each as *mut *mut u8)[0] = free_lists[class]; + free_lists[class] = each; + } + let_go(); + } + return true; +} + +# Gives a thread's cached blocks, and its cache, back to the lists every thread +# shares, as it ends, holding the lock. +def flush_cache(me: *mut state): void { + val held := (*me).cache; + if held == null { + return; + } + for class in 0..classes { + while held[0].counts[class] != 0 { + val each := held[0].heads[class] as *mut u8; + held[0].heads[class] = word(each); + held[0].counts[class] -= 1; + (each as *mut *mut u8)[0] = free_lists[class]; + free_lists[class] = each; + } + } + dispose(held as *mut u8, size_of::()); + (*me).cache = null; +} + +# `allocate_zeroed` and `allocate`, holding the lock around the runtime's memory. +def allocate_held(size: u64, cleared: bool): *mut u8 { + if size > 0xFFFFFFFFFFFFFFFF - block_header - 4095 { + trap(error_out_of_memory); + } + + val wanted := block_header + size; + var total: u64 = 0; + var made: *mut block = null; + if wanted > largest { + total = pages(wanted); + made = map_large(total, cleared) as *mut block; + } + else { + val class: u64 = class_by_size[(wanted + 15) >> 4]; + total = size_of_class[class]; + made = take(class, cleared ? total : 0) as *mut block; + } + + (*made).size = total - block_header; + (*made).mark = (made as u64) ^ live_key; + if total > largest { + remember_large(made); + } + return (made as *mut u8) + block_header; +} + +#! Releases a block for `core::raw_release`, stopping the program where the +#! pointer is not that of a live block. +#! @param data The first byte of the block, or `null`, which does nothing. +def release(data: *mut u8): void { + if data == null { + return; + } + if threaded && cached_release(data) { + return; + } + hold(); + release_held(data); + let_go(); +} + +# `release`, holding the lock around the runtime's memory. +def release_held(data: *mut u8): void { + if data == null { + return; + } + unblock(block_of(data)); +} + +#! Moves a block to one of another size for `core::raw_resize`. A block whose +#! memory is already of the size keeps its place, and a large block grown larger +#! is remapped where it is, or moved by the kernel, rather than copied. +#! @param data The first byte of the block, or `null` to allocate one. +#! @param size The number of bytes the new block holds. +#! @returns The first byte of the new block, which holds what the old one did, +#! as far as it reaches, and may hold anything past that. +def resize(data: *mut u8, size: u64): *mut u8 { + if threaded { + hold(); + } + val made := resize_held(data, size); + if threaded { + let_go(); + } + return made; +} +module runtime when backend == native && os == linux; +# `resize`, holding the lock around the runtime's memory. +def resize_held(data: *mut u8, size: u64): *mut u8 { + if data == null { + return allocate_held(size, false); + } + + val found := block_of(data); + val most: u64 = 0xFFFFFFFFFFFFFFFF - block_header - 4095; + if size > most { + trap(error_out_of_memory); + } + + val total := acquired(block_header + size); + val before := block_header + (*found).size; + if total == before { + return data; + } + + if total > largest && before > largest && total > before { + val moved := syscall(call_mremap, found as u64, before, total, 1, 0, 0); + if moved < 0 { + trap(error_out_of_memory); + } + + # The block keeps its place among the blocks, under its new address. + unset(block_slot(found)); + large_count--; + val made := moved as u64 as *mut block; + (*made).size = total - block_header; + (*made).mark = (made as u64) ^ live_key; + remember_large(made); + return (made as *mut u8) + block_header; + } + + val grown := allocate_held(size, false); + copy_bytes(grown, data, (*found).size < size ? (*found).size : size); + unblock(found); + return grown; +} + +module runtime when backend == native && os == windows; + +# Windows maps memory in parts of 64 KiB, which takes no more memory than a page +# where less is used, and gives back only all of what it mapped at once, as every +# call of `unmap` does. +def map(size: u64): *mut u8 { + val address := VirtualAlloc(0, size, 0x3000, 0x04); + if address == 0 { + trap(31); + } + return address as *mut u8; +} + +def unmap(address: *mut u8, size: u64): void { + VirtualFree(address as u64, 0, 0x8000); +} + +# Opens the chunk after the last, committing it, or the first of a new region +# where this one is full. Windows counts what is committed against the memory it +# has, so a chunk it cannot commit is the program running out of memory. +def open_chunk(): void { + if region_high + chunk_size > region_end { + reserve(); + chunk = region_high as *mut u8; + chunk_left = 0; + } + if VirtualAlloc(region_high, chunk_size, 0x1000, 0x04) == 0 { + trap(error_out_of_memory); + } + region_high = region_high + chunk_size; + chunk_left = chunk_left + chunk_size; +} + +# Reserves a region without access, as on Linux, down to a chunk. +def reserve(): void { + if region_low != 0 { + keep_region(); + } + + var size := region_size; + while size >= chunk_size { + val address := VirtualAlloc(0, size, 0x2000, 0x01); + if address != 0 { + region_low = address; + region_high = address; + region_end = address + size; + return; + } + size = size / 2; + } + trap(error_out_of_memory); +} + +# `resize`, holding the lock around the runtime's memory. Windows cannot move +# what it mapped elsewhere, so a large block grows as a small one does, copied. +def resize_held(data: *mut u8, size: u64): *mut u8 { + if data == null { + return allocate_held(size, false); + } + + val found := block_of(data); + val most: u64 = 0xFFFFFFFFFFFFFFFF - block_header - 4095; + if size > most { + trap(error_out_of_memory); + } + + val total := acquired(block_header + size); + val before := block_header + (*found).size; + if total == before { + return data; + } + + val grown := allocate_held(size, false); + copy_bytes(grown, data, (*found).size < size ? (*found).size : size); + unblock(found); + return grown; +} diff --git a/runtime/start.sakura b/runtime/start.sakura new file mode 100644 index 00000000..653b6308 --- /dev/null +++ b/runtime/start.sakura @@ -0,0 +1,318 @@ +#! @file start.sakura +#! @author John Christman (sorakatadzuma@gmail.com) +#! @copyright Malunal Studios, LLC. +#! @license MIT +#! +#! Contains how an executable starts and stops: the arguments it gives `main`, +#! exiting, and the report a fault gives. + +import system::windows; + +module runtime when backend == native; + +#! Writes a view of the text of each argument into a slot, for `main`, leaving +#! out the path of the executable, as the machine gives only those after it. +#! +#! A view owns nothing, so each one views the text the system left on the stack +#! rather than a copy of it, and the run of views is a block the program keeps +#! for as long as it runs. +#! @param out The slot the view of the views is written to. +def arguments(out: *mut u8): void { + val info := executable(); + val argc := (*(*info).state).argc > 0 ? (*(*info).state).argc - 1 : 0; + val argv := (*(*info).state).argv + 1; + + val views := argc > 0 ? acquire(argc * 16) : null; + for i in 0..argc { + val text := argv[i] as *mut u8; + var length := 0u; + while text[length] != 0 { + length++; + } + + val view := (views + i * 16) as *mut u64; + view[0] = text as u64; + view[1] = length; + } + + val slot := out as *mut u64; + slot[0] = views as u64; + slot[1] = argc; +} + +#! The vector instructions the program uses, of those the processor running it +#! has, which the entry found by asking it as it started, one bit each: all of +#! them, but where the variable `SAKURA_CPU` names fewer, only those, so the +#! program runs as it would on a processor without the rest. It names them +#! joined by `+`: `sse2`, `ssse3`, `sse4.1`, `sse4.2`, `avx`, `avx2`, `fma`, +#! `popcnt`, `lzcnt`, `bmi1`, and `avx512`, or a level of x86-64, `x86-64`, +#! `x86-64-v2`, `x86-64-v3`, or `x86-64-v4`, for those it has. SSE2 is every x86-64 processor's, so always +#! kept. +#! @param found The instruction sets the processor has. +#! @returns Those the program uses. +def processor(found: u64): u64 { + val info := executable(); + val argc := (*(*info).state).argc; + var at := (*(*info).state).argv + argc + 1; + while at[0] != 0 { + val text := at[0] as *u8; + if named_at(text, 11, "SAKURA_CPU=") { + return found & processor_named(text + 11); + } + at = at + 1; + } + return found; +} + +# The instruction sets `SAKURA_CPU` names, from its value. +def processor_named(text: *u8): u64 { + var allowed: u64 = 0x01; + var start: u64 = 0; + var i: u64 = 0; + while true { + val c := text[i]; + if c == 0 || c == '+' as u8 { + val name := text + start; + val length := i - start; + if named_at(name, length, "ssse3") { allowed = allowed | 0x02; } + if named_at(name, length, "sse4.1") { allowed = allowed | 0x04; } + if named_at(name, length, "sse4.2") { allowed = allowed | 0x08; } + if named_at(name, length, "avx") { allowed = allowed | 0x10; } + if named_at(name, length, "avx2") { allowed = allowed | 0x20; } + if named_at(name, length, "fma") { allowed = allowed | 0x40; } + if named_at(name, length, "popcnt") { allowed = allowed | 0x80; } + if named_at(name, length, "lzcnt") { allowed = allowed | 0x100; } + if named_at(name, length, "bmi1") { allowed = allowed | 0x200; } + if named_at(name, length, "avx512") { allowed = allowed | 0x400; } + if named_at(name, length, "x86-64-v2") { allowed = allowed | 0x8F; } + if named_at(name, length, "x86-64-v3") { allowed = allowed | 0x3FF; } + if named_at(name, length, "x86-64-v4") { allowed = allowed | 0x7FF; } + break if c == 0; + start = i + 1; + } + i++; + } + return allowed; +} + +# Whether bytes are a name. +def named_at(bytes: *u8, length: u64, name: strview): bool { + return false if length != name.length; + for k in 0..length { + return false if bytes[k] != name[k]; + } + return true; +} +module runtime when backend == native && os == linux; +# Retries a system call interrupted by a signal. +def retried(n: i64, a: u64, b: u64, c: u64): i64 { + while true { + val result := syscall(n, a, b, c, 0, 0, 0); + if result != -4 { + return result; + } + } + return 0; +} + +def write_all(file: u64, data: *u8, length: u64): void { + var written := 0u; + while written < length { + val count := retried(call_write, file, (data + written) as u64, length - written); + if count <= 0 { + return; + } + written = written + count as u64; + } +} +module runtime when backend == native; +# The function whose code holds an address, or null. +def function_at(address: u64): *function { + val info := executable(); + for i in 0..(*info).function_count { + val each := (*info).functions + i; + if address >= (*each).start && address < (*each).end { + return each; + } + } + return null; +} + +# Writes ` at name (path:line:column)` for an address within a function, unless +# the function belongs to the runtime. +def put_frame(into: *mut builder, address: u64): void { + val found := function_at(address); + if found == null || (*found).runtime != 0 || (*found).line_count == 0 { + return; + } + + var line := (*found).lines; + for i in 1..(*found).line_count { + val next := (*found).lines + i; + if (*next).offset as u64 > address - (*found).start { + break; + } + line = next; + } + + # Code inlined names the function it came from, where it is, then each function + # it was called within, where it was called, out to the function itself. + val info := executable(); + val path := (*info).paths + (*line).path as u64; + if (*line).site == 0 { + put_place(into, (*found).name, (*found).name_length, (*path).bytes, (*path).length, (*line).line as u64, (*line).column as u64); + return; + } + var site := (*info).sites + ((*line).site - 1) as u64; + val inlined := (*info).functions + (*site).function as u64; + put_place(into, (*inlined).name, (*inlined).name_length, (*path).bytes, (*path).length, (*line).line as u64, (*line).column as u64); + while true { + val called := (*info).paths + (*site).path as u64; + var within := found; + val parent := (*site).parent; + if parent != 0 { + within = (*info).functions + (*((*info).sites + (parent - 1) as u64)).function as u64; + } + put_place(into, (*within).name, (*within).name_length, (*called).bytes, (*called).length, (*site).line as u64, (*site).column as u64); + break if parent == 0; + site = (*info).sites + (parent - 1) as u64; + } +} + +# Writes one frame of a trace: ` at name (path:line:column)`. +def put_place(into: *mut builder, name: *u8, name_length: u64, path: *u8, path_length: u64, line: u64, column: u64): void { + put_text(into, text_at); + append(into, name, name_length); + put_text(into, text_open); + append(into, path, path_length); + put_text(into, text_colon); + put_unsigned(into, line); + put_text(into, text_colon); + put_unsigned(into, column); + put_text(into, text_close); +} +module runtime when backend == native && os == linux; +#! Stops the program with a status, having run everything asked of it. +#! @param code The status to stop with. +def exit(code: i64): void { + syscall(call_exit_group, code as u64, 0, 0, 0, 0, 0); +} +module runtime when backend == native; +#! Stops the program at once, reporting the functions that were running. +#! +#! The report is the one every fault gives, so an abort reads like any other way +#! the program stops, and exits with the same status. +def abort(): void { + trap(error_aborted); +} + +# The text `fault` was given, which the report of its trap gives. +var fault_data: *u8; +var fault_length: u64; + +#! Stops the program at once, reporting the text given, then the functions that +#! were running, as every fault does. +#! @param data The text's bytes. +#! @param length How many there are. +def fault(data: *u8, length: u64): void { + # The lock is kept to the end, so a thread faulting beside it waits rather + # than changing the text. + hold(); + fault_data = data; + fault_length = length; + trap(error_faulted); +} +module runtime when backend == native && os == linux; +#! Reports a trap and exits with 1: its error, then the functions it happened +#! in, from the address the trap was called from and the chain of frame +#! pointers. +#! @param code The error, as the machine numbers them. +#! @param address The address the trap was called from, in the function that +#! faulted. +#! @param chain The frame pointer of that function, whose saved frame +#! pointers and return addresses lead to each caller. +#! @remarks It does not return. +def fail(code: i64, address: u64, chain: *mut u64): void { + hold(); + val report := acquire(size_of::()) as *mut builder; + put_text(report, text_prefix); + if code == error_faulted && fault_data != null { + append(report, fault_data, fault_length); + } else { + put_text(report, code >= 0 && code < 31 ? code as u64 : text_out_of_memory); + } + put_text(report, text_newline); + + # A stack overflow is found entering the function called, so its caller is first. + if code != 8 { + put_frame(report, address - 1); + } + var each := chain; + while each != null { + put_frame(report, each[1] - 1); + each = each[0] as *mut u64; + } + + write_all(2, (*report).data, (*report).length); + syscall(call_exit_group, 1, 0, 0, 0, 0, 0); +} + +module runtime when backend == native && os == windows; + +# Writes to the standard output or error, a file `file` numbers as Linux does: +# to a console as the text it is, and elsewhere as its bytes. +def write_all(file: u64, data: *u8, length: u64): void { + val handle := GetStdHandle((0xFFFFFFF6 - file) as u32); + var mode: u32 = 0; + if GetConsoleMode(handle, &mut mode) != 0 && write_console(handle, data, length) { + return; + } + var written := 0u; + while written < length { + val left := length - written; + val asked: u32 = left > 0x40000000 ? 0x40000000 : left as u32; + var count: u32 = 0; + if WriteFile(handle, data + written, asked, &mut count, null) == 0 || count == 0 { + return; + } + written = written + count as u64; + } +} + +#! Stops the program with a status, having run everything asked of it. +#! @param code The status to stop with. +def exit(code: i64): void { + ExitProcess(code as u32); +} + +#! Reports a trap and exits with 1, as on Linux. +#! @param code The error, as the machine numbers them. +#! @param address The address the trap was called from, in the function that +#! faulted. +#! @param chain The frame pointer of that function, whose saved frame +#! pointers and return addresses lead to each caller. +#! @remarks It does not return. +def fail(code: i64, address: u64, chain: *mut u64): void { + hold(); + val report := acquire(size_of::()) as *mut builder; + put_text(report, text_prefix); + if code == error_faulted && fault_data != null { + append(report, fault_data, fault_length); + } else { + put_text(report, code >= 0 && code < 31 ? code as u64 : text_out_of_memory); + } + put_text(report, text_newline); + + # A stack overflow is found entering the function called, so its caller is first. + if code != 8 { + put_frame(report, address - 1); + } + var each := chain; + while each != null { + put_frame(report, each[1] - 1); + each = each[0] as *mut u64; + } + + write_all(2, (*report).data, (*report).length); + ExitProcess(1); +} diff --git a/runtime/threads.sakura b/runtime/threads.sakura new file mode 100644 index 00000000..9d7225e1 --- /dev/null +++ b/runtime/threads.sakura @@ -0,0 +1,281 @@ +#! @file threads.sakura +#! @author John Christman (sorakatadzuma@gmail.com) +#! @copyright Malunal Studios, LLC. +#! @license MIT +#! +#! Contains the threads of an executable: starting one with stacks of its own, +#! ending it, and the lock every thread takes around the runtime's memory. +#! +#! Each thread has a record, which `gs` points at in it, holding its stack's +#! bounds, its text being formatted, and the function it runs. The first +#! thread's is the executable's state, and the records are a list from it. +#! Until the program starts a thread, nothing here takes a lock. + +import system::windows; + +module runtime when backend == native; + + +# Whether the program started a thread, after which the runtime's memory is +# locked. +var threaded: bool; + +# The lock around the runtime's memory: its word, 0 where no thread holds it, 1 +# where one does, and 2 where others may wait, and the thread holding it, which may +# take it again, as allocating while formatting does. +var lock_word: atomic; +var lock_owner: u64; +var lock_depth: u64; + +# The bytes of a record. +val record_bytes := 256u; + +# The stack past a thread's limit, reserved for reporting a trap, as +# `native/native.sakura` reserves it. +val stack_reserve := 262144u; +module runtime when backend == native && os == linux; +val call_getpid: i64 = 39; +val call_clone_exit: i64 = 60; +val call_rt_sigprocmask: i64 = 14; +val call_tgkill: i64 = 234; +val call_futex: i64 = 202; + +#! Takes the lock around the runtime's memory, once the program has threads. +def hold(): void { + return if !threaded; + val me := current() as u64; + if lock_owner == me { + lock_depth++; + return; + } + if lock_word.exchange(1) != 0 { + while lock_word.exchange(2) != 0 { + syscall(call_futex, lock_address(), 0, 2, 0, 0, 0); + } + } + lock_owner = me; + lock_depth = 1; +} + +#! Lets go of the lock around the runtime's memory. +def let_go(): void { + return if !threaded; + lock_depth--; + return if lock_depth != 0; + lock_owner = 0; + if lock_word.exchange(0) == 2 { + syscall(call_futex, lock_address(), 1, 1, 0, 0, 0); + } +} + +def lock_address(): u64 { + return ((&mut lock_word) as *mut atomic) as u64; +} + +#! `op::start`: starts a thread running a function, with a stack of its own as +#! large as the first thread's. +#! @param body The function, two words, then the context it is given, a word. +#! @returns The thread's number, or a negative error number. +def start_thread(body: *mut u8): i64 { + threaded = true; + hold(); + reap(); + val first := (*executable()).state; + val size := (*first).shadow_base as u64 - (*first).trap_frame as u64; + val record := mapped(record_bytes) as *mut state; + val stack := mapped(size); + if record == null || stack == null { + unmapped(record as *mut u8, record_bytes); + unmapped(stack, size); + let_go(); + return -12; + } + + (*record).itself = record; + (*record).trap_frame = stack; + (*record).shadow_limit = stack + stack_reserve; + (*record).shadow_base = stack + size; + (*record).map = stack; + (*record).map_size = size; + (*record).running = 1; + copy_bytes((&mut record[0].body) as *mut u8, body, 24); + (*record).next = (*first).next; + (*first).next = record; + + # Every signal is blocked while it starts, so the thread begins with them blocked, + # and takes those it does once `gs` holds its record. + var all: u64 = 0xFFFFFFFFFFFFFFFF; + var kept: u64 = 0; + syscall(call_rt_sigprocmask, 2, ((&mut all) as *mut u64) as u64, ((&mut kept) as *mut u64) as u64, 8, 0, 0); + val number := clone_thread(record); + syscall(call_rt_sigprocmask, 2, ((&mut kept) as *mut u64) as u64, 0, 8, 0, 0); + if number < 0 { + (*first).next = (*record).next; + unmapped(record as *mut u8, record_bytes); + unmapped(stack, size); + } + let_go(); + return number; +} + +#! What a thread runs, on its own stack: its function, then the end of it. The +#! system clears its number once it has ended, and its stack is unmapped after. +def thread_main(): void { + val me := current(); + (*me).body((*me).context); + hold(); + flush_cache(me); + if (*me).builders != null { + dispose((*me).builders as *mut u8, (*me).builder_capacity * size_of::()); + } + (*me).running = 0; + let_go(); + syscall(call_clone_exit, 0, 0, 0, 0, 0, 0); +} + +# Unmaps the records and stacks of threads the system has ended. +def reap(): void { + val first := (*executable()).state; + var link := first; + while (*link).next != null { + val each := (*link).next; + if (*each).running == 0 && (*each).tid == 0 { + (*link).next = (*each).next; + unmapped((*each).map, (*each).map_size); + unmapped(each as *mut u8, record_bytes); + continue; + } + link = each; + } +} + +# Maps memory, giving null where there is none. +def mapped(size: u64): *mut u8 { + val address := syscall(call_mmap, 0, size, 3, 0x4022, 0xFFFFFFFFFFFFFFFF, 0); + return address < 0 ? null : address as *mut u8; +} + +def unmapped(address: *mut u8, size: u64): void { + if address != null { + syscall(call_munmap, address as u64, size, 0, 0, 0, 0); + } +} + +module runtime when backend == native && os == windows; + +# On Windows each thread runs on a stack of the system's, which the system +# reserves, commits as it grows, and frees as the thread ends, and the record's +# word for its stack holds the thread's handle instead. The lock's word is +# waited on as Linux waits on a futex. + +#! Takes the lock around the runtime's memory, once the program has threads. +def hold(): void { + return if !threaded; + val me := current() as u64; + if lock_owner == me { + lock_depth++; + return; + } + if lock_word.exchange(1) != 0 { + var contended: u32 = 2; + while lock_word.exchange(2) != 0 { + WaitOnAddress(lock_address() as *mut u32, &contended, 4, 0xFFFFFFFF); + } + } + lock_owner = me; + lock_depth = 1; +} + +#! Lets go of the lock around the runtime's memory. +def let_go(): void { + return if !threaded; + lock_depth--; + return if lock_depth != 0; + lock_owner = 0; + if lock_word.exchange(0) == 2 { + WakeByAddressSingle(lock_address() as *mut u32); + } +} + +def lock_address(): u64 { + return ((&mut lock_word) as *mut atomic) as u64; +} + +#! `op::start`: starts a thread running a function, on a stack the system makes +#! it, as large as the first thread's. +#! @param body The function, two words, then the context it is given, a word. +#! @returns The thread's number, or a negative error number. +def start_thread(body: *mut u8): i64 { + threaded = true; + hold(); + reap(); + val first := (*executable()).state; + + # The thread runs on a stack the system makes it, as large as the first + # thread's. + val size := (*first).shadow_base as u64 - (*first).trap_frame as u64; + val record := mapped(record_bytes) as *mut state; + if record == null { + let_go(); + return -12; + } + + (*record).itself = record; + (*record).map_size = size; # The system reserves its stack this large. + (*record).running = 1; + copy_bytes((&mut record[0].body) as *mut u8, body, 24); + (*record).next = (*first).next; + (*first).next = record; + + val number := clone_thread(record); + if number < 0 { + (*first).next = (*record).next; + unmapped(record as *mut u8, record_bytes); + } + let_go(); + return number; +} + +#! What a thread runs, on the stack the system made it: its function, then the +#! end of it, after which it returns to `beginning`, which ends the thread. The +#! system then signals its handle, and its record is unmapped after. +def thread_main(): void { + val me := current(); + (*me).body((*me).context); + hold(); + flush_cache(me); + if (*me).builders != null { + dispose((*me).builders as *mut u8, (*me).builder_capacity * size_of::()); + } + (*me).running = 0; + let_go(); +} + +# Unmaps the records of threads the system has ended, closing their handles; the +# system frees their stacks itself. +def reap(): void { + val first := (*executable()).state; + var link := first; + while (*link).next != null { + val each := (*link).next; + val handle := (*each).spare_map[0]; + if (*each).running == 0 && WaitForSingleObject(handle, 0) == 0 { + (*link).next = (*each).next; + CloseHandle(handle); + unmapped(each as *mut u8, record_bytes); + continue; + } + link = each; + } +} + +# Maps zeroed memory, giving null where there is none. +def mapped(size: u64): *mut u8 { + return VirtualAlloc(0, size, 0x3000, 0x04) as *mut u8; +} + +def unmapped(address: *mut u8, size: u64): void { + if address != null { + VirtualFree(address as u64, 0, 0x8000); + } +} diff --git a/runtime/values.sakura b/runtime/values.sakura new file mode 100644 index 00000000..2984d140 --- /dev/null +++ b/runtime/values.sakura @@ -0,0 +1,127 @@ +#! @file values.sakura +#! @author John Christman (sorakatadzuma@gmail.com) +#! @copyright Malunal Studios, LLC. +#! @license MIT +#! +#! Contains the operations the code an executable is compiled to calls on +#! values. +#! +#! The operations generated code calls on values, ports of those of +#! `sources/machine.c`. Values are in their frame representation in slots, and +#! in their memory representation within fixed arrays, structs, and objects. + +module runtime when backend == native; + +# Reads a scalar in memory as its frame representation. +def read_scalar(dst: *mut u8, at: *mut u8, access: u64): void { + if access == access_i8 { + set_word(dst, (at as *mut i8)[0] as u64); + } + else if access == access_u8 { + set_word(dst, at[0] as u64); + } + else if access == access_i16 { + set_word(dst, (at as *mut i16)[0] as u64); + } + else if access == access_u16 { + set_word(dst, (at as *mut u16)[0] as u64); + } + else if access == access_i32 { + set_word(dst, (at as *mut i32)[0] as u64); + } + else if access == access_u32 { + set_word(dst, (at as *mut u32)[0] as u64); + } + else if access == access_f32 { + (dst as *mut f64)[0] = (at as *mut f32)[0] as f64; + } + else { + set_word(dst, word(at)); + } +} + +# Writes a scalar in its frame representation to memory. +def write_scalar(at: *mut u8, src: *mut u8, access: u64): void { + if access == access_i8 || access == access_u8 { + at[0] = word(src) as u8; + } + else if access == access_i16 || access == access_u16 { + (at as *mut u16)[0] = word(src) as u16; + } + else if access == access_i32 || access == access_u32 { + (at as *mut u32)[0] = word(src) as u32; + } + else if access == access_f32 { + (at as *mut f32)[0] = (src as *mut f64)[0] as f32; + } + else { + set_word(at, word(src)); + } +} + +# The field a union holds, by its index: its tag, or of one laid out without a +# tag, its field of bytes where its first word is not null, and its empty one +# where it is. +def held_field(at: *mut u8, kind: *layout): u64 { + val first := word(at); + return first if ((*kind).flags & layout_niche) == 0; + val first_empty := (*(*(*kind).fields).layout).size == 0; + return (first != 0) == first_empty ? 1 : 0; +} + +# Whether values are equal: fixed arrays element by element, structs field by +# field, and unions by variant and then value. +def equal_values(a: *mut u8, b: *mut u8, kind: *layout): bool { + if (*kind).kind == kind_float { + if (*kind).access == access_f32 { + return (a as *mut f32)[0] == (b as *mut f32)[0]; + } + return (a as *mut f64)[0] == (b as *mut f64)[0]; + } + + if (*kind).kind == kind_fixed { + val element := (*kind).element; + val plain := (*element).kind; + if plain == kind_int || plain == kind_uint || plain == kind_bool || plain == kind_pointer { + return compare_bytes(a, b, (*kind).size) == 0; + } + for i in 0..(*kind).count { + if !equal_values(a + i * (*element).size, b + i * (*element).size, element) { + return false; + } + } + return true; + } + + if (*kind).kind == kind_struct { + for i in 0..(*kind).count { + val field := (*kind).fields + i; + if !equal_values(a + (*field).offset, b + (*field).offset, (*field).layout) { + return false; + } + } + return true; + } + + if (*kind).kind == kind_union { + val tag := held_field(a, kind); + if tag != held_field(b, kind) || tag >= (*kind).count { + return false; + } + val field := (*kind).fields + tag; + return equal_values(a + (*field).offset, b + (*field).offset, (*field).layout); + } + + return compare_bytes(a, b, (*kind).size) == 0; +} + +# The helpers generated code calls. + +#! `OP_EQUAL`: whether the values are equal. +#! @param a One value, in its frame representation. +#! @param b The other. +#! @param kind The layout of their type. +#! @returns Whether they are equal, as `==` compares them. +def equal(a: *mut u8, b: *mut u8, kind: *layout): bool { + return equal_values(a, b, kind); +} diff --git a/runtime/windows.sakura b/runtime/windows.sakura new file mode 100644 index 00000000..04347104 --- /dev/null +++ b/runtime/windows.sakura @@ -0,0 +1,213 @@ +#! @file windows.sakura +#! @author John Christman (sorakatadzuma@gmail.com) +#! @copyright Malunal Studios, LLC. +#! @license MIT +#! +#! Contains what the runtime needs of Windows: the functions of the system it +#! calls, and how an executable finds the arguments and variables it started +#! with. +#! +#! Windows has no system calls a program makes itself. The runtime calls the +#! functions of kernel32 instead, as C functions the executable imports, and +#! those of the library Windows names for the waits on an address, which +#! `system::windows` declares for everything that reaches the system. The other +#! files of the runtime declare their functions that call the system once for +#! each system, in sections of their own. + +import system::windows; + +module runtime when backend == native && os == windows; + + +# What the functions of the system are given is written where they are called, +# as numbers, since `system_start` and what it calls run before the globals, +# constants among them, are set: UTF-8's code page is 65001, memory is +# committed with 0x1000, reserved with 0x2000, and released with 0x8000, and it +# is read and written with 0x04, or not at all with 0x01. + +#! Finds the arguments and variables the program started with, before anything +#! else runs, as Linux leaves them on the first thread's stack: views of their +#! texts in a run of words, the arguments, a zero, the variables, and a zero, +#! which the state's `argv` points at and whose arguments its `argc` counts. +#! Windows gives them in UTF-16, the arguments as one line, so they are +#! converted to UTF-8, and the line split as Microsoft's C library splits it. +#! Every block is mapped and kept for as long as the program runs. +#! @remarks It runs before the globals are set, and before a trap could be +#! reported, so it exits with 2 where there is no memory, as the start +#! does. +def system_start(): void { + # A failure of the program nothing reports ends it, as one would on Linux, + # rather than asking the user what to do: SEM_FAILCRITICALERRORS, + # SEM_NOGPFAULTERRORBOX, and SEM_NOOPENFILEERRORBOX. + SetErrorMode(0x8003); + + val line := GetCommandLineW(); + var units := 0u; + while line[units] != 0 { + units++; + } + val line_room := units * 3 + 1; + val line_text := start_map(line_room); + var length := 0u; + if units > 0 { + length = WideCharToMultiByte(65001, 0, line, units as i32, line_text, line_room as i32, null, null) as u64; + } + # Splitting gives no more bytes than the line has, and a zero after each argument. + val arguments := start_map(2 * length + 2); + val argc := split_arguments(line_text, arguments); + + # The variables end at an empty one, and those Windows keeps of each drive, + # named from `=`, are left out. + val block := GetEnvironmentStringsW(); + var total := 0u; + while block != null && (block[total] != 0 || block[total + 1] != 0) { + total++; + } + val variables_room := total * 3 + 2; + val variables := start_map(variables_room); + var bytes := 0u; + if total > 0 { + bytes = WideCharToMultiByte(65001, 0, block, (total + 1) as i32, variables, variables_room as i32, null, null) as u64; + } + if block != null { + FreeEnvironmentStringsW(block); + } + var envc := 0u; + var at := 0u; + while at < bytes && variables[at] != 0 { + if variables[at] != '=' as u8 { + envc++; + } + while variables[at] != 0 { + at++; + } + at++; + } + + val words := start_map((argc + envc + 2) * 8) as *mut u64; + var word := 0u; + at = 0; + for i in 0..argc { + words[word] = (arguments + at) as u64; + word++; + while arguments[at] != 0 { + at++; + } + at++; + } + word++; + at = 0; + while at < bytes && variables[at] != 0 { + if variables[at] != '=' as u8 { + words[word] = (variables + at) as u64; + word++; + } + while variables[at] != 0 { + at++; + } + at++; + } + + val first := (*executable()).state; + (*first).argc = argc; + (*first).argv = words; +} + +# Maps zeroed memory for `system_start`, exiting with 2 where there is none. +def start_map(size: u64): *mut u8 { + val address := VirtualAlloc(0, size, 0x3000, 0x04); + if address == 0 { + ExitProcess(2); + } + return address as *mut u8; +} + +# Splits a command line into arguments as Microsoft's C library does, writing +# each into `into`, which is zeroed, with a zero after it, and gives how many +# there are. The path of the program ends at the first space or tab outside +# quotes, and quotes only begin and end the parts of it within them. In each +# argument after it, quotes do too, but within quotes two are one, and +# backslashes are themselves but before a quote, where each two are one, and +# one left over makes the quote one. +def split_arguments(line: *u8, into: *mut u8): u64 { + var at := 0u; + var out := 0u; + var quoted := false; + while line[at] != 0 && (quoted || (line[at] != ' ' as u8 && line[at] != '\t' as u8)) { + if line[at] == '"' as u8 { + quoted = !quoted; + } else { + into[out] = line[at]; + out++; + } + at++; + } + out++; + var count := 1u; + + quoted = false; + while true { + while line[at] == ' ' as u8 || line[at] == '\t' as u8 { + at++; + } + break if line[at] == 0; + while true { + var kept := true; + var backslash := 0u; + while line[at] == '\\' as u8 { + at++; + backslash++; + } + if line[at] == '"' as u8 { + if backslash % 2 == 0 { + if quoted && line[at + 1] == '"' as u8 { + at++; + } else { + kept = false; + quoted = !quoted; + } + } + backslash = backslash / 2; + } + while backslash > 0 { + into[out] = '\\' as u8; + out++; + backslash--; + } + break if line[at] == 0 || (!quoted && (line[at] == ' ' as u8 || line[at] == '\t' as u8)); + if kept { + into[out] = line[at]; + out++; + } + at++; + } + out++; + count++; + } + return count; +} + +# Writes text to a console, which takes UTF-16, converting it a part at a time +# in memory of its own, or giving up where there is none, and gives whether it +# did. +def write_console(handle: u64, data: *u8, length: u64): bool { + val part := 16384u; + val units := VirtualAlloc(0, part * 2, 0x3000, 0x04) as *mut u16; + return false if units == null; + var at := 0u; + while at < length { + # A part ends before the bytes after the first of a character, never within it. + var end := length - at > part ? at + part : length; + while end < length && end > at && (data[end] & 0xC0) == 0x80 { + end--; + } + val count := MultiByteToWideChar(65001, 0, data + at, (end - at) as i32, units, part as i32); + var done: u32 = 0; + if count <= 0 || WriteConsoleW(handle, units, count as u32, &mut done, null) == 0 { + break; + } + at = end; + } + VirtualFree(units as u64, 0, 0x8000); + return true; +} diff --git a/server/README.md b/server/README.md new file mode 100644 index 00000000..5c766481 --- /dev/null +++ b/server/README.md @@ -0,0 +1,103 @@ +# sakura::server + +`sakura::server` is Sakura's language server: what `sakura lsp` serves. It speaks the +language server protocol over the standard input and output, checking every `.sakura` file +of the editor's workspace folders as `sakura check` would. It publishes each file's notes +as diagnostics, and answers hovering, completion, the help shown while a call's arguments +are written, colouring, going to a declaration, finding where a name is written, and +renaming. The text open in the editor is checked in place of what's on disk. + +The server itself never checks anything. Each job is worked out by a process of its own, +so a fault while checking can't stop the server, and a job taking more than 30 seconds is +stopped. A base process keeps the workspace parsed and checked, and checks again only what +an edit affects. + +## Using it + +Require this repository, which exports each of the compiler's libraries, and name this +one among a target's `deps`: + +```yaml +requires: +- https://git.malunal.studio/sakura/std@v1.0.0 +- https://git.malunal.studio/sakura/sakurac@v1.0.0 + +targets: +- name: app + type: program + deps: [sakura.server] +``` + +A program serving the protocol as `sakura lsp` does: + +```sakura +import system; +import sakura::server; + +# Serves the language server protocol until the client exits, checking for +# Linux, as `sakura run` would, with each argument a library as `NAME=DIR`. +def main(args: span): void { + # Windows can't copy a process, so there the server starts this program + # again for its jobs, as `PROGRAM lsp --base` and `PROGRAM lsp --worker`. + when os == windows { + if args.length == 2 && args[0] == "lsp" && (args[1] == "--base" || args[1] == "--worker") { + exit(serve_process(args[1] == "--base")); + } + } + # The standard library is found as `sakurac` finds it, unless an argument + # names it. + val found := found_std(args); + var libraries := vector::::new(); + for each in args { + libraries.append(each); + } + for &each in found { + libraries.append(each.view()); + } + exit(serve(server_options { native = false, system = "linux", libraries = libraries.view() })); +} +``` + +Like `sakurac`, the program finds `core`, `system`, and `runtime` as folders beside +its executable, or in the nearest folder above it that holds them. `found_std` finds `std` +the same way, or else the libraries of std in the `share/sakura` folder above it. + +## What it holds + +- **The server**: `serve`, given its `server_options`: + - `native` and `system`: what the workspace is checked for, an executable or the + machine, and which system; + - `libraries`: the libraries, the standard library's among them, each `NAME=DIR`, as + `sakura --lib` takes them. + + It returns 0 where the client shut it down before exiting, and 1 otherwise. +- **Programs**: every `.sakura` file of the workspace folders, past hidden folders and + the folders of the libraries given, with `core` and the modules of `system`, the + standard library, and the libraries that they refer to. Where several files declare + `main`, each begins a program of its own, and the one checked is that of the file last + opened, edited, or asked about. +- **Jobs**: on Linux, the base starts a copy of itself for each job. On Windows, the + base and the workers are the program started again, which hands them to + `serve_process`. +- **Answers**: what's checked evaluates the program's constants on `sakura::machine`, so + the diagnostics are what `sakura check` says. +- **The protocol's text**: JSON, positions counted in UTF-16 code units, the `file:` URIs + of each system's paths, and the Markdown of documentation comments. +- **The toolchain**: `toolchain_folder` finds a folder beside the executable or above it, + as `core`, `found_std` the standard library, as `--lib` would give it, and + `target_checker` sets what a checker checks for. `sakura`'s commands use them too. + +## Testing + +From the repository's root, `blossom test` runs them as `sakura.server.tests`, or, with +`std` beside the repository: + +```sh +sakurac run --lib std=../std --lib sakura::analyzer=analyzer --lib sakura::compiler=compiler \ + --lib sakura::machine=machine --lib sakura::server=server \ + tests/main.sakura tests/server/*.sakura +``` + +The tests are declared within the module. They check the positions of text whose lines +end in CR LF, messages carrying whatever a file holds as JSON, and the paths `file:` URIs +name, as Linux and Windows each spell them. diff --git a/server/answers.sakura b/server/answers.sakura new file mode 100644 index 00000000..21f7f1ac --- /dev/null +++ b/server/answers.sakura @@ -0,0 +1,861 @@ +#! @file answers.sakura +#! @author John Christman (sorakatadzuma@gmail.com) +#! @copyright Malunal Studios, LLC. +#! @license MIT +#! +#! Contains the jobs a process of the server's works out from the files of the +#! workspace, and how each is answered: the diagnostics of every file, what the +#! name at a position is, the names that may be written there, what is being +#! called there, the names of a file as what they are, and where what a name +#! refers to is declared and written. Each answer is the text the server shapes +#! into what it sends the client. + +import std::net; +import std::json; +import std::serial; +import sakura::analyzer; +import sakura::machine; +module sakura::server; + + +#! What a process of its own is asked to work out. +pub enum task : u8 { + check, #! The diagnostics of every file. + hover, #! What the name at a position is. + complete, #! The names that may be written at a position. + call, #! What is being called at a position, while its arguments are written. + tokens, #! The names of a file, as the checker made them. + name, #! What the name at a position refers to, and where it is declared. + refer, #! Everywhere what the name at a position refers to is written. +} + +#! What is asked of a process. +pub struct job { + pub var task: task; #! What is asked. + pub var strict: bool; #! Whether files with mistakes of syntax are left out, as a check without drafts does. + pub var path: string; #! The file asked about, or empty. + pub var line: u32; #! The line of the position asked about, from 0. + pub var character: u32; #! Its UTF-16 code unit within the line, from 0. + pub var touched: string; #! The file last opened, edited, or asked about, or empty. + pub var entry: string; #! The file declaring `main` the last job was answered from, or empty. +} + +#! What the server's processes work with: the program, its checker, and what +#! names the files of the editor's documents. +pub struct workplace { + pub var held: &mut program; #! The program's files, parsed. + pub var checker: &mut checker; #! Its checker. + pub var documents: &vector; #! The documents open in the editor. +} + +#! Written after a `.` being completed, so the value before it parses as one. +pub const placeholder: strview = "sakura__completion"; + +#! Right after `.`, a member name must follow for the value before it to parse, +#! so one is written into the text of the file being completed. +#! @param files The files, as gathered. +#! @param asked The job. +pub def write_placeholder(files: &mut vector, asked: &job): void { + return if asked.task != task::complete; + for i in 0..files.length { + continue if files[i].path.view() != asked.path.view(); + val text := files[i].text.view(); + val offset := locate(text, asked.line as u64, asked.character as u64); + val start := word_start(text, offset); + return if start != offset || start == 0 || text[(start - 1) as u64] != '.' + || (start >= 2 && text[(start - 2) as u64] == '.'); + var written := string::from(text.substr(0, offset as u64), nothing {}); + written.append(placeholder); + written.append(text.substr(offset as u64, text.length - offset as u64)); + files[i].text = move(&mut written); + return; + } +} + +#! Where the word a byte of the text ends, or is within, begins. +#! @param text The text. +#! @param offset The byte. +#! @returns The byte the word begins at, which is the byte itself where no word +#! ends there. +def word_start(text: strview, offset: u32): u32 { + var start := offset; + while start > 0 && is_word_byte(text[(start - 1) as u64]) { + start--; + } + return start; +} + +#! Answers a job from a checked program. The path of the file declaring `main` +#! the program begins with comes first, ended by a zero byte, so the server knows +#! which program answered. +#! @param place What the process works with. +#! @param asked The job. +#! @param out Where the answer is written. +pub def answer(place: &mut workplace, asked: &job, out: &mut string): void { + if place.held.entry != none { + out.append(place.held.paths[place.held.entry].view()); + } + out.push(0); + match asked.task { + task::check => answer_check(place, out); + task::hover => answer_hover(place, asked, out); + task::complete => answer_complete(place, asked, out); + task::call => answer_call(place, asked, out); + task::tokens => answer_tokens(place, asked, out); + task::name => answer_name(place, asked, out); + task::refer => answer_refer(place, asked, out); + } +} + +#! The URI a file is named by: the one the editor gave it where it is open, +#! which may be spelled other than as its path is, and else its path's. +#! @param place What the process works with. +#! @param path The file's path. +#! @param out Where the URI is written, as a JSON string. +def write_file_uri(place: &workplace, path: strview, out: &mut json::writer): void { + # The types the syntax makes are shown from a file of their own. + if path == builtin_path { + val shown := builtin_document(); + if shown.length != 0 { + var uri := string::new(nothing {}); + append_uri(&mut uri, shown.view()); + out.text(uri.view()); + return; + } + } + for &each in place.documents { + if each.path.view() == path { + out.text(each.uri.view()); + return; + } + } + var uri := string::new(nothing {}); + append_uri(&mut uri, path); + out.text(uri.view()); +} + +#! Appends the URI a file's line of a check begins with: the one the editor gave +#! it where it is open, which may be spelled other than as its path is, unless +#! a space or a line feed in it would end it early, and else its path's. +#! @param place What the process works with. +#! @param path The file's path. +#! @param out Where the URI is written. +def append_line_uri(place: &workplace, path: strview, out: &mut string): void { + for &each in place.documents { + continue if each.path.view() != path; + var plain := true; + for i in 0..each.uri.length { + plain = plain && each.uri[i] != ' ' && each.uri[i] != '\n'; + } + if plain { + out.append(each.uri.view()); + return; + } + break; + } + append_uri(out, path); +} + +#! Writes a place a name is written as the protocol writes a location. +#! @param place What the process works with. +#! @param file The file, as the program counts them. +#! @param start The byte the name begins at. +#! @param end The byte it ends before. +#! @param out Where it is written. +def write_location(place: &workplace, file: u32, start: u32, end: u32, out: &mut json::writer): void { + out.begin_object(); + out.member("uri"); + write_file_uri(place, place.held.paths[file].view(), out); + out.member("range"); + write_range(out, place.held.source_text(file), &place.held.sources[file].lines, start, end); + out.end_object(); +} + +#! Writes a place the checker gave, by the file of its own count. +#! @param place What the process works with. +#! @param at The place. +#! @param out Where it is written. +def write_spot(place: &workplace, at: &spot, out: &mut json::writer): void { + val file: u32 = place.held.files[at.file]; + write_location(place, file, at.offset, at.offset + at.length, out); +} + +#! The file a job asks about, as the program holds it, and the position asked +#! about within it. +struct asked_file { + var file: u32; #! The file, as the program counts them. + var unit: u32; #! The checker's index of it. + var text: strview; #! Its text, as its source holds it. + var offset: u32; #! The byte of the text the position is at. +} + +#! Finds the file a job asks about, and the position within it. +#! @param place What the process works with. +#! @param asked The job. +#! @returns The file, or nothing where the program does not check it. +def open_asked(place: &workplace, asked: &job): maybe { + val file := place.held.file_of(asked.path.view()); + return nothing {} if file == none || place.held.units[file] == none; + val text := place.held.source_text(file); + return asked_file { + file = file, + unit = place.held.units[file], + text = text, + offset = locate(text, asked.line as u64, asked.character as u64) + }; +} + +#! Writes a line for each file with notes: its URI, as `append_line_uri` gives +#! it, a space, and the JSON array of its diagnostics. A file with mistakes of +#! syntax only shows those, since what the checker says of a file it could not +#! wholly read would mislead. +#! @param place What the process works with. +#! @param out Where the answer is written. +def answer_check(place: &mut workplace, out: &mut string): void { + # The program is checked whole, as `sakura check` would check it, so what is + # shown is what it would say. What checking leaves to evaluating is evaluated + # once the program checks, which notes what goes wrong as checking does. + var notes := vector::::new(); + var whole := checker::new(&mut place.held.names, &mut notes); + place.held.check_whole(&mut whole); + if notes.length == 0 { + var clean := true; + for &file in place.held.files { + clean = clean && !place.held.broken(file); + } + if clean { + evaluate(&mut whole); + } + } + + var diagnostics := message_writer(); + for i in 0..place.held.paths.length { + val file := i as u32; + val broken := place.held.broken(file); + var found: u32 = 0; + diagnostics.clear(); + diagnostics.begin_array(); + for &each in place.held.parse_notes[i] { + write_diagnostic(place, file, &each, &mut diagnostics); + found++; + } + val unit: u32 = place.held.units[i]; + if !broken && unit != none { + for &each in notes { + continue if each.file != unit; + write_diagnostic(place, file, &each, &mut diagnostics); + found++; + } + } + diagnostics.end_array(); + continue if found == 0; + append_line_uri(place, place.held.paths[i].view(), out); + out.push(' '); + append_written(out, &mut diagnostics); + out.push('\n'); + } +} + +#! What a note says: its message, then the instance of a generic it was found +#! in, where it was found in one, as `... (box)`. +#! @param each The note. +#! @param held The source of its file. +#! @returns The text. +pub def note_text(each: ¬e, held: &source): string { + var text := each.message(held); + if each.instance.length != 0 { + text.append(" ("); + text.append(each.instance.view()); + text.append(")"); + } + return text; +} + +#! Writes a note as a diagnostic of the protocol: the range of what it is +#! about, which marks the character it is at where it is about no text, its +#! message, with the instance of a generic it was found in, and the place it +#! refers to besides its own. +#! @param place What the process works with. +#! @param file The file it is of. +#! @param each The note. +#! @param out Where it is written. +def write_diagnostic(place: &workplace, file: u32, each: ¬e, out: &mut json::writer): void { + val text := place.held.source_text(file); + val start := each.offset; + var end := start + each.length; + if end == start && (start as u64) < text.length && text[start as u64] != '\n' { + val size := serial::utf8_length(text, start as u64); + end += size != 0 ? size as u32 : 1; + } + if end as u64 > text.length { + end = text.length as u32; + } + + val message := note_text(each, &place.held.sources[file]); + val code := $"{each.code}"; + out.begin_object(); + out.member("range"); + write_range(out, text, &place.held.sources[file].lines, start, end); + out.member("severity"); out.unsigned(each.warning ? 2 : 1); + out.member("source"); out.text("sakura"); + out.member("code"); out.text(code.view()); + out.member("message"); out.text(message.view()); + if each.related.length != 0 && place.held.units[file] != none { + val other: u32 = place.held.files[each.related_file]; + out.member("relatedInformation"); + out.begin_array(); + out.begin_object(); + out.member("location"); + write_location(place, other, each.related_offset, each.related_offset + each.related_length, out); + out.member("message"); + out.text(each.related.view()); + out.end_object(); + out.end_array(); + } + out.end_object(); +} + +#! Writes the hover of the name at the position, or nothing where there is none. +#! @param place What the process works with. +#! @param asked The job. +#! @param out Where the answer is written. +def answer_hover(place: &mut workplace, asked: &job, out: &mut string): void { + val opened := open_asked(place, asked) else { return; }; + var shown := place.checker.hover(opened.unit, opened.offset) else { return; }; + + var markdown := string::new(nothing {}); + append_code(&mut markdown, shown.signature.view()); + if shown.documentation.length != 0 { + markdown.append("\n\n"); + append_markdown(&mut markdown, shown.documentation.view()); + } + var made := message_writer(); + made.begin_object(); + made.member("contents"); + write_markdown(&mut made, markdown.view()); + made.member("range"); + write_range(&mut made, opened.text, &place.held.sources[opened.file].lines, shown.offset, shown.offset + shown.length); + made.end_object(); + append_written(out, &mut made); +} + +#! The kind of completion item of the protocol each kind of name is. +#! @param kind What the name is. +#! @returns The item's kind. +def item_kind(kind: symbol): u32 { + return match kind { + symbol::keyword => 14, + symbol::namespace => 9, + symbol::function => 3, + symbol::method => 2, + symbol::variable => 6, + symbol::constant => 21, + symbol::parameter => 6, + symbol::field => 5, + symbol::struct_type => 22, + symbol::trait_type => 8, + symbol::enum_type => 13, + symbol::enum_member => 20, + symbol::type_name => 7, + symbol::type_param => 25 + }; +} + +#! Writes what an item shows beside its name in the list, read from the first +#! line of its signature, as its member `labelDetails`: the parameters of a +#! function, as `(&this, by: int)`, with what it gives, and the type of anything +#! else, as `int` of `val count: int`. +#! @param item The item. +#! @param called Whether the names follow `value.`, where a method's receiver +#! is the value, so it is not shown. +#! @param out Where it is written, within the item. +def write_label_details(item: &completion, called: bool, out: &mut json::writer): void { + val function := item.kind == symbol::function || item.kind == symbol::method; + val value := item.kind == symbol::variable || item.kind == symbol::constant || item.kind == symbol::parameter + || item.kind == symbol::field; + return if !function && !value; + + var signature := item.signature.view(); + for i in 0..signature.length { + if signature[i] == '\n' { + signature = signature.substr(0, i); + break; + } + } + val name := item.name.view(); + + # The name as the signature declares it, followed by what describes it. + var after := signature.length + 1; + var at: u64 = 0; + while at + name.length <= signature.length && after > signature.length { + val next := at + name.length; + if signature.substr(at, name.length) == name && (at == 0 || !is_word_byte(signature[at - 1])) + && next < signature.length && (signature[next] == '(' || signature[next] == '<' || signature[next] == ':') { + after = next; + } + at++; + } + return if after > signature.length; + + val rest := signature.substr(after, signature.length - after); + if rest[0] == ':' && value { + val skip: u64 = rest.length > 1 && rest[1] == ' ' ? 2 : 1; + out.member("labelDetails"); + out.begin_object(); + out.member("description"); + out.text(rest.substr(skip, rest.length - skip)); + out.end_object(); + return; + } + + # The parameters end at the `)` closing the first `(`. + var depth := 0; + var close := rest.length; + for i in 0..rest.length { + if rest[i] == '(' { + depth++; + } else if rest[i] == ')' && depth > 0 { + depth--; + if depth == 0 { + close = i; + break; + } + } + } + return if close == rest.length || !function; + + # Called on a value after `.`, a method is given its receiver, so it is not shown. + var shown := string::new(nothing {}); + var open: u64 = 0; + while open < close && rest[open] != '(' { + open++; + } + if called && item.kind == symbol::method && open + 5 <= close && rest.substr(open + 1, 4) == "this" { + var past := open + 5; + while past < close && rest[past] != ',' && rest[past] != ')' { + past++; + } + if past < close && rest[past] == ',' { + past++; + } + while past < close && rest[past] == ' ' { + past++; + } + shown.append(rest.substr(0, open + 1)); + shown.append(rest.substr(past, close + 1 - past)); + } else { + shown.append(rest.substr(0, close + 1)); + } + out.member("labelDetails"); + out.begin_object(); + out.member("detail"); + out.text(shown.view()); + var gives := rest.substr(close + 1, rest.length - close - 1); + if gives.length > 2 && gives[0] == ':' && gives[1] == ' ' { + gives = gives.substr(2, gives.length - 2); + # What a function gives ends where a `where` clause bounding it begins. + for i in 0..gives.length { + if gives.substr(i, gives.length - i).starts_with(" where ") { + gives = gives.substr(0, i); + break; + } + } + out.member("description"); + out.text(gives); + } + out.end_object(); +} + +#! Writes the names that may be written at the position, in the order found, so +#! locals come before what is declared further away. The answer is the items, +#! a zero byte, then the documentation of each item in turn, each ended by a +#! zero byte, which the server keeps to give the one item the editor asks to +#! resolve rather than sending all of it with the list. +#! @param place What the process works with. +#! @param asked The job. +#! @param out Where the answer is written. +def answer_complete(place: &mut workplace, asked: &job, out: &mut string): void { + val opened := open_asked(place, asked) else { return; }; + val items := place.checker.complete(opened.unit, opened.offset); + + # Whether the names follow `value.`, where a method's receiver is the value. + val start := word_start(opened.text, opened.offset); + val called := start > 0 && opened.text[(start - 1) as u64] == '.'; + + var documentation := string::new(nothing {}); + var made := message_writer(); + made.begin_object(); + made.member("isIncomplete"); made.boolean(false); + made.member("items"); + made.begin_array(); + for i in 0..items.length { + val item := &items[i]; + made.begin_object(); + made.member("label"); made.text(item.name.view()); + made.member("kind"); made.unsigned(item_kind(item.kind) as u64); + val order := $"{i}"; + var sorted := string::new(nothing {}); + for _ in order.length..5 { + sorted.push('0'); + } + sorted.append(order.view()); + made.member("sortText"); made.text(sorted.view()); + if item.insert.length != 0 { + made.member("insertText"); made.text(item.insert.view()); + } + write_label_details(item, called, &mut made); + + # The detail is a line, so a struct's signature shows whole in the + # documentation. + val signature := item.signature.view(); + var newline := signature.length; + for k in 0..signature.length { + if signature[k] == '\n' { + newline = k; + break; + } + } + if signature.length != 0 { + made.member("detail"); made.text(signature.substr(0, newline)); + } + + var markdown := string::new(nothing {}); + if newline < signature.length { + append_code(&mut markdown, signature); + } + if item.documentation.length != 0 { + if newline < signature.length { + markdown.append("\n\n"); + } + append_markdown(&mut markdown, item.documentation.view()); + } + if markdown.length != 0 { + made.member("data"); made.unsigned(i); + } + documentation.append(markdown.view()); + documentation.push(0); + made.end_object(); + } + made.end_array(); + made.end_object(); + append_written(out, &mut made); + out.push(0); + out.append(documentation.view()); +} + +#! Writes what is called at the position: its overloads, each with the +#! parameters of its signature marked, and which parameter is being written. +#! @param place What the process works with. +#! @param asked The job. +#! @param out Where the answer is written. +def answer_call(place: &mut workplace, asked: &job, out: &mut string): void { + val opened := open_asked(place, asked) else { return; }; + var help := place.checker.calls_at(opened.unit, opened.offset) else { return; }; + + var made := message_writer(); + made.begin_object(); + made.member("signatures"); + made.begin_array(); + for &each in help.overloads { + made.begin_object(); + made.member("label"); made.text(each.signature.view()); + # The contract its body begins with comes before what is written of it. + if each.documentation.length != 0 || each.contract.length != 0 { + var markdown := string::new(nothing {}); + if each.contract.length != 0 { + append_code(&mut markdown, each.contract.view()); + } + if each.documentation.length != 0 { + if markdown.length != 0 { + markdown.append("\n\n"); + } + append_markdown(&mut markdown, each.documentation.view()); + } + made.member("documentation"); + write_markdown(&mut made, markdown.view()); + } + + # Each parameter is a range of the label, which the editor marks in place. + made.member("parameters"); + made.begin_array(); + val label := each.signature.view(); + var begin: u64 = 0; + while begin < label.length && label[begin] != '(' { + begin++; + } + var from := begin + 1; + var nested := 0; + for at in (begin + 1)..label.length { + val byte: u8 = label[at]; + if byte == '(' || byte == '[' || byte == '<' { + nested++; + } else if (byte == ')' || byte == ']' || byte == '>') && nested > 0 { + nested--; + continue; + } + continue if nested > 0 || (byte != ',' && byte != ')'); + while from < at && label[from] == ' ' { + from++; + } + if at > from { + made.begin_object(); + made.member("label"); + made.begin_array(); made.unsigned(from); made.unsigned(at); made.end_array(); + made.end_object(); + } + from = at + 1; + break if byte == ')'; + } + made.end_array(); + # Every argument after a variadic parameter's first is given to it too. + val active := each.variadic && each.arity > 0 && help.parameter >= each.arity ? each.arity - 1 : help.parameter; + made.member("activeParameter"); made.unsigned(active as u64); + made.end_object(); + } + made.end_array(); + made.member("activeSignature"); made.unsigned(0); + made.member("activeParameter"); made.unsigned(help.parameter as u64); + made.end_object(); + append_written(out, &mut made); +} + +#! The kind of semantic token each kind of name is, in the order of the legend +#! the server declares. +#! @param kind What the name is. +#! @returns The token's kind. +def token_kind(kind: symbol): u32 { + return match kind { + symbol::namespace => 0, + symbol::struct_type => 1, + symbol::trait_type => 2, + symbol::enum_type => 3, + symbol::type_name => 4, + symbol::type_param => 5, + symbol::parameter => 6, + symbol::variable => 7, + symbol::constant => 7, + symbol::field => 8, + symbol::enum_member => 9, + symbol::function => 10, + symbol::method => 11, + symbol::keyword => 12 + }; +} + +#! Writes the names of the file as the protocol counts them: five numbers each, +#! the line and character of the first being from the beginning of the file and +#! of the rest from the name before it. +#! @param place What the process works with. +#! @param asked The job. +#! @param out Where the answer is written. +def answer_tokens(place: &mut workplace, asked: &job, out: &mut string): void { + val opened := open_asked(place, asked) else { return; }; + val found := place.checker.highlights(opened.unit); + val starts := &place.held.sources[opened.file].lines; + + var line: u32 = 0; + var character: u32 = 0; + var made := message_writer(); + made.begin_object(); + made.member("data"); + made.begin_array(); + for &each in found { + val begins := position_of(opened.text, starts, each.offset); + val ends := position_of(opened.text, starts, each.offset + each.length); + continue if ends.line != begins.line || ends.character <= begins.character || begins.line < line; + made.unsigned((begins.line - line) as u64); + made.unsigned((begins.line == line ? begins.character - character : begins.character) as u64); + made.unsigned((ends.character - begins.character) as u64); + made.unsigned(token_kind(each.kind) as u64); + made.unsigned(((each.declared ? 1 : 0) | (each.readonly ? 2 : 0)) as u64); + line = begins.line; + character = begins.character; + } + made.end_array(); + made.end_object(); + append_written(out, &mut made); +} + +#! Writes what the name at the position refers to: the name as it is written, +#! where it is, where what it refers to is declared, and why it cannot be +#! renamed, which the requests about names shape into their answers. +#! @param place What the process works with. +#! @param asked The job. +#! @param out Where the answer is written. +def answer_name(place: &mut workplace, asked: &job, out: &mut string): void { + val opened := open_asked(place, asked) else { return; }; + val named := place.checker.name_at(opened.unit, opened.offset) else { return; }; + + var made := message_writer(); + made.begin_object(); + made.member("name"); + made.text(opened.text.substr(named.at.offset as u64, named.at.length as u64)); + made.member("at"); + write_spot(place, &named.at, &mut made); + if named.declared { + made.member("declaration"); + write_spot(place, &named.declaration, &mut made); + } + if named.refusal.length != 0 { + made.member("refusal"); + made.text(named.refusal); + } + made.end_object(); + append_written(out, &mut made); +} + +#! A place a name is written, by the file of the program's count, which every +#! program the name is sought in shares. +struct placed { + var file: u32; #! The file, as the program counts them. + var start: u32; #! The byte the name begins at. + var end: u32; #! The byte it ends before. +} + +#! Writes everywhere what the name at the position refers to is written, in +#! every program, with where it is declared and why it cannot be renamed, as +#! `answer_name` does, whether it is a local or a member, and where its text is +#! written but was never resolved. +#! @param place What the process works with. +#! @param asked The job. +#! @param out Where the answer is written. +def answer_refer(place: &mut workplace, asked: &job, out: &mut string): void { + val opened := open_asked(place, asked) else { return; }; + val named := place.checker.name_at(opened.unit, opened.offset) else { return; }; + val written := opened.text.substr(named.at.offset as u64, named.at.length as u64); + + var places := vector::::new(); + var strays := vector::::new(); + var seen := vector::::new(); + var found := vector::::new(); + var stray := vector::::new(); + place.checker.refer_all(opened.unit, opened.offset, &mut found, &mut stray); + for &each in found { + keep_once(place.held.files[each.file], &each, &mut places, &mut seen); + } + for &each in stray { + keep_once(place.held.files[each.file], &each, &mut strays, &mut seen); + } + if named.declared && !named.local { + refer_elsewhere(place, &named.declaration, written, &mut places, &mut strays, &mut seen); + } + + var made := message_writer(); + made.begin_object(); + made.member("name"); + made.text(written); + made.member("locations"); + write_places(place, &places, &mut made); + if named.declared { + made.member("declaration"); + write_spot(place, &named.declaration, &mut made); + } + if named.refusal.length != 0 { + made.member("refusal"); + made.text(named.refusal); + } + made.member("local"); made.boolean(named.local); + made.member("member"); made.boolean(named.member); + made.member("unresolved"); + write_places(place, &strays, &mut made); + made.end_object(); + append_written(out, &mut made); +} + +#! Writes places a name is written, as an array of locations. +#! @param place What the process works with. +#! @param places The places. +#! @param out Where they are written. +def write_places(place: &workplace, places: &vector, out: &mut json::writer): void { + out.begin_array(); + for &each in places { + write_location(place, each.file, each.start, each.end, out); + } + out.end_array(); +} + +#! Whether text holds a name as a word of its own. +#! @param text The text. +#! @param name The name. +#! @returns Whether it does. +def mentions(text: strview, name: strview): bool { + return false if name.length == 0; + var at: u64 = 0; + while at + name.length <= text.length { + if text.substr(at, name.length) == name { + val joined := (at > 0 && is_word_byte(text[at - 1])) || (at + name.length < text.length && is_word_byte(text[at + name.length])); + return true if !joined; + } + at++; + } + return false; +} + +#! Keeps where the name is written in the programs the job was not answered +#! from. Every file but those beginning a program is in each of them, so only +#! those files are looked within, each by checking its program in turn, and +#! only where it mentions the name. What is declared in a file beginning a +#! program is not written in another program, so it is not sought. +#! @param place What the process works with. +#! @param declared Where what the name refers to is declared. +#! @param name The name as it is written. +#! @param places Where the places it is written are kept. +#! @param strays Where the places it is written unresolved are kept. +#! @param seen The places kept so far. +def refer_elsewhere( + place: &mut workplace, + declared: &spot, + name: strview, + places: &mut vector, + strays: &mut vector, + seen: &mut vector +): void { + val held := &mut place.held; + val home: u32 = held.files[declared.file]; + return if held.mains[home]; + for i in 0..held.paths.length { + val entry := i as u32; + continue if !held.mains[i] || entry == held.entry || !mentions(held.texts[i].view(), name); + + # The other program, checked with the same files, by a checker of its own. + var notes := vector::::new(); + var other := checker::new(&mut held.names, &mut notes); + target_checker(&mut other, held.system, held.native); + var units := vector::::new(); + var files := vector::::new(); + for j in 0..held.paths.length { + val file := j as u32; + if (held.mains[j] && file != entry) || (held.strict && held.broken(file)) { + units.append(none); + continue; + } + units.append(other.add(&held.sources[j], &held.syntaxes[j], held.roots[j])); + files.append(file); + } + other.check(); + val there: u32 = units[home]; + continue if there == none; + + var found := vector::::new(); + var stray := vector::::new(); + other.refer_all(there, declared.offset, &mut found, &mut stray); + for &each in found { + keep_once(files[each.file], &each, places, seen); + } + for &each in stray { + keep_once(files[each.file], &each, strays, seen); + } + } +} + +#! Keeps a place a checker gave, once. +#! @param file The place's file, as the program counts them. +#! @param at The place. +#! @param into Where it is kept. +#! @param seen The places kept so far, by file and offset. +def keep_once(file: u32, at: &spot, into: &mut vector, seen: &mut vector): void { + val key := (file as u64 << 32) | at.offset as u64; + return if seen.view().contains(&key); + seen.append(key); + into.append(placed { file = file, start = at.offset, end = at.offset + at.length }); +} diff --git a/server/jobs.sakura b/server/jobs.sakura new file mode 100644 index 00000000..1a960cdb --- /dev/null +++ b/server/jobs.sakura @@ -0,0 +1,704 @@ +#! @file jobs.sakura +#! @author John Christman (sorakatadzuma@gmail.com) +#! @copyright Malunal Studios, LLC. +#! @license MIT +#! +#! Contains how the server has a job worked out: by asking the base, which +#! starts a copy of itself for the job, or where the base cannot, by a process +#! of the server's own that works it out from nothing. Either way the job runs +#! in a process of its own, which cannot take the server down with it, and is +#! stopped where it takes too long. +#! +#! Windows cannot start a copy of a process, so there the server's processes +#! are this program started again, `lsp --base` and `lsp --worker`, which read +#! what the server works with from their input. The base answers each job +#! itself, bringing the program up to date with the files as they are, so a job +#! that faults or never ends takes only the base with it, which the server stops +#! and makes again. A worker works out one job from nothing, as the process of +#! the server's own does on Linux. + +import std::process; +import system; +import sakura::analyzer; +module sakura::server; + + +#! What each kind of job is doing, as the client's log says where it fails. +#! @param kind The kind of job. +#! @returns What it is doing. +def doing(kind: task): strview { + return match kind { + task::check => "Checking the workspace", + task::hover => "Describing the name hovered", + task::complete => "Completing the name", + task::call => "Describing what is called", + task::tokens => "Colouring the file", + task::name => "Finding what the name refers to", + task::refer => "Finding where the name is written" + }; +} + +#! Writes the documents open in the editor to a handle: how many there are, then +#! the URI, path, and text of each. +#! @param handle The handle. +#! @param documents The documents. +#! @returns Whether they were written. +def put_documents(handle: system::fd, documents: &vector): bool { + var sent := put_size(handle, documents.length); + for &each in documents { + sent = sent && put_text(handle, each.uri.view()) && put_text(handle, each.path.view()) + && put_text(handle, each.text.view()); + } + return sent; +} + +#! Reads the documents open in the editor from a handle, as `put_documents` +#! writes them, after those already held. +#! @param handle The handle. +#! @param documents Where the documents are appended. +#! @returns Whether they were read. +def get_documents(handle: system::fd, documents: &mut vector): bool { + var count: u64 = 0; + return false if !get_size(handle, &mut count, 0); + for _ in 0..count { + var each := document { uri = string::new(nothing {}), path = string::new(nothing {}), text = string::new(nothing {}) }; + return false if !get_text(handle, &mut each.uri, 0) || !get_text(handle, &mut each.path, 0) + || !get_text(handle, &mut each.text, 0); + documents.append(move(&mut each)); + } + return true; +} + +#! Writes a job to a handle, with the documents open in the editor. +#! @param handle The handle. +#! @param asked The job. +#! @param documents The documents. +#! @returns Whether it was written. +def put_job(handle: system::fd, asked: &job, documents: &vector): bool { + return put_size(handle, asked.task as u64) && put_size(handle, asked.strict ? 1 : 0) + && put_size(handle, asked.line as u64) && put_size(handle, asked.character as u64) + && put_text(handle, asked.path.view()) && put_text(handle, asked.touched.view()) + && put_text(handle, asked.entry.view()) && put_documents(handle, documents); +} + +#! Reads a job from a handle, as `put_job` writes it, with the documents open in +#! the editor, which replace those known before. +#! @param handle The handle. +#! @param asked Where the job is written. +#! @param documents Where the documents are written. +#! @returns Whether it was read. +def get_job(handle: system::fd, asked: &mut job, documents: &mut vector): bool { + var kind: u64 = 0; + var strict: u64 = 0; + var line: u64 = 0; + var character: u64 = 0; + val read := get_size(handle, &mut kind, 0) && get_size(handle, &mut strict, 0) + && get_size(handle, &mut line, 0) && get_size(handle, &mut character, 0) + && get_text(handle, &mut asked.path, 0) && get_text(handle, &mut asked.touched, 0) + && get_text(handle, &mut asked.entry, 0); + return false if !read || kind > task::refer as u64; + asked.task = kind as u8 as task; + asked.strict = strict != 0; + asked.line = line as u32; + asked.character = character as u32; + documents.clear(); + return get_documents(handle, documents); +} + +#! A job with nothing in it, to be read into. +#! @returns The job. +def empty_job(): job { + return job { + task = task::check, + path = string::new(nothing {}), + touched = string::new(nothing {}), + entry = string::new(nothing {}) + }; +} + +#! Does a job, asking the base and working it out from nothing where the base +#! cannot, and gives whether it was done. A job about a file touches it, so one +#! about a file declaring `main` is answered from that file's program. +#! @param this The server. +#! @param asked The job. +#! @param output Where the answer is written. +#! @returns Whether it was done. +def server::run_job(&mut this, asked: &mut job, output: &mut string): bool { + this.touch(asked.path.view()); + asked.touched = string::copy_of(&this.touched); + asked.entry = string::copy_of(&this.entry); + if !this.ask(asked, output) { + output.clear(); + return false if !this.fork_job(asked, output); + } + this.answered(asked, output); + return true; +} + +#! Takes the file declaring `main` that a job's program began with off the +#! front of its answer, and keeps it, so the next job is answered from the same +#! program unless another such file is touched. A job answered from another +#! program than the last says so, and has the workspace checked again where it +#! was not a check, so the diagnostics shown follow it. +#! @param this The server. +#! @param asked The job. +#! @param output The answer, which the file is taken from. +def server::answered(&mut this, asked: &job, output: &mut string): void { + val zero: u8 = 0; + val end := output.view().index_of(&zero) else { return; }; + val chosen := output.substr(0, end); + if chosen != this.entry.view() { + val moved := this.entry.length != 0 && chosen.length != 0; + this.entry = string::from(chosen, nothing {}); + this.dirty = this.dirty || asked.task != task::check; + if moved { + val shown := this.shown_path(this.entry.view()); + var text := string::from("Checking the program begun by ", nothing {}); + text.append(shown); + text.append(". The other files declaring `main` are left out until one of them is opened, edited, or asked about."); + this.log(log_info, text.view()); + } + } + var rest := string::from(output.substr(end + 1, output.length - end - 1), nothing {}); + output = move(&mut rest); +} + +#! Asks the base for a job, giving false where it could not answer, which leaves +#! the job to be worked out from nothing. A base whose files moved on is made +#! again, and the job asked of the new one. A strict check leaves out files the +#! base checked, so it is always worked out from nothing, and +#! `SAKURA_LSP_BASE=0` asks for every job to be, which is how the two are +#! compared. +#! @param this The server. +#! @param asked The job. +#! @param output Where the answer is written. +#! @returns Whether the base answered. +def server::ask(&mut this, asked: &job, output: &mut string): bool { + return false if asked.strict; + if variable("SAKURA_LSP_BASE") is some(wanted) { + return false if wanted == "0"; + } + var status := this.ask_once(asked, output); + if status == answer_stale { + this.stop_base(); + output.clear(); + status = this.ask_once(asked, output); + } + return status == answer_ok; +} + +#! Asks the base for a job once. +#! @param this The server. +#! @param asked The job. +#! @param output Where the answer is written. +#! @returns What the base said of it, or `answer_fail` where it did not answer. +def server::ask_once(&mut this, asked: &job, output: &mut string): u64 { + return answer_fail if !this.start_base(); + val sent := put_job(this.base.jobs, asked, &this.documents); + var status: u64 = answer_fail; + var answer := string::new(nothing {}); + val deadline := now_ms() + timeout; + val heard := sent && get_size(this.base.answers, &mut status, deadline) + && get_text(this.base.answers, &mut answer, deadline); + if !heard { + this.stop_base(); + if sent { + this.log_failure(asked.task, " took longer than 30 seconds, or stopped unexpectedly, and was stopped."); + } + return answer_fail; + } + if status == answer_ok { + output.append(answer.view()); + } + return status; +} + +#! Logs that a job was not done: what it was doing, then what went wrong. +#! @param this The server. +#! @param kind The kind of job. +#! @param what What went wrong, which follows what it was doing, as +#! ` stopped unexpectedly.`. +def server::log_failure(&mut this, kind: task, what: strview): void { + var text := string::from(doing(kind), nothing {}); + text.append(what); + this.log(log_error, text.view()); +} + +#! The base itself: it reads and checks the files of the workspace once, then +#! answers each job, as `answer_jobs` does on the system it runs on. +#! @param this The server, as the base copied or read it. +#! @param jobs Where jobs are read. +#! @param answers Where answers are written. +def server::base_main(&mut this, jobs: system::fd, answers: system::fd): void { + # On Linux, the base copies the server, so it leads a group of its own, which + # the copies it starts belong to, and writes nothing where the server answers. + when os == linux { + lead_group(); + quiet_output(); + } + var files := gather_all(&this.gathering()); + var held := program::parse(&files, false, this.options.native, this.options.system, &this.gathering()); + var checker := checker::new(&mut held.names, &mut held.check_notes); + held.begin(&mut checker, held.choose(this.touched.view(), this.entry.view())); + checker.check(); + this.answer_jobs(&mut held, &mut checker, jobs, answers); +} + +#! Gathers the files a job is worked out from as they are now, with the +#! placeholder written where it completes a name after `.`. +#! @param this The server. +#! @param asked The job. +#! @returns The files. +def server::gather_for(&this, asked: &job): vector { + var files := gather_all(&this.gathering()); + write_placeholder(&mut files, asked); + return files; +} + +#! Works out one job from nothing, in a process of its own: reads the files, +#! parses and checks them, answers, and writes the answer. +#! @param this The server, as the process copied or read it. +#! @param asked The job. +#! @param out Where the answer is written. +def server::work_alone(&mut this, asked: &job, out: system::fd): void { + var files := this.gather_for(asked); + var held := program::parse(&files, asked.strict, this.options.native, this.options.system, &this.gathering()); + var checker := checker::new(&mut held.names, &mut held.check_notes); + held.begin(&mut checker, held.choose(asked.touched.view(), asked.entry.view())); + if asked.task != task::check { + checker.check(); + } + var place := workplace { held = &mut held, checker = &mut checker, documents = &this.documents }; + var made := string::new(nothing {}); + answer(&mut place, asked, &mut made); + put_all(out, made.view()); +} + +#! The two pipes between the server and a process of its own: one jobs are sent +#! to it by, and one its answers come back by. +struct pipes { + var jobs_read: system::fd; #! Where the process reads jobs. + var jobs_write: system::fd; #! Where the server writes them. + var answers_read: system::fd; #! Where the server reads answers. + var answers_write: system::fd; #! Where the process writes them. +} + +#! Makes the two pipes between the server and a process of its own, or neither. +#! @returns The pipes, or nothing where they could not be made. +def make_pipes(): maybe { + var made := pipes { jobs_read = -1, jobs_write = -1, answers_read = -1, answers_write = -1 }; + return nothing {} if system::pipe(&mut made.jobs_read, &mut made.jobs_write) != 0; + if system::pipe(&mut made.answers_read, &mut made.answers_write) != 0 { + made.jobs_read.close(); + made.jobs_write.close(); + return nothing {}; + } + return made; +} + +#! Closes the ends of the pipes the process keeps, which the server lets go of +#! once the process has them. +#! @param this The pipes. +def pipes::close_process_ends(&this): void { + this.jobs_read.close(); + this.answers_write.close(); +} + +#! Closes the ends of the pipes the server keeps. +#! @param this The pipes. +def pipes::close_server_ends(&this): void { + this.jobs_write.close(); + this.answers_read.close(); +} + +when os == linux { + #! Starts the base, giving false where it could not be, so the job is worked out + #! from nothing instead. + #! @param this The server. + #! @returns Whether the base is running. + def server::start_base(&mut this): bool { + return true if this.base.process > 0; + val ends := make_pipes() else { return false; }; + + val child := system::fork(); + if child == 0 { + ends.close_server_ends(); + this.base_main(ends.jobs_read, ends.answers_write); + system::exit(0); + } + ends.close_process_ends(); + if child < 0 { + ends.close_server_ends(); + return false; + } + this.base = base_link { process = child, jobs = ends.jobs_write, answers = ends.answers_read }; + return true; + } + + #! Stops the base, and every copy of it working out a job, which is made again + #! once it is next needed. + #! @param this The server. + def server::stop_base(&mut this): void { + return if this.base.process <= 0; + this.base.jobs.close(); + this.base.answers.close(); + system::kill(0 - this.base.process, system::signal::kill); + var status := system::process_status {}; + reap(this.base.process, &mut status); + this.base = base_link {}; + } + + #! Answers each job the base is sent by a copy of itself, which brings the + #! program up to date with the files as they are and answers, and once a check + #! is answered, brings the base up to date the same way. + #! @param this The server, as the base copied it. + #! @param held The program, as the base read and checked it. + #! @param checker Its checker. + #! @param jobs Where jobs are read. + #! @param answers Where answers are written. + def server::answer_jobs(&mut this, held: &mut program, checker: &mut checker, jobs: system::fd, answers: system::fd): void { + var asked := empty_job(); + while true { + if !get_job(jobs, &mut asked, &mut this.documents) { + system::exit(0); + } + + var reading: system::fd = -1; + var writing: system::fd = -1; + if system::pipe(&mut reading, &mut writing) != 0 { + put_size(answers, answer_fail); + put_text(answers, ""); + continue; + } + val worker := system::fork(); + if worker == 0 { + reading.close(); + jobs.close(); + answers.close(); + val code := this.base_work(held, checker, &asked, writing); + system::exit(code); + } + writing.close(); + var output := string::new(nothing {}); + if worker > 0 { + get_rest(reading, &mut output); + } + reading.close(); + + var status := system::process_status {}; + val waited := worker > 0 && reap(worker, &mut status); + val done := waited && status.exited && status.code == 0; + val stale := waited && status.exited && status.code == worker_stale; + if !put_size(answers, done ? answer_ok : stale ? answer_stale : answer_fail) + || !put_text(answers, done ? output.view() : "") { + system::exit(0); + } + + # The copy showed the files can be brought up to date without a fault, so + # once a check is answered, the base brings itself up to date too. + if done && asked.task == task::check { + var now := gather_all(&this.gathering()); + if held.sync(checker, &now, asked.touched.view(), asked.entry.view(), true, &this.gathering()) == synced::stale { + system::exit(0); + } + } + } + } + + #! Works out one job, in a copy of the base, which brings the program up to date + #! with the files as they are, answers, and writes the answer. + #! @param this The server, as the base copied it. + #! @param held The program, as the base has it. + #! @param checker Its checker. + #! @param asked The job. + #! @param out Where the answer is written. + #! @returns The status to exit with: 0 where the job is answered, and + #! `worker_stale` where the files moved on in a way the program cannot + #! follow. + def server::base_work(&mut this, held: &mut program, checker: &mut checker, asked: &job, out: system::fd): i32 { + var files := this.gather_for(asked); + # A check checks the program whole, so what changed is only parsed again. + val checks := asked.task != task::check; + return worker_stale if held.sync(checker, &files, asked.touched.view(), asked.entry.view(), checks, &this.gathering()) == synced::stale; + + var place := workplace { held = held, checker = checker, documents = &this.documents }; + var output := string::new(nothing {}); + answer(&mut place, asked, &mut output); + put_all(out, output.view()); + return 0; + } + + #! Works out a job from nothing, in a process of its own, and collects what it + #! writes. Gives false where it did not finish. + #! @param this The server. + #! @param asked The job. + #! @param output Where the answer is written. + #! @returns Whether it finished. + def server::fork_job(&mut this, asked: &job, output: &mut string): bool { + var reading: system::fd = -1; + var writing: system::fd = -1; + if system::pipe(&mut reading, &mut writing) != 0 { + this.log_failure(asked.task, " failed: no pipe could be made."); + return false; + } + + val child := system::fork(); + if child == 0 { + reading.close(); + quiet_output(); + this.work_alone(asked, writing); + system::exit(0); + } + writing.close(); + if child < 0 { + reading.close(); + this.log_failure(asked.task, " failed: no process could be started."); + return false; + } + + val finished := get_until(reading, output, now_ms() + timeout); + reading.close(); + if !finished { + system::kill(child, system::signal::kill); + } + var status := system::process_status {}; + reap(child, &mut status); + + if !finished { + this.log_failure(asked.task, " took longer than 30 seconds and was stopped."); + } else if !status.exited { + val said := $" stopped unexpectedly with signal {status.signal}."; + this.log_failure(asked.task, said.view()); + } else if status.code != 0 { + this.log_failure(asked.task, " stopped unexpectedly."); + } else { + return true; + } + return false; + } +} + +when os == windows { + # The word a process the server starts is sent first, which changes whenever + # what it is sent does, so a process of another build, as one put in place of + # the executable while the server runs, says it cannot read what it is sent + # rather than misreading it. + val process_version: u64 = 3; + + # The digits of hexadecimal, as the code of an exception is written with them, + # lowest first. + val hex_upper: strview = "0123456789ABCDEF"; + + #! Writes what a process the server starts works with, which on Windows it + #! cannot copy from the server: the libraries, the standard library's among + #! them, what the workspace is checked for, the file last touched and the + #! program last answered from, the workspace folders, and the documents open + #! in the editor. + #! @param this The server. + #! @param handle The handle. + #! @param documents The documents, which are none for a worker, since the + #! job it is sent brings them. + #! @returns Whether it was written. + def server::put_state(&this, handle: system::fd, documents: &vector): bool { + var sent := put_size(handle, process_version) + && put_size(handle, this.options.native ? 1 : 0) && put_text(handle, this.options.system) + && put_text(handle, this.touched.view()) && put_text(handle, this.entry.view()) + && put_size(handle, this.libraries.length); + for &each in this.libraries { + sent = sent && put_text(handle, each.view()); + } + sent = sent && put_size(handle, this.roots.length); + for &each in this.roots { + sent = sent && put_text(handle, each.view()); + } + return sent && put_documents(handle, documents); + } + + #! Reads what a process the server starts works with, as `put_state` writes + #! it, after the word of its version, which `serve_process` reads. + #! @param this The process's server, which it is read into. + #! @param handle The handle. + #! @param system Where the name of the system the workspace is checked for + #! is kept, which the server's options view. + #! @returns Whether it was read. + def server::get_state(&mut this, handle: system::fd, system: &mut string): bool { + var native: u64 = 0; + var libraries: u64 = 0; + var roots: u64 = 0; + val read := get_size(handle, &mut native, 0) + && get_text(handle, system, 0) && get_text(handle, &mut this.touched, 0) + && get_text(handle, &mut this.entry, 0) && get_size(handle, &mut libraries, 0); + return false if !read; + this.options.native = native != 0; + this.options.system = system.view(); + for _ in 0..libraries { + var library := string::new(nothing {}); + return false if !get_text(handle, &mut library, 0); + this.libraries.append(move(&mut library)); + } + return false if !get_size(handle, &mut roots, 0); + for _ in 0..roots { + var root := string::new(nothing {}); + return false if !get_text(handle, &mut root, 0); + this.roots.append(move(&mut root)); + } + return get_documents(handle, &mut this.documents); + } + + #! Works out what the server asks of a process it started, which on Windows is + #! this program started again, as `lsp --base` or `lsp --worker`: it reads what + #! the server works with from its standard input, then answers, as the base, + #! each job it is sent there, or as a worker, the one job, writing the answers + #! to its standard output. + #! @param base Whether it is the base, rather than a worker. + #! @returns The status to exit with: 0 where it read what it was sent, 2 where + #! another build of the server sent it, and 1 otherwise. + pub def serve_process(base: bool): i32 { + val answers := take_output(); + var version: u64 = 0; + return 1 if !get_size(system::fd::stdin, &mut version, 0); + if version != process_version { + system::fd::stderr.put("sakura: lsp: a process of the language server is only started by the server of the same build\n"); + return 2; + } + + var system := string::new(nothing {}); + var running := make_server(&server_options {}); + return 1 if !running.get_state(system::fd::stdin, &mut system); + if base { + running.base_main(system::fd::stdin, answers); + return 0; + } + var asked := empty_job(); + return 1 if !get_job(system::fd::stdin, &mut asked, &mut running.documents); + running.work_alone(&asked, answers); + return 0; + } + + #! Starts the base, giving false where it could not be, so the job is worked out + #! from nothing instead. + #! @param this The server. + #! @returns Whether the base is running. + def server::start_base(&mut this): bool { + return true if this.base.process > 0; + val ends := make_pipes() else { return false; }; + + val child := start_process("--base", ends.jobs_read, ends.answers_write); + ends.close_process_ends(); + if child == 0 { + ends.close_server_ends(); + return false; + } + this.base = base_link { process = child, jobs = ends.jobs_write, answers = ends.answers_read }; + + # The base reads what it works with before anything else, so it is sent now. + if !this.put_state(ends.jobs_write, &this.documents) { + this.stop_base(); + return false; + } + return true; + } + + #! Stops the base, which answers each job itself, so nothing else is working + #! one out, and which is made again once it is next needed. + #! @param this The server. + def server::stop_base(&mut this): void { + return if this.base.process <= 0; + this.base.jobs.close(); + this.base.answers.close(); + var code: u32 = 0; + end_process(this.base.process, 0, &mut code); + this.base = base_link {}; + } + + #! Answers each job the base is sent itself, bringing the program up to date + #! with the files as they are, since it cannot answer by a copy of itself. + #! Files that moved on in a way the program cannot follow end it once it has + #! said so, and the server makes another. + #! @param this The server, as the base read it. + #! @param held The program, as the base read and checked it. + #! @param checker Its checker. + #! @param jobs Where jobs are read. + #! @param answers Where answers are written. + def server::answer_jobs(&mut this, held: &mut program, checker: &mut checker, jobs: system::fd, answers: system::fd): void { + var asked := empty_job(); + while true { + return if !get_job(jobs, &mut asked, &mut this.documents); + var output := string::new(nothing {}); + val status := this.base_answer(held, checker, &asked, &mut output); + return if !put_size(answers, status) || !put_text(answers, output.view()) || status != answer_ok; + } + } + + #! Works out one job in the base itself, which brings the program up to date + #! with the files as they are, checking again what that affects, as the base + #! on Linux brings itself up to date once a check is answered, and answers. + #! @param this The server, as the base read it. + #! @param held The program. + #! @param checker Its checker. + #! @param asked The job. + #! @param out Where the answer is written. + #! @returns `answer_ok` where the job is answered, and `answer_stale` where the + #! files moved on in a way the program cannot follow, which leaves it + #! brought up to date only in part. + def server::base_answer(&mut this, held: &mut program, checker: &mut checker, asked: &job, out: &mut string): u64 { + var files := this.gather_for(asked); + return answer_stale if held.sync(checker, &files, asked.touched.view(), asked.entry.view(), true, &this.gathering()) == synced::stale; + + var place := workplace { held = held, checker = checker, documents = &this.documents }; + answer(&mut place, asked, out); + return answer_ok; + } + + #! Works out a job from nothing, in a worker, a process of its own, and + #! collects what it writes. Gives false where it did not finish. + #! @param this The server. + #! @param asked The job. + #! @param output Where the answer is written. + #! @returns Whether it finished. + def server::fork_job(&mut this, asked: &job, output: &mut string): bool { + val ends := make_pipes() else { + this.log_failure(asked.task, " failed: no pipe could be made."); + return false; + }; + + val child := start_process("--worker", ends.jobs_read, ends.answers_write); + ends.close_process_ends(); + if child == 0 { + ends.close_server_ends(); + this.log_failure(asked.task, " failed: no process could be started."); + return false; + } + + # The worker reads all it is sent before it writes anything, so it is sent + # all at once, and its answer read until it ends. The answer ends as the + # worker does, unless it closed its output and went on. + val none := vector::::new(); + if this.put_state(ends.jobs_write, &none) { + put_job(ends.jobs_write, asked, &this.documents); + } + ends.jobs_write.close(); + val deadline := now_ms() + timeout; + val finished := get_until(ends.answers_read, output, deadline); + ends.answers_read.close(); + var code: u32 = 1; + val ended := end_process(child, finished ? deadline : 0, &mut code); + + if !ended { + this.log_failure(asked.task, " took longer than 30 seconds and was stopped."); + } else if code >= 0xC0000000 { + var said := string::from(" stopped unexpectedly with exception 0x", nothing {}); + for i in 0u..8u { + said.push(hex_upper[((code >> (28 - 4 * i as u32)) & 0xF) as u64]); + } + said.append("."); + this.log_failure(asked.task, said.view()); + } else if code != 0 { + val said := $" stopped unexpectedly with exit code {code}."; + this.log_failure(asked.task, said.view()); + } else { + return true; + } + return false; + } +} diff --git a/server/program.sakura b/server/program.sakura new file mode 100644 index 00000000..84e530a2 --- /dev/null +++ b/server/program.sakura @@ -0,0 +1,532 @@ +#! @file program.sakura +#! @author John Christman (sorakatadzuma@gmail.com) +#! @copyright Malunal Studios, LLC. +#! @license MIT +#! +#! Contains the files a check reads, and the program they make: `core`, every +#! `.sakura` file of the workspace folders, and the modules of `system` and the +#! standard library those refer to, with the runtime where an executable is +#! checked for, read as a check reads them, each with the +#! text open in the editor where it is open, and otherwise its text on disk, +#! lexed and parsed, and those of one program checked. +#! +#! Where several files declare `main`, each begins a program holding every +#! file that declares none, and one is checked at a time, so their `main`s do +#! not clash: that of the file last opened, edited, or asked about where it +#! declares `main`, else the one checked last, else the one whose file comes +#! first by path. The rest are parsed, so their mistakes of syntax are shown, +#! but nothing in them is declared or checked. +#! +#! Once made, a program is brought up to date with the files as they are by +#! parsing again only what changed of each file that changed, and checking +#! again only what that affects, as `checker::update` does. + +import std::io; +import system; +import sakura::analyzer; +module sakura::server; + + +#! A document open in the editor. +pub struct document { + pub var uri: string; #! The URI the editor names it by. + pub var path: string; #! Its path, or empty where it is no file, as an unsaved one. + pub var text: string; #! Its text, as the editor has it. +} + +#! A file a check reads: its path, and the text it is read with. +pub struct gathered { + pub var path: string; #! The file's path. + pub var text: string; #! Its text. +} + +#! What the files of a check are gathered from. +pub struct gathering { + pub var core: strview; #! `core`'s directory, or empty. + pub var system: strview; #! `system`'s directory, or empty. + pub var runtime: strview; #! The runtime's directory, or empty. + pub var libraries: span; #! The libraries, each as `NAME=DIR`, the standard library's among them. + pub var roots: &vector; #! The workspace folders. + pub var documents: &vector; #! The documents open in the editor. +} + +#! The most directories deep the folders are read. +const deepest: u32 = 64; + +#! A name a directory holds, and what it names. +struct listed { + var name: string; + var kind: file_kind; +} + +#! Gathers the files a check reads before what they refer to: the types the +#! syntax makes and `core`'s, then each of the workspace folders', or the +#! documents open in the editor where there is no folder, and any of `system`, +#! the runtime, and the libraries, the standard library's among them, open in +#! the editor, whose modules are read whole. +#! Each is read with the text open in the editor where it is open. +#! @param from What they are gathered from. +#! @returns The files. +pub def gather_all(from: &gathering): vector { + var made := vector::::new(); + if from.core.length != 0 { + made.append(gathered { path = string::from(builtin_path, nothing {}), text = string::from(builtin_text, nothing {}) }); + gather_directory(from, from.core, &mut made, 0, true); + } + for &each in from.documents { + if is_sakura(each.path.view()) && (within_folder(each.path.view(), from.system) || within_folder(each.path.view(), from.runtime) + || within_libraries(from, each.path.view())) { + gather_file(from, each.path.view(), &mut made); + } + } + for &root in from.roots { + gather_directory(from, root.view(), &mut made, 0, false); + } + # Without a workspace folder, the files open in the editor are the program. + if from.roots.length == 0 { + for &each in from.documents { + if each.path.length != 0 && is_sakura(each.path.view()) { + gather_file(from, each.path.view(), &mut made); + } + } + } + return made; +} + +#! The directory of a library given as `NAME=DIR`. +#! @param given The library. +#! @returns The directory, or empty where none is given. +def library_folder(given: strview): strview { + val split := given.index_of(&'=') else { return strview::empty(); }; + return given.substr(split + 1, given.length - split - 1); +} + +#! Whether a path is one of the libraries' directories. +#! @param from What the files are gathered from. +#! @param at The path. +#! @returns Whether it is. +def is_library_folder(from: &gathering, at: strview): bool { + for &each in from.libraries { + return true if library_folder(each.view()) == at; + } + return false; +} + +#! Whether a path is within one of the libraries' directories. +#! @param from What the files are gathered from. +#! @param at The path. +#! @returns Whether it is. +def within_libraries(from: &gathering, at: strview): bool { + for &each in from.libraries { + return true if within_folder(at, library_folder(each.view())); + } + return false; +} + +#! Whether a path is within a folder. +#! @param at The path. +#! @param folder The folder, or empty, which holds nothing. +#! @returns Whether it is. +def within_folder(at: strview, folder: strview): bool { + return folder.length != 0 && at.length > folder.length && at.starts_with(folder) && at[folder.length] == '/'; +} + +#! The resolver of the libraries a check reads: `core`, read whole, and +#! `system`, the runtime, and the libraries, the standard library's among them, +#! read by what refers to them. +#! @param from What the files are gathered from. +#! @returns The resolver. +pub def library_finder(from: &gathering): resolver { + var made := resolver::new(); + if from.core.length != 0 { + made.whole("core", from.core); + } + if from.system.length != 0 { + made.add_library("system", from.system); + } + if from.runtime.length != 0 { + made.add_library("runtime", from.runtime); + } + for &each in from.libraries { + val split := each.view().index_of(&'=') else { continue; }; + made.add_library(each.view().substr(0, split), library_folder(each.view())); + } + return made; +} + +#! The text of a library's file, as the editor has it where it is open, and +#! otherwise as it is on disk, or empty where it cannot be read. +#! @param from What the files are gathered from. +#! @param at The file's path. +#! @returns The text. +def library_text(from: &gathering, at: strview): string { + for &each in from.documents { + return string::copy_of(&each.text) if each.path.view() == at; + } + var text := string::new(nothing {}); + _ = read_text(at, &mut text); + return text; +} + +#! Adds a file to what is gathered, once, with the text open in the editor where +#! it is open, and otherwise its text on disk. +#! @param from What the files are gathered from. +#! @param at The file's path. +#! @param into What is gathered so far. +def gather_file(from: &gathering, at: strview, into: &mut vector): void { + for &each in into { + return if each.path.view() == at; + } + for &each in from.documents { + if each.path.view() == at { + into.append(gathered { path = string::from(at, nothing {}), text = string::copy_of(&each.text) }); + return; + } + } + var text := string::new(nothing {}); + return if !read_text(at, &mut text); + into.append(gathered { path = string::from(at, nothing {}), text = move(&mut text) }); +} + +#! Gathers the `.sakura` files of a directory and those within it, by name, +#! passing over hidden directories, `node_modules`, and, within a workspace +#! folder, the libraries, which are gathered on their own. A link to a +#! directory is not followed, so a link cannot lead the reading in a circle. +#! @param from What the files are gathered from. +#! @param at The directory's path. +#! @param into What is gathered so far. +#! @param depth How deep the directory is. +#! @param library Whether it is a library's, as `core`'s. +def gather_directory(from: &gathering, at: strview, into: &mut vector, depth: u32, library: bool): void { + return if depth > deepest; + var found := path::parse(at) else (_) { return; }; + var listing := io::directory::open(&found) else (_) { return; }; + var entries := vector::::new(); + while listing.next() is some(each) { + continue if each.name.length == 0 || each.name[0] == '.' || each.name == "node_modules"; + entries.append(listed { name = string::from(each.name, nothing {}), kind = each.kind }); + } + + # Read in the order of their names, so a check reads the files alike however + # the system lists them. + entries.sort_by(def(a: &listed, b: &listed): bool { return a.name.compare(b.name.view()) < 0; }); + + var inner := vector::::new(); + for &each in entries { + var joined := $"{at}/{each.name}"; + var kind: file_kind = each.kind; + if kind == file_kind::link { + var linked := path::parse(joined.view()) else (_) { continue; }; + val info := io::info(&linked) else (_) { continue; }; + continue if info.kind == file_kind::directory; + kind = info.kind; + } + if kind == file_kind::directory { + # `core`, `system`, the runtime, and the libraries within a workspace + # folder are gathered on their own. + continue if !library && is_library_folder(from, joined.view()); + continue if !library && from.core.length != 0 && joined.view() == from.core; + continue if !library && from.system.length != 0 && joined.view() == from.system; + continue if !library && from.runtime.length != 0 && joined.view() == from.runtime; + inner.append(move(&mut joined)); + } else if kind == file_kind::regular && is_sakura(each.name.view()) { + gather_file(from, joined.view(), into); + } + } + for &each in inner { + gather_directory(from, each.view(), into, depth + 1, library); + } +} + +#! What says none, of a file a program leaves out or a program begun by none. +pub const none: u32 = 0xFFFFFFFF; + +#! The files of a check, lexed and parsed, and which make the program checked. +#! The checker refers to what this holds, so once it is made this stays where +#! it is. +pub struct program { + pub var names: names; #! The names the files were lexed with. + pub var parse_notes: vector>; #! What lexing and parsing noted of each file. + pub var check_notes: vector; #! What checking noted, each by the checker's index of its file. + pub var paths: vector; #! The path of each file. + pub var texts: vector; #! The text each was parsed with. + pub var sources: vector; #! Each file's source. + pub var syntaxes: vector; #! What each parsed into. + pub var roots: vector; #! The `document` node of each. + pub var mains: vector; #! Whether each declares `main`. + pub var units: vector; #! The checker's index of each, or `none` where the program leaves it out. + pub var files: vector; #! The file of each of the checker's indexes. + pub var entry: u32; #! The file declaring `main` the program begins with, or `none`. + pub var strict: bool; #! Whether files with mistakes of syntax are left out, as a check without drafts does. + pub var native: bool; #! Whether it is checked for an executable. + pub var system: strview; #! The operating system it is checked for, as `linux`. + pub var given: u64; #! How many of the files were gathered; the rest are the libraries' files they refer to. + var finder: resolver; #! What found the libraries' files, which finds what an edit refers to anew. +} + +#! Lexes and parses the files gathered, then the files of the libraries' modules +#! they refer to, a round at a time, as a check reads them, ready to be checked +#! as a program. +#! @param files The files gathered. +#! @param strict Whether files with mistakes of syntax are left out of the +#! program. +#! @param native Whether it is checked for an executable, which reads the +#! runtime too. +#! @param system The operating system it is checked for, as `linux`. +#! @param from What the files were gathered from, which says where the +#! libraries are. +#! @returns The files, parsed. +pub def program::parse(files: &vector, strict: bool, native: bool, system: strview, from: &gathering): program { + var made := program { + names = names::new(), + parse_notes = vector::>::new(), + check_notes = vector::::new(), + paths = vector::::new(), + texts = vector::::new(), + sources = vector::::new(), + syntaxes = vector::::new(), + roots = vector::::new(), + mains = vector::::new(), + units = vector::::new(), + files = vector::::new(), + entry = none, + strict = strict, + native = native, + system = system, + given = files.length, + finder = library_finder(from) + }; + + # Each file's path, source, and syntax stay where they are once the checker + # refers to them, so there is room for every file before any is made. + val room := files.length + made.finder.files_held(); + made.paths.reserve(room); + made.texts.reserve(room); + made.sources.reserve(room); + made.syntaxes.reserve(room); + made.parse_notes.reserve(room); + for &each in files { + made.finder.mark(each.path.view()); + made.add(each.path.view(), &each.text); + } + + # What the files refer to is read after them, until a round refers to + # nothing new. + var done: u64 = 0; + while done < made.paths.length { + var found := vector::::new(); + if done == 0 && native { + made.finder.want("runtime", &mut found); + } + val to := made.paths.length; + for i in done..to { + made.finder.refer(&made.syntaxes[i], &made.names, &mut found); + } + done = to; + for &each in found { + val text := library_text(from, each.view()); + made.add(each.view(), &text); + } + } + return made; +} + +#! Adds a file to the program, lexed and parsed. +#! @param this The program. +#! @param path The file's path. +#! @param text Its text. +def program::add(&mut this, path: strview, text: &string): void { + val i := this.paths.length; + this.paths.append(string::from(path, nothing {})); + this.texts.append(string::copy_of(text)); + this.parse_notes.append(vector::::new()); + this.sources.append(source::from(this.paths[i].view(), text.view())); + this.syntaxes.append(syntax::new()); + val main := this.names.intern(&"main"); + var lexing := lexer::new(&mut this.sources[i], &mut this.names, &mut this.parse_notes[i], i as u32); + lexing.tokenize_all(&mut this.syntaxes[i]); + var parsing := parser::new(&mut this.syntaxes[i], &this.names, &mut this.parse_notes[i], i as u32); + this.roots.append(parsing.parse()); + this.mains.append(this.syntaxes[i].declares_main(this.roots[i], main)); +} + +#! Whether a file has mistakes of syntax. +#! @param this The program. +#! @param file The file. +#! @returns Whether it has. +pub def program::broken(&this, file: u32): bool { + return this.parse_notes[file].length != 0; +} + +#! The text of a file as its source holds it, which the places the checker +#! gives are within: the text it was parsed with, but with each CR LF line +#! break the LF alone. A position of the protocol is the same in either, since +#! it counts lines, and characters within a line, which the CR ends. +#! @param this The program. +#! @param file The file. +#! @returns The text. +pub def program::source_text(&this, file: u32): strview { + val held := &this.sources[file]; + return held.make_lexeme(0, held.length); +} + +#! The file declaring `main` a program begins with: the one last opened, edited, +#! or asked about where it declares `main`, else the one checked last, else the +#! one whose path comes first. +#! @param this The program. +#! @param touched The path of the file last opened, edited, or asked about, or +#! empty. +#! @param last The path of the file the last program began with, or empty. +#! @returns The file, or `none` where none declares `main`. +pub def program::choose(&this, touched: strview, last: strview): u32 { + var chosen := none; + for i in 0..this.paths.length { + if this.mains[i] && this.paths[i].view() == touched && this.usable(i as u32) { + chosen = i as u32; + } + } + return chosen if chosen != none; + for i in 0..this.paths.length { + if this.mains[i] && this.paths[i].view() == last && this.usable(i as u32) { + chosen = i as u32; + } + } + return chosen if chosen != none; + for i in 0..this.paths.length { + continue if !this.mains[i] || !this.usable(i as u32); + if chosen == none || this.paths[i].compare(this.paths[chosen].view()) < 0 { + chosen = i as u32; + } + } + return chosen; +} + +#! Whether a file may be checked: any, unless the program is strict, which +#! leaves out files with mistakes of syntax. +#! @param this The program. +#! @param file The file. +#! @returns Whether it may be. +def program::usable(&this, file: u32): bool { + return !this.strict || !this.broken(file); +} + +#! Sets what a checker checks a program for, which `when` decides by: the +#! operating system, and the backend of an executable where it is checked for +#! one. +#! @param checker The checker. +#! @param system The operating system, as `linux`. +#! @param native Whether it is checked for an executable. +pub def target_checker(checker: &mut checker, system: strview, native: bool): void { + checker.target.os = checker.names.intern(&system); + if native { + checker.target.backend = checker.names.intern(&"native"); + } +} + +#! Gives the checker the files of the program the file begins: it, and every +#! file declaring no `main`. +#! @param this The program. +#! @param checker The checker, made of this program's names and notes. +#! @param entry The file declaring `main`, or `none`. +pub def program::begin(&mut this, checker: &mut checker, entry: u32): void { + this.entry = entry; + target_checker(checker, this.system, this.native); + checker.shelves = this.finder.held(); + for i in 0..this.paths.length { + val file := i as u32; + val taken := (!this.mains[i] || file == entry) && this.usable(file); + if !taken { + this.units.append(none); + continue; + } + this.units.append(checker.add(&this.sources[i], &this.syntaxes[i], this.roots[i])); + this.files.append(file); + } +} + +#! What bringing a program up to date with the files found. +pub enum synced : u8 { + same, #! It is up to date, having checked again what changed. + stale, #! The files moved on in a way it cannot follow: some are new or gone, or another program is to be checked. +} + +#! Brings a program up to date with the files as they are now: each file whose +#! text changed is parsed again where it changed, and what that affects is +#! checked again. Where files are new or gone, a file refers to a module not +#! read, or a file's `main` changes which program is checked, the program +#! cannot follow, and says so. +#! @param this The program. +#! @param checker Its checker. +#! @param files The files as they are now. +#! @param touched The path of the file last opened, edited, or asked about. +#! @param last The path of the file the last program began with. +#! @param checks Whether what changed is checked again, rather than only +#! parsed again, as for a check, which checks the program whole. +#! @param from What the files were gathered from, which the libraries' +#! files are read again from. +#! @returns Whether it is up to date. +pub def program::sync( + &mut this, checker: &mut checker, files: &vector, touched: strview, last: strview, checks: bool, from: &gathering +): synced { + return synced::stale if files.length != this.given; + for i in 0..files.length { + return synced::stale if files[i].path.view() != this.paths[i].view(); + } + + val main := this.names.intern(&"main"); + for i in 0..this.paths.length { + val now := i < this.given ? string::copy_of(&files[i].text) : library_text(from, this.paths[i].view()); + continue if now.view() == this.texts[i].view(); + val file := i as u32; + val was_broken := this.broken(file); + var fresh_source := source::from(this.paths[i].view(), now.view()); + var fresh := syntax::new(); + var fresh_notes := vector::::new(); + var lexing := lexer::new(&mut fresh_source, &mut this.names, &mut fresh_notes, file); + lexing.tokenize_all(&mut fresh); + this.roots[i] = this.syntaxes[i].reparse(&mut fresh, &this.names, this.roots[i], &mut this.parse_notes[i], &mut fresh_notes, file); + this.sources[i] = move(&mut fresh_source); + this.texts[i] = string::copy_of(&now); + + # A file referring to a module not read changes what the program holds. + var found := vector::::new(); + this.finder.refer(&this.syntaxes[i], &this.names, &mut found); + return synced::stale if found.length != 0; + + # A file changing whether it declares `main`, or a strict program's file + # gaining or losing its mistakes, changes what the program holds. + val mains := this.syntaxes[i].declares_main(this.roots[i], main); + return synced::stale if mains != this.mains[i]; + return synced::stale if this.strict && this.broken(file) != was_broken; + if this.units[i] != none && checks { + checker.update(this.units[i], &this.sources[i], this.roots[i]); + } + } + return synced::stale if this.choose(touched, last) != this.entry; + return synced::same; +} + +#! Checks the program whole with a checker of its own, as `sakura check` would, +#! giving the checker the files in the order the program's checker has them, so +#! each has the same index in both. +#! @param this The program. +#! @param checker The checker, made of this program's names and notes of its +#! own. +pub def program::check_whole(&mut this, checker: &mut checker): void { + target_checker(checker, this.system, this.native); + for &file in this.files { + checker.add(&this.sources[file], &this.syntaxes[file], this.roots[file]); + } + checker.check(); +} + +#! The file of a path, or `none`. +#! @param this The program. +#! @param at The path. +#! @returns The file, or `none`. +pub def program::file_of(&this, at: strview): u32 { + for i in 0..this.paths.length { + return i as u32 if this.paths[i].view() == at; + } + return none; +} diff --git a/server/requests.sakura b/server/requests.sakura new file mode 100644 index 00000000..dfa2a5eb --- /dev/null +++ b/server/requests.sakura @@ -0,0 +1,525 @@ +#! @file requests.sakura +#! @author John Christman (sorakatadzuma@gmail.com) +#! @copyright Malunal Studios, LLC. +#! @license MIT +#! +#! Contains how the server answers what the client asks of the program: +#! checking the workspace, whose notes it publishes as diagnostics, hovering, +#! completing, the help shown while a call's arguments are written, colouring +#! a file, going to where a name is declared, finding where it is written, and +#! renaming it. + +import std::json; +import system; +import sakura::analyzer; +module sakura::server; + + +#! Publishes the diagnostics of a file. +#! @param this The server. +#! @param uri The file's URI. +#! @param diagnostics Its diagnostics, as a JSON array. +def server::publish(&mut this, uri: strview, diagnostics: strview): void { + var body := notification("textDocument/publishDiagnostics"); + body.begin_object(); + body.member("uri"); body.text(uri); + body.member("diagnostics"); body.raw(diagnostics); + body.end_object(); + this.send_written(&mut body); +} + +#! Checks the program, then publishes the diagnostics of each file, clearing +#! those of the files that no longer have any. Should checking with the files +#! whose syntax has mistakes fail, they are left out, and the rest checked again. +#! @param this The server. +def server::check(&mut this): void { + var asked := empty_job(); + var output := string::new(nothing {}); + if !this.run_job(&mut asked, &mut output) { + asked.strict = true; + output.clear(); + # A check that did not finish keeps the diagnostics already shown. + return if !this.fork_job(&asked, &mut output); + this.answered(&asked, &mut output); + } + + # Each line is the URI of a file, a space, and its diagnostics. Those of files + # no longer reported are cleared first, so a client that takes two URIs for + # one file, as the editor's spelling of it while it is open and its path's + # once it is closed, keeps the diagnostics published last. + var published := vector::::new(); + var reported := vector::::new(); + val space: u8 = ' '; + for line in output.view().split('\n') { + val at := line.index_of(&space) else { continue; }; + published.append(string::from(line.substr(0, at), nothing {})); + reported.append(line.substr(at + 1, line.length - at - 1)); + } + + var cleared := move(&mut this.published); + this.published = move(&mut published); + for &each in cleared { + if !this.published.view().contains(&each) { + this.publish(each.view(), "[]"); + } + } + for i in 0..this.published.length { + this.publish(this.published[i].view(), reported[i]); + } + + # A base stopped for being out of date is made again now, while nothing waits. + this.start_base(); +} + +#! The job a request about a position asks for: the file of its document, and +#! its position. +#! @param params What the request is given. +#! @param kind The kind of job. +#! @param out Where the job is written. +#! @returns Whether the request gives a file and a position. +def job_at(params: &json::value, kind: task, out: &mut job): bool { + val item := params.get("textDocument") else { return false; }; + val position := params.get("position") else { return false; }; + val at := position_in(&position) else { return false; }; + var path := uri_path(text_of(&item, "uri")) else { return false; }; + out.task = kind; + out.path = move(&mut path); + out.line = at.line; + out.character = at.character; + return true; +} + +#! Answers a hover, completion, or the help shown while a call's arguments are +#! written, from the files as they are now. +#! @param this The server. +#! @param id The request's ID. +#! @param params What it is given. +#! @param kind What it asks. +def server::query(&mut this, id: strview, params: &json::value, kind: task): void { + val none_text: strview = kind == task::complete ? "{\"isIncomplete\":false,\"items\":[]}" : "null"; + var asked := empty_job(); + if !job_at(params, kind, &mut asked) { + this.respond(id, none_text); + return; + } + + # Typing `:` only completes a path after `::`, not a type after `name:`. + if params.get("context") is some(context) { + if text_of(&context, "triggerCharacter") == ":" { + val item := params.get("textDocument") else { return; }; + val at := this.document_of(text_of(&item, "uri")); + if at < this.documents.length { + val text := this.documents[at].text.view(); + val offset := locate(text, asked.line as u64, asked.character as u64); + if offset < 2 || text[(offset - 2) as u64] != ':' { + this.respond(id, none_text); + return; + } + } + } + } + + var output := string::new(nothing {}); + val done := this.run_job(&mut asked, &mut output); + + # The documentation follows the items, after a zero byte, and is kept here so + # that resolving an item is answered without asking the program again. + var items := output.length; + if kind == task::complete { + this.documented.clear(); + val parts := output.view().split(0).to_vector(); + items = parts[0].length; + if done { + # Each item's documentation ends in a zero, after which nothing is left. + for i in 1..parts.length { + continue if i + 1 == parts.length && parts[i].length == 0; + this.documented.append(string::from(parts[i], nothing {})); + } + } + } + this.respond(id, done && items != 0 ? output.substr(0, items) : none_text); +} + +#! Answers `textDocument/semanticTokens/full` with the names of the file, which +#! the editor colours by what the checker made of them rather than by their +#! shape. +#! @param this The server. +#! @param id The request's ID. +#! @param params What it is given. +def server::colour(&mut this, id: strview, params: &json::value): void { + var asked := empty_job(); + asked.task = task::tokens; + var done := false; + var output := string::new(nothing {}); + if params.get("textDocument") is some(item) { + if uri_path(text_of(&item, "uri")) is some(&found) { + asked.path = string::copy_of(found); + done = this.run_job(&mut asked, &mut output); + } + } + this.respond(id, done && output.length != 0 ? output.view() : "{\"data\":[]}"); +} + +#! Answers `completionItem/resolve` with the item as it was sent, and the +#! documentation the server kept for it, which the list itself did not carry. +#! @param this The server. +#! @param id The request's ID. +#! @param params The item. +def server::resolve(&mut this, id: strview, params: &json::value): void { + var which: u64 = 0xFFFFFFFFFFFFFFFF; + if params.get("data") is some(data) { + if data.as_u64() is value(found) { + which = found; + } + } + + # What the client gave is written again as `json_text` writes it, which writes + # a value it cannot write whole as `null`. + var body := response(id); + body.begin_object(); + for member in params.members() { + continue if member.key == "documentation"; + var written := json_text(&member.value); + body.member(member.key); + body.raw(written.view()); + } + if which < this.documented.length && this.documented[which].length != 0 { + body.member("documentation"); + write_markdown(&mut body, this.documented[which].view()); + } + body.end_object(); + this.send_written(&mut body); +} + +#! Asks for a job about the name at the position a request gives, and gives +#! what it wrote. +#! @param this The server. +#! @param params What the request is given. +#! @param kind The kind of job. +#! @param output Where what the job wrote is written. +#! @returns Whether a name the checker resolved is there. +def server::ask_name(&mut this, params: &json::value, kind: task, output: &mut string): bool { + var asked := empty_job(); + return false if !job_at(params, kind, &mut asked); + return this.run_job(&mut asked, output) && output.length != 0; +} + +#! Answers `textDocument/definition` with where what the name at the position +#! is declared, or null for what has no declaration to go to, as a built-in +#! type. +#! @param this The server. +#! @param id The request's ID. +#! @param params What it is given. +def server::define(&mut this, id: strview, params: &json::value): void { + var output := string::new(nothing {}); + if this.ask_name(params, task::name, &mut output) { + var parsed := json::parse(output.view()) else (_) { + this.respond(id, "null"); + return; + }; + if parsed.root.get("declaration") is some(found) { + var body := response(id); + found.encode(&mut body); + this.send_written(&mut body); + return; + } + } + this.respond(id, "null"); +} + +#! Answers `textDocument/references` with everywhere what the name at the +#! position refers to is written, leaving out its declaration where the request +#! asks. +#! @param this The server. +#! @param id The request's ID. +#! @param params What it is given. +def server::references(&mut this, id: strview, params: &json::value): void { + var declared := true; + if params.get("context") is some(context) { + if context.get("includeDeclaration") is some(include) { + if include.as_bool() is value(given) { + declared = given; + } + } + } + var output := string::new(nothing {}); + if !this.ask_name(params, task::refer, &mut output) { + this.respond(id, "null"); + return; + } + var parsed := json::parse(output.view()) else (_) { + this.respond(id, "null"); + return; + }; + val named := parsed.root; + var declaration := string::new(nothing {}); + if named.get("declaration") is some(found) { + declaration = json_text(&found); + } + + var body := response(id); + body.begin_array(); + if named.get("locations") is some(locations) { + for each in locations.elements() { + if !declared { + var written := json_text(&each); + continue if written.view() == declaration.view(); + } + each.encode(&mut body); + } + } + body.end_array(); + this.send_written(&mut body); +} + +#! Whether a rename may change a file: one within a workspace folder, or one open +#! in the editor. The standard library is changed only where the workspace holds +#! it, so renaming a name a program uses never rewrites the library it came from. +#! @param this The server. +#! @param at The file's path. +#! @returns Whether it may. +def server::editable(&this, at: strview): bool { + return false if at.length == 0; + for &root in this.roots { + return true if at.starts_with(root.view()) && (at.length == root.length || at[root.length] == '/'); + } + for &each in this.documents { + return true if each.path.view() == at; + } + return false; +} + +#! Why the name a job found cannot be renamed, or empty text where it can. What +#! the checker refuses is said first, then any place it is written that the +#! workspace does not hold. +#! @param this The server. +#! @param named What the job wrote, or nothing where no name was found. +#! @returns Why, or empty text. +def server::refuse_rename(&this, named: maybe): string { + var reason := string::new(nothing {}); + val found := named else { + reason.append("Nothing the checker resolved is named here."); + return reason; + }; + val name := text_of(&found, "name"); + if has_text(&found, "refusal") { + reason.append("`"); + reason.append(name); + reason.append("` cannot be renamed. "); + reason.append(text_of(&found, "refusal")); + return reason; + } + + # The declaration comes first, then each place it is written. + var places := vector::::new(); + if found.get("declaration") is some(declared) { + places.append(declared); + } + if found.get("locations") is some(locations) { + for each in locations.elements() { + places.append(each); + } + } + for &place in places { + var at := string::new(nothing {}); + var made := uri_path(text_of(&place, "uri")); + if made is some(&mut found) { + at = move(found); + } + if !this.editable(at.view()) { + reason.append("`"); + reason.append(name); + reason.append("` cannot be renamed. It is written in "); + reason.append(at.length != 0 ? at.view() : "a file the server cannot name"); + reason.append(", which is outside the workspace."); + return reason; + } + } + return reason; +} + +#! Asks for a job about the name at the position a request about renaming gives, +#! and reads what it wrote, answering the request where the name cannot be +#! renamed: with an error saying why, or null where what the job wrote is not +#! JSON. +#! @param this The server. +#! @param id The request's ID. +#! @param params What it is given. +#! @param kind The kind of job. +#! @param output Where what the job wrote is kept, which the document read +#! views. +#! @returns What the job wrote, read, or nothing where the request is answered. +def server::ask_renamable(&mut this, id: strview, params: &json::value, kind: task, output: &mut string): maybe { + val asked := this.ask_name(params, kind, output); + var parsed := json::parse(asked ? output.view() : "null") else (_) { + this.respond(id, "null"); + return nothing {}; + }; + val named: maybe = asked && parsed.root.kind == json::kind::object ? parsed.root : nothing {}; + var refusal := this.refuse_rename(named); + if refusal.length != 0 { + this.respond_error(id, request_failed, refusal.view()); + return nothing {}; + } + return move(parsed); +} + +#! Answers `textDocument/prepareRename` with the name at the position, or an +#! error saying why it cannot be renamed, so the editor says so before asking +#! for a name. +#! @param this The server. +#! @param id The request's ID. +#! @param params What it is given. +def server::prepare_rename(&mut this, id: strview, params: &json::value): void { + var output := string::new(nothing {}); + val parsed := this.ask_renamable(id, params, task::name, &mut output) else { return; }; + val found := parsed.root; + var body := response(id); + body.begin_object(); + body.member("range"); + write_range_of(found.get("at"), &mut body); + body.member("placeholder"); + body.text(text_of(&found, "name")); + body.end_object(); + this.send_written(&mut body); +} + +#! Writes the range of a location a job wrote, or `null` where there is none. +#! @param location The location, or nothing. +#! @param out Where it is written. +def write_range_of(location: maybe, out: &mut json::writer): void { + val found := location else { + out.empty(); + return; + }; + val range := found.get("range") else { + out.empty(); + return; + }; + range.encode(out); +} + +#! Whether text is a name a declaration may be given: a letter or `_`, then +#! letters, digits, and `_`, which is no keyword, nor a word the language keeps. +#! @param text The text. +#! @returns Whether it is. +def is_name(text: strview): bool { + return false if text.length == 0 || (text[0] >= '0' && text[0] <= '9'); + for i in 0..text.length { + return false if !is_word_byte(text[i]); + } + var names := names::new(); + val id := names.intern(&text); + return !names.is_keyword(id) && !names.is_reserved(id); +} + +#! Answers `textDocument/rename` with an edit replacing everywhere the name at +#! the position is written, declaration and all, grouped by file. +#! @param this The server. +#! @param id The request's ID. +#! @param params What it is given. +def server::rename(&mut this, id: strview, params: &json::value): void { + val given := text_of(params, "newName"); + if !is_name(given) { + var reason := string::from("`", nothing {}); + reason.append(given); + reason.append("` is not a name: a name is a letter or `_`, then letters, digits, and `_`, and is not a keyword."); + this.respond_error(id, request_failed, reason.view()); + return; + } + + var output := string::new(nothing {}); + val parsed := this.ask_renamable(id, params, task::refer, &mut output) else { return; }; + + # Each file is given once, with every place in it, in the order they were found. + val found := parsed.root; + var locations := vector::::new(); + if found.get("locations") is some(all) { + for each in all.elements() { + locations.append(each); + } + } + var body := response(id); + body.begin_object(); + body.member("changes"); + body.begin_object(); + for i in 0..locations.length { + val uri := text_of(&locations[i], "uri"); + var seen := false; + for j in 0..i { + seen = seen || text_of(&locations[j], "uri") == uri; + } + continue if seen; + body.member(uri); + body.begin_array(); + for j in i..locations.length { + continue if text_of(&locations[j], "uri") != uri; + body.begin_object(); + body.member("range"); + write_range_of(locations[j], &mut body); + body.member("newText"); + body.text(given); + body.end_object(); + } + body.end_array(); + } + body.end_object(); + body.end_object(); + this.send_written(&mut body); + this.warn_unresolved(&found, given); +} + +#! A path as the editor's user is shown it: within a root of the workspace, +#! relative to it. +#! @param this The server. +#! @param path The path. +#! @returns The path shown. +def server::shown_path(&this, path: strview): strview { + var shown := path; + for &root in this.roots { + if shown.starts_with(root.view()) && shown.length > root.length && shown[root.length] == '/' { + shown = shown.substr(root.length + 1, shown.length - root.length - 1); + } + } + return shown; +} + +#! Tells the editor where a name a rename changed is also written but was never +#! resolved, as in a branch of `when` for another target, or in the runtime of +#! executables where the target is not one, so what the rename left as it is +#! can be looked at rather than found broken on that target. +#! @param this The server. +#! @param named What the job found. +#! @param given The name given. +def server::warn_unresolved(&mut this, named: &json::value, given: strview): void { + val name := text_of(named, "name"); + var places := string::new(nothing {}); + var count := 0; + if named.get("unresolved") is some(unresolved) { + for place in unresolved.elements() { + var at := uri_path(text_of(&place, "uri")) else { continue; }; + val range := place.get("range") else { continue; }; + val start := range.get("start") else { continue; }; + val begins := position_in(&start) else { continue; }; + val shown := this.shown_path(at.view()); + if places.length != 0 { + places.append(", "); + } + val text := $"{shown}:{begins.line + 1}:{begins.character + 1}"; + places.append(text.view()); + count++; + } + } + return if count == 0; + + var message := string::from("Renamed `", nothing {}); + message.append(name); + message.append("` to `"); + message.append(given); + message.append("`, but `"); + message.append(name); + message.append("` is also written in code the checker does not read for this target, where it may be the same name, and there it was left as it is: "); + message.append(places.view()); + message.append("."); + this.tell("window/showMessage", log_warning, message.view()); +} diff --git a/server/server.sakura b/server/server.sakura new file mode 100644 index 00000000..1c825f17 --- /dev/null +++ b/server/server.sakura @@ -0,0 +1,654 @@ +#! @file server.sakura +#! @author John Christman (sorakatadzuma@gmail.com) +#! @copyright Malunal Studios, LLC. +#! @license MIT +#! +#! Contains the language server: it serves the language server protocol over +#! the standard input and output until the client exits. Every `.sakura` file +#! of the workspace folders is checked together with the standard library, +#! using the text of the editor for the files open in it, and each file's notes +#! are published as its diagnostics. Where several files declare `main`, each +#! begins a program holding every file that does not, and one program is +#! checked at a time: that of the file declaring `main` last opened, edited, or +#! asked about. +#! +#! The server itself never checks anything. Each job, as checking the workspace +#! or describing the name hovered, is worked out by a process of its own, so a +#! fault while checking cannot stop the server, and one taking too long is +#! stopped. The server keeps a process, the base, holding the files of the +#! workspace parsed and checked. A job is worked out by a process the base +#! starts as a copy of itself, which parses again what changed of the files as +#! they are, checks again only what that affects, and answers. A check of the +#! workspace checks the program whole, so its diagnostics are what +#! `sakura check` would say. Once a check is answered, the base brings itself +#! up to date with the files, so the next job has less to do. Where the base +#! cannot answer, as where files are new or gone, it is made again, and where it +#! still cannot, the job is worked out from nothing by a process of its own. +#! Windows cannot copy a process, so there the base answers each job itself, as +#! a process of its own still, and the server stops it and makes it again where +#! a job faults or takes too long. + +import std::io; +import std::json; +import system; +import sakura::analyzer; +module sakura::server; + + +#! How the server is run. +pub struct server_options { + pub var native: bool; #! Whether the workspace is checked for an executable. + pub var system: strview; #! The operating system it is checked for, as `linux`. + pub var libraries: span; #! The libraries, each as `NAME=DIR`, as `--lib` gives them, the standard library's among them. +} + +#! The base: the process holding the workspace parsed and checked, which works +#! out each job. +struct base_link { + var process: i64; #! The process, by its number on Linux and its handle on Windows, or 0 where there is none. + var jobs: system::fd; #! Where jobs are written to it. + var answers: system::fd; #! Where its answers are read. +} + +#! The server. +struct server { + var options: server_options; + var libraries: vector; #! The libraries, each as `NAME=DIR`, their directories made absolute. + var core: string; #! `core`'s directory, beside the server's executable or above it, or empty. + var platform: string; #! `system`'s directory, found as `core`'s is, or empty. + var runtime: string; #! The runtime's directory, `runtime`, found as `core`'s is, or empty. + var roots: vector; #! The paths of the workspace folders. + var documents: vector; #! The documents open in the editor. + var published: vector; #! The URIs last published with diagnostics. + var documented: vector; #! The documentation of the last completion's items, which resolving one is answered from. + var initialized: bool; + var shutdown: bool; + var dirty: bool; #! Whether something changed since the last check. + var touched: string; #! The file last opened, edited, or asked about. + var entry: string; #! The file declaring `main` the last job was answered from, or empty. + var base: base_link; +} + +#! Milliseconds without changes before the workspace is checked. +const delay: i64 = 200; + +#! Milliseconds a job may take before it is stopped. +const timeout: i64 = 30000; + +# Error codes of JSON-RPC and the protocol. +const invalid_request: i64 = -32600; +const method_not_found: i64 = -32601; +const not_initialized: i64 = -32002; +const request_failed: i64 = -32803; + +# Message types of `window/logMessage` and `window/showMessage`. +const log_error: u32 = 1; +const log_warning: u32 = 2; +const log_info: u32 = 3; + +# What a process says of a job: answered, not finished, or that the files moved +# on, so the base must be made again. A job says so by its exit status. +const answer_ok: u64 = 0; +const answer_fail: u64 = 1; +const answer_stale: u64 = 2; +const worker_stale: i32 = 3; + +#! Serves the language server protocol over the standard input and output +#! until the client exits. +#! @param given How the server is run. +#! @returns The status to exit with: 0 where the client shut the server down +#! before it exited, and 1 otherwise. +pub def serve(given: server_options): i32 { + system::ignore(system::signal::pipe); + var running := make_server(&given); + for each in given.libraries { + val split := each.index_of(&'=') else { continue; }; + var folder := spelled_folder(each.substr(split + 1, each.length - split - 1)) else { continue; }; + running.libraries.append($"{each.substr(0, split)}={folder}"); + } + + var input := string::new(nothing {}); + var chunk: u8[65536]; + while true { + # Each whole message that has arrived is handled. + while true { + var body := string::new(nothing {}); + break if !take_message(&mut input, &mut body); + var parsed := json::parse(body.view()) else (_) { + running.log(log_warning, "A message from the client was not valid JSON."); + continue; + }; + val going := running.handle(parsed.root); + if !going { + running.stop_base(); + return running.shutdown ? 0 : 1; + } + } + + # Checking waits for a pause in the changes, so typing is not held up by it. + val waited := wait_readable(system::fd::stdin, running.dirty ? delay : -1); + if waited == -4 { + continue; + } + if waited == 0 { + running.dirty = false; + running.check(); + continue; + } + val size := system::fd::stdin.read((&mut chunk) as *mut u8, 65536); + if size == -4 { + continue; + } + if size <= 0 { + running.stop_base(); + return running.shutdown ? 0 : 1; + } + input.append(strview::over((&chunk) as *u8, size as u64)); + } + return 1; +} + +#! Makes a server, which knows of no folder or document yet. +#! @param given How the server is run, which is copied. +#! @returns The server. +def make_server(given: &server_options): server { + return server { + options = server_options { native = given.native, system = given.system, libraries = given.libraries }, + libraries = vector::::new(), + core = toolchain_folder("core"), + platform = toolchain_folder("system"), + runtime = toolchain_folder("runtime"), + roots = vector::::new(), + documents = vector::::new(), + published = vector::::new(), + documented = vector::::new(), + touched = string::new(nothing {}), + entry = string::new(nothing {}) + }; +} + +#! A library's directory, spelled as the paths of the documents are, which its +#! files' paths are compared with: made absolute, and on Windows, which spells a +#! file many ways, in the one way of its own. +#! @param folder The directory, as given. +#! @returns The directory, or `nothing` where it cannot be spelled so. +def spelled_folder(folder: strview): maybe { + var made: maybe = nothing {}; + when os == linux { + if path::parse(folder) is value(&found) { + if io::absolute(found) is value(&whole) { + made = string::from(whole.view(), nothing {}); + } + } + } + when os == windows { + made = canonical_path(folder); + } + return made; +} + +#! Takes the body of the next whole message from what has arrived, if one has. +#! A header without a length cannot be followed, so it is dropped. +#! @param input What has arrived, which the message is taken from. +#! @param body Where the body is written. +#! @returns Whether a whole message had arrived. +def take_message(input: &mut string, body: &mut string): bool { + while true { + val text := input.view(); + var end: u64 = 0; + var found := false; + while end + 4 <= text.length { + if text.substr(end, 4) == "\r\n\r\n" { + found = true; + break; + } + end++; + } + return false if !found; + + val header := end + 4; + var known := false; + var length: u64 = 0; + var line: u64 = 0; + while line < end { + var stop := line; + while stop + 1 < end + 2 && text.substr(stop, 2) != "\r\n" { + stop++; + } + val field := text.substr(line, stop - line); + if field.length >= 15 && field.substr(0, 15).lower().view() == "content-length:" { + val number := field.substr(15, field.length - 15).trim(); + length = 0; + for i in 0..number.length { + break if number[i] < '0' || number[i] > '9'; + length = length * 10 + (number[i] - '0') as u64; + } + known = true; + } + line = stop + 2; + } + + if !known { + input = string::from(text.substr(header, text.length - header), nothing {}); + continue; + } + return false if text.length < header + length; + body = string::from(text.substr(header, length), nothing {}); + input = string::from(text.substr(header + length, text.length - header - length), nothing {}); + return true; + } + return false; +} + +#! Sends a message to the client. +#! @param this The server. +#! @param body The message, as JSON. +def server::send(&mut this, body: strview): void { + var made := $"Content-Length: {body.length}\r\n\r\n"; + made.append(body); + if !put_all(system::fd::stdout, made.view()) { + system::exit(1); + } +} + +#! Begins a message to the client, as JSON-RPC 2.0 writes one, leaving it open +#! for its members, which `send_written` closes. +#! @returns The writer, within the message. +def envelope(): json::writer { + var made := message_writer(); + made.begin_object(); + made.member("jsonrpc"); + made.text("2.0"); + return made; +} + +#! Begins the response to a request, whose outcome is written next, as a value. +#! @param id The request's ID, as JSON. +#! @param outcome The outcome's member: `result`, or `error`. +#! @returns The writer, within the response. +def response(id: strview, outcome: strview = "result"): json::writer { + var made := envelope(); + made.member("id"); + made.raw(id); + made.member(outcome); + return made; +} + +#! Begins a notification to the client, whose parameters are written next, as a +#! value. +#! @param method The method it notifies. +#! @returns The writer, within the notification. +def notification(method: strview): json::writer { + var made := envelope(); + made.member("method"); + made.text(method); + made.member("params"); + return made; +} + +#! Sends a message `response` or `notification` began, once what follows its +#! beginning is written. +#! @param this The server. +#! @param body The message. +def server::send_written(&mut this, body: &mut json::writer): void { + body.end_object(); + # A lossy writer given nothing but integers and text never fails. + val text := body.finish() else (_) { return; }; + this.send(text); +} + +#! Tells the client something, which it logs, or shows its user. +#! @param this The server. +#! @param method `window/logMessage`, or `window/showMessage`. +#! @param kind How grave it is. +#! @param text What it says. +def server::tell(&mut this, method: strview, kind: u32, text: strview): void { + var body := notification(method); + body.begin_object(); + body.member("type"); body.unsigned(kind as u64); + body.member("message"); body.text(text); + body.end_object(); + this.send_written(&mut body); +} + +#! Logs a message in the client's log. +#! @param this The server. +#! @param kind How grave it is. +#! @param text What it says. +def server::log(&mut this, kind: u32, text: strview): void { + this.tell("window/logMessage", kind, text); +} + +#! Answers a request. +#! @param this The server. +#! @param id The request's ID, as JSON. +#! @param result The answer, as JSON. +def server::respond(&mut this, id: strview, result: strview): void { + var body := response(id); + body.raw(result); + this.send_written(&mut body); +} + +#! Answers a request with an error. +#! @param this The server. +#! @param id The request's ID, as JSON. +#! @param code The error's code. +#! @param message What it says. +def server::respond_error(&mut this, id: strview, code: i64, message: strview): void { + var body := response(id, "error"); + body.begin_object(); + body.member("code"); body.signed(code); + body.member("message"); body.text(message); + body.end_object(); + this.send_written(&mut body); +} + +#! The JSON a value is written as. +#! @param value The value. +#! @returns Its text. +def json_text(value: &json::value): string { + var writer := json::writer::new(); + value.encode(&mut writer); + val made := writer.finish() else (_) { return string::from("null", nothing {}); }; + return string::from(made, nothing {}); +} + +#! The text of a string member of an object, or empty text where it is none. +#! @param value The object. +#! @param key The member's name. +#! @returns The text. +def text_of(value: &json::value, key: strview): strview { + val member := value.get(key) else { return ""; }; + return member.as_text() else ""; +} + +#! Whether an object has a string member of the name. +#! @param value The object. +#! @param key The member's name. +#! @returns Whether it has. +def has_text(value: &json::value, key: strview): bool { + val member := value.get(key) else { return false; }; + return member.kind == json::kind::text; +} + +#! Keeps the file last opened, edited, or asked about, whose program the next +#! job is answered from where it declares `main`. +#! @param this The server. +#! @param at The file's path, or empty. +def server::touch(&mut this, at: strview): void { + return if at.length == 0; + this.touched = string::from(at, nothing {}); +} + +#! The document open of a URI, or the count of documents. +#! @param this The server. +#! @param uri The URI. +#! @returns Its index. +def server::document_of(&this, uri: strview): u64 { + for i in 0..this.documents.length { + return i if this.documents[i].uri.view() == uri; + } + return this.documents.length; +} + +#! Adds a workspace folder, once. +#! @param this The server. +#! @param uri The folder's URI. +def server::add_root(&mut this, uri: strview): void { + var found := uri_path(uri) else { return; }; + return if this.roots.view().contains(&found); + this.roots.append(move(&mut found)); +} + +#! Takes a workspace folder away. +#! @param this The server. +#! @param uri The folder's URI. +def server::remove_root(&mut this, uri: strview): void { + val found := uri_path(uri) else { return; }; + val at := this.roots.view().index_of(&found) else { return; }; + this.roots.remove_at(at); +} + +#! Whether any of the libraries is the standard library's, or one of its +#! modules', as `std::io`. +#! @param this The server. +#! @returns Whether one is. +def server::reads_std(&this): bool { + for &each in this.libraries { + return true if each.view().starts_with("std=") || each.view().starts_with("std::"); + } + return false; +} + +#! What the files of a check are gathered from now. +#! @param this The server. +#! @returns What they are gathered from. +def server::gathering(&this): gathering { + return gathering { + core = this.core.view(), system = this.platform.view(), runtime = this.runtime.view(), + libraries = this.libraries.view(), roots = &this.roots, documents = &this.documents + }; +} + +#! Handles a message, giving whether the server goes on: it stops once the +#! client asks it to exit. +#! @param this The server. +#! @param message The message. +#! @returns Whether it goes on. +def server::handle(&mut this, message: json::value): bool { + val method := text_of(&message, "method"); + # A response to the server, which asks nothing. + return true if method.length == 0; + return false if method == "exit"; + + var params := message; + if message.get("params") is some(given) { + params = given; + } + if message.get("id") is some(found) { + var id := json_text(&found); + if method == "initialize" { + this.initialize(id.view(), ¶ms); + } else if !this.initialized { + this.respond_error(id.view(), not_initialized, "The server was not initialized."); + } else if this.shutdown { + this.respond_error(id.view(), invalid_request, "The server is shutting down."); + } else if method == "shutdown" { + this.shutdown = true; + this.respond(id.view(), "null"); + } else if method == "textDocument/hover" { + this.query(id.view(), ¶ms, task::hover); + } else if method == "textDocument/completion" { + this.query(id.view(), ¶ms, task::complete); + } else if method == "completionItem/resolve" { + this.resolve(id.view(), ¶ms); + } else if method == "textDocument/definition" { + this.define(id.view(), ¶ms); + } else if method == "textDocument/references" { + this.references(id.view(), ¶ms); + } else if method == "textDocument/prepareRename" { + this.prepare_rename(id.view(), ¶ms); + } else if method == "textDocument/rename" { + this.rename(id.view(), ¶ms); + } else if method == "textDocument/signatureHelp" { + this.query(id.view(), ¶ms, task::call); + } else if method == "textDocument/semanticTokens/full" { + this.colour(id.view(), ¶ms); + } else { + this.respond_error(id.view(), method_not_found, "The server does not support this request."); + } + return true; + } + + return true if !this.initialized || this.shutdown; + if method == "initialized" { + # Making the base takes as long as a check, so it is made before it is + # asked for, leaving the first check of a session to pay for nothing but + # checking. + this.start_base(); + if this.core.length == 0 { + this.log(log_warning, "No `core` folder is beside the server's executable or above it, so checks know nothing of the language's own types."); + } + if !this.reads_std() { + this.log(log_warning, "The standard library was not found, so it is left out of checks. Put it beside the server's executable or above it, install it with `blossom install`, or give `--lib std=DIR` to `sakura lsp`."); + } + } + if method == "initialized" || method == "textDocument/didSave" || method == "workspace/didChangeWatchedFiles" + || method == "workspace/didChangeConfiguration" { + this.dirty = true; + } else if method == "textDocument/didOpen" { + this.open(¶ms); + } else if method == "textDocument/didChange" { + this.change(¶ms); + } else if method == "textDocument/didClose" { + this.close(¶ms); + } else if method == "workspace/didChangeWorkspaceFolders" { + this.folders(¶ms); + } + return true; +} + +#! Answers `initialize` with what the server can do, taking the workspace +#! folders it is given. +#! @param this The server. +#! @param id The request's ID. +#! @param params What it is given. +def server::initialize(&mut this, id: strview, params: &json::value): void { + if params.get("workspaceFolders") is some(folders) { + for folder in folders.elements() { + this.add_root(text_of(&folder, "uri")); + } + } else if has_text(params, "rootUri") { + this.add_root(text_of(params, "rootUri")); + } + this.initialized = true; + this.respond(id, """ + {"capabilities":{ + "positionEncoding":"utf-16", + "textDocumentSync":{"openClose":true,"change":2,"save":{"includeText":false}}, + "hoverProvider":true, + "completionProvider":{"triggerCharacters":[".",":"],"resolveProvider":true}, + "definitionProvider":true, + "referencesProvider":true, + "renameProvider":{"prepareProvider":true}, + "signatureHelpProvider":{"triggerCharacters":["(",","],"retriggerCharacters":[",",")"]}, + "semanticTokensProvider":{"legend":{"tokenTypes":[ + "namespace","struct","interface","enum","type","typeParameter", + "parameter","variable","property","enumMember","function","method", + "keyword"], + "tokenModifiers":["declaration","readonly"]},"full":true}, + "workspace":{"workspaceFolders":{"supported":true,"changeNotifications":true}} + }, + "serverInfo":{"name":"sakura"}} + """); +} + +#! Takes a document the editor opened. +#! @param this The server. +#! @param params What `textDocument/didOpen` is given. +def server::open(&mut this, params: &json::value): void { + val item := params.get("textDocument") else { return; }; + return if !has_text(&item, "uri") || !has_text(&item, "text"); + val uri := text_of(&item, "uri"); + var at := this.document_of(uri); + if at == this.documents.length { + var path := string::new(nothing {}); + var made := uri_path(uri); + if made is some(&mut found) { + path = move(found); + } + this.documents.append(document { uri = string::from(uri, nothing {}), path = move(&mut path), text = string::new(nothing {}) }); + } + this.documents[at].text = string::from(text_of(&item, "text"), nothing {}); + this.touch(this.documents[at].path.view()); + this.dirty = true; +} + +#! The byte of a document's text a position of the protocol is at. +#! @param text The text. +#! @param position The position. +#! @param out Where the byte is written. +#! @returns Whether the value is a position. +def position_at(text: strview, position: &json::value, out: &mut u32): bool { + val at := position_in(position) else { return false; }; + out = locate(text, at.line as u64, at.character as u64); + return true; +} + +#! The position of the protocol a value is. +#! @param value The value, as `{"line":0,"character":4}`. +#! @returns The position, or nothing where the value is none. +def position_in(value: &json::value): maybe { + val line := value.get("line") else { return nothing {}; }; + val character := value.get("character") else { return nothing {}; }; + val row := line.as_u64() else (_) { return nothing {}; }; + val column := character.as_u64() else (_) { return nothing {}; }; + return position { line = row as u32, character = column as u32 }; +} + +#! Takes the changes the editor made to a document. A change is the text a range +#! becomes, and they are made in turn, since each is given against the text the +#! one before it left. A change without a range is the whole document. +#! @param this The server. +#! @param params What `textDocument/didChange` is given. +def server::change(&mut this, params: &json::value): void { + val item := params.get("textDocument") else { return; }; + val at := this.document_of(text_of(&item, "uri")); + return if at == this.documents.length; + val changes := params.get("contentChanges") else { return; }; + for each in changes.elements() { + continue if !has_text(&each, "text"); + val text := text_of(&each, "text"); + if each.get("range") is some(range) { + var from: u32 = 0; + var to: u32 = 0; + val start := range.get("start") else { continue; }; + val end := range.get("end") else { continue; }; + val old := this.documents[at].text.view(); + continue if !position_at(old, &start, &mut from) || !position_at(old, &end, &mut to); + if to < from { + to = from; + } + var edited := string::from(old.substr(0, from as u64), nothing {}); + edited.append(text); + edited.append(old.substr(to as u64, old.length - to as u64)); + this.documents[at].text = move(&mut edited); + } else { + this.documents[at].text = string::from(text, nothing {}); + } + } + this.touch(this.documents[at].path.view()); + this.dirty = true; +} + +#! Lets go of a document the editor closed, which is read from disk again. +#! @param this The server. +#! @param params What `textDocument/didClose` is given. +def server::close(&mut this, params: &json::value): void { + val item := params.get("textDocument") else { return; }; + val at := this.document_of(text_of(&item, "uri")); + return if at == this.documents.length; + this.documents.remove_at(at); + this.dirty = true; +} + +#! Takes the workspace folders the editor added and removed. +#! @param this The server. +#! @param params What `workspace/didChangeWorkspaceFolders` is given. +def server::folders(&mut this, params: &json::value): void { + val event := params.get("event") else { return; }; + if event.get("removed") is some(removed) { + for folder in removed.elements() { + this.remove_root(text_of(&folder, "uri")); + } + } + if event.get("added") is some(added) { + for folder in added.elements() { + this.add_root(text_of(&folder, "uri")); + } + } + # The base gathers the files of the folders it was made with, so it is made + # again with these. + this.stop_base(); + this.dirty = true; +} diff --git a/server/system.sakura b/server/system.sakura new file mode 100644 index 00000000..da6334e8 --- /dev/null +++ b/server/system.sakura @@ -0,0 +1,715 @@ +#! @file system.sakura +#! @author John Christman (sorakatadzuma@gmail.com) +#! @copyright Malunal Studios, LLC. +#! @license MIT +#! +#! Contains what the server asks of the system beyond what `system` gives: +#! making a process the leader of a group of its own, sending what it writes +#! nowhere, and the path of the executable running, which `sakura` also finds +#! the standard library by, with waiting on a handle for a while, the time, and +#! reading and writing whole messages over the pipes between its processes. The +#! calls are those of Linux on x86-64, and on Windows the functions of the +#! system, where the server also starts its processes itself, and spells each +#! path one way, since Windows spells a file many. + +import std::io; +import std::process; +import system; +import system::windows; +import sakura::analyzer; + +module sakura::server; + + +when os == linux { + # The numbers of the calls made here, as Linux gives them on x86-64. + val call_dup2: i64 = 33; + val call_readlink: i64 = 89; + val call_setpgid: i64 = 109; + + #! Sends what the process writes to its standard output nowhere, so that only + #! the server, which answers the client, ever writes to it. + pub def quiet_output(): void { + val nowhere := system::open(system::null_device, open_flags::write); + return if nowhere < 0; + system::linux::syscall(call_dup2, nowhere as u64, 1, 0, 0, 0, 0); + nowhere.close(); + } + + #! Makes the process the leader of a group of its own, which the processes it + #! starts belong to, so they are all stopped at once. + pub def lead_group(): void { + system::linux::syscall(call_setpgid, 0, 0, 0, 0, 0, 0); + } + + #! The path of the executable running. + #! @returns The path, or empty text where the system does not say. + pub def executable_path(): string { + val link: strview = "/proc/self/exe"; + var name: u8[16]; + for i in 0..link.length { + name[i] = link[i]; + } + name[link.length] = 0; + + var text: u8[4096]; + val from := (&mut name) as *mut u8; + val into := (&mut text) as *mut u8; + val length := system::linux::syscall(call_readlink, from as u64, into as u64, 4095, 0, 0, 0); + return string::new(nothing {}) if length <= 0; + return string::from(span::::over(into as *u8, length as u64), nothing {}); + } +} + +when os == windows { + # What `GetStdHandle` and `SetStdHandle` take for the standard output. + val standard_output: u32 = 0xFFFFFFF5; + + # What they take for the standard error. + val standard_error: u32 = 0xFFFFFFF4; + + # What the other functions of the system are given, and give. + val invalid_handle: u64 = 0xFFFFFFFFFFFFFFFF; + val infinite: u32 = 0xFFFFFFFF; + val utf8_page: u32 = 65001; + val same_access: u32 = 2; + val use_std_handles: u32 = 0x100; + val handle_list: u64 = 0x20002; + val suspended: u32 = 0x4; + val extended_startup: u32 = 0x80000; + val no_window: u32 = 0x08000000; + val extended_limits: u32 = 9; # The limits of a job object, JOBOBJECT_EXTENDED_LIMIT_INFORMATION. + val kill_on_close: u64 = 0x2000; # Its processes are stopped once the last handle of it is closed. + val basic_find: u32 = 1; # Finding a file without its short name. + + # The most units of UTF-16 a path of the system holds, with the zero it ends + # in. + val wide_limit: u64 = 32768; + + # The job object every process the server starts is put in, which stops them + # all once the server ends, however it ends, or 0 before the first starts. + var processes: u64; + + # The system's handle a handle of `system` stands for, which gives the + # standard streams as 0, 1, and 2. + def system_handle(handle: system::fd): u64 { + return handle >= 0 && handle <= 2 ? GetStdHandle(0xFFFFFFF6 - handle as u32) : (handle as i64) as u64; + } + + #! Sends what the process writes to its standard output nowhere, so that only + #! the server, which answers the client, ever writes to it. The handle of + #! nowhere is the standard output from then on, so it stays open. + pub def quiet_output(): void { + val nowhere := system::open(system::null_device, open_flags::write); + return if nowhere < 0; + SetStdHandle(standard_output, system_handle(nowhere)); + } + + #! The path of the executable running, in UTF-8. + #! @returns The path, or empty text where the system does not say. + pub def executable_path(): string { + var wide: u16[4096]; + var text: u8[16384]; + val units := (&mut wide) as *mut u16; + val into := (&mut text) as *mut u8; + val count := GetModuleFileNameW(0, units, 4096); + return string::new(nothing {}) if count == 0 || count >= 4096; + val length := WideCharToMultiByte(utf8_page, 0, units as *u16, count as i32, into, 16384, null, null); + return string::new(nothing {}) if length <= 0; + return string::from(span::::over(into as *u8, length as u64), nothing {}); + } + + #! Takes the standard output the process was given, which the server reads + #! its answers from, and sends anything else written there nowhere, as + #! `quiet_output` does. + #! @returns The handle of the output it was given. + pub def take_output(): system::fd { + val given := GetStdHandle(standard_output); + quiet_output(); + return (given as i64) as system::fd; + } + + #! Starts a process of the server's, which on Windows is this program started + #! again, as `PROGRAM lsp ROLE`, since Windows cannot start a copy of the + #! server. It is given the handles as its standard input and output, and the + #! server's standard error as its own, which reaches the editor's log, and it + #! inherits nothing else, so it never holds the connection to the client open. + #! No console is made for it, as the server has none under an editor, and it + #! is put in a job object before it runs, which stops it once the server + #! ends, however that is. + #! @param role What it is to be, as `--worker`. + #! @param input The handle it reads. + #! @param output The handle it writes. + #! @returns The process, as the system's handle of it, or 0 where it could not + #! be started. + pub def start_process(role: strview, input: system::fd, output: system::fd): i64 { + if processes == 0 { + processes = CreateJobObjectW(null, null); + if processes != 0 { + # JOBOBJECT_EXTENDED_LIMIT_INFORMATION, whose flags are 16 bytes in. + var limits: u64[18]; + limits[2] = kill_on_close; + SetInformationJobObject(processes, extended_limits, (&mut limits) as *mut u8, 144); + } + } + + # `"PROGRAM" lsp ROLE`, which Windows may write into while it starts it. + var program: u16[32768]; + val length := GetModuleFileNameW(0, (&mut program) as *mut u16, wide_limit as u32) as u64; + return 0 if length == 0 || length >= wide_limit; + var command: u16[32800]; + var at: u64 = 0; + command[at] = '"' as u16; + at++; + for i in 0..length { + command[at] = program[i]; + at++; + } + val rest := $"\" lsp {role}"; + for i in 0..rest.length { + command[at] = rest[i] as u16; + at++; + } + command[at] = 0; + + # Each handle it is given is a copy made for it to inherit, and it is told to + # inherit only those. + val ours := GetCurrentProcess(); + var given: u64[3]; + given[0] = system_handle(input); + given[1] = system_handle(output); + given[2] = GetStdHandle(standard_error); + var copies: u64[3]; + var count: u64 = 0; + for i in 0u..3u { + var copy: u64 = 0; + if given[i] != 0 && given[i] != invalid_handle && DuplicateHandle(ours, given[i], ours, &mut copy, 0, 1, same_access) != 0 { + copies[count] = copy; + count++; + } + given[i] = copy; + } + + var size: u64 = 0; + var list: u64[32]; + InitializeProcThreadAttributeList(null, 1, 0, &mut size); + val listed := size <= 256 && InitializeProcThreadAttributeList((&mut list) as *mut u8, 1, 0, &mut size) != 0; + var startup := startup_information { size = 112, flags = use_std_handles }; + startup.standard_input = given[0]; + startup.standard_output = given[1]; + startup.standard_error = given[2]; + startup.attributes = (&mut list) as *mut u8; + var made: process_information; + val started := listed && given[0] != 0 && given[1] != 0 + && UpdateProcThreadAttribute((&mut list) as *mut u8, 0, handle_list, (&mut copies) as *mut u8, count * 8, null, null) != 0 + && CreateProcessW( + (&program) as *u16, (&mut command) as *mut u16, null, null, 1, no_window | suspended | extended_startup, + null, null, &mut startup, &mut made + ) != 0; + if listed { + DeleteProcThreadAttributeList((&mut list) as *mut u8); + } + for i in 0..count { + CloseHandle(copies[i]); + } + return 0 if !started; + + # It starts suspended, so it is in the job object before it can do anything. + if processes != 0 { + AssignProcessToJobObject(processes, made.process); + } + ResumeThread(made.thread); + CloseHandle(made.thread); + return made.process as i64; + } + + #! Waits for a process the server started to end, until a moment passes, when + #! it is stopped, and lets go of it. + #! @param process The process, as `start_process` gives it. + #! @param deadline The moment it is stopped, as `now_ms` gives it, or 0 to + #! stop it at once. + #! @param code Where the status it exited with is written, which is the + #! code of the exception where one ended it. + #! @returns Whether it ended before it was stopped. + pub def end_process(process: i64, deadline: i64, code: &mut u32): bool { + val handle := process as u64; + val left := deadline - now_ms(); + val ended := WaitForSingleObject(handle, left > 0 ? left as u32 : 0) == 0; + if !ended { + TerminateProcess(handle, 1); + WaitForSingleObject(handle, infinite); + } + code = 1; + GetExitCodeProcess(handle, code); + CloseHandle(handle); + return ended; + } + + #! The one spelling of a path that paths are compared by, since Windows spells + #! a file many ways: absolute, without `.` and `..`, with `/` between names, + #! the letter of its drive upper case, and each name that exists spelled as + #! its directory spells it, which turns a short name, as `PROGRA~1`, into the + #! long one, and gives each letter its case on disk. A share is + #! `//server/share/...`, the server's name lower case, as a URI spells it. It + #! ends in `/` only where it is the root of a drive. Links are not followed, + #! so a path stays within the folder the editor named it by. + #! @param given The path. + #! @returns The path, or nothing where the system takes it for none. + pub def canonical_path(given: strview): maybe { + return nothing {} if given.length == 0 || given.length >= wide_limit; + var wide: u16[32768]; + var whole: u16[32768]; + var spelled: u16[32768]; + val named := (&mut wide) as *mut u16; + val full := (&mut whole) as *mut u16; + val out := (&mut spelled) as *mut u16; + val units := MultiByteToWideChar(utf8_page, 0, given.data, given.length as i32, named, 32767); + return nothing {} if units <= 0; + named[units as u64] = 0; + val length := GetFullPathNameW(named as *u16, wide_limit as u32, full, null) as u64; + return nothing {} if length == 0 || length >= wide_limit; + + # `\\?\D:\x` and `\\?\UNC\server\share` are taken as `D:\x` and + # `\\server\share`. + var start: u64 = 0; + if begins_with(full as *u16, length, 0, "\\\\?\\UNC\\") { + start = 6; + full[6] = '\\' as u16; + } else if begins_with(full as *u16, length, 0, "\\\\?\\") && is_wide_drive(full as *u16, length, 4) { + start = 4; + } + + # The root, `D:\` or `\\server\share\`, is not looked up. + var root := start; + val shared := begins_with(full as *u16, length, start, "\\\\"); + if is_wide_drive(full as *u16, length, start) { + root = start + (start + 2 < length && full[start + 2] == '\\' as u16 ? 3 : 2); + } else if shared { + var names := 0; + root = start + 2; + while root < length && names < 2 { + if full[root] == '\\' as u16 { + names++; + } + root++; + } + } + + var made: u64 = 0; + for i in start..root { + out[made] = full[i]; + made++; + } + # The server's name is lower case, as a URI spells it. + if shared { + var i: u64 = 2; + while i < made && out[i] != '\\' as u16 { + if out[i] >= 'A' as u16 && out[i] <= 'Z' as u16 { + out[i] = out[i] + 32; + } + i++; + } + } + + # Past a name that does not exist, the rest is kept as it is given. A name + # with a wildcard would be looked up as a pattern, so it is not looked up. + var found := true; + var entry: u64[74]; + var at := root; + while at < length { + var end := at; + while end < length && full[end] != '\\' as u16 { + end++; + } + if end > at { + found = found && !has_wildcard(full as *u16, at, end) && find_entry(full as *u16, end, (&mut entry) as *mut u8); + if made > 0 && out[made - 1] != '\\' as u16 { + out[made] = '\\' as u16; + made++; + } + # The name found is 44 bytes into what `FindFirstFileExW` writes. + val name := ((&entry) as *u8 + 44) as *u16; + var count := end - at; + if found { + count = 0; + while count < 260 && name[count] != 0 { + count++; + } + } + return nothing {} if made + count >= wide_limit; + for i in 0..count { + out[made] = found ? name[i] : full[at + i]; + made++; + } + } + at = end + 1; + } + + for i in 0..made { + if out[i] == '\\' as u16 { + out[i] = '/' as u16; + } + } + if is_wide_drive(out as *u16, made, 0) && out[0] >= 'a' as u16 { + out[0] = out[0] - 32; + } + while made > 1 && out[made - 1] == '/' as u16 && !(made == 3 && is_wide_drive(out as *u16, made, 0)) { + made--; + } + + var bytes: u8[98304]; + val written := WideCharToMultiByte(utf8_page, 0, out as *u16, made as i32, (&mut bytes) as *mut u8, 98304, null, null); + return nothing {} if written <= 0; + return string::from(strview::over((&bytes) as *u8, written as u64), nothing {}); + } + + # Whether the units of UTF-16 from an index on begin with ASCII text. + def begins_with(units: *u16, length: u64, at: u64, text: strview): bool { + return false if at + text.length > length; + for i in 0..text.length { + return false if units[at + i] != text[i] as u16; + } + return true; + } + + # Whether the units of UTF-16 from an index on begin with the letter of a + # drive and its colon, as `C:`. + def is_wide_drive(units: *u16, length: u64, at: u64): bool { + return false if at + 2 > length; + val letter := units[at]; + val is_letter := (letter >= 'a' as u16 && letter <= 'z' as u16) || (letter >= 'A' as u16 && letter <= 'Z' as u16); + return is_letter && units[at + 1] == ':' as u16; + } + + # Whether a name, between two indexes of a path, holds what `FindFirstFileExW` + # takes as a wildcard. + def has_wildcard(units: *u16, from: u64, to: u64): bool { + for i in from..to { + val unit := units[i]; + return true if unit == '*' as u16 || unit == '?' as u16 || unit == '<' as u16 || unit == '>' as u16 + || unit == '"' as u16; + } + return false; + } + + # Finds the entry the first units of a path name in its directory, writing it + # as `FindFirstFileExW` gives it. A path too long for the functions of the + # system to take as it is is looked up as a path of the whole file system, + # `\\?\D:\x` or `\\?\UNC\server\share\x`. + def find_entry(units: *u16, length: u64, entry: *mut u8): bool { + var path: u16[32800]; + val named := (&mut path) as *mut u16; + var at: u64 = 0; + var from: u64 = 0; + if length >= 248 && !begins_with(units, length, 0, "\\\\?\\") { + val shared := begins_with(units, length, 0, "\\\\"); + val prefix: strview = shared ? "\\\\?\\UNC" : "\\\\?\\"; + for i in 0..prefix.length { + named[at] = prefix[i] as u16; + at++; + } + from = shared ? 1 : 0; + } + for i in from..length { + named[at] = units[i]; + at++; + } + named[at] = 0; + val find := FindFirstFileExW(named as *u16, basic_find, entry, 0, null, 0); + return false if find == invalid_handle; + FindClose(find); + return true; + } +} + +#! Milliseconds since a moment the system chose, which only ever grow. +#! @returns The time. +pub def now_ms(): i64 { + return system::clock(clock_kind::steady) / 1000000; +} + +#! Waits until a handle can be read, or has ended, for at most a while, as +#! `system::poll` waits. On Windows, where it looks at a pipe again and again, +#! waiting for as long as it takes is left to the read that follows instead, +#! which waits without waking until something arrives. +#! @param handle The handle. +#! @param wait The most milliseconds to wait, or -1 to wait for as long as +#! it takes. +#! @returns More than 0 where it can be read, 0 where the wait ran out, and a +#! negative error number where it failed. +pub def wait_readable(handle: system::fd, wait: i64): i64 { + when os == windows { + return 1 if wait < 0; + } + var handles: system::fd[1]; + var ready: bool[1]; + handles[0] = handle; + val watched := span::::over((&handles) as *system::fd, 1); + return system::poll(watched, slice::::over((&mut ready) as *mut bool, 1), wait) as i64; +} + +#! Writes the whole of the text to a handle. +#! @param handle The handle. +#! @param text The text. +#! @returns Whether all of it was written, which it is not where the other end +#! is gone. +pub def put_all(handle: system::fd, text: strview): bool { + var written: u64 = 0; + while written < text.length { + val size := handle.write(text.data + written, text.length - written); + if size == -4 { + continue; + } + return false if size <= 0; + written += size as u64; + } + return true; +} + +#! Writes a number to a handle, as the eight bytes it is held in. +#! @param handle The handle. +#! @param value The number. +#! @returns Whether it was written. +pub def put_size(handle: system::fd, value: u64): bool { + var held := value; + return put_all(handle, strview::over((&held) as *u8, 8)); +} + +#! Writes text to a handle, as its length and then its bytes. +#! @param handle The handle. +#! @param text The text. +#! @returns Whether it was written. +pub def put_text(handle: system::fd, text: strview): bool { + return put_size(handle, text.length) && put_all(handle, text); +} + +#! Reads as many bytes as asked from a handle into the text, waiting until they +#! arrive, or until a moment passes. +#! @param handle The handle. +#! @param into Where the bytes are appended. +#! @param length How many bytes to read. +#! @param deadline The moment to stop waiting, as `now_ms` gives it, or 0 to +#! wait for as long as it takes. +#! @returns Whether they all arrived. +pub def get_all(handle: system::fd, into: &mut string, length: u64, deadline: i64): bool { + var chunk: u8[16384]; + var left := length; + while left != 0 { + if deadline != 0 { + val wait := deadline - now_ms(); + return false if wait <= 0; + val ready := wait_readable(handle, wait); + if ready == -4 { + continue; + } + return false if ready <= 0; + } + val asked: u64 = left < 16384 ? left : 16384; + val size := handle.read((&mut chunk) as *mut u8, asked); + if size == -4 { + continue; + } + return false if size <= 0; + into.append(strview::over((&chunk) as *u8, size as u64)); + left -= size as u64; + } + return true; +} + +#! Reads a number from a handle, as `put_size` writes one. +#! @param handle The handle. +#! @param out Where the number is written. +#! @param deadline The moment to stop waiting, or 0. +#! @returns Whether it arrived. +pub def get_size(handle: system::fd, out: &mut u64, deadline: i64): bool { + var bytes := string::new(nothing {}); + return false if !get_all(handle, &mut bytes, 8, deadline); + out = *(bytes.view().data as *u64); + return true; +} + +#! Reads text from a handle, as `put_text` writes it. +#! @param handle The handle. +#! @param out Where the text is written. +#! @param deadline The moment to stop waiting, or 0. +#! @returns Whether it arrived. +pub def get_text(handle: system::fd, out: &mut string, deadline: i64): bool { + var length: u64 = 0; + return false if !get_size(handle, &mut length, deadline); + out.clear(); + return get_all(handle, out, length, deadline); +} + +#! Reads everything a handle gives until it ends. +#! @param handle The handle. +#! @param into Where it is appended. +pub def get_rest(handle: system::fd, into: &mut string): void { + var chunk: u8[16384]; + while true { + val size := handle.read((&mut chunk) as *mut u8, 16384); + if size == -4 { + continue; + } + break if size <= 0; + into.append(strview::over((&chunk) as *u8, size as u64)); + } +} + +#! Reads everything a handle gives until it ends, or until a moment passes. +#! @param handle The handle. +#! @param into Where it is appended. +#! @param deadline The moment to stop waiting, as `now_ms` gives it. +#! @returns Whether it ended before the moment passed. +pub def get_until(handle: system::fd, into: &mut string, deadline: i64): bool { + var chunk: u8[16384]; + while true { + val wait := deadline - now_ms(); + return false if wait <= 0; + val ready := wait_readable(handle, wait); + if ready == -4 { + continue; + } + return true if ready < 0; + return false if ready == 0; + val size := handle.read((&mut chunk) as *mut u8, 16384); + if size == -4 { + continue; + } + return true if size <= 0; + into.append(strview::over((&chunk) as *u8, size as u64)); + } + return true; +} + +#! Waits for a process the server started to stop, and says how. +#! @param process The process. +#! @param status How it stopped. +#! @returns Whether it was waited for. +pub def reap(process: i64, status: &mut system::process_status): bool { + while true { + val result := system::wait(process, status); + return result >= 0 if result != -4; + } + return false; +} + +#! Reads the whole of a file. +#! @param at The file's path. +#! @param out Where its text is written. +#! @returns Whether it was read. +pub def read_text(at: strview, out: &mut string): bool { + var found := path::parse(at) else (_) { return false; }; + var text := io::read_file(&found) else (_) { return false; }; + out = move(&mut text); + return true; +} + +#! The folder of a library the compiler brings with it, as `core`: the one of +#! the name beside its executable, or in the nearest folder above that holds +#! one, so a compiler built anywhere within a repository finds the +#! repository's. No option or variable names it. +#! @param name The folder's name. +#! @returns Its path, or empty where there is none. +pub def toolchain_folder(name: strview): string { + val whole := executable_path(); + var end := whole.length; + while end > 0 { + end--; + continue if whole[end] != '/' && !(is_windows && whole[end] == '\\'); + var tried := $"{whole.view().substr(0, end)}/{name}"; + return tried if is_folder(tried.view()); + } + return string::new(nothing {}); +} + +#! The standard library the compiler finds, as `--lib` would give it, where no +#! `--lib` names `std` itself: a `std` folder beside the executable or in the +#! nearest folder above it that holds one, as `core` is found, and otherwise +#! each of std's libraries in the `share/sakura` folder nearest above it, where +#! `blossom install` puts them, as `std.io` gives `std::io`. No option or +#! variable names it. +#! @param given The libraries `--lib` names, each as `NAME=DIR`. +#! @returns Each library found, as `NAME=DIR`, in the order of their names: +#! none where `--lib` names `std`, or where none is found. +pub def found_std(given: span): vector { + var found := vector::::new(); + for each in given { + return found if each.starts_with("std="); + } + val tree := toolchain_folder("std"); + if tree.length != 0 { + found.append($"std={tree}"); + return found; + } + val shelf := toolchain_folder("share/sakura"); + return found if shelf.length == 0; + val at := path::parse(shelf.view()) else (_) { return found; }; + var listing := io::directory::open(&at) else (_) { return found; }; + var names := vector::::new(); + while listing.next() is some(each) { + continue if each.name != "std" && !each.name.starts_with("std."); + continue if !is_folder($"{shelf}/{each.name}".view()); + names.append(string::from(each.name, nothing {})); + } + names.sort_by(def(a: &string, b: &string): bool { return a.view().compare(b.view()) < 0; }); + for &name in names { + var named := string::new(nothing {}); + for byte in name.view() { + if byte == '.' { + named.append("::"); + } else { + named.push(byte); + } + } + found.append($"{named}={shelf}/{name}"); + } + return found; +} + +#! Whether a path names a folder, following a link it ends in. +#! @param at The path. +#! @returns Whether it does. +pub def is_folder(at: strview): bool { + var found := path::parse(at) else (_) { return false; }; + val info := io::info(&found) else (_) { return false; }; + return info.kind == file_kind::directory; +} + +when os == linux { + # Whether the system spells paths with `\` as well as `/`. + val is_windows: bool = false; +} + +when os == windows { + # Whether the system spells paths with `\` as well as `/`. + val is_windows: bool = true; +} + +#! The file the declarations of the types the syntax makes are shown from, which +#! the compiler holds as text rather than in a file: written once, where the +#! user's files of the moment are kept, so going to `string` opens it. Editing +#! it changes nothing, since no check reads it. +#! @returns Its path, or empty where it could not be written. +pub def builtin_document(): string { + var folder := string::new(nothing {}); + when os == windows { + if process::variable("LOCALAPPDATA") is some(at) { + folder = $"{at}/sakura"; + } + } else { + if process::variable("XDG_CACHE_HOME") is some(at) { + folder = $"{at}/sakura"; + } else if process::variable("HOME") is some(at) { + folder = $"{at}/.cache/sakura"; + } + } + return string::new(nothing {}) if folder.length == 0; + var made := $"{folder}/built-in.sakura"; + var held := string::new(nothing {}); + return made if read_text(made.view(), &mut held) && held.view() == builtin_text; + + var at := path::parse(folder.view()) else (_) { return string::new(nothing {}); }; + _ = io::create_directories(&at); + var file := path::parse(made.view()) else (_) { return string::new(nothing {}); }; + return io::write_file(&file, builtin_text) is value(_) ? move(&mut made) : string::new(nothing {}); +} diff --git a/server/text.sakura b/server/text.sakura new file mode 100644 index 00000000..52ff9730 --- /dev/null +++ b/server/text.sakura @@ -0,0 +1,329 @@ +#! @file text.sakura +#! @author John Christman (sorakatadzuma@gmail.com) +#! @copyright Malunal Studios, LLC. +#! @license MIT +#! +#! Contains how the server writes and reads what the protocol carries: JSON, +#! written whatever a file holds, positions, whose characters are counted in +#! UTF-16 code units, the `file:` URIs files are named by, and the Markdown +#! documentation is shown in. + +import std::net; +import std::json; +import std::serial; +import sakura::analyzer; +module sakura::server; + + +#! A writer of the JSON the server sends. It is lossy, writing bytes that are not +#! valid UTF-8 as U+FFFD, so a message stays valid whatever a file holds. +#! @returns The writer, which holds nothing yet. +pub def message_writer(): json::writer { + var made := json::writer::new(); + made.set_lossy(true); + return made; +} + +#! Appends what a writer wrote, once its value is written whole. +#! @param out Where it is appended. +#! @param written The writer, which a lossy writer given nothing but integers +#! and text never fails at. +pub def append_written(out: &mut string, written: &mut json::writer): void { + val text := written.finish() else (_) { return; }; + out.append(text); +} + +#! Writes Markdown as the protocol's content of that kind, as +#! `{"kind":"markdown","value":"..."}`. +#! @param out Where it is written. +#! @param markdown The Markdown. +pub def write_markdown(out: &mut json::writer, markdown: strview): void { + out.begin_object(); + out.member("kind"); out.text("markdown"); + out.member("value"); out.text(markdown); + out.end_object(); +} + +#! A position as the protocol gives one: a line, and a character counted in +#! UTF-16 code units, both from 0. +pub struct position { + pub var line: u32; #! The line, from 0. + pub var character: u32; #! The UTF-16 code unit within it, from 0. +} + +#! The byte of the text a position of the protocol is at. +#! @param text The text. +#! @param line The line, from 0. +#! @param character The UTF-16 code unit within it, from 0. +#! @returns The byte, which is the end of the line where the line is shorter. +pub def locate(text: strview, line: u64, character: u64): u32 { + var offset: u64 = 0; + var at: u64 = 0; + while at < line && offset < text.length { + if text[offset] == '\n' { + at++; + } + offset++; + } + var units: u64 = 0; + return count_units(text, offset, text.length, character, &mut units) as u32; +} + +#! The position of the protocol a byte of the text is at. +#! @param text The text. +#! @param starts Where each line of the text begins, as its source found. +#! @param offset The byte. +#! @returns The position. +pub def position_of(text: strview, starts: &lines, offset: u32): position { + val end := (offset as u64) < text.length ? offset as u64 : text.length; + val at := starts.place_of(end as u32); + var units: u64 = 0; + count_units(text, end + 1 - at.column as u64, end, 0xFFFFFFFFFFFFFFFF, &mut units); + return position { line = at.line - 1, character = units as u32 }; +} + +#! Counts the UTF-16 code units of a line's characters from a byte on, until a +#! byte, a count of units, or the line's end, whichever comes first. A character +#! of four bytes is two units, and a byte that breaks UTF-8 counts as a character +#! of its own. +#! @param text The text. +#! @param from The byte the characters begin at. +#! @param to The byte they end before, at the latest. +#! @param most How many units are counted, at most. +#! @param units Where the count is written. +#! @returns The byte the characters counted end before. +def count_units(text: strview, from: u64, to: u64, most: u64, units: &mut u64): u64 { + var at := from; + units = 0; + while at < to && text[at] != '\n' && units < most { + val size := serial::utf8_length(text, at); + units += size == 4 ? 2 : 1; + at += size != 0 ? size : 1; + } + return at; +} + +#! Writes a position of the protocol, as `{"line":0,"character":4}`. +#! @param out Where it is written. +#! @param text The text the position is of. +#! @param starts Where each line of the text begins. +#! @param offset The byte it is at. +pub def write_position(out: &mut json::writer, text: strview, starts: &lines, offset: u32): void { + val at := position_of(text, starts, offset); + out.begin_object(); + out.member("line"); out.unsigned(at.line as u64); + out.member("character"); out.unsigned(at.character as u64); + out.end_object(); +} + +#! Writes a range of the protocol, from one byte of the text to another. +#! @param out Where it is written. +#! @param text The text. +#! @param starts Where each line of the text begins. +#! @param start The byte it begins at. +#! @param end The byte it ends before. +pub def write_range(out: &mut json::writer, text: strview, starts: &lines, start: u32, end: u32): void { + out.begin_object(); + out.member("start"); write_position(out, text, starts, start); + out.member("end"); write_position(out, text, starts, end); + out.end_object(); +} + +when os == linux { + #! The path a `file:` URI names, as files of this machine are named, with an + #! empty authority or `localhost`. A folder given with a trailing slash is + #! named without it, so paths compare alike. A `%` that two hexadecimal digits + #! do not follow is kept as it is. + #! @param uri The URI. + #! @returns The path, or nothing where the URI is of another scheme. + pub def uri_path(uri: strview): maybe { + return nothing {} if !uri.starts_with("file://"); + var at: u64 = 7; + while at < uri.length && uri[at] != '/' { + at++; + } + return nothing {} if at >= uri.length; + + var made := uri::decode_lenient(uri.substr(at, uri.length - at)); + while made.length > 1 && made[made.length - 1] == '/' { + made = string::from(made.substr(0, made.length - 1), nothing {}); + } + return move(&mut made); + } + + #! Appends the `file:` URI of a path, its bytes escaped where a URI does not + #! take them as they are. + #! @param out Where it is written. + #! @param path The path. + pub def append_uri(out: &mut string, path: strview): void { + val escaped := uri::encode(path, "/"); + out.append("file://"); + out.append(escaped.view()); + } +} + +when os == windows { + #! The path a `file:` URI names, spelled as `canonical_path` spells paths, so + #! paths compare alike however the editor spells a file. An empty authority, + #! or `localhost` before the path of a drive, names this machine, and any + #! other the server of a share, whose files are `//server/share/...`: VS Code + #! names `\\localhost\c$\x` `file://localhost/c%24/x`, and escapes the name of + #! a server as it does the path, as `file://wsl%24/x`. A `%` that two + #! hexadecimal digits do not follow is kept as it is. + #! @param uri The URI. + #! @returns The path, or nothing where the URI is of another scheme, or names + #! no path. + pub def uri_path(uri: strview): maybe { + return nothing {} if !uri.starts_with("file://"); + val decoded := uri::decode_lenient(uri.substr(7, uri.length - 7)); + var made := string::from("//", nothing {}); + made.append(decoded.view()); + + # `/c:/x`, as VS Code writes `file:///c%3A/x`, is the path `c:/x` of a + # drive, and `/c:` is its root, `c:/`, since `c:` alone is the drive's + # working directory. + val text := made.view(); + var named: u64 = 2; + while named < text.length && text[named] != '/' { + named++; + } + val authority := text.substr(2, named - 2); + val drive := named < text.length && is_drive(text, named + 1); + val local := authority.length == 0 || (drive && authority.lower().view() == "localhost"); + val start: u64 = local ? named + (drive ? 1 : 0) : 0; + var path := string::from(text.substr(start, text.length - start), nothing {}); + if path.length == 2 && is_drive(path.view(), 0) { + path.push('/'); + } + return canonical_path(path.view()); + } + + #! Appends the `file:` URI of a path, as VS Code spells it: `file:///c%3A/x` + #! for `C:/x`, and `file://server/x` for `//server/x`, the bytes of the rest + #! escaped where a URI does not take them as they are. + #! @param out Where it is written. + #! @param path The path. + pub def append_uri(out: &mut string, path: strview): void { + out.append("file://"); + var from: u64 = 0; + if path.starts_with("//") { + from = 2; + } else if is_drive(path, 0) { + val letter: u8 = path[0]; + out.push('/'); + out.push(letter >= 'A' && letter <= 'Z' ? letter + 32 : letter); + out.append("%3A"); + from = 2; + } + val escaped := uri::encode(path.substr(from, path.length - from), "/"); + out.append(escaped.view()); + } + + # Whether text from a byte on begins with the letter of a drive and its + # colon, as `C:`. + def is_drive(text: strview, at: u64): bool { + return false if at + 2 > text.length; + val letter: u8 = text[at]; + return ((letter >= 'a' && letter <= 'z') || (letter >= 'A' && letter <= 'Z')) && text[at + 1] == ':'; + } +} + + +#! Whether a file's name is that of Sakura source, ending in `.sakura`. +#! @param name The name, or a path. +#! @returns Whether it is. +pub def is_sakura(name: strview): bool { + return name.length > 7 && name.ends_with(".sakura"); +} + +#! Appends a documentation comment as Markdown. Doxygen commands, as `@param`, +#! begin paragraphs of their own, and the lines of a paragraph are joined. +#! @param out Where it is written. +#! @param documentation The comment, without its markers. +pub def append_markdown(out: &mut string, documentation: strview): void { + var first := true; + var blank := false; + var line: u64 = 0; + while line < documentation.length { + var stop := line; + while stop < documentation.length && documentation[stop] != '\n' { + stop++; + } + var at := line; + while at < stop && (documentation[at] == ' ' || documentation[at] == '\t') { + at++; + } + line = stop + 1; + if at == stop { + blank = true; + continue; + } + + if (documentation[at] == '@' || documentation[at] == '\\') && at + 1 < stop && is_word_byte(documentation[at + 1]) { + at++; + val name := at; + while at < stop && is_word_byte(documentation[at]) { + at++; + } + val command := documentation.substr(name, at - name); + if !first { + out.append("\n\n"); + } + val param := command == "param" || command == "tparam"; + if param && at < stop && documentation[at] == '[' { + while at < stop && documentation[at] != ']' { + at++; + } + at++; + } + while at < stop && (documentation[at] == ' ' || documentation[at] == '\t') { + at++; + } + + if command == "brief" { + out.append(documentation.substr(at, stop - at)); + } else if param { + val word := at; + while at < stop && is_word_byte(documentation[at]) { + at++; + } + out.append("*@"); + out.append(command); + out.append("* `"); + out.append(documentation.substr(word, at - word)); + out.append("`"); + while at < stop && (documentation[at] == ' ' || documentation[at] == '\t') { + at++; + } + if at < stop { + out.append(" \xE2\x80\x94 "); + } + out.append(documentation.substr(at, stop - at)); + } else { + out.append("*@"); + out.append(command); + out.append("*"); + if at < stop { + out.append(" \xE2\x80\x94 "); + } + out.append(documentation.substr(at, stop - at)); + } + } else { + if !first { + out.append(blank ? "\n\n" : " "); + } + out.append(documentation.substr(at, stop - at)); + } + first = false; + blank = false; + } +} + +#! Appends a signature as a block of Sakura code in Markdown. +#! @param out Where it is written. +#! @param signature The signature. +pub def append_code(out: &mut string, signature: strview): void { + out.append("```sakura\n"); + out.append(signature); + out.append("\n```"); +} diff --git a/system/clock.sakura b/system/clock.sakura new file mode 100644 index 00000000..a4091dce --- /dev/null +++ b/system/clock.sakura @@ -0,0 +1,20 @@ +#! @file clock.sakura +#! @author John Christman (sorakatadzuma@gmail.com) +#! @copyright Malunal Studios, LLC. +#! @license MIT +#! +#! Contains the kinds of clock a system keeps, which `system` reads on each +#! system and `std::time` gives as moments. + +module system; + + +#! A clock a system keeps, which `system::clock` reads. +pub enum clock_kind: u8 { + #! The time of day, since 1970 began in UTC. The system sets it, so it may go + #! forward or back, as when it is corrected over a network. + wall, + #! A clock that only ever goes forward, from a start that means nothing, which + #! is what measures how long something took. + steady, +} diff --git a/system/files.sakura b/system/files.sakura new file mode 100644 index 00000000..c6674c37 --- /dev/null +++ b/system/files.sakura @@ -0,0 +1,99 @@ +#! @file files.sakura +#! @author John Christman (sorakatadzuma@gmail.com) +#! @copyright Malunal Studios, LLC. +#! @license MIT +#! +#! Contains what `system` and `std::io` above it both speak of files in: what +#! kind of file something is, who may do what with it, how one is opened, where +#! a seek is measured from, and what is known of one. They are the system's, so +#! `system` names them without reaching up into the layer above it. + +module system; + +#! What kind of file a path names. +pub enum file_kind: u8 { + other, #! A device, a pipe, a socket, or anything else. + regular, #! A file that holds bytes. + directory, #! A directory, which holds other files. + link, #! A link to another path, which is only seen where links are not followed. +} + +#! Who may do what with a file: read it, write it, or run it, each for its +#! owner, its group, and everyone else, as nine bits. +#! +#! These are the bits POSIX systems keep for every file, written in octal as +#! `0o644`, and they are given and taken as those systems keep them. Those +#! systems may also set three more, the set-user, set-group, and sticky bits, +#! which are kept as they are. +#! +#! Windows keeps less: a file is read only or it is not, and whether it runs is +#! decided by its name. There, permissions read as readable by everyone, +#! writable by everyone unless the file is read only, and runnable by everyone +#! for a directory or a program. Setting them looks only at whether the owner +#! may write, which clears or sets the file's read-only attribute. So +#! `is_read_only` and `with_read_only` mean the same on every system. +pub type permissions = u32; + +pub val permissions::owner_read := 0o400; #! The owner may read it. +pub val permissions::owner_write := 0o200; #! The owner may write it. +pub val permissions::owner_execute := 0o100; #! The owner may run it, or search it where it is a directory. +pub val permissions::group_read := 0o040; #! Its group may read it. +pub val permissions::group_write := 0o020; #! Its group may write it. +pub val permissions::group_execute := 0o010; #! Its group may run it, or search it. +pub val permissions::others_read := 0o004; #! Everyone else may read it. +pub val permissions::others_write := 0o002; #! Everyone else may write it. +pub val permissions::others_execute := 0o001; #! Everyone else may run it, or search it. + +#! What a new file is given, less what the system's mask of the program takes +#! away, as `0o644` from the usual mask of `0o022`. +pub val permissions::default_file := 0o666; + +#! What a new directory is given, less what the system's mask takes away. +pub val permissions::default_directory := 0o777; + +#! Whether no one may write the file. +#! @param this The permissions to read. +#! @returns Whether none of the three write bits is set. +pub val permissions::is_read_only: bool { + get => (this & 0o222) == 0; +} + +#! Makes permissions that are read only, or that let the owner write. +#! @param this The permissions to start from. +#! @param read_only Whether no one may write the file. +#! @returns The permissions without any write bit when read only, and otherwise +#! with the owner's write bit added, leaving who else may write as it +#! was. +pub def permissions::with_read_only(&this, read_only: bool): permissions { + if read_only { + return this & 0o7555; + } + return this | 0o200; +} + +#! How a file is opened, combined with `|`. A file opened without `write` or +#! `append` is opened for reading. +pub type open_flags = u32; + +pub val open_flags::read := 1; #! The file is read. +pub val open_flags::write := 2; #! The file is written. +pub val open_flags::create := 4; #! The file is made where there is none, as `write` needs. +pub val open_flags::truncate := 8; #! What the file held is thrown away. +pub val open_flags::append := 16; #! Every write goes at the end; this implies `write`. +pub val open_flags::exclusive := 32; #! With `create`, opening fails where the file exists. + +#! Where an offset to seek to is measured from. +pub type whence = i32; + +pub val whence::start := 0; #! The start of the file. +pub val whence::current := 1; #! Where the next read or write happens. +pub val whence::end := 2; #! The end of the file. + +#! What is known of a file. +pub struct file_info { + pub var kind: file_kind; #! A file, a directory, a link, or another kind. + pub var size: u64; #! In bytes. A directory's size means what its system says. + pub var permissions: permissions; #! Who may read, write, and run it. + pub var modified: i64; #! When its bytes last changed, in nanoseconds since 1970. + pub var accessed: i64; #! When it was last read, in nanoseconds since 1970. +} diff --git a/system/io_error.sakura b/system/io_error.sakura new file mode 100644 index 00000000..f21c03bc --- /dev/null +++ b/system/io_error.sakura @@ -0,0 +1,39 @@ +#! @file io_error.sakura +#! @author John Christman (sorakatadzuma@gmail.com) +#! @copyright Malunal Studios, LLC. +#! @license MIT +#! +#! Contains why reading or writing a stream, or an operation on a file, failed, +#! which `system` reports, and `std::io`'s streams give. + +module system; + +#! Why an operation on a file, a directory, or the working directory failed. +#! +#! Every operating system reports its failures by numbers of its own, and +#! `system::error_of` turns them into these, so the same failure is the same +#! member everywhere. A failure the members do not name is `other`, and +#! `unexpected_end` is one `std::io` finds itself, never the system. Only a +#! program that handles a signal is ever `interrupted`, and only in a wait for +#! something to arrive: a read, or a wait for a child, which it can try again. +pub enum io_error: u8 { + other, #! A failure none of the other members names. + not_found, #! Nothing is at the path, or a directory on the way to it is missing. + permission_denied, #! The program may not do this to the file. + already_exists, #! Something is already at the path. + not_a_directory, #! A directory was needed, and the path names something else. + is_a_directory, #! A file was needed, and the path names a directory. + directory_not_empty, #! The directory still holds something. + invalid, #! A path, handle, or argument the operation cannot take. + name_too_long, #! The path, or a name within it, is longer than the system takes. + busy, #! The file is in use in a way that stops this. + read_only, #! The file system holding the file is read only. + no_space, #! The device, or the user's share of it, is full. + too_many_open, #! The program, or the system, has as many files open as it may. + cross_device, #! A file cannot be renamed onto another device. + link_loop, #! Following the links in the path went around in a circle. + broken_pipe, #! What was written to has nothing reading it any more. + unsupported, #! The system does not do this. + unexpected_end, #! The input ended before all that was asked for was read. + interrupted, #! A signal the program handles came, ending the wait early. +} diff --git a/system/linux/linux.sakura b/system/linux/linux.sakura new file mode 100644 index 00000000..919a11d9 --- /dev/null +++ b/system/linux/linux.sakura @@ -0,0 +1,26 @@ +#! @file linux.sakura +#! @author John Christman (sorakatadzuma@gmail.com) +#! @copyright Malunal Studios, LLC. +#! @license MIT +#! +#! Contains `system::linux`: what Linux gives a program, declared once for std +#! and anything else that reaches the system itself. A program reaches Linux by +#! system calls, whose numbers and the layouts of what they read and write +#! differ by processor, so each processor's are in a file of its own, as +#! `x86_64.sakura`. + + +module system::linux when os == linux; + +#! Makes a system call, as the operations here do. Its numbers, and what it +#! reads and writes, are the system's, and differ by processor. +#! @param n The number of the call. +#! @param a Its first argument. +#! @param b Its second. +#! @param c Its third. +#! @param d Its fourth. +#! @param e Its fifth. +#! @param f Its sixth. +#! @returns What the call gives, or the negated error number where it fails. +@intrinsic +pub def syscall(n: i64, a: u64, b: u64, c: u64, d: u64, e: u64, f: u64): i64; diff --git a/system/linux/x86_64.sakura b/system/linux/x86_64.sakura new file mode 100644 index 00000000..a79ff99a --- /dev/null +++ b/system/linux/x86_64.sakura @@ -0,0 +1,71 @@ +#! @file x86_64.sakura +#! @author John Christman (sorakatadzuma@gmail.com) +#! @copyright Malunal Studios, LLC. +#! @license MIT +#! +#! Contains what `system::linux` gives of Linux on x86-64. +#! +#! What a program needs to know of Linux on x86-64: the numbers of the system +#! calls it makes, the flags that differ by processor, and +#! where `stat` writes what `file_info` is read from. + + +module system::linux when os == linux && arch == x86_64; + +pub val call_read: i64 = 0; +pub val call_write: i64 = 1; +pub val call_open: i64 = 2; +pub val call_close: i64 = 3; +pub val call_stat: i64 = 4; +pub val call_fstat: i64 = 5; +pub val call_lstat: i64 = 6; +pub val call_poll: i64 = 7; +pub val call_lseek: i64 = 8; +pub val call_mmap: i64 = 9; +pub val call_munmap: i64 = 11; +pub val call_rt_sigaction: i64 = 13; +pub val call_rt_sigprocmask: i64 = 14; +pub val call_dup2: i64 = 33; +pub val call_nanosleep: i64 = 35; +pub val call_getpid: i64 = 39; +pub val call_fork: i64 = 57; +pub val call_execve: i64 = 59; +pub val call_wait4: i64 = 61; +pub val call_kill: i64 = 62; +pub val call_fcntl: i64 = 72; +pub val call_getcwd: i64 = 79; +pub val call_chdir: i64 = 80; +pub val call_rename: i64 = 82; +pub val call_mkdir: i64 = 83; +pub val call_rmdir: i64 = 84; +pub val call_unlink: i64 = 87; +pub val call_chmod: i64 = 90; +pub val call_fchmod: i64 = 91; +pub val call_sched_yield: i64 = 24; +pub val call_rt_sigsuspend: i64 = 130; +pub val call_gettid: i64 = 186; +pub val call_futex: i64 = 202; +pub val call_sched_getaffinity: i64 = 204; +pub val call_getdents64: i64 = 217; +pub val call_clock_gettime: i64 = 228; +pub val call_exit_group: i64 = 231; +pub val call_newfstatat: i64 = 262; +pub val call_pipe2: i64 = 293; + +pub val open_directory := 0x10000u; + +pub const stat_bytes: u64 = 144; +pub val stat_mode := 24u; +pub val stat_size := 48u; +pub val stat_accessed := 72u; # Seconds, then nanoseconds. +pub val stat_modified := 88u; # Seconds, then nanoseconds. + +# What `fcntl` is asked: a copy of a handle at the lowest free number from +# another up, or the handle's flags, of which only close-on-exec is set. +pub val f_dupfd := 0u; +pub val f_setfd := 2u; + +# How `rt_sigprocmask` changes the signals held off: adding some, or setting +# all of them. +pub val sig_block := 0u; +pub val sig_setmask := 2u; diff --git a/system/on_linux.sakura b/system/on_linux.sakura new file mode 100644 index 00000000..f90aab87 --- /dev/null +++ b/system/on_linux.sakura @@ -0,0 +1,1016 @@ +#! @file on_linux.sakura +#! @author John Christman (sorakatadzuma@gmail.com) +#! @copyright Malunal Studios, LLC. +#! @license MIT +#! +#! Contains the operations of `system` on Linux, over the system calls they +#! are made of. +#! +#! The operations of `system` on Linux, over the system calls they are made +#! of, which fail by giving the negated error number, as the operations do. The +#! calls are made through `system::linux`, which declares their numbers, and +#! where `stat` writes what `file_info` is read from, for each processor. + +import system::linux; + +module system when os == linux; + + +#! A handle to an open file or directory, which only the system makes. +pub type fd = i32; + +#! The handle of the standard input. +pub val fd::stdin := 0; +#! The handle of the standard output. +pub val fd::stdout := 1; +#! The handle of the standard error. +pub val fd::stderr := 2; + +#! The longest path the system takes, in bytes, with the zero it ends in. +pub const path_limit: u64 = 4096; + +# Bytes read of a directory at a time. +const listing_bytes: u64 = 16384; + +#! Opens the file at a path. +#! @param path The path of the file to open. +#! @param flags How to open the file. Without `write` or `append`, it is read. +#! @param mode The permissions a file `create` makes is given, less the mask. +#! @returns The handle of the opened file. +pub def open(path: strview, flags: open_flags, mode: u32 = 0o666): fd { + if (flags & 0xFFFFFFC0) != 0 { + return -22 as fd; + } + + val reads := (flags & open_flags::read) != 0; + val writes := (flags & (open_flags::write | open_flags::append)) != 0; + var native: u64 = writes ? (reads ? 2 : 1) : 0; + native = native | 0x80000; + if (flags & open_flags::create) != 0 { + native = native | 0x40; + } + if (flags & open_flags::truncate) != 0 { + native = native | 0x200; + } + if (flags & open_flags::append) != 0 { + native = native | 0x400; + } + if (flags & open_flags::exclusive) != 0 { + native = native | 0x80; + } + return on_path(call_open, path, native, mode) as fd; +} + +#! Describes the file at a path, following a link the path ends in. +#! @param path The path of the file to describe. +#! @param out The description to fill. +#! @returns Zero when the file was described. +pub def stat(path: strview, out: &mut file_info): i32 { + var status: u8[stat_bytes]; + val at := (&mut status) as *mut u8; + return described(on_path(call_stat, path, at as u64, 0), at, out); +} + +#! Describes the file at a path, or the link the path ends in, where it does. +#! @param path The path of the file to describe. +#! @param out The description to fill. +#! @returns Zero when the file was described. +pub def lstat(path: strview, out: &mut file_info): i32 { + var status: u8[stat_bytes]; + val at := (&mut status) as *mut u8; + return described(on_path(call_lstat, path, at as u64, 0), at, out); +} + +#! Sets the permissions of the file at a path. +#! @param path The path of the file. +#! @param mode The permissions to give it. +#! @returns Zero when they were set. +pub def chmod(path: strview, mode: u32): i32 { + return on_path(call_chmod, path, mode, 0) as i32; +} + +#! Makes a directory. +#! @param path The path of the directory, whose parent must exist. +#! @param mode The permissions to give it, less the mask. +#! @returns Zero when it was made. +pub def mkdir(path: strview, mode: u32): i32 { + return on_path(call_mkdir, path, mode, 0) as i32; +} + +#! Removes an empty directory. +#! @param path The path of the directory. +#! @returns Zero when it was removed. +pub def rmdir(path: strview): i32 { + return on_path(call_rmdir, path, 0, 0) as i32; +} + +#! Removes a file, or a link without what it leads to, but not a directory. +#! @param path The path of the file. +#! @returns Zero when it was removed. +pub def unlink(path: strview): i32 { + return on_path(call_unlink, path, 0, 0) as i32; +} + +#! Moves a file or directory to another path, replacing a file there. +#! @param from The path of what to move. +#! @param to Where to move it. +#! @returns Zero when it was moved. +pub def rename(from: strview, to: strview): i32 { + var target: u8[path_limit]; + val at := (&mut target) as *mut u8; + val bad := terminate(to, at); + if bad < 0 { + return bad as i32; + } + return on_path(call_rename, from, at as u64, 0) as i32; +} + +#! Writes the path of the working directory, which is absolute, without a zero. +#! @param into Where the path is written. +#! @param length How many bytes there is room for, `path_limit` being enough. +#! @returns The number of bytes written. +pub def getcwd(into: *mut u8, length: u64): i64 { + val result := syscall(call_getcwd, into as u64, length, 0, 0, 0, 0); + return result < 0 ? result : result - 1; +} + +#! Sets the working directory, which relative paths are taken from. +#! @param path The path of the directory. +#! @returns Zero when it was set. +pub def chdir(path: strview): i32 { + return on_path(call_chdir, path, 0, 0) as i32; +} + +#! Reads from the file into a buffer, waiting until something arrives. +#! @param this The handle of the file to read. +#! @param into Where the bytes read are written. +#! @param length How many bytes there is room for. +#! @returns The number of bytes read, which is zero at the end of the file, or +#! a negative error number, which is `-4` where a signal the program +#! handles ended the wait. +pub def fd::read(&this, into: *mut u8, length: u64): i64 { + return waited(call_read, (this as i64) as u64, into as u64, length); +} + +#! Writes bytes to the file. +#! +#! Writing to a pipe nothing reads fails with -32, which is `broken_pipe`, once +#! the program has made a pipe, as `pipe` says. Writing to the program's own +#! output or error still stops the program, quietly, as it would have before. +#! @param this The handle of the file to write. +#! @param from Where the bytes to write begin. +#! @param length How many bytes to write. +#! @returns The number of bytes written, which may be fewer than asked. +pub def fd::write(&this, from: *u8, length: u64): i64 { + val handle := this as i64; + val result := retried(call_write, handle as u64, from as u64, length); + if result == -32 && quieted && (handle == 1 || handle == 2) { + _ = restore(signal::pipe); + _ = raise(signal::pipe); + } + return result; +} + +#! Writes text to the file. +#! @param this The handle of the file to write. +#! @param text The text to write, which may be a literal, a view of one, or +#! the text a `string` lends. +#! @returns The number of bytes written, which may be fewer than asked. +pub def fd::put(&this, text: strview): i64 { + return this.write(text.data, text.length); +} + +#! Moves the position in the file that reads and writes happen at. +#! @param this The handle of the file to seek. +#! @param offset The offset to move to. +#! @param from Where the offset is measured from. +#! @returns The new position from the start of the file. +pub def fd::seek(&this, offset: i64, from: whence): i64 { + if from < 0 || from > 2 { + return -22; + } + return syscall(call_lseek, (this as i64) as u64, offset as u64, from as u64, 0, 0, 0); +} + +#! Closes the file. +#! @param this The handle of the file to close. +#! @returns Zero when the file was closed. +pub def fd::close(&this): i32 { + val result := syscall(call_close, (this as i64) as u64, 0, 0, 0, 0, 0); + return result < 0 ? result as i32 : 0; +} + +#! Describes the file. +#! @param this The handle of the file to describe. +#! @param out The description to fill. +#! @returns Zero when the file was described. +pub def fd::stat(&this, out: &mut file_info): i32 { + var status: u8[stat_bytes]; + val at := (&mut status) as *mut u8; + return described(syscall(call_fstat, (this as i64) as u64, at as u64, 0, 0, 0, 0), at, out); +} + +#! Sets the permissions of the file. +#! @param this The handle of the file. +#! @param mode The permissions to give it. +#! @returns Zero when they were set. +pub def fd::chmod(&this, mode: u32): i32 { + return syscall(call_fchmod, (this as i64) as u64, mode as u64, 0, 0, 0, 0) as i32; +} + +#! A directory being read, one name at a time, which `opendir` starts and +#! `close` ends. +pub struct dir_stream : owning { + var _handle: fd; + var _buffer: *mut u8; #! What `getdents64` last wrote, which is null where not open. + var _filled: u64; + var _at: u64; +} + +#! Starts reading the names a directory holds. +#! @param path The path of the directory. +#! @param into The stream to read them with, which `close` ends. +#! @returns Zero when the directory was opened. +pub def opendir(path: strview, into: &mut dir_stream): i32 { + val handle := on_path(call_open, path, open_directory | 0x80000, 0); + if handle < 0 { + return handle as i32; + } + + into._handle = handle as fd; + into._buffer = raw_allocate(listing_bytes); + into._filled = 0; + into._at = 0; + return 0; +} + +#! Reads the next name the directory holds, in no particular order, leaving out +#! `.` and `..`. +#! @param this The stream to read. +#! @param out The entry to fill, whose name views the stream's own memory. +#! @returns One when an entry was read, and zero once there are no more. +pub def dir_stream::next(&mut this, out: &mut dir_entry): i32 { + if this._buffer == null { + return -9; + } + + while true { + if this._at >= this._filled { + val handle := (this._handle as i64) as u64; + val count := retried(call_getdents64, handle, this._buffer as u64, listing_bytes); + if count <= 0 { + return count as i32; + } + this._filled = count as u64; + this._at = 0; + } + + # A record holds its file's number, an offset, its own length, the kind, and + # the name, which ends in a zero. + val record := this._buffer + this._at; + this._at += (*((record + 16) as *mut u16)) as u64; + val name := record + 19; + var length := 0u; + while name[length] != 0 { + length++; + } + if name[0] == '.' && (length == 1 || (length == 2 && name[1] == '.')) { + continue; + } + + out.name = strview::over(name, length); + out.kind = this.kind_of(record[18], name); + return 1; + } + return 0; +} + +#! Stops reading the directory. Closing a stream that is not open does nothing. +#! @param this The stream to close. +pub def dir_stream::close(&mut this): void { + if this._buffer == null { + return; + } + + syscall(call_close, (this._handle as i64) as u64, 0, 0, 0, 0, 0); + raw_release(this._buffer); + this._buffer = null; +} + +# The kind a record gives, asking the file itself where the file system does not +# say, as some do not. +def dir_stream::kind_of(&this, kind: u8, name: *mut u8): file_kind { + if kind == 4 { return file_kind::directory; } + if kind == 8 { return file_kind::regular; } + if kind == 10 { return file_kind::link; } + if kind != 0 { return file_kind::other; } + + var status: u8[stat_bytes]; + val at := (&mut status) as *mut u8; + val handle := (this._handle as i64) as u64; + if syscall(call_newfstatat, handle, name as u64, at as u64, 0x100, 0, 0) < 0 { + return file_kind::other; + } + return kind_of_mode(*((at + stat_mode) as *mut u32)); +} + +#! What a failure an operation gave means. +#! @param code The negative number the operation gave. +#! @returns The kind of failure, which is `other` for one no member names. +pub def error_of(code: i64): io_error { + return match -code { + 2 => io_error::not_found, + 1, 13 => io_error::permission_denied, + 17 => io_error::already_exists, + 20 => io_error::not_a_directory, + 21 => io_error::is_a_directory, + 39 => io_error::directory_not_empty, + 9, 22 => io_error::invalid, + 36 => io_error::name_too_long, + 16, 26 => io_error::busy, + 30 => io_error::read_only, + 28, 122 => io_error::no_space, + 23, 24 => io_error::too_many_open, + 18 => io_error::cross_device, + 40 => io_error::link_loop, + 32 => io_error::broken_pipe, + 38, 95 => io_error::unsupported, + 4 => io_error::interrupted, + else => io_error::other, + }; +} + +#! Starts a copy of the program, which goes on from here as the program does, +#! with memory of its own, so nothing either changes reaches the other. +#! @returns Zero in the copy, and in the program the number the copy is known +#! by, which `wait` takes, or a negative error number when no copy +#! started. +pub def fork(): i64 { + return syscall(call_fork, 0, 0, 0, 0, 0, 0); +} + +#! Waits for a copy of the program that `fork` started to stop. +#! @param child The number `fork` gave the program for the copy, or -1 for +#! whichever of its copies stops first. +#! @param status How the copy stopped. +#! @returns The number of the copy that stopped, or a negative error number, +#! which is `-4` where a signal the program handles ended the wait. +pub def wait(child: i64, status: &mut process_status): i64 { + val raw := raw_allocate_zeroed(4) as *mut i32; + val result := waited(call_wait4, child as u64, raw as u64, 0); + val word := raw[0]; + raw_release(raw as *mut u8); + if result < 0 { + return result; + } + + status.exited = (word & 0x7F) == 0; + status.code = (word >> 8) & 0xFF; + status.signal = word & 0x7F; + return result; +} + +#! Sends a signal to a process. +#! @param process The number the system knows the process by, as `getpid` +#! gives the program its own, and `fork` the program a copy's. +#! @param sent The signal to send. +#! @returns Zero when it was sent. +pub def kill(process: i64, sent: signal): i32 { + return syscall(call_kill, process as u64, number_of(sent) as u64, 0, 0, 0, 0) as i32; +} + +#! Sends a signal to the program itself. A signal the program handles is noted +#! before this returns, and its handler runs at the next safe point. +#! @param sent The signal to send. +#! @returns Zero when it was sent. +pub def raise(sent: signal): i32 { + return kill(getpid(), sent); +} + +#! The number the system knows the program by. +#! @returns The number, which `kill` takes. +pub def getpid(): i64 { + return syscall(call_getpid, 0, 0, 0, 0, 0, 0); +} + +#! Has the system throw a signal away when it comes, until `handle` or +#! `restore` says otherwise. +#! @param which The signal to ignore. +#! @returns Zero when it is ignored. `kill` and `stop` cannot be, and neither +#! can `child`, since the system would then throw away how each child +#! stopped, which `wait` gives: each gives -22, which is `invalid`. +pub def ignore(which: signal): i32 { + if which == signal::kill || which == signal::stop || which == signal::child { + return -22; + } + return disposed(which, 1); +} + +#! Has the system do what it does with a signal by default, as it did before the +#! program said otherwise: for most, stopping the program. +#! @param which The signal to restore. +#! @returns Zero when it is restored. +pub def restore(which: signal): i32 { + return disposed(which, 0); +} + +#! Handles a signal with a function, until `handle`, `ignore`, or `restore` says +#! otherwise. The function runs at the program's next safe point once the +#! signal comes, and before a wait the signal interrupts ends. A signal that +#! comes again before its handler runs is handled once, and one that comes while +#! a handler runs is handled once that handler returns. +#! @tparam F The handler's type: a function, a lambda, or a functor. +#! @param which The signal to handle. +#! @param by What handles it, which the program then keeps until another +#! handles the signal: a functor holding what it needs, or a +#! closure sharing the locals where it was made, as one setting a +#! flag the program's loop reads, while those locals last. +#! @returns Zero when it is handled. `kill` and `stop` cannot be, and give -22, +#! which is `invalid`. +pub def handle(which: signal, by: F): i32 where F: invokable { + if which == signal::kill || which == signal::stop { + return -22; + } + + # The handler is in place before the signal can come. + val bit := 1u << (number_of(which) as u64); + handlers[which as u64] = handler::new(move(&mut by)); + handled = handled | bit; + val result := catch_signal(number_of(which)); + if result < 0 { + handled = handled & ~bit; + return result; + } + + noting = noting & ~bit; + ignored = ignored & ~bit; + quieted = quieted && which != signal::pipe; + return result; +} + +#! Has the system note a signal when it comes, for `watched` to give, until +#! `handle`, `ignore`, or `restore` says otherwise. No handler runs, so a +#! program that only watches for signals has no safe points, and asks itself +#! whether one came, as a machine running a program does for that program. A +#! wait the signal interrupts goes on. +#! @param which The signal to watch for. +#! @returns Zero when it is watched for. `kill` and `stop` cannot be, and give +#! -22, which is `invalid`. +pub def watch(which: signal): i32 { + if which == signal::kill || which == signal::stop { + return -22; + } + + val bit := 1u << (number_of(which) as u64); + val result := catch_signal(number_of(which)); + if result < 0 { + return result; + } + + handled = handled & ~bit; + noting = noting | bit; + ignored = ignored & ~bit; + quieted = quieted && which != signal::pipe; + return result; +} + +#! The signals `watch` watches for that came since this last asked, which it +#! forgets. +#! @returns One bit each, by the system's number. +pub def watched(): u64 { + arrived = arrived | take_signals(); + val came := arrived & noting; + arrived = arrived & ~noting; + return came; +} + +#! Waits until a handler has run. A signal that came before the wait began is +#! not missed: its handler runs, and the wait ends at once. Within a handler, +#! where no other runs, it waits until a signal the program handles comes, whose +#! handler runs once the one running returns. +pub def pause(): void { + # The signals handled are held off, so that none comes between finding none + # waiting and the wait, which lets them come and waits in one step. The + # system's set of signals has a bit for each number less one. + var held: u64 = handled >> 1; + var before: u64 = 0; + val holding := (&mut held) as *mut u64; + val kept := (&mut before) as *mut u64; + syscall(call_rt_sigprocmask, sig_block, holding as u64, kept as u64, 8, 0, 0); + while !run_handlers() { + syscall(call_rt_sigsuspend, kept as u64, 8, 0, 0, 0, 0); + if dispatching { + break; + } + } + syscall(call_rt_sigprocmask, sig_setmask, kept as u64, 0, 8, 0, 0); +} + +#! Reads a clock. +#! @param which The clock: the wall clock, or the steady one. +#! @returns Nanoseconds: since 1970 began in UTC of the wall clock, which the +#! system may set forward or back, and since a start that never moves +#! of the steady one, which only ever grows. +pub def clock(which: clock_kind): i64 { + # The system's `CLOCK_REALTIME` is 0, and its `CLOCK_MONOTONIC` 1. It writes + # seconds, then nanoseconds. + var spec: i64[2]; + val at := (&mut spec) as *mut i64; + syscall(call_clock_gettime, which == clock_kind::wall ? 0 : 1, at as u64, 0, 0, 0, 0); + return spec[0] * 1000000000 + spec[1]; +} + +#! Waits for a length of time. +#! @param nanoseconds How long to wait, which is no time at all where it is +#! not above zero. +#! @returns Zero once the time has passed, or a negative error number, which is +#! -4 where a signal the program handles ended the wait, once its +#! handlers ran. A signal no handler ran for only interrupts the wait, +#! which goes on for what is left. +pub def sleep(nanoseconds: i64): i32 { + if nanoseconds <= 0 { + return 0; + } + + # The system takes seconds, then nanoseconds, and writes what is left of a + # wait a signal interrupts. + var wanted: i64[2]; + var left: i64[2]; + wanted[0] = nanoseconds / 1000000000; + wanted[1] = nanoseconds % 1000000000; + val asking := (&mut wanted) as *mut i64; + val unwaited := (&mut left) as *mut i64; + while true { + val result := syscall(call_nanosleep, asking as u64, unwaited as u64, 0, 0, 0, 0); + if result != -4 { + return result as i32; + } + if run_handlers() { + return -4; + } + wanted[0] = left[0]; + wanted[1] = left[1]; + } + return 0; +} + +#! Waits while a word holds what is expected, until another thread or process +#! wakes those waiting on it, which every way of waiting for one another is built +#! on. The word is read and the wait begun in one step, so a wake after the word +#! changes is never missed. +#! @param at The word, which processes sharing the memory share too. +#! @param expected What the word holds to be waited on. +#! @param timeout Nanoseconds to wait at most, or for ever where it is +#! negative. +#! @returns Zero where it was woken, which may be for no reason, or a negative +#! error number: -11 where the word held something else, -110 where the +#! time ran out, and -4 where a signal interrupted it. +pub def futex_wait(at: *mut u32, expected: u32, timeout: i64): i32 { + # The system takes a length of time as seconds, then nanoseconds, or none. + var spec: i64[2]; + spec[0] = timeout / 1000000000; + spec[1] = timeout % 1000000000; + val length: u64 = timeout < 0 ? 0 : ((&mut spec) as *mut i64) as u64; + return syscall(call_futex, at as u64, futex_op_wait, expected as u64, length, 0, 0) as i32; +} + +#! Wakes threads or processes waiting on a word. +#! @param at The word. +#! @param count How many to wake at most. +#! @returns How many it woke, or a negative error number. +pub def futex_wake(at: *mut u32, count: u32): i32 { + return syscall(call_futex, at as u64, futex_op_wake, count as u64, 0, 0, 0) as i32; +} + +# The operations of `futex` the program asks for: waiting and waking, shared with +# other processes mapping the memory, so a word in such memory serves them too. +val futex_op_wait := 0u; +val futex_op_wake := 1u; + +#! How many processors the program may run on, which is how many of its threads +#! run at once. +#! @returns How many, at least one. +pub def cpu_count(): u32 { + # The system writes a set of processors, one bit each, giving its bytes. + var set: u64[16]; + val written := syscall(call_sched_getaffinity, 0, 128, ((&mut set) as *mut u64) as u64, 0, 0, 0); + if written <= 0 { + return 1; + } + var count: u32 = 0; + for i in 0..(written as u64 / 8) { + var word: u64 = set[i]; + while word != 0 { + word = word & (word - 1); + count++; + } + } + return count == 0 ? 1 : count; +} + +#! The number the system knows the calling thread by, which is the program's +#! own number in the thread it began with. +#! @returns The number. +pub def thread_id(): u64 { + return syscall(call_gettid, 0, 0, 0, 0, 0, 0) as u64; +} + +#! Lets the system run other threads before this one goes on. +pub def yield_now(): void { + syscall(call_sched_yield, 0, 0, 0, 0, 0, 0); +} + +# Whether the calling thread is the one the program began with, whose number is +# the program's. +def is_first_thread(): bool { + return thread_id() == getpid() as u64; +} + +# Sets what the system does with a signal: 0 for its default, and 1 to throw it +# away, giving zero, or the negated error number. +def disposed(which: signal, action: u64): i32 { + var act: u64[4]; + val at := (&mut act) as *mut u64; + at[0] = action; + val result := syscall(call_rt_sigaction, number_of(which) as u64, at as u64, 0, 8, 0, 0) as i32; + if result != 0 { + return result; + } + + val bit := 1u << (number_of(which) as u64); + handled = handled & ~bit; + noting = noting & ~bit; + ignored = action == 1 ? ignored | bit : ignored & ~bit; + quieted = quieted && which != signal::pipe; + return result; +} + +# The signals the program ignores, one bit each by number, which a program it +# starts is given at their defaults. +var ignored: u64; + +# Whether std ignores `pipe`, which it does once the program makes a pipe where +# the program has neither handled nor ignored the signal itself. +var quieted: bool; + +# Has the system ignore `pipe`, so that writing to a pipe nothing reads fails +# rather than stopping the program, where the program has said nothing of the +# signal itself. +def quiet_broken_pipes(): void { + val bit := 1u << (number_of(signal::pipe) as u64); + if quieted || ((handled | ignored) & bit) != 0 { + return; + } + if disposed(signal::pipe, 1) == 0 { + quieted = true; + } +} + +#! The path of the device that reads as empty, and throws away what is written +#! to it. +pub val null_device: strview = "/dev/null"; + +#! Makes a pipe: what is written to one end is read from the other. Neither end +#! is inherited by a program the program starts, unless `spawn` is asked to give +#! it one. +#! +#! Writing to a pipe nothing reads then fails with -32, which is `broken_pipe`, +#! rather than stopping the program, as the system would by default. The first +#! pipe has the system ignore `signal::pipe`, where the program has neither +#! handled nor ignored it itself, and `fd::write` still stops the program where +#! its own output or error is what nothing reads. +#! @param reading Where the handle of the end that is read is written. +#! @param writing Where the handle of the end that is written is written. +#! @returns Zero when the pipe was made. +pub def pipe(reading: &mut fd, writing: &mut fd): i32 { + var ends: i32[2]; + val at := (&mut ends) as *mut i32; + val made := syscall(call_pipe2, at as u64, 0x80000, 0, 0, 0, 0); + if made < 0 { + return made as i32; + } + + quiet_broken_pipes(); + reading = ends[0]; + writing = ends[1]; + return 0; +} + +#! Starts a program, which runs beside this one until it stops, and which `wait` +#! waits for. +#! +#! The program is given the handles the request names as its standard streams, +#! and inherits no other. The signals this program ignores are put back at their +#! defaults for it, and those it handles go back to theirs by themselves. +#! @param request What to start, and with what, all of which is copied before +#! the program starts. +#! @returns The number the system knows the started program by, which `wait` +#! and `kill` take, or a negative error number: -2 where the program +#! is not found, -13 where it may not be run, and -22 where a text the +#! request holds has a zero in it. +pub def spawn(request: &spawn_request): i64 { + var laid: spawn_block; + if !laid.lay_out(request) { + return -22; + } + + # The copy that becomes the program writes why where it cannot. Both ends close + # on `execve`, so nothing comes through where the program starts. + var ends: i32[2]; + val at := (&mut ends) as *mut i32; + val piped := syscall(call_pipe2, at as u64, 0x80000, 0, 0, 0, 0); + if piped < 0 { + raw_release(laid.block); + return piped; + } + + val child := syscall(call_fork, 0, 0, 0, 0, 0, 0); + if child == 0 { + become(request, &laid, ends[1]); + } + + syscall(call_close, ends[1] as u64, 0, 0, 0, 0, 0); + raw_release(laid.block); + var code: i32 = 0; + val read := child < 0 ? 0 : retried(call_read, ends[0] as u64, ((&mut code) as *mut i32) as u64, 4); + syscall(call_close, ends[0] as u64, 0, 0, 0, 0, 0); + if child < 0 || read != 4 { + return child; + } + + # The copy has stopped, and is waited for so that it leaves nothing behind. + var word: i32 = 0; + retried(call_wait4, child as u64, ((&mut word) as *mut i32) as u64, 0); + return -(code as i64); +} + +#! Waits until one of the handles can be read, or has ended, for at most a +#! while. +#! @param handles The handles to wait on. One that is negative is passed over, +#! as one already read to its end may be. +#! @param ready Where whether each can be read, or has ended, is written, at +#! the index of its handle. +#! @param wait The most milliseconds to wait, or -1 to wait for as long as +#! it takes. +#! @returns How many can be, 0 where the wait ran out, or a negative error +#! number, which is -4 where a signal the program handles ended the +#! wait. +pub def poll(handles: span, ready: slice, wait: i64 = -1): i32 { + if ready.length < handles.length { + return -22; + } + + # Each entry is a handle, then what is waited for and what came, as two halves + # of a word. Only reading is waited for, and an end or a failure comes anyway. + val entries := raw_allocate(handles.length * 8) as *mut i32; + for i in 0..handles.length { + entries[2 * i] = handles[i]; + entries[2 * i + 1] = 1; + } + val result := waited(call_poll, entries as u64, handles.length, (wait < 0 ? -1 : wait) as u64); + val came := entries as *mut i16; + for i in 0..handles.length { + ready[i] = result > 0 && came[4 * i + 3] != 0; + } + raw_release(entries as *mut u8); + return result as i32; +} + +# Where the system put the variables the program started with: pointers to text +# ending in a zero, then a null pointer. +@intrinsic +def environ(): **u8; + +# Views of the variables the program started with, once `environment` has made +# them, which it keeps for as long as the program runs. +var variables: span; +var viewed: bool; + +#! The variables the program started with, each as `NAME=value`. +#! @returns Views of each, which are good for as long as the program runs, since +#! nothing changes what they view. +pub def environment(): span { + if viewed { + return variables; + } + + val each := environ(); + var count := 0u; + while each != null && each[count] != null { + count++; + } + val views := raw_allocate(count * size_of::()) as *mut strview; + for i in 0..count { + val text := each[i]; + var length := 0u; + while text[length] != 0 { + length++; + } + views[i] = strview::over(text, length); + } + + variables = span::::over(views as *strview, count); + viewed = true; + return variables; +} + +# What `spawn` copies a request into before the program starts: one block +# holding the runs of pointers `execve` takes, each ending in null, then each +# text, ending in a zero. +struct spawn_block { + var block: *mut u8; + var path: *mut u8; + var arguments: *mut u64; + var environment: *mut u64; + var directory: *mut u8; # Null where the request names none. +} + +# Copies a request into a block of its own, giving whether it could, which it +# cannot where a text holds a zero. +def spawn_block::lay_out(&mut this, request: &spawn_request): bool { + val arguments := request.arguments.length; + val variables := request.environment.length; + var size := (arguments + variables + 2) * 8 + request.program.length + request.directory.length + 2; + for i in 0..arguments { + size += request.arguments[i].length + 1; + } + for i in 0..variables { + size += request.environment[i].length + 1; + } + + this.block = raw_allocate_zeroed(size); + this.arguments = this.block as *mut u64; + this.environment = this.arguments + arguments + 1; + var at := (this.environment + variables + 1) as *mut u8; + this.path = at; + at = copied(request.program, at); + for i in 0..arguments { + this.arguments[i] = at as u64; + at = at == null ? null : copied(request.arguments[i], at); + } + for i in 0..variables { + this.environment[i] = at as u64; + at = at == null ? null : copied(request.environment[i], at); + } + this.arguments[arguments] = 0; + this.environment[variables] = 0; + this.directory = request.directory.length == 0 ? null : at; + if at != null && request.directory.length != 0 { + at = copied(request.directory, at); + } + + if at == null { + raw_release(this.block); + return false; + } + return true; +} + +# Copies text, then a zero, giving where the copy ends, or null where the text +# holds a zero itself. +def copied(text: strview, into: *mut u8): *mut u8 { + if into == null { + return null; + } + for i in 0..text.length { + if text.data[i] == 0 { + return null; + } + } + memcpy(into, text.data, text.length); + into[text.length] = 0; + return into + text.length + 1; +} + +# Becomes the program the request names, in the copy `spawn` started, making +# only system calls, so the copy changes nothing it shares with the program. +# Where it cannot, it writes why to `report`, and exits with 127, which runs +# nothing the program asked to be run as it stops. +def become(request: &spawn_request, laid: &spawn_block, report: i32): void { + # A handle below 3 not already where it goes would be overwritten by moving + # another there, so each is moved above them first. + var handles: i64[3]; + handles[0] = request.input as i64; + handles[1] = request.output as i64; + handles[2] = request.error as i64; + for i in 0u..3u { + if handles[i] >= 0 && handles[i] < 3 && handles[i] != i as i64 { + handles[i] = syscall(call_fcntl, handles[i] as u64, f_dupfd, 3, 0, 0, 0); + } + } + for i in 0u..3u { + if handles[i] == i as i64 { + syscall(call_fcntl, i, f_setfd, 0, 0, 0, 0); + continue; + } + syscall(call_dup2, handles[i] as u64, i, 0, 0, 0, 0); + } + + # Ignored signals stay ignored across `execve`, so each goes back to its + # default, and none is held off. + var act: u64[4]; + val default := (&mut act) as *mut u64; + for number in 1u..64u { + if ((ignored >> number) & 1) != 0 { + syscall(call_rt_sigaction, number, default as u64, 0, 8, 0, 0); + } + } + syscall(call_rt_sigprocmask, sig_setmask, default as u64, 0, 8, 0, 0); + + var failed: i64 = 0; + if laid.directory != null { + failed = syscall(call_chdir, laid.directory as u64, 0, 0, 0, 0, 0); + } + if failed >= 0 { + failed = syscall(call_execve, laid.path as u64, laid.arguments as u64, laid.environment as u64, 0, 0, 0); + } + + var code: i32 = (-failed) as i32; + syscall(call_write, report as u64, ((&mut code) as *mut i32) as u64, 4, 0, 0, 0); + syscall(call_exit_group, 127, 0, 0, 0, 0, 0); +} + +# Makes a system call on a path, with two more arguments, giving what it gives. +def on_path(n: i64, path: strview, b: u64, c: u64): i64 { + var text: u8[path_limit]; + val at := (&mut text) as *mut u8; + val bad := terminate(path, at); + if bad < 0 { + return bad; + } + return retried(n, at as u64, b, c); +} + +# Copies a path into `into`, then a zero, as the system calls read paths. Gives +# zero, or the negated error number where the path is too long or holds a zero. +def terminate(path: strview, into: *mut u8): i64 { + if path.length >= path_limit { + return -36; + } + for i in 0..path.length { + if path.data[i] == 0 { + return -22; + } + } + + memcpy(into, path.data, path.length); + into[path.length] = 0; + return 0; +} + +# Retries a system call interrupted by a signal, as everything that does not +# wait for something to arrive is, so that it is never left half done. The +# handlers run at the program's next safe point. +def retried(n: i64, a: u64, b: u64, c: u64): i64 { + while true { + val result := syscall(n, a, b, c, 0, 0, 0); + if result != -4 { + return result; + } + } + return 0; +} + +# Makes a system call that waits for something to arrive. Where a signal the +# program handles interrupts it, the handlers run, and the wait ends, giving -4; +# where none ran, as within a handler, it waits again. +def waited(n: i64, a: u64, b: u64, c: u64): i64 { + while true { + val result := syscall(n, a, b, c, 0, 0, 0); + if result != -4 || run_handlers() { + return result; + } + } + return 0; +} + +# Fills a description from what `stat` wrote, where the call that wrote it, which +# gave `result`, succeeded. Gives zero, or that call's failure. +def described(result: i64, status: *mut u8, out: &mut file_info): i32 { + if result < 0 { + return result as i32; + } + + val mode := *((status + stat_mode) as *mut u32); + val size := *((status + stat_size) as *mut i64); + out.kind = kind_of_mode(mode); + out.size = size < 0 ? 0 : size as u64; + out.permissions = mode & 0o7777; + out.modified = nanoseconds(status + stat_modified); + out.accessed = nanoseconds(status + stat_accessed); + return 0; +} + +# A time `stat` wrote, as seconds then nanoseconds, in nanoseconds. +def nanoseconds(at: *mut u8): i64 { + val words := at as *mut i64; + return words[0] * 1000000000 + words[1]; +} + +def kind_of_mode(mode: u32): file_kind { + val kind := mode & 0xF000; + if kind == 0x8000 { return file_kind::regular; } + if kind == 0x4000 { return file_kind::directory; } + if kind == 0xA000 { return file_kind::link; } + return file_kind::other; +} diff --git a/system/on_linux_x86_64.sakura b/system/on_linux_x86_64.sakura new file mode 100644 index 00000000..13ba7745 --- /dev/null +++ b/system/on_linux_x86_64.sakura @@ -0,0 +1,52 @@ +#! @file on_linux_x86_64.sakura +#! @author John Christman (sorakatadzuma@gmail.com) +#! @copyright Malunal Studios, LLC. +#! @license MIT +#! +#! Contains the numbers Linux gives the signals `system` names, on x86-64. + + +module system when os == linux && arch == x86_64; + +# The number Linux gives a signal on x86-64. +def number_of(which: signal): i32 { + return match which { + hangup => 1, + interrupt => 2, + quit => 3, + kill => 9, + user1 => 10, + user2 => 12, + pipe => 13, + alarm => 14, + terminate => 15, + child => 17, + resume => 18, + stop => 19, + suspend => 20, + resized => 28, + }; +} + +#! The signal Linux gives a number on x86-64, where it is one `signal` names. +#! @param number The number. +#! @returns The signal, or nothing. +pub def signal_of(number: i64): maybe { + return match number { + 1 => signal::hangup, + 2 => signal::interrupt, + 3 => signal::quit, + 9 => signal::kill, + 10 => signal::user1, + 12 => signal::user2, + 13 => signal::pipe, + 14 => signal::alarm, + 15 => signal::terminate, + 17 => signal::child, + 18 => signal::resume, + 19 => signal::stop, + 20 => signal::suspend, + 28 => signal::resized, + else => nothing{}, + }; +} diff --git a/system/on_windows.sakura b/system/on_windows.sakura new file mode 100644 index 00000000..c824fa51 --- /dev/null +++ b/system/on_windows.sakura @@ -0,0 +1,2449 @@ +#! @file on_windows.sakura +#! @author John Christman (sorakatadzuma@gmail.com) +#! @copyright Malunal Studios, LLC. +#! @license MIT +#! +#! Contains the operations of `system` on Windows, over the functions of the +#! system they are made of. +#! +#! The operations of `system` on Windows, over the functions of the system, +#! which the program links as C functions, from `kernel32.dll` and, for waiting +#! on a word, from the set of functions Windows keeps for that. They fail as the +#! operations do everywhere, by giving the negated error number Linux would +#! give, which `errno_of` makes of the system's own codes, so `error_of` reads +#! them as it does on Linux. +#! +#! Paths and text are UTF-8 to the program and UTF-16 to the system, and are +#! turned from one to the other here, a surrogate standing alone in a name +#! becoming three bytes, as WTF-8 writes one, so a name read from the system +#! reaches the same file again. A handle is the system's own, which fits 32 +#! bits, with 0, 1, and 2 standing for the standard streams. Windows has no +#! signals of its own: the console's Ctrl-C, Ctrl-Break, and closing are noted +#! as `interrupt`, `quit`, and `hangup`, and logging off and shutting down as +#! `terminate`, by the numbers Linux gives them, which `on_windows_x86_64.sakura` +#! declares. + +import system::windows; + +module system when os == windows; + + +const find_bytes: u64 = 592; # A WIN32_FIND_DATAW, whose name is 44 bytes in. +const name_bytes: u64 = 1024; # A name of a directory, of at most 255 units, as UTF-8. + +#! A handle to an open file, pipe, or console, which only the system makes: the +#! system's own, which fits 32 bits, or 0, 1, or 2, which stand for the +#! standard streams the program was given. +pub type fd = i32; + +#! The handle of the standard input. +pub val fd::stdin := 0; +#! The handle of the standard output. +pub val fd::stdout := 1; +#! The handle of the standard error. +pub val fd::stderr := 2; + +#! The longest path the system takes, in bytes, with the zero it ends in. +pub const path_limit: u64 = 32768; + +# The longest a path is that every function of the system takes as it is, in +# units. A longer one is written as a path of the whole file system, which they +# take up to `path_limit`. +const long_path: u64 = 248; + +# The system's handle an fd stands for. +def handle_of(which: fd): u64 { + if which >= 0 && which <= 2 { + return GetStdHandle(0xFFFFFFF6 - which as u32); + } + return (which as i64) as u64; +} + +# The fd of a handle the system gave, or the failure where it gave none. +def fd_of(handle: u64): i64 { + if handle == invalid_handle || handle == 0 { + return failed(); + } + return handle as i64; +} + +# The failure the system says the call before failed with, as an error number. +def failed(): i64 { + return errno_of(GetLastError()); +} + +# The error number Linux gives the failure a code of the system says, or, for a +# code no number stands for, the code itself, past the numbers Linux gives, so +# that `error_of` reads it as `other` and it is not lost. +def errno_of(code: u32): i64 { + return match code { + 2, 3, 15, 53, 67, 161 => -2, + 5, 1314, 1920 => -13, + 80, 183 => -17, + 267 => -20, + 145 => -39, + 6 => -9, + 87, 123, 131, 1113 => -22, + 206 => -36, + 16, 32, 33, 148, 170 => -16, + 19 => -30, + 39, 112 => -28, + 1295 => -122, + 4 => -24, + 17 => -18, + 1921 => -40, + 109, 232, 233 => -32, + 1, 50, 120 => -95, + 995 => -4, + 1460 => -110, + 132 => -29, + 193 => -8, + 8, 14 => -12, + else => -(65536 + code as i64), + }; +} + +#! What a failure an operation gave means. +#! @param code The negative number the operation gave. +#! @returns The kind of failure, which is `other` for one no member names. +pub def error_of(code: i64): io_error { + return match -code { + 2 => io_error::not_found, + 1, 13 => io_error::permission_denied, + 17 => io_error::already_exists, + 20 => io_error::not_a_directory, + 21 => io_error::is_a_directory, + 39 => io_error::directory_not_empty, + 9, 22 => io_error::invalid, + 36 => io_error::name_too_long, + 16, 26 => io_error::busy, + 30 => io_error::read_only, + 28, 122 => io_error::no_space, + 23, 24 => io_error::too_many_open, + 18 => io_error::cross_device, + 40 => io_error::link_loop, + 32 => io_error::broken_pipe, + 38, 95 => io_error::unsupported, + 4 => io_error::interrupted, + else => io_error::other, + }; +} + +# Text as UTF-16, ending in a zero, as the system takes it, in memory of its own, +# which is let go where it closes. +struct wide_text : owning { + var block: *mut u16; # The memory, which is null where none was taken. + var units: *mut u16; # Where the text begins within it. +} + +def wide_text::close(&mut this): void { + if this.block != null { + raw_release(this.block as *mut u8); + this.block = null; + this.units = null; + } +} + +# The character UTF-8 writes at a byte, as WTF-8 reads it, into `code`, giving +# how many bytes it takes, or zero where none begins there. +def decoded(text: strview, at: u64, code: &mut u32): u64 { + val first := text[at] as u32; + if first < 0x80 { + code = first; + return 1; + } + + var length := 0u; + var value: u32 = 0; + if first >= 0xC2 && first <= 0xDF { + length = 2; + value = first & 0x1F; + } else if first >= 0xE0 && first <= 0xEF { + length = 3; + value = first & 0x0F; + } else if first >= 0xF0 && first <= 0xF4 { + length = 4; + value = first & 0x07; + } else { + return 0; + } + return 0 if at + length > text.length; + for k in 1u..length { + val next := text[at + k] as u32; + return 0 if (next & 0xC0) != 0x80; + value = (value << 6) | (next & 0x3F); + } + return 0 if (length == 3 && value < 0x800) || (length == 4 && (value < 0x10000 || value > 0x10FFFF)); + code = value; + return length; +} + +# Writes UTF-8 as UTF-16, giving how many units it wrote, which are at most as +# many as the bytes. Where `strict` asks, text holding a zero, or that is not +# UTF-8, gives -22; otherwise a zero is written as it is, and a byte beginning +# no character as U+FFFD. A surrogate standing alone, as WTF-8 writes one, is +# written as itself. +def utf16_of(text: strview, into: *mut u16, strict: bool): i64 { + var at := 0u; + var out := 0u; + while at < text.length { + var code: u32 = 0xFFFD; + val length := decoded(text, at, &mut code); + if strict && (length == 0 || code == 0) { + return -22; + } + at += length == 0 ? 1 : length; + + if code >= 0x10000 { + into[out] = (0xD800 | ((code - 0x10000) >> 10)) as u16; + into[out + 1] = (0xDC00 | ((code - 0x10000) & 0x3FF)) as u16; + out += 2; + } else { + into[out] = code as u16; + out++; + } + } + return out as i64; +} + +# Writes UTF-16 as UTF-8, a surrogate standing alone as WTF-8 writes one, giving +# how many bytes it wrote, or -34 where they do not fit. +def narrow(units: *u16, count: u64, into: *mut u8, room: u64): i64 { + var out := 0u; + var at := 0u; + while at < count { + var code := units[at] as u32; + at++; + if code >= 0xD800 && code < 0xDC00 && at < count && units[at] >= 0xDC00 && units[at] < 0xE000 { + code = 0x10000 + ((code - 0xD800) << 10) + (units[at] as u32 - 0xDC00); + at++; + } + + val bytes := code < 0x80 ? 1u : code < 0x800 ? 2u : code < 0x10000 ? 3u : 4u; + if out + bytes > room { + return -34; + } + if bytes == 1 { + into[out] = code as u8; + } else if bytes == 2 { + into[out] = (0xC0 | (code >> 6)) as u8; + into[out + 1] = (0x80 | (code & 0x3F)) as u8; + } else if bytes == 3 { + into[out] = (0xE0 | (code >> 12)) as u8; + into[out + 1] = (0x80 | ((code >> 6) & 0x3F)) as u8; + into[out + 2] = (0x80 | (code & 0x3F)) as u8; + } else { + into[out] = (0xF0 | (code >> 18)) as u8; + into[out + 1] = (0x80 | ((code >> 12) & 0x3F)) as u8; + into[out + 2] = (0x80 | ((code >> 6) & 0x3F)) as u8; + into[out + 3] = (0x80 | (code & 0x3F)) as u8; + } + out += bytes; + } + return out as i64; +} + +# How many units text the system wrote holds before the zero it ends in. +def length_of(units: *u16): u64 { + var length := 0u; + while units[length] != 0 { + length++; + } + return length; +} + +# Writes text as the system takes it, giving zero, or -22 where it holds a zero +# or is not UTF-8. +def widen(text: strview, into: &mut wide_text): i64 { + into.block = raw_allocate((text.length + 1) * 2) as *mut u16; + into.units = into.block; + val count := utf16_of(text, into.units, true); + if count < 0 { + return count; + } + into.units[count] = 0; + return 0; +} + +# Writes a path as the system takes it, giving zero, or -22 where it holds a +# zero or is not UTF-8. A path too long for every function to take as it is, +# and that names where it is from the root of a drive or a share, is written as +# a path of the whole file system, `\\?\C:\…` or `\\?\UNC\server\…`, which +# they take whole. The system then works out no `.` or `..` in it, so a path +# holding one is left as it is. +def wide_path(path: strview, into: &mut wide_text): i64 { + # Room is kept before the text for what such a path begins with. + into.block = raw_allocate((path.length + 9) * 2) as *mut u16; + val text := into.block + 8; + val count := utf16_of(path, text, true); + if count < 0 { + return count; + } + text[count] = 0; + into.units = text; + + val length := count as u64; + val drive := length >= 3 && text[1] == ':' as u16 && is_slash(text[2]); + val shared := length >= 3 && is_slash(text[0]) && is_slash(text[1]) && text[2] != '?' as u16 && text[2] != '.' as u16; + if length < long_path || !(drive || shared) || has_dots(text, length) { + return 0; + } + + for i in 0..length { + if text[i] == '/' as u16 { + text[i] = '\\' as u16; + } + } + if drive { + into.units = text - 4; + put_units(into.units, "\\\\?\\"); + } else { + into.units = text - 6; + put_units(into.units, "\\\\?\\UNC\\"); + } + return 0; +} + +# Writes text of ASCII as units. +def put_units(into: *mut u16, text: strview): void { + for i in 0..text.length { + into[i] = text[i] as u16; + } +} + +def is_slash(unit: u16): bool { + return unit == '\\' as u16 || unit == '/' as u16; +} + +# Whether a path holds a `.` or `..` between its slashes. +def has_dots(units: *mut u16, length: u64): bool { + var start := 0u; + for i in 0..length + 1 { + if i < length && !is_slash(units[i]) { + continue; + } + val size := i - start; + val dot := size >= 1 && units[start] == '.' as u16; + if dot && (size == 1 || (size == 2 && units[start + 1] == '.' as u16)) { + return true; + } + start = i + 1; + } + return false; +} + +# Calls a function of the system on a path, giving zero where it succeeded, or +# its failure. +def on_path(path: strview, act: def(*u16): i32): i32 { + var name: wide_text; + val bad := wide_path(path, &mut name); + if bad < 0 { + return bad as i32; + } + if act(name.units as *u16) == 0 { + return failed() as i32; + } + return 0; +} + +# Whether a name the system takes is of a directory. +def is_directory(name: *u16): bool { + val attributes := GetFileAttributesW(name); + return attributes != invalid_attributes && (attributes & directory) != 0; +} + +#! Opens the file at a path. +#! +#! Another program, or this one, may read, write, rename, and remove the file +#! while it is open, as POSIX lets it. A directory opens only to be read. +#! @param path The path of the file to open. +#! @param flags How to open the file. Without `write` or `append`, it is read. +#! @param mode The permissions a file `create` makes is given, of which only +#! whether the owner may write is kept: without it, the file is +#! read only. +#! @returns The handle of the opened file. +pub def open(path: strview, flags: open_flags, mode: u32 = 0o666): fd { + if (flags & 0xFFFFFFC0) != 0 { + return -22 as fd; + } + + val reads := (flags & open_flags::read) != 0; + val appends := (flags & open_flags::append) != 0; + val writes := (flags & open_flags::write) != 0 || appends; + val creates := (flags & open_flags::create) != 0; + val truncates := (flags & open_flags::truncate) != 0; + val exclusive := (flags & open_flags::exclusive) != 0; + + # A file opened to append may only add to its end, so every write goes there, + # whoever else writes it, unless it is emptied too, which writing does. + var access: u32 = synchronize | read_attributes; + if reads || !writes { + access = access | generic_read; + } + if writes && (!appends || truncates) { + access = access | generic_write; + } + if appends { + access = access | append_data | write_attributes; + } + val disposition: u32 = creates + ? (exclusive ? create_new : truncates ? create_always : open_always) + : (truncates ? truncate_existing : open_existing); + var attributes: u32 = creates && (mode & 0o200) == 0 ? readonly : normal; + if !writes { + attributes = attributes | backup_semantics; + } + + var name: wide_text; + val bad := wide_path(path, &mut name); + if bad < 0 { + return bad as fd; + } + val handle := CreateFileW(name.units as *u16, access, share_all, null, disposition, attributes, 0); + if handle == invalid_handle { + val why := GetLastError(); + if why == error_access_denied && writes && is_directory(name.units as *u16) { + return -21 as fd; + } + return errno_of(why) as fd; + } + return fd_of(handle) as fd; +} + +#! Describes the file at a path, following a link the path ends in. +#! @param path The path of the file to describe. +#! @param out The description to fill. +#! @returns Zero when the file was described. +pub def stat(path: strview, out: &mut file_info): i32 { + return described_at(path, true, out); +} + +#! Describes the file at a path, or the link the path ends in, where it does. +#! @param path The path of the file to describe. +#! @param out The description to fill. +#! @returns Zero when the file was described. +pub def lstat(path: strview, out: &mut file_info): i32 { + return described_at(path, false, out); +} + +# Describes the file at a path, following a link it ends in where `follow` says. +def described_at(path: strview, follow: bool, out: &mut file_info): i32 { + var name: wide_text; + val bad := wide_path(path, &mut name); + if bad < 0 { + return bad as i32; + } + + val units := name.units as *u16; + val flags: u32 = follow ? backup_semantics : backup_semantics | open_reparse_point; + var handle := CreateFileW(units, read_attributes, share_all, null, open_existing, flags, 0); + var why: u32 = handle == invalid_handle ? GetLastError() : 0; + + # An alias of an app of the system's store opens only as itself, and is the + # program it starts. + var aliased := false; + if why == error_cant_access_file && follow { + handle = CreateFileW(units, read_attributes, share_all, null, open_existing, flags | open_reparse_point, 0); + why = handle == invalid_handle ? GetLastError() : 0; + aliased = true; + } + + # A file the system holds open for itself, as its paging file, is described by + # its directory instead. + if why == error_sharing_violation { + return described_found(units, out); + } + if handle == invalid_handle { + return errno_of(why) as i32; + } + + val result := described(handle, !follow && !aliased, units, out); + CloseHandle(handle); + return result; +} + +# Fills a description of an open file, as its handle gives it, of what a link +# it is where `links` says to look, and of whether it runs by its name, where +# that is given. +def described(handle: u64, links: bool, name: *u16, out: &mut file_info): i32 { + SetLastError(0); + val kind := GetFileType(handle); + if kind != disk_type { + if kind == 0 && GetLastError() != 0 { + return failed() as i32; + } + + # A console, a pipe, or a device is no file the system describes. + out.kind = file_kind::other; + out.size = 0; + out.permissions = 0o666; + out.modified = 0; + out.accessed = 0; + return 0; + } + + var info: file_information; + if GetFileInformationByHandle(handle, &mut info) == 0 { + return failed() as i32; + } + out.kind = (info.attributes & directory) != 0 ? file_kind::directory : file_kind::regular; + if links && (info.attributes & reparse_point) != 0 && is_link(handle) { + out.kind = file_kind::link; + } + out.size = ((info.size_high as u64) << 32) | info.size_low as u64; + out.permissions = permissions_of(info.attributes, out.kind, name); + out.modified = nanoseconds_of(&info.written); + out.accessed = nanoseconds_of(&info.accessed); + return 0; +} + +# Describes a file by what its directory says of it, as `FindFirstFileExW` reads +# it, for a file the system will not open even to describe. +def described_found(name: *u16, out: &mut file_info): i32 { + val data := raw_allocate(find_bytes); + val find := FindFirstFileExW(name, 1, data, 0, null, 0); + if find == invalid_handle { + val why := failed(); + raw_release(data); + return why as i32; + } + FindClose(find); + + val attributes := *(data as *mut u32); + out.kind = (attributes & directory) != 0 ? file_kind::directory : file_kind::regular; + out.size = ((*((data + 28) as *mut u32) as u64) << 32) | *((data + 32) as *mut u32) as u64; + out.permissions = permissions_of(attributes, out.kind, name); + out.modified = nanoseconds_of(&*((data + 20) as *mut filetime)); + out.accessed = nanoseconds_of(&*((data + 12) as *mut filetime)); + raw_release(data); + return 0; +} + +# Whether an open file whose attributes say it is a reparse point is a link to +# a file or a directory, rather than one of the other kinds the system keeps. +def is_link(handle: u64): bool { + var tag: u32[2]; + if GetFileInformationByHandleEx(handle, 9, (&mut tag) as *mut u8, 8) == 0 { + return false; + } + return tag[1] == symlink_tag || tag[1] == junction_tag; +} + +# The permissions of a file, as Windows keeps them: readable by everyone, +# writable by everyone unless it is read only, and runnable by everyone where it +# is a directory, or its name says it is a program. +def permissions_of(attributes: u32, kind: file_kind, name: *u16): u32 { + if kind == file_kind::link { + return 0o777; + } + var made: u32 = 0o444; + if (attributes & readonly) == 0 { + made = made | 0o222; + } + if kind == file_kind::directory || (name != null && runs(name)) { + made = made | 0o111; + } + return made; +} + +# Whether a name ends in what a program's does: `.exe` or `.com`, which the +# system runs, or `.bat` or `.cmd`, which `cmd.exe` does. +def runs(name: *u16): bool { + val length := length_of(name); + return length >= 4 && name[length - 4] == '.' as u16 && ( + ends_as(name, length, "exe") || ends_as(name, length, "com") || + ends_as(name, length, "bat") || ends_as(name, length, "cmd") + ); +} + +# Whether units end in ASCII, compared without regard to case. +def ends_as(units: *u16, length: u64, ending: strview): bool { + if length < ending.length { + return false; + } + for i in 0..ending.length { + var unit := units[length - ending.length + i]; + if unit >= 'A' as u16 && unit <= 'Z' as u16 { + unit = unit + 32; + } + if unit != ending[i] as u16 { + return false; + } + } + return true; +} + +# A time of the system, in nanoseconds since 1970. +def nanoseconds_of(time: &filetime): i64 { + val ticks := (((time.high as u64) << 32) | time.low as u64) as i64; + return (ticks - 116444736000000000) * 100; +} + +# The attributes a file is given for permissions, which set only whether it is +# read only: it is where the owner may not write. +def attributes_with(attributes: u32, mode: u32): u32 { + val made: u32 = (mode & 0o200) == 0 ? attributes | readonly : attributes & ~readonly; + return made == 0 ? normal : made; +} + +#! Sets the permissions of the file at a path, of which only whether the owner +#! may write is kept: without it, the file is read only. +#! @param path The path of the file. +#! @param mode The permissions to give it. +#! @returns Zero when they were set. +pub def chmod(path: strview, mode: u32): i32 { + var name: wide_text; + val bad := wide_path(path, &mut name); + if bad < 0 { + return bad as i32; + } + + val units := name.units as *u16; + val attributes := GetFileAttributesW(units); + if attributes == invalid_attributes || SetFileAttributesW(units, attributes_with(attributes, mode)) == 0 { + return failed() as i32; + } + return 0; +} + +#! Makes a directory. +#! @param path The path of the directory, whose parent must exist. +#! @param mode The permissions to give it, which Windows has no use for. +#! @returns Zero when it was made. +pub def mkdir(path: strview, mode: u32): i32 { + return on_path(path, def(name: *u16): i32 => CreateDirectoryW(name, null)); +} + +#! Removes an empty directory. +#! @param path The path of the directory. +#! @returns Zero when it was removed. One that holds anything gives -39, as on +#! Linux, though Windows refuses first to remove a directory a program +#! has open, as a program has the one it works in. +pub def rmdir(path: strview): i32 { + val result := on_path(path, def(name: *u16): i32 => RemoveDirectoryW(name)); + if result == -16 && holds_names(path) { + return -39; + } + return result; +} + +# Whether a directory holds anything besides `.` and `..`. +def holds_names(path: strview): bool { + var stream: dir_stream; + if opendir(path, &mut stream) != 0 { + return false; + } + var entry: dir_entry; + return stream.next(&mut entry) == 1; +} + +#! Removes a file, or a link without what it leads to, but not a directory. A +#! file that is read only is removed too, as POSIX removes one. +#! @param path The path of the file. +#! @returns Zero when it was removed. +pub def unlink(path: strview): i32 { + var name: wide_text; + val bad := wide_path(path, &mut name); + if bad < 0 { + return bad as i32; + } + + val units := name.units as *u16; + if DeleteFileW(units) != 0 { + return 0; + } + val why := GetLastError(); + val attributes := GetFileAttributesW(units); + if why != error_access_denied || attributes == invalid_attributes { + return errno_of(why) as i32; + } + + # A link to a directory is removed as a directory is, which removes the link. + if (attributes & directory) != 0 { + if (attributes & reparse_point) == 0 { + return -21; + } + return RemoveDirectoryW(units) != 0 ? 0 : failed() as i32; + } + if (attributes & readonly) == 0 || SetFileAttributesW(units, attributes_with(attributes, 0o200)) == 0 { + return errno_of(why) as i32; + } + if DeleteFileW(units) != 0 { + return 0; + } + val again := failed(); + SetFileAttributesW(units, attributes); + return again as i32; +} + +#! Moves a file or directory to another path, replacing a file there. +#! @param from The path of what to move. +#! @param to Where to move it, on the same volume. +#! @returns Zero when it was moved. +pub def rename(from: strview, to: strview): i32 { + var target: wide_text; + val bad := wide_path(to, &mut target); + if bad < 0 { + return bad as i32; + } + val at := target.units as *u16; + return on_path(from, def(name: *u16): i32 => MoveFileExW(name, at, 1)); +} + +#! Writes the path of the working directory, which is absolute, without a zero. +#! @param into Where the path is written. +#! @param length How many bytes there is room for, `path_limit` being enough +#! for any the system keeps but those holding many characters +#! beyond ASCII. +#! @returns The number of bytes written, or -34 where they do not fit. +pub def getcwd(into: *mut u8, length: u64): i64 { + while true { + val needed := GetCurrentDirectoryW(0, null); + if needed == 0 { + return failed(); + } + + val units := raw_allocate(needed as u64 * 2) as *mut u16; + val count := GetCurrentDirectoryW(needed, units); + val why := count == 0 ? failed() : 0; + # It may have changed, and grown, between the two calls. + if count == 0 || count < needed { + val written := count == 0 ? why : narrow(units as *u16, count as u64, into, length); + raw_release(units as *mut u8); + return written; + } + raw_release(units as *mut u8); + } + return 0; +} + +#! Sets the working directory, which relative paths are taken from. +#! @param path The path of the directory. +#! @returns Zero when it was set. +pub def chdir(path: strview): i32 { + var name: wide_text; + val bad := widen(path, &mut name); + if bad < 0 { + return bad as i32; + } + return SetCurrentDirectoryW(name.units as *u16) == 0 ? failed() as i32 : 0; +} + +#! Reads from the file into a buffer, waiting until something arrives. A +#! console is read as the characters typed, which are given as UTF-8, and a line +#! beginning with Ctrl-Z ends what it gives, as a pipe ends once nothing more +#! can be written to it. +#! @param this The handle of the file to read. +#! @param into Where the bytes read are written. +#! @param length How many bytes there is room for. +#! @returns The number of bytes read, which is zero at the end of the file, or +#! a negative error number, which is `-4` where a signal the program +#! handles ended the wait. +pub def fd::read(&this, into: *mut u8, length: u64): i64 { + val handle := handle_of(this); + if is_console(handle) { + return console_read(handle, into, length); + } + + val asked: u32 = length > 0x7FFFFFFF ? 0x7FFFFFFF : length as u32; + while true { + var read: u32 = 0; + if ReadFile(handle, into, asked, &mut read, null) != 0 { + return read as i64; + } + + # A pipe ends once every handle that writes it is closed. A read the system + # gave up on for a signal ends where a handler ran, and is made again where + # none did. + val why := GetLastError(); + if why == error_broken_pipe || why == error_handle_eof { + return 0; + } + if why == error_invalid_function && is_directory_handle(handle) { + return -21; + } + if why != error_operation_aborted || run_handlers() { + return errno_of(why); + } + } + return 0; +} + +# Whether a handle is of a console, which is asked again where a signal ended +# the asking, as a signal ends any call to the console. +def is_console(handle: u64): bool { + var mode: u32 = 0; + while GetConsoleMode(handle, &mut mode) == 0 { + if GetLastError() != error_operation_aborted { + return false; + } + } + return true; +} + +# Whether an open file is a directory. +def is_directory_handle(handle: u64): bool { + var info: file_information; + return GetFileInformationByHandle(handle, &mut info) != 0 && (info.attributes & directory) != 0; +} + +#! Writes bytes to the file. A console is written the characters the bytes are +#! as UTF-8, whichever code page it shows, and a character cut short at the end +#! is held until the write that finishes it, being counted as written. +#! +#! Writing to a pipe nothing reads fails with -32, which is `broken_pipe`. +#! Writing to the program's own output or error that way stops the program, +#! quietly, as it does on Linux, unless the program handles, watches for, or +#! ignores `signal::pipe`, which it is then sent instead. +#! @param this The handle of the file to write. +#! @param from Where the bytes to write begin. +#! @param length How many bytes to write. +#! @returns The number of bytes written, which may be fewer than asked. +pub def fd::write(&this, from: *u8, length: u64): i64 { + val handle := handle_of(this); + var result: i64 = 0; + if is_console(handle) { + result = console_write(handle, from, length); + } else { + # A write the system gave up on for a signal, as it gives up the program's + # waits for one, is made again, as on Linux, unless part of it was written. + val asked: u32 = length > 0x7FFFFFFF ? 0x7FFFFFFF : length as u32; + while true { + var written: u32 = 0; + if WriteFile(handle, from, asked, &mut written, null) != 0 { + result = written as i64; + break; + } + val why := GetLastError(); + if why != error_operation_aborted || written > 0 { + result = written > 0 ? written as i64 : errno_of(why); + break; + } + } + } + + val number := this as i64; + val bit := 1u << (number_of(signal::pipe) as u64); + if result == -32 && (((handled | noting) & bit) != 0 || number == 1 || number == 2) { + _ = raise(signal::pipe); + } + return result; +} + +#! Writes text to the file. +#! @param this The handle of the file to write. +#! @param text The text to write, which may be a literal, a view of one, or +#! the text a `string` lends. +#! @returns The number of bytes written, which may be fewer than asked. +pub def fd::put(&this, text: strview): i64 { + return this.write(text.data, text.length); +} + +#! Moves the position in the file that reads and writes happen at. +#! @param this The handle of the file to seek. +#! @param offset The offset to move to. +#! @param from Where the offset is measured from. +#! @returns The new position from the start of the file, or -29 for a pipe, a +#! console, or a device, which have none. +pub def fd::seek(&this, offset: i64, from: whence): i64 { + if from < 0 || from > 2 { + return -22; + } + + val handle := handle_of(this); + SetLastError(0); + val kind := GetFileType(handle); + if kind != disk_type { + return kind == 0 && GetLastError() != 0 ? failed() : -29; + } + var position: i64 = 0; + if SetFilePointerEx(handle, offset, &mut position, from as u32) == 0 { + return failed(); + } + return position; +} + +#! Closes the file. Closing a standard stream leaves the program without it, so +#! that using its handle fails with -9, which is `invalid`. +#! @param this The handle of the file to close. +#! @returns Zero when the file was closed. +pub def fd::close(&this): i32 { + if CloseHandle(handle_of(this)) == 0 { + return failed() as i32; + } + val number := this as i64; + if number >= 0 && number <= 2 { + SetStdHandle(0xFFFFFFF6 - number as u32, 0); + } + return 0; +} + +#! Describes the file. +#! @param this The handle of the file to describe. +#! @param out The description to fill. +#! @returns Zero when the file was described. +pub def fd::stat(&this, out: &mut file_info): i32 { + val handle := handle_of(this); + var path: u16[1024]; + val units := (&mut path) as *mut u16; + val length := GetFinalPathNameByHandleW(handle, units, 1024, 0); + return described(handle, false, length == 0 || length >= 1024 ? null : units as *u16, out); +} + +#! Sets the permissions of the file, of which only whether the owner may write +#! is kept: without it, the file is read only. +#! @param this The handle of the file. +#! @param mode The permissions to give it. +#! @returns Zero when they were set. +pub def fd::chmod(&this, mode: u32): i32 { + val handle := handle_of(this); + var basic: basic_information; + if GetFileInformationByHandleEx(handle, 0, (&mut basic) as *mut u8, basic_bytes as u32) == 0 { + return failed() as i32; + } + + # Times left zero are left as they are. + var changed := basic_information { attributes = attributes_with(basic.attributes, mode) }; + val at := (&mut changed) as *mut u8; + if SetFileInformationByHandle(handle, 0, at, basic_bytes as u32) != 0 { + return 0; + } + val why := GetLastError(); + if why != error_access_denied { + return errno_of(why) as i32; + } + + # A handle that may not change what is written of the file is opened again + # with one that may. + val writing := ReOpenFile(handle, write_attributes, share_all, backup_semantics); + if writing == invalid_handle { + return failed() as i32; + } + val result := SetFileInformationByHandle(writing, 0, at, basic_bytes as u32) == 0 ? failed() as i32 : 0; + CloseHandle(writing); + return result; +} + +#! A directory being read, one name at a time, which `opendir` starts and +#! `close` ends. +pub struct dir_stream : owning { + var _find: u64; #! The search of the system, which is zero where it found nothing. + var _data: *mut u8; #! What the search last found, then its name as UTF-8, which is null where not open. + var _pending: bool; #! Whether what the search last found is yet to be read. +} + +#! Starts reading the names a directory holds. +#! @param path The path of the directory. +#! @param into The stream to read them with, which `close` ends. +#! @returns Zero when the directory was opened. +pub def opendir(path: strview, into: &mut dir_stream): i32 { + var pattern := string::from(path, nothing{}); + val last := path.length == 0 ? '\\' : path[path.length - 1]; + pattern.append(last == '\\' || last == '/' || last == ':' ? "*" : "\\*"); + var name: wide_text; + val bad := wide_path(pattern.view(), &mut name); + if bad < 0 { + return bad as i32; + } + + val data := raw_allocate(find_bytes + name_bytes); + val find := FindFirstFileExW(name.units as *u16, 1, data, 0, null, 2); + if find == invalid_handle { + # A directory holding nothing, not even `.`, as the root of an empty drive + # does, is found holding nothing; a file is found missing, as is all past it. + val why := GetLastError(); + var plain: wide_text; + val known := wide_path(path, &mut plain) == 0; + val attributes := known ? GetFileAttributesW(plain.units as *u16) : invalid_attributes; + val found := attributes != invalid_attributes; + if !found || (attributes & directory) == 0 || why != error_file_not_found { + raw_release(data); + return found && (attributes & directory) == 0 ? -20 : errno_of(why) as i32; + } + into._find = 0; + into._data = data; + into._pending = false; + return 0; + } + + into._find = find; + into._data = data; + into._pending = true; + return 0; +} + +#! Reads the next name the directory holds, in no particular order, leaving out +#! `.` and `..`. +#! @param this The stream to read. +#! @param out The entry to fill, whose name views the stream's own memory. +#! @returns One when an entry was read, and zero once there are no more. +pub def dir_stream::next(&mut this, out: &mut dir_entry): i32 { + if this._data == null { + return -9; + } + + while true { + if this._find == 0 { + return 0; + } + if !this._pending && FindNextFileW(this._find, this._data) == 0 { + val why := GetLastError(); + return why == error_no_more_files ? 0 : errno_of(why) as i32; + } + this._pending = false; + + # A name is up to 260 units 44 bytes in, ending in a zero. + val units := (this._data + 44) as *u16; + var length := 0u; + while length < 260 && units[length] != 0 { + length++; + } + if units[0] == '.' as u16 && (length == 1 || (length == 2 && units[1] == '.' as u16)) { + continue; + } + + val text := this._data + find_bytes; + val bytes := narrow(units, length, text, name_bytes); + if bytes < 0 { + return bytes as i32; + } + + # What a reparse point is, a link or another kind, is 36 bytes in. + val attributes := *(this._data as *mut u32); + val tag := *((this._data + 36) as *mut u32); + out.name = strview::over(text as *u8, bytes as u64); + out.kind = (attributes & reparse_point) != 0 && (tag == symlink_tag || tag == junction_tag) ? file_kind::link + : (attributes & directory) != 0 ? file_kind::directory + : (attributes & device) != 0 ? file_kind::other + : file_kind::regular; + return 1; + } + return 0; +} + +#! Stops reading the directory. Closing a stream that is not open does nothing. +#! @param this The stream to close. +pub def dir_stream::close(&mut this): void { + if this._data == null { + return; + } + + if this._find != 0 { + FindClose(this._find); + } + raw_release(this._data); + this._data = null; +} + +#! Would start a copy of the program going on from here, which Windows cannot +#! do: `respawn` starts one from the start instead. +#! @returns -38, which is `unsupported`. +pub def fork(): i64 { + return -38; +} + +#! Starts a copy of the program from its start, as it was started: the same +#! program, given the same command line, with the variables the program started +#! with, and one more, which it can tell it is the copy by. It stands in for +#! `fork`, which Windows lacks, as `std::testing` uses it. +#! @param variable The variable added, as `NAME=value`, in place of any of +#! the name the program has. +#! @param input The handle the copy's standard input is given. +#! @param output The handle its standard output is given. +#! @param error The handle its standard error is given. +#! @returns The number the system knows the copy by, which `wait` and `kill` +#! take, or a negative error number. +pub def respawn(variable: strview, input: fd, output: fd, error: fd): i64 { + var program := wide_text { block = raw_allocate(path_limit * 2) as *mut u16 }; + program.units = program.block; + val length := GetModuleFileNameW(0, program.units, path_limit as u32); + if length == 0 || length as u64 >= path_limit { + return length == 0 ? failed() : -36; + } + + # The command line is given again as it is, so nothing in it is quoted anew. + val line := GetCommandLineW(); + val count := length_of(line); + var command := wide_text { block = raw_allocate((count + 1) * 2) as *mut u16 }; + command.units = command.block; + for i in 0..count + 1 { + command.units[i] = line[i]; + } + + var name_length := 0u; + while name_length < variable.length && variable[name_length] != '=' { + name_length++; + } + var entries := vector::::new(); + for each in environment() { + if !(each.length > name_length && each[name_length] == '=' && same_name(each, variable, name_length)) { + entries.append(each); + } + } + entries.append(variable); + + var block: wide_text; + val bad := block_of(&mut entries, &mut block); + if bad < 0 { + return bad; + } + return started(program.units as *u16, command.units, block.units, null, input, output, error); +} + +# Whether two variables have the same name of a length, which Windows compares +# without regard to case. +def same_name(a: strview, b: strview, length: u64): bool { + for i in 0..length { + if upper(a[i]) != upper(b[i]) { + return false; + } + } + return true; +} + +def upper(byte: u8): u8 { + return byte >= 'a' && byte <= 'z' ? byte - 32 : byte; +} + +# A program `spawn` started, until `wait` finds it stopped: its number, the +# handle the system gave of it, and the signal `kill` stopped it with, or zero. +struct child_entry { + var id: i64; + var handle: u64; + var killed: i32; +} + +# The programs `spawn` started that are yet to be waited for, which a word +# guards, as `std::io` guards the console, since any thread may start one or +# wait for one: 0 where no thread holds it, 1 where one does, and 2 where others +# may wait. +var children: *mut child_entry; +var child_count: u64; +var child_room: u64; +var children_held: atomic; + +def hold_children(): void { + if children_held.exchange(1) != 0 { + while children_held.exchange(2) != 0 { + _ = futex_wait(((&mut children_held) as *mut atomic) as *mut u32, 2, -1); + } + } +} + +def let_go_of_children(): void { + if children_held.exchange(0) == 2 { + _ = futex_wake(((&mut children_held) as *mut atomic) as *mut u32, 1); + } +} + +# Keeps a program started, until it is waited for. +def remember(id: i64, handle: u64): void { + hold_children(); + if child_count == child_room { + child_room = child_room == 0 ? 8 : child_room * 2; + val bytes := child_room * size_of::(); + val grown := children == null ? raw_allocate(bytes) : raw_resize(children as *mut u8, bytes); + children = grown as *mut child_entry; + } + children[child_count] = child_entry { id = id, handle = handle, killed = 0 }; + child_count++; + let_go_of_children(); +} + +#! Waits for a program that `spawn`, or a copy of the program that `respawn`, +#! started to stop. +#! @param child The number the system knows it by, or -1 for whichever of +#! them stops first. +#! @param status How it stopped: exited with its code, or, where `kill` +#! stopped it, by that signal, and where the console's Ctrl-C +#! did, by `interrupt`. +#! @returns The number of the program that stopped, or a negative error number, +#! which is `-10` where there is none to wait for, and `-4` where a +#! signal the program handles ended the wait. +pub def wait(child: i64, status: &mut process_status): i64 { + while true { + # Those waited on, at most 63, then the event of signals. + var handles: u64[64]; + var ids: i64[63]; + var count := 0u; + hold_children(); + for i in 0..child_count { + if (child == -1 || children[i].id == child) && count < 63 { + handles[count] = children[i].handle; + ids[count] = children[i].id; + count++; + } + } + let_go_of_children(); + if count == 0 { + return -10; + } + + val event := interrupting(); + val waited := event == 0 ? count : count + 1; + handles[count] = event; + val woke := WaitForMultipleObjects(waited as u32, (&handles) as *u64, 0, milliseconds_of(wait_slice)); + if woke == wait_failed { + return failed(); + } + # Another thread may have waited for the same program first, and forgotten + # it, which leaves those still running to wait for. + if (woke as u64) < count { + val id := reaped(ids[woke as u64], status); + if id != -10 { + return id; + } + continue; + } + if run_handlers() { + return -4; + } + } + return 0; +} + +# How a program of a number that stopped did, which forgets it, giving the +# number, or -10 where no program of the number has stopped and is yet to be +# waited for. +def reaped(id: i64, status: &mut process_status): i64 { + hold_children(); + var index := child_count; + for i in 0..child_count { + if children[i].id == id { + index = i; + break; + } + } + if index == child_count || WaitForSingleObject(children[index].handle, 0) != 0 { + let_go_of_children(); + return -10; + } + val handle := children[index].handle; + val killed := children[index].killed; + children[index] = children[child_count - 1]; + child_count--; + let_go_of_children(); + + var code: u32 = 0; + _ = GetExitCodeProcess(handle, &mut code); + CloseHandle(handle); + status.exited = killed == 0 && code != control_c_exit; + status.code = status.exited ? code as i32 : 0; + status.signal = killed != 0 ? killed : status.exited ? 0 : number_of(signal::interrupt); + return id; +} + +#! Sends a signal to a process, which Windows can do only to stop one: `kill` +#! and `terminate` stop it at once, as `TerminateProcess` does, with 128 more +#! than the signal's number as its status. Any signal may be sent to the +#! program itself, as `raise` sends it. +#! @param process The number the system knows the process by, as `getpid` +#! gives the program its own, and `spawn` the program a child's. +#! @param sent The signal to send. +#! @returns Zero when it was sent, and -95, which is `unsupported`, for another +#! signal to another process. +pub def kill(process: i64, sent: signal): i32 { + if process == getpid() { + return raise(sent); + } + if sent != signal::kill && sent != signal::terminate { + return -95; + } + + val code := (128 + number_of(sent)) as u32; + hold_children(); + for i in 0..child_count { + if children[i].id != process { + continue; + } + # One that has stopped already, or is stopping, which the system will not + # stop again, but which is not yet waited for, is stopped. + val handle := children[i].handle; + var result: i32 = 0; + if TerminateProcess(handle, code) != 0 { + children[i].killed = number_of(sent); + } else { + val why := GetLastError(); + result = WaitForSingleObject(handle, 1000) == 0 ? 0 : errno_of(why) as i32; + } + let_go_of_children(); + return result; + } + let_go_of_children(); + + val handle := OpenProcess(process_terminate, 0, process as u32); + if handle == 0 { + val why := GetLastError(); + return why == error_invalid_parameter ? -3 : errno_of(why) as i32; + } + val done := TerminateProcess(handle, code); + val why := done == 0 ? GetLastError() : 0; + CloseHandle(handle); + return done == 0 ? errno_of(why) as i32 : 0; +} + +#! Sends a signal to the program itself. A signal the program handles or +#! watches for is noted before this returns, and its handler runs at the next +#! safe point. One it ignores does nothing. Any other does what Linux does by +#! default: `child`, `resume`, and `resized` nothing, `stop` and `suspend` +#! nothing Windows can do, which gives -95, and the rest stop the program at +#! once, `interrupt` with the status the console's Ctrl-C gives, and the others +#! with 128 more than the signal's number. +#! @param sent The signal to send. +#! @returns Zero when it was sent. +pub def raise(sent: signal): i32 { + val number := number_of(sent); + val bit := 1u << (number as u64); + if ((handled | noting) & bit) != 0 { + return catch_signal(number | (3 << 8)); + } + if (ignored & bit) != 0 { + return 0; + } + + if sent == signal::child || sent == signal::resume || sent == signal::resized { + return 0; + } + if sent == signal::stop || sent == signal::suspend { + return -95; + } + val code: u32 = sent == signal::interrupt ? control_c_exit : (128 + number) as u32; + TerminateProcess(GetCurrentProcess(), code); + return 0; +} + +#! The number the system knows the program by. +#! @returns The number, which `kill` takes. +pub def getpid(): i64 { + return GetCurrentProcessId() as i64; +} + +#! Has the system throw a signal away when it comes, until `handle` or +#! `restore` says otherwise. +#! @param which The signal to ignore. +#! @returns Zero when it is ignored. `kill` and `stop` cannot be, and neither +#! can `child`, as on Linux: each gives -22, which is `invalid`. +pub def ignore(which: signal): i32 { + if which == signal::kill || which == signal::stop || which == signal::child { + return -22; + } + return disposed(which, 1); +} + +#! Has the system do what it does with a signal by default, as it did before the +#! program said otherwise: for those the console sends, stopping the program. +#! @param which The signal to restore. +#! @returns Zero when it is restored. `kill` and `stop` have nothing to restore, +#! and give -22, which is `invalid`. +pub def restore(which: signal): i32 { + if which == signal::kill || which == signal::stop { + return -22; + } + return disposed(which, 2); +} + +#! Handles a signal with a function, until `handle`, `ignore`, or `restore` says +#! otherwise. The function runs at the program's next safe point once the +#! signal comes, and before a wait the signal interrupts ends. A signal that +#! comes again before its handler runs is handled once, and one that comes while +#! a handler runs is handled once that handler returns. +#! @tparam F The handler's type: a function, a lambda, or a functor. +#! @param which The signal to handle. +#! @param by What handles it, which the program then keeps until another +#! handles the signal: a functor holding what it needs, or a +#! closure sharing the locals where it was made, as one setting a +#! flag the program's loop reads, while those locals last. +#! @returns Zero when it is handled. `kill` and `stop` cannot be, and give -22, +#! which is `invalid`. +pub def handle(which: signal, by: F): i32 where F: invokable { + if which == signal::kill || which == signal::stop { + return -22; + } + + # The handler is in place before the signal can come. + val bit := 1u << (number_of(which) as u64); + handlers[which as u64] = handler::new(move(&mut by)); + handled = handled | bit; + val result := catch_signal(number_of(which)); + if result < 0 { + handled = handled & ~bit; + return result; + } + + noting = noting & ~bit; + ignored = ignored & ~bit; + return result; +} + +#! Has the system note a signal when it comes, for `watched` to give, until +#! `handle`, `ignore`, or `restore` says otherwise. No handler runs, so a +#! program that only watches for signals has no safe points, and asks itself +#! whether one came, as a machine running a program does for that program. A +#! wait the signal interrupts goes on. +#! @param which The signal to watch for. +#! @returns Zero when it is watched for. `kill` and `stop` cannot be, and give +#! -22, which is `invalid`. +pub def watch(which: signal): i32 { + if which == signal::kill || which == signal::stop { + return -22; + } + + val bit := 1u << (number_of(which) as u64); + val result := catch_signal(number_of(which)); + if result < 0 { + return result; + } + + handled = handled & ~bit; + noting = noting | bit; + ignored = ignored & ~bit; + return result; +} + +#! The signals `watch` watches for that came since this last asked, which it +#! forgets. +#! @returns One bit each, by the system's number. +pub def watched(): u64 { + arrived = arrived | take_signals(); + val came := arrived & noting; + arrived = arrived & ~noting; + return came; +} + +#! Waits until a handler has run. A signal that came before the wait began is +#! not missed: its handler runs, and the wait ends at once. Within a handler, +#! where no other runs, it waits until a signal the program handles comes, whose +#! handler runs once the one running returns. In any thread but the one the +#! program began with, where no handler runs, it waits for good. +pub def pause(): void { + if !is_first_thread() { + while true { + Sleep(milliseconds_of(wait_slice)); + } + } + + # The event is set whenever a signal is noted, and only cleared as the + # signals are taken, so none comes between finding none and the wait. + val event := signal_event(); + while !run_handlers() { + if event == 0 { + Sleep(10); + } else { + WaitForSingleObject(event, infinite); + } + if dispatching { + break; + } + } +} + +# The signals the program ignores, one bit each by number. +var ignored: u64; + +# Has the system do with a signal what `catch_signal` does for an action: 1 to +# throw it away, and 2 what the system does by default. Gives zero, or a +# negative number. +def disposed(which: signal, action: i32): i32 { + val result := catch_signal(number_of(which) | (action << 8)); + if result != 0 { + return result; + } + + val bit := 1u << (number_of(which) as u64); + handled = handled & ~bit; + noting = noting & ~bit; + ignored = action == 1 ? ignored | bit : ignored & ~bit; + return result; +} + +# The thread the program began with, which runs the handlers, as it sets the +# program's globals before `main`. +var first_thread: u32 = GetCurrentThreadId(); + +# Whether the calling thread is the one the program began with. +def is_first_thread(): bool { + return GetCurrentThreadId() == first_thread; +} + +# The event the system sets whenever it notes a signal, and clears as +# `take_signals` takes them, once `catch_signal` has given it, or zero. +var signal_event_handle: u64; + +#! The event the system sets whenever it notes a signal, and resets as signals +#! are taken, which a wait waits on as well so that a signal the program handles +#! ends it. It is a manual-reset event made the first time it is asked for, and +#! kept while the program runs, or zero where the system gives none. A machine +#! running a program gives it the same event, so the program's waits end on a +#! signal as they do in an executable. +#! @returns The event's handle, or zero. +pub def signal_event(): u64 { + if signal_event_handle == 0 { + val given := catch_signal(number_of(signal::interrupt) | (4 << 8)); + signal_event_handle = given > 0 ? given as u64 : 0; + } + return signal_event_handle; +} + +# The event a wait waits on too, so that a signal the program handles ends it, +# or zero where no handler would run: where the program handles none, where a +# handler runs, or in a thread other than the one the program began with. +def interrupting(): u64 { + if handled == 0 || dispatching || !is_first_thread() { + return 0; + } + return signal_event(); +} + +# How many of the steady clock's ticks make a second, once asked for. +var ticks_per_second: i64; + +#! Reads a clock. +#! @param which The clock: the wall clock, or the steady one. +#! @returns Nanoseconds: since 1970 began in UTC of the wall clock, which the +#! system may set forward or back, and since a start that never moves +#! of the steady one, which only ever grows. +pub def clock(which: clock_kind): i64 { + if which == clock_kind::wall { + var now: filetime; + GetSystemTimePreciseAsFileTime(&mut now); + return nanoseconds_of(&now); + } + + if ticks_per_second == 0 { + var frequency: i64 = 0; + QueryPerformanceFrequency(&mut frequency); + ticks_per_second = frequency; + } + var count: i64 = 0; + QueryPerformanceCounter(&mut count); + return (count / ticks_per_second) * 1000000000 + (count % ticks_per_second) * 1000000000 / ticks_per_second; +} + +# The steady clock's reading a length of time from now, or the furthest it reads. +def deadline(nanoseconds: i64): i64 { + val now := clock(clock_kind::steady); + val most: i64 = 0x7FFFFFFFFFFFFFFF; + return nanoseconds > most - now ? most : now + nanoseconds; +} + +# Milliseconds a length of time in nanoseconds takes, rounded up, and short of +# waiting for good. +def milliseconds_of(nanoseconds: i64): u32 { + val whole := nanoseconds / 1000000 + (nanoseconds % 1000000 != 0 ? 1 : 0); + return whole >= 0xFFFFFFFE ? 0xFFFFFFFE : whole as u32; +} + +# The longest a wait of the system lasts before it is begun again, so that a +# thread waiting sees soon that another stopped the program, which ends few of +# the waits of the system. +const wait_slice: i64 = 100000000; + +#! Waits for a length of time, to well within a millisecond where the system +#! has timers that fine, as Windows 10 has since its 1803 update. +#! @param nanoseconds How long to wait, which is no time at all where it is +#! not above zero. +#! @returns Zero once the time has passed, or a negative error number, which is +#! -4 where a signal the program handles ended the wait, once its +#! handlers ran. A signal no handler ran for does not end the wait. +pub def sleep(nanoseconds: i64): i32 { + if nanoseconds <= 0 { + return 0; + } + + val until := deadline(nanoseconds); + val timer := CreateWaitableTimerExW(null, null, 2, 0x1F0003); + var result: i32 = 0; + while true { + val left := until - clock(clock_kind::steady); + if left <= 0 { + break; + } + + # The timer is set in tenths of microseconds from now, as a negative number. + val event := interrupting(); + val slice := left < wait_slice ? left : wait_slice; + var woke: u32 = 0; + if timer != 0 { + var handles: u64[2]; + handles[0] = timer; + handles[1] = event; + val due: i64 = -((slice + 99) / 100); + SetWaitableTimer(timer, &due, 0, null, null, 0); + woke = WaitForMultipleObjects(event == 0 ? 1 : 2, (&handles) as *u64, 0, infinite); + } else if event == 0 { + Sleep(milliseconds_of(slice)); + } else { + woke = WaitForSingleObject(event, milliseconds_of(slice)) == 0 ? 1 : 0; + } + if woke == 1 && run_handlers() { + result = -4; + break; + } + } + if timer != 0 { + CloseHandle(timer); + } + return result; +} + +# The longest a wait on a word lasts before the word is looked at again. +const futex_slice: i64 = 100000000; + +#! Waits while a word holds what is expected, until another thread wakes those +#! waiting on it, which every way of waiting for one another is built on. The +#! word is read and the wait begun in one step, so a wake after the word changes +#! is never missed. Only threads of one program wait on one another this way on +#! Windows, not processes sharing memory. +#! @param at The word. +#! @param expected What the word holds to be waited on. +#! @param timeout Nanoseconds to wait at most, or for ever where it is +#! negative. +#! @returns Zero where it was woken, which may be for no reason, or a negative +#! error number: -11 where the word held something else, and -110 +#! where the time ran out. +pub def futex_wait(at: *mut u32, expected: u32, timeout: i64): i32 { + if *at != expected { + return -11; + } + + # The wait is made of short ones, each of which looks at the word again. + val until := timeout < 0 ? 0 : deadline(timeout); + while true { + var slice := futex_slice; + if timeout >= 0 { + val left := until - clock(clock_kind::steady); + if left <= 0 { + return -110; + } + slice = left < slice ? left : slice; + } + if WaitOnAddress(at, &expected, 4, milliseconds_of(slice)) != 0 { + return 0; + } + val why := GetLastError(); + if why != error_timeout { + return errno_of(why) as i32; + } + } + return 0; +} + +#! Wakes threads waiting on a word. +#! @param at The word. +#! @param count How many to wake at most, of which Windows tells one from many. +#! @returns Zero, since the system does not say how many it woke. +pub def futex_wake(at: *mut u32, count: u32): i32 { + if count == 1 { + WakeByAddressSingle(at); + } else if count > 1 { + WakeByAddressAll(at); + } + return 0; +} + +#! How many processors the program may run on, which is how many of its threads +#! run at once. +#! @returns How many, at least one. +pub def cpu_count(): u32 { + val all := GetActiveProcessorCount(0xFFFF); + var mask: u64 = 0; + var system: u64 = 0; + if all <= 64 && GetProcessAffinityMask(GetCurrentProcess(), &mut mask, &mut system) != 0 && mask != 0 { + var count: u32 = 0; + while mask != 0 { + mask = mask & (mask - 1); + count++; + } + return count; + } + return all == 0 ? 1 : all; +} + +#! The number the system knows the calling thread by. +#! @returns The number. +pub def thread_id(): u64 { + return GetCurrentThreadId() as u64; +} + +#! Lets the system run other threads before this one goes on. +pub def yield_now(): void { + SwitchToThread(); +} + +#! The path of the device that reads as empty, and throws away what is written +#! to it. +pub val null_device: strview = "NUL"; + +#! Makes a pipe: what is written to one end is read from the other. Neither end +#! is inherited by a program the program starts, unless `spawn` is asked to give +#! it one. Writing to a pipe nothing reads fails with -32, which is +#! `broken_pipe`, as Windows has no signal to stop the program with. +#! @param reading Where the handle of the end that is read is written. +#! @param writing Where the handle of the end that is written is written. +#! @returns Zero when the pipe was made. +pub def pipe(reading: &mut fd, writing: &mut fd): i32 { + var read_end: u64 = 0; + var write_end: u64 = 0; + if CreatePipe(&mut read_end, &mut write_end, null, 65536) == 0 { + return failed() as i32; + } + reading = (read_end as i64) as fd; + writing = (write_end as i64) as fd; + return 0; +} + +#! Starts a program, which runs beside this one until it stops, and which `wait` +#! waits for. +#! +#! The program is given the handles the request names as its standard streams, +#! and inherits no other. Its command line is its arguments, quoted as the C +#! runtime reads them back, so it is given each as it is. A batch file, whose +#! name ends in `.bat` or `.cmd`, is run by `cmd.exe`, which reads its arguments +#! in a way of its own: each is quoted where it needs to be, and one holding a +#! `"`, a `%`, or a new line, which `cmd.exe` cannot be given unchanged, is not +#! run. +#! @param request What to start, and with what, all of which is copied before +#! the program starts. +#! @returns The number the system knows the started program by, which `wait` +#! and `kill` take, or a negative error number: -2 where the program +#! is not found, -13 where it may not be run, as it may not where it is +#! no program, and -22 where a text the request holds has a zero in it, +#! or a batch file is given an argument it cannot be. +pub def spawn(request: &spawn_request): i64 { + # A program named from where the child runs is found from there. + var program := string::new(nothing{}); + if request.directory.length != 0 && !is_rooted(request.program) { + program.append(request.directory); + val last := request.directory[request.directory.length - 1]; + if last != '\\' && last != '/' { + program.push('\\'); + } + } + for i in 0..request.program.length { + val byte := request.program[i]; + program.push(byte == '/' ? '\\' : byte); + } + # cmd.exe takes a batch file's path from where the child runs, so it is given + # the whole of it. + made_whole(&mut program); + + var application := string::new(nothing{}); + var line := string::new(nothing{}); + if is_batch(program.view()) { + var system: u16[260]; + val length := GetSystemDirectoryW((&mut system) as *mut u16, 260); + var bytes: u8[1024]; + val written := length == 0 || length >= 260 + ? -1 + : narrow((&system) as *u16, length as u64, (&mut bytes) as *mut u8, 1024); + if written < 0 { + return length == 0 ? failed() : -36; + } + application.append(strview::over((&bytes) as *u8, written as u64)); + application.append("\\cmd.exe"); + + # cmd.exe takes the quotes around the whole of what follows `/c` away, and + # runs the rest. + line.append("cmd.exe /d /e:ON /v:OFF /c \""); + if !quote_for_cmd(&mut line, program.view(), true) { + return -22; + } + for i in 1..request.arguments.length { + line.push(' '); + if !quote_for_cmd(&mut line, request.arguments[i], false) { + return -22; + } + } + line.push('"'); + } else { + application.append(program.view()); + val first := request.arguments.length == 0 ? request.program : request.arguments[0]; + if !quote_first(&mut line, first) { + return -22; + } + for i in 1..request.arguments.length { + line.push(' '); + quote(&mut line, request.arguments[i]); + } + } + + var path: wide_text; + var command: wide_text; + var block: wide_text; + var place: wide_text; + var entries := vector::::new(); + for each in request.environment { + entries.append(each); + } + val bad := widen(application.view(), &mut path) < 0 || widen(line.view(), &mut command) < 0 + || block_of(&mut entries, &mut block) < 0 + || (request.directory.length != 0 && wide_path(request.directory, &mut place) < 0); + if bad { + return -22; + } + if length_of(command.units as *u16) >= 32767 { + return -7; + } + + # A directory that is missing, or is no directory, is found so before the + # program is looked for. + if request.directory.length != 0 { + val attributes := GetFileAttributesW(place.units as *u16); + if attributes == invalid_attributes { + return failed(); + } + if (attributes & directory) == 0 { + return -20; + } + } + return started( + path.units as *u16, command.units, block.units, + request.directory.length == 0 ? null : place.units as *u16, + request.input, request.output, request.error + ); +} + +# Makes a path absolute, taking it from the working directory as the system +# does, where the system can. +def made_whole(path: &mut string): void { + var name: wide_text; + if widen(path.view(), &mut name) < 0 { + return; + } + val needed := GetFullPathNameW(name.units as *u16, 0, null, null); + if needed == 0 { + return; + } + + var whole := wide_text { block = raw_allocate(needed as u64 * 2) as *mut u16 }; + whole.units = whole.block; + val count := GetFullPathNameW(name.units as *u16, needed, whole.units, null); + if count == 0 || count >= needed { + return; + } + val room := count as u64 * 3; + val bytes := raw_allocate(room); + val written := narrow(whole.units as *u16, count as u64, bytes, room); + if written >= 0 { + path.clear(); + path.append(strview::over(bytes as *u8, written as u64)); + } + raw_release(bytes); +} + +# Whether a path names where it is from a root, a drive, or a share, rather +# than from the working directory. +def is_rooted(path: strview): bool { + return path.length > 0 && (path[0] == '\\' || path[0] == '/' || (path.length > 1 && path[1] == ':')); +} + +# Whether a program is a batch file, which `cmd.exe` runs. +def is_batch(program: strview): bool { + if program.length < 4 || program[program.length - 4] != '.' { + return false; + } + val ending := program.substr(program.length - 3, 3); + return same_name(ending, "bat", 3) || same_name(ending, "cmd", 3); +} + +# Writes what a program is called first on its command line, as the C runtime +# reads it back: up to the next space, or within quotes, where it holds one or +# is empty. A name holding a quote cannot be read back, and gives false. +def quote_first(into: &mut string, text: strview): bool { + var plain := text.length != 0; + for i in 0..text.length { + val byte := text[i]; + if byte == '"' { + return false; + } + if byte == ' ' || byte == '\t' { + plain = false; + } + } + if !plain { + into.push('"'); + } + into.append(text); + if !plain { + into.push('"'); + } + return true; +} + +# Writes an argument on a command line, as the C runtime reads it back: as it +# is, or within quotes where it holds a space, a tab, a new line, or a quote, or +# is empty, with a backslash before each quote it holds, and the backslashes +# before that, and before the closing quote, doubled. +def quote(into: &mut string, text: strview): void { + var plain := text.length != 0; + for i in 0..text.length { + val byte := text[i]; + if byte == ' ' || byte == '\t' || byte == '\n' || byte == 0x0B || byte == '"' { + plain = false; + } + } + if plain { + into.append(text); + return; + } + + into.push('"'); + var slashes := 0u; + for i in 0..text.length { + val byte := text[i]; + if byte == '"' { + for _ in 0..slashes + 1 { + into.push('\\'); + } + } + slashes = byte == '\\' ? slashes + 1 : 0; + into.push(byte); + } + for _ in 0..slashes { + into.push('\\'); + } + into.push('"'); +} + +# Writes a batch file's path, or an argument of it, as `cmd.exe` reads it: within +# quotes, where it takes everything as it is but a `%` or a `"`, unless it is +# plain, or the path. One holding either, or a new line, cannot be given +# unchanged, and gives false. Backslashes before the closing quote are doubled, +# so a program the batch file gives the argument to reads that quote as closing. +def quote_for_cmd(into: &mut string, text: strview, always: bool): bool { + var plain := text.length != 0 && !always; + for i in 0..text.length { + val byte := text[i]; + if byte == '"' || byte == '%' || byte == '\r' || byte == '\n' || byte == 0 { + return false; + } + val letter := (byte >= 'a' && byte <= 'z') || (byte >= 'A' && byte <= 'Z') || (byte >= '0' && byte <= '9'); + if !letter && byte < 0x80 && byte != '-' && byte != '_' && byte != '.' && byte != '\\' && byte != '/' && byte != ':' { + plain = false; + } + } + if plain { + into.append(text); + return true; + } + + into.push('"'); + into.append(text); + var at := text.length; + while at > 0 && text[at - 1] == '\\' { + into.push('\\'); + at--; + } + into.push('"'); + return true; +} + +# Writes variables as the system gives a program them: as UTF-16, each ending +# in a zero, in the order of their names without regard to case, and a zero +# after the last. Gives zero, or -22 where one holds a zero or is not UTF-8. +def block_of(entries: &mut vector, into: &mut wide_text): i64 { + val count := entries.length; + for i in 1..count { + var at := i; + while at > 0 && name_order(entries[at - 1], entries[at]) > 0 { + val swapped := strview::over(entries[at - 1].data, entries[at - 1].length); + entries.set(at - 1, entries[at]); + entries.set(at, swapped); + at--; + } + } + + var size := 2u; + for each in entries { + size += each.length + 1; + } + into.block = raw_allocate(size * 2) as *mut u16; + into.units = into.block; + var out := 0u; + for each in entries { + val written := utf16_of(each, into.units + out, true); + if written < 0 { + return written; + } + out += written as u64; + into.units[out] = 0; + out++; + } + into.units[out] = 0; + into.units[out + 1] = 0; + return 0; +} + +# How the names of two variables order, as Windows orders them: without regard +# to case. +def name_order(a: strview, b: strview): i64 { + var i := 0u; + while true { + val ended_a := i >= a.length || a[i] == '='; + val ended_b := i >= b.length || b[i] == '='; + if ended_a || ended_b { + return ended_a && ended_b ? 0 : ended_a ? -1 : 1; + } + val x := upper(a[i]); + val y := upper(b[i]); + if x != y { + return x < y ? -1 : 1; + } + i++; + } + return 0; +} + +# Starts a program from what the system takes: the path of the program, its +# command line, its variables as `block_of` writes them, and where it runs, or +# null for here, with the handles given as its standard streams, which are all +# it inherits. Gives its number, keeping it for `wait`, or the negated error +# number. +def started( + application: *u16, + command: *mut u16, + block: *mut u16, + directory: *u16, + input: fd, + output: fd, + error: fd +): i64 { + # Each stream is a copy of its handle the program may inherit, made only for + # it, and the program is told to inherit only those, so it inherits nothing + # another thread is starting a program with. + val ours := GetCurrentProcess(); + var streams: fd[3]; + streams[0] = input; + streams[1] = output; + streams[2] = error; + var given: u64[3]; + var copies: u64[3]; + var count := 0u; + for i in 0u..3u { + val source := handle_of(streams[i]); + var copy: u64 = 0; + if source != 0 && source != invalid_handle && DuplicateHandle(ours, source, ours, &mut copy, 0, 1, same_access) != 0 { + given[i] = copy; + copies[count] = copy; + count++; + } + } + + var info := startup_information { size = startup_bytes as u32, flags = use_std_handles }; + info.standard_input = given[0]; + info.standard_output = given[1]; + info.standard_error = given[2]; + var list: *mut u8 = null; + var why: u32 = 0; + if count > 0 { + var size: u64 = 0; + InitializeProcThreadAttributeList(null, 1, 0, &mut size); + list = raw_allocate(size); + if InitializeProcThreadAttributeList(list, 1, 0, &mut size) == 0 { + why = GetLastError(); + raw_release(list); + list = null; + } else if UpdateProcThreadAttribute(list, 0, handle_list, (&mut copies) as *mut u8, count * 8, null, null) == 0 { + why = GetLastError(); + } + info.attributes = list; + } + + var made: process_information; + if why == 0 { + val flags := unicode_block | extended_startup; + val inherit: i32 = count > 0 ? 1 : 0; + if CreateProcessW(application, command, null, null, inherit, flags, block, directory, &mut info, &mut made) == 0 { + why = GetLastError(); + } + } + + if list != null { + DeleteProcThreadAttributeList(list); + raw_release(list); + } + for i in 0..count { + CloseHandle(copies[i]); + } + if why != 0 { + return why == error_bad_exe_format ? -13 : errno_of(why); + } + + CloseHandle(made.thread); + remember(made.process_id as i64, made.process); + return made.process_id as i64; +} + +#! Waits until one of the handles can be read, or has ended, for at most a +#! while. A pipe is looked at again and again, a little longer apart each time it +#! holds nothing, up to a hundredth of a second, since Windows cannot wait on one; +#! anything else counts as ready. +#! @param handles The handles to wait on. One that is negative is passed over, +#! as one already read to its end may be. +#! @param ready Where whether each can be read, or has ended, is written, at +#! the index of its handle. +#! @param wait The most milliseconds to wait, or -1 to wait for as long as +#! it takes. +#! @returns How many can be, 0 where the wait ran out, or a negative error +#! number, which is -4 where a signal the program handles ended the +#! wait. +pub def poll(handles: span, ready: slice, wait: i64 = -1): i32 { + if ready.length < handles.length { + return -22; + } + + val until := wait < 0 ? 0 : deadline(wait * 1000000); + var resting: u32 = 0; + while true { + var count: i32 = 0; + for i in 0..handles.length { + ready[i] = false; + if handles[i] < 0 { + continue; + } + var available: u32 = 0; + if PeekNamedPipe(handle_of(handles[i]), null, 0, null, &mut available, null) == 0 || available > 0 { + ready[i] = true; + count++; + } + } + if count > 0 { + return count; + } + + # A wait with an end rests no longer than is left of it. + var rest := resting; + if wait >= 0 { + val left := until - clock(clock_kind::steady); + if left <= 0 { + return 0; + } + val most := milliseconds_of(left); + rest = most < rest ? most : rest; + } + val event := interrupting(); + if event == 0 { + Sleep(rest); + } else if WaitForSingleObject(event, rest) == 0 && run_handlers() { + return -4; + } + resting = resting < 10 ? resting + 1 : 10; + } + return 0; +} + +# Views of the variables the program started with, once `environment` has made +# them, which it keeps for as long as the program runs. +var variables: span; +var viewed: bool; + +#! The variables the program started with, each as `NAME=value`, including +#! those whose name begins with `=`, which keep the working directory of each +#! drive, and which a program it starts is given too. +#! @returns Views of each, which are good for as long as the program runs, since +#! nothing changes what they view. +pub def environment(): span { + if viewed { + return variables; + } + + # The system gives them as UTF-16, each ending in a zero, and a zero after. + val block := GetEnvironmentStringsW(); + var count := 0u; + var units := 0u; + while block != null && block[units] != 0 { + units += length_of((block + units) as *u16) + 1; + count++; + } + + val views := raw_allocate(count * size_of::()) as *mut strview; + val text := raw_allocate(units * 3 + 1); + var at := 0u; + var out := 0u; + for i in 0..count { + val length := length_of((block + at) as *u16); + val bytes := narrow((block + at) as *u16, length, text + out, units * 3 + 1 - out); + views[i] = strview::over((text + out) as *u8, bytes as u64); + out += bytes as u64; + at += length + 1; + } + if block != null { + FreeEnvironmentStringsW(block); + } + + variables = span::::over(views as *strview, count); + viewed = true; + return variables; +} + +#! Writes the rule the zone the system is set to keeps its clocks by, as the +#! `TZ` variable of POSIX writes one, as `6:005:00,M3.2.0/2:00:00,M11.1.0/2:00:00`, which `std::time` reads. +#! Windows keeps no database of zones, so this is the zone the program keeps as +#! the system's own there. +#! @param into The text to write the rule to. +#! @returns Whether the system says which zone it is set to. +pub def zone_rule(into: &mut string): bool { + var information: zone_information; + if GetDynamicTimeZoneInformation(&mut information) == 0xFFFFFFFF { + return false; + } + + val usual := information.bias + information.standard_bias; + put_zone_name(into, (&information.standard_name) as *u16, usual); + put_behind(into, usual); + + # A rule giving the day of a year it changes is one of that year alone, which + # no rule of POSIX says. + val start := information.daylight_date; + val end := information.standard_date; + if information.no_daylight != 0 || start.month == 0 || end.month == 0 || start.year != 0 || end.year != 0 { + return true; + } + val summer := information.bias + information.daylight_bias; + put_zone_name(into, (&information.daylight_name) as *u16, summer); + put_behind(into, summer); + put_turning(into, &start); + put_turning(into, &end); + return true; +} + +# Writes what a zone calls a time between `<` and `>`, leaving out either where +# it holds them, or its offset where it calls it nothing. +def put_zone_name(into: &mut string, units: *u16, behind: i32): void { + var count := 0u; + while count < 32 && units[count] != 0 { + count++; + } + var text: u8[96]; + val bytes := narrow(units, count, (&mut text) as *mut u8, 96); + into.push('<'); + var named := false; + for i in 0..(bytes < 0 ? 0u : bytes as u64) { + if text[i] != '<' && text[i] != '>' { + into.push(text[i]); + named = true; + } + } + if !named { + val ahead := -behind; + into.append(ahead < 0 ? "-" : "+"); + val size := ahead < 0 ? -ahead : ahead; + into.append($"{size / 60}:{size % 60 < 10 ? "0" : ""}{size % 60}".view()); + } + into.push('>'); +} + +# Writes how far behind UTC a time is, as the rule writes it, as `6:00` or +# `-5:30`. +def put_behind(into: &mut string, minutes: i32): void { + val size := minutes < 0 ? -minutes : minutes; + if minutes < 0 { + into.push('-'); + } + into.append($"{size / 60}:{size % 60 < 10 ? "0" : ""}{size % 60}".view()); +} + +# Writes when a change of the zone comes, as the rule writes it, as +# `,M3.2.0/2:00:00`: the month, which of its weeks, the day of the week, and +# the time of day, to the second, rounded. +def put_turning(into: &mut string, date: &system_time): void { + val time := date.hour as i64 * 3600 + date.minute as i64 * 60 + date.second as i64 + (date.millisecond >= 500 ? 1 : 0); + val minute := time / 60 % 60; + val second := time % 60; + into.append($",M{date.month}.{date.day}.{date.day_of_week}/{time / 3600}:".view()); + into.append($"{minute < 10 ? "0" : ""}{minute}:{second < 10 ? "0" : ""}{second}".view()); +} + +# The bytes of a character cut short at the end of what was last written to a +# console, which the next write to it finishes: for each of the program's own +# output and error, and one for any other console. +struct console_tail { + var handle: u64; + var count: u64; + var bytes: u8[4]; +} + +var tails: console_tail[3]; + +# How many bytes a character takes that a byte begins, as UTF-8 writes it, or +# one for a byte beginning none. +def sequence_length(byte: u8): u64 { + if byte >= 0xC2 && byte <= 0xDF { return 2; } + if byte >= 0xE0 && byte <= 0xEF { return 3; } + if byte >= 0xF0 && byte <= 0xF4 { return 4; } + return 1; +} + +# How many bytes at the end of some begin a character they do not finish. +def cut_short(from: *u8, length: u64): u64 { + var at := length; + while at > 0 && length - at < 3 && (from[at - 1] & 0xC0) == 0x80 { + at--; + } + if at == 0 { + return 0; + } + val begins := at - 1; + return begins + sequence_length(from[begins]) > length ? length - begins : 0; +} + +# Writes UTF-8 to a console as the characters it is, holding a character cut +# short at the end until the next write finishes it. Gives how many bytes it +# took, which is every one but where the console failed. +def console_write(handle: u64, from: *u8, length: u64): i64 { + val slot := handle == GetStdHandle(0xFFFFFFF5) ? 0u : handle == GetStdHandle(0xFFFFFFF4) ? 1u : 2u; + if tails[slot].handle != handle { + tails[slot] = console_tail { handle = handle }; + } + + # A character the last write cut short is finished first, where this write + # holds the rest of it. + var done := 0u; + if tails[slot].count > 0 { + var joined: u8[4]; + val held := tails[slot].count; + for i in 0..held { + joined[i] = tails[slot].bytes[i]; + } + val wanted := sequence_length(joined[0]); + var count := held; + while count < wanted && done < length && (from[done] & 0xC0) == 0x80 { + joined[count] = from[done]; + count++; + done++; + } + if count < wanted && done == length { + for i in held..count { + tails[slot].bytes[i] = joined[i]; + } + tails[slot].count = count; + return length as i64; + } + tails[slot].count = 0; + val result := console_units(handle, strview::over((&joined) as *u8, count)); + if result < 0 { + return result; + } + } + + # What is left is written in pieces, none splitting a character, keeping a + # character cut short at its end for the next write. + val cut := cut_short(from + done, length - done); + val end := length - cut; + for i in 0..cut { + tails[slot].bytes[i] = from[end + i]; + } + tails[slot].count = cut; + while done < end { + var piece := end - done < 4096 ? end - done : 4096; + while piece < end - done && piece > 1 && (from[done + piece] & 0xC0) == 0x80 { + piece--; + } + val result := console_units(handle, strview::over(from + done, piece)); + if result < 0 { + return done > 0 ? done as i64 : result; + } + done += piece; + } + return length as i64; +} + +# Writes UTF-8 of at most 4096 bytes to a console as the characters it is, +# giving zero, or the failure. +def console_units(handle: u64, text: strview): i64 { + var units: u16[4096]; + val at := (&mut units) as *mut u16; + val count := utf16_of(text, at, false) as u64; + var done := 0u; + while done < count { + # A write the system gave up on for a signal is made again, as on Linux. + var written: u32 = 0; + if WriteConsoleW(handle, (at + done) as *u16, (count - done) as u32, &mut written, null) == 0 { + val why := GetLastError(); + if why != error_operation_aborted { + return errno_of(why); + } + } + done += written as u64; + } + return 0; +} + +# What a read of the console gave as UTF-8 that there was no room for, which +# the next read gives first. +var console_pending: *mut u8; +var pending_at: u64; +var pending_end: u64; + +# The first half of a character a read of the console ended in, which the next +# read finishes, or zero. +var console_half: u16; + +# Units read from the console at a time. +const console_units_read: u64 = 4096; + +# Reads what is typed at a console, as UTF-8. +def console_read(handle: u64, into: *mut u8, length: u64): i64 { + if length == 0 { + return 0; + } + + while pending_at == pending_end { + # A character the last read cut short begins what this one gives. + var units: u16[console_units_read]; + var held: u32 = 0; + if console_half != 0 { + units[0] = console_half; + held = 1; + } + var read: u32 = 0; + SetLastError(0); + val ok := ReadConsoleW(handle, ((&mut units) as *mut u16) + held, console_units_read as u32 - held, &mut read, null); + val why := GetLastError(); + if ok == 0 && why != error_operation_aborted { + return errno_of(why); + } + + # Ctrl-C ends a read with nothing, rather than ending the input, a moment + # before the system notes the signal; the read is made again where no + # handler ran. + if read == 0 { + if why != error_operation_aborted { + return 0; + } + val event := interrupting(); + if event != 0 { + WaitForSingleObject(event, 100); + } + if run_handlers() { + return -4; + } + continue; + } + + # A line beginning with Ctrl-Z ends the input. + if held == 0 && units[0] == 0x1A { + return 0; + } + + # A read that ends in the first half of a character, as a long line read in + # parts may, keeps it for the next. + read += held; + console_half = 0; + if units[read - 1] >= 0xD800 && units[read - 1] < 0xDC00 { + console_half = units[read - 1]; + read--; + } + if console_pending == null { + console_pending = raw_allocate(console_units_read * 3); + } + pending_end = narrow((&units) as *u16, read as u64, console_pending, console_units_read * 3) as u64; + pending_at = 0; + } + + val count := length < pending_end - pending_at ? length : pending_end - pending_at; + memcpy(into, console_pending + pending_at, count); + pending_at += count; + return count as i64; +} diff --git a/system/on_windows_x86_64.sakura b/system/on_windows_x86_64.sakura new file mode 100644 index 00000000..ee270412 --- /dev/null +++ b/system/on_windows_x86_64.sakura @@ -0,0 +1,58 @@ +#! @file on_windows_x86_64.sakura +#! @author John Christman (sorakatadzuma@gmail.com) +#! @copyright Malunal Studios, LLC. +#! @license MIT +#! +#! Contains what `system` needs to know of Windows on x86-64. +#! +#! What `system` needs to know of Windows on x86-64: the numbers of the +#! signals. Windows numbers none of its own, so they are Linux's on x86-64, +#! which keeps the bits `watched` gives, and the numbers `signal_of` takes, the +#! same on both. + + +module system when os == windows && arch == x86_64; + +# The number a signal is given, as Linux gives it on x86-64. +def number_of(which: signal): i32 { + return match which { + hangup => 1, + interrupt => 2, + quit => 3, + kill => 9, + user1 => 10, + user2 => 12, + pipe => 13, + alarm => 14, + terminate => 15, + child => 17, + resume => 18, + stop => 19, + suspend => 20, + resized => 28, + }; +} + +#! The signal a number is given to, as Linux gives it on x86-64, where it is +#! one `signal` names. +#! @param number The number. +#! @returns The signal, or nothing. +pub def signal_of(number: i64): maybe { + return match number { + 1 => signal::hangup, + 2 => signal::interrupt, + 3 => signal::quit, + 9 => signal::kill, + 10 => signal::user1, + 12 => signal::user2, + 13 => signal::pipe, + 14 => signal::alarm, + 15 => signal::terminate, + 17 => signal::child, + 18 => signal::resume, + 19 => signal::stop, + 20 => signal::suspend, + 28 => signal::resized, + else => nothing{}, + }; +} diff --git a/system/system.sakura b/system/system.sakura new file mode 100644 index 00000000..85dad006 --- /dev/null +++ b/system/system.sakura @@ -0,0 +1,262 @@ +#! @file system.sakura +#! @author John Christman (sorakatadzuma@gmail.com) +#! @copyright Malunal Studios, LLC. +#! @license MIT +#! +#! Contains `system`, the layer of the standard library that talks to the +#! operating system, as each system provides it, and what every system shares: a +#! directory's entries, how a copy of the program stopped, and stopping the +#! program. +#! +#! The layer of the standard library that talks to the operating system, and the +#! only one that knows which system it runs on. `std::io` is written once over +#! it, for every system, and is what programs use; this layer is for what +#! `std::io` does not cover. +#! +#! Each system implements the same operations in a section of its own, as +#! `linux.sakura` and `windows.sakura` do, with the numbers that differ by +#! processor in another, as `linux_x86_64.sakura`. Another system is supported +#! by writing those two, with the same names and signatures, and nothing above +#! this layer changes, but where the system cannot do what Linux does: as +#! Windows cannot `fork`, `std::testing` says with `when` what it does there +#! instead. +#! +#! The operations are thin: they take paths as text, as `path::view` gives it, +#! and fail by giving a negative number, the error number Linux would give, +#! which another system makes of its own, and which `error_of` turns into an +#! `io_error`. Each system provides: +#! +#! ``` +#! fd its handle to an open file, with fd::stdin, stdout, +#! and stderr, and `path_limit`, the longest path it takes +#! open(path, flags, mode) opens a file, as `open_flags` say, creating it with +#! the permissions `mode` gives where it is made +#! fd::read, write, put, seek, close, stat, chmod +#! stat, lstat describes the file at a path, following a link at +#! the end of it or not, into a `file_info` +#! chmod sets the permissions of the file at a path +#! mkdir, rmdir, unlink makes a directory, removes an empty one, removes a file +#! rename moves a file to another path, replacing a file there +#! getcwd, chdir reads and sets the working directory +#! dir_stream, opendir reads the names a directory holds, with their kinds +#! error_of what a failure means, as an `io_error` +#! fork, wait starts a copy of the program and waits for it, +#! which Windows starts from the start, by `respawn` +#! pipe, spawn, poll makes a pipe, starts another program, and waits, +#! for at most a while, until one of several handles +#! can be read +#! environment, null_device the variables the program started with, and the +#! path of the device that holds nothing +#! kill, raise, getpid sends a signal to a process, or to the program +#! itself, and gives the program's own number +#! ignore, restore, handle has the system throw a signal away, do what it +#! does by default, or note it for a handler +#! pause waits until a handler has run +#! clock, sleep reads the wall clock or the steady one, and waits +#! for a length of time +#! futex_wait, futex_wake waits while a word holds a value, and wakes those +#! waiting on it, which threads, and on Linux processes +#! sharing memory, wait for one another with +#! cpu_count, thread_id, how many processors the program may run on, the +#! yield_now calling thread's number, and letting others run +#! ``` +#! +#! Windows also provides `respawn`, which starts a copy of the program from its +#! start, and `zone_rule`, the rule of the zone the system is set to, since it +#! keeps no files of zones. +#! +#! What every system shares of signals is here: the `signal` each is, and the +#! handlers. A handler never runs in the middle of whatever the program was +#! doing, as C's does. The system's own handler only notes that the signal came, +#! and the program's runs at its next safe point: where one of the program's own +#! functions begins, or a pass of one of its loops, in a program that handles a +#! signal somewhere. A wait the signal interrupts runs the handlers too, then +#! ends, failing with `io_error::interrupted`. So a handler may do anything a +#! function may, and never finds a container, a string, or a writer of std in +#! the middle of a change. + + +module system; + +#! How a copy of the program that `fork` started stopped, or a program `spawn` +#! started, as `wait` gives it. +pub struct process_status { + pub var exited: bool; #! Whether it stopped by exiting, with `code`, rather than by a signal. + pub var code: i32; #! The status it exited with. + pub var signal: i32; #! The signal that stopped it, when it did not exit. +} + +#! What `spawn` starts a program with, all of which it copies before the program +#! starts. +pub struct spawn_request { + #! The path of the program, which is found already. + pub var program: strview; + #! What the program is given, the first being what it is called. + pub var arguments: span; + #! The variables it is given, each as `NAME=value`. + pub var environment: span; + #! Where it runs, or empty for where this program runs. + pub var directory: strview; + #! The handle its standard input is given. + pub var input: fd; + #! The handle its standard output is given. + pub var output: fd; + #! The handle its standard error is given. + pub var error: fd; +} + +#! A name a directory holds, as `dir_stream::next` gives it. +pub struct dir_entry { + pub var name: strview; #! Only good until the next entry is read. + pub var kind: file_kind; #! What the name is itself, not what a link there leads to. +} + +#! Stops the program with a status, having run everything asked of it. +#! +#! Whatever the program has written is written, and nothing it has yet to do is +#! done. A status of zero says the program did what it was asked to. +#! @param code The status to stop with, which Linux reads as a byte, and +#! Windows whole. +@intrinsic +pub def exit(code: i32): void; + +#! Stops the program at once, reporting where it was. +#! +#! This is for a program that has found something it cannot go on from. It is +#! not graceful: the report names the functions that were running, and the +#! status is the one every other fault gives. +@intrinsic +pub def abort(): void; + +#! Starts a thread of the system running a function given a context, which the +#! backend makes: a thread of the virtual machine, or of an executable with +#! stacks of its own. `std::thread` starts threads with it. +#! @param body The function the thread runs. +#! @param context What the function is given. +#! @returns The thread's number, or a negative error number. A program +#! evaluating a constant starts none. +@intrinsic +pub def start(body: def(*mut u8): void, context: *mut u8): i64; + +#! A signal the system, or another program, sends a program. +#! +#! The members are the same on every system, which numbers them in its own way. +#! Faults are not among them: reading through a null pointer, dividing by zero, +#! and the like stop the program with a report, since a fault is a mistake of +#! the program that no handler can put right. +pub enum signal: u8 { + #! SIGHUP: the terminal went away. By custom, a server reads its settings + #! again. + hangup, + #! SIGINT: Ctrl-C. + interrupt, + #! SIGQUIT: Ctrl-\. + quit, + #! SIGKILL: the program stops at once. It cannot be handled or ignored. + kill, + #! SIGUSR1: whatever the programs sending and receiving it agree on. + user1, + #! SIGUSR2: the same. + user2, + #! SIGPIPE: the program wrote to a pipe nothing reads. + pipe, + #! SIGALRM: a timer ran out. + alarm, + #! SIGTERM: the program is asked to stop. + terminate, + #! SIGCHLD: a child stopped, or was paused or resumed. + child, + #! SIGCONT: the program goes on after being paused. + resume, + #! SIGSTOP: the program is paused. It cannot be handled or ignored. + stop, + #! SIGTSTP: Ctrl-Z, asking the program to pause. + suspend, + #! SIGWINCH: the terminal changed size. + resized, +} + +#! A function that handles a signal, given the signal it handles, which it owns, +#! as a functor holding what it needs: whatever it was given as. +pub type handler = function; + +# How many members `signal` has. +const signal_count: u64 = 14; + +# The handler of each signal, by member, which holds nothing where none was +# given, and which signals the program handles, one bit each by the system's +# number. +var handlers: handler[signal_count]; +var handled: u64; + +# The signals the program watches for rather than handles, one bit each by the +# system's number, and the signals taken from the system that neither `watched` +# nor the handlers have yet. +var noting: u64; +var arrived: u64; + +# Whether a handler is running, so that another runs only once it returns. +var dispatching: bool; + +# Has the system note a signal of its number when it comes, rather than doing +# what it would, and end the waits the signal interrupts rather than go on with +# them. Gives zero, or a negative number. +@intrinsic +def catch_signal(number: i32): i32; + +# Gives the signals noted since they were last asked for, one bit each by the +# system's number, and forgets them in the same step. +@intrinsic +def take_signals(): u64; + +# Runs the handlers of the signals that have come. Safe points call this, which +# std's own code has none of. +def dispatch(): void { + _ = run_handlers(); +} + +# Runs the handler of each signal that has come, in the order of the system's +# numbers, until none has, giving whether any ran. Within a handler it runs +# none, so the signals that come while one runs are handled once it returns. A +# signal that came before the program stopped handling it is passed over. +# Handlers run in the thread the program began with, as each system's +# `is_first_thread` finds it, so a wait another thread's signal ended runs none. +def run_handlers(): bool { + if dispatching || !is_first_thread() { + return false; + } + + dispatching = true; + var ran := false; + while true { + arrived = arrived | take_signals(); + val waiting := arrived & ~noting; + arrived = arrived & noting; + if waiting == 0 { + break; + } + + # A handler may stop the program handling a signal that came with its own. + for number in 0u..64u { + if (((waiting & handled) >> number) & 1) == 0 { + continue; + } + val which := signal_of(number as i64) else { continue; }; + + # A handler is taken from its place while it runs, so one handling its own + # signal anew replaces it without closing what runs. It goes back where + # nothing replaced it, and closes where something did. + var by := move(&mut handlers[which as u64]); + if !by.holds() { + continue; + } + by(which); + ran = true; + if !handlers[which as u64].holds() { + handlers[which as u64] = move(&mut by); + } + } + } + dispatching = false; + return ran; +} diff --git a/system/windows/waits.sakura b/system/windows/waits.sakura new file mode 100644 index 00000000..d9c921f2 --- /dev/null +++ b/system/windows/waits.sakura @@ -0,0 +1,18 @@ +#! @file waits.sakura +#! @author John Christman (sorakatadzuma@gmail.com) +#! @copyright Malunal Studios, LLC. +#! @license MIT +#! +#! Contains the functions Windows keeps for waiting on a word, of +#! `system::windows`, which `system` and the runtime wait and wake with. They are +#! a library of their own, and a file names one library on Windows. + +extern import "api-ms-win-core-synch-l1-2-0.dll" when os == windows; + +extern module system::windows when os == windows; + +pub def WaitOnAddress( + at: *mut u32, compare: &u32, size: u64, milliseconds: u32 +): i32; +pub def WakeByAddressSingle(at: *mut u32): void; +pub def WakeByAddressAll(at: *mut u32): void; diff --git a/system/windows/windows.sakura b/system/windows/windows.sakura new file mode 100644 index 00000000..6e010b05 --- /dev/null +++ b/system/windows/windows.sakura @@ -0,0 +1,268 @@ +#! @file windows.sakura +#! @author John Christman (sorakatadzuma@gmail.com) +#! @copyright Malunal Studios, LLC. +#! @license MIT +#! +#! Contains `system::windows`: what Windows gives a program, declared once for +#! std, its runtime, and anything else that reaches the system itself. These are +#! the functions of `kernel32.dll`, the structs they take, as C lays them out, +#! and the numbers they are asked for and give. The functions Windows keeps for +#! waiting on a word are in `waits.sakura`, a library of their own. + + +extern import "kernel32.dll" when os == windows; + +extern module system::windows when os == windows; + +pub def GetLastError(): u32; +pub def SetLastError(code: u32): void; +pub def GetStdHandle(which: u32): u64; +pub def SetStdHandle(which: u32, handle: u64): i32; +pub def CloseHandle(handle: u64): i32; +pub def DuplicateHandle( + from_process: u64, handle: u64, to_process: u64, made: &mut u64, access: u32, inherit: i32, options: u32 +): i32; +pub def CreateFileW( + name: *u16, access: u32, share: u32, security: *mut u8, disposition: u32, flags: u32, model: u64 +): u64; +pub def ReOpenFile(handle: u64, access: u32, share: u32, flags: u32): u64; +pub def ReadFile( + handle: u64, into: *mut u8, length: u32, read: &mut u32, overlapped: *mut u8 +): i32; +pub def WriteFile( + handle: u64, from: *u8, length: u32, written: &mut u32, overlapped: *mut u8 +): i32; +pub def SetFilePointerEx(handle: u64, distance: i64, position: &mut i64, method: u32): i32; +pub def GetFileType(handle: u64): u32; +pub def GetFileInformationByHandle(handle: u64, info: &mut file_information): i32; +pub def GetFileInformationByHandleEx(handle: u64, class: u32, info: *mut u8, size: u32): i32; +pub def SetFileInformationByHandle(handle: u64, class: u32, info: *mut u8, size: u32): i32; +pub def GetFinalPathNameByHandleW(handle: u64, into: *mut u16, length: u32, flags: u32): u32; +pub def GetFileAttributesW(name: *u16): u32; +pub def SetFileAttributesW(name: *u16, attributes: u32): i32; +pub def CreateDirectoryW(name: *u16, security: *mut u8): i32; +pub def RemoveDirectoryW(name: *u16): i32; +pub def DeleteFileW(name: *u16): i32; +pub def MoveFileExW(from: *u16, to: *u16, flags: u32): i32; +pub def GetCurrentDirectoryW(length: u32, into: *mut u16): u32; +pub def SetCurrentDirectoryW(name: *u16): i32; +pub def GetFullPathNameW(name: *u16, length: u32, into: *mut u16, part: *mut u8): u32; +pub def FindFirstFileExW( + name: *u16, level: u32, data: *mut u8, search: u32, filter: *mut u8, flags: u32 +): u64; +pub def FindNextFileW(find: u64, data: *mut u8): i32; +pub def FindClose(find: u64): i32; +pub def GetConsoleMode(handle: u64, mode: &mut u32): i32; +pub def WriteConsoleW( + handle: u64, from: *u16, length: u32, written: &mut u32, reserved: *mut u8 +): i32; +pub def ReadConsoleW( + handle: u64, into: *mut u16, length: u32, read: &mut u32, control: *mut u8 +): i32; +pub def CreatePipe(reading: &mut u64, writing: &mut u64, security: *mut u8, size: u32): i32; +pub def PeekNamedPipe( + handle: u64, into: *mut u8, length: u32, read: *mut u32, available: &mut u32, left: *mut u32 +): i32; +pub def GetCurrentProcess(): u64; +pub def GetCurrentProcessId(): u32; +pub def GetCurrentThreadId(): u32; +pub def GetModuleFileNameW(library: u64, into: *mut u16, length: u32): u32; +pub def GetCommandLineW(): *u16; +pub def GetSystemDirectoryW(into: *mut u16, length: u32): u32; +pub def CreateProcessW( + application: *u16, command: *mut u16, process_security: *mut u8, thread_security: *mut u8, inherit: i32, + flags: u32, environment: *mut u16, directory: *u16, startup: &mut startup_information, + information: &mut process_information +): i32; +pub def InitializeProcThreadAttributeList( + list: *mut u8, count: u32, flags: u32, size: &mut u64 +): i32; +pub def UpdateProcThreadAttribute( + list: *mut u8, flags: u32, attribute: u64, value: *mut u8, size: u64, previous: *mut u8, returned: *mut u64 +): i32; +pub def DeleteProcThreadAttributeList(list: *mut u8): void; +pub def OpenProcess(access: u32, inherit: i32, process: u32): u64; +pub def TerminateProcess(process: u64, code: u32): i32; +pub def GetExitCodeProcess(process: u64, code: &mut u32): i32; +pub def WaitForSingleObject(handle: u64, milliseconds: u32): u32; +pub def WaitForMultipleObjects(count: u32, handles: *u64, all: i32, milliseconds: u32): u32; +pub def CreateWaitableTimerExW(security: *mut u8, name: *u16, flags: u32, access: u32): u64; +pub def SetWaitableTimer( + timer: u64, due: &i64, period: i32, routine: *mut u8, argument: *mut u8, wake: i32 +): i32; +pub def Sleep(milliseconds: u32): void; +pub def SwitchToThread(): i32; +pub def GetActiveProcessorCount(group: u16): u32; +pub def GetProcessAffinityMask(process: u64, mask: &mut u64, system: &mut u64): i32; +pub def GetEnvironmentStringsW(): *mut u16; +pub def FreeEnvironmentStringsW(block: *mut u16): i32; +pub def GetSystemTimePreciseAsFileTime(time: &mut filetime): void; +pub def QueryPerformanceCounter(count: &mut i64): i32; +pub def QueryPerformanceFrequency(frequency: &mut i64): i32; +pub def GetDynamicTimeZoneInformation(into: &mut zone_information): u32; +pub def VirtualAlloc(address: u64, size: u64, kind: u32, protection: u32): u64; +pub def VirtualFree(address: u64, size: u64, kind: u32): i32; +pub def MultiByteToWideChar(page: u32, flags: u32, bytes: *u8, count: i32, + units: *mut u16, room: i32): i32; +pub def WideCharToMultiByte( + page: u32, flags: u32, wide: *u16, count: i32, into: *mut u8, size: i32, fallback: *u8, used: *mut i32 +): i32; +pub def ExitProcess(code: u32): void; +pub def SetErrorMode(mode: u32): u32; +pub def OpenThread(access: u32, inherit: i32, id: u32): u64; +pub def SuspendThread(thread: u64): u32; +pub def ResumeThread(thread: u64): u32; +pub def GetThreadContext(thread: u64, context: *mut u64): i32; +pub def VirtualProtect(at: u64, size: u64, protect: u32, was: &mut u32): i32; +pub def FlushInstructionCache(process: u64, at: u64, size: u64): i32; +pub def LoadLibraryW(name: *u16): u64; +pub def FreeLibrary(handle: u64): i32; +pub def GetProcAddress(handle: u64, name: *u8): u64; +pub def GetModuleHandleW(name: *u16): u64; +pub def K32EnumProcessModules(process: u64, into: *mut u64, size: u32, needed: &mut u32): i32; +pub def CreateJobObjectW(security: *mut u8, name: *u16): u64; +pub def SetInformationJobObject(job: u64, kind: u32, information: *mut u8, length: u32): i32; +pub def AssignProcessToJobObject(job: u64, process: u64): i32; + +# What the system's functions are asked for, and what they give. +pub val invalid_handle: u64 = 0xFFFFFFFFFFFFFFFF; +pub val invalid_attributes: u32 = 0xFFFFFFFF; +pub val infinite: u32 = 0xFFFFFFFF; +pub val wait_failed: u32 = 0xFFFFFFFF; +pub val generic_read: u32 = 0x80000000; +pub val generic_write: u32 = 0x40000000; +pub val append_data: u32 = 0x4; +pub val read_attributes: u32 = 0x80; +pub val write_attributes: u32 = 0x100; +pub val synchronize: u32 = 0x100000; +pub val share_all: u32 = 7; # Others may read, write, rename, and remove it. +pub val create_new: u32 = 1; +pub val create_always: u32 = 2; +pub val open_existing: u32 = 3; +pub val open_always: u32 = 4; +pub val truncate_existing: u32 = 5; +pub val backup_semantics: u32 = 0x02000000; # Lets a directory be opened. +pub val open_reparse_point: u32 = 0x00200000; # Opens a link rather than what it leads to. +pub val readonly: u32 = 0x1; +pub val directory: u32 = 0x10; +pub val device: u32 = 0x40; +pub val normal: u32 = 0x80; +pub val reparse_point: u32 = 0x400; +pub val symlink_tag: u32 = 0xA000000C; +pub val junction_tag: u32 = 0xA0000003; +pub val disk_type: u32 = 1; +pub val use_std_handles: u32 = 0x100; +pub val unicode_block: u32 = 0x400; +pub val extended_startup: u32 = 0x80000; +pub val handle_list: u64 = 0x20002; +pub val same_access: u32 = 2; +pub val process_terminate: u32 = 1; +pub val control_c_exit: u32 = 0xC000013A; # What a program the console's Ctrl-C stopped exits with. + +# The codes of failures the operations look for themselves. +pub val error_file_not_found: u32 = 2; +pub val error_path_not_found: u32 = 3; +pub val error_access_denied: u32 = 5; +pub val error_invalid_function: u32 = 1; +pub val error_sharing_violation: u32 = 32; +pub val error_handle_eof: u32 = 38; +pub val error_invalid_parameter: u32 = 87; +pub val error_broken_pipe: u32 = 109; +pub val error_no_more_files: u32 = 18; +pub val error_bad_exe_format: u32 = 193; +pub val error_operation_aborted: u32 = 995; +pub val error_timeout: u32 = 1460; +pub val error_cant_access_file: u32 = 1920; + +# A time of the system, in tenths of microseconds since 1601 began, as two +# halves. +pub struct filetime { + pub var low: u32; + pub var high: u32; +} + +# What `GetFileInformationByHandle` describes a file with. +pub struct file_information { + pub var attributes: u32; + pub var created: filetime; + pub var accessed: filetime; + pub var written: filetime; + pub var volume: u32; + pub var size_high: u32; + pub var size_low: u32; + pub var links: u32; + pub var index_high: u32; + pub var index_low: u32; +} + +# What `SetFileInformationByHandle` sets a file's attributes with, leaving each +# time that is zero as it is. +pub struct basic_information { + pub var created: i64; + pub var accessed: i64; + pub var written: i64; + pub var changed: i64; + pub var attributes: u32; +} + +# What a program is started with: its window, which a program of the console +# has none of, its standard streams, and a list of what more it is given. +pub struct startup_information { + pub var size: u32; + pub var reserved: *mut u16; + pub var desktop: *mut u16; + pub var title: *mut u16; + pub var x: u32; + pub var y: u32; + pub var width: u32; + pub var height: u32; + pub var columns: u32; + pub var rows: u32; + pub var fill: u32; + pub var flags: u32; + pub var show: u16; + pub var extra_size: u16; + pub var extra: *mut u8; + pub var standard_input: u64; + pub var standard_output: u64; + pub var standard_error: u64; + pub var attributes: *mut u8; +} + +# What `CreateProcessW` gives of a program it started. +pub struct process_information { + pub var process: u64; + pub var thread: u64; + pub var process_id: u32; + pub var thread_id: u32; +} + +# A date and time of the system, as a zone's changes are given. +pub struct system_time { + pub var year: u16; + pub var month: u16; + pub var day_of_week: u16; + pub var day: u16; # Of a change, which of the month's weeks, 5 being its last. + pub var hour: u16; + pub var minute: u16; + pub var second: u16; + pub var millisecond: u16; +} + +# The zone the system is set to, as `GetDynamicTimeZoneInformation` gives it: +# minutes behind UTC, and what it calls its usual and its summer time, how far +# each is from that, and when each begins. +pub struct zone_information { + pub var bias: i32; + pub var standard_name: u16[32]; + pub var standard_date: system_time; + pub var standard_bias: i32; + pub var daylight_name: u16[32]; + pub var daylight_date: system_time; + pub var daylight_bias: i32; + pub var key_name: u16[128]; + pub var no_daylight: u8; +} + +pub const startup_bytes: u64 = 112; +pub const basic_bytes: u64 = 40; diff --git a/tests/analyzer/checker.sakura b/tests/analyzer/checker.sakura new file mode 100644 index 00000000..5eaec124 --- /dev/null +++ b/tests/analyzer/checker.sakura @@ -0,0 +1,3116 @@ +#! @file checker.sakura +#! @author John Christman (sorakatadzuma@gmail.com) +#! @copyright Malunal Studios, LLC. +#! @license MIT +#! +#! Contains the tests of the checker: what each part of the language means, what +#! it refuses, and the notes it makes. + +import std::testing; +module sakura::analyzer; + + +# Programs here are checked without the standard library, unless a test gives +# a small `std` of its own as another file. + +@test def a_valid_program_checks_clean(t: &mut tester): void { + t.expects(checks(""" + def add(a: i64, b: i64): i64 { return a + b; } + def main(): void { + val x := add(1, 2); + var y: i64 = x * 3; + y += 1; + if y > 4 { y = 0; } else { y--; } + while y < 10 { y++; } + for i in 0..3 { y += i; } + } + """)); +} + +@test def locals_take_the_types_of_their_values(t: &mut tester): void { + t.expects(local_type("x", "def f(): void { val x := 1; }").view() == "int"); + t.expects(local_type("x", "def f(): void { val x := 1u; }").view() == "uint"); + t.expects(local_type("x", "def f(): void { val x := 2.5; }").view() == "float"); + t.expects(local_type("x", "def f(): void { val x := 2.5f; }").view() == "f32"); + t.expects(local_type("x", "def f(): void { val x := 'a'; }").view() == "u32"); + t.expects(local_type("x", "def f(): void { val x := true; }").view() == "bool"); + t.expects(local_type("x", "def f(): void { val x: u8 = 7; }").view() == "u8"); + t.expects(local_type("x", "def f(): void { val x := [1, 2, 3]; }").view() == "int[3]"); + t.expects(local_type("x", "def f(): void { var a := 1; val x := &mut a; }").view() == "&mut int"); +} + +@test def names_must_be_declared(t: &mut tester): void { + t.expects(check_noted(1, 26, ec::undefined, "def f(): void { val x := y; }")); + t.expects(check_noted(1, 10, ec::undefined, "def f(): nope { }")); +} + +@test def a_name_is_declared_once_where_it_is(t: &mut tester): void { + val made := check_program("", "val a := 1;\nval a := 2;"); + t.expects(made.notes.length == 1); + t.expects(made.notes.length == 1 && made.notes.at(0).line == 2 && made.notes.at(0).code == ec::duplicate); +} + +@test def values_convert_only_where_they_fit(t: &mut tester): void { + t.expects(check_noted(1, 30, ec::mismatch, "def f(): void { val x: i32 = true; }")); + t.expects(check_noted(1, 29, ec::overflow, "def f(): void { val x: u8 = 256; }")); + t.expects(check_noted(1, 30, ec::mismatch, "def f(): void { val x: i32 = 1u; }")); + t.expects(checks("def f(): void { val x: u64 = 7u; val y: i64 = x as i64; val z: u16 = 3; val w: u32 = z; }")); + t.expects(check_noted(1, 46, ec::mismatch, "def f(): void { val x: u32 = 3; val y: u16 = x; }")); +} + +@test def operators_take_what_they_apply_to(t: &mut tester): void { + t.expects(check_noted(1, 42, ec::operands, "def f(a: i64, b: u64): void { val c := a + b; }")); + t.expects(checks("def f(a: i64, b: u64): bool { return a < b; }")); + t.expects(checks("def f(a: f64, b: u8): f64 { return a * 2 + b; }")); + t.expects(check_noted(1, 26, ec::overflow, "def f(): void { val c := -1u; }")); + t.expects(check_noted(1, 26, ec::operands, "def f(): void { val c := !5; }")); + t.expects(checks("def f(p: *u8, q: *u8): i64 { val r := p + 3; return q - p; }")); +} + +@test def operators_call_the_methods_that_give_them(t: &mut tester): void { + # An operator on what is no number is a call of its method, on the left + # operand's type: the overload the right operand fits is chosen, a constant + # taking its parameter's type, and the operator gives what the method gives. A + # number on the left asks its own type, and a compound assignment writes what + # the method gives. + t.expects(checks(""" + import std; + struct length { var ns: i64; } + def length::add(&this, other: &length): length { return length{ this.ns + other.ns }; } + def length::negate(&this): length { return length{ -this.ns }; } + def length::mul(&this, by: &i64): length { return length{ this.ns * by }; } + def length::mul(&this, by: &f64): length { return length{ this.ns }; } + def length::div(&this, by: &length): f64 { return 1.0; } + struct moment { var ns: i64; } + def moment::add(&this, by: &length): moment { return moment{ this.ns + by.ns }; } + def moment::sub(&this, by: &length): moment { return moment{ this.ns - by.ns }; } + def moment::sub(&this, since: &moment): length { return length{ this.ns - since.ns }; } + def i64::mul(&this, by: &length): length { return by * this; } + struct holder { var kept: length; } + var holder::all: length { get => this.kept; set => this.kept = value; } + def main(): void { + var began := moment{ 1 }; + val waited: length = moment{ 5 } - began; + val later: moment = began + waited * 2 + -waited; + val scaled: length = 3 * waited * 0.5; + val ratio: f64 = waited / scaled; + began += waited; + began -= waited * 2; + var h := holder{ waited }; + h.all += waited; + val still: i64 = 2 * 3 + 4.mul(&5); + } + """, mini_std)); + + # Generic code has an operator from any bound asking for its method, composed + # traits included, and what a bound composes gives its own operators too. + t.expects(checks(""" + import std; + trait scales : additive { def mul(&this, by: &S): self; } + def lerp(a: V, b: V, t: S): V where V: scales { return a == b ? a : a + (b - a) * t; } + def total(a: T, b: T): T where T: addable { var t := a; t += b; return t + b; } + def flip(a: T): T where T: negatable { return -a; } + struct vec2 : additive { var x: f64; } + def vec2::equals(&this, o: &vec2): bool { return this.x == o.x; } + def vec2::add(&this, o: &vec2): vec2 { return vec2{ this.x + o.x }; } + def vec2::sub(&this, o: &vec2): vec2 { return vec2{ this.x - o.x }; } + def vec2::negate(&this): vec2 { return vec2{ -this.x }; } + def vec2::mul(&this, by: &f64): vec2 { return vec2{ this.x * by }; } + def main(): void { + val a := lerp(1.0, 3.0, 0.5) + total(1, 2) as f64; + val b := flip(total(lerp(vec2{ 0.0 }, vec2{ 2.0 }, 0.5), vec2{ 1.0 })); + val c := 1 is additive && 1.5 is multiplicative && b is additive && !(b is numeric); + } + """, mini_std)); + + # Each operator needs its own method, taking the other operand by reference + # and nothing more, with no type parameters of its own. What `+=` calls gives + # the type it writes over. Comparisons and bitwise operators are as they were. + val wrong := """ + import std; + struct p { var x: i64; } + def p::add(&this, o: &p): p { return p{ this.x + o.x }; } + def p::mul(&this, by: i64): p { return p{ this.x * by }; } + def p::div(&this, by: &T): p { return p{ this.x }; } + struct q { var y: i64; } + def q::sub(&this, o: &q): p { return p{ this.y - o.y }; } + def q::rem(&this, by: &i32): q { return q{ this.y }; } + def q::rem(&this, by: &u8): q { return q{ this.y }; } + def both(a: T, b: T): T where T: equatable { return a + b; } + def main(): void { + var a := p{ 1 }; + var m := q{ 1 }; + val c := a - a; + val d := -a; + val e := a * 2; + val f := a / a; + val g := a + 1; + val h := 2 + a; + val i := a & a; + val j := a << 1; + val k := a == a; + val n := m + a; + m -= m; + val o := m % 1; + } + """; + t.expects(note_count(wrong, mini_std) == 13); + t.expects(check_noted(10, 58, ec::operands, wrong, mini_std)); + for line in 14u..24u { + t.expects(check_noted(line as u32, line == 15 ? 12 : 14, ec::operands, wrong, mini_std)); + } + t.expects(check_noted(24, 5, ec::operands, wrong, mini_std)); + t.expects(check_noted(25, 14, ec::ambiguous, wrong, mini_std)); +} + +@test def a_programs_methods_on_numbers_stand_beside_the_compilers(t: &mut tester): void { + # With `f64::mul` declared for a vector, `f64` is still `numeric`, and its own + # `mul` is still called where the argument is a number. + t.expects(checks(""" + import std; + struct vec2 { var x: f64; } + def vec2::mul(&this, by: &f64): vec2 { return vec2{ this.x * by }; } + def f64::mul(&this, v: &vec2): vec2 { return v * this; } + def twice(x: T): T where T: numeric { return x.mul(&x) + x; } + def main(): void { + val a: f64 = 2.5.mul(&2.0) + twice(1.5); + val b: vec2 = 2.0 * vec2{ 1.0 } * 2.0; + val c := 2.5 is numeric && 2.5 is multipliable; + } + """, mini_std)); + t.expects(check_noted(5, 20, ec::mismatch, """ + import std; + struct vec2 { var x: f64; } + def f64::mul(&this, v: &vec2): vec2 { return vec2{ this }; } + def main(): void { + val a := 2.5.mul(&true); + } + """, mini_std)); +} + +@test def members_a_module_declares_on_anothers_type_are_seen_where_it_is_imported(t: &mut tester): void { + # `core`'s members are seen everywhere, and a type's own wherever it is. One a + # module declares on another's type, or on a built-in one, is seen within + # that module and where a file imports it, whatever another file of the + # program imports. + val core := """ + module std; module core; + pub struct lanes { pub var x: f64; } + pub def lanes::doubled(&this): f64 { return this.x * 2.0; } + pub def u8::twice(&this): u8 { return this * 2; } + """; + val math := """ + module math; + pub def lanes::root(&this): f64 { return this.x; } + pub def u8::halved(&this): u8 { return this / 2; } + def within(v: lanes): f64 { return v.root(); } + """; + t.expects(checks(""" + import math; + def f(v: lanes, b: u8): f64 { return v.root() + v.doubled() + (b.halved() + b.twice()) as f64; } + """, core, math)); + t.expects(check_noted(1, 47, ec::member, """ + def g(v: lanes): f64 { return v.doubled() + v.root(); } + """, core, math, """ + import math; + def f(v: lanes): f64 { return v.root(); } + """)); + t.expects(check_noted(2, 33, ec::member, "\n def g(b: u8): u8 { return b.halved(); }\n", core, math)); +} + +@test def constants_fold_where_they_are_known(t: &mut tester): void { + t.expects(local_type("x", "const n := 2 * 3; def f(): void { var x: i64[n + 1]; }").view() == "int[7]"); + t.expects(check_noted(1, 33, ec::overflow, "def f(): void { val x: u8 = 200 + 100; }")); + t.expects(check_noted(1, 45, ec::overflow, "def f(): void { val x := 0x7FFFFFFFFFFFFFFF * 4; }")); + t.expects(check_noted(1, 33, ec::constant, "def f(n: u64): void { var x: u8[n]; }")); +} + +@test def local_constants_are_worked_out_as_global_ones_are(t: &mut tester): void { + # A table is run while checking, as a global constant's is. + t.expects(checks(mini_std, """ + import std; + def f(): f64 { + const reals: span = [-0.0, 2.5, 1e-7]; + const whole: i64[2] = [1, -2]; + const n := 3 * 4; + var a: i64[n]; + return reals[1]; + } + """)); + t.expects(check_noted(1, 38, ec::constant, "def f(n: i64): void { const m: i64 = n; }")); +} + +@test def what_is_written_can_be_written(t: &mut tester): void { + t.expects(check_noted(1, 29, ec::assignable, "def f(): void { val a := 1; a = 2; }")); + t.expects(check_noted(2, 40, ec::assignable, + "struct p { val x: i64; var y: i64; }\ndef f(): void { var v := p{ x = 1 }; v.x = 2; v.y = 3; }")); + t.expects(check_noted(1, 36, ec::assignable, "def f(r: &i64): void { var a := 1; r = 2; }")); + t.expects(checks("def f(r: &mut i64): void { r = 2; r += 1; }")); + t.expects(checks("def f(): void { var a := 1; var r := &mut a; r = 5; var b := 2; r = &mut b; }")); +} + +@test def an_index_is_the_reference_at_gives(t: &mut tester): void { + # `d[key]` is `d.at(key)`, the reference `at` gives, `&mut` where `d` can be + # written. A binding takes the value it reaches, and `&` or `&mut` written + # binds the reference. + val table := """ + struct table { var items: i64[4]; } + def table::at(&this, key: u64): &i64 { return &this.items[key]; } + def table::at(&mut this, key: u64): &mut i64 { return &mut this.items[key]; } + def f(): void { + val read := table { items = [1, 2, 3, 4] }; + var written := table { items = [1, 2, 3, 4] }; + val r := read[0]; + val w := written[1]; + val c: i64 = written[2]; + val again := &written[3]; + val lent := &read[0]; + val writes := &mut written[1]; + } + """; + t.expects(local_type("r", table).view() == "int"); + t.expects(local_type("w", table).view() == "int"); + t.expects(local_type("c", table).view() == "int"); + t.expects(local_type("again", table).view() == "&int"); + t.expects(local_type("lent", table).view() == "&int"); + t.expects(local_type("writes", table).view() == "&mut int"); + + # What gives only `at(&this)` is read through `&` however it is held, so + # nothing writes through it, nor takes `&mut` of it to write a copy. + val frozen := """ + struct frozen { var items: i64[4]; } + def frozen::at(&this, key: u64): &i64 { return &this.items[key]; } + def f(): void { + var b := frozen { items = [1, 2, 3, 4] }; + b[0] = 1; + b[1]++; + val m := &mut b[2]; + val k := &mut b.at(3); + } + """; + t.expects(check_noted(5, 4, ec::assignable, frozen)); + t.expects(check_noted(6, 4, ec::assignable, frozen)); + t.expects(check_noted(7, 12, ec::assignable, frozen)); + t.expects(check_noted(8, 12, ec::assignable, frozen)); +} + +@test def contracts_check_what_they_are_given(t: &mut tester): void { + t.expects(checks(""" + def f(n: i64): i64 { + expects(n > 0); + ensures(r: r > old(n)); + asserts(n != 3); + return n + 1; + } + def g(n: i64): void { + for i in 0..n { + ensures(i < n); + continue if i == 1; + } + } + """)); + # A condition is a `bool`, which changes nothing it names. + t.expects(check_noted(1, 31, ec::mismatch, "def f(n: i64): void { expects(n); }")); + t.expects(check_noted(1, 44, ec::invalid, "def f(n: i64): void { var k := n; asserts(k++ > 0); }")); + t.expects(check_noted(1, 46, ec::invalid, "def f(n: i64): void { var k := n; asserts((k = 2) == 2); }")); + # Only a function's own block names what it returns, of a function returning + # something. + t.expects(check_noted(1, 25, ec::invalid, "def f(): void { ensures(r: true); }")); + t.expects(check_noted(1, 41, ec::invalid, "def f(n: i64): i64 { if n > 0 { ensures(r: r > 0); return n; } return 1; }")); + # The name is the `ensures`'s own. + t.expects(check_noted(1, 50, ec::undefined, "def f(n: i64): i64 { ensures(r: r > 0); val k := r; return n; }")); +} + +@test def variables_left_undefined_are_vars_of_what_closes_nothing(t: &mut tester): void { + t.expects(checks(""" + def f(n: u64): u64 { + var buffer: u64[8] = undefined; + var at: *u8 = undefined; + buffer[0] = n; + return buffer[0]; + } + def g(): u64 { val undefined: u64 = 2; return undefined + 1; } + """)); + # Only a `var` with a type written, of what has a zero value and closes + # nothing, and only a local. + t.expects(check_noted(1, 30, ec::invalid, "def f(): void { val n: u64 = undefined; }")); + t.expects(check_noted(1, 26, ec::invalid, "def f(): void { var n := undefined; }")); + t.expects(check_noted(1, 38, ec::invalid, "def f(x: &u64): void { var r: &u64 = undefined; }")); + t.expects(check_noted(1, 116, ec::invalid, mini_std, + "import std; struct held : owning { var n: i64; } def held::close(&mut this): void {} def f(): void { var h: held = undefined; }")); + t.expects(check_noted(1, 14, ec::invalid, "var g: u64 = undefined;")); +} + +@test def functions_return_on_every_path(t: &mut tester): void { + t.expects(check_noted(1, 5, ec::control, "def f(c: bool): i64 { if c { return 1; } }")); + t.expects(checks("def f(c: bool): i64 { if c { return 1; } else { return 2; } }")); + t.expects(checks("def f(c: bool): i64 { if c { return 1; } return 2; }")); + t.expects(check_noted(1, 17, ec::control, "def f(): void { break; }")); + t.expects(check_noted(1, 24, ec::mismatch, "def f(): void { return 1; }")); +} + +@test def calls_choose_the_overload_that_fits_best(t: &mut tester): void { + t.expects(checks(""" + def show(n: i64): i64 { return 1; } + def show(n: f64): i64 { return 2; } + def use(): void { val a := show(1); val b := show(1.5); } + """)); + t.expects(check_noted(3, 19, ec::arguments, """ + def show(n: i64): void {} + def show(n: f64): void {} + def use(): void { show(true); } + """)); + t.expects(check_noted(2, 19, ec::arguments, "def two(a: i64, b: i64): void {}\ndef use(): void { two(1); }")); + t.expects(checks("def pad(a: i64, b: i64 = 2): void {}\ndef use(): void { pad(1); pad(1, 3); }")); + t.expects(checks("def sum(xs: i64...): void {}\ndef use(): void { sum(); sum(1, 2, 3); }")); +} + +@test def references_are_taken_for_reference_parameters(t: &mut tester): void { + t.expects(checks("def grow(n: &mut i64): void { n += 1; }\ndef use(): void { var a := 1; grow(a); grow(&mut a); }")); + t.expects(check_noted(2, 36, ec::assignable, + "def grow(n: &mut i64): void { n += 1; }\ndef use(): void { val a := 1; grow(a); }")); + t.expects(checks("def read(n: &u8): u8 { return n; }\ndef use(): void { val a := read(200); }")); + + # A property's value is copied to be referred to, as any value is, but has no + # place for `&mut` to write. + val sized := "struct r { var w: i64; }\nval r::width: i64 { get => this.w; }\ndef read(n: &i64): i64 { return n; }\n"; + t.expects(checks(sized, "def f(): i64 { var v := r{ w = 1 }; return read(&v.width); }")); + t.expects(check_noted(1, 47, ec::invalid, sized, "def f(): void { var v := r{ w = 1 }; val m := &mut v.width; }")); +} + +@test def structs_are_made_of_their_fields(t: &mut tester): void { + val shape := "struct v { var x: f64; var y := 0.0; }\n"; + t.expects(checks(shape, "def f(): void { val a := v{ x = 1.0 }; val b := v{1.0, 2.0}; val c := v{ y = 2.0, x = 1.0 }; }")); + t.expects(note_count("struct v { var x: f64; var y := 0.0; }\ndef f(): void { val a := v{ z = 1.0 }; }") == 1); + t.expects(check_noted(2, 38, ec::duplicate, "struct v { var x: f64; }\ndef f(): void { val a := v{ x = 1.0, x = 2.0 }; }")); + t.expects(check_noted(2, 27, ec::zero_value, "struct v { val r: &i64; }\ndef f(): void { val a := v{}; }")); +} + +@test def methods_belong_to_their_types(t: &mut tester): void { + t.expects(checks(""" + struct v { var x: f64; } + def v::length(&this): f64 { return this.x; } + def v::grow(&mut this): void { this.x += 1.0; } + def v::of(x: f64): v { return v{ x = x }; } + val v::zero := v{ x = 0.0 }; + def u8::upper(&this): bool { return this >= 'A' && this <= 'Z'; } + def f(): void { + var a := v::of(1.0); + a.grow(); + val b := a.length() + v::zero.x; + val d := (65 as u8).upper(); + } + """)); + t.expects(check_noted(3, 40, ec::assignable, """ + struct v { var x: f64; } + def v::grow(&mut this): void { this.x += 1.0; } + def f(): void { val a := v{ x = 1.0 }; a.grow(); } + """)); +} + +@test def a_constant_settles_where_its_members_are_reached(t: &mut tester): void { + # A literal is a `strview` and a number an `int`, as either would be alone, and + # only interpolation builds a `string`. + val text := """ + module std; module core; + pub struct span { var data: *T; var count: u64; } + pub type strview = span; + pub val strview::length: u64 { get => this.count; } + pub def strview::trim(&this): strview { return this; } + pub struct string { var count: u64; } + pub val string::capacity: u64 { get => this.count; } + """; + val program := """ + import std; + def f(): u64 { + val plain := "abc"; + val built := $"abc{1}"; + return "abc".trim().length + plain.length + built.capacity + 5.hash(); + } + """; + t.expects(checks(program, text)); + t.expects(check_program("plain", program, text).asked.view() == "strview"); + t.expects(check_noted(2, 29, ec::member, "import std;\ndef f(): u64 { return \"abc\".capacity; }", text)); +} + +@test def enums_have_members_and_values(t: &mut tester): void { + t.expects(checks(""" + enum color: u8 { red, green = 4, blue } + def f(c: color): u8 { + val n: u8 = c; + val m := color::blue as u8 + 1; + return match c { red => 1, green => 2, blue => 3 }; + } + """)); + t.expects(check_noted(1, 24, ec::duplicate, "enum e { a = 1, b = 0, c }")); + t.expects(check_noted(1, 23, ec::overflow, "enum e: u8 { a = 255, b }")); + t.expects(check_noted(3, 3, ec::arms, """ + enum color { red, green, blue } + def f(c: color): void { + match c { red => {} green => {} } + } + """)); +} + +@test def unions_hold_one_of_their_fields(t: &mut tester): void { + t.expects(checks(""" + struct pair { var a: i64; var b: i64; } + union shape { var circle: f64; var rect: pair; } + def area(s: &shape): f64 { + match s { + circle(r) => return r; + rect(p) => return (p.a * p.b) as f64; + } + } + def f(): void { + var s: shape = 2.5; + s = pair{ a = 1, b = 2 }; + val t := shape{ circle = 1.0 }; + if s is circle(r) { val x := r + 1.0; } + if s is not rect(p) { return; } + val y := p.a; + } + """)); +} + +@test def generics_are_checked_against_their_bounds(t: &mut tester): void { + t.expects(checks(mini_std, """ + import std; + def max(a: T, b: T): T where T: ordered { return a > b ? a : b; } + struct box { var item: T; } + def box::get(&this): T { return this.item; } + def f(): void { + val a := max(1, 2); + val b := max::(1, 2); + val c := box{ item = 5 }.get(); + val d: box = box{ item = 1.5 }; + } + """)); + t.expects(check_noted(5, 3, ec::bound, mini_std, """ + import std; + struct p {} + def max(a: T, b: T): T where T: ordered { return a; } + def f(): void { + max(p{}, p{}); + } + """)); + t.expects(check_noted(2, 26, ec::generic, "def make(): T { return make::(); }\ndef f(): void { val x := make(); }")); +} + +# A program keeping references past what they refer to, each line a warning or +# none, as the checker is sure of it. +const lifetimes_program: strview = """ + import std; + struct point { var x: i64; } + struct holder { var p: &point; } + def returns_local(): &point { var p := point { x = 1 }; return &p; } + def returns_temp(): &point { return &point { x = 2 }; } + def returns_alias(): &point { var p := point { x = 3 }; val r := &p; return r; } + def returns_field(): &i64 { var p := point { x = 4 }; return &p.x; } + def returns_closure(): def(): i64 { var n: i64 = 5; return def(): i64 { return n; }; } + def returns_holder(): holder { var p := point { x = 6 }; return holder { p = &p }; } + def returns_by_value(p: point): &point { return &p; } + def into_param(h: &mut holder): void { var p := point { x = 7 }; h.p = &p; } + var global: maybe<&point> = nothing {}; + def into_global(): void { var p := point { x = 8 }; global = &p; } + def into_outer(): void { + var r: maybe<&point> = nothing {}; + { var p := point { x = 9 }; r = &p; } + for i in 0..3 { var q := point { x = i }; r = &q; } + } + def temporaries(h: &mut holder): void { + h.p = &point { x = 10 }; + val bound: &point = &point { x = 11 }; + val held := holder { p = &point { x = 12 } }; + } + def returns_param(p: &point): &point { return p; } + def returns_through(p: &point): &i64 { return &p.x; } + def returns_element(items: span): maybe<&i64> { for &x in items { return &x; } return nothing {}; } + def in_scope(): i64 { + var p := point { x = 13 }; + val r := &p; + var h := holder { p = &p }; + h.p = &p; + val f := def(): i64 { return p.x; }; + val g := def(): &point { var inner := point { x = 1 }; return &p; }; + return f() + r.x + h.p.x + g().x; + } + def lambda_own(): void { val g := def(): &point { var inner := point { x = 1 }; return &inner; }; } + @allow def allowed(): &point { var p := point { x = 14 }; return &p; } +"""; + +# What `allow` needs of std beside the mini one. +const allow_std: strview = "module std; module core;\npub trait attribute {}\npub struct allow : attribute {}\n"; + +@test def references_kept_past_what_they_refer_to_are_warned_of(t: &mut tester): void { + # A reference, view, or closure returned from the function declaring what it + # refers to, or written into a global, what a parameter refers to, or a local + # of a scope around the local's, outlives it, as one to a value its statement + # makes does where it is kept past the statement. These are warnings, so they + # stop nothing, and `@allow` quiets those of a function. + val made := check_program("", lifetimes_program, mini_std, allow_std); + var lines := vector::::new(); + var others: u64 = 0; + for &each in made.notes { + if each.code == ec::lifetime { + lines.append(each.line); + } else { + others++; + } + } + val wanted: u32[14] = [4, 5, 6, 7, 8, 9, 10, 11, 13, 16, 17, 20, 22, 36]; + t.expects(others == 0 && lines.length == 14); + for i in 0..14u { + t.expects(i < lines.length && lines[i] == wanted[i]); + } +} + +@test def references_satisfy_what_they_refer_to(t: &mut tester): void { + # A reference or a pointer satisfies what its referent does, so a generic given + # one borrows what it would otherwise own. An instance refers to an argument as + # its template did, so `take(to)` takes the reference itself where `S` is one. + t.expects(checks(mini_std, """ + import std; + trait sink { def put(&mut this, n: i64): void; } + trait sized { def size(&this): i64; } + struct tally : sink, owning { var n: i64; } + def tally::put(&mut this, n: i64): void { this.n += n; } + def tally::size(&this): i64 { return this.n; } + def tally::close(&mut this): void {} + struct held where S: sink { var to: S; } + def held::put(&mut this, n: i64): void { this.to.put(n); val r: &mut sink = &mut this.to; r.put(n); } + def take(x: &mut T): T { var made: T = x; return made; } + def hold(to: S): held where S: sink { return held::{ to = take(to) }; } + def measure(x: T): i64 where T: sized { return x.size(); } + def f(): void { + var t := tally{ n = 0 }; + var a := hold(&mut t); + var b := hold(&mut (*((&mut t) as *mut tally))); + val dyn: &mut sink = &mut t; + var c := hold(dyn); + a.put(1); b.put(2); c.put(3); + val n := measure(&t) + measure(&(*((&t) as *tally))); + } + """)); + + # Not where it only reads and the trait writes, where the trait asks for what is + # not called through it, or where the trait says what a value itself is. + val refused := """ + import std; + trait sink { def put(&mut this, n: i64): void; } + trait made { def make(): i64; } + struct tally { var n: i64; } + def tally::put(&mut this, n: i64): void { this.n += n; } + def tally::make(): i64 { return 1; } + def tally::close(&mut this): void {} + def sinks(to: S): void where S: sink {} + def makes(to: S): void where S: made {} + def closes(to: S): void where S: owning {} + def f(): void { + var t := tally{ n = 0 }; + sinks(&t); + makes(&mut t); + closes(&mut t); + } + """; + t.expects(check_noted(13, 3, ec::bound, mini_std, refused)); + t.expects(check_noted(14, 3, ec::bound, mini_std, refused)); + t.expects(check_noted(15, 3, ec::bound, mini_std, refused)); +} + +@test def references_compare_as_what_they_refer_to(t: &mut tester): void { + # A reference is compared and ordered as what it refers to, so it takes a trait + # naming `self` where `self` is only taken by reference. A pointer is compared as + # its address, so its `equals` and `compare` are its own. + t.expects(checks(mini_std, """ + import std; + trait near { def near(&this, other: &self): bool; } + struct tally : ordered, near { var n: i64; } + def tally::equals(&this, other: &tally): bool { return this.n == other.n; } + def tally::compare(&this, other: &tally): i64 { return this.n - other.n; } + def tally::near(&this, other: &tally): bool { return true; } + def least(a: T, b: T): T where T: ordered { if b < a { return b; } return a; } + def same(a: T, b: T): bool where T: equatable { return a == b && a.equals(&b); } + def nears(a: T, b: T): bool where T: near { return a.near(&b); } + def f(): void { + var t := tally{ n = 1 }; + var x: i64 = 2; + val l := least(&t, &t); + val s := same(&t, &mut t) && same(&x, &x) && nears(&t, &t); + val p := (&t) as *tally; + val q := p.equals(&p) && p.compare(&p) == 0 && same(p, p); + } + """)); + + # Not where `self` is given or taken by value, nor through a pointer. + val refused := """ + import std; + trait near { def near(&this, other: &self): bool; } + trait merges { def merge(&mut this, other: self): void; } + struct tally : near, merges { var n: i64; } + def tally::near(&this, other: &tally): bool { return true; } + def tally::merge(&mut this, other: tally): void {} + def adds(a: T): void where T: numeric {} + def nears(a: T): void where T: near {} + def merging(a: T): void where T: merges {} + def f(): void { + var t := tally{ n = 1 }; + var x: i64 = 1; + adds(&x); + nears((&t) as *tally); + merging(&mut t); + val p := (&t) as *tally; + val b := p.near(&p); + } + """; + t.expects(check_noted(13, 3, ec::bound, mini_std, refused)); + t.expects(check_noted(14, 3, ec::bound, mini_std, refused)); + t.expects(check_noted(15, 3, ec::bound, mini_std, refused)); + t.expects(check_noted(17, 14, ec::member, mini_std, refused)); +} + +@test def pointers_are_addresses(t: &mut tester): void { + # A pointer is compared and ordered as an address and moves by whole elements, as + # does a type parameter bounded by `pointer`. Nothing of what it points at is + # reached through it, but by dereferencing it. + val shared := "module std; module core;\npub trait pointer {}"; + t.expects(checks(mini_std, shared, """ + import std; + def gap

(a: P, b: P): i64 where P: pointer { var at := a; at += 1; return b < at ? 0 : b - at; } + def none

(): P where P: pointer { var made: P; return made; } + struct node { var next: *node; } + def f(n: &node): void { + val p := n as *node; + val g := gap(p, p + 2); + val q := none::<*node>(); + val next := (*p).next; + val also := p[0].next; + } + """)); + t.expects(check_noted(3, 36, ec::member, mini_std, shared, "import std;\nstruct node { var next: *node; }\ndef f(p: *node): void { val x := p.next; }")); + t.expects(check_noted(3, 17, ec::bound, mini_std, shared, "import std;\ndef take

(p: P): void where P: pointer {}\ndef f(): void { take(5); }")); +} + +@test def traits_give_their_default_methods(t: &mut tester): void { + # A method a trait writes a body for is its default: what implements the trait + # may leave it out, and a type naming the trait has it as its own. What a pointer + # points at is reached by dereferencing it, through a reference to it too. + t.expects(checks(mini_std, """ + import std; + trait sink { def put(&mut this, n: i64): void; def twice(&mut this, n: i64): void { this.put(n); this.put(n); } } + struct tally : sink { var n: i64; } + def tally::put(&mut this, n: i64): void { this.n += n; } + def fill(s: &mut S): void where S: sink { s.twice(1); } + def f(): void { + var t := tally{ n = 0 }; + t.twice(2); + fill(&mut t); + var p := (&mut t) as *mut tally; + (*p).twice(3); + val r: &mut *mut tally = &mut p; + (*r).put(4); + (*r).n = 5; + } + """)); + + # A type satisfying the trait without naming it has its defaults only through a + # reference to the trait. + t.expects(check_noted(7, 5, ec::member, mini_std, """ + import std; + trait sink { def put(&mut this, n: i64): void; def twice(&mut this, n: i64): void { this.put(n); } } + struct plain { var n: i64; } + def plain::put(&mut this, n: i64): void {} + def f(): void { + var p := plain{ n = 0 }; + p.twice(1); + val s: &mut sink = &mut p; + s.twice(1); + } + """)); +} + +@test def traits_have_functions_of_their_own(t: &mut tester): void { + # A function declared through a trait, outside it, is the trait's own: named + # through the trait, and generic as any function is, its type arguments written + # or inferred. + t.expects(checks(""" + trait parses {} + def parses::id(x: T): T { return x; } + def parses::one(): i64 { return 1; } + def f(): void { + val x: f64 = parses::id::(2.0); + val b: u8 = 3; + val y: u8 = parses::id(b); + val z: i64 = parses::one(); + } + """)); + + # What a trait asks for is declared within it, so a method taking `this`, an + # associated variable, or a nested type is not declared through it, and a + # function of its own takes a name it does not ask for. + val asking := """ + trait made { + def make(): i64 { return 1; } + def pick(x: T): T; + def size(&this): i64; + def build(): i64; + } + def made::grow(&this): i64 { return 1; } + val made::count: i64 = 1; + def made::size(): i64 { return 2; } + def made::own(): i64 { return 3; } + struct made::inner {} + struct thing {} + def f(): void { + val a := made::build(); + val c := thing::own(); + } + """; + t.expects(check_noted(7, 5, ec::invalid, asking)); + t.expects(check_noted(8, 5, ec::invalid, asking)); + t.expects(check_noted(9, 11, ec::duplicate, asking)); + t.expects(check_noted(11, 8, ec::invalid, asking)); + + # What it asks for each implementer gives: a static method has no default, + # since nothing within the trait names the type implementing it, no method has + # type parameters, since each implementation is called through the trait, and + # a static one is called through a type parameter, not the trait's own name. + t.expects(check_noted(2, 7, ec::invalid, asking)); + t.expects(check_noted(3, 12, ec::generic, asking)); + t.expects(check_noted(14, 18, ec::invalid, asking)); + + # What implements the trait has none of its own functions. + t.expects(check_noted(15, 19, ec::member, asking)); +} + +@test def fallbacks_keep_one_owner(t: &mut tester): void { + # A value that closes has one owner. `else` hands over what a call made, but a + # variable tested keeps what it holds, a result keeps the error it holds, and a + # union keeps the field it holds, even where it is only a call's result, so + # none of them is copied out. + val taken := """ + import std; + struct held : owning { var n: i64; } + def held::close(&mut this): void {} + def make(): result { return result:: { value = held { n = 1 } }; } + def find(): maybe { return held { n = 2 }; } + def f(): void { + val kept := make(); + val a := kept else held { n = 3 }; + val b := make() else (e) { return; }; + val c := find() else kept.value; + val d := make().value; + val e := find() else held { n = 4 }; + val g := make() else (_) { return; }; + } + """; + t.expects(check_noted(8, 12, ec::owned, mini_std, taken)); + t.expects(check_noted(9, 25, ec::owned, mini_std, taken)); + t.expects(check_noted(10, 29, ec::owned, mini_std, taken)); + t.expects(check_noted(11, 19, ec::owned, mini_std, taken)); + t.expects(note_count(mini_std, taken) == 4); +} + +@test def for_const_counts_through_ranges_known_while_checking(t: &mut tester): void { + # Each number is a constant in its copy of the body, which `if const` decides + # by, and a fixed array may take its length from. + t.expects(checks(""" + const count: u64 = 3; + def f(): void { + for const i in 0..count + 1 { + if const i == 0 { continue; } + var held: u8[i]; + } + } + """)); + # A range of an enum's members counts through each member. + t.expects(checks(""" + enum gap { a, b = 4, c } + def f(): void { + for const m in gap::a..=gap::c { + if const m == gap::a { continue; } + var held: u8[m as u64]; + } + } + """)); + + # What the program running gives is not counted through, nor read by `if + # const`, and a range gives numbers, as many as `for const` unrolls. + val wrong := """ + def f(n: u64): void { + val local := n + 1; + for const i in 0..n { } + for const &j in 0..3 { } + for const k in 0..2000 { } + if const local > 2 { } + for const m in 0..3 { m = 2; } + } + """; + t.expects(check_noted(3, 21, ec::constant, wrong)); + t.expects(check_noted(4, 14, ec::invalid, wrong)); + t.expects(check_noted(5, 13, ec::limit, wrong)); + t.expects(check_noted(6, 12, ec::constant, wrong)); + t.expects(check_noted(7, 25, ec::assignable, wrong)); +} + +@test def loops_own_what_iterators_give_by_value(t: &mut tester): void { + # A loop variable takes the value of each element. An element an iterator gives + # by value is the loop's own, which `for x` takes. One it gives by reference + # belongs to what it walks, as an array's elements do, so `for x` copies it, + # which a value that closes refuses, and `for &x` refers to it. + t.expects(checks(mini_std, """ + import std; + struct held : owning { var n: i64; } + def held::close(&mut this): void {} + struct gives : iterator { var n: i64; } + def gives::next(&mut this): maybe { return nothing {}; } + struct lends : iterator<&held> { var n: i64; } + def lends::next(&mut this): maybe<&held> { return nothing {}; } + def f(): void { + for x in (gives{ n = 0 }) { val n := x.n; } + for &x in (lends{ n = 0 }) { val n := x.n; } + for &x in (lends{ n = 0 }) { val r: &held = x; } + var hs: held[2]; + for &h in hs { val r: &held = h; } + } + """)); + val copied := """ + import std; + struct held : owning { var n: i64; } + def held::close(&mut this): void {} + struct lends : iterator<&held> { var n: i64; } + def lends::next(&mut this): maybe<&held> { return nothing {}; } + def f(): void { + for x in (lends{ n = 0 }) { val n := x.n; } + } + """; + t.expects(check_noted(7, 7, ec::owned, copied, mini_std)); +} + +@test def union_fields_that_close_are_taken_from_what_a_call_made(t: &mut tester): void { + # A union a call made owns nothing past the statement, so naming a field of it + # that closes takes the field over, and an arm used as a value may give it. A + # variable keeps what it holds, so its field is named by `&` or `&mut`. `_` + # names nothing. + t.expects(checks(mini_std, """ + import std; + struct held : owning { var n: i64; } + def held::close(&mut this): void {} + def make(): maybe { return nothing {}; } + def f(): held { + while make() is some(h) { break; } + match make() { + some(h) => {} + else => {} + } + val given: held = match make() { some(h) => h, else => held {} }; + val kept: maybe = held {}; + if kept is some(&h) {} + val tested := kept is some(_) || false; + if make() is not some(h) { return held {}; } + return h; + } + """)); + t.expects(check_noted(6, 19, ec::owned, mini_std, """ + import std; + struct held : owning { var n: i64; } + def held::close(&mut this): void {} + def f(): void { + val kept: maybe = held {}; + if kept is some(h) {} + } + """)); +} + +@test def names_are_given_where_their_test_holds(t: &mut tester): void { + # Wherever the test is known to hold: the right of `&&`, the right of `||` for + # `is not`, through `!`, the branches of an `if` or a `while`, and below a guard, + # with or without an `else`. + t.expects(checks(mini_std, """ + import std; + def f(a: maybe, b: maybe): i64 { + if a is some(x) && x > 3 { return x; } + if a is some(x) && b is some(y) { return x + y; } + while a is some(x) && b is not some(y) { return x; } + val big := b is some(v) && v > 3; + if a is not some(x) || x < 2 { return 0; } else { val y := x; } + if !(b is some(z)) { return x; } else { return z; } + } + """)); + t.expects(check_noted(3, 22, ec::undefined, mini_std, """ + import std; + def f(a: maybe): i64 { + if a is some(x) || x > 3 { return x; } + return 0; + } + """)); + t.expects(check_noted(4, 10, ec::undefined, mini_std, """ + import std; + def f(a: maybe): i64 { + if a is some(x) { return 0; } + return x; + } + """)); +} + +@test def bindings_of_values_can_be_changed(t: &mut tester): void { + # A binding holding a value of its own can be changed and moved from, as a `var` + # can, and so can the variable of a loop. + t.expects(checks(mini_std, """ + import std; + struct handle : owning { var id: i64; } + def handle::close(&mut this): void { this.id = 0; } + def make(): maybe { return handle { id = 1 }; } + def f(): void { + if make() is some(h) { h.id = 2; } + match make() { + some(h) => h.id = 2; + else => {} + } + for n in 0..3 { n += 1; } + } + """)); +} + +@test def branches_copy_nothing_that_closes_out_of_its_place(t: &mut tester): void { + t.expects(check_noted(6, 19, ec::owned, mini_std, """ + import std; + struct held : owning { var n: i64; } + def held::close(&mut this): void {} + def f(flag: bool): void { + val a := held {}; + val b := flag ? a : held {}; + } + """)); + t.expects(check_noted(6, 50, ec::owned, mini_std, """ + import std; + struct held : owning { var n: i64; } + def held::close(&mut this): void {} + def f(flag: bool): void { + val a := held {}; + val c := match flag { true => held {}, else => a }; + } + """)); +} + +@test def conditions_and_branches_read_through_references(t: &mut tester): void { + t.expects(checks(mini_std, """ + import std; + def f(flag: &mut bool, seen: &bool, count: &u32): u32 { + if flag { } + while seen { break; } + val n := flag ? count : 0; + return seen ? n : count; + } + """)); +} + +@test def lockfree_is_decided_by_the_compiler(t: &mut tester): void { + # Integers, `bool`, enums, and pointers are words or less every processor reads + # and writes whole, and a type parameter is where its bounds say so. + t.expects(checks(mini_std, """ + import std; + enum level: u8 { low, high } + def take(value: T): T where T: lockfree { return value; } + def pass(value: T): T where T: lockfree { return take::(value); } + def f(p: *mut i64): void { + val a := take::(1); + val b := take::(-1); + val c := take::(true); + val d := take::(level::high); + val e := take::<*mut i64>(p); + val g := pass::(7); + } + """)); + + # Nothing else is: not a struct, a real, a reference, or a parameter its bounds + # do not say is. + val made := check_program("", """ + import std; + struct pair { var a: i64; var b: i64; } + def take(value: T): T where T: lockfree { return value; } + def bare(value: T): T { return take::(value); } + def f(r: &i64): void { + val a := take::(pair { a = 1, b = 2 }); + val b := take::(1.0); + val c := take::<&i64>(r); + } + """, mini_std); + t.expects(made.notes.length == 4); + for &each in made.notes { + t.expects(each.code == ec::bound); + } +} + +@test def zeroable_is_decided_by_the_compiler(t: &mut tester): void { + t.expects(checks(mini_std, """ + import std; + enum lonely: u8 { one = 1 } + enum level: u8 { low, high } + struct holds { var r: &i64; } + struct plain { var n: i64 = 5; var l: level; var p: *i64; } + def make(): T where T: zeroable { var made: T; return made; } + def passes(): T where T: zeroable { return make::(); } + def zeroes(): bool { if const T is zeroable { var made: T; return true; } return false; } + def guarded(): bool { if const T is not zeroable { return false; } var made: T; return true; } + def counted(): T where T: integer { var made: T; return make::() + made; } + def f(): void { + val p := passes::(); + val a := zeroes::() || zeroes::() || guarded::<&i64>(); + val c := counted::(); + } + """)); + + # A type argument without a zero value is reported where it is given, with + # what in it has none. + val made := check_program("", """ + import std; + enum lonely: u8 { one = 1 } + struct holds { var r: &i64; } + struct outer { var inner: holds; } + def make(): T where T: zeroable { var made: T; return made; } + def bare(): T { var made: T; return made; } + def passes(): T { return make::(); } + def f(): void { + val a := make::(); + val b := make::(); + val c := make::<&i64>(); + } + """, mini_std); + t.expects(made.notes.length == 5); + t.expects(made.notes.length == 5 && made.notes.at(0).line == 6 && made.notes.at(0).code == ec::zero_value); + t.expects(made.notes.length == 5 && made.notes.at(1).line == 7 && made.notes.at(1).code == ec::bound); + t.expects(made.notes.length == 5 && made.notes.at(2).detail.view() + == "`lonely` is not `zeroable`, which `T` of `make` requires: no member of `lonely` has the value 0."); + t.expects(made.notes.length == 5 && made.notes.at(3).detail.view() + == "`outer` is not `zeroable`, which `T` of `make` requires: its field `inner.r` holds `&int`, which has no zero value."); + t.expects(made.notes.length == 5 && made.notes.at(4).detail.view() + == "`&int` is not `zeroable`, which `T` of `make` requires: a reference has no zero value."); + + # `equatable` and `ordinal` give no zero value: a struct holding a reference + # may be equatable, and an enum without a member of value 0 is ordinal. + t.expects(check_noted(2, 44, ec::zero_value, mini_std, "import std;\ndef equal(): T where T: equatable { var made: T; return made; }")); + t.expects(check_noted(2, 48, ec::zero_value, mini_std, "import std;\ndef ordered_one(): T where T: ordered { var made: T; return made; }")); + t.expects(check_noted(2, 48, ec::zero_value, mini_std, "import std;\ndef ordinal_one(): T where T: ordinal { var made: T; return made; }")); +} + +@test def traits_nest_in_types(t: &mut tester): void { + t.expects(checks(mini_std, """ + import std; + def shown(x: &T): i64 where T: ns::shows { return x.show(); } + struct point : ns::shows, ns::ranked { var x: i64; } + def point::show(&this): i64 { return this.x; } + def point::compare(&this, other: &point): i64 { return this.x - other.x; } + struct ns {} + trait ns::shows { def show(&this): i64; } + trait ns::ranked { def compare(&this, other: &self): i64; } + struct bag { var items: T[2]; } + trait bag::visitor { def visit(&mut this, item: &T): void; } + def bag::walk(&this, v: &mut bag::visitor): void { v.visit(&this.items[0]); } + struct summer : bag::visitor { var total: i64; } + def summer::visit(&mut this, item: &i64): void { this.total += item; } + def use(p: &point): i64 { + val r: &ns::shows = p; + val b := bag::{ items = [1, 2] }; + var s := summer{ total = 0 }; + b.walk(&mut s); + return shown(p) + r.show(); + } + """)); + t.expects(check_noted(4, 8, ec::bound, mini_std, """ + import std; + struct ns {} + trait ns::shows { def show(&this): i64; } + struct quiet : ns::shows { var x: i64; } + def need(x: &T): void where T: ns::nope {} + """)); + t.expects(check_noted(5, 39, ec::undefined, mini_std, """ + import std; + struct ns {} + trait ns::shows { def show(&this): i64; } + struct quiet : ns::shows { var x: i64; } + def need(x: &T): void where T: ns::nope {} + """)); +} + +@test def members_reached_through_bounds_need_no_pub(t: &mut tester): void { + val lib := """ + import std; + module lib; + pub trait sink { def text(&mut this, value: span): void; } + pub def through_bound(out: &mut W): void where W: sink { out.text("bound"); } + pub struct quiet { pub var said: u64; } + def quiet::text(&mut this, value: span): void { this.said += value.length; } + """; + t.expects(checks(""" + import std; + import lib; + struct shout { var said: u64; } + def shout::text(&mut this, value: span): void { this.said += value.length; } + def f(): void { + var s := shout{ said = 0 }; + var q := quiet{ said = 0 }; + through_bound(&mut s); + through_bound(&mut q); + } + """, mini_std, lib)); + + # Naming the method from another module still needs `pub`. + t.expects(check_noted(3, 47, ec::hidden, """ + import std; + import lib; + def f(): void { var q := quiet{ said = 0 }; q.text("x"); } + """, mini_std, lib)); +} + +@test def a_module_comes_before_a_type_of_its_name(t: &mut tester): void { + # `kit::make` names the module where `kit` is also a type the module declares, + # as `serial::encode` does. + t.expects(checks(""" + import std; + import kit; + def f(): i64 { val made: kit::count = kit::make(); return made + kit::make(); } + """, mini_std, """ + module kit; + pub struct kit { var n: i64; } + pub type count = i64; + pub def make(): count { return 1; } + """)); +} + +@test def a_guard_that_ends_in_compile_error_narrows_what_follows(t: &mut tester): void { + val reports := """ + module std; module core; + pub trait attribute {} + pub struct intrinsic : attribute {} + @intrinsic pub def compile_error(text: span): void; + """; + + # What follows the guard has the bound it tests, given its arguments. + t.expects(checks(mini_std, reports, """ + import std; + trait shows { def show(&this): T; } + def first(k: &K): i64 { + if const !(K is shows) { + compile_error("A key shows itself."); + } + return k.show(); + } + def second(k: &K): i64 { + if const K is shows { + return k.show(); + } + return 0; + } + """)); +} + +@test def an_alias_satisfies_traits_through_what_it_aliases(t: &mut tester): void { + # `boxed` is `box`, whose `equals` takes a `&box`, which is a `&boxed`. + t.expects(checks(mini_std, """ + import std; + struct box { var item: T; } + def box::equals(&this, other: &box): bool { return true; } + type boxed = box; + def same(a: &T, b: &T): bool where T: equatable { return a == b; } + def f(x: &boxed): bool { return same(x, x); } + """)); +} + +@test def a_slice_writes_its_elements_however_it_is_held(t: &mut tester): void { + # A slice made where it is indexed is no place, but what it views is written + # through it, as through a `*mut` pointer. + t.expects(checks(mini_std, """ + module std; module core; + pub struct slice { var data: *mut T; var count: u64; } + pub def slice::over(data: *mut T, count: u64): slice { return slice { data = data, count = count }; } + pub def slice::at(&this, index: u64): &T { return &this.data[index]; } + pub def slice::at(&mut this, index: u64): &mut T { return &mut this.data[index]; } + """, """ + import std; + def f(p: *mut i64): &mut i64 { + slice::::over(p, 1)[0] = 5; + return &mut slice::::over(p, 1)[0]; + } + """)); +} + +@test def each_instance_is_checked_with_its_types(t: &mut tester): void { + val made := check_program("", """ + import std; + def small(x: T): T where T: numeric { return x + 300; } + def f(): void { + val a := small(1); + val b := small::(1); + } + """, mini_std); + t.expects(made.notes.length == 1); + t.expects(made.notes.length == 1 && made.notes.at(0).code == ec::overflow); + t.expects(made.notes.length == 1 && made.notes.at(0).instance.view() == "In `small`"); +} + +@test def types_satisfy_traits_by_their_shape(t: &mut tester): void { + t.expects(checks(""" + trait shown { def show(&this): i64; } + struct a {} + def a::show(&this): i64 { return 1; } + def print(s: &shown): i64 { return s.show(); } + def f(): void { val x := print(a{}); } + """)); + t.expects(check_noted(2, 8, ec::bound, """ + trait shown { def show(&this): i64; } + struct b : shown {} + def b::show(&this): bool { return true; } + """)); + t.expects(checks(mini_std, """ + import std; + struct v : equatable { var x: i64; } + def v::equals(&this, other: &v): bool { return this.x == other.x; } + def f(a: v, b: v): bool { return a == b; } + """)); + t.expects(check_noted(3, 36, ec::operands, mini_std, """ + import std; + struct v { var x: i64; } + def f(a: v, b: v): bool { return a == b; } + """)); +} + +@test def if_const_proves_bounds_for_its_branch(t: &mut tester): void { + t.expects(checks(mini_std, """ + import std; + def finish(x: &mut T): void { + if const T is owning { + x.close(); + } + } + def tell(x: &T): i64 { + return 0 if const T is not owning; + return 1; + } + """)); +} + +@test def loops_walk_ranges_arrays_and_iterators(t: &mut tester): void { + t.expects(local_type("x", "def f(): void { for i in 0..3u { val x := i; } }").view() == "uint"); + t.expects(local_type("x", "def f(a: i64[4]): void { for &e in a { val x := &e; } }").view() == "&int"); + t.expects(local_type("x", "def f(a: i64[4]): void { for e in a { val x := e; } }").view() == "int"); + t.expects(local_type("x", "def f(a: i64[4]): void { for i, e in a { val x := i; } }").view() == "uint"); + t.expects(checks(mini_std, "import std;\ndef f(s: span): void { for b in s { val c: u8 = b; } }")); + t.expects(check_noted(1, 32, ec::member, "def f(n: i64): void { for x in n { } }")); +} + +@test def fallbacks_take_what_a_result_or_maybe_holds(t: &mut tester): void { + t.expects(checks(mini_std, """ + import std; + def parse(): result { return 5; } + def find(): maybe { return 1; } + def f(): i64 { + val a := parse() else 0; + val b := find() else { return 0; }; + val c := parse() else (e) { return e as i64; }; + return a + b + c; + } + """)); + t.expects(check_noted(3, 38, ec::control, mini_std, """ + import std; + def find(): maybe { return 1; } + def f(): void { val b := find() else { val x := 1; }; } + """)); +} + +@test def modules_see_their_own_and_what_is_pub(t: &mut tester): void { + val geometry := """ + module geometry; + pub struct rect { pub var w: f64; } + def hidden(): i64 { return 1; } + pub def area(r: &rect): f64 { return r.w; } + """; + t.expects(checks("import geometry;\ndef f(): void { val r := rect{ w = 1.0 }; val a := area(r); }", geometry)); + t.expects(checks("def f(): void { val r := geometry::rect{ w = 1.0 }; val a := geometry::area(r); }", geometry)); + t.expects(check_noted(2, 26, ec::hidden, "import geometry;\ndef f(): void { val h := hidden(); }", geometry)); + t.expects(check_noted(1, 1, ec::undefined, "import nowhere;")); + t.expects(checks(""" + module inner; + def helper(): i64 { return 1; } + module inner::deeper; + def use(): i64 { return helper(); } + """)); +} + +@test def no_module_is_within_the_program(t: &mut tester): void { + # The files declaring no module are the program, which holds no module, so + # what a module names comes from it, the modules holding it, and its imports. + val tools := "module tools;\npub def scratch(): u32 { return 1; }"; + t.expects(checks( + "import tools;\nmodule user;\ndef f(): u32 { return scratch(); }", + "struct scratch { var at: u32; }", + tools)); + t.expects(checks( + "import tools;\nmodule user::inner;\ndef f(): u32 { return scratch(); }", + "struct scratch { var at: u32; }", + tools)); + t.expects(check_noted(2, 23, ec::undefined, + "module user;\ndef f(): u32 { return rooted(); }", + "def rooted(): u32 { return 2; }")); +} + +@test def fields_are_private_unless_pub(t: &mut tester): void { + val geometry := """ + module geometry; + pub struct point { pub var x: i64; var y: i64; } + pub union shape { pub var dot: point; var blob: u8; } + pub struct base { pub var w: i64; } + pub struct framed { pub var b: ...base; } + pub struct hidden { var b: ...base; } + pub def origin(): point { return point { x = 0, y = 0 }; } + pub def y_of(p: &point): i64 { return p.y; } + module geometry::inner; + def deeper(p: &point): i64 { return p.y; } + """; + t.expects(checks(""" + import geometry; + def f(): i64 { + val p := point { x = 1 }; + val q := origin(); + val r := framed {}; + return p.x + q.x + r.w + y_of(&q); + } + """, geometry)); + t.expects(check_noted(2, 44, ec::hidden, "import geometry;\ndef f(): i64 { val p := origin(); return p.y; }", geometry)); + t.expects(check_noted(2, 41, ec::hidden, "import geometry;\ndef f(): void { val p := point { x = 1, y = 2 }; }", geometry)); + t.expects(check_noted(2, 37, ec::hidden, "import geometry;\ndef f(): void { val p := point { 1, 2 }; }", geometry)); + t.expects(check_noted(2, 37, ec::hidden, "import geometry;\ndef f(s: shape): bool { return s is blob; }", geometry)); + t.expects(check_noted(2, 35, ec::hidden, "import geometry;\ndef f(h: &hidden): i64 { return h.w; }", geometry)); +} + +@test def a_field_and_a_type_through_its_type_share_a_name(t: &mut tester): void { + t.expects(checks(""" + struct token { var kind: token::kind; } + enum token::kind { word, number } + def f(t: &token): bool { return t.kind == token::kind::word; } + """)); + t.expects(checks(""" + enum token::kind { word, number } + struct token { val kind: token::kind; } + def f(): token { return token { kind = token::kind::number }; } + """)); + + # Only a field shares its name with a type, since a method is reached through + # a value as a field is. + t.expects(check_noted(3, 13, ec::duplicate, """ + struct token { var at: u64; } + def token::kind(&this): u64 { return this.at; } + enum token::kind { word } + """)); + t.expects(check_noted(3, 37, ec::member, """ + struct token { var at: u64; } + enum token::kind { word } + def f(t: &token): void { val k := t.kind; } + """)); +} + +@test def a_type_names_its_own_without_them(t: &mut tester): void { + t.expects(checks(""" + struct token { var genus: kind; var at: span; } + enum token::kind { word, number } + struct token::span { var start: u64; var end: u64; } + val token::none: kind = kind::word; + def token::matches(&this, k: kind): bool { return this.genus == k && k != none; } + def token::kind::is_word(&this): bool { return this == word; } + def token::width(&this): u64 { val s: span = this.at; return s.end - s.start; } + def f(t: &token): bool { return t.matches(token::kind::number) && t.genus.is_word(); } + """)); + + # A generic type gives what is nested in it its arguments. + t.expects(local_type("n", """ + struct list { var head: *node; } + struct list::node { var value: T; } + def list::first(&this): T { val n: node = this.head[0]; return n.value; } + def f(l: &list): i64 { return l.first(); } + """).view() == "node"); + + # Only types are meant in a type, so an enum's member `u8` leaves `u8` the type. + t.expects(checks(""" + enum width { u8, u16 } + def width::bytes(&this): u8 { val one: u8 = 1; return this == u8 ? one : one + one; } + """)); + + # A type's functions are named through it, since they are often named for the + # free functions they implement. + t.expects(check_noted(3, 36, ec::undefined, """ + struct token { var at: u64; } + def token::make(): token { return token {}; } + def token::again(): token { return make(); } + """)); +} + +@test def a_name_a_type_and_its_module_both_give_is_ambiguous(t: &mut tester): void { + t.expects(check_noted(2, 27, ec::ambiguous, """ + enum kind { a } + struct token { var genus: kind; } + enum token::kind { b } + """)); + t.expects(check_noted(3, 21, ec::ambiguous, """ + module shapes; + enum kind { a } + struct box { var k: kind; } + enum box::kind { b } + """)); + t.expects(checks(""" + module shapes; + enum kind { a } + struct box { var k: box::kind; var other: shapes::kind; } + enum box::kind { b } + """)); + + # A name of the module shadows those imports give, and a type's does too. + t.expects(checks(""" + import lib; + struct token { var genus: kind; } + enum token::kind { b } + def f(t: &token): bool { return t.genus == token::kind::b; } + """, "module lib;\npub enum kind { a }")); +} + +@test def when_keeps_what_the_target_takes(t: &mut tester): void { + t.expects(checks(""" + when os == linux { def home(): i64 { return 1; } } + else { def home(): bool { return true; } } + def f(): void { val h: i64 = home(); } + """)); + t.expects(check_noted(1, 12, ec::invalid, "when os == lynx { }")); + t.expects(checks("def f(): i64 { when backend == vm { return 1; } else { return nope; } }")); +} + +#! A standard library giving what C's declarations use: `cfn`. +const c_std: strview = """ + module std; module core; + pub trait attribute {} + pub struct intrinsic : attribute {} + @intrinsic pub struct cfn {} + """; + +@test def extern_sections_declare_what_c_gives(t: &mut tester): void { + # A section's functions with no body, structs, and unions are C's, and the + # rest is the module's own. A function of the program is given where C's + # address of one is expected. + t.expects(checks(""" + import std; + extern import "libc.so.6" when os == linux; + def compare(a: *u8, b: *u8): i32 { return 0; } + def sorted(xs: *mut u8): i32 { + c::qsort(xs, 1, 4, compare); + val order: cfn = compare; + val q := c::div(7, 2); + return c::twice(q.quot); + } + extern module c when os == linux; + pub struct quotient { pub var quot: i32; pub var rem: i32; } + pub union bits { pub var whole: u32; pub var real: f32; } + pub def div(a: i32, b: i32): quotient; + pub def qsort(base: *mut u8, count: u64, size: u64, order: cfn): void; + pub def twice(x: i32): i32 { return x * 2; } + """, c_std)); + # A section says which systems it is for. + t.expects(check_noted(1, 1, ec::invalid, "extern module c;\npub def f(): void;", c_std)); + t.expects(check_noted(1, 1, ec::invalid, "extern module c when backend == native;\npub def f(): void;", c_std)); + # A function with no body is C's only in a section, and never generic there. + t.expects(check_noted(1, 5, ec::invalid, "def f(): void;", c_std)); + t.expects(check_noted(2, 9, ec::invalid, "extern module c when os == linux;\npub def f(x: T): T;", c_std)); + # A section's struct holds only what crosses to C. + t.expects(check_noted(2, 24, ec::invalid, "extern module c when os == linux;\npub struct s { pub var r: &i32; }", c_std)); + # A C union holds no tag, so `is` can't ask which field it holds. + t.expects(check_noted(1, 39, ec::invalid, + "def f(b: c::bits): bool { return b is whole; }\nextern module c when os == linux;\npub union bits { pub var whole: u32; pub var real: f32; }", c_std)); + # C calls back a function by its name, not a lambda. + t.expects(check_noted(2, 47, ec::invalid, + "import std;\ndef f(xs: *mut u8): void { c::qsort(xs, 1, 4, def(a: *u8, b: *u8): i32 => 0); }\nextern module c when os == linux;\npub def qsort(base: *mut u8, count: u64, size: u64, order: cfn): void;", c_std)); + # A library nothing in its file uses is warned of. + t.expects(check_noted(1, 1, ec::invalid, "extern import \"libm.so.6\";\ndef f(): void {}", c_std)); + # The attributes C was declared with before say where it is declared now, once. + t.expects(check_noted(1, 1, ec::invalid, "@foreign def f(): void {}", c_std)); + t.expects(note_count("@foreign def f(): void {}", c_std) == 1); +} + +@test def declarations_that_depend_on_themselves_are_reported(t: &mut tester): void { + t.expects(check_noted(1, 7, ec::cycle, "const a: i64 = b;\nconst b: i64 = a;")); + t.expects(check_noted(1, 6, ec::cycle, "type loop = loop;")); + t.expects(checks("enum e { a = 1, b = e::a }")); +} + +@test def notes_point_at_what_they_relate_to(t: &mut tester): void { + val made := check_program("", "val a := 1;\n\nval a := 2;"); + t.expects(made.notes.length == 1 && made.notes.at(0).line == 3 && made.notes.at(0).related == 1); +} + +@test def what_is_not_checked_yet_is_counted(t: &mut tester): void { + val made := check_program("", "def f(): void { val x: type_of(f) = 1; }"); + t.expects(made.notes.length == 0 && made.skipped == 1); +} + +@test def traits_that_name_self_are_only_bounds(t: &mut tester): void { + t.expects(check_noted(2, 11, ec::not_type, "trait cloneable { def clone(&this): self; }\ndef f(c: &cloneable): void {}")); + t.expects(checks("trait shown { def show(&this): i64; }\ndef f(s: &shown): i64 { return s.show(); }")); + t.expects(check_noted(2, 24, ec::not_type, "trait shown { def show(&this): i64; }\ndef f(): void { val s: shown; }")); + # `void` is a value's type, unlike a trait, of its one value. + t.expects(checks("def f(): void { val v: void; }")); +} + +@test def defaults_of_a_bound_are_compiled_for_each_type(t: &mut tester): void { + # A trait only a bound gives defaults compiled for each type implementing it, + # generic ones too, and a default may ask more of the trait's parameters or of + # `self`, which only the types meeting it have. + t.expects(checks(mini_std, ranges_std, """ + import std; + trait shelf { + def get(&this, at: u64): T; + def first(&this): T { return this.get(0); } + def pick(&this, at: u64, f: F): U where F: invokable { return f(this.get(at)); } + def total(&this): T where T: numeric { return this.get(0) + this.get(1); } + def tagged(&this): u64 where self: labeled { return this.label(); } + } + trait labeled { def label(&this): u64; } + struct trio : shelf, labeled { var items: i64[3]; } + def trio::get(&this, at: u64): i64 { return this.items[at]; } + def trio::label(&this): u64 { return 3; } + def sum(s: &S): i64 where S: shelf { return s.first() + s.total(); } + def f(): void { + val t := trio { items = [1, 2, 3] }; + val a: i64 = t.first() + t.total() + sum(&t); + val b: u64 = t.pick(1, def(x) => x as u64) + t.tagged(); + } + """)); + + # A type not meeting what a default asks does not have it, and the trait, + # having one compiled for each type, is no type of a reference. + val unmet := """ + import std; + trait shelf { + def get(&this, at: u64): T; + def total(&this): T where T: numeric { return this.get(0) + this.get(1); } + def tagged(&this): u64 where self: labeled { return this.label(); } + } + trait labeled { def label(&this): u64; } + struct words : shelf { var a: strview; } + def words::get(&this, at: u64): strview { return this.a; } + def use(s: &shelf): void {} + def main(): void { + val w := words { a = "x" }; + val a := w.total(); + val b := w.tagged(); + } + """; + t.expects(check_noted(10, 13, ec::not_type, mini_std, ranges_std, unmet)); + t.expects(check_noted(13, 14, ec::bound, mini_std, ranges_std, unmet)); + t.expects(check_noted(14, 14, ec::bound, mini_std, ranges_std, unmet)); +} + +@test def methods_exist_where_their_bounds_hold(t: &mut tester): void { + # A method bounding its type's parameters belongs to the instances meeting + # them, which then satisfy a trait asking for it. + t.expects(checks(mini_std, ranges_std, """ + import std; + struct holder { var held: T; } + def holder::doubled(&this): T where T: numeric { return this.held + this.held; } + def holder::get(&this): T { return this.held; } + trait doubles { def doubled(&this): T; } + def twice(h: &H): i64 where H: doubles { return h.doubled(); } + def f(): void { + val h := holder:: { held = 2 }; + val a: i64 = h.doubled() + twice(&h); + val w := holder:: { held = "w" }; + val b: strview = w.get(); + } + """)); + + val unmet := """ + import std; + struct holder { var held: T; } + def holder::doubled(&this): T where T: numeric { return this.held + this.held; } + trait doubles { def doubled(&this): T; } + def twice(h: &H): strview where H: doubles { return h.doubled(); } + def f(): void { + val w := holder:: { held = "w" }; + val a := w.doubled(); + val b := twice(&w); + } + """; + t.expects(check_noted(8, 14, ec::bound, mini_std, ranges_std, unmet)); + t.expects(check_noted(9, 12, ec::bound, mini_std, ranges_std, unmet)); +} + +@test def lambdas_take_their_types_from_bounds(t: &mut tester): void { + # An anonymous function given for a parameter bounded by `invokable` takes + # the types it leaves out from the bound. + t.expects(checks(mini_std, ranges_std, """ + import std; + def apply(x: i64, f: F): i64 where F: invokable { return f(x); } + def both(f: F): bool where F: invokable { val s: strview = "ab"; return f(&s, 2); } + def f(): void { + val a: i64 = apply(3, def(x) => x + 1); + val b: bool = both(def(s, n) => s.length == n as u64); + val c: i64 = apply(4, def(x) { return x * 2; }); + } + """)); + + # Where nothing gives a parameter's type, it is written. + val untyped := """ + import std; + def apply(x: i64, f: F): i64 where F: invokable { return f(x); } + def keep(f: F): void {} + def f(): void { + keep(def(x) => x); + val a := apply(3, def(x) => x.length); + val b := apply(3, def(x, y) => x); + } + """; + t.expects(check_noted(5, 12, ec::mismatch, mini_std, ranges_std, untyped)); + t.expects(check_noted(6, 33, ec::member, mini_std, ranges_std, untyped)); + t.expects(check_noted(7, 28, ec::mismatch, mini_std, ranges_std, untyped)); + + # Within a generic, its own parameters are known, so the bound gives them too. + t.expects(checks(mini_std, ranges_std, """ + import std; + struct box { var held: T; } + def apply(b: &box, f: F): U where F: invokable): U> { return f(b); } + def f(b: &box): T { return apply(b, def(x) => x.held); } + """)); +} + +@test def properties_and_methods_of_generic_types_are_values(t: &mut tester): void { + # A property named as a value is its `get`, a function of `&this`. A method or + # property of a generic type named without its type arguments takes them from + # the function type expected, or a parameter's `invokable` bound. + t.expects(checks(mini_std, ranges_std, """ + import std; + struct rect { var w: f32; var h: f32; } + val rect::area: f32 { get => this.w * this.h; } + var rect::width: f32 { get => this.w; set => this.w = value; } + struct box { var held: T; } + val box::inner: T { get => this.held; } + def box::peek(&this): T { return this.held; } + def apply(r: &rect, f: F): f32 where F: invokable { return f(r); } + def look(b: &box, f: F): i64 where F: invokable): i64> { return f(b); } + def f(): i64 { + val r := rect { w = 3, h = 4 }; + val area: def(&rect): f32 = rect::area; + val width: def(&rect): f32 = rect::width; + val a := apply(&r, rect::area) + area(&r) + width(&r); + val b := box:: { held = 5 }; + val inner: def(&box): i64 = box::inner; + val peek: def(&box): i64 = box::peek; + return look(&b, box::inner) + look(&b, box::peek) + look(&b, box::::inner) + inner(&b) + peek(&b); + } + def g(b: &box): T { + val inner: def(&box): T = box::inner; + return inner(b); + } + """)); + + # A generic function whose type arguments neither the function type expected + # nor anything else gives is named with them. + val unwritten := """ + import std; + struct maker {} + def maker::make(x: i64): i64 { return x; } + def apply(f: F): i64 where F: invokable { return f(1); } + def f(): i64 { return apply(maker::make); } + """; + t.expects(check_noted(5, 29, ec::generic, mini_std, ranges_std, unwritten)); +} + +@test def if_const_names_the_type_a_parameter_is(t: &mut tester): void { + # Where `if const` says a type parameter is a type, the branch names that type + # by the parameter's name, and each instance taking the branch checks it with + # the parameter that type. + t.expects(checks(mini_std, ranges_std, """ + import std; + struct box { var held: T; } + def pick(x: T): i64 { + if const T is i64 { + val n: i64 = x; + val b: box = box:: { held = n }; + return b.held; + } + return 0 if const T is not bool; + return 1; + } + def f(): i64 { return pick(5) + pick(true) + pick(2u); } + """)); + + # What is wrong there is noted by the instances taking it. + val wrong := """ + import std; + def pick(x: T): i64 { + if const T is bool { + val n: i64 = x; + return n; + } + return 0; + } + def f(): i64 { return pick(true) + pick(3); } + """; + val made := check_program("", mini_std, ranges_std, wrong); + t.expects(made.notes.length == 1 && made.notes.at(0).line == 4 && made.notes.at(0).code == ec::mismatch); +} + +@test def references_never_stack_and_bindings_take_values(t: &mut tester): void { + # `&` of a reference is that reference, wherever it is held, and `&mut` of one + # writes where it does. Inference, like a binding, takes the value a reference + # reaches unless `&` is written, and a reference to a trait is taken as it is. + val lending := """ + struct point { var x: i64; } + def larger(a: T, b: T): T { return a; } + def f(r: &mut point, s: &point, v: &mut i64[4]): void { + val again := &r; + val writes := &mut r; + val read := &s; + val copied := r; + val big := larger(v[0], v[1]); + val lent := &larger(&v[0], &v[1]); + val given := larger(&v[0], &v[1]); + } + """; + t.expects(local_type("again", lending).view() == "&point"); + t.expects(local_type("writes", lending).view() == "&mut point"); + t.expects(local_type("read", lending).view() == "&point"); + t.expects(local_type("copied", lending).view() == "point"); + t.expects(local_type("big", lending).view() == "int"); + t.expects(local_type("lent", lending).view() == "&int"); + t.expects(local_type("given", lending).view() == "int"); + t.expects(check_noted(1, 33, ec::assignable, "def f(s: &i64): void { val w := &mut s; }")); + t.expects(checks(mini_std, """ + import std; + trait shown { def show(&this): i64; } + struct dot : shown { var n: i64; } + def dot::show(&this): i64 { return this.n; } + def f(d: &mut dot, m: maybe<&mut shown>): i64 { + val as_trait: &shown = d; + val kept := as_trait; + if m is some(held) { return held.show() + kept.show(); } + return kept.show(); + } + """)); + + # A pattern copies what a field holding a reference reaches, and `&` or + # `&mut` names the reference. + val payload := """ + union slot { var none: u8; var some: &mut i64; } + def f(m: slot): void { + if m is some(n) { val copy := n; } + if m is some(&mut w) { val lent := &mut w; } + } + """; + t.expects(local_type("copy", payload).view() == "int"); + t.expects(local_type("lent", payload).view() == "&mut int"); + + # A reference written as one is a pointer where one is expected, but nothing + # else is, and a pointer keeps no value alive past its statement. + t.expects(checks("def look(p: *i64): i64 { return p[0]; }\ndef f(): void { var x: i64 = 1; val p: *mut i64 = &mut x; val q: *i64 = &x; val n := look(&x) + look(&2); }")); + t.expects(check_noted(2, 38, ec::mismatch, "def look(p: *i64): i64 { return p[0]; }\ndef f(): void { var x: i64 = 1; look(x); }")); + t.expects(check_noted(1, 31, ec::invalid, "def f(): void { val p: *i64 = &10; }")); + t.expects(check_noted(1, 51, ec::mismatch, "def f(): void { val x: i64 = 1; val p: *mut i64 = &x; }")); +} + +@test def named_functions_are_called_as_the_type_asks(t: &mut tester): void { + # A named function given where a function type it doesn't match is expected + # is called as that type asks: each parameter given as a call gives it, the + # rest taking their defaults, and among overloads the one such a call chooses. + t.expects(checks(""" + def doubled(x: &i64): i64 { return x * 2; } + def tripled(x: i64): i64 { return x * 3; } + def scaled(x: i64, by: i64 = 10): i64 { return x * by; } + def shown(x: &i64): i64 { return x; } + def shown(x: &f64): i64 { return 0; } + def f(): void { + val a: def(i64): i64 = doubled; + val b: def(&i64): i64 = tripled; + val d: def(i64): i64 = scaled; + val e: def(i64): i64 = shown; + } + """)); + # A value that closes is never copied out of what a reference reaches, so a + # function taking one is not called with what a `&` parameter gives. + val owned := """ + import std; + struct held : owning { var n: i64; } + def held::close(&mut this): void {} + def keep(h: held): i64 { return h.n; } + def f(): void { val g: def(&held): i64 = keep; } + """; + t.expects(check_noted(5, 42, ec::mismatch, owned, mini_std)); + + # Between `&` and `&mut` parameters, what can be written is lent to `&mut`. + val picked := """ + def pick(v: &mut i64): i64 { return 1; } + def pick(v: &i64): bool { return true; } + def f(): void { var a: i64 = 1; val b: i64 = 2; val x := pick(a); val y := pick(b); } + """; + t.expects(local_type("x", picked).view() == "int"); + t.expects(local_type("y", picked).view() == "bool"); +} + +@test def ranges_are_values(t: &mut tester): void { + # `a..b` and `a..=b` are std's `range` of the integers their ends are, or of + # what is expected of them, as an `iterator` bound expects a + # `range`. A local of the name is no type. + t.expects(checks(mini_std, ranges_std, """ + import std; + def total(r: range): u64 { var t: u64 = 0; for x in r { t += x; } return t; } + def count(it: I): u64 where I: iterator { return 0; } + def f(): void { + val r := 0..10; + val s: range = 1..=255; + val a: u64 = total(1..=4) + count(2..6); + for i in 0..=3 { val j: int = i; } + val range: maybe = 3; + if range is some(x) { val y: i64 = x; } + } + """)); + + # Members of one enum make a range of its members, and a type parameter + # bounded by `integer` or `ordinal` a range of what it is. + t.expects(checks(mini_std, ranges_std, """ + import std; + enum color { red, green = 4, blue } + def walk(a: T, b: T): void where T: integer { for i in a..b { val j: T = i; } val r := a..=b; } + def step(a: T, b: T): void where T: ordinal { for i in a..b { val j: T = i; } val r: range = a..=b; } + def f(): void { + val r := color::red..=color::blue; + val s: range = color::red..color::green; + for c in color::red..color::blue { val d: color = c; } + walk(1, 4); + step(color::green, color::blue); + } + """)); + val mixed := """ + import std; + enum color { red, green } + enum level { low, high } + def f(): void { + val a := color::red..level::high; + val b := color::red..1; + } + """; + t.expects(check_noted(5, 12, ec::operands, mini_std, ranges_std, mixed)); + t.expects(check_noted(6, 12, ec::operands, mini_std, ranges_std, mixed)); + + val wrong := """ + import std; + def f(): void { + val a := 1.5..2.5; + val s: strview = "x"; + val b := 0..s; + for i in 0..=true {} + val c: range = 0..300; + } + """; + t.expects(check_noted(3, 12, ec::operands, mini_std, ranges_std, wrong)); + t.expects(check_noted(5, 12, ec::operands, mini_std, ranges_std, wrong)); + t.expects(check_noted(6, 12, ec::operands, mini_std, ranges_std, wrong)); + t.expects(check_noted(7, 25, ec::overflow, mini_std, ranges_std, wrong)); +} + +@test def a_struct_holds_itself_only_through_a_pointer(t: &mut tester): void { + t.expects(check_noted(1, 8, ec::recursive, "struct node { var next: node; }")); + t.expects(check_noted(1, 7, ec::recursive, "union tree { var leaf: i64; var both: tree[2]; }")); + t.expects(checks("struct node { var next: *node; }\nunion tree { var leaf: i64; var both: &tree; }")); +} + +@test def overloads_differ_in_their_parameters(t: &mut tester): void { + t.expects(check_noted(2, 5, ec::duplicate, "def f(a: i64): void {}\ndef f(b: i64): void {}")); + t.expects(checks("def f(a: i64): void {}\ndef f(a: u8): void {}\nstruct v {}\ndef v::g(&this): void {}\ndef v::g(&mut this): void {}")); +} + +@test def what_is_nodiscard_is_handled(t: &mut tester): void { + val shared := "module std; module core;\npub trait attribute {}\npub struct nodiscard : attribute {}"; + t.expects(check_noted(3, 21, ec::unhandled, shared, "import std;\n@nodiscard def must(): i64 { return 1; }\ndef f(): void { must(); }")); + t.expects(checks(shared, "import std;\n@nodiscard def must(): i64 { return 1; }\ndef f(): void { _ = must(); val x := must(); }")); +} + +@test def what_is_inline_has_a_body_to_copy(t: &mut tester): void { + val shared := """ + module std; module core; + pub trait attribute {} + pub enum target : u32 { functions = 1, methods = 2, structs = 32, requirements = 0x400, properties = 0x1000, all = 0xFFFF } + pub struct usage : attribute { pub val on: u32 = target::all; pub val many: bool = false; } + pub struct intrinsic : attribute {} + @usage{ on = target::functions | target::methods | target::properties } + pub struct inline : attribute {} + """; + # A function, a method, and a property, whose accessors it marks, are copied + # where they are called. + val program := """ + import std; + struct p { var x: i64; } + @inline def twice(x: i64): i64 { return x * 2; } + @inline def p::sum(&this): i64 { return this.x; } + @inline val p::doubled: i64 { get => this.x * 2; } + def f(q: p): i64 { return twice(q.sum()) + q.doubled; } + """; + t.expects(checks(shared, program)); + + # What C or the compiler gives has no body to copy, and neither a struct nor + # what a trait asks for is a function of its own. + t.expects(check_noted(2, 1, ec::invalid, shared, "import std;\n@inline @intrinsic def given(): u64;")); + t.expects(check_noted(2, 1, ec::invalid, shared, "extern module c when os == linux;\n@inline pub def puts(text: *u8): i32;")); + t.expects(checks(shared, "extern module c when os == linux;\n@inline pub def twice(x: i32): i32 { return x * 2; }")); + t.expects(check_noted(2, 1, ec::invalid, shared, "import std;\n@inline struct s {}")); + t.expects(check_noted(2, 15, ec::invalid, shared, "import std;\ntrait shape { @inline def area(&this): i64; }")); +} + +@test def a_value_that_closes_has_one_owner(t: &mut tester): void { + val shared := """ + import std; + struct file : owning { var fd: i64; } + def file::close(&mut this): void {} + def take(f: file): void {} + def open(): file { val made := file{ fd = 1 }; return made; } + """; + t.expects(checks(mini_std, shared, "import std;\ndef f(): void { var a := open(); take(open()); take(move_out(&mut a)); }\ndef move_out(f: &mut file): file { return file{ fd = f.fd }; }")); + t.expects(check_noted(2, 43, ec::owned, mini_std, shared, "import std;\ndef f(): void { var a := open(); val b := a; }")); + t.expects(check_noted(2, 39, ec::owned, mini_std, shared, "import std;\ndef f(): void { var a := open(); take(a); }")); + + # What a reference refers to still has its owner, and so does a field. A `return` + # hands over a local it names, and what a pointer points at. + t.expects(check_noted(2, 30, ec::owned, mini_std, shared, "import std;\ndef f(r: &file): void { take(r); }")); + t.expects(check_noted(2, 32, ec::owned, mini_std, shared, "import std;\ndef f(r: &file): file { return r; }")); + t.expects(check_noted(3, 42, ec::owned, mini_std, shared, "import std;\nstruct box { var f: file; }\ndef box::take(&this): file { return this.f; }")); + t.expects(checks(mini_std, shared, "import std;\ndef f(p: *file): file { return p[0]; }\ndef g(r: &file): &file { return r; }")); +} + +@test def what_a_loop_iterates_is_locked(t: &mut tester): void { + t.expects(check_noted(1, 49, ec::locked, "def f(): void { var xs: i64[3]; for x in xs { xs[0] = x; } }")); + t.expects(checks("def f(): void { var xs: i64[3]; for &mut x in xs { x += 1; } }")); +} + +@test def attributes_are_checked_where_they_are_written(t: &mut tester): void { + val shared := """ + module std; module core; + pub trait attribute {} + pub enum target : u32 { functions = 1, methods = 2, constants = 4, structs = 32, all = 0xFFFF } + pub struct usage : attribute { pub val on: u32 = target::all; pub val many: bool = false; } + """; + val program := """ + import std; + @usage{ on = target::functions | target::constants } + struct test : attribute { val skip: bool = false; } + struct plain { var x: i64 = 0; } + @test def a(): void {} + @test{ skip = true } def b(): void {} + @test struct wrong {} + @plain def c(): void {} + @test @test def d(): void {} + """; + val made := check_program("", program, shared); + t.expects(made.notes.length == 3); + t.expects(check_noted(7, 1, ec::invalid, program, shared)); + t.expects(check_noted(8, 1, ec::invalid, program, shared)); + t.expects(check_noted(9, 7, ec::duplicate, program, shared)); +} + +@test def compile_error_reports_where_checking_reaches_it(t: &mut tester): void { + val shared := "module std; module core;\npub trait attribute {}\npub struct intrinsic : attribute {}\npub struct span { var data: *T; }\n@intrinsic pub def compile_error(text: span): void;"; + t.expects(check_noted(2, 30, ec::invalid, "import std;\ndef f(): void { compile_error(\"no\"); }", shared)); + t.expects(checks("import std;\ndef f(): void { compile_error(\"later\"); }", shared)); +} + +@test def packs_give_each_argument_its_own_type(t: &mut tester): void { + val program := """ + import std; + trait shown { def show(&this): i64; } + def i64::show(&this): i64 { return this; } + def bool::show(&this): i64 { return 1; } + def show_all(args: Ts...): i64 where Ts...: shown { + var out := 0; + for const x in args { out += x.show(); } + return out + args.length as i64; + } + def total(first: T, rest: Ts...): T where T: numeric where Ts...: numeric { + return first if const rest.length == 0; + return first + total(...rest) as T; + } + def head(args: Ts...): i64 where Ts...: shown { return args[0].show(); } + def f(): void { + val a := show_all(1, true); + val b := show_all::(1, true); + val c := total(1, 2, 3); + val d := head(5); + } + """; + t.expects(checks(mini_std, program)); + val made := check_program("", mini_std, """ + import std; + trait shown { def show(&this): i64; } + def show_all(args: Ts...): i64 where Ts...: shown { return 0; } + def f(): void { val e := show_all(1.5); } + """); + t.expects(made.notes.length == 1 && made.notes.at(0).code == ec::bound); +} + +#! What calling values needs of std, as the real one declares it. +const calling_std: strview = """ + module std; module core; + pub trait signature { type result; type params...; } + pub trait invokable { def invoke(&mut this, args: Ts...): R; } + """; + +@test def function_types_take_any_number_and_packs(t: &mut tester): void { + t.expects(checks(mini_std, """ + import std; + def sum(xs: i64...): i64 { return 0; } + def apply(f: def(Ts...): R, args: Ts...): R { return f(...args); } + def add(a: i64, b: i64): i64 { return a + b; } + def f(): void { + val s: def(i64...): i64 = sum; + val t: def(span): i64 = sum; + val a := s(1, 2, 3) + s() + t(span::{ data = null, count = 0 }) + apply(add, 1, 2); + } + """)); + + # A variadic parameter type is the last, and only a variadic one takes a view. + val wrong := """ + import std; + def two(a: i64, b: i64): i64 { return a + b; } + def f(): void { + val g: def(i64..., bool): i64 = two; + val h := two; + val xs: i64[2] = [1, 2]; + _ = h(...xs); + } + """; + t.expects(check_noted(4, 14, ec::invalid, mini_std, wrong)); + t.expects(check_noted(7, 9, ec::arguments, mini_std, wrong)); +} + +@test def types_and_traits_take_packs(t: &mut tester): void { + t.expects(checks(mini_std, """ + import std; + trait sink { def put(&mut this, args: Ts...): void; } + trait counted : sink { def count(&this): i64; } + struct log : counted { var n: i64; } + def log::put(&mut this, args: Ts...): void { this.n += args.length as i64; } + def log::count(&this): i64 { return this.n; } + def feed(into: &mut S, args: Ts...): void where S: sink { into.put(...args); } + def f(): void { + var l := log::{ n = 0 }; + l.put(1, true); + feed(&mut l, 2, false); + val as_sink: &mut counted = &mut l; + as_sink.put(3, true); + var none := log::{ n = 0 }; + none.put(); + } + """)); + + # A pack is no field's type, an alias takes none, and one not known yet is + # passed on alone. + val wrong := """ + import std; + struct box { var held: A; } + struct holds { var all: Ts; } + type all = box; + def pass(args: Ts...): void { + val b: box = box::{ held = 1 }; + } + """; + t.expects(check_noted(3, 32, ec::not_type, mini_std, wrong)); + t.expects(check_noted(4, 10, ec::generic, mini_std, wrong)); + t.expects(check_noted(6, 10, ec::generic, mini_std, wrong)); +} + +@test def pattern_parameters_name_the_parts_of_a_function_type(t: &mut tester): void { + t.expects(checks(mini_std, calling_std, """ + import std; + trait first { def head(&this, a: A): R; def rest(&this, args: Rest...): u64; } + struct picker : first {} + def picker::head(&this, a: i64): u8 { return a as u8; } + def picker::rest(&this, b: bool, c: u8): u64 { return 2; } + struct summer : invokable {} + def summer::invoke(&mut this, xs: i64...): i64 { return 0; } + struct wrapped : invokable where F: signature { var call: F; } + def wrapped::invoke(&mut this, args: F::params...): F::result { return this.call(...args); } + def add(a: i64, b: i64): i64 { return a + b; } + def total(f: &mut invokable): i64 { return f.invoke(1, 2); } + def f(): void { + val p := picker{}; + val n := p.head(1) as u64 + p.rest(true, 2); + var s := summer{}; + val m := total(s); + var w := wrapped::{ call = add }; + val k := w.invoke(1, 2); + } + """)); + + # A pattern is given a function type with the parameters it names, and only a + # struct, union, or trait takes one. + val wrong := """ + import std; + trait unary { def one(&this, a: A): R; } + def generic(x: i64): void {} + def f(a: &unary, b: &unary, c: &unary): void {} + """; + t.expects(check_noted(3, 13, ec::generic, mini_std, wrong)); + t.expects(check_noted(4, 11, ec::generic, mini_std, wrong)); + t.expects(check_noted(4, 27, ec::generic, mini_std, wrong)); + t.expects(check_noted(4, 58, ec::generic, mini_std, wrong)); +} + +@test def function_types_naming_a_pack_are_what_each_instance_gives(t: &mut tester): void { + # Written in a body, a function type naming a pack is the type its instance's + # pack makes of it, as the signature's is, a variadic one's included. + t.expects(checks(mini_std, calling_std, """ + import std; + def plain(args: Ts...): i64 { return 0; } + def named(): void { val f: def(Ts...): i64 = plain::; } + def thunk(at: *mut u8, args: Ts...): R where F: invokable { + return (at as *mut F)[0](...args); + } + struct holder : invokable { var call: def(*mut u8, Ts...): R; var at: *mut u8; } + def holder::invoke(&mut this, args: Ts...): R { return this.call(this.at, ...args); } + def holder::of(f: *mut F): holder where F: invokable { + return holder:: { call = thunk::, at = f as *mut u8 }; + } + def over_thunk(at: *mut u8, args: S::params...): S::result where S: signature where F: invokable { + return (at as *mut F)[0](...args); + } + struct over : invokable where S: signature { var call: def(*mut u8, S::params...): S::result; var at: *mut u8; } + def over::invoke(&mut this, args: S::params...): S::result { return this.call(this.at, ...args); } + def over::of(f: *mut F): over where F: invokable { + return over:: { call = over_thunk::, at = f as *mut u8 }; + } + struct add : invokable {} + def add::invoke(&mut this, a: i64, b: i64): i64 { return a + b; } + struct summer : invokable {} + def summer::invoke(&mut this, xs: i64...): i64 { return 0; } + def f(): void { + var a := add{}; + var s := summer{}; + var h := holder::::of(&mut a as *mut add); + var all := holder::::of(&mut s as *mut summer); + var o: over = over::of(&mut a as *mut add); + val n := h(1, 2) + all(1, 2, 3) + o(3, 4); + named::(); + } + """)); +} + +@test def signature_bounds_hold_wherever_their_parameter_is_declared(t: &mut tester): void { + # A pattern given a signature finds it bounded whether it is declared before + # or after the parameter bounded by the pattern. + t.expects(checks(mini_std, calling_std, """ + import std; + def before(f: &mut F, args: S::params...): S::result where S: signature where F: invokable { + return f(...args); + } + def after(f: &mut F, args: S::params...): S::result where F: invokable where S: signature { + return f(...args); + } + struct add : invokable {} + def add::invoke(&mut this, a: i64, b: i64): i64 { return a + b; } + def f(): void { + var a := add{}; + val n := before::(&mut a, 1, 2) + after::(&mut a, 3, 4); + } + """)); +} + +@test def void_is_a_type_of_one_value(t: &mut tester): void { + # `void` is a value's type, of the one value `void {}`, which a function giving + # nothing gives: a type argument, a field, a local, an element, and a + # signature's result, and `return;` gives it where a union holds a `void`. + t.expects(checks(mini_std, calling_std, """ + import std; + struct pair_of { var first: A; var second: B; } + union outcome { var value: T; var error: E; } + struct holder : invokable where S: signature { var call: def(S::params...): S::result; } + def holder::invoke(&mut this, args: S::params...): S::result { return this.call(...args); } + def said(x: i64): void {} + def give(x: T): T { return x; } + def checked(n: i64): outcome { + if n < 0 { return outcome:: { error = n }; } + return; + } + def done(): void { return said(0); } + type unit = void; + const quiet: void = void {}; + def f(): void { + val v := void {}; + var w: void; + w = v; + val x := said(1); + give::(said(2)); + val p := pair_of:: { first = void {}, second = 3 }; + val u: unit = quiet; + var h := holder:: { call = said }; + h(4); + val o := checked(5); + val many: void[2] = [void {}, said(6)]; + val r: &void = &v; + } + """)); + + # A function giving a value still returns one, falling off its end returns + # nothing, and `void {}` is given no fields. + val wrong := """ + import std; + union outcome { var value: T; var error: E; } + def number(): i64 { return; } + def fell(): outcome { } + def f(): void { + val bad := void { x = 1 }; + } + """; + t.expects(check_noted(3, 21, ec::mismatch, mini_std, wrong)); + t.expects(check_noted(4, 5, ec::control, mini_std, wrong)); + t.expects(check_noted(6, 21, ec::invalid, mini_std, wrong)); +} + +@test def array_patterns_name_the_element_and_length_of_a_fixed_array(t: &mut tester): void { + t.expects(checks(mini_std, """ + import std; + struct lanes { var items: L[N]; } + def lanes::count(&this): u64 { return N; } + def lanes::first(&this): L { return this.items[0]; } + def first(v: &lanes): L { return v.items[0]; } + type four = lanes; + def f(): void { + val a := lanes:: { items = [1, 2, 3] }; + val n: u64 = a.count(); + val x: i64 = a.first() + first(&a); + val b := four {}; + val m: u64 = b.count(); + val c: lanes[2]> = lanes::[2]> {}; + } + """)); + + # A pattern is given a fixed array, and only a struct, union, or trait takes one. + val wrong := """ + import std; + struct lanes { var items: L[N]; } + def generic(x: i64): void {} + def f(a: &lanes, b: &lanes): void {} + """; + t.expects(check_noted(3, 13, ec::generic, mini_std, wrong)); + t.expects(check_noted(4, 11, ec::generic, mini_std, wrong)); + t.expects(check_noted(4, 27, ec::generic, mini_std, wrong)); +} + +# A struct or union has the bitwise operators and shifts by the methods that give +# them, as it has arithmetic, and integers give them as methods too. +@test def bitwise_operators_and_shifts_call_methods(t: &mut tester): void { + t.expects(checks(mini_std, """ + import std; + struct bits { var word: u64; } + def bits::bit_and(&this, other: &bits): bits { return bits { word = this.word & other.word }; } + def bits::bit_or(&this, other: &bits): bits { return bits { word = this.word | other.word }; } + def bits::bit_xor(&this, other: &bits): bits { return bits { word = this.word ^ other.word }; } + def bits::bit_not(&this): bits { return bits { word = ~this.word }; } + def bits::shift_left(&this, by: &u32): bits { return bits { word = this.word << by }; } + def bits::shift_right(&this, by: &u32): bits { return bits { word = this.word >> by }; } + def f(a: bits, b: bits): u64 { + var c := (a & b) | (a ^ ~b); + c <<= 2; + c &= a >> 1; + val x: u32 = 12; + return c.word + (x.bit_and(&10) | x.shift_left(&2)) as u64; + } + """)); + + val wrong := """ + import std; + struct bits { var word: u64; } + def bits::bit_and(&this, other: &bits): bits { return this; } + def f(a: bits): void { + val b := a | a; + val c := a << 1; + } + """; + t.expects(check_noted(5, 14, ec::operands, mini_std, wrong)); + t.expects(check_noted(6, 14, ec::operands, mini_std, wrong)); +} + +# An operator of numbers keeps an alias its operands are written with, so a +# mask made of masks has a mask's methods: the right operand's type where it is +# the number they operate as, else the left's. +@test def operators_keep_an_alias_of_a_number(t: &mut tester): void { + t.expects(checks(mini_std, """ + import std; + type mask = u64; + type word = u64; + def mask::first(&this): u64 { return this & 7; } + def word::mask_of(&this): mask { return this; } + def f(a: mask, b: mask, c: u64, w: word): u64 { + val d := (a | b).first() + (a & 3).first() + (~a).first() + (a >> 1).first() + (a << c).first(); + val e := (a + b).first() + (c ^ a).first() + (2 * a).first() + (w & a).first() + (a ^ w).mask_of(); + return d + e; + } + """)); + + val wrong := """ + import std; + type mask = u64; + def mask::first(&this): u64 { return this & 7; } + def f(a: mask, c: u64): u64 { + return (a | c).first() + (c << a).first(); + } + """; + t.expects(check_noted(5, 18, ec::member, mini_std, wrong)); + t.expects(check_noted(5, 37, ec::member, mini_std, wrong)); +} + +# A vector of std holds 16 or 32 bytes of numbers, or 64 of at most 32. +@test def vectors_hold_sixteen_or_thirty_two_bytes_of_numbers(t: &mut tester): void { + val lanes_std := """ + module std; module core; + pub struct simd { var _lanes: L[N]; } + pub struct mask { var _lanes: L[N]; } + """; + t.expects(checks(mini_std, lanes_std, """ + import std; + def f(a: simd, b: simd, c: mask, d: simd, e: simd, g: mask): void {} + """)); + val wrong := """ + import std; + def f(a: simd, b: mask, c: simd, d: simd): void {} + """; + t.expects(check_noted(2, 10, ec::generic, mini_std, lanes_std, wrong)); + t.expects(check_noted(2, 27, ec::generic, mini_std, lanes_std, wrong)); + t.expects(check_noted(2, 43, ec::generic, mini_std, lanes_std, wrong)); + t.expects(check_noted(2, 62, ec::generic, mini_std, lanes_std, wrong)); +} + +@test def values_are_called_through_invoke(t: &mut tester): void { + t.expects(checks(mini_std, calling_std, """ + import std; + struct adder : invokable { var calls: i64; } + def adder::invoke(&mut this, a: i64, b: i64): i64 { this.calls++; return a + b; } + struct doubler : invokable {} + def doubler::invoke(&this, x: i64): i64 { return x * 2; } + struct holder { var f: adder; } + def twice(f: &mut F, x: i64): i64 where F: invokable { return f(f(x)); } + def run(f: &mut invokable): i64 { return f(1, 2); } + def square(x: i64): i64 { return x * x; } + def f(): void { + var a := adder{ calls = 0 }; + val d := doubler{}; + var h := holder{ f = adder{ calls = 0 } }; + var sq: def(i64): i64 = square; + val n := a(1, 2) + d(3) + h.f(4, 5) + run(a) + twice(&mut sq, 2) + sq.invoke(3); + } + """)); + + # A generic of another module calls a functor through its `invoke`, which needs + # no `pub` there, whether the functor is given by value or by reference. + t.expects(checks(mini_std, calling_std, """ + import std; + module algo; + pub def count(f: F, n: i64): i64 where F: invokable { + var hits: i64 = 0; + for i in 0..n { if f(i) { hits++; } } + return hits; + } + """, """ + import std; + import algo; + struct odd : invokable { var seen: i64; } + def odd::invoke(&mut this, x: i64): bool { this.seen++; return x % 2 == 1; } + def f(): void { + var o := odd{ seen = 0 }; + val n := count(o, 4) + count(&mut o, 4); + } + """)); + + # A function's `invoke` gives what a bound's pattern binds, as one declared + # would: `half` gives the `K` of `invokable`. + t.expects(checks(mini_std, calling_std, """ + import std; + def key_of(f: F, x: i64): K where F: invokable { return f(x); } + def half(x: i64): u32 { return (x / 2) as u32; } + def f(): void { val k := key_of(half, 8); } + """)); + + # A value of a type without `invoke` is not called, and one taking `&mut this` + # is called on what can be written. + val wrong := """ + import std; + struct adder { var calls: i64; } + def adder::invoke(&mut this, a: i64, b: i64): i64 { return a + b; } + struct plain { var n: i64; } + def f(): void { + val a := adder{ calls = 0 }; + _ = a(1, 2); + val p := plain{ n = 1 }; + _ = p(1); + } + """; + t.expects(check_noted(7, 7, ec::assignable, mini_std, wrong)); + t.expects(check_noted(9, 7, ec::operands, mini_std, wrong)); +} + +#! What reflection needs of std, as the real one declares it. +const reflection_std: strview = """ + module std; module core; + pub trait attribute {} + pub trait zeroable {} + pub struct intrinsic : attribute {} + pub struct span { var data: *T; var count: u64; } + pub val span::length: u64 { get => this.count; } + pub def span::at(&this, index: u64): &T { return &this.data[index]; } + pub enum target : u32 { functions = 1, methods = 2, fields = 16, structs = 32, properties = 0x1000, all = 0xFFFF } + pub struct decl { pub val kind: target; pub val generic: bool; } + @intrinsic pub def declarations(): span; + @intrinsic pub def decl_of(): decl; + @intrinsic pub def members_of(d: decl): span; + @intrinsic pub def attached(d: decl): span where A: attribute; + @intrinsic pub def value_of(d: decl): void; + @intrinsic pub def compile_error(text: span): void; + """; + +@test def reflection_reads_declarations_while_checking(t: &mut tester): void { + val program := """ + import std; + struct check : attribute {} + @check def a(): i64 { return 1; } + @check def b(): i64 { return 2; } + @check def c(x: i64): i64 { return 3; } + struct p { var x: i64; var y: bool; } + def fields(): i64 { + var count := 0; + for const f in members_of(decl_of::()) { + if const f.kind == target::fields { count += 1; } + } + return count; + } + def run(): i64 { + var total := 0; + for const d in declarations() { + if const attached::(d).length == 0 { continue; } + if const !(value_of(d) is def(): i64) { + compile_error("A check takes nothing and gives an i64."); + continue; + } + total += value_of(d)(); + } + return total + fields::

(); + } + """; + val made := check_program("", program, reflection_std); + t.expects(made.notes.length == 1); + t.expects(made.notes.length == 1 && made.notes.at(0).code == ec::invalid && made.notes.at(0).line == 19); + t.expects(made.skipped == 0); +} + +@test def reflection_gives_an_instance_its_arguments(t: &mut tester): void { + # The fields of `page` hold `u8`, and `is (d)` names a field as its name + # would, within each instance. + val made := check_program("", """ + import std; + struct page { var items: T[2]; var count: T; } + union shape { var circle: f64; var square: u32; } + def fill(): T where T: zeroable { + var made: T; + for const field in members_of(decl_of::()) { + if const field.kind == target::fields { + var read: type_of(field); + made.(field) = read; + } + } + return made; + } + def which(value: &T): i64 { + var at := 0; + for const field in members_of(decl_of::()) { + if const field.kind == target::fields { + if value is (field) { return at; } + at += 1; + } + } + return at; + } + def run(): i64 { + val p := fill::>(); + val s := shape{ square = 3 }; + return which(&s) + p.count as i64; + } + """, reflection_std); + t.expects(made.notes.length == 0 && made.skipped == 0); + + # What names no field of the value is reported, as what is no description is. + val wrong := check_program("", """ + import std; + struct point { var x: i64; } + union shape { var circle: f64; } + def f(s: &shape, p: &point): void { + val n := 4; + for const field in members_of(decl_of::()) { + if const field.kind == target::fields { + if s is (field) { return; } + val x := s.(field); + } + } + if s is (n) { return; } + val y := p.(n); + } + """, reflection_std); + t.expects(wrong.notes.length == 4 && wrong.skipped == 0); + t.expects(wrong.notes.length == 4 && wrong.notes.at(0).code == ec::invalid && wrong.notes.at(1).code == ec::member); + t.expects(wrong.notes.length == 4 && wrong.notes.at(2).code == ec::constant && wrong.notes.at(3).code == ec::constant); +} + +@test def reflection_names_methods_properties_and_instances(t: &mut tester): void { + # `x.(d)` reads a property and calls a method as their names would, and + # `value_of(d)::` is the instance of the generic function `d` describes. + val made := check_program("", """ + import std; + struct mark : attribute {} + struct point { var x: i64; } + def point::sum(&this): i64 { return this.x; } + val point::twice: i64 { get => this.x * 2; } + @mark def same(x: T): T { return x; } + def run(p: &point): i64 { + var total := 0; + for const m in members_of(decl_of::()) { + if const m.kind == target::methods { total += p.(m)(); } + if const m.kind == target::properties { total += p.(m); } + } + for const d in declarations() { + if const attached::(d).length == 0 { continue; } + total += value_of(d)::(21); + } + return total; + } + """, reflection_std); + t.expects(made.notes.length == 0 && made.skipped == 0); + + # What is no description is reported where it is given, as `x.(d)` reports. + t.expects(check_noted(2, 40, ec::constant, """ + import std; + def run(): void { val n := 4; value_of(n); } + """, reflection_std)); +} + +@test def an_edit_checks_again_only_what_it_affects(t: &mut tester): void { + val before := """ + def helper(n: i64): i64 { return n + 1; } + def caller(): i64 { return helper(2); } + def other(): i64 { return 7; } + """; + + # An edit within a body that keeps its signature checks only that body. + val body := check_edit(before, """ + def helper(n: i64): i64 { return n * 2 + 1; } + def caller(): i64 { return helper(2); } + def other(): i64 { return 7; } + """); + t.expects(body.same); + t.expects(body.checked == 1); + + # A changed signature checks again what calls it. + val signature := check_edit(before, """ + def helper(n: bool): i64 { return 1; } + def caller(): i64 { return helper(2); } + def other(): i64 { return 7; } + """); + t.expects(signature.same && signature.notes == 1); + t.expects(signature.checked == 2); + + # What is gone leaves what called it naming nothing. + val gone := check_edit(before, """ + def caller(): i64 { return helper(2); } + def other(): i64 { return 7; } + """); + t.expects(gone.same && gone.notes == 1); + + # What is new is found where it was named before. + val added := check_edit("def caller(): i64 { return helper(2); }", """ + def caller(): i64 { return helper(2); } + def helper(n: i64): i64 { return n; } + """); + t.expects(added.same && added.notes == 0); +} + +@test def an_edit_keeps_what_other_files_worked_out(t: &mut tester): void { + val lib := """ + module geometry; + pub struct rect { pub var w: f64; } + pub def area(r: &rect): f64 { return r.w; } + """; + val made := check_edit( + "import geometry;\ndef f(): f64 { return area(rect{ w = 1.0 }); }", + "import geometry;\ndef f(): f64 { return area(rect{ w = 2.0 }) + 1.0; }", + lib); + t.expects(made.same && made.notes == 0 && made.checked == 1); +} + +@test def hovering_shows_types_and_what_names_name(t: &mut tester): void { + val text := "def twice(n: i64): i64 { return n * 2; }\ndef f(): u8 { val small: u8 = 3; return small; }\ndef g(): i64 { return twice(4); }"; + t.expects(hover_of(text, "small;").view() == "val small: u8"); + t.expects(hover_of(text, "twice(4)").view() == "def twice(n: int): int"); +} + +@test def constants_run_functions_while_checking(t: &mut tester): void { + val program := """ + def square(n: i64): i64 { return n * n; } + def table(): u32[4] { + var made: u32[4]; + for i in 0..4 { made[i] = (i * 10) as u32; } + return made; + } + enum gap { a = 1, b = 4, c, d = 9 } + def through(n: i64): i64 { var t := 0; for i in 1..=n { t += i; } return t; } + def members(): i64 { var t := 0; for g in gap::b..=gap::d { t = t * 10 + (g as i64); } return t; } + const four := square(2); + const tens: u32[4] = table(); + const thirty: u32 = tens[3]; + def f(): void { + var a: i64[four]; + var b: i64[square(3)]; + var c: u8[thirty - 25]; + var d: u8[through(3)]; + var e: u8[members()]; + } + """; + t.expects(checks(program)); + t.expects(local_type("c", program).view() == "u8[5]"); + t.expects(local_type("b", program).view() == "int[9]"); + # `a..=b` counts `b` too, and a range of an enum's members each member. + t.expects(local_type("d", program).view() == "u8[6]"); + t.expects(local_type("e", program).view() == "u8[459]"); + + val faults := check_program("", """ + def forever(): i64 { var x := 0; while true { x++; } return x; } + def deep(n: i64): i64 { return deep(n + 1); } + const loops: i64 = forever(); + const nested: i64 = deep(0); + """); + t.expects(faults.notes.length == 2); + t.expects(faults.notes.length == 2 && faults.notes.at(0).code == ec::constant && faults.notes.at(1).code == ec::constant); +} + +@test def constant_parameters_are_values_worked_out_while_checking(t: &mut tester): void { + t.expects(checks(mini_std, """ + import std; + struct buffer where T: zeroable { var items: T[N]; } + def buffer::capacity(&this): u64 { return N; } + def total(xs: &i64[N]): i64 { return xs[0]; } + def grown(xs: &i64[N]): i64[N + 1] { var out: i64[N + 1]; return out; } + enum color { red, green } + struct point { var x: i64; var y: i64 = 7; } + struct at {} + struct painted {} + const origin: point = point { x = 1 }; + const four: u64 = 4; + def f(): void { + var b: buffer; + val c: buffer = b; + val d: at = at:: {}; + val e: painted = painted:: {}; + val xs: i64[3] = [1, 2, 3]; + val n := total(&xs) + c.capacity() as i64; + val g: i64[4] = grown(&xs); + } + """)); + t.expects(local_type("b", """ + struct buffer { var n: T; } + def f(): void { val b := buffer:: { n = 1 }; } + """).view() == "buffer"); + + # A constant parameter takes a value of its type, and no bounds, and closes nothing. + t.expects(check_noted(2, 29, ec::overflow, """ + struct keep {} + def f(): void { val k: keep<300> = keep::<1> {}; } + """)); + t.expects(check_noted(2, 39, ec::generic, mini_std, """ + import std; + struct bounded where N: ordered {} + """)); + t.expects(check_noted(2, 31, ec::generic, """ + struct buffer { var n: T; } + def f(): void { val b: buffer<4, 4> = buffer:: { n = 1 }; } + """)); + t.expects(check_noted(3, 32, ec::constant, """ + struct keep {} + def get(): u64 { return 4; } + def f(): void { val k: keep = keep::<4> {}; } + """)); +} + +@test def calls_infer_from_bounds_results_and_waiting_arguments(t: &mut tester): void { + t.expects(checks(mini_std, """ + import std; + def first(c: &C): maybe where C: iterable { return nothing {}; } + struct box { var value: T; } + def box::new(value: T): box { return box:: { value = value }; } + def same(x: T): T { return x; } + def apply(f: def(T): U, x: T): U { return f(x); } + def made(): box where T: zeroable { var b: box; return b; } + def pick(a: T, b: T): T { return b; } + def head(xs: span): T { return xs.at(0); } + def second(a: T, b: U): U { return b; } + def f(s: span, b: box): void { + val e := first(&s); + val c: box = box::new(5); + val g: def(i64): i64 = same; + val h := apply(same, 3) + apply(def(x) => x * 2, 4); + val i := pick(made(), b); + val j := head([1, 2, 3]); + val k := second::(1, true); + val l := pick(1, 2.5); + } + """)); + val inferred := check_program("e", """ + import std; + def first(c: &C): maybe where C: iterable { return nothing {}; } + def f(s: span): void { val e := first(&s); } + """, mini_std); + t.expects(inferred.asked.view() == "maybe"); +} + +@test def generic_traits_are_inferred_through_what_implements_them(t: &mut tester): void { + # A type implementing a generic trait gives its parameters through its + # methods, whether or not it names the trait. + val inferred := check_program("got", """ + trait into { def into(&this): T; } + struct count { var n: i64; } + def count::into(&this): i64 { return this.n; } + def pick(x: &into): T { return x.into(); } + def f(c: &count): void { val got := pick(c); } + """); + t.expects(inferred.notes.length == 0 && inferred.asked.view() == "int"); + + # A generic trait's default gives the types of the trait's arguments. + val both := check_program("got", """ + trait into { def into(&this): T; } + trait pair: into { def twice(&this): T[2] { return [this.into(), this.into()]; } } + struct one: pair { var v: i64; } + def one::into(&this): i64 { return this.v; } + def f(o: &one): void { val got := o.twice(); } + """); + t.expects(both.notes.length == 0 && both.asked.view() == "int[2]"); +} + +@test def traits_take_defaults_types_and_nested_instances(t: &mut tester): void { + # A type the bound asks for is the one given, or the trait's default, in each + # instance; a requirement a composed trait's default meets is met; and a member + # of a generic type's enum is of the enum given the type's arguments. + t.expects(checks(""" + trait walk { type cursor; def start(&this): cursor; } + struct ctr { var at: i64; } + struct one { var to: i64; } + type one::cursor = ctr; + def one::start(&this): ctr { return ctr { at = this.to }; } + def first(c: &C): C::cursor where C: walk { return c.start(); } + def f(o: &one): i64 { val x: ctr = first(o); return x.at; } + """)); + t.expects(checks(""" + trait stored { type storage = self; } + struct bit { var on: bool; } + type bool::storage = bit; + def keep(x: T::storage): T::storage where T: stored { return x; } + def f(): void { + val a: i64 = keep::(5); + val b: bit = keep::(bit { on = true }); + } + """)); + t.expects(checks(""" + trait base { def id(&this): i64; def f(&this): i64 { return 1; } } + trait keeps: base { def f(&this): i64; } + trait all: base { def l(&this): i64; } + struct z: all { var n: i64; } + def z::id(&this): i64 { return this.n; } + def z::l(&this): i64 { return 10; } + def f(x: &z): i64 { val k: &keeps = x; return k.f(); } + """)); + t.expects(checks(""" + struct bag { var count: u64; } + enum bag::state { empty, full } + def bag::status(&this): bag::state { + return this.count == 4 ? bag::::state::full : bag::::state::empty; + } + def f(b: &bag): bool { return b.status() == bag::::state::empty; } + """)); +} + +# The containers the tables are made of. + +@test def locals_are_declared_once_in_each_block(t: &mut tester): void { + t.expects(check_noted(1, 32, ec::duplicate, "def f(): i64 { val x := 1; val x := x + 1; return x; }")); + # A parameter, a block within, a loop's body, and a function within may each + # declare a name again, hiding the one around them. + t.expects(checks(""" + def f(x: i64): i64 { + val x := x + 1; + if x > 2 { val x := 3; return x; } + var n := 0; + while n < 2 { val n := 7; break; } + val g := def(x: i64): i64 { val x := x * 2; return x; }; + return g(x); + } + """)); + # What an `is not` test names for the rest of the block is declared there. + t.expects(check_noted(4, 7, ec::duplicate, mini_std, """ + import std; + def f(m: maybe): i64 { + if m is not some(v) { return 0; } + val v := 5; + return v; + } + """)); +} + +@test def union_fields_are_lent_where_the_union_is_known_to_hold_them(t: &mut tester): void { + # `&mut` of a field could write it whichever field the union holds, and `&` of + # what closes could outlive it once the union holds another: a test names it + # where it is held. + val held := """ + struct held : owning { var n: i64; } + def held::close(&mut this): void {} + struct pair { var a: i64; var h: held; } + """; + val made := check_program("", """ + import std; + def f(a: &mut maybe, b: &mut maybe, c: &mut maybe): void { + val p := &a.some; + val q := &mut a.some; + val s := &b.some; + val x := &c.some.a; + val y := &mut c.some.a; + val z := &c.some.h; + if b is some(&mut w) { w.n = 1; } + } + """, held, mini_std); + t.expects(made.notes.length == 4); + t.expects(made.notes.length == 4 && made.notes.at(0).line == 4 && made.notes.at(0).column == 12 && made.notes.at(0).code == ec::invalid); + t.expects(made.notes.length == 4 && made.notes.at(1).line == 5 && made.notes.at(1).column == 12 && made.notes.at(1).code == ec::owned); + t.expects(made.notes.length == 4 && made.notes.at(2).line == 7 && made.notes.at(2).column == 12 && made.notes.at(2).code == ec::invalid); + t.expects(made.notes.length == 4 && made.notes.at(3).line == 8 && made.notes.at(3).column == 12 && made.notes.at(3).code == ec::owned); +} + +@test def properties_hold_values_and_generic_types_hold_no_variables(t: &mut tester): void { + t.expects(check_noted(2, 22, ec::invalid, "struct p { var n: i64; }\nval p::nothing_here: void { get { return; } }")); + # Each instance would need a variable of its own, which an alias of one has. + t.expects(check_noted(2, 5, ec::invalid, "struct box { var v: T; }\nval box::count: i64 = 3;")); + t.expects(checks("struct box { var v: T; }\ntype ibox = box;\nval ibox::count: i64 = 3;\ndef f(): i64 { return ibox::count; }")); +} + +@test def tests_and_conversions_that_cannot_mean_what_they_say_are_refused(t: &mut tester): void { + # `is` with a type asks the value's own type, which a union's field never is. + t.expects(check_noted(2, 42, ec::invalid, mini_std, "import std;\ndef f(m: maybe): bool { return m is nothing; }")); + t.expects(checks(mini_std, "import std;\ndef f(m: maybe): bool { return m is none; }")); + t.expects(checks(mini_std, "import std;\ndef f(x: T): bool { return x is nothing; }")); + + # A reference written `&x` converts as the value it refers to, so a number from + # it is `x`, where its address was surely meant. + t.expects(check_noted(1, 48, ec::conversion, "def f(): u64 { var x: u64 = 5; return (&mut x) as u64; }")); + t.expects(check_noted(1, 44, ec::conversion, "def f(): bool { val x := true; return (&x) as bool; }")); + t.expects(checks("def f(): u64 { var x: u64 = 5; return (&mut x) as *mut u64 as u64; }")); + t.expects(checks("def f(r: &u64): u32 { return r as u32; }")); + + # A string compared with a view, either way round, which `view()` settles. + val text := """ + module std; module core; + pub struct span { var data: *T; var count: u64; } + pub def span::equals(&this, other: &span): bool { return this.count == other.count; } + pub type strview = span; + pub struct string { var count: u64; } + pub def string::equals(&this, other: &string): bool { return this.count == other.count; } + pub def string::view(&this): strview { return strview { count = this.count }; } + """; + t.expects(check_noted(2, 48, ec::operands, "import std;\ndef f(s: &string, v: strview): bool { return s == v; }", text)); + t.expects(check_noted(2, 48, ec::operands, "import std;\ndef f(s: &string, v: strview): bool { return v != s; }", text)); + t.expects(checks("import std;\ndef f(s: &string, v: strview): bool { return s.view() == v && s == \"abc\"; }", text)); +} + +@test def members_declared_on_cores_types_are_chosen_over_cores(t: &mut tester): void { + # A program's member of a name `core` gives the type too is no duplicate of it: + # where both are seen the program's is chosen, and `core`'s where the program's + # takes nothing given, so `core` adding a member later changes no program. + val made_core := """ + module std; module core; + pub struct text { var n: i64; } + pub val text::size: i64 { get => this.n; } + pub def text::grow(&mut this, by: i64): void { this.n += by; } + pub def text::trim(&this): i64 { return 1; } + pub def text::measured(&this): i64 { return this.size + this.trim(); } + pub struct text::piece { pub var n: i64; } + pub def text::cut(&this): text::piece { return text::piece { n = this.n }; } + """; + t.expects(checks(""" + import std; + def text::size(&this): bool { return true; } + def text::grow(&mut this, by: bool): void {} + def text::trim(&this): bool { return false; } + def text::piece(&this): bool { return true; } + def f(t: text): bool { + var c := t; + c.grow(1); + c.grow(true); + val a: bool = c.size(); + val b: bool = c.trim(); + val n: i64 = c.measured(); + val d: bool = c.piece(); + return a && b && d; + } + """, made_core)); + # So is a type, as one a trait asks for, and `core`'s own code keeps its own. + t.expects(checks(""" + import std; + type text::piece = bool; + def f(t: &text): bool { val p: text::piece = true; val k := t.cut(); val n: i64 = k.n; return p; } + """, made_core)); + # The program's own overloads still take parameters apart. + val made := check_program("", """ + import std; + def text::trim(&this): bool { return false; } + def text::trim(&this): bool { return true; } + """, made_core); + t.expects(made.notes.length == 1 && made.notes.at(0).line == 3 && made.notes.at(0).code == ec::duplicate); +} + +@test def compound_assignments_change_in_place_where_a_type_can(t: &mut tester): void { + # `+=` calls `add_assign` where it takes the value, and `add` elsewhere. + t.expects(checks(""" + struct acc { var n: i64; } + def acc::add(&this, other: &acc): acc { return acc { n = this.n + other.n }; } + def acc::add(&this, k: &i64): acc { return acc { n = this.n + k }; } + def acc::add_assign(&mut this, other: &acc): void { this.n += other.n; } + def f(): i64 { var x := acc { n = 1 }; x += acc { n = 2 }; x += 3; return x.n; } + """)); + t.expects(check_noted(3, 43, ec::operands, """ + struct acc { var n: i64; } + def acc::add_assign(&mut this, other: &acc): acc { return this; } + def f(): void { var x := acc { n = 1 }; x += acc { n = 2 }; } + """)); +} + +@test def a_module_sees_the_names_of_those_holding_it(t: &mut tester): void { + t.expects(checks("module app::util;\npub def go(): i64 { return helper(); }", "module app;\ndef helper(): i64 { return 1; }")); + # With no file of the module holding it, the note says so. + val made := check_program("", "module app::util;\npub def go(): i64 { return helper(); }"); + t.expects(made.notes.length == 1 && made.notes.at(0).detail.view() + == "`helper` is not declared where it is used. No file of `app`, which holds this file's module and whose names it sees, was read: is one missing?"); +} + +@test def accessors_have_this_and_a_set_has_its_value(t: &mut tester): void { + t.expects(checks(""" + struct r { var w: i64; var writes: i64; } + var r::width: i64 { + get => this.w; + set { this.w = value; this.writes += 1; } + } + var r::height: i64 { get { return this.w * 2; } set => this.w = value / 2; } + val r::area: i64 { get => this.width * this.height; } + trait sized { val area: i64 { get; } } + def f(): i64 { var v := r{}; v.width = 3; v.height += 2; return v.area; } + def g(x: &T): i64 where T: sized { return x.area; } + def h(): i64 { return g(&r{ w = 2 }); } + """)); + # `get` reads `this`, and writes nothing through it; `value` is a `set`'s, of + # the property's type. + val reads := check_program("", "struct r { var w: i64; }\nval r::bad: i64 { get { this.w = 1; return 1; } }"); + t.expects(reads.notes.length == 1 && reads.notes.at(0).line == 2 && reads.notes.at(0).code == ec::assignable); + t.expects(check_noted(2, 26, ec::undefined, "struct r { var w: i64; }\nval r::bad: i64 { get => value; }")); + val typed := check_program("", "struct r { var w: i64; }\nvar r::w2: i64 { get => this.w; set { val s: bool = value; } }"); + t.expects(typed.notes.length == 1 && typed.notes.at(0).code == ec::mismatch); + # `value` is a plain name, which stays a union's field name too. + t.expects(checks(mini_std, """ + import std; + struct r { var w: i64; } + var r::w2: result { + get => this.w; + set { if value is value(n) { this.w = n; } } + } + """)); +} + +@test def a_column_keeps_where_its_rows_are(t: &mut tester): void { + var made := column::::new(); + for i in 0..100 { + made.append(i as u32); + } + t.expects(made.length == 100 && made.p[0] == 0 && made.p[99] == 99); + made.resize(300); + t.expects(made.length == 300 && made.p[99] == 99 && made.p[100] == 0 && made.p[299] == 0); +} + +@test def an_index_lists_each_declaration_once_in_order(t: &mut tester): void { + var made := decl_index::new(); + made.add(3, 10); + made.add(3, 4); + made.add(3, 12); + made.add(3, 4); + made.add(5, 1); + val listed := made.of(3); + t.expects(listed.length == 3 && listed[0] == 4 && listed[1] == 10 && listed[2] == 12); + t.expects(made.of(5).length == 1 && made.of(6).length == 0); +} + +@test def a_ternary_names_what_its_tests_give(t: &mut tester): void { + t.expects(checks(mini_std, """ + import std; + def f(a: maybe): i64 { return a is some(x) ? x + 1 : 0; } + def g(a: maybe): i64 { return a is not some(x) ? 0 : x; } + """)); + # Only in the branch where the test holds. + t.expects(check_noted(2, 55, ec::undefined, mini_std, """ + import std; + def f(a: maybe): i64 { return a is some(x) ? 0 : x; } + """)); +} + +@test def a_literal_of_text_is_walked_as_a_view(t: &mut tester): void { + t.expects(checks(mini_std, ranges_std, """ + import std; + def f(): u64 { + var n: u64 = 0; + for c in "abc" { n += c as u64; } + return n; + } + """)); +} + +@test def a_lambda_whose_types_are_written_gives_its_own(t: &mut tester): void { + # To a type parameter where overloads are chosen between, and to the type + # parameters a function type leaves unknown. + t.expects(checks(mini_std, ranges_std, """ + import std; + struct w { var n: i64; } + def w::each(&mut this, f: F): void where F: invokable {} + def w::each(&mut this, f: F): void where F: invokable {} + def tested(test: def(&T): bool): bool { return true; } + def f(): void { + var x := w{ n = 0 }; + x.each(def(a: &i64) {}); + x.each(def(a: &mut i64, b: &bool) {}); + _ = tested(def(v: &u8) => true); + } + """)); +} + +@test def a_pack_of_types_has_a_length(t: &mut tester): void { + t.expects(checks(mini_std, """ + import std; + def count(xs: Ts...): u64 { return Ts.length; } + def f(): u64 { return count(1, true); } + """)); +} + +@test def a_property_is_read_rather_than_called(t: &mut tester): void { + t.expects(check_noted(3, 30, ec::operands, """ + struct s { var n: i64; } + val s::big: bool { get => this.n > 3; } + def f(v: s): bool { return v.big(); } + """)); +} + +@test def a_copy_a_test_names_is_only_read(t: &mut tester): void { + t.expects(check_noted(2, 53, ec::assignable, mini_std, """ + import std; + def f(a: maybe<&mut i64>): void { if a is some(x) { x = 3; } } + """)); + t.expects(checks(mini_std, """ + import std; + def f(a: maybe<&mut i64>): void { if a is some(&mut x) { x = 3; } } + """)); +} diff --git a/tests/analyzer/keymap.sakura b/tests/analyzer/keymap.sakura new file mode 100644 index 00000000..a5a2089e --- /dev/null +++ b/tests/analyzer/keymap.sakura @@ -0,0 +1,94 @@ +#! @file keymap.sakura +#! @author John Christman (sorakatadzuma@gmail.com) +#! @copyright Malunal Studios, LLC. +#! @license MIT +#! +#! Contains the tests of the key map and the ID index: keys set, replaced, and +#! taken, as many as make it grow, and IDs found by their hash. + +import std::testing; +module sakura::analyzer; + + +@test def key_maps_find_what_they_were_given(t: &mut tester): void { + var made := keymap::new(); + t.expects(made.length == 0 && made.get(&7) is none && made.get_or(&7, 3) == 3); + + # Enough keys to grow it several times, of IDs paired as the checker pairs + # them, and 0, which is a key like any other. + var fresh := true; + for i in 1..2001 { + fresh = made.insert(pair_key(i as u32, (i * 7) as u32), i as u32) && fresh; + } + t.expects(fresh && made.insert(0, 99)); + t.expects(made.length == 2001 && made.capacity * 3 >= made.length * 4); + var found := true; + for i in 1..2001 { + found = found && made.get_or(&pair_key(i as u32, (i * 7) as u32), 0xFFFFFFFF) == i as u32; + } + t.expects(found && made.get_or(&0, 0) == 99); + + # Inserting keeps the value held, and setting replaces it. + t.expects(!made.insert(pair_key(5, 35), 1) && made.get_or(&pair_key(5, 35), 0) == 5); + made.set(pair_key(5, 35), 1); + t.expects(made.get_or(&pair_key(5, 35), 0) == 1 && made.length == 2001); +} + +@test def key_maps_find_the_rest_once_one_is_taken(t: &mut tester): void { + var made := keymap::new(); + for i in 0..3000 { + made.set(i as u64 * 16, i as u32); + } + + # Every third key is taken, and the rest are still found, wherever the keys + # after each taken one moved back to. + for i in 0..3000 { + if i % 3 == 0 { + made.remove(&(i as u64 * 16)); + } + } + t.expects(made.length == 2000); + var right := true; + for i in 0..3000 { + val found := made.get(&(i as u64 * 16)); + right = right && (i % 3 == 0 ? found is none : found.unwrap_or(0xFFFFFFFF) == i as u32); + } + t.expects(right); + + made.clear(); + t.expects(made.length == 0 && !made.contains(&16)); + made.set(16, 4); + t.expects(made.get_or(&16, 0) == 4); +} + +@test def id_indexes_walk_the_ids_of_a_hash(t: &mut tester): void { + var made := id_index::new(); + t.expects(made.next(&mut made.walk(7 << 32)) == 0); + made.add(7 << 32, 1); + made.add(9 << 32, 2); + made.add(7 << 32 | 5, 4); + + # A walk gives one more than each ID whose hash shares its top half, in the + # order they were added, then 0. + var walk := made.walk(7 << 32); + t.expects(made.next(&mut walk) == 2 && made.next(&mut walk) == 5 && made.next(&mut walk) == 0); + walk = made.walk(9 << 32); + t.expects(made.next(&mut walk) == 3 && made.next(&mut walk) == 0); + walk = made.walk(8 << 32); + t.expects(made.next(&mut walk) == 0); + + # As many as make it grow are each still found. + for i in 0..5000 { + made.add(mix(0, i as u64), (i + 10) as u32); + } + var found := true; + for i in 0..5000 { + var each := made.walk(mix(0, i as u64)); + var at := made.next(&mut each); + while at != 0 && at != (i + 11) as u32 { + at = made.next(&mut each); + } + found = found && at == (i + 11) as u32; + } + t.expects(found && made.length == 5003); +} diff --git a/tests/analyzer/lexer.sakura b/tests/analyzer/lexer.sakura new file mode 100644 index 00000000..12f3d04b --- /dev/null +++ b/tests/analyzer/lexer.sakura @@ -0,0 +1,204 @@ +#! @file lexer.sakura +#! @author John Christman (sorakatadzuma@gmail.com) +#! @copyright Malunal Studios, LLC. +#! @license MIT +#! +#! Contains the tests of the lexer: the kinds of tokens text makes, where they +#! are, and what it reports. + +import std::testing; +module sakura::analyzer; + + +@test def keywords_lex_as_their_kinds(t: &mut tester): void { + t.expects(lexes_as("def mut import continue null", tk::kw_def, tk::kw_mut, tk::kw_imp, tk::kw_cont, tk::kw_null)); + t.expects(lexes_as("is not as where when", tk::kw_is, tk::kw_not, tk::kw_as, tk::kw_where, tk::kw_when)); +} + +@test def words_keep_their_ids(t: &mut tester): void { + val lexing := lex("this get set type_of thing thing"); + val syntax := &lexing.syntax; + t.expects(syntax.token(0, &lexing.names).kind == tk::name && syntax.token(0, &lexing.names).name == names::this_id); + t.expects(syntax.token(1, &lexing.names).name == names::get_id); + t.expects(syntax.token(2, &lexing.names).name == names::set_id); + t.expects(syntax.token(3, &lexing.names).name == names::type_of_id); + + # A name is interned once, so each place it is written has the same ID. + t.expects(syntax.token(4, &lexing.names).name == syntax.token(5, &lexing.names).name && syntax.token(4, &lexing.names).name > names::type_of_id); + t.expects(syntax.token(6, &lexing.names).kind == tk::eof); +} + +@test def tokens_know_where_they_are(t: &mut tester): void { + val lexing := lex("val name\n >>= 12u"); + val syntax := &lexing.syntax; + t.expects(syntax.token(0, &lexing.names).offset == 0 && syntax.token(0, &lexing.names).length == 3); + t.expects(syntax.token(1, &lexing.names).offset == 5 && syntax.token(1, &lexing.names).length == 4); + t.expects(syntax.token(2, &lexing.names).offset == 12 && syntax.token(2, &lexing.names).length == 3); + + # `>>=` is followed by tokens of what is left of it, `>=` and `=`. + t.expects(syntax.token(3, &lexing.names).offset == 13 && syntax.token(3, &lexing.names).length == 2); + t.expects(syntax.token(4, &lexing.names).offset == 14 && syntax.token(4, &lexing.names).length == 1); + t.expects(syntax.token(5, &lexing.names).offset == 16 && syntax.token(5, &lexing.names).length == 3); + t.expects(lexing.source.lines.length == 2); +} + +@test def sources_find_where_their_lines_begin(t: &mut tester): void { + val made := source::from("lines.sakura", "one\n\nthree\n"); + t.expects(made.lines.length == 4); + t.expects(made.lines.at(1) == 4 && made.lines.at(2) == 5 && made.lines.at(3) == 11); + + val at := made.lines.place_of(6); + t.expects(at.line == 3 && at.column == 2); +} + +@test def windows_line_breaks_read_as_those_of_other_systems(t: &mut tester): void { + val made := source::from("lines.sakura", "one\r\n\r\nthree\r\n"); + t.expects(made.length == 11); + t.expects(made.lines.length == 4); + t.expects(made.lines.at(1) == 4 && made.lines.at(2) == 5 && made.lines.at(3) == 11); + + # A CR on its own is no line break, and stays. + val alone := source::from("alone.sakura", "a\rb\r"); + t.expects(alone.length == 4 && alone.lines.length == 1); + + # A literal spanning lines holds the LF alone, wherever its text came from. + val crlf := lex("val a := \"\"\"\r\n x\r\n \"\"\";\r\n# note\r\nval b := 1;\r\n"); + val lf := lex("val a := \"\"\"\n x\n \"\"\";\n# note\nval b := 1;\n"); + t.expects(crlf.syntax.token_kinds.length == lf.syntax.token_kinds.length); + for i in 0..lf.syntax.token_kinds.length { + val ours := crlf.syntax.token(i as u32, &crlf.names); + val theirs := lf.syntax.token(i as u32, &lf.names); + t.expects(ours.kind == theirs.kind && ours.offset == theirs.offset + && crlf.source.make_lexeme(ours.offset as u64, ours.length as u64) == lf.source.make_lexeme(theirs.offset as u64, theirs.length as u64)); + } +} + +@test def numbers(t: &mut tester): void { + t.expects(lexes_as("1 12u 1.5 2f 0xff 0o17 0b101", tk::signed, tk::unsigned, tk::float, tk::float, tk::signed, tk::signed, tk::signed)); + + t.expects(lexes_as("0xFFu 0o17u 0b101u", tk::unsigned, tk::unsigned, tk::unsigned)); + + # An exponent makes a float, with or without a fraction or a sign, and `e` among + # hexadecimal digits is a digit. + t.expects(lexes_as("6.02e23 1e-9 2E+10 3e5f 0x1e5", tk::float, tk::float, tk::float, tk::float, tk::signed)); + t.expects(lexes_as("1e", tk::bad_number)); + t.expects(lexes_as("2ex", tk::bad_number)); + t.expects(lexes_as("1e5u", tk::bad_number)); + + # A fraction cannot be unsigned, and a suffix comes once. + t.expects(lexes_as("1.5u", tk::bad_number)); + t.expects(lexes_as("1uf", tk::bad_number)); + t.expects(lexes_as("2fu", tk::bad_number)); + + # `0..n` is a range, not a number with a fraction. + t.expects(lexes_as("0..n", tk::signed, tk::cascade, tk::name)); + + val bad := lex("val a := 0x;\nval b := 12ab;"); + t.expects(bad.syntax.token_kinds.at(4) == tk::bad_number); + t.expects(lex_noted(&bad, 1, 10, ec::token)); + t.expects(lex_noted(&bad, 2, 10, ec::token)); +} + +@test def operators_munch_as_much_as_they_can(t: &mut tester): void { + t.expects(lexes_as("... .. :: := => <<= <", tk::spread, tk::cascade, tk::scope, tk::colon, tk::assign, tk::arrow, tk::lshifteq, tk::less)); + t.expects(lexes_as("a++ && b-- || !c != d", tk::name, tk::increment, tk::logand, tk::name, tk::decrement, tk::logor, tk::negate, tk::name, tk::noteq, tk::name)); +} + +@test def a_greater_than_is_followed_by_what_is_left_of_it(t: &mut tester): void { + # Each `>` and `=` after the first `>` of an operator begins a token of what is + # left of it, so a `>` closing type arguments always has a token of its own. + t.expects(lexes_as(">", tk::more)); + t.expects(lexes_as(">>", tk::rshift, tk::more)); + t.expects(lexes_as(">=", tk::moreeq, tk::assign)); + t.expects(lexes_as(">>=", tk::rshifteq, tk::moreeq, tk::assign)); + t.expects(lexes_as(">>>=", tk::rshift, tk::more, tk::moreeq, tk::assign)); + + # What is left ends where the operator does. + t.expects(lexes_as(">==", tk::moreeq, tk::assign, tk::assign)); + t.expects(lexes_as("> > =", tk::more, tk::more, tk::assign)); +} + +@test def comments_are_skipped(t: &mut tester): void { + t.expects(lexes_as("a # a comment\n#! documentation\nb", tk::name, tk::name)); + + # Both are kept for the token after them, documentation apart from the rest. + val lexing := lex("a # a comment\n#! documentation\nb"); + val syntax := &lexing.syntax; + t.expects(syntax.comments.length == 1 && syntax.docs.length == 1); + t.expects(lexing.source.make_lexeme(syntax.comments.at(0).offset, syntax.comments.at(0).length) == "# a comment"); + t.expects(syntax.comments.at(0).token == 1 && syntax.docs.at(0).token == 1); +} + +@test def strings_and_characters(t: &mut tester): void { + t.expects(lexes_as("\"text\" 'c' '\\n' \"\\x41\\{\"", tk::string, tk::char, tk::char, tk::string)); + + val lexing := lex("\"\\q\" 'ab' '' 'é'"); + t.expects(lex_noted(&lexing, 1, 2, ec::escape)); + t.expects(lex_noted(&lexing, 1, 6, ec::char)); + t.expects(lex_noted(&lexing, 1, 11, ec::char)); + t.expects(lexing.notes.length == 3); +} + +@test def text_that_is_never_closed(t: &mut tester): void { + val lexing := lex("val s := \"open\nval c := 'x\n"); + t.expects(lexing.syntax.token_kinds.at(4) == tk::bad_quote); + t.expects(lex_noted(&lexing, 1, 10, ec::token)); + t.expects(lex_noted(&lexing, 2, 10, ec::token)); +} + +@test def text_spanning_lines(t: &mut tester): void { + val good := lex("val s := \"\"\"\n one\n\n two\n \"\"\";"); + t.expects(good.notes.length == 0); + t.expects(good.syntax.token_kinds.at(4) == tk::string); + + # Text on the opening line, the closing quotes after text, and a line indented + # less than the closing quotes. + t.expects(lex_noted(&lex("val s := \"\"\" x\n \"\"\";"), 1, 10, ec::block)); + t.expects(lex_noted(&lex("val s := \"\"\"\n x \"\"\";"), 2, 1, ec::block)); + t.expects(lex_noted(&lex("val s := \"\"\"\n x\n \"\"\";"), 2, 1, ec::block)); +} + +@test def interpolated_strings_split_at_their_holes(t: &mut tester): void { + t.expects(lexes_as("$\"plain\"", tk::istring)); + t.expects(lexes_as("$\"a{b}c{d}e\"", tk::istring_beg, tk::name, tk::istring_mid, tk::name, tk::istring_end)); + + # Braces within a hole are counted, so a struct literal there closes nothing. + t.expects(lexes_as("$\"{p{ x = 1 }}\"", tk::istring_beg, tk::name, tk::lbrace, tk::name, tk::assign, tk::signed, tk::rbrace, tk::istring_end)); + + # A string within a hole holds holes of its own. + t.expects(lexes_as("$\"a{$\"b{c}\"}\"", tk::istring_beg, tk::istring_beg, tk::name, tk::istring_end, tk::istring_end)); + + # A block's holes may span lines, where a line's may not. + t.expects(lexes_as("$\"\"\"\n {a +\n b}\n \"\"\"", tk::istring_beg, tk::name, tk::plus, tk::name, tk::istring_end)); + t.expects(lex("$\"\"\"\n {a}\n \"\"\"").notes.length == 0); +} + +@test def escapes_within_interpolated_strings(t: &mut tester): void { + val lexing := lex("$\"\\{ {a} \\q\""); + t.expects(lexing.notes.length == 1); + t.expects(lex_noted(&lexing, 1, 10, ec::escape)); +} + +@test def unknown_characters_are_reported_and_dropped(t: &mut tester): void { + val lexing := lex("a ` b"); + t.expects(lex_noted(&lexing, 1, 3, ec::token)); + t.expects(lexes_as("a ` b", tk::name, tk::name)); + + # A character beyond ASCII is reported once, however many bytes it takes. + val wide := lex("a é b"); + t.expects(wide.notes.length == 1 && lex_noted(&wide, 1, 3, ec::token)); + t.expects(wide.notes.at(0).length == 2); + t.expects(lexes_as("a é b", tk::name, tk::name)); +} + +@test def names_outlive_the_text_they_were_read_in(t: &mut tester): void { + var table := names::new(); + var text := string::from("fresh_name", nothing {}); + val view := text.view(); + val id := table.intern(&view); + + # The text a name was read in may change or go, as an editor's does. + text.at(0) = 'X'; + val again: strview = "fresh_name"; + t.expects(table.intern(&again) == id); +} diff --git a/tests/analyzer/names.sakura b/tests/analyzer/names.sakura new file mode 100644 index 00000000..72189ab6 --- /dev/null +++ b/tests/analyzer/names.sakura @@ -0,0 +1,19 @@ +#! @file names.sakura +#! @author John Christman (sorakatadzuma@gmail.com) +#! @copyright Malunal Studios, LLC. +#! @license MIT +#! +#! Contains the test that the reserved words follow the keywords, where the +#! names table interns them. + +import std::testing; +module sakura::analyzer; + + + +@test def reserved_words_follow_the_keywords(t: &mut tester): void { + var table := names::new(); + t.expects(table.is_keyword(table.intern("while")) && !table.is_keyword(table.intern("this"))); + t.expects(table.is_reserved(table.intern("this")) && table.is_reserved(table.intern("_"))); + t.expects(!table.is_reserved(table.intern("get")) && !table.is_reserved(table.intern("thing"))); +} diff --git a/tests/analyzer/parser.sakura b/tests/analyzer/parser.sakura new file mode 100644 index 00000000..3714a519 --- /dev/null +++ b/tests/analyzer/parser.sakura @@ -0,0 +1,285 @@ +#! @file parser.sakura +#! @author John Christman (sorakatadzuma@gmail.com) +#! @copyright Malunal Studios, LLC. +#! @license MIT +#! +#! Contains the tests of the parser: the trees declarations, statements, and +#! expressions parse into, as `syntax::print` writes them. + +import std::testing; +module sakura::analyzer; + + +# What each test expects is the tree `syntax::print` gives, where a node is +# `(kind:text slots...)`, or `kind:text` where its slots hold nothing. + +@test def assignment_else_and_ternaries_group_to_the_right(t: &mut tester): void { + t.expects(expression("a = b += c").view() == + "(assign:= name:a (assign:+= name:b name:c))"); + t.expects(expression("c ? d : e ? f : g").view() == + "(ternary name:c name:d (ternary name:e name:f name:g))"); + t.expects(expression("p else q else r").view() == + "(fallback name:p _ (fallback name:q _ name:r))"); + t.expects(expression("x = p else q").view() == + "(assign:= name:x (fallback name:p _ name:q))"); + # The branch taken where the condition holds ends at `:`, so it may be a + # fallback, and one after `:` takes the whole ternary, as before. + t.expects(expression("c ? p else q : r").view() == + "(ternary name:c (fallback name:p _ name:q) name:r)"); + t.expects(expression("c ? p else q ? s : t : r").view() == + "(ternary name:c (fallback name:p _ (ternary name:q name:s name:t)) name:r)"); + t.expects(expression("c ? p else (e) { return; } : r").view() == + "(ternary name:c (fallback name:p name:e (block [return_stmt])) name:r)"); + t.expects(expression("c ? p : q else r").view() == + "(fallback (ternary name:c name:p name:q) _ name:r)"); +} + +@test def binary_operators_group_by_precedence(t: &mut tester): void { + t.expects(expression("a || b && c | d ^ e & f == g < h << i + j * k").view() == + "(binary:|| name:a (binary:&& name:b (binary:| name:c (binary:^ name:d (binary:& name:e (binary:== name:f (binary:< name:g (binary:<< name:h (binary:+ name:i (binary:* name:j name:k))))))))))"); + t.expects(expression("-m as u8 + n").view() == + "(binary:+ (cast (unary:- name:m) type_name:u8) name:n)"); + t.expects(expression("true != null").view() == + "(binary:!= boolean:true null_lit:null)"); +} + +@test def is_tests_values_fields_and_types(t: &mut tester): void { + t.expects(expression("!k is not value(&mut v)").view() == + "(is_test (unary:! name:k) type_name:value (reference:& name:v {mutable}) {negated})"); + t.expects(expression("r is error(why)").view() == + "(is_test name:r type_name:error name:why)"); + t.expects(expression("x is (d)").view() == + "(is_test name:x name:d _ {computed})"); + t.expects(expression("T is copyable && T is not moveable").view() == + "(binary:&& (is_test name:T type_name:copyable _) (is_test name:T type_name:moveable _ {negated}))"); + t.expects(expression("type_of(d) is numeric").view() == + "(is_test (type_of:type_of name:d) type_name:numeric _)"); + t.expects(expression("box:: is Shown").view() == + "(is_test (path:box [(segment:box [type_name:T])]) type_name:Shown _)"); +} + +@test def postfix_operators_bind_tightest(t: &mut tester): void { + t.expects(expression("w.f(1)[2]++").view() == + "(postfix:++ (index (call (member:f name:w []) [number:1]) number:2))"); + t.expects(expression("xs[a:] + xs[:n] + xs[a:n]").view() == + "(binary:+ (binary:+ (slice name:xs name:a _) (slice name:xs _ name:n)) (slice name:xs name:a name:n))"); + t.expects(expression("x.(d)").view() == + "(member_of name:x name:d)"); + t.expects(expression("value_of(d)::").view() == + "(type_args (call name:value_of [name:d]) [type_name:i64])"); + t.expects(expression("max::(a, ...xs)").view() == + "(call (path:max [(segment:max [type_name:u8])]) [name:a (unary name:xs)])"); + t.expects(expression("std::io::print").view() == + "(path:std [segment:std segment:io segment:print])"); + t.expects(expression("*p = &mut x").view() == + "(assign:= (unary:* name:p) (reference:& name:x {mutable}))"); +} + +@test def else_names_the_error_only_before_a_block(t: &mut tester): void { + t.expects(expression("f(1) else 0").view() == + "(fallback (call name:f [number:1]) _ number:0)"); + t.expects(expression("f(1) else (e) { return; }").view() == + "(fallback (call name:f [number:1]) name:e (block [return_stmt]))"); + t.expects(expression("f(1) else (e) + 1").view() == + "(fallback (call name:f [number:1]) _ (binary:+ name:e number:1))"); + t.expects(expression("f(1) else { return; }").view() == + "(fallback (call name:f [number:1]) _ (block [return_stmt]))"); +} + +@test def literals_lambdas_and_matches(t: &mut tester): void { + t.expects(expression("point{ x = 1, 2 }").view() == + "(construct type_name:point [(field_init:x number:1 {named}) (field_init:2 number:2)])"); + t.expects(expression("[1, 2, 3,]").view() == + "(array [number:1 number:2 number:3])"); + t.expects(expression("def(a, b: i64) => a + b").view() == + "(lambda [param:a (param:b type_name:i64 _)] _ (binary:+ name:a name:b))"); + t.expects(expression("def(): i64 { return 1; }").view() == + "(lambda [] type_name:i64 (block [(return_stmt number:1)]))"); + t.expects(statements("val v := match k { 1, 2 => a, else => b };").view() == + "(variable:v [] _ _ (match_value name:k [(match_arm:1 [number:1 number:2] name:a) (match_arm [] name:b)]))"); + t.expects(expression("$\"a{b}c{d + 1}e\"").view() == + "(istring:$\"a{ [string:$\"a{ name:b string:}c{ (binary:+ name:d number:1) string:}e\"])"); + t.expects(expression("$\"plain\"").view() == + "(istring:$\"plain\" [string:$\"plain\"])"); +} + +@test def conditions_and_jumps(t: &mut tester): void { + t.expects(statements("if a {} else if b {} else {}").view() == + "(if_stmt name:a block (if_stmt name:b block block))"); + t.expects(statements("if const T is integer {}").view() == + "(if_const (is_test name:T type_name:integer _) block _)"); + t.expects(statements("if x == y { }").view() == + "(if_stmt (binary:== name:x name:y) block _)"); + t.expects(statements("return x if a;").view() == + "(if_stmt name:a (block [(return_stmt name:x)]) _)"); + t.expects(statements("break if const n > 1;").view() == + "(if_const (binary:> name:n number:1) (block [break_stmt]) _)"); +} + +@test def loops_and_matches(t: &mut tester): void { + t.expects(statements("for i, &mut x in xs {}").view() == + "(for_stmt name:i name:x name:xs _ {mutable,reference} block)"); + t.expects(statements("for const x in args {}").view() == + "(for_stmt _ name:x name:args _ {constant} block)"); + t.expects(statements("for i in 0..n {}").view() == + "(for_stmt _ name:i number:0 name:n block)"); + # A loop counts through a range written in place itself, and walks one + # made as a value otherwise. + t.expects(statements("for i in 0..=n {}").view() == + "(for_stmt _ name:i number:0 name:n {inclusive} block)"); + t.expects(statements("for i in (0..n).rev() {}").view() == + "(for_stmt _ name:i (call (member:rev (range:.. number:0 name:n) []) []) _ block)"); + t.expects(statements("while a { continue; }").view() == + "(while_stmt name:a (block [continue_stmt]))"); + t.expects(statements("match k { 1 => a(); else => { b(); } }").view() == + "(match_stmt name:k [(match_arm:1 [number:1] (block:a [(expr_stmt:a (call name:a []))])) (match_arm [] (block [(expr_stmt:b (call name:b []))]))])"); +} + +@test def ranges_are_written_as_values(t: &mut tester): void { + # `..` and `..=` bind looser than every binary operator, and tighter than + # `?:`. + t.expects(expression("a + 1..b * 2").view() == "(range:.. (binary:+ name:a number:1) (binary:* name:b number:2))"); + t.expects(expression("lo..=hi").view() == "(range:..= name:lo name:hi)"); + t.expects(expression("f(0..n, 1..=2)").view() == "(call name:f [(range:.. number:0 name:n) (range:..= number:1 number:2)])"); +} + +@test def locals_and_local_functions(t: &mut tester): void { + t.expects(statements("val x := 1; var y: i64; const z: u8 = 2;").view() == + "(variable:x [] _ _ number:1) (variable:y [] _ type_name:i64 _ {mutable}) (variable:z [] _ type_name:u8 number:2 {constant})"); + t.expects(statements("def local(a: i64): i64 { return a; }").view() == + "(variable:local [] _ _ (lambda [(param:a type_name:i64 _)] type_name:i64 (block [(return_stmt name:a)])) {function})"); + t.expects(statements("when os == linux { f(); } else when !(arch != x86_64) {} else {}").view() == + "(when_block (binary:== name:os name:linux) (block [(expr_stmt:f (call name:f []))]) (when_block (unary:! (binary:!= name:arch name:x86_64)) block block))"); +} + +@test def contracts_are_statements_their_words_begin(t: &mut tester): void { + t.expects(statements("expects(b != 0); asserts(ok, \"Fine.\"); ensures(r: r > old(n));").view() == + "(contract:expects (binary:!= name:b number:0) _ _) (contract:asserts name:ok _ string:\"Fine.\") (contract:ensures (binary:> name:r (old_value:old name:n)) name:r _)"); + # Anywhere else, each word is a name, and `old` is one outside an `ensures`. + t.expects(statements("t.expects(x); f(asserts); ensures = 1; val v := old(2); asserts + 1;").view() == + "(expr_stmt:t (call (member:expects name:t []) [name:x])) (expr_stmt:f (call name:f [name:asserts])) (expr_stmt:ensures (assign:= name:ensures number:1)) (variable:v [] _ _ (call name:old [number:2])) (expr_stmt:asserts (binary:+ name:asserts number:1))"); +} + +@test def undefined_is_a_variables_value_alone(t: &mut tester): void { + # Anywhere but as the whole of a variable's value, the word is a name. + t.expects(statements("var b: u8[4] = undefined; var u := undefined + 1; val undefined := 2;").view() == + "(variable:b [] _ (type_fixed type_name:u8 number:4) undefined:undefined {mutable}) (variable:u [] _ _ (binary:+ name:undefined number:1) {mutable}) (variable:undefined [] _ _ number:2)"); +} + +@test def imports_modules_and_when(t: &mut tester): void { + t.expects(tree("import std::io;").view() == + "(document [(import_decl (path:std [segment:std segment:io]))])"); + t.expects(tree("module a::b when os == linux && backend == vm;").view() == + "(document [(module_decl (path:a [segment:a segment:b]) (binary:&& (binary:== name:os name:linux) (binary:== name:backend name:vm)))])"); + t.expects(tree("when os == linux { def f(): void {} } else { val x := 1; }").view() == + "(document [(when_block (binary:== name:os name:linux) (block [(function:f [] _ [] [] type_name:void block)]) (block [(variable:x [] _ _ number:1)]))])"); +} + +@test def extern_names_libraries_and_sections_of_c(t: &mut tester): void { + t.expects(tree("extern import \"libc.so.6\" when os == linux; extern module c when os == linux; extern module d;").view() == + "(document [(extern_import string:\"libc.so.6\" (binary:== name:os name:linux)) (extern_module path:c (binary:== name:os name:linux)) (extern_module path:d _)])"); + # `extern` begins an import of a library or a section, and a library is text. + val stray := parse("extern def f(): void;"); + t.expects(noted(&stray, 1, 8, ec::token)); + val unnamed := parse("extern import libc;"); + t.expects(noted(&unnamed, 1, 15, ec::token)); +} + +@test def functions(t: &mut tester): void { + t.expects(tree("@doc{ text = \"x\" } pub def box::map(&mut this, f: def(T): U, n: u64 = 0, xs: U...): box where T: copyable where U: equatable, hashable;").view() == + "(document [(function:map [(attribute type_name:doc [(field_init:text string:\"x\" {named})])] (type_name:box [(segment:box [(type_param:T [type_name:copyable])])]) [(type_param:U [type_name:equatable type_name:hashable])] [(param:this _ _ {mutable}) (param:f (type_func [type_name:T] type_name:U) _) (param:n type_name:u64 number:0) (param:xs type_name:U _ {variadic})] (type_name:box [(segment:box [type_name:U])]) _ {exported})])"); + t.expects(tree("const def zero(): i64 { return 0; }").view() == + "(document [(function:zero [] _ [] [] type_name:i64 (block [(return_stmt number:0)]) {constant})])"); +} + +@test def structs_unions_and_traits(t: &mut tester): void { + t.expects(tree("struct pair : copyable { var a: A; val b: ...base{ x as y }; }").view() == + "(document [(struct_decl:pair [] _ [type_param:A (type_param:Bs [] {packed})] [type_name:copyable] [(field:a [] _ type_name:A _ {mutable}) (field:b [] _ (spread type_name:base [(rename:x name:y)]) _)])])"); + t.expects(tree("union either { var l: i64; var r: str; }").view() == + "(document [(union_decl:either [] _ [] [] [(field:l [] _ type_name:i64 _ {mutable}) (field:r [] _ type_name:str _ {mutable})])])"); + t.expects(tree("trait shown : equatable { def show(&this): str; type cursor: iterator<&T> = span::cursor; val n: u64 { get; } const k: u8; }").view() == + "(document [(trait_decl:shown [] _ [] [type_name:equatable] [(function:show [] _ [] [param:this] type_name:str _) (assoc_type:cursor [] [(type_name:iterator [(segment:iterator [(type_ref:& type_name:T)])])] (type_name:span [(segment:span [type_name:T]) segment:cursor])) (property:n [] _ type_name:u64 [(accessor:get [(param:this _ _ {implied})] _)]) (variable:k [] _ type_name:u8 _ {constant})])])"); +} + +@test def trait_methods_bound_the_traits_parameters_and_self(t: &mut tester): void { + # A trait's method may bound the trait's parameters or `self` beyond what the + # trait does, which the record keeps apart from its own parameters. + t.expects(tree("trait shelf { def total(&this): T where T: numeric; def tagged(&this): U where self: labeled where U: shown; }").view() == + "(document [(trait_decl:shelf [] _ [type_param:T] [] [(function:total [] _ [] [param:this] type_name:T _ [(type_param:T [type_name:numeric])]) (function:tagged [] _ [(type_param:U [type_name:shown])] [param:this] type_name:U _ [(type_param:self [type_name:labeled])])])])"); +} + +@test def fields_are_pub_where_marked(t: &mut tester): void { + t.expects(tree("struct s { pub var a: i64; @x pub val b: u8; var c: u8; }").view() == + "(document [(struct_decl:s [] _ [] [] [(field:a [] _ type_name:i64 _ {exported,mutable}) (field:b [(attribute type_name:x [])] _ type_name:u8 _ {exported}) (field:c [] _ type_name:u8 _ {mutable})])])"); + val twice := parse("struct s { pub pub var a: i64; }"); + t.expects(noted(&twice, 1, 16, ec::token)); +} + +@test def properties_enums_and_aliases(t: &mut tester): void { + t.expects(tree("pub var rect::area: u64 { get => 1; pub set {} }").view() == + "(document [(property:area [] (type_name:rect [segment:rect]) type_name:u64 {exported,mutable} [(accessor:get [(param:this _ _ {implied})] (block [(return_stmt number:1)])) (accessor:set [(param:this _ _ {mutable,implied}) (param:value _ _ {implied})] block {exported})])])"); + # `=>` gives what a `get` returns, and is what a `set` does; the parameters + # are implied, and written ones refused. + t.expects(tree("var r::w: i64 { get => this.n; set => this.n = value; }").view() == + "(document [(property:w [] (type_name:r [segment:r]) type_name:i64 {mutable} [(accessor:get [(param:this _ _ {implied})] (block [(return_stmt (member:n name:this []))])) (accessor:set [(param:this _ _ {mutable,implied}) (param:value _ _ {implied})] (block [(expr_stmt (assign:= (member:n name:this []) name:value))]))])])"); + val written := parse("var r::w: i64 { get(&this) { return 1; } }"); + t.expects(noted(&written, 1, 20, ec::token)); + t.expects(tree("enum color : u8 { red, @old green = 2, blue, }").view() == + "(document [(enumeration:color [] _ type_name:u8 [enumerator:red (enumerator:green [(attribute type_name:old [])] number:2) enumerator:blue])])"); + t.expects(tree("type list::cursor = span::cursor where T: copyable;").view() == + "(document [(alias:cursor [] (type_name:list [(segment:list [type_param:T])]) [] (type_name:span [(segment:span [type_name:T]) segment:cursor]))])"); +} + +@test def types(t: &mut tester): void { + t.expects(tree("val m: dict> = make();").view() == + "(document [(variable:m [] _ (type_name:dict [(segment:dict [type_name:str (type_name:vec [(segment:vec [type_name:i64])])])]) (call name:make []))])"); + t.expects(tree("val p: *mut u8[4][2] = null; val r: &mut def(u8): bool = f;").view() == + "(document [(variable:p [] _ (type_ptr:* (type_fixed (type_fixed type_name:u8 number:4) number:2) {mutable}) null_lit:null) (variable:r [] _ (type_ref:& (type_func [type_name:u8] type_name:bool) {mutable}) name:f)])"); + t.expects(tree("val t: type_of(d) = x;").view() == + "(document [(variable:t [] _ (type_of:type_of name:d) name:x)])"); +} + +@test def spreads_and_patterns_among_types(t: &mut tester): void { + t.expects(tree("val f: def(i64, bool...): u8 = g; val b: box = x;").view() == + "(document [(variable:f [] _ (type_func [type_name:i64 (type_spread type_name:bool)] type_name:u8) name:g) (variable:b [] _ (type_name:box [(segment:box [type_name:i64 (type_spread type_name:Ts)])]) name:x)])"); + t.expects(tree("trait t { type p...; }").view() == + "(document [(trait_decl:t [] _ [(type_pattern [type_param:A (type_param:Ts [] {packed})] type_param:R)] [] [(assoc_type:p [] [] {packed} _)])])"); +} + +# A pattern of a fixed array, `L[N]`, names its element's type parameter and its +# length's constant one, among a declaration's type parameters and a receiver's. +@test def array_patterns_among_type_parameters(t: &mut tester): void { + t.expects(tree("struct simd where L: numeric { var lanes: L[N]; }").view() == + "(document [(struct_decl:simd [] _ [(array_pattern:L (type_param:L [type_name:numeric]) const_param:N)] [] [(field:lanes [] _ (type_fixed type_name:L name:N) _ {mutable})])])"); + t.expects(tree("def simd::count(&this): u64 { return N; }").view() == + "(document [(function:count [] (type_name:simd [(segment:simd [(array_pattern:L type_param:L const_param:N)])]) [] [param:this] type_name:u64 (block [(return_stmt name:N)]))])"); +} + +@test def a_greater_than_closes_type_arguments_or_operates(t: &mut tester): void { + t.expects(expression("a >> b >= c").view() == + "(binary:>= (binary:>> name:a name:b) name:c)"); + t.expects(expression("a >>= b").view() == + "(assign:>>= name:a name:b)"); + + # `>>` and `>>=` close nested type arguments a `>` at a time, and what is left + # after the last is what follows them. + t.expects(expression("x as box> y").view() == + "(binary:> (cast name:x (type_name:box [(segment:box [type_name:u8])])) name:y)"); + t.expects(expression("x as box>>= y").view() == + "(binary:>= (cast name:x (type_name:box [(segment:box [(type_name:box [(segment:box [type_name:u8])])])])) name:y)"); + t.expects(statements("var v: box>= w;").view() == + "(variable:v [] _ (type_name:box [(segment:box [(type_name:box [(segment:box [type_name:u8])])])]) name:w {mutable})"); +} + +# A constant parameter is written `const N: u64`, and is given a value: a literal, +# a name, or an expression of them, within which `>` closes the arguments. +@test def constant_parameters_and_arguments(t: &mut tester): void { + t.expects(tree("struct buffer { var items: T[N]; }").view() == + "(document [(struct_decl:buffer [] _ [type_param:T (const_param:N [] type_name:u64)] [] [(field:items [] _ (type_fixed type_name:T name:N) _ {mutable})])])"); + t.expects(tree("val b: grid = x;").view() == + "(document [(variable:b [] _ (type_name:grid [(segment:grid [(binary:* name:N number:2) type_name:M])]) name:x)])"); + t.expects(tree("val p: at = x;").view() == + "(document [(variable:p [] _ (type_name:at [(segment:at [(construct type_name:point [(field_init:x number:1 {named})]) string:\"t\" (unary:- number:1) (array [number:1 number:2])])]) name:x)])"); + t.expects(expression("make:: b)>()").view() == + "(call (path:make [(segment:make [(binary:+ name:N number:1) (binary:> name:a name:b)])]) [])"); +} diff --git a/tests/analyzer/queries.sakura b/tests/analyzer/queries.sakura new file mode 100644 index 00000000..74ce895a --- /dev/null +++ b/tests/analyzer/queries.sakura @@ -0,0 +1,477 @@ +#! @file queries.sakura +#! @author John Christman (sorakatadzuma@gmail.com) +#! @copyright Malunal Studios, LLC. +#! @license MIT +#! +#! Contains the tests of the queries an editor asks of a checked program: what +#! hovering a name shows, what it refers to and where that is written, what +#! may be written at a place, what a call being written calls, and what each +#! name of a file is. + +import std::testing; +module sakura::analyzer; + + +@test def hovering_a_declaration_shows_how_it_is_declared(t: &mut tester): void { + val text := """ + #! A point on the plane. + pub struct point { + pub var x: i64; #! Across. + var y: i64 = 7; + } + #! How far across. + #! @param p The point. + pub def across(p: &point): i64 { return p.x; } + def point::moved(&this, by: i64): point { return point { x = this.x + by, y = this.y }; } + enum color: u8 { red, green = 4 } + const limit: u32 = 9; + def f(): void { + var p := point { x = 1 }; + val q := p.moved(2); + val c := color::green; + val n := across(&q) + limit as i64; + } + """; + t.expects(hover_of(text, "point {", 0).view() == "pub struct point {\n pub var x: int;\n var y: int;\n}\n\nA point on the plane."); + t.expects(hover_of(text, "x: i64").view() == "pub var x: int\n\nAcross."); + t.expects(hover_of(text, "across(p").view() == "pub def across(p: &point): int\n\nHow far across.\n@param p The point."); + t.expects(hover_of(text, "p: &point").view() == "p: &point\n\nThe point."); + t.expects(hover_of(text, "moved(2)").view() == "def point::moved(this: &point, by: int): point"); + t.expects(hover_of(text, "color: u8").view() == "enum color: u8 {\n red = 0,\n green = 4,\n}"); + t.expects(hover_of(text, "green;").view() == "color::green = 4"); + t.expects(hover_of(text, "limit as").view() == "const limit: u32"); + t.expects(hover_of(text, "p := point").view() == "var p: point"); + t.expects(hover_of(text, "q := p").view() == "val q: point"); + t.expects(hover_of(text, "y = this", 0).view() == "var y: int"); + t.expects(hover_of(text, "i64; #!").view() == "type int"); + t.expects(hover_of(text, "return p.x").view() == ""); +} + +@test def hovering_names_through_modules_and_generics(t: &mut tester): void { + val lib := """ + module shapes; + pub struct box { pub var item: T; } + pub def box::get(&this): T { return this.item; } + """; + val text := """ + import shapes; + def f(b: shapes::box): u8 { return b.item + b.get(); } + """; + t.expects(asked(def(c: &mut checker): string { + var made := string::new(nothing {}); + var at := c.hover(0, place_in(text, "shapes::box", 0)) else { return made; }; + made.append(at.signature.view()); + made.append("|"); + var box := c.hover(0, place_in(text, "box")) else { return made; }; + made.append(box.signature.view()); + made.append("|"); + var item := c.hover(0, place_in(text, "item +")) else { return made; }; + made.append(item.signature.view()); + return made; + }, text, lib).view() == "module shapes|pub struct box {\n pub var item: T;\n}|pub var item: u8"); +} + +@test def hovering_a_call_writes_a_pack_as_the_types_it_gives(t: &mut tester): void { + val text := """ + def count(xs: Ts...): i64 { return 0; } + def f(): i64 { return count(1, true); } + """; + # The pack given for `Ts` is written as notes write it, rather than as `(int, bool)`. + val shown := hover_of(text, "count(1"); + t.expects(shown.view().starts_with("def count(")); +} + +#! Where each place a query gives is, as `line:column` of the file it is in, +#! each file named by its index, joined by spaces. +#! @param c The checker. +#! @param places The places. +#! @returns The text. +def places_text(c: &mut checker, places: &vector): string { + var made := string::new(nothing {}); + for &each in places { + val at := c.units[each.file].source.lines.place_of(each.offset); + val text := $"{each.file}:{at.line}:{at.column}"; + if made.length != 0 { + made.append(" "); + } + made.append(text.view()); + } + return made; +} + +@test def names_go_to_where_they_are_declared(t: &mut tester): void { + val lib := """ + module shapes; + pub struct box { pub var w: i64; } + pub def area(b: &box): i64 { return b.w; } + """; + val text := """ + import shapes; + def f(n: i64): i64 { + val b := box { w = n }; + return area(&b) + b.w + n; + } + """; + t.expects(asked(def(c: &mut checker): string { + var made := string::new(nothing {}); + for &needle in ["area(&b)", "w + n", "b.w", "n;", "box {", "w = n", "shapes;", "i64 {"] { + var named := c.name_at(0, place_in(text, needle)) else { + made.append("none|"); + continue; + }; + var places := vector::::new(); + if named.declared { + places.append(named.declaration); + } + var shown := places_text(c, &places); + made.append(shown.view()); + if named.refusal.length != 0 { + made.append("!"); + } + made.append("|"); + } + return made; + }, text, lib).view() == "1:3:9|1:2:26|0:3:7|0:2:7|1:2:12|1:2:26|1:1:8!|!|"); +} + +@test def references_are_every_place_a_name_is_written(t: &mut tester): void { + val lib := """ + module shapes; + pub struct box { pub var w: i64; } + pub def area(b: &box): i64 { return b.w; } + """; + val text := """ + import shapes; + def f(n: i64): i64 { + val b := box { w = n }; + return area(&b) + b.w + n; + } + def g(): i64 { return area(&box { w = 2 }); } + """; + t.expects(asked(def(c: &mut checker): string { + var made := string::new(nothing {}); + for &needle in ["area(&b)", "w + n", "n;", "b :="] { + var found := c.references(0, place_in(text, needle)); + var shown := places_text(c, &found); + made.append(shown.view()); + made.append("|"); + } + return made; + }, text, lib).view() == "1:3:9 0:4:10 0:6:23|1:2:26 1:3:39 0:3:18 0:4:23 0:6:35|0:2:7 0:3:22 0:4:27|0:3:7 0:4:16 0:4:21|"); +} + +@test def a_trait_method_is_renamed_with_those_implementing_it(t: &mut tester): void { + val text := """ + trait shape { def area(&this): i64; } + struct square : shape { var w: i64; } + def square::area(&this): i64 { return this.w * this.w; } + struct dot {} + def dot::area(&this): i64 { return 0; } + def f(s: &square): i64 { return s.area(); } + """; + t.expects(asked(def(c: &mut checker): string { + var found := c.references(0, place_in(text, "area(&this): i64;")); + return places_text(c, &found); + }, text).view() == "0:1:19 0:3:13 0:6:35"); +} + +@test def renaming_refuses_what_the_compiler_finds_by_name(t: &mut tester): void { + val text := """ + def main(): void { val n: i64 = 1; } + struct box {} + def box::get(&this): i64 { return 0; } + """; + t.expects(asked(def(c: &mut checker): string { + var made := string::new(nothing {}); + for &needle in ["main", "i64", "this)", "box {}"] { + var named := c.name_at(0, place_in(text, needle)) else { + made.append("none|"); + continue; + }; + made.append(named.refusal); + made.append("|"); + } + return made; + }, text).view() == "A program begins at the function named `main`.|It is built into the language.|`this` is what every method calls its receiver.||"); +} + +@test def accessors_name_this_and_value_where_they_are_used(t: &mut tester): void { + val text := """ + struct r { var w: i64; } + var r::width: i64 { + get => this.w; + set => this.w = value; + } + """; + t.expects(hover_of(text, "value;").view() == "value: int"); + t.expects(hover_of(text, "this.w;").view() == "this: &r"); + t.expects(asked(def(c: &mut checker): string { + var made := string::new(nothing {}); + for &needle in ["value;", "set =>"] { + var named := c.name_at(0, place_in(text, needle)) else { + made.append("none|"); + continue; + }; + made.append(named.refusal); + made.append("|"); + } + return made; + }, text).view() == "`value` is what every `set` calls what it is given.|none|"); +} + +@test def renaming_refuses_the_methods_operators_call(t: &mut tester): void { + # A type has `+` by its `add`, so renaming the method would lose the operator, + # but one of the name taking something else than an operand is only a method. + val text := """ + struct box { var w: i64; } + def box::add(&this, other: &box): box { return box { w = this.w + other.w }; } + def box::negate(&this): box { return box { w = -this.w }; } + def box::mul(&this, by: &i64, more: &i64): box { return box { w = this.w * by * more }; } + def box::grown(&this): box { return this + this; } + """; + t.expects(asked(def(c: &mut checker): string { + var made := string::new(nothing {}); + for &needle in ["add(&this", "negate(&this", "mul(&this", "grown(&this"] { + var named := c.name_at(0, place_in(text, needle)) else { + made.append("none|"); + continue; + }; + made.append(named.refusal.length != 0 ? "refused|" : "renamed|"); + } + return made; + }, text).view() == "refused|refused|renamed|renamed|"); +} + +@test def hovering_a_function_shows_the_contract_its_body_begins_with(t: &mut tester): void { + val text := """ + #! Divides. + def divide(a: i64, b: i64): i64 { + expects(b != 0, + "Nothing is divided by zero."); + ensures(q: q * b + a % b == a); + asserts(b > 0); + return a / b; + } + def f(): void { val q := divide(7, 2); } + """; + t.expects(hover_of(text, "divide(7").view() == + "def divide(a: int, b: int): int\nexpects(b != 0, \"Nothing is divided by zero.\")\nensures(q: q * b + a % b == a)\n\nDivides."); +} + +@test def contracts_are_coloured_as_words_of_the_language(t: &mut tester): void { + val text := "def f(n: i64): i64 { expects(n > 0); ensures(r: r > old(n)); return n + 1; }"; + t.expects(asked(def(c: &mut checker): string { + var made := string::new(nothing {}); + for &each in c.highlights(0) { + continue if each.kind != symbol::keyword; + made.append(text.substr(each.offset as u64, each.length as u64)); + made.append(" "); + } + return made; + }, text).view() == "expects ensures old "); +} + +@test def undefined_is_coloured_as_a_word_of_the_language_where_it_is_one(t: &mut tester): void { + val text := "def f(): u64 { var b: u64[2] = undefined; val undefined: u64 = 1; return undefined; }"; + t.expects(asked(def(c: &mut checker): string { + var made := string::new(nothing {}); + for &each in c.highlights(0) { + continue if text.substr(each.offset as u64, each.length as u64) != "undefined"; + made.append($"{each.offset}:{each.kind == symbol::keyword} "); + } + return made; + }, text).view() == "31:true 46:false 73:false "); +} + +@test def names_are_coloured_by_what_they_are(t: &mut tester): void { + val text := "struct p { var x: i64; }\ndef f(a: p): i64 { val y := a.x; return y; }"; + t.expects(asked(def(c: &mut checker): string { + var made := string::new(nothing {}); + val found := c.highlights(0); + for &each in found { + val name := text.substr(each.offset as u64, each.length as u64); + val line := $"{name}:{each.kind as u32}{each.declared ? "+" : ""}{each.readonly ? "r" : ""} "; + made.append(line.view()); + } + return made; + }, text).view() == "p:8+ x:7+ i64:12r f:2+ a:6+ p:8r i64:12r y:4+r a:6 x:7 y:4r "); +} + +#! The names completion offers at a place, joined by spaces. +#! @param text The program's text, of one file. +#! @param needle Where in it the place is. +#! @param skip How far into the needle the place is. +#! @param others The other files. +#! @returns The names. +def completed(text: strview, needle: strview, skip: u32, others: strview...): string { + var texts := vector::::new(); + texts.append(text); + for &each in others { + texts.append(each); + } + return asked(def(c: &mut checker): string { + var made := string::new(nothing {}); + val found := c.complete(0, place_in(text, needle, skip)); + for &each in found { + break if each.kind == symbol::keyword && each.name.view() != "else"; + if made.length != 0 { + made.append(" "); + } + made.append(each.name.view()); + if each.insert.length != 0 { + made.append("="); + made.append(each.insert.view()); + } + } + return made; + }, ...texts.view()); +} + +@test def completion_offers_what_the_place_takes(t: &mut tester): void { + val text := """ + struct point { var x: i64; var y: i64; } + def point::norm(&this): i64 { return this.x; } + enum color { red, green } + def f(p: point, c: color): i64 { + val q := point { x = 1, }; + val n := p.sakura__completion; + match c { red => {} } + return 0; + } + """; + t.expects(completed(text, ".sakura__completion", 1).view() == "x y norm"); + t.expects(completed(text, "x = 1, ", 7).view().starts_with("y=y = p c point color f ")); + t.expects(completed(text, "red => {} }", 10).view() == "green=green => else=else => "); + val locals := completed(text, "return 0", 7); + t.expects(locals.view().starts_with("q n p c point color f ")); +} + +@test def completion_offers_the_names_a_pattern_binds(t: &mut tester): void { + val text := """ + struct lanes { var items: L[N]; } + def lanes::count(&this): u64 { + return N; + } + """; + t.expects(completed(text, "return N", 7).view().starts_with("this L N ")); +} + +@test def signature_help_shows_what_is_called(t: &mut tester): void { + val text := """ + #! Adds. + #! @param a The first. + def add(a: i64, b: i64): i64 { return a + b; } + def add(a: i64): i64 { return a; } + def f(): i64 { return add(1, 2); } + """; + t.expects(asked(def(c: &mut checker): string { + var made := string::new(nothing {}); + var help := c.calls_at(0, place_in(text, "2);")) else { return made; }; + for &each in help.overloads { + made.append(each.signature.view()); + made.append("|"); + } + val line := $"{help.parameter}"; + made.append(line.view()); + return made; + }, text).view() == "def add(a: int, b: int): int|def add(a: int): int|1"); +} + +@test def an_edit_parsing_a_file_whole_again_checks_it_anew(t: &mut tester): void { + # Taking away the `}` of the first function has it swallow the last, which has + # the file parsed whole again and every node made anew, so what was kept of + # the old ones, as the nodes of the functions taken away, is let go of. + val before := """ + def a(): i64 { return 1; } + def b(): i64 { return a() + 2; } + def c(): i64 { return b() + 3; } + def d(): i64 { return c() + 4; } + def e(): i64 { return 5; } + """; + t.expects(hovers_after_edits(before, "def a(): i64 { return 1;\ndef e(): i64 { return 5; }\n").view() == ""); + t.expects(hovers_after_edits(before, "def a(): i64 { return 1;\ndef e(): i64 { return 5; }\n", before).view() == ""); +} + +@test def an_edit_keeps_what_was_worked_out_of_each_file_apart(t: &mut tester): void { + # Another file whose top-level declaration has the same node as one the edit + # keeps, but whose nodes begin elsewhere, leaves what is kept of this one as + # it was. + val before := """ + def f(n: i64): i64 { return n; } + def g(n: i64): i64 { val m := n + 1; return m * f(m); } + """; + val after := """ + def f(n: i64): i64 { return n + 0; } + def g(n: i64): i64 { val m := n + 1; return m * f(m); } + """; + val kept: u64 = top_nodes(before)[1]; + var other := string::new(nothing {}); + for pad in 0u..24u { + var text := string::from("def p(): void { ", nothing {}); + for _ in 0..(pad / 3) { + text.append("val x := 1; "); + } + for _ in 0..(pad % 3) { + text.append("1; "); + } + text.append("}\n"); + for _ in 0..8 { + text.append("def q(): void {}\n"); + } + for &each in top_nodes(text.view()) { + if each >> 32 == kept >> 32 && (each & 0xFFFFFFFF) > (kept & 0xFFFFFFFF) { + other = move(&mut text); + break; + } + } + break if other.length != 0; + } + t.expects(other.length != 0); + var others := vector::::new(); + others.append(other.view()); + t.expects(hovers_after_edits_with(others.view(), before, after).view() == ""); +} + +@test def queries_after_edits_answer_as_a_whole_check_does(t: &mut tester): void { + val before := """ + struct adder { var calls: i64; } + def adder::add(&mut this, a: i64, b: i64): i64 { this.calls++; return a + b; } + def make(): adder { return adder {}; } + def main(): void { + var a := adder {}; + val n := a.add(1, 2); + } + """; + val typing := """ + struct adder { var calls: i64; } + def adder::add(&mut this, a: i64, b: i64): i64 { this.calls++; return a + b; } + def make(): adder { return adder {}; } + def main(): void { + var a := adder {}; + val q := a. + val n := a.add(1, 2); + } + """; + val completing := """ + struct adder { var calls: i64; } + def adder::add(&mut this, a: i64, b: i64): i64 { this.calls++; return a + b; } + def make(): adder { return adder {}; } + def main(): void { + var a := adder {}; + val q := a.sakura__completion + val n := a.add(1, 2); + } + """; + val wrong := """ + struct adder { var calls: i64; } + def adder::add(&mut this, a: i64, b: i64): i64 { this.calls++; return a + b; } + def make(): u8 { return adder {}; } + def main(): void { + var a := adder {}; + val q := a.calls; + val r: bool = 5; + val n := a.add(1, 2) + make(); + } + """; + t.expects(hovers_after_edits(before, typing, completing, wrong, before).view() == ""); +} diff --git a/tests/analyzer/reading.sakura b/tests/analyzer/reading.sakura new file mode 100644 index 00000000..48a728ab --- /dev/null +++ b/tests/analyzer/reading.sakura @@ -0,0 +1,146 @@ +#! @file reading.sakura +#! @author John Christman (sorakatadzuma@gmail.com) +#! @copyright Malunal Studios, LLC. +#! @license MIT +#! +#! Contains the tests of reading files on threads, which must read them as one +#! thread does: each word given the same ID, each file the same tokens and +#! nodes, and the same notes heard of each, and of hearing notes as they are +#! made, rather than finding them kept. + +import std::testing; +module sakura::analyzer; + + +#! What reading files made: the names, each file's syntax and `document` node, +#! what was noted of each, and how many times each was heard read whole. +struct read_whole { + var names: names; + var sources: vector; + var syntaxes: vector; + var roots: vector; + var notes: vector>; + var reads: vector; +} + +#! Reads files on a number of threads. +#! @param threads How many threads read them. +#! @param texts The files' texts. +#! @returns What reading them made. +def read_on(threads: u32, texts: span): read_whole { + var made := read_whole { + names = names::new(), + sources = vector::::new(), + syntaxes = vector::::new(), + roots = vector::::new(), + notes = vector::>::new(), + reads = vector::::new() + }; + made.sources.reserve(texts.length); + made.syntaxes.reserve(texts.length); + for i in 0..texts.length { + made.sources.append(source::from("test.sakura", texts[i])); + made.syntaxes.append(syntax::new()); + } + made.notes.resize(texts.length); + made.reads.resize(texts.length); + + # What is heard of a file is heard on the thread reading it, so each file's + # vector is written by one thread alone. + val notes := &mut made.notes; + val reads := &mut made.reads; + val heard := listener { + noted = def(each: &mut note): void { notes[each.file as u64].append(move(each)); }, + read = def(file: u32): void { reads[file as u64] += 1; } + }; + read_files(&made.sources, &mut made.syntaxes, &mut made.roots, &mut made.names, threads, &heard, 0, texts.length); + return made; +} + +#! Whether two readings made the same: names, tokens, nodes, and notes. +#! @param a One reading. +#! @param b The other. +#! @returns Whether they did. +def read_alike(a: &read_whole, b: &read_whole): bool { + return false if a.names.count != b.names.count; + for id in 0..a.names.count { + return false if a.names.text(id as u32) != b.names.text(id as u32); + } + for j in 0..a.syntaxes.length { + val x := &a.syntaxes.at(j); + val y := &b.syntaxes.at(j); + return false if a.roots.at(j) != b.roots.at(j) || x.token_count != y.token_count || x.node_count != y.node_count; + for k in 0..x.token_count { + val p := x.token(k as u32, &a.names); + val q := y.token(k as u32, &b.names); + return false if p.kind != q.kind || p.offset != q.offset || p.name != q.name; + } + for k in 0..x.node_count { + return false if x.node_kinds.at(k) != y.node_kinds.at(k) || x.node_tokens.at(k) != y.node_tokens.at(k); + } + return false if a.notes.at(j).length != b.notes.at(j).length || a.reads.at(j) != 1 || b.reads.at(j) != 1; + for k in 0..a.notes.at(j).length { + val p := &a.notes.at(j).at(k); + val q := &b.notes.at(j).at(k); + return false if p.offset != q.offset || p.code != q.code || p.length != q.length; + } + } + return true; +} + +@test def files_read_on_threads_are_read_as_one_thread_reads_them(t: &mut tester): void { + # The files share some names and not others, and first use them in other + # orders, and some have mistakes, so what joins the names when, and what is + # heard of which file, would show. + val texts: strview[9] = [ + "def alpha(beta: i64): i64 { return beta + gamma; }\nval gamma: i64 = 3;\n", + "struct point { var x: f64; var y: f64; }\ndef length(p: point): f64 { return p.x * p.x + p.y * p.y; }\n", + "def gamma2(): void { var delta := alpha(1); delta = delta * 2; }\n", + "def broken(: i64 { return 1 }\nval ok := 1;\n", + "enum colour { red, green, blue }\ndef pick(c: colour): u8 { return c == colour::red ? 1 : 2; }\n", + "def lexed(): void { val a := 1 @ 2; }\n", + "def x(): i64 { return y() + z(); }\ndef y(): i64 { return 1; }\ndef z(): i64 { return 2; }\n", + "def words(): strview { return $\"{alpha(2)} and {beta}\"; }\n", + "val last := point { x = 1.0, y = 2.0 };\ndef zeta(): void {}\n" + ]; + val one := read_on(1, texts[:]); + t.expects(one.notes.at(3).length != 0 && one.notes.at(5).length != 0); + for threads in 2..6u { + val many := read_on(threads as u32, texts[:]); + t.expects(read_alike(&one, &many)); + } +} + +@test def notes_heard_as_they_are_made_are_not_kept(t: &mut tester): void { + var names := names::new(); + var notes := vector::::new(); + var heard := vector::::new(); + var syntax := syntax::new(); + val source := source::from("test.sakura", "def f(): void {}\ndef g(): void { val a := 1 @ 2; }\ndef f(): void {}\n"); + val hear := def(each: &mut note): void { heard.append(move(each)); }; + + var lexing := lexer::new(&source, &mut names, &mut notes, 0); + lexing.sink.heard = hear; + lexing.tokenize_all(&mut syntax); + var parsing := parser::new(&mut syntax, &names, &mut notes, 0); + parsing.sink.heard = hear; + val root := parsing.parse(); + var checker := checker::new(&mut names, &mut notes); + checker.sink.heard = hear; + checker.add(&source, &syntax, root); + val read := heard.length; + checker.check(); + + # The lexer's note first, and the checker's of `f` declared twice, which says + # where it was first declared, as one kept would. + t.expects(notes.length == 0 && read != 0 && heard.length > read); + t.expects(heard.at(0).code == ec::token); + var related := false; + for &each in heard { + if each.code == ec::duplicate { + related = each.related.length != 0 && each.related_length != 0 && each.related_offset < each.offset; + } + } + t.expects(related); + t.expects(checker.notes_made as u64 == heard.length - read); +} diff --git a/tests/analyzer/recovery.sakura b/tests/analyzer/recovery.sakura new file mode 100644 index 00000000..023f27c3 --- /dev/null +++ b/tests/analyzer/recovery.sakura @@ -0,0 +1,141 @@ +#! @file recovery.sakura +#! @author John Christman (sorakatadzuma@gmail.com) +#! @copyright Malunal Studios, LLC. +#! @license MIT +#! +#! Contains the tests of how the parser recovers from mistakes: going on past an +#! item, a parameter, a statement, or a declaration that fails, with one note +#! for each mistake. + +import std::testing; +module sakura::analyzer; + + +@test def a_list_goes_on_past_an_item_that_fails(t: &mut tester): void { + val made := parse("def f(): void { g(1 +, 2, h(3 *), [4, , 5]); }\nval ok := 1;\n"); + t.expects(made.notes.length == 3); + t.expects(noted(&made, 1, 22, ec::expr)); + t.expects(noted(&made, 1, 32, ec::expr)); + t.expects(noted(&made, 1, 39, ec::expr)); + t.expects(made.syntax.print(made.root, &made.source, &made.names).view() == + "(document [(function:f [] _ [] [] type_name:void (block [(expr_stmt:g (call name:g [(binary:+ number:1 error) number:2 (call name:h [(binary:* number:3 error)]) (array [number:4 error number:5])]))])) (variable:ok [] _ _ number:1)])"); +} + +@test def parameters_go_on_past_one_that_fails(t: &mut tester): void { + val made := parse("def f(a: , b: i64, 7, c: u8): void {}"); + t.expects(made.notes.length == 2); + t.expects(noted(&made, 1, 10, ec::kind)); + t.expects(noted(&made, 1, 20, ec::ident)); +} + +@test def statements_and_declarations_resume_after_errors(t: &mut tester): void { + val made := parse("def f(): void { val x := 1 }\ndef g(): void { y = ; z(); }\nstruct s { var a: i64 }\nval ok := 1;\n"); + t.expects(made.notes.length == 3); + t.expects(noted(&made, 1, 28, ec::token)); + t.expects(noted(&made, 2, 21, ec::expr)); + t.expects(noted(&made, 3, 23, ec::token)); + t.expects(made.syntax.print(made.root, &made.source, &made.names).view() == + "(document [(function:f [] _ [] [] type_name:void (block [(variable:x [] _ _ number:1)])) (function:g [] _ [] [] type_name:void (block [(expr_stmt:y (assign:= name:y error))])) (struct_decl:s [] _ [] [] [(field:a [] _ type_name:i64 _ {mutable})]) (variable:ok [] _ _ number:1)])"); +} + +@test def members_resume_after_errors(t: &mut tester): void { + val made := parse("trait t { pub def f(): void; var x: i64; }\nenum e { a = , b, 3, c }\n"); + t.expects(noted(&made, 1, 11, ec::token)); + t.expects(noted(&made, 1, 30, ec::token)); + t.expects(noted(&made, 2, 14, ec::expr)); + t.expects(noted(&made, 2, 19, ec::ident)); +} + +@test def what_belongs_nowhere_is_kept_within_errors(t: &mut tester): void { + # A trait's `var` that is no property, attributes before no member, and those + # within a function, each kept under an `error` node rather than dropped. + t.expects(tree("trait t { var x: i64; }").view() == + "(document [(trait_decl:t [] _ [] [] [(error [(variable:x [] _ type_name:i64 _ {mutable})])])])"); + t.expects(tree("struct s { @a }").view() == + "(document [(struct_decl:s [] _ [] [] [(error [(attribute type_name:a [])])])])"); + t.expects(statements("@a val x := 1;").view() == + "(error [(attribute type_name:a []) (variable:x [] _ _ number:1)])"); +} + +@test def declarations_are_pub_once_and_after_their_attributes(t: &mut tester): void { + val made := parse("pub pub def f(): void {}\n@a pub @b def g(): void {}\nimport x\nmodule m;\n"); + t.expects(noted(&made, 1, 5, ec::token)); + t.expects(noted(&made, 2, 8, ec::token)); + t.expects(noted(&made, 4, 1, ec::token)); + + # The attributes written after `pub` still describe the function. + t.expects(tree("@a pub @b def g(): void {}").view() == + "(document [(function:g [(attribute type_name:a []) (attribute type_name:b [])] _ [] [] type_name:void block {exported})])"); +} + +@test def nothing_is_nullable(t: &mut tester): void { + val made := parse("def f(p: ?i64): void { g(p!); }\n"); + t.expects(made.notes.length == 2); + t.expects(noted(&made, 1, 10, ec::kind)); + t.expects(noted(&made, 1, 27, ec::token)); +} + +@test def else_takes_a_value_in_parentheses_before_anything_but_a_block(t: &mut tester): void { + val made := parse("val n := f() else (e) 1;\n"); + t.expects(made.notes.length == 1); + t.expects(noted(&made, 1, 23, ec::token)); +} + +@test def a_comparison_after_a_cast_needs_parentheses(t: &mut tester): void { + val made := parse("val ok := n as u64 < limit;\n"); + t.expects(made.notes.length == 1); + t.expects(noted(&made, 1, 27, ec::token)); + t.expects(made.notes.at(0).detail.starts_with("Expected `>` to close the type arguments. A `<` after the type of `as` or `is`")); + + # Anywhere else the plain message is given. + val plain := parse("val v: list` to close the type arguments."); +} + +@test def too_deep_gives_up_on_only_its_declaration(t: &mut tester): void { + var text := string::from("val x := ", nothing {}); + for _ in 0..150 { text.append("("); } + text.append("1"); + for _ in 0..150 { text.append(")"); } + text.append(";\nval y := (;\nval z := 1;\n"); + + val made := parse(text.view()); + t.expects(made.notes.length == 2); + t.expects(noted(&made, 1, 110, ec::syntax)); + t.expects(noted(&made, 2, 11, ec::expr)); + + # The declarations after it are parsed as though nothing went wrong. + val decls := made.syntax.node_lefts.at(made.root); + t.expects(made.syntax.run_length(decls) == 3); + t.expects(made.syntax.print(made.syntax.run_at(decls, 2), &made.source, &made.names).view() == "(variable:z [] _ _ number:1)"); +} + +@test def notes_are_bounded(t: &mut tester): void { + var text := string::new(nothing {}); + for _ in 0..150 { text.append("val v := ;\n"); } + t.expects(parse(text.view()).notes.length == parser::max_notes as u64); +} + +@test def the_walker_follows_the_shapes(t: &mut tester): void { + val made := parse("def f(a: i64): i64 { return a + 1; }"); + val function := made.syntax.run_at(made.syntax.node_lefts.at(made.root), 0); + + var kids := vector::::new(); + made.syntax.children(function, &mut kids); + + # The record's runs and nodes in order: the parameter, the result, the body. + t.expects(kids.length == 3); + t.expects(made.syntax.node_kinds.at(kids.at(0)) == nk::param); + t.expects(made.syntax.node_kinds.at(kids.at(1)) == nk::type_name); + t.expects(made.syntax.node_kinds.at(kids.at(2)) == nk::block); + + # Every node is reached once from the document. + var todo := vector::::new(); + todo.append(made.root); + var walked := 0u; + while walked < todo.length { + made.syntax.children(todo.at(walked), &mut todo); + walked++; + } + t.expects(todo.length == made.syntax.node_count - 1); +} diff --git a/tests/analyzer/reparse.sakura b/tests/analyzer/reparse.sakura new file mode 100644 index 00000000..1d435d9f --- /dev/null +++ b/tests/analyzer/reparse.sakura @@ -0,0 +1,128 @@ +#! @file reparse.sakura +#! @author John Christman (sorakatadzuma@gmail.com) +#! @copyright Malunal Studios, LLC. +#! @license MIT +#! +#! Contains the tests of parsing a file again after an edit, which must give the +#! tree and notes a whole parse of the edited text gives. + +import std::testing; +module sakura::analyzer; + + +@test def an_edit_within_a_declaration(t: &mut tester): void { + t.expects(reparses_as_whole( + "val a := 1;\ndef f(): void { g(1); }\nval b := 2;", + "val a := 1;\ndef f(): void { g(1, 2 + 3); h(); }\nval b := 2;")); + t.expects(reparses_as_whole( + "def f(): void {}\nval b := 2;", + "def f(): i64 { return 1; }\nval b := 2;")); +} + +@test def an_edit_of_only_spacing_and_comments(t: &mut tester): void { + t.expects(reparses_as_whole( + "val a := 1;\nval b := 2;", + "val a := 1;\n\n# a comment\n#! documentation\nval b := 2;")); +} + +@test def declarations_added_and_taken_away(t: &mut tester): void { + t.expects(reparses_as_whole("val a := 1;\nval c := 3;", "val a := 1;\nval b := 2;\nval c := 3;")); + t.expects(reparses_as_whole("val a := 1;\nval b := 2;\nval c := 3;", "val a := 1;\nval c := 3;")); + t.expects(reparses_as_whole("val a := 1;", "val a := 1;\nstruct s { var x: i64; }")); + t.expects(reparses_as_whole("val a := 1;\nval b := 2;", "val b := 2;")); + t.expects(reparses_as_whole("val a := 1;", "")); +} + +@test def edits_that_make_and_mend_errors(t: &mut tester): void { + t.expects(reparses_as_whole("val a := 1;\nval b := 2;\nval c := 3;", "val a := 1;\nval b := ;\nval c := 3;")); + t.expects(reparses_as_whole("val a := 1;\nval b := ;\nval c := 3;", "val a := 1;\nval b := 2;\nval c := 3;")); + t.expects(reparses_as_whole("val a := 0x;\nval b := 2;", "val a := 0x1;\nval b := 2;")); +} + +@test def an_edit_that_opens_what_runs_on(t: &mut tester): void { + # Taking away a `}` makes the function take in what follows it, which only + # parsing the whole file again finds. + t.expects(reparses_as_whole( + "def f(): void { g(); }\nval b := 2;\nval c := 3;", + "def f(): void { g();\nval b := 2;\nval c := 3;")); +} + +@test def what_the_edit_did_not_touch_is_kept(t: &mut tester): void { + var made := parse("val a := 1;\nval b := 2;\nval c := 3;"); + val decls := made.syntax.node_lefts.at(made.root); + val first := made.syntax.run_at(decls, 0); + val last := made.syntax.run_at(decls, 2); + + var fresh := lex("val a := 1;\nval b := 20 + 2;\nval c := 3;"); + made.root = made.syntax.reparse(&mut fresh.syntax, &fresh.names, made.root, &mut made.notes, &mut fresh.notes, 0); + + val after := made.syntax.node_lefts.at(made.root); + t.expects(made.syntax.run_at(after, 0) == first); + t.expects(made.syntax.run_at(after, 2) == last); + + # What moved along with the edit says where it is now. + t.expects(made.syntax.token(made.syntax.node_tokens.at(last), &fresh.names).offset == 33); +} + +@test def what_follows_an_edit_is_kept_as_the_tree_grows(t: &mut tester): void { + # A longer comment above the first declaration moves every token, so all up + # to the edit is parsed again, and the nodes that adds move the tables the + # declarations after it are kept from, which are still read once it is done. + for count in 1..60 { + var before := string::from("# A file.\nimport std;\nmodule m;\n", nothing {}); + var after := string::from("# A file, said at more length.\nimport std;\nmodule m;\n", nothing {}); + for i in 0..count { + var line := $"def f{i}(x: u32): u32 "; + before.append(line.view()); + before.append("{ return x + 1; }\n"); + after.append(line.view()); + after.append(i == count / 2 ? "{ return x * 2; }\n" : "{ return x + 1; }\n"); + } + t.expects(reparses_as_whole(before.view(), after.view())); + } +} + +@test def type_arguments_closed_by_one_token_are_kept(t: &mut tester): void { + # A `>>` closing type arguments is the same tokens after the edit as before, + # so the declaration it is in is kept. + var made := parse("val a: x> = 1;\nval b := 2;\nval c := 3;"); + val first := made.syntax.run_at(made.syntax.node_lefts.at(made.root), 0); + + var fresh := lex("val a: x> = 1;\nval b := 2;\nval c := 30;"); + made.root = made.syntax.reparse(&mut fresh.syntax, &fresh.names, made.root, &mut made.notes, &mut fresh.notes, 0); + t.expects(made.syntax.run_at(made.syntax.node_lefts.at(made.root), 0) == first); + t.expects(reparses_as_whole( + "val a: x> = 1;\nval b := 2;\nval c := 3;", + "val a: x> = 1;\nval b := 2;\nval c := 30;")); +} + +@test def notes_keep_the_order_a_whole_parse_gives(t: &mut tester): void { + # Parser notes before, within and after what is parsed again, and a lexer note. + t.expects(reparses_as_whole( + "val a := ;\nval b := 2;\nval c := ;", + "val a := ;\nval b := 2 +;\nval c := 0x;")); + t.expects(reparses_as_whole( + "val a := ;\nval b := 2 +;\nval c := ;", + "val a := ;\nval b := 2;\nval c := ;")); +} + +@test def notes_past_the_cap_parse_whole(t: &mut tester): void { + var before := string::new(nothing {}); + var after := string::new(nothing {}); + for i in 0..(parser::max_notes + 20) { + before.append(i == 50 ? "val b := 2;\n" : "val a := ;\n"); + after.append(i == 50 ? "val b := ;\n" : "val a := ;\n"); + } + t.expects(reparses_as_whole(before.view(), after.view())); +} + +@test def edits_over_time_do_not_keep_growing(t: &mut tester): void { + var made := parse("val a := 1;\nval b := 2;\nval c := 3;"); + val whole := made.syntax.node_count; + for i in 0..50 { + var fresh := lex(i % 2 == 0 ? "val a := 1;\nval b := 2 + 3 * 4;\nval c := 3;" : "val a := 1;\nval b := 2;\nval c := 3;"); + made.root = made.syntax.reparse(&mut fresh.syntax, &fresh.names, made.root, &mut made.notes, &mut fresh.notes, 0); + } + t.expects(made.syntax.node_count <= made.syntax.whole_nodes * 2); + t.expects(made.syntax.whole_nodes <= whole * 2); +} diff --git a/tests/analyzer/support.sakura b/tests/analyzer/support.sakura new file mode 100644 index 00000000..c78965e6 --- /dev/null +++ b/tests/analyzer/support.sakura @@ -0,0 +1,611 @@ +#! @file support.sakura +#! @author John Christman (sorakatadzuma@gmail.com) +#! @copyright Malunal Studios, LLC. +#! @license MIT +#! +#! Contains what the tests share: lexing, parsing, and checking text, printing +#! trees, and asking what notes were made. + +module sakura::analyzer; + + +#! Text that was lexed, with what the lexer reported. +struct lexed { + var source: source; + var names: names; + var syntax: syntax; + var notes: vector; +} + +#! Text that was lexed and parsed, with what both reported. +struct parsed { + var source: source; + var names: names; + var syntax: syntax; + var notes: vector; + var root: u32; +} + +#! Lexes the text through its `eof`. +#! @param text The text. +#! @returns Its source, names, tokens, and notes. +def lex(text: strview): lexed { + var made := lexed { + source = source::from("test.sakura", text), + names = names::new(), + syntax = syntax::new(), + notes = vector::::new() + }; + + var lexing := lexer::new(&mut made.source, &mut made.names, &mut made.notes, 0); + lexing.tokenize_all(&mut made.syntax); + return made; +} + +#! Lexes and parses the text as a file. +#! @param text The text. +#! @returns Its source, names, syntax, notes, and `document` node. +def parse(text: strview): parsed { + var made := parsed { + source = source::from("test.sakura", text), + names = names::new(), + syntax = syntax::new(), + notes = vector::::new() + }; + + var lexing := lexer::new(&mut made.source, &mut made.names, &mut made.notes, 0); + lexing.tokenize_all(&mut made.syntax); + + var parsing := parser::new(&mut made.syntax, &made.names, &mut made.notes, 0); + made.root = parsing.parse(); + return made; +} + +#! The kinds of the tokens lexed, without the `eof` ending them. +#! @param text The text. +#! @returns The kinds. +def kinds_of(text: strview): vector { + val lexing := lex(text); + var kinds := vector::::new(); + for &each in lexing.syntax.token_kinds { + if each != tk::eof { + kinds.append(each); + } + } + return kinds; +} + +#! Whether the tokens lexed are exactly those kinds. +#! @param text The text. +#! @param kinds The kinds expected, without the `eof`. +#! @returns Whether they are. +def lexes_as(text: strview, kinds: tk...): bool { + val got := kinds_of(text); + return false if got.length != kinds.length; + for i in 0..got.length { + return false if got.at(i) != kinds.at(i); + } + return true; +} + +#! The tree of a whole file, printed. +#! @param text The text. +#! @returns The tree, as `printer` writes it. +def tree(text: strview): string { + val made := parse(text); + return made.syntax.print(made.root, &made.source, &made.names); +} + +#! The statements of a function's body, each printed, separated by spaces. +#! @param text A file holding the function first. +#! @returns The statements. +def statements(text: strview): string { + var wrapped := string::from("def test(): void {\n", nothing {}); + wrapped.append(text); + wrapped.append("\n}\n"); + + val made := parse(wrapped.view()); + val function := made.syntax.run_at(made.syntax.node_lefts.at(made.root), 0); + val record := made.syntax.node_lefts.at(function); + val body := made.syntax.extras.at(record as u64 + 5); + val run := made.syntax.node_lefts.at(body); + + var out := string::new(nothing {}); + for i in 0..made.syntax.run_length(run) { + if i != 0 { + out.append(" "); + } + out.append(made.syntax.print(made.syntax.run_at(run, i as u32), &made.source, &made.names).view()); + } + return out; +} + +#! An expression statement's expression, printed. +#! @param text A file holding a function whose body is the expression +#! statement. +#! @returns The expression. +def expression(text: strview): string { + var wrapped := string::from(text, nothing {}); + wrapped.append(";"); + + val printed := statements(wrapped.view()); + val inner := printed.view(); + + # `(expr_stmt:x EXPR)` without its own head and closing parenthesis. + var at := 0u; + var spaces := 0u; + while at < inner.length && spaces == 0 { + if inner.at(at) == ' ' { spaces++; } + at++; + } + return string::from(inner.substr(at, inner.length - at - 1), nothing {}); +} + +#! Whether a note of the code was made at the line and column. +#! @param made What was parsed. +#! @param line The note's line, counted from 1. +#! @param column Its column, counted from 1. +#! @param code What kind of note it is. +#! @returns Whether it was. +def noted(made: &parsed, line: u32, column: u32, code: ec): bool { + for &each in made.notes { + val at := made.source.lines.place_of(each.offset); + return true if at.line == line && at.column == column && each.code == code; + } + return false; +} + +#! Whether a note of the code was made at the line and column, lexing only. +#! @param made What was lexed. +#! @param line The note's line, counted from 1. +#! @param column Its column, counted from 1. +#! @param code What kind of note it is. +#! @returns Whether it was. +def lex_noted(made: &lexed, line: u32, column: u32, code: ec): bool { + for &each in made.notes { + val at := made.source.lines.place_of(each.offset); + return true if at.line == line && at.column == column && each.code == code; + } + return false; +} + +#! Parses `before`, then reparses it as edited into `after`, and says whether +#! the tree and notes are those a whole parse of `after` makes. +#! @param before The text first parsed. +#! @param after The text it is edited into. +#! @returns Whether they are. +def reparses_as_whole(before: strview, after: strview): bool { + var made := parse(before); + var fresh := lex(after); + made.root = made.syntax.reparse(&mut fresh.syntax, &fresh.names, made.root, &mut made.notes, &mut fresh.notes, 0); + + val whole := parse(after); + return false if made.syntax.print(made.root, &fresh.source, &fresh.names).view() != whole.syntax.print(whole.root, &whole.source, &whole.names).view(); + return false if made.notes.length != whole.notes.length; + for i in 0..whole.notes.length { + val each := &whole.notes.at(i); + val other := &made.notes.at(i); + return false if other.offset != each.offset || other.code != each.code || other.lexed != each.lexed; + } + return true; +} + +#! A note the checker made, where it is, and what it says. +struct seen { + var line: u32; + var column: u32; + var code: ec; + var detail: string; + var instance: string; #! The instance of a generic it was found in, or empty. + var related: u32; #! The line of the place it relates to, or 0. +} + +#! What checking a program found: its notes, and the type of each local named +#! in `asked`, as notes spell it. +struct checking { + var notes: vector; + var asked: string; + var skipped: u32; +} + +#! Checks the first text, then each after it in turn as an edit of the one +#! before, checking again only what each edit affects, and whether hovering +#! each name of the last text shows what it does once that text is checked +#! whole. +#! @param texts The text before every edit, then the text after each. +#! @returns The names whose hovers differ, each with both, or empty text. +def hovers_after_edits(texts: strview...): string { + return hovers_after_edits_with(span::::empty(), ...texts); +} + +#! Checks the files, the edited one last, then each text after the first in turn +#! as an edit of the edited file, as `hovers_after_edits` does. +#! @param others The files checked with it, which are not edited. +#! @param texts The text before every edit, then the text after each. +#! @returns The names whose hovers differ, each with both, or empty text. +def hovers_after_edits_with(others: span, texts: strview...): string { + var names := names::new(); + var notes := vector::::new(); + var parse_notes := vector::>::new(); + var sources := vector::::new(); + var syntaxes := vector::::new(); + var roots := vector::::new(); + val edited := others.length; + sources.reserve(others.length + texts.length); + syntaxes.reserve(others.length + 1); + parse_notes.reserve(others.length + 1); + for i in 0..(others.length + 1) { + sources.append(source::from(i == edited ? "test.sakura" : "other.sakura", i == edited ? texts[0] : others[i])); + syntaxes.append(syntax::new()); + parse_notes.append(vector::::new()); + } + for i in 0..(others.length + 1) { + var lexing := lexer::new(&mut sources[i], &mut names, &mut parse_notes[i], i as u32); + lexing.tokenize_all(&mut syntaxes[i]); + var parsing := parser::new(&mut syntaxes[i], &names, &mut parse_notes[i], i as u32); + roots.append(parsing.parse()); + } + + var checker := checker::new(&mut names, &mut notes); + for i in 0..(others.length + 1) { + checker.add(&sources[i], &syntaxes[i], roots[i]); + } + checker.check(); + for i in 1..texts.length { + sources.append(source::from("test.sakura", texts[i])); + val at := sources.length - 1; + var fresh := syntax::new(); + var fresh_notes := vector::::new(); + var again := lexer::new(&mut sources[at], &mut names, &mut fresh_notes, edited as u32); + again.tokenize_all(&mut fresh); + roots[edited] = syntaxes[edited].reparse(&mut fresh, &names, roots[edited], &mut parse_notes[edited], &mut fresh_notes, edited as u32); + checker.update(edited as u32, &sources[at], roots[edited]); + } + + val last := texts[texts.length - 1]; + var files := vector::::new(); + for &each in others { + files.append(each); + } + files.append(last); + return asked(def(whole: &mut checker): string { + var made := string::new(nothing {}); + var at: u64 = 0; + while at < last.length { + if !is_word_byte(last[at]) || (at > 0 && is_word_byte(last[at - 1])) { + at++; + continue; + } + var one := checker.hover(edited as u32, at as u32); + var two := whole.hover(edited as u32, at as u32); + var a := string::new(nothing {}); + var b := string::new(nothing {}); + if one is some(&found) { + a = string::copy_of(&found.signature); + } + if two is some(&found) { + b = string::copy_of(&found.signature); + } + if a.view() != b.view() { + val line := $"{at}: {a} | {b}\n"; + made.append(line.view()); + } + at++; + } + return made; + }, ...files.view()); +} + +#! The top-level nodes of a file once parsed, each with the first node of what +#! it declares. +#! @param text The file's text. +#! @returns The pairs, as `top << 32 | first`. +def top_nodes(text: strview): vector { + val made := parse(text); + var found := vector::::new(); + val decls := made.syntax.node_lefts[made.root]; + for i in 0..made.syntax.run_length(decls) { + val top := made.syntax.run_at(decls, i as u32); + var lowest := top; + var todo := vector::::new(); + todo.append(top); + while todo.length != 0 { + val at: u32 = todo[todo.length - 1]; + todo.remove_at(todo.length - 1); + lowest = at < lowest ? at : lowest; + made.syntax.children(at, &mut todo); + } + found.append((top as u64 << 32) | lowest as u64); + } + return found; +} + +#! Lexes, parses, and checks the files as one program, the first named +#! `test.sakura`, and the type of the local named `asked` in the first file. +#! @param asked The name of a local whose type is asked for, or empty text. +#! @param texts The files' texts. +#! @returns The notes made, the local's type as notes spell it, and how much was +#! let through unchecked. +def check_program(asked: strview, texts: strview...): checking { + var names := names::new(); + var notes := vector::::new(); + var sources := vector::::new(); + var syntaxes := vector::::new(); + var roots := vector::::new(); + + # Each file's source and syntax stay where they are once the checker refers + # to them, so there is room for all of them before any is made. + sources.reserve(texts.length); + syntaxes.reserve(texts.length); + for i in 0..texts.length { + sources.append(source::from(i == 0 ? "test.sakura" : "other.sakura", texts.at(i))); + syntaxes.append(syntax::new()); + } + + for i in 0..texts.length { + var lexing := lexer::new(sources.at(i), &mut names, &mut notes, i as u32); + lexing.tokenize_all(syntaxes.at(i)); + var parsing := parser::new(syntaxes.at(i), &names, &mut notes, i as u32); + roots.append(parsing.parse()); + } + + var checker := checker::new(&mut names, &mut notes); + for i in 0..texts.length { + checker.add(sources.at(i), syntaxes.at(i), roots.at(i)); + } + checker.check(); + + var made := checking { + notes = vector::::new(), + asked = string::new(nothing {}), + skipped = checker.skipped + }; + for &each in notes { + val at := sources.at(each.file).lines.place_of(each.offset); + val related := each.related.length == 0 ? 0 : sources.at(each.related_file).lines.place_of(each.related_offset).line; + made.notes.append(seen { + line = at.line, + column = at.column, + code = each.code, + detail = string::from(each.detail, nothing {}), + instance = string::from(each.instance, nothing {}), + related = related + }); + } + + if asked.length != 0 { + checker.use_table(checker.units.at(0).table); + val syntax := &syntaxes.at(0); + for at in 1..syntax.node_count { + val node := at as u32; + continue if syntax.node_kinds.at(node) != nk::variable; + continue if names.text(syntax.token_names.at(syntax.node_tokens.at(node))) != asked; + var described := checker.describe(checker.type_at(node)); + made.asked = move(&mut described); + } + } + return made; +} + +#! Whether the program checks without a note. +#! @param texts The files' texts. +#! @returns Whether it does. +def checks(texts: strview...): bool { + val made := check_program("", ...texts); + return made.notes.length == 0; +} + +#! Whether checking the program makes a note of the code at the line and +#! column, among any others. +#! @param line The note's line, counted from 1. +#! @param column Its column, counted from 1. +#! @param code What kind of note it is. +#! @param texts The files' texts. +#! @returns Whether it does. +def check_noted(line: u32, column: u32, code: ec, texts: strview...): bool { + val made := check_program("", ...texts); + for &each in made.notes { + return true if each.line == line && each.column == column && each.code == code; + } + return false; +} + +#! How many notes checking the program makes. +#! @param texts The files' texts. +#! @returns How many. +def note_count(texts: strview...): u64 { + val made := check_program("", ...texts); + return made.notes.length; +} + +#! The type of the local of the name in the program, as notes spell it. +#! @param name The local's name. +#! @param text The program's text. +#! @returns Its type. +def local_type(name: strview, text: strview): string { + var made := check_program(name, text); + return move(&mut made.asked); +} + +#! A small standard library for checking programs that use what the checker +#! knows of std, as the real one declares it. +const mini_std: strview = """ + module std; module core; + pub struct nothing {} + pub trait equatable { def equals(&this, other: &self): bool; } + pub trait ordered : equatable { def compare(&this, other: &self): i64; } + pub trait addable { def add(&this, other: &self): self; } + pub trait subtractable { def sub(&this, other: &self): self; } + pub trait multipliable { def mul(&this, other: &self): self; } + pub trait divisible { def div(&this, other: &self): self; } + pub trait modular { def rem(&this, other: &self): self; } + pub trait negatable { def negate(&this): self; } + pub trait additive : equatable, addable, subtractable, negatable {} + pub trait multiplicative : equatable, multipliable {} + pub trait numeric : additive, multiplicative, divisible, modular {} + pub trait integer {} + pub trait ordinal {} + pub trait zeroable {} + pub trait lockfree {} + pub trait owning { def close(&mut this): void; } + pub union maybe { pub var none: nothing; pub var some: T; } + pub union result { pub var value: T; pub var error: E; } + pub trait iterator { def next(&mut this): maybe; } + pub trait iterable { + type cursor: iterator<&T>; + def iter(&this): cursor; + } + pub struct span { pub var data: *T; pub var count: u64; } + pub val span::length: u64 { get => this.count; } + pub def span::at(&this, index: u64): &T { return &this.data[index]; } + pub struct span::cursor : iterator<&T> { var at: *T; var left: u64; } + pub def span::cursor::next(&mut this): maybe<&T> { + if this.left == 0 { return nothing {}; } + this.left--; + return &this.at[0]; + } + pub def span::iter(&this): span::cursor { return span::::cursor { at = this.data, left = this.count }; } + """; + +#! What `mini_std` lacks for checking anonymous functions given for bounds and +#! ranges as values: `invokable`, `range`, which `a..b` makes, and `strview`. +const ranges_std: strview = """ + module std; module core; + pub type strview = span; + pub trait invokable { def invoke(&mut this, args: Ts...): R; } + pub struct range : iterator where T: ordinal { pub var start: T; pub var end: T; var _last: bool; } + pub def range::next(&mut this): maybe { return nothing {}; } + """; + +#! What checking a file again after an edit found, against checking it whole. +struct rechecked { + var same: bool; #! Whether its notes are those checking the edited text whole makes. + var checked: u32; #! How many top-level declarations were checked again. + var notes: u64; #! How many notes it made. +} + +#! Checks `before`, with `others` after it, then edits it into `after`, parses +#! it again, and checks it again, and says whether its notes are those of +#! checking the edited program whole, and how much was checked again. +#! @param before The text of the file first checked. +#! @param after The text it is edited into. +#! @param others The texts of the program's other files. +#! @returns Whether its notes are the same, and how much was checked again. +def check_edit(before: strview, after: strview, others: strview...): rechecked { + var names := names::new(); + var notes := vector::::new(); + var sources := vector::::new(); + var syntaxes := vector::::new(); + var roots := vector::::new(); + sources.reserve(others.length + 2); + syntaxes.reserve(others.length + 1); + sources.append(source::from("test.sakura", before)); + syntaxes.append(syntax::new()); + for &each in others { + sources.append(source::from("other.sakura", each)); + syntaxes.append(syntax::new()); + } + for i in 0..syntaxes.length { + var lexing := lexer::new(sources.at(i), &mut names, &mut notes, i as u32); + lexing.tokenize_all(syntaxes.at(i)); + var parsing := parser::new(syntaxes.at(i), &names, &mut notes, i as u32); + roots.append(parsing.parse()); + } + + var checker := checker::new(&mut names, &mut notes); + for i in 0..syntaxes.length { + checker.add(sources.at(i), syntaxes.at(i), roots.at(i)); + } + checker.check(); + + # The edit: the text lexed whole, then parsed again where it changed. + sources.append(source::from("test.sakura", after)); + val edited := sources.length - 1; + var fresh := syntax::new(); + var fresh_notes := vector::::new(); + var lexing := lexer::new(sources.at(edited), &mut names, &mut fresh_notes, 0); + lexing.tokenize_all(&mut fresh); + val root := syntaxes.at(0).reparse(&mut fresh, &names, roots.at(0), &mut notes, &mut fresh_notes, 0); + val count := checker.update(0, sources.at(edited), root); + + var texts := vector::::new(); + texts.append(after); + for &each in others { + texts.append(each); + } + val whole := check_program("", ...texts.view()); + var same := whole.notes.length == notes.length; + for &want in whole.notes { + var found := false; + for &each in notes { + val at := sources.at(each.file == 0 ? edited : each.file as u64).lines.place_of(each.offset); + found = found || (at.line == want.line && at.column == want.column && each.code == want.code); + } + same = same && found; + } + return rechecked { same = same, checked = count, notes = notes.length }; +} + +#! Lexes, parses, and checks the files as one program, the first named +#! `test.sakura` and the rest `other.sakura`, then asks it a question. +#! @param question What is asked of the checked program. +#! @param texts The files' texts. +#! @returns What the question gives. +def asked(question: def(&mut checker): string, texts: strview...): string { + var names := names::new(); + var notes := vector::::new(); + var sources := vector::::new(); + var syntaxes := vector::::new(); + var roots := vector::::new(); + sources.reserve(texts.length); + syntaxes.reserve(texts.length); + for i in 0..texts.length { + sources.append(source::from(i == 0 ? "test.sakura" : "other.sakura", texts[i])); + syntaxes.append(syntax::new()); + } + for i in 0..texts.length { + var lexing := lexer::new(sources[i], &mut names, &mut notes, i as u32); + lexing.tokenize_all(syntaxes[i]); + var parsing := parser::new(syntaxes[i], &names, &mut notes, i as u32); + roots.append(parsing.parse()); + } + + var checker := checker::new(&mut names, &mut notes); + for i in 0..texts.length { + checker.add(sources[i], syntaxes[i], roots[i]); + } + checker.check(); + return question(&mut checker); +} + +#! Where text first holds `needle`, and `skip` bytes into it. +#! @param text The text. +#! @param needle What to find. +#! @param skip How far into it the place is. +#! @returns The offset, or the text's length where it does not hold it. +def place_in(text: strview, needle: strview, skip: u32 = 0): u32 { + var at := 0u; + while at + needle.length <= text.length && text.substr(at, needle.length) != needle { + at++; + } + return at as u32 + skip; +} + +#! What hovering the first place the text holds `needle` shows, once checked: +#! the signature, and after a blank line the documentation, where there is +#! some. +#! @param text The program's text. +#! @param needle The text to hover. +#! @param skip How far into the needle the place hovered is. +#! @returns What hovering shows, or empty text. +def hover_of(text: strview, needle: strview, skip: u32 = 0): string { + return asked(def(c: &mut checker): string { + var shown := c.hover(0, place_in(text, needle, skip)) else { return string::new(nothing {}); }; + var made := move(&mut shown.signature); + if shown.documentation.length != 0 { + made.append("\n\n"); + made.append(shown.documentation.view()); + } + return made; + }, text); +} diff --git a/tests/analyzer/syntax.sakura b/tests/analyzer/syntax.sakura new file mode 100644 index 00000000..bffd7b89 --- /dev/null +++ b/tests/analyzer/syntax.sakura @@ -0,0 +1,92 @@ +#! @file syntax.sakura +#! @author John Christman (sorakatadzuma@gmail.com) +#! @copyright Malunal Studios, LLC. +#! @license MIT +#! +#! Contains the tests of how a syntax holds its nodes: names and paths of one +#! segment, records of nothing, and the last token of each node. + +import std::testing; +module sakura::analyzer; + + +@test def plain_type_names_and_paths_are_one_node(t: &mut tester): void { + val made := parse("import std;\nval x: u8 = 1;"); + val decls := made.syntax.node_lefts.at(made.root); + val path := made.syntax.node_lefts.at(made.syntax.run_at(decls, 0)); + t.expects(made.syntax.node_kinds.at(path) == nk::path && made.syntax.node_lefts.at(path) == 0); + + # The document, the import, its path, the variable, its type, and its value, + # with node 0. + t.expects(made.syntax.node_count == 7); +} + +@test def records_of_nothing_take_no_room(t: &mut tester): void { + # A parameter with no default value and no flags shares the zeros `extras` + # begins with, so the function's record and the run of its parameters are all + # it writes. + val made := parse("def f(a: i64, b: i64): void;"); + val param := made.syntax.run_at(made.syntax.extras.at(made.syntax.node_lefts.at(made.syntax.run_at(made.syntax.node_lefts.at(made.root), 0)) as u64 + 3), 0); + t.expects(made.syntax.node_kinds.at(param) == nk::param && made.syntax.node_rights.at(param) == 0); + t.expects(made.syntax.extras.length == syntax::zeros as u64 + 2 + 7 + 3); +} + +@test def nodes_know_their_last_token(t: &mut tester): void { + val made := parse("def f(): void { g(1, 2); }\nval x := a + b;"); + val decls := made.syntax.node_lefts.at(made.root); + val func := made.syntax.run_at(decls, 0); + val local := made.syntax.run_at(decls, 1); + + # `}` ends the function, and `;` the variable. + t.expects(made.syntax.token(made.syntax.node_end(func), &made.names).kind == tk::rbrace); + t.expects(made.syntax.token(made.syntax.node_end(local), &made.names).kind == tk::semicolon); + t.expects(made.syntax.node_end(made.root) == made.syntax.token_count as u32 - 1); + + # A declaration begins at its keyword, its own token being its name. + t.expects(made.syntax.start_of(local) == made.syntax.node_end(func) + 1); +} + +@test def documentation_belongs_to_what_it_is_written_before(t: &mut tester): void { + val made := parse("#! The answer.\n#! Twice.\n@a pub val x := 42;\n# Not documentation.\nval y := 1;\nstruct s {\n #! A field.\n var f: i64;\n}"); + val decls := made.syntax.node_lefts.at(made.root); + t.expects(made.syntax.docs.length == 3); + + val first := made.syntax.docs_of(made.syntax.run_at(decls, 0)); + t.expects(first.first == 0 && first.count == 2); + t.expects(made.source.make_lexeme(made.syntax.docs.at(1).offset, made.syntax.docs.at(1).length) == "#! Twice."); + + t.expects(made.syntax.docs_of(made.syntax.run_at(decls, 1)).count == 0); + + val structure := made.syntax.run_at(decls, 2); + val field := made.syntax.run_at(made.syntax.node_rights.at(structure), 0); + val of_field := made.syntax.docs_of(field); + t.expects(of_field.first == 2 && of_field.count == 1); +} + +@test def notes_say_what_they_found(t: &mut tester): void { + val made := parse("val x := 1\nval y := ;"); + t.expects(made.notes.at(0).message(&made.source).view() == "Expected `;` after the declaration. Found `val`."); + t.expects(made.notes.at(1).message(&made.source).view() == "Expected an expression. Found `;`."); + + val ended := parse("val x := 1"); + t.expects(ended.notes.at(0).message(&ended.source).view() == "Expected `;` after the declaration. Found the end of the file."); + + # A note saying what is wrong, rather than what was expected, says no more. + val twice := parse("pub pub val x := 1;"); + t.expects(twice.notes.at(0).message(&twice.source).view() == "A declaration is `pub` once."); +} + +@test def notes_say_which_stage_made_them(t: &mut tester): void { + val made := parse("val x := 0x;\nval y := ;"); + t.expects(made.notes.length == 2); + t.expects(made.notes.at(0).lexed); + t.expects(!made.notes.at(1).lexed); +} + +@test def token_tables_answer_for_each_kind(t: &mut tester): void { + t.expects(tk::pluseq.has(tt::assigns) && !tk::plus.has(tt::assigns)); + t.expects(tk::kw_struct.has(tt::declares) && !tk::kw_if.has(tt::declares)); + t.expects(tk::kw_if.has(tt::states) && tk::lbrace.has(tt::opens) && tk::istring_end.has(tt::closes)); + t.expects(tk::name.has(tt::text) && !tk::lparen.has(tt::text)); + t.expects(token_powers[tk::star as u64] == parser::bp::product && token_powers[tk::comma as u64] == parser::bp::none); +} diff --git a/tests/checked/an_index_outside_a_view_is_a_fault_1.out b/tests/checked/an_index_outside_a_view_is_a_fault_1.out new file mode 100644 index 00000000..0fa7df65 --- /dev/null +++ b/tests/checked/an_index_outside_a_view_is_a_fault_1.out @@ -0,0 +1,4 @@ + +--- exit 1 +sakura: runtime error: Index or slice is out of bounds. + at main (tests/checked/an_index_outside_a_view_is_a_fault_1.sakura:5:15) diff --git a/tests/checked/an_index_outside_a_view_is_a_fault_1.sakura b/tests/checked/an_index_outside_a_view_is_a_fault_1.sakura new file mode 100644 index 00000000..9f79b0b1 --- /dev/null +++ b/tests/checked/an_index_outside_a_view_is_a_fault_1.sakura @@ -0,0 +1,6 @@ +import std::io; +def main(): void { + var a: i64[2] = [1, 2]; + val s := span::::over(&a as *i64, 2); + println($"{s[5]}"); +} diff --git a/tests/checked/enums_and_match_values_3.out b/tests/checked/enums_and_match_values_3.out new file mode 100644 index 00000000..5d0100bf --- /dev/null +++ b/tests/checked/enums_and_match_values_3.out @@ -0,0 +1,5 @@ +before + +--- exit 1 +sakura: runtime error: Value is not a member of its enum. + at main (tests/checked/enums_and_match_values_3.sakura:6:14) diff --git a/tests/checked/enums_and_match_values_3.sakura b/tests/checked/enums_and_match_values_3.sakura new file mode 100644 index 00000000..e8f81e4d --- /dev/null +++ b/tests/checked/enums_and_match_values_3.sakura @@ -0,0 +1,8 @@ +import std::io; +enum color: u8 { red, green = 4, blue } +def main(): void { + val n := 260; + println("before"); + val c := n as color; + println($"{c}"); +} diff --git a/tests/checked/enums_declared_out_of_order_check_their_members_1.out b/tests/checked/enums_declared_out_of_order_check_their_members_1.out new file mode 100644 index 00000000..39b1b8e8 --- /dev/null +++ b/tests/checked/enums_declared_out_of_order_check_their_members_1.out @@ -0,0 +1,6 @@ +lowest low middle high higher + +--- exit 1 +sakura: runtime error: Value is not a member of its enum. + at convert (tests/checked/enums_declared_out_of_order_check_their_members_1.sakura:7:39) + at main (tests/checked/enums_declared_out_of_order_check_their_members_1.sakura:15:21) diff --git a/tests/checked/enums_declared_out_of_order_check_their_members_1.sakura b/tests/checked/enums_declared_out_of_order_check_their_members_1.sakura new file mode 100644 index 00000000..c63382d4 --- /dev/null +++ b/tests/checked/enums_declared_out_of_order_check_their_members_1.sakura @@ -0,0 +1,16 @@ +import std::io; + +# Members declared out of the order of their values, which the check of a +# conversion sorts into runs. +enum level: u32 { high = 9, low = 1, middle = 5, lowest = 0, higher = 10 } + +def convert(n: u32): level { return n as level; } + +def main(): void { + val members: u32[5] = [0, 1, 5, 9, 10]; + for n in members { + print($"{convert(n)} "); + } + println(""); + println($"{convert(4)}"); +} diff --git a/tests/checked/faults_1.out b/tests/checked/faults_1.out new file mode 100644 index 00000000..85c02257 --- /dev/null +++ b/tests/checked/faults_1.out @@ -0,0 +1,5 @@ +99 + +--- exit 1 +sakura: runtime error: Index or slice is out of bounds. + at main (tests/checked/faults_1.sakura:5:18) diff --git a/tests/checked/faults_1.sakura b/tests/checked/faults_1.sakura new file mode 100644 index 00000000..842ee869 --- /dev/null +++ b/tests/checked/faults_1.sakura @@ -0,0 +1,6 @@ +import std::io; +def main(): void { + val text: span = "abc"; + println($"{text[2]}"); + println($"{text[3]}"); +} diff --git a/tests/checked/fixed_arrays_are_bounded_1.out b/tests/checked/fixed_arrays_are_bounded_1.out new file mode 100644 index 00000000..491e50a2 --- /dev/null +++ b/tests/checked/fixed_arrays_are_bounded_1.out @@ -0,0 +1,4 @@ + +--- exit 1 +sakura: runtime error: Index or slice is out of bounds. + at main (tests/checked/fixed_arrays_are_bounded_1.sakura:5:4) diff --git a/tests/checked/fixed_arrays_are_bounded_1.sakura b/tests/checked/fixed_arrays_are_bounded_1.sakura new file mode 100644 index 00000000..047002b6 --- /dev/null +++ b/tests/checked/fixed_arrays_are_bounded_1.sakura @@ -0,0 +1,6 @@ +import std::io; +def main(): void { + var a: int[3] = [1, 2, 3]; + var i: uint = 3; + a[i] = 0; +} diff --git a/tests/checked/functions_as_values_2.out b/tests/checked/functions_as_values_2.out new file mode 100644 index 00000000..c125d549 --- /dev/null +++ b/tests/checked/functions_as_values_2.out @@ -0,0 +1,6 @@ +4 + +--- exit 1 +sakura: runtime error: Index or slice is out of bounds. + at (tests/checked/functions_as_values_2.sakura:5:67) + at main (tests/checked/functions_as_values_2.sakura:7:18) diff --git a/tests/checked/functions_as_values_2.sakura b/tests/checked/functions_as_values_2.sakura new file mode 100644 index 00000000..fa5407a5 --- /dev/null +++ b/tests/checked/functions_as_values_2.sakura @@ -0,0 +1,8 @@ +import std::io; +def main(): void { + var held: int[4] = [1, 2, 3, 4]; + val view := ((&mut held) as *mut int)[0:4]; + val pick := def(values: span, at: u64): int { return values[at]; }; + println($"{pick(view, 3)}"); + println($"{pick(view, 9)}"); +} diff --git a/tests/checked/ordinal_parameters_convert_to_and_from_integers_2.out b/tests/checked/ordinal_parameters_convert_to_and_from_integers_2.out new file mode 100644 index 00000000..3b4907af --- /dev/null +++ b/tests/checked/ordinal_parameters_convert_to_and_from_integers_2.out @@ -0,0 +1,5 @@ + +--- exit 1 +sakura: runtime error: Value is not a member of its enum. + at back (tests/checked/ordinal_parameters_convert_to_and_from_integers_2.sakura:3:52) + at main (tests/checked/ordinal_parameters_convert_to_and_from_integers_2.sakura:4:42) diff --git a/tests/checked/ordinal_parameters_convert_to_and_from_integers_2.sakura b/tests/checked/ordinal_parameters_convert_to_and_from_integers_2.sakura new file mode 100644 index 00000000..f14a64a8 --- /dev/null +++ b/tests/checked/ordinal_parameters_convert_to_and_from_integers_2.sakura @@ -0,0 +1,4 @@ +import std::io; +enum color: u8 { red, green = 4 } +def back(n: u64): T where T: ordinal { return n as T; } +def main(): void { val c := back::(3); } diff --git a/tests/checked/refined_functions_as_values_2.out b/tests/checked/refined_functions_as_values_2.out new file mode 100644 index 00000000..6d513199 --- /dev/null +++ b/tests/checked/refined_functions_as_values_2.out @@ -0,0 +1,4 @@ + +--- exit 1 +sakura: runtime error: Union does not hold the field that was read. + at main (tests/checked/refined_functions_as_values_2.sakura:6:8) diff --git a/tests/checked/refined_functions_as_values_2.sakura b/tests/checked/refined_functions_as_values_2.sakura new file mode 100644 index 00000000..24781059 --- /dev/null +++ b/tests/checked/refined_functions_as_values_2.sakura @@ -0,0 +1,7 @@ +import std::io; +struct failure { val message: span; } +union callable { var failure: failure; var call: def(): void; } +def main(): void { + val held := callable{ failure = failure{ message = "no" } }; + held.call(); +} diff --git a/tests/checked/text_constants_are_indexed_as_views_2.out b/tests/checked/text_constants_are_indexed_as_views_2.out new file mode 100644 index 00000000..4669f05d --- /dev/null +++ b/tests/checked/text_constants_are_indexed_as_views_2.out @@ -0,0 +1,5 @@ +66 +--- exit 1 +sakura: runtime error: Index or slice is out of bounds. + at pick (tests/checked/text_constants_are_indexed_as_views_2.sakura:2:35) + at main (tests/checked/text_constants_are_indexed_as_views_2.sakura:3:57) diff --git a/tests/checked/text_constants_are_indexed_as_views_2.sakura b/tests/checked/text_constants_are_indexed_as_views_2.sakura new file mode 100644 index 00000000..cba3f53a --- /dev/null +++ b/tests/checked/text_constants_are_indexed_as_views_2.sakura @@ -0,0 +1,3 @@ +import std::io; +def pick(i: u64): u8 { return "AB"[i]; } +def main(): void { print($"{pick(1)} "); println($"{pick(5)}"); } diff --git a/tests/checked/types_implementing_indexable_are_indexed_3.out b/tests/checked/types_implementing_indexable_are_indexed_3.out new file mode 100644 index 00000000..af4fe6ab --- /dev/null +++ b/tests/checked/types_implementing_indexable_are_indexed_3.out @@ -0,0 +1,6 @@ +before + +--- exit 1 +sakura: runtime error: Index or slice is out of bounds. + at holder::at (tests/checked/types_implementing_indexable_are_indexed_3.sakura:4:71) + at main (tests/checked/types_implementing_indexable_are_indexed_3.sakura:8:15) diff --git a/tests/checked/types_implementing_indexable_are_indexed_3.sakura b/tests/checked/types_implementing_indexable_are_indexed_3.sakura new file mode 100644 index 00000000..64f72b8d --- /dev/null +++ b/tests/checked/types_implementing_indexable_are_indexed_3.sakura @@ -0,0 +1,9 @@ +import std::io; +struct holder : indexable { var items: int[4]; } +def holder::at(&this, key: u64): &int { return &this.items[key]; } +def holder::at(&mut this, key: u64): &mut int { return &mut this.items[key]; } +def main(): void { + var d := holder { items = [1, 2, 3, 4] }; + println("before"); + println($"{d[9]}"); +} diff --git a/tests/checked/unions_2.out b/tests/checked/unions_2.out new file mode 100644 index 00000000..c951807d --- /dev/null +++ b/tests/checked/unions_2.out @@ -0,0 +1,5 @@ +before + +--- exit 1 +sakura: runtime error: Union does not hold the field that was read. + at main (tests/checked/unions_2.sakura:6:14) diff --git a/tests/checked/unions_2.sakura b/tests/checked/unions_2.sakura new file mode 100644 index 00000000..0bd9a105 --- /dev/null +++ b/tests/checked/unions_2.sakura @@ -0,0 +1,7 @@ +import std::io; +union number { var whole: int; var real: f64; } +def main(): void { + val n := number{ real = 1.5 }; + println("before"); + val i := n.whole; +} diff --git a/tests/checked/views_of_fixed_arrays_write_where_the_array_can_2.out b/tests/checked/views_of_fixed_arrays_write_where_the_array_can_2.out new file mode 100644 index 00000000..6664b0b4 --- /dev/null +++ b/tests/checked/views_of_fixed_arrays_write_where_the_array_can_2.out @@ -0,0 +1,5 @@ +before + +--- exit 1 +sakura: runtime error: Index or slice is out of bounds. + at main (tests/checked/views_of_fixed_arrays_write_where_the_array_can_2.sakura:6:13) diff --git a/tests/checked/views_of_fixed_arrays_write_where_the_array_can_2.sakura b/tests/checked/views_of_fixed_arrays_write_where_the_array_can_2.sakura new file mode 100644 index 00000000..5d037c59 --- /dev/null +++ b/tests/checked/views_of_fixed_arrays_write_where_the_array_can_2.sakura @@ -0,0 +1,8 @@ +import std::io; +def main(): void { + var a: int[4] = [1, 2, 3, 4]; + var n := 3; + println("before"); + val s := a[n:2]; + println($"{s}"); +} diff --git a/tests/compiler/compiler.sakura b/tests/compiler/compiler.sakura new file mode 100644 index 00000000..caba95c3 --- /dev/null +++ b/tests/compiler/compiler.sakura @@ -0,0 +1,510 @@ +#! @file compiler.sakura +#! @author John Christman (sorakatadzuma@gmail.com) +#! @copyright Malunal Studios, LLC. +#! @license MIT +#! +#! Contains the tests of lowering: small programs are checked and lowered, and +#! the code of their functions printed and compared with what is expected, +#! after the verifier has found nothing wrong with any of it. + +import std::io; +import std::testing; +import sakura::analyzer; +module sakura::compiler; + + +#! Checks the files as one program, lowers every function of it, and gives the +#! code of those named, printed one after another, or what went wrong. +#! @param names The names of the functions, separated by spaces. +#! @param texts The files' texts. +#! @returns The code. +def lowered(names: strview, texts: strview...): string { + var held := names::new(); + var notes := vector::::new(); + var sources := vector::::new(); + var syntaxes := vector::::new(); + var roots := vector::::new(); + sources.reserve(texts.length); + syntaxes.reserve(texts.length); + for i in 0..texts.length { + sources.append(source::from(i == 0 ? "test.sakura" : "other.sakura", texts.at(i))); + syntaxes.append(syntax::new()); + } + for i in 0..texts.length { + var lexing := lexer::new(sources.at(i), &mut held, &mut notes, i as u32); + lexing.tokenize_all(syntaxes.at(i)); + var parsing := parser::new(syntaxes.at(i), &held, &mut notes, i as u32); + roots.append(parsing.parse()); + } + var checker := checker::new(&mut held, &mut notes); + for i in 0..texts.length { + checker.add(sources.at(i), syntaxes.at(i), roots.at(i)); + } + checker.check(); + + var out := string::new(nothing {}); + if notes.length != 0 { + out.append("the program does not check"); + return out; + } + var lowering := lowerer::new(&mut checker, lowering { verify = true, everything = true }); + lowering.compile(); + for &each in lowering.problems { + out.append(each.view()); + out.append("\n"); + } + + var wanted := string::from(names, nothing {}); + for name in wanted.split(' ') { + for &function in lowering.program.functions { + if function.name.view() == name { + var text := function.body.print(); + out.append(text.view()); + } + } + } + return out; +} + +#! Whether code printed is what is expected, but for the line breaks ending +#! them, printing what it is where it is not. +#! @param got The code printed. +#! @param want The code expected. +#! @returns Whether it is. +def lowers_as(got: &string, want: strview): bool { + var x := got.length; + var y := want.length; + while x > 0 && got.at(x - 1) == '\n' { x--; } + while y > 0 && want.at(y - 1) == '\n' { y--; } + val same := got.substr(0, x) == want.substr(0, y); + if !same { + println(got); + } + return same; +} + + +@test def arithmetic_narrows_to_its_type(t: &mut tester): void { + # Arithmetic on words wraps at 64 bits, so a result narrower than a word is + # narrowed again, and an `f32` is rounded to its precision. + val got := lowered("add neg mix", """ + def add(a: u8, b: u8): u8 { return a + b; } + def neg(a: i16): i16 { return -a; } + def mix(a: i32, b: f32): f32 { return a as f32 * b; } + def clamp(a: i64): i64 { return a < 0 ? 0 : a; } + def both(a: bool, b: bool): bool { return a && !b; } + """); + t.expects(lowers_as(&got, """ + b0(v0: i64, v1: i64): + v2 = add v0, v1 + v3 = wrap v2, 8, unsigned + ret v3 + b0(v0: i64): + v1 = neg v0 + v2 = wrap v1, 16, signed + ret v2 + b0(v0: i64, v1: f64): + v2 = itof v0 + v3 = fsingle v2 + v4 = fmul v3, v1 + v5 = fsingle v4 + ret v5 + """)); +} + + +@test def and_or_branch_rather_than_compute(t: &mut tester): void { + # `&&` goes to its right only where its left holds, and `!` swaps where a + # condition goes rather than computing a value. + val got := lowered("both", """ + def add(a: u8, b: u8): u8 { return a + b; } + def neg(a: i16): i16 { return -a; } + def mix(a: i32, b: f32): f32 { return a as f32 * b; } + def clamp(a: i64): i64 { return a < 0 ? 0 : a; } + def both(a: bool, b: bool): bool { return a && !b; } + """); + t.expects(lowers_as(&got, """ + b0(v0: i64, v1: i64): + branch v0, b1, b3 + b1: + branch v1, b3, b2 + b2: + v2 = iconst 1 + jump b4(v2) + b3: + v3 = iconst 0 + jump b4(v3) + b4(v4: i64): + ret v4 + """)); +} + + +@test def structs_live_in_cells_and_return_by_address(t: &mut tester): void { + # A struct is built in a cell, what its fields given do not write cleared + # and its default given; a local referred to where the reference cannot be + # kept is held in a cell, and a struct returned in memory is written where + # the call says. + val got := lowered("make main", """ + struct pair { var a: i64; var b: i32 = 7; } + def sum(p: pair): i64 { return p.a + p.b as i64; } + def make(): pair { return pair { a = 1 }; } + def bump(x: &mut i64): void { x = x + 1; } + def main(): void { + var n: i64 = 1; + bump(&mut n); + val p := make(); + sum(p); + } + """); + t.expects(lowers_as(&got, """ + c0: 16, 8 + b0: + v0 = cell c0 + v1 = iconst 0 + store.i64 v0+8, v1 + v2 = iconst 1 + store.i64 v0, v2 + v3 = iconst 7 + store.i32 v0+8, v3 + ret v0 + c0: 8, 8 + c1: 16, 8 + c2: 16, 8 + b0: + v0 = cell c0 + v1 = iconst 1 + store.i64 v0, v1 + call f4(v0) + v2 = cell c1 + v3 = cell c2 + call f3(v3) + copy v2, v3, 16 + v4 = cell c2 + copy v4, v2, 16 + v5 = call f2(v4) + ret + """)); +} + + +@test def tests_and_matches_read_the_tag(t: &mut tester): void { + # A union's tag says which field it holds, which a test names and a match + # goes by; a match used as a value without `else` traps where none holds. + val got := lowered("size", """ + union shape { var circle: f64; var square: i64; } + def size(s: &shape): i64 { + if s is square(w) { + return w; + } + return match s { + circle(r) => r as i64, + square(w) => w + }; + } + """); + t.expects(lowers_as(&got, """ + b0(v0: i64): + v1 = iconst 0 + v2 = load.i64 v0 + v3 = iconst 1 + v4 = eq v2, v3 + branch v4, b1, b2(v1) + b1: + v5 = load.i64 v0+8 + jump b2(v5) + b2(v6: i64): + branch v4, b9, b3 + b3: + v7 = load.i64 v0 + v8 = iconst 0 + v9 = eq v7, v8 + branch v9, b7, b4 + b4: + v10 = load.i64 v0 + v11 = iconst 1 + v12 = eq v10, v11 + branch v12, b6, b5 + b5: + trap not_member + b6: + v13 = load.i64 v0+8 + jump b8(v13) + b7: + v14 = load.f64 v0+8 + v15 = ftoi v14 + jump b8(v15) + b8(v16: i64): + ret v16 + b9: + ret v6 + """)); +} + + +@test def traits_dispatch_through_vtables_and_closures_capture_where_they_can_be_reached(t: &mut tester): void { + # A call through a trait reference goes through its vtable, and a reference to + # a value becomes one to a trait by its vtable, the value known while compiling + # held where the statement holds it. A local an anonymous function captures is + # held where its environment refers to it, both cells of the frame. + val got := lowered("call main ", """ + trait named { def name(&this): i64; } + struct one : named { var n: i64; } + def one::name(&this): i64 { return this.n; } + def call(x: &named): i64 { return x.name(); } + def main(): void { + val o := one { n = 3 }; + call(&o); + var k: i64 = 5; + val f := def(x: i64): i64 { return x + k; }; + f(1); + } + """); + t.expects(lowers_as(&got, """ + b0(v0: i64, v1: i64): + v2 = call_trait s2[0](v0, v1) + ret v2 + c0: 8, 8 + c1: 8, 8 + c2: 8, 8 + c3: 8, 8 + b0: + v0 = cell c0 + v1 = cell c1 + v2 = iconst 3 + store.i64 v1, v2 + copy v0, v1, 8 + v3 = iconst 0 + v4 = call f3(v0, v3) + v5 = cell c2 + v6 = iconst 5 + store.i64 v5, v6 + v7 = iconst 5 + v8 = cell c3 + store.i64 v8, v5 + v9 = iconst 1 + v10 = call_value s3(v7, v8, v9) + ret + b0(v0: i64, v1: i64): + v2 = load.i64 v1 + v3 = load.i64 v2 + v4 = add v0, v3 + ret v4 + """)); +} + +# What a walk of the escape tests walks. +struct escape_body { + var n: i64; # Its number. +} + +# A walk holding a reference to what it walks. +struct escape_walk { + var of: &escape_body; # What it walks. +} + +# A walk of a body, which holds a reference to it. +def escape_body::walk(&this): escape_walk { + return escape_walk { of = this }; +} + +# The number a walk of a body local to the frame reads. +def escape_walked(n: i64): i64 { + var made := escape_body { n = n }; + val walk := made.walk(); + return walk.of.n; +} + +# Gives each element of a vector to a function. +def escape_each_of(xs: &vector, f: def(&i64): void): void { + for &x in xs { + f(x); + } +} + +# The sum of a vector's elements, through a closure writing a local of the frame. +def escape_sum_of(xs: &vector): i64 { + var total: i64 = 0; + escape_each_of(xs, def(x: &i64): void { total += x; }); + return total; +} + +@test def references_and_closures_refer_to_what_their_frames_hold(t: &mut tester): void { + # A walk and a closure refer to what the frame making them holds, where it is, + # so each sees it changed, and those made in a function read and write its + # frame while it runs. + var held := escape_body { n = 4 }; + val a := held.walk(); + var k: i64 = 5; + val f := def(): i64 { return k; }; + held.n = 11; + k = 9; + var xs := vector::::new(); + xs.append(1); + xs.append(2); + xs.append(3); + t.expects(a.of.n == 11 && escape_walked(7) == 7 && f() == 9 && escape_sum_of(&xs) == 6); +} + +@test def a_value_called_through_invoke_is_referred_to_where_it_is(t: &mut tester): void { + # A value called as `a(2)` is the `this` of its `invoke`, which cannot keep it, + # so it stays in a cell of the frame as it does for `a.invoke(2)`, and a + # function calling a parameter so keeps nothing of it. + val got := lowered("main apply", """ + struct adder { var total: i64; } + def adder::invoke(&mut this, by: i64): i64 { this.total += by; return this.total; } + def apply(f: &mut adder): i64 { return f(1); } + def main(): void { + var a := adder { total = 0 }; + a(2); + apply(&mut a); + } + """); + val text := got.view(); + var boxed := false; + for i in 0..text.length { + boxed = boxed || text.substr(i, 3) == "box"; + } + t.expects(text.substr(0, 4) == "c0: " && !boxed); +} + + +@test def values_made_down_one_branch_close_where_made(t: &mut tester): void { + # What a statement makes that closes is closed where it ends, where it was made, + # and a local where its scope ends. + val got := lowered("pick hold", """ + import std; + struct handle : owning { var n: i64; } + def handle::close(&mut this): void { this.n = 0; } + def make(): handle { return handle { n = 1 }; } + def peek(h: &handle): i64 { return h.n; } + def pick(c: bool): i64 { return c ? peek(&make()) : 0; } + def hold(): void { + val h := make(); + peek(&h); + } + """, """ + module std; module core; + pub trait owning { def close(&mut this): void; } + """); + t.expects(lowers_as(&got, """ + c0: 8, 8 + b0(v0: i64): + v1 = iconst 0 + branch v0, b2, b1 + b1: + v2 = iconst 0 + jump b3(v2, v1) + b2: + v3 = cell c0 + call f2(v3) + v4 = iconst 1 + v5 = call f3(v3) + jump b3(v5, v4) + b3(v6: i64, v7: i64): + branch v7, b4, b5 + b4: + v8 = cell c0 + call f1(v8) + v9 = iconst 0 + jump b5 + b5: + ret v6 + c0: 8, 8 + c1: 8, 8 + b0: + v0 = cell c0 + v1 = cell c1 + call f2(v1) + v2 = iconst 1 + copy v0, v1, 8 + v3 = call f3(v0) + call f1(v0) + ret + """)); +} + + +@test def loops_lower_with_their_variables_at_their_heads(t: &mut tester): void { + # Variables a loop changes arrive at its head as parameters, and a loop over a + # fixed array walks its elements by address. + val got := lowered("steps total", """ + def steps(start: u64): u64 { + var n := start; + var count: u64 = 0; + while n != 1 { + if n % 2 == 0 { n = n / 2; } else { n = 3 * n + 1; } + count += 1; + } + return count; + } + def total(xs: &i64[4]): i64 { + var sum: i64 = 0; + for x in xs { + sum += x; + } + return sum; + } + def first_even(xs: &i64[4]): i64 { + for i in 0..4 { + if xs[i] % 2 == 0 { return xs[i]; } + if xs[i] < 0 { break; } + } + return -1; + } + """); + t.expects(lowers_as(&got, """ + b0(v0: i64): + v1 = iconst 0 + jump b1(v0, v1) + b1(v2: i64, v3: i64): + v4 = iconst 1 + v5 = ne v2, v4 + branch v5, b3, b2 + b2: + ret v3 + b3: + v6 = iconst 2 + v7 = remu v2, v6 + v8 = iconst 0 + v9 = eq v7, v8 + branch v9, b5, b4 + b4: + v10 = iconst 3 + v11 = mul v10, v2 + v12 = iconst 1 + v13 = add v11, v12 + jump b6(v13) + b5: + v14 = iconst 2 + v15 = divu v2, v14 + jump b6(v15) + b6(v16: i64): + v17 = iconst 1 + v18 = add v3, v17 + jump b7 + b7: + jump b1(v16, v18) + b0(v0: i64): + v1 = iconst 0 + v2 = iconst 4 + v3 = iconst 0 + jump b1(v3, v1) + b1(v4: i64, v5: i64): + v6 = ltu v4, v2 + branch v6, b3, b2 + b2: + ret v5 + b3: + v7 = iconst 8 + v8 = mul v4, v7 + v9 = add v0, v8 + v10 = load.i64 v9 + v11 = add v5, v10 + jump b4 + b4: + v12 = iconst 1 + v13 = add v4, v12 + jump b1(v13, v11) + """)); +} diff --git a/tests/compiler/intermediate.sakura b/tests/compiler/intermediate.sakura new file mode 100644 index 00000000..bcd5a783 --- /dev/null +++ b/tests/compiler/intermediate.sakura @@ -0,0 +1,298 @@ +#! @file intermediate.sakura +#! @author John Christman (sorakatadzuma@gmail.com) +#! @copyright Malunal Studios, LLC. +#! @license MIT +#! +#! Contains the tests of the intermediate code: building it with variables, +#! which become the parameters of blocks where control flow joins, taking out +#! what stands for one value, verifying it, printing it, and walking it, and +#! the lists of indices its blocks and edges hold. + +import std::io; +import std::testing; +module sakura::compiler; + + +#! Whether two texts are the same but for the line breaks ending them, which +#! printed code ends with and a block of text does not. +#! @param a One text. +#! @param b The other. +#! @returns Whether they are. +def same_text(a: strview, b: strview): bool { + var x := a.length; + var y := b.length; + while x > 0 && a.at(x - 1) == '\n' { x--; } + while y > 0 && b.at(y - 1) == '\n' { y--; } + val same := a.substr(0, x) == b.substr(0, y); + if !same { + println(a); + } + return same; +} + +#! Builds the loop of `steps`, which counts the steps of the Collatz sequence: +#! +#! ``` +#! def steps(start: u64): u64 { +#! var n := start; +#! var count: u64 = 0; +#! while n != 1 { +#! if n % 2 == 0 { n = n / 2; } else { n = 3 * n + 1; } +#! count += 1; +#! } +#! return count; +#! } +#! ``` +#! @returns Its code. +def build_steps(): code { + var params: vt[1] = [vt::word]; + var made := builder::new(params[0:1]); + val n := made.variable(vt::word); + val count := made.variable(vt::word); + made.assign(n, made.param(0)); + made.assign(count, made.word(0)); + + val head := made.new_block(); + val body := made.new_block(); + val exit := made.new_block(); + made.jump(head); + made.switch_to(head); + val done := made.binary(op::ne, made.read(n), made.word(1)); + made.branch(done, body, exit); + made.seal(body); + made.seal(exit); + + made.switch_to(body); + val even := made.binary(op::eq, made.binary(op::remu, made.read(n), made.word(2)), made.word(0)); + val half := made.new_block(); + val odd := made.new_block(); + val next := made.new_block(); + made.branch(even, half, odd); + made.seal(half); + made.seal(odd); + + made.switch_to(half); + made.assign(n, made.binary(op::divu, made.read(n), made.word(2))); + made.jump(next); + made.switch_to(odd); + made.assign(n, made.binary(op::add, made.binary(op::mul, made.word(3), made.read(n)), made.word(1))); + made.jump(next); + made.seal(next); + + made.switch_to(next); + made.assign(count, made.binary(op::add, made.read(count), made.word(1))); + made.jump(head); + made.seal(head); + + made.switch_to(exit); + var result: u32[1] = [made.read(count)]; + made.ret(result[0:1]); + return made.finish(); +} + +@test def loops_take_their_variables_as_parameters(t: &mut tester): void { + var made := build_steps(); + made.results.append(vt::word); + val verdict := made.verify(); + t.expects(verdict.ok()); + for &each in verdict.problems { + println(each); + } + + val printed := made.print(); + val want := """ + b0(v0: i64): + v1 = iconst 0 + jump b1(v0, v1) + b1(v2: i64, v3: i64): + v4 = iconst 1 + v5 = ne v2, v4 + branch v5, b3, b2 + b2: + ret v3 + b3: + v6 = iconst 2 + v7 = remu v2, v6 + v8 = iconst 0 + v9 = eq v7, v8 + branch v9, b5, b4 + b4: + v10 = iconst 3 + v11 = mul v10, v2 + v12 = iconst 1 + v13 = add v11, v12 + jump b6(v13) + b5: + v14 = iconst 2 + v15 = divu v2, v14 + jump b6(v15) + b6(v16: i64): + v17 = iconst 1 + v18 = add v3, v17 + jump b1(v16, v18) + """; + t.expects(same_text(printed.view(), want)); +} + +@test def parameters_standing_for_one_value_are_taken_out(t: &mut tester): void { + # `x` is given before the branch, and neither side changes it, so the join + # takes nothing. + var params: vt[1] = [vt::word]; + var made := builder::new(params[0:1]); + val x := made.variable(vt::word); + made.assign(x, made.param(0)); + val then := made.new_block(); + val other := made.new_block(); + val join := made.new_block(); + made.branch(made.param(0), then, other); + made.seal(then); + made.seal(other); + made.switch_to(then); + made.jump(join); + made.switch_to(other); + made.jump(join); + made.seal(join); + made.switch_to(join); + var result: u32[1] = [made.read(x)]; + made.ret(result[0:1]); + + var code := made.finish(); + code.results.append(vt::word); + t.expects(code.verify().ok()); + t.expects(same_text(code.print().view(), """ + b0(v0: i64): + branch v0, b2, b1 + b1: + jump b3 + b2: + jump b3 + b3: + ret v0 + """)); +} + +@test def what_nothing_reaches_is_taken_out(t: &mut tester): void { + var made := builder::new(span::::empty()); + var none: u32[1] = [0]; + made.ret(none[0:0]); + # Code after a `return` goes in a block nothing reaches. + made.word(5); + made.ret(none[0:0]); + + var code := made.finish(); + t.expects(code.verify().ok()); + t.expects(same_text(code.print().view(), "b0:\n ret")); +} + +@test def the_verifier_finds_uses_not_dominated(t: &mut tester): void { + var params: vt[1] = [vt::word]; + var made := builder::new(params[0:1]); + val then := made.new_block(); + val other := made.new_block(); + val join := made.new_block(); + made.branch(made.param(0), then, other); + made.seal(then); + made.seal(other); + made.switch_to(then); + val only_here := made.word(1); + made.jump(join); + made.switch_to(other); + made.jump(join); + made.seal(join); + made.switch_to(join); + var result: u32[1] = [only_here]; + made.ret(result[0:1]); + + var code := made.finish(); + code.results.append(vt::word); + val verdict := code.verify(); + t.expects(!verdict.ok()); +} + + +@test def lists_of_indices_hold_four_themselves_and_more_in_memory(t: &mut tester): void { + var list := ids {}; + for i in 0..4u { + list.append(i as u32 * 3); + } + t.expects(list.length == 4 && list.at(3) == 9); + + # Past four the indices move to memory of the list's own, and stay in order. + for i in 4..100u { + list.append(i as u32 * 3); + } + var total: u64 = 0; + for &each in list { + total += each as u64; + } + t.expects(list.length == 100 && list.at(0) == 0 && list.at(99) == 297 && total == 14850); + + list.at(5) = 1; + var other := list.copied(nothing {}); + t.expects(other.at(5) == 1 && other.length == 100); + var same := ids {}; + for &each in other { + same.append(each); + } + t.expects(same.same(&list)); + same.clear(); + t.expects(same.length == 0 && !same.same(&list)); +} + +@test def walks_give_each_instruction_and_what_each_reads(t: &mut tester): void { + var made := build_steps(); + + # Every instruction of the blocks not removed, each once. + var count: u32 = 0; + var all := made.walk_all(); + while all.more() { + all.next(); + count++; + } + t.expects(count != 0 && count == made.size()); + + # The loop's head, block 1, compares and branches. + var found := vector::::new(); + var head := made.walk(1); + while head.more() { + found.append(head.next()); + } + t.expects(found.length == 3 && made.insts[found[0]].kind == op::iconst + && made.insts[found[1]].kind == op::ne && made.insts[found[2]].kind == op::branch); + + # The comparison reads its operands, in order. + var operands := made.reads_of(found[1]); + var places: u32 = 0; + while operands.more() { + operands.next(); + t.expects(operands.operand() == places); + places++; + } + t.expects(places == 2); + + # The branch leaves by two edges, one after another. + var outs := made.edges_of(found[2]); + t.expects(outs.more() && outs.next() == made.insts[found[2]].aux); + t.expects(outs.more() && outs.next() == made.insts[found[2]].aux + 1 && !outs.more()); + + # The jump back to the head reads only what its edge gives. + val jump: u32 = made.blocks[6].last; + val first: u32 = made.edges[made.insts[jump].aux].args[0]; + var given := made.reads_of(jump); + var values := vector::::new(); + while given.more() { + values.append(given.next()); + t.expects(given.operand() == no_operand); + } + t.expects(values.length == 2 && values[0] == first); + + # A walk reads where each instruction goes on to as it gives it, so taking + # the one given out of its block's order does not end the walk. + var cut: u32 = 0; + var again := made.walk(1); + while again.more() { + made.insts[again.next()].next = 0; + cut++; + } + t.expects(cut == 3); +} diff --git a/tests/compiler/optimizer.sakura b/tests/compiler/optimizer.sakura new file mode 100644 index 00000000..1c686425 --- /dev/null +++ b/tests/compiler/optimizer.sakura @@ -0,0 +1,697 @@ +#! @file optimizer.sakura +#! @author John Christman (sorakatadzuma@gmail.com) +#! @copyright Malunal Studios, LLC. +#! @license MIT +#! +#! Contains the tests of the optimizer: small programs are checked, lowered, +#! and optimized at a level, the verifier running after every pass, and the +#! code of their functions printed and compared with what is expected. Each +#! test shows what one pass does, with the others cleaning up after it. The +#! containers the passes keep track of what they find with are tested too. + +import std::io; +import std::testing; +import sakura::analyzer; +module sakura::compiler; + + +#! Checks the files as one program, lowers and optimizes every function of it +#! at a level, and gives the code of those named, printed one after another, +#! or what went wrong, the verifier's problems among it. At level 0, every named +#! local is kept in a cell of its own, as `-O0` keeps them. +#! @param level How much the code is optimized. +#! @param names The names of the functions, separated by spaces. +#! @param texts The files' texts. +#! @returns The code. +def optimized(level: u32, names: strview, texts: strview...): string { + return optimized_on(1, level, names, ...texts); +} + +#! Checks the files as one program, lowers and optimizes every function of it +#! at a level on a number of threads, and gives the code of those named, +#! printed one after another, or what went wrong, as `optimized` does. +#! @param threads How many threads optimize the functions. +#! @param level How much the code is optimized. +#! @param names The names of the functions, separated by spaces. +#! @param texts The files' texts. +#! @returns The code. +def optimized_on(threads: u32, level: u32, names: strview, texts: strview...): string { + var held := names::new(); + var notes := vector::::new(); + var sources := vector::::new(); + var syntaxes := vector::::new(); + var roots := vector::::new(); + sources.reserve(texts.length); + syntaxes.reserve(texts.length); + for i in 0..texts.length { + sources.append(source::from(i == 0 ? "test.sakura" : "other.sakura", texts.at(i))); + syntaxes.append(syntax::new()); + } + for i in 0..texts.length { + var lexing := lexer::new(sources.at(i), &mut held, &mut notes, i as u32); + lexing.tokenize_all(syntaxes.at(i)); + var parsing := parser::new(syntaxes.at(i), &held, &mut notes, i as u32); + roots.append(parsing.parse()); + } + var checker := checker::new(&mut held, &mut notes); + for i in 0..texts.length { + checker.add(sources.at(i), syntaxes.at(i), roots.at(i)); + } + checker.check(); + + var out := string::new(nothing {}); + if notes.length != 0 { + out.append("the program does not check"); + return out; + } + var lowering := lowerer::new(&mut checker, lowering { verify = true, everything = true, level = level, keep_locals = level == 0, threads = threads }); + lowering.compile(); + for &each in lowering.problems { + out.append(each.view()); + out.append("\n"); + } + + var wanted := string::from(names, nothing {}); + for name in wanted.split(' ') { + for &function in lowering.program.functions { + if function.name.view() == name { + var text := function.body.print(); + out.append(text.view()); + } + } + } + return out; +} + +#! Checks the files as one program, lowers it checked and optimizes it with +#! inlining, and lists the checks left in its functions as +#! `check --checks-report` counts them: for each, the function, the line, the +#! kind, and how many, each followed by a space. +#! @param texts The files' texts. +#! @returns The list, or what went wrong. +def checks_left_in(texts: strview...): string { + var held := names::new(); + var notes := vector::::new(); + var sources := vector::::new(); + var syntaxes := vector::::new(); + var roots := vector::::new(); + sources.reserve(texts.length); + syntaxes.reserve(texts.length); + for i in 0..texts.length { + sources.append(source::from(i == 0 ? "test.sakura" : "other.sakura", texts.at(i))); + syntaxes.append(syntax::new()); + } + for i in 0..texts.length { + var lexing := lexer::new(sources.at(i), &mut held, &mut notes, i as u32); + lexing.tokenize_all(syntaxes.at(i)); + var parsing := parser::new(syntaxes.at(i), &held, &mut notes, i as u32); + roots.append(parsing.parse()); + } + var checker := checker::new(&mut held, &mut notes); + for i in 0..texts.length { + checker.add(sources.at(i), syntaxes.at(i), roots.at(i)); + } + checker.check(); + + var out := string::new(nothing {}); + if notes.length != 0 { + out.append("the program does not check"); + return out; + } + var lowering := lowerer::new(&mut checker, lowering { verify = true, everything = true, level = 2 }); + lowering.compile(); + val kinds: strview[4] = ["index", "field", "member", "fault"]; + for &each in lowering.checks_left() { + val line := sources.at(pair_high(each.at) as u64 - 1).lines.place_of(pair_low(each.at)).line; + out.append($"{lowering.program.functions[each.function].name}:{line}:{kinds[each.kind as u64]}:{each.count} "); + } + return out; +} + +@test def the_checks_the_optimizer_leaves_are_listed_by_line(t: &mut tester): void { + # A check inlined is listed at the call, and one the code proved before, or + # a loop's own test answers, is not left. + val got := checks_left_in(""" + union shape { var round: f64; var square: i64; } + enum color: u8 { red, green, blue } + def pick(xs: &i64[8], i: u64): i64 { return xs[i]; } + def side(s: shape): i64 { return s.square; } + def hue(n: u8): color { return n as color; } + def total(xs: &i64[8]): i64 { var t: i64 = 0; for i in 0..8u { t += xs[i]; } return t; } + def twice(xs: &i64[8], i: u64): i64 { + return pick(xs, i) + pick(xs, i); + } + """); + t.expects(got.view() == "pick:3:index:1 side:4:field:1 hue:5:member:1 twice:8:index:1 "); +} + +@test def constants_fold_and_powers_of_two_shift(t: &mut tester): void { + # Operators of constants are worked out, and an unsigned division and + # remainder by a power of two become a shift and a mask. + val got := optimized(1, "fold", """ + def fold(x: u64): u64 { return x / 8 + x % 16 + 2 * 3; } + """); + t.expects(lowers_as(&got, """ + b0(v0: i64): + v1 = iconst 15 + v2 = iconst 3 + v3 = shru v0, v2 + v4 = band v0, v1 + v5 = add v3, v4 + v6 = iconst 6 + v7 = add v5, v6 + ret v7 + """)); +} + + +@test def values_nothing_needs_go_even_around_loops(t: &mut tester): void { + # `waste` is only ever added to, and read by nothing else, so the loop no + # longer carries it. The loop is rotated: whether to go round again is asked + # at its bottom, and once before it. + val got := optimized(1, "count", """ + def count(n: u64): u64 { + var waste: u64 = 0; + var i: u64 = 0; + while i < n { waste += i; i += 1; } + return i; + } + """); + t.expects(lowers_as(&got, """ + b0(v0: i64): + v1 = iconst 0 + v2 = iconst 1 + branch v0, b1(v1), b2(v1) + b1(v3: i64): + v4 = add v3, v2 + v5 = ltu v4, v0 + branch v5, b1(v4), b2(v4) + b2(v6: i64): + ret v6 + """)); +} + + +@test def conditions_joined_as_constants_go_straight_where_they_lead(t: &mut tester): void { + # `a && !b` joins the constant it works out before branching on it; each + # edge giving a constant goes straight where the branch would send it. + val got := optimized(1, "both", """ + def both(a: bool, b: bool): i64 { + if a && !b { return 1; } + return 2; + } + """); + t.expects(lowers_as(&got, """ + b0(v0: i64, v1: i64): + branch v0, b1, b3 + b1: + branch v1, b3, b2 + b2: + v2 = iconst 1 + ret v2 + b3: + v3 = iconst 2 + ret v3 + """)); +} + + +@test def flags_worked_out_from_constants_go_straight_where_they_lead(t: &mut tester): void { + # The join works out `found == 1` from the constant each way gives it, so + # each goes straight where the test sends it, and the value it gave `at` + # reaches what reads it as a parameter of where it went. + val got := optimized(1, "first", """ + def first(a: bool, x: i64): i64 { + var found: u64 = 0; + var at: i64 = 0; + if a { found = 1; at = x; } + if found == 1 { return at + 1; } + return 0; + } + """); + t.expects(lowers_as(&got, """ + b0(v0: i64, v1: i64): + v2 = iconst 0 + branch v0, b2, b1 + b1: + ret v2 + b2: + v3 = iconst 1 + v4 = add v1, v3 + ret v4 + """)); +} + + +@test def branches_choosing_values_become_selects(t: &mut tester): void { + # The `if` only chooses the value `x` joins with, so it becomes a `select`. + val got := optimized(1, "pick", """ + def pick(c: bool, a: i64, b: i64): i64 { + var x := b; + if c { x = a; } + return x; + } + """); + t.expects(lowers_as(&got, """ + b0(v0: i64, v1: i64, v2: i64): + v3 = select v0, v1, v2 + ret v3 + """)); + + # Where `n` is zero, `k` is 0 either way, which is `n`. + val zeros := optimized(1, "nonzero", """ + def nonzero(n: u64): u64 { + var k: u64 = 0; + if n != 0 { k = n; } + return k; + } + """); + t.expects(lowers_as(&zeros, """ + b0(v0: i64): + ret v0 + """)); + + # Within the `if`, `c` is known not to be zero, so the choice is known. + val known := optimized(1, "known", """ + def known(c: bool, a: i64, b: i64): i64 { + if c { return c ? a : b; } + return 0; + } + """); + t.expects(lowers_as(&known, """ + b0(v0: i64, v1: i64, v2: i64): + branch v0, b2, b1 + b1: + v3 = iconst 0 + ret v3 + b2: + ret v1 + """)); +} + + +@test def a_check_a_dominating_one_made_goes(t: &mut tester): void { + # The second `v[i]` compares what the first did, which was checked, and + # reads what it read. + val got := optimized(1, "twice", """ + def twice(v: &i64[8], i: u64): i64 { return v[i] + v[i]; } + """); + t.expects(lowers_as(&got, """ + b0(v0: i64, v1: i64): + v2 = iconst 3 + v3 = iconst 8 + v4 = ltu v1, v3 + check v4, out_of_bounds + v5 = shl v1, v2 + v6 = add v0, v5 + v7 = load.i64 v6 + v8 = add v7, v7 + ret v8 + """)); +} + + +@test def a_read_a_loop_writing_nothing_repeats_reads_what_was_read_before(t: &mut tester): void { + # Nothing in the loop writes, so `p.key` reads what it read before the loop + # each time round. + val got := optimized(1, "scan", """ + struct pair { var key: i64; var other: i64; } + def scan(p: &pair, v: &i64[8]): u64 { + if p.key < 0 { return 8; } + var i: u64 = 0; + while i < 8 { if v[i] == p.key { return i; } i += 1; } + return i; + } + """); + t.expects(lowers_as(&got, """ + b0(v0: i64, v1: i64): + v2 = iconst 1 + v3 = iconst 8 + v4 = iconst 3 + v5 = load.i64 v0 + v6 = iconst 0 + v7 = lts v5, v6 + branch v7, b6, b1 + b1: + jump b2(v6) + b2(v8: i64): + v9 = shl v8, v4 + v10 = add v1, v9 + v11 = load.i64 v10 + v12 = eq v11, v5 + branch v12, b5, b3 + b3: + v13 = add v8, v2 + v14 = ltu v13, v3 + branch v14, b2(v13), b4 + b4: + ret v13 + b5: + ret v8 + b6: + ret v3 + """)); +} + + +@test def a_choice_sunk_past_the_branch_deciding_it_is_what_it_chooses(t: &mut tester): void { + # `s` is only read where `c != 0`, so the `select` making it is sunk there, + # where the branch decides its condition, and becomes what it chooses. + val got := optimized(1, "pick", """ + def pick(a: *u64): u64 { + val c := a[0]; + val s := c != 0 ? c + 1 : 5; + if c != 0 { return s * 3; } + return 7; + } + """); + t.expects(lowers_as(&got, """ + b0(v0: i64): + v1 = iconst 1 + v2 = load.i64 v0 + branch v2, b2, b1 + b1: + v3 = iconst 7 + ret v3 + b2: + v4 = add v2, v1 + v5 = iconst 3 + v6 = mul v4, v5 + ret v6 + """)); +} +@test def loops_rotate_and_what_they_work_out_the_same_moves_out(t: &mut tester): void { + # The loop asks whether to go round again at its bottom, and once before it, + # where the size is read. Nothing in it writes, so the size is read there + # only, and where the pointer is read and checked is before the loop, as its + # first pass reads and checks it before anything else. + val got := optimized(1, "find", """ + struct table { var data: *i64; var size: u64; } + def find(t: &table, key: i64): u64 { + var i: u64 = 0; + while i < t.size { if t.data[i] == key { return i; } i += 1; } + return t.size; + } + """); + t.expects(lowers_as(&got, """ + b0(v0: i64, v1: i64): + v2 = iconst 0 + v3 = iconst 1 + v4 = iconst 3 + v5 = load.i64 v0+8 + branch v5, b1, b4 + b1: + v6 = load.i64 v0 + check v6, null_reference + jump b2(v2) + b2(v7: i64): + v8 = shl v7, v4 + v9 = add v6, v8 + v10 = load.i64 v9 + v11 = eq v10, v1 + branch v11, b5, b3 + b3: + v12 = add v7, v3 + v13 = ltu v12, v5 + branch v13, b2(v12), b4 + b4: + ret v5 + b5: + ret v7 + """)); +} + + +@test def writes_known_not_to_touch_a_read_leave_it_known(t: &mut tester): void { + # Writing `p.b` does not write `p.a`, so `p.a` is read once. + val fields := optimized(1, "bump", """ + struct pair { var a: i64; var b: i64; } + def bump(p: &mut pair): i64 { val x := p.a; p.b = x; return p.a + 1; } + """); + t.expects(lowers_as(&fields, """ + b0(v0: i64): + v1 = load.i64 v0 + store.i64 v0+8, v1 + v2 = iconst 1 + v3 = add v1, v2 + ret v3 + """)); + + # A call cannot write a cell whose address it is not given, so what was + # stored there is read again without the cell. + val called := optimized(1, "kept", """ + def tick(): void {} + def kept(n: i64): i64 { var x := n * 3; tick(); return x + 1; } + """); + t.expects(lowers_as(&called, """ + b0(v0: i64): + v1 = iconst 3 + v2 = mul v0, v1 + call f1() + v3 = iconst 1 + v4 = add v2, v3 + ret v4 + """)); + + # Writing the frame's array does not write what `p` points at, so the loop + # reads `p.a` once, before it. + val looped := optimized(2, "fill", """ + struct pair { var a: i64; var b: i64; } + def fill(p: &pair): i64 { + var buf: i64[4] = [0, 0, 0, 0]; + var i: u64 = 0; + while i < 4 { buf[i] = p.a; i += 1; } + return buf[0] + buf[3]; + } + """); + t.expects(lowers_as(&looped, """ + c0: 32, 8 + b0(v0: i64): + v1 = iconst 1 + v2 = iconst 4 + v3 = iconst 3 + v4 = cell c0 + v5 = iconst 0 + v6 = load.i64 v0 + jump b1(v5) + b1(v7: i64): + v8 = shl v7, v3 + v9 = add v4, v8 + store.i64 v9, v6 + v10 = add v7, v1 + v11 = ltu v10, v2 + branch v11, b1(v10), b2 + b2: + v12 = load.i64 v4 + v13 = load.i64 v4+24 + v14 = add v12, v13 + ret v14 + """)); +} + + +@test def what_one_way_out_reads_moves_into_that_way(t: &mut tester): void { + # The limit and the step are read only where `go` holds, so they are read + # there, after the count that both ways read. + val got := optimized(1, "advance", """ + struct counter { var count: u64; var limit: u64; var step: u64; } + def advance(c: &counter, go: bool): u64 { + val limit := c.limit; + val step := c.step; + val count := c.count; + if go { return limit + step + count; } + return count; + } + """); + t.expects(lowers_as(&got, """ + b0(v0: i64, v1: i64): + v2 = load.i64 v0 + branch v1, b2, b1 + b1: + ret v2 + b2: + v3 = load.i64 v0+8 + v4 = load.i64 v0+16 + v5 = add v3, v4 + v6 = add v5, v2 + ret v6 + """)); +} + + +@test def small_functions_inline_and_their_cells_become_values(t: &mut tester): void { + # `sum` is inlined, and the point it was given the address of, and the copy + # of its literal, become the values they hold. + val got := optimized(2, "made", """ + struct point { var x: i64; var y: i64; } + def point::sum(&this): i64 { return this.x + this.y; } + def made(a: i64, b: i64): i64 { val p := point { x = a, y = b }; return p.sum(); } + """); + t.expects(lowers_as(&got, """ + b0(v0: i64, v1: i64): + v2 = add v0, v1 + ret v2 + """)); + + # `% 2 == 0` becomes a mask, and `/ 2` a shift; both ways of the `if` are + # worked out and a `select` of the mask chooses between them, and the loop, + # rotated, goes round without making its constants again. + val looped := optimized(2, "steps", """ + def steps(start: u64): u64 { + var n := start; + var count: u64 = 0; + while n != 1 { + if n % 2 == 0 { n = n / 2; } else { n = 3 * n + 1; } + count += 1; + } + return count; + } + """); + t.expects(lowers_as(&looped, """ + b0(v0: i64): + v1 = iconst 3 + v2 = iconst 1 + v3 = iconst 0 + v4 = ne v0, v2 + branch v4, b1(v0, v3), b2(v3) + b1(v5: i64, v6: i64): + v7 = band v5, v2 + v8 = mul v5, v1 + v9 = add v8, v2 + v10 = shru v5, v2 + v11 = select v7, v9, v10 + v12 = add v6, v2 + v13 = ne v11, v2 + branch v13, b1(v11, v12), b2(v12) + b2(v14: i64): + ret v14 + """)); +} + +@test def inline_functions_are_copied_at_every_level(t: &mut tester): void { + val text := """ + struct inline {} + @inline def twice(x: i64): i64 { val y := x * 2; return y; } + def thrice(x: i64): i64 { return x * 3; } + @inline def count(n: i64): i64 { return n == 0 ? 0 : count(n - 1) + 1; } + def f(a: i64): i64 { return thrice(twice(a)) + count(a); } + """; + # At `-O0`, the calls of `twice` and `count` are copied, each parameter and + # local still in a cell of its own, and nothing else changes: `thrice` is + # called, and so is `count` within its copy, as that call closes a loop. The + # copies clear none of their cells, as each is written before it is read, so + # the functions' own frames would zero none of them. + val none := optimized(0, "f", text); + t.expects(lowers_as(&none, """ + c0: 8, 8 + c1: 8, 8 + c2: 8, 8 + c3: 8, 8 + b0(v0: i64): + v1 = cell c0 + store.i64 v1, v0 + v2 = load.i64 v1 + jump b1 + b1: + v3 = cell c1 + store.i64 v3, v2 + v4 = cell c2 + v5 = load.i64 v3 + v6 = iconst 2 + v7 = mul v5, v6 + store.i64 v4, v7 + v8 = load.i64 v4 + jump b2 + b2: + v9 = call f2(v8) + v10 = load.i64 v1 + jump b3 + b3: + v11 = cell c3 + store.i64 v11, v10 + v12 = load.i64 v11 + v13 = iconst 0 + v14 = eq v12, v13 + branch v14, b5, b4 + b4: + v15 = load.i64 v11 + v16 = iconst 1 + v17 = sub v15, v16 + v18 = call f3(v17) + v19 = iconst 1 + v20 = add v18, v19 + jump b6(v20) + b5: + v21 = iconst 0 + jump b6(v21) + b6(v22: i64): + jump b7 + b7: + v23 = add v9, v22 + ret v23 + """)); + + # At `-O1`, the copies are folded into what calls them as any code is. + val local := optimized(1, "f", text); + t.expects(lowers_as(&local, """ + b0(v0: i64): + v1 = iconst 1 + v2 = shl v0, v1 + v3 = call f2(v2) + v4 = iconst 0 + branch v0, b1, b2(v4) + b1: + v5 = sub v0, v1 + v6 = call f3(v5) + v7 = add v6, v1 + jump b2(v7) + b2(v8: i64): + v9 = add v3, v8 + ret v9 + """)); + + # At `-O2`, one of any size is copied, past `--inline N`, though it is called + # more than once. + val large := optimized(2, "g", """ + struct inline {} + @inline def mix(x: u64): u64 { + var h := x; + h = (h ^ (h >> 33)) * 0xFF51AFD7ED558CCD; + h = (h ^ (h >> 33)) * 0xC4CEB9FE1A85EC53; + h = (h ^ (h >> 29)) * 0xFF51AFD7ED558CCD; + h = (h ^ (h >> 31)) * 0xC4CEB9FE1A85EC53; + h = (h ^ (h >> 30)) * 0xFF51AFD7ED558CCD; + h = (h ^ (h >> 27)) * 0xC4CEB9FE1A85EC53; + return h ^ (h >> 31); + } + def g(a: u64, b: u64): u64 { return mix(a) + mix(b); } + """); + t.expects(large.view().find("mul") is some && large.view().find("call") is none); +} + +@test def worklists_take_each_index_once_and_scopes_take_back_what_they_set(t: &mut tester): void { + var work := worklist::new(8, nothing {}); + t.expects(work.push_new(3) && work.push_new(5) && !work.push_new(3)); + t.expects(work.pop() == 5 && work.pop() == 3 && work.is_empty); + t.expects(work.has(3) && !work.has(4) && !work.push_new(5)); + + # A stamped set empties as each round begins. + var counted := stamped_set::new(8, nothing {}); + t.expects(counted.insert(2) && !counted.insert(2) && counted.contains(2)); + counted.next_round(); + t.expects(!counted.contains(2) && counted.insert(2)); + + # Rewinding puts back what each key held at the mark, or takes it out. + val one: u32 = 1; + val two: u32 = 2; + var scoped := scoped_dict::::new(nothing {}); + scoped.set(1, 10); + val mark := scoped.mark(); + scoped.set(1, 11); + scoped.set(2, 20); + t.expects(scoped.get_or(&one, 0) == 11 && scoped.contains(&two)); + scoped.rewind(mark); + t.expects(scoped.get_or(&one, 0) == 10 && !scoped.contains(&two)); + scoped.rewind(0); + t.expects(!scoped.contains(&one) && scoped.mark() == 0); +} diff --git a/tests/compiler/workers.sakura b/tests/compiler/workers.sakura new file mode 100644 index 00000000..131003b4 --- /dev/null +++ b/tests/compiler/workers.sakura @@ -0,0 +1,137 @@ +#! @file workers.sakura +#! @author John Christman (sorakatadzuma@gmail.com) +#! @copyright Malunal Studios, LLC. +#! @license MIT +#! +#! Contains the tests of sharing the compiler's work out among threads: each +#! index done once, each after those it waits for, each thread with scratch +#! memory of its own, and functions optimized on threads made into what one +#! thread makes them. + +import std::containers; +import std::testing; +import sakura::analyzer; +module sakura::compiler; + + +@test def work_shared_out_is_done_once_for_each_index(t: &mut tester): void { + val count: u64 = 2000; + for threads in 1..6u { + var done := vector::>::new(); + for _ in 0..count { + done.append(atomic::::new(0)); + } + share_out(count, threads as u32, def(index: u64): void { _ = done[index].fetch_add(1); }); + var once := true; + for i in 0..count { + once = once && done[i].load() == 1; + } + t.expects(once); + } +} + +@test def work_shared_out_in_order_waits_for_what_it_waits_for(t: &mut tester): void { + # Each index but the first waits for the one halfway to it, as in a heap, + # and is stamped as it is done, after the one it waits for. + val count: u64 = 1023; + var waiting := groups::::new(count); + for child in 1..count { + waiting.count((child - 1) / 2); + } + waiting.seal(); + for child in 1..count { + waiting.put((child - 1) / 2, child as u32); + } + for threads in 1..6u { + var stamps := vector::>::new(); + for _ in 0..count { + stamps.append(atomic::::new(0)); + } + var clock := atomic::::new(0); + share_out_ordered(count, threads as u32, &waiting, def(index: u64): void { + stamps[index].store(clock.fetch_add(1) + 1); + }); + var ordered := true; + for i in 1..count { + ordered = ordered && stamps[i].load() != 0 && stamps[(i - 1) / 2].load() < stamps[i].load(); + } + t.expects(ordered && stamps[0].load() != 0); + } +} + +@test def each_thread_takes_scratch_memory_of_its_own(t: &mut tester): void { + # Each index fills scratch memory it marked, then reads it back; another + # thread marking, taking, or rewinding the same memory meanwhile would change + # what it reads. + var wrong := atomic::::new(0); + share_out(256, 5, def(index: u64): void { + val point := mark_scratch(); + var filled := vector::::new(scratch()); + for k in 0..4000u { + filled.append(index * 4000 + k); + } + var also := vector::::new(scratch()); + also.resize(512); + for k in 0..4000u { + if filled[k] != index * 4000 + k { + _ = wrong.fetch_add(1); + } + } + also.close(); + filled.close(); + release_scratch(point); + }); + t.expects(wrong.load() == 0); +} + +@test def functions_optimized_on_threads_are_made_what_one_thread_makes_them(t: &mut tester): void { + # Functions calling each other, in a cycle and through several levels, which + # inlining copies into one another, so one optimized before or after what it + # inlines would come out otherwise. + val text := """ + def leaf(x: i64): i64 { return x * 2 + 1; } + def twice(x: i64): i64 { return leaf(x) + leaf(x + 1); } + def even(n: i64): bool { return n == 0 ? true : odd(n - 1); } + def odd(n: i64): bool { return n == 0 ? false : even(n - 1); } + def sum(n: i64): i64 { + var total: i64 = 0; + for i in 0..n { total += twice(i); } + return total; + } + def pick(n: i64): i64 { return even(n) ? sum(n) : twice(n); } + def main(): void { if pick(10) == 0 { return; } } + """; + val names := "leaf twice even odd sum pick main"; + for level in 1..3u { + val one := optimized_on(1, level as u32, names, text); + t.expects(one.length > 200 && !one.view().starts_with("the program")); + for threads in 2..6u { + val many := optimized_on(threads as u32, level as u32, names, text); + t.expects(one.view() == many.view()); + } + } + + # The same, where some are `@inline`, and so copied at `-O0` too. + val marked := """ + struct inline {} + @inline def leaf(x: i64): i64 { return x * 2 + 1; } + @inline def twice(x: i64): i64 { return leaf(x) + leaf(x + 1); } + @inline def even(n: i64): bool { return n == 0 ? true : odd(n - 1); } + def odd(n: i64): bool { return n == 0 ? false : even(n - 1); } + def sum(n: i64): i64 { + var total: i64 = 0; + for i in 0..n { total += twice(i); } + return total; + } + def pick(n: i64): i64 { return even(n) ? sum(n) : twice(n); } + def main(): void { if pick(10) == 0 { return; } } + """; + for level in 0..3u { + val one := optimized_on(1, level as u32, names, marked); + t.expects(one.length > 200 && !one.view().starts_with("the program")); + for threads in 2..6u { + val many := optimized_on(threads as u32, level as u32, names, marked); + t.expects(one.view() == many.view()); + } + } +} diff --git a/tests/core/allocators.sakura b/tests/core/allocators.sakura new file mode 100644 index 00000000..c0075506 --- /dev/null +++ b/tests/core/allocators.sakura @@ -0,0 +1,16 @@ +# Tests of the memory `core` gives: a block of the heap keeps what it holds +# through resizing. The allocators of std, an arena and a pool, are tested +# there. +import std::testing; + + +@test def uncleared_memory_keeps_what_it_holds_through_resizing(t: &mut tester): void { + val block := raw_allocate(64) as *mut u64; + for i in 0..8u { block[i] = i * 11; } + val grown := raw_resize(block as *mut u8, 8192) as *mut u64; + var same := true; + for i in 0..8u { same = same && grown[i] == i * 11; } + val shrunk := raw_resize(grown as *mut u8, 16) as *mut u64; + t.expects(same && shrunk[1] == 11); + raw_release(shrunk as *mut u8); +} diff --git a/tests/core/atomics.sakura b/tests/core/atomics.sakura new file mode 100644 index 00000000..3685263e --- /dev/null +++ b/tests/core/atomics.sakura @@ -0,0 +1,195 @@ +# Tests of atomics: each operation at each width, of integers, `bool`, enums, +# and pointers, the orders that make no sense stopping the program, and two +# processes adding to memory they share, which loses nothing only where every +# addition is one step. + +import system; +import std::testing; + + +# Whether running the function stops the program. It runs in a copy of the +# program that writes nothing, so that this one goes on and the report of the +# stop is not mixed into the tests'. +def stops_atomically(run: def(): void): bool { + when os == windows { + val stopped := copied(run); + return !(stopped.exited && stopped.code == 0); + } + val child := fork(); + if child == 0 { + val out: fd = fd::stdout; + val err: fd = fd::stderr; + out.close(); + err.close(); + run(); + exit(0); + } + var status: process_status; + return wait(child, &mut status) >= 0 && !(status.exited && status.code == 0); +} + +# Works every operation on an atomic of `T`, given a value below another, compared +# as `T` is, where of an unsigned type the higher has its top bit set, so that +# comparing it as signed would order them the other way, and the least and +# greatest of `T`. +def operations_of(t: &mut tester, low: T, high: T, least: T, most: T): void where T: integer, lockfree { + var a := atomic::::new(low); + t.expects(a.load() == low); + a.store(high); + t.expects(a.load() == high); + t.expects(a.exchange(low) == high && a.load() == low); + + # Adding and subtracting wrap. + a.store(most); + t.expects(a.fetch_add(1) == most && a.load() == least); + t.expects(a.fetch_sub(1) == least && a.load() == most); + a.store(low); + t.expects(a.fetch_add(high) == low); + val sum := a.load(); + t.expects(a.fetch_sub(high) == sum && a.load() == low); + + # Bits, against the operators. + a.store(high); + t.expects(a.fetch_and(low) == high && a.load() == (high & low)); + a.store(high); + t.expects(a.fetch_or(low) == high && a.load() == (high | low)); + a.store(high); + t.expects(a.fetch_xor(low) == high && a.load() == (high ^ low)); + + # The least and greatest, compared as `T` is. + a.store(low); + t.expects(a.fetch_min(high) == low && a.load() == low); + t.expects(a.fetch_max(high) == low && a.load() == high); + t.expects(a.fetch_max(low) == high && a.load() == high); + t.expects(a.fetch_min(low) == high && a.load() == low); + + # A compare-exchange writes where it finds what it expects, and otherwise gives + # what it found. + match a.compare_exchange(low, high) { + value(found) => t.expects(found == low && a.load() == high); + error(_) => t.expects(false); + } + match a.compare_exchange(low, most, order::acq_rel, order::acquire) { + value(_) => t.expects(false); + error(found) => t.expects(found == high && a.load() == high); + } + match a.compare_exchange_weak(high, least, order::release, order::relaxed) { + value(found) => t.expects(found == high && a.load() == least); + error(_) => t.expects(false); + } +} + +@test def every_operation_works_at_every_width(t: &mut tester): void { + operations_of::(t, 100, 200, 0, 255); + operations_of::(t, -56, 100, -128, 127); + operations_of::(t, 0x1234, 0xF00D, 0, 0xFFFF); + operations_of::(t, -4000, 0x1234, -32768, 32767); + operations_of::(t, 7, 0x80000001, 0, 0xFFFFFFFF); + operations_of::(t, -2000000000, 2000000000, -2147483648, 2147483647); + operations_of::(t, 3, 0x8000000000000003, 0, 0xFFFFFFFFFFFFFFFF); + operations_of::(t, -0x7000000000000000, 0x7000000000000000, -0x7FFFFFFFFFFFFFFF - 1, 0x7FFFFFFFFFFFFFFF); +} + +@test def every_order_is_taken_where_it_makes_sense(t: &mut tester): void { + var a := atomic::::new(1); + for how in [order::relaxed, order::acquire, order::seq_cst] { + t.expects(a.load(how) == 1); + } + for how in [order::relaxed, order::release, order::seq_cst] { + a.store(2, how); + t.expects(a.load() == 2); + } + for how in [order::relaxed, order::acquire, order::release, order::acq_rel, order::seq_cst] { + t.expects(a.fetch_add(1, how) == 2 && a.exchange(2, how) == 3); + fence(how); + } + t.expects(a.compare_exchange(2, 5, order::seq_cst, order::seq_cst) is value); + t.expects(a.compare_exchange(5, 6, order::acq_rel, order::acquire) is value); + t.expects(a.compare_exchange(6, 7, order::release, order::relaxed) is value); + t.expects(a.compare_exchange(0, 8, order::relaxed, order::relaxed) is error); + t.expects(a.load() == 7); +} + +enum light { red, amber, green } + +@test def bools_enums_and_pointers_are_atomic(t: &mut tester): void { + var flag := atomic::::new(false); + t.expects(!flag.exchange(true) && flag.load()); + t.expects(flag.compare_exchange(true, false) is value && !flag.load()); + t.expects(flag.compare_exchange(true, true) is error); + + var lamp := atomic::::new(light::red); + lamp.store(light::green); + t.expects(lamp.exchange(light::amber) == light::green); + match lamp.compare_exchange(light::red, light::green) { + value(_) => t.expects(false); + error(found) => t.expects(found == light::amber); + } + + val block := raw_allocate(16); + var at := atomic::<*mut u8>::new(null); + t.expects(at.exchange(block) == null && at.load() == block); + t.expects(at.compare_exchange(block, block + 8) is value && at.load() == block + 8); + raw_release(block); +} + +@test def orders_that_make_no_sense_stop_the_program(t: &mut tester): void { + t.expects(stops_atomically(def() { var a := atomic::::new(0); _ = a.load(order::release); })); + t.expects(stops_atomically(def() { var a := atomic::::new(0); _ = a.load(order::acq_rel); })); + t.expects(stops_atomically(def() { var a := atomic::::new(0); a.store(1, order::acquire); })); + t.expects(stops_atomically(def() { var a := atomic::::new(0); a.store(1, order::acq_rel); })); + t.expects(stops_atomically(def() { var a := atomic::::new(0); _ = a.compare_exchange(0, 1, order::seq_cst, order::release); })); + t.expects(stops_atomically(def() { var a := atomic::::new(0); _ = a.compare_exchange(0, 1, order::seq_cst, order::acq_rel); })); + # A failure no stronger than what the success reads. + t.expects(stops_atomically(def() { var a := atomic::::new(0); _ = a.compare_exchange(0, 1, order::relaxed, order::acquire); })); + t.expects(stops_atomically(def() { var a := atomic::::new(0); _ = a.compare_exchange(0, 1, order::release, order::acquire); })); + t.expects(stops_atomically(def() { var a := atomic::::new(0); _ = a.compare_exchange(0, 1, order::acq_rel, order::seq_cst); })); + t.expects(!stops_atomically(def() { var a := atomic::::new(0); _ = a.compare_exchange(0, 1, order::acq_rel, order::acquire); })); + t.expects(!stops_atomically(def() { var a := atomic::::new(0); _ = a.load(order::acquire); a.store(1, order::release); })); +} + +# How many times each process adds. +const contended: u64 = 1000000; + +# Sharing a page between processes takes `fork` and `mmap`, which Linux has. +when os == linux { + @test def two_processes_adding_to_memory_they_share_lose_nothing(t: &mut tester): void { + # A page both processes keep after `fork`, rather than a copy each. + val page := system::linux::syscall(9, 0, 4096, 3, 0x21, 0xFFFFFFFFFFFFFFFF, 0); + t.expects(page > 0); + return if page <= 0; + val sum := page as u64 as *mut atomic; + val tries := (page as u64 + 8) as *mut atomic; + val bits := (page as u64 + 16) as *mut atomic; + val most := (page as u64 + 24) as *mut atomic; + + val child := fork(); + val own: u64 = child == 0 ? 1 : 2; + for i in 0..contended { + _ = sum[0].fetch_add(1); + # A loop of compare-exchanges adds as well, trying again where the other + # process wrote first. + var seen := tries[0].load(order::relaxed); + while true { + match tries[0].compare_exchange_weak(seen, seen + 1, order::acq_rel, order::relaxed) { + value(_) => break; + error(found) => seen = found; + } + } + _ = most[0].fetch_max((i * 2 + own) as i32); + if i % 1000 == 0 { + _ = bits[0].fetch_or((1 << (own * 4 + i / 1000 % 4)) as u16); + } + } + if child == 0 { + exit(0); + } + var status: process_status; + t.expects(wait(child, &mut status) >= 0 && status.exited && status.code == 0); + t.expects(sum[0].load() == 2 * contended); + t.expects(tries[0].load() == 2 * contended as u32); + t.expects(bits[0].load() == 0xFF0); + t.expects(most[0].load() == ((contended - 1) * 2 + 2) as i32); + _ = system::linux::syscall(11, page as u64, 4096, 0, 0, 0, 0); + } +} diff --git a/tests/core/containers.sakura b/tests/core/containers.sakura new file mode 100644 index 00000000..4bdabf2c --- /dev/null +++ b/tests/core/containers.sakura @@ -0,0 +1,111 @@ +# Tests of the containers: what they check of what they are asked for, what they +# close of their elements, and what they do where an allocator gives no memory, +# with the helpers of std they lean on. +import system; +import std::testing; +import std::containers; + + +# How many counters have been closed, which only those holding a count are. +var closed: u64 = 0; + +struct counter : owning, hashable, ordered { + var n: u64; +} + +def counter::close(&mut this): void { + if this.n != 0 { + closed++; + this.n = 0; + } +} + +def counter::hash(&this): u64 { return this.n; } + +def counter::equals(&this, other: &counter): bool { return this.n == other.n; } + +def counter::compare(&this, other: &counter): i64 { return this.n as i64 - other.n as i64; } + +@test def vectors_grow_by_elements_left_undefined(t: &mut tester): void { + var v := vector::::new(); + v.append(1); + v.extend_undefined(1000); + t.expects(v.length == 1001 && v[0] == 1); + for i in 1..v.length { + v[i] = i; + } + t.expects(v[1000] == 1000); + + var zeroed := vector::::new(); + zeroed.resize(5000); + var sum: u64 = 0; + for &each in zeroed { + sum += each; + } + t.expects(zeroed.length == 5000 && sum == 0); +} + +# A set closes a value where it lets it go: one it is given and already holds, one +# removed, and one another set leaves or takes out, while what it copies in is its +# own, so the set copied from closes only its own. +# A vector reads its ends, removes its last, grows by copies, and sorts, closing +# only what it removes, and moving what it sorts without closing or copying it. +@test def vectors_read_their_ends_and_sort_what_they_hold(t: &mut tester): void { + closed = 0; + var v := vector::::new(); + for n in 1..4 { v.append(counter { n = n as u64 }); } + t.expects(v.first().n == 1 && v.last().n == 3); + v.last().n = 9; + v.truncate(); + t.expects(closed == 1 && v.length == 2 && v.last().n == 2); + + # Many are sorted by merging runs, and those an order leaves equal keep theirs. + closed = 0; + var many := vector::::new(); + for i in 0..40 { many.append(counter { n = ((i * 17) % 41 + 1) as u64 }); } + many.sort(); + var sorted := true; + for i in 1..many.length { sorted = sorted && many[i - 1].n < many[i].n; } + t.expects(sorted && closed == 0); + many.sort_by(def(a: &counter, b: &counter): bool { return a.n % 2 < b.n % 2; }); + t.expects(many[0].n == 2 && many[1].n == 4 && many[20].n == 1 && closed == 0); + many.clear(); + t.expects(closed == 40); + + var texts := vector::::new(); + val more: string[2] = [string::from("b", nothing {}), string::from("a", nothing {})]; + texts.extend(more[:]); + texts.resize(4, string::from("z", nothing {})); + texts.sort(); + t.expects(texts.length == 4 && texts[0].view() == "a" && texts[3].view() == "z" && more[0].view() == "b"); + + var numbers := vector::::new(); + numbers.resize(3, 0xFFFFFFFF); + numbers.extend([4, 2]); + numbers.sort(); + val view := numbers.view(); + t.expects(numbers.first() == 2 && view.lower_bound(&4) == 1 && view.upper_bound(&4) == 2 && view.lower_bound(&5) == 2); + t.expects(view.partition_point(def(x: &u32): bool { return x < 0xFFFFFFFF; }) == 2); + + var d := dict::::new(); + d.set(1, string::from("one", nothing {})); + t.expects(d.get_or(&1, string::new(nothing {})).view() == "one" && d.get_or(&2, string::from("none", nothing {})).view() == "none"); +} + +@test def bytes_compare_flags_change_and_digits_read_in_any_base(t: &mut tester): void { + val a: strview = "abc"; + val b: strview = "abd"; + t.expects(memcmp(a.data, b.data, 3) < 0 && memcmp(b.data, a.data, 3) > 0 && memcmp(a.data, a.data, 3) == 0); + + var f: flags32 = 0; + f.set(3, true); + t.expects(f.get(3 as u8) && !f.get(4 as u8)); + f.set(3, false); + t.expects(!f.get(3 as u8) && f == 0); + t.expects(f.with(5, true).get(5 as u8) && !f.get(5 as u8)); + f.set(target::fields); + t.expects(f.get(target::fields) && !f.with(4, false).get(target::fields)); + + t.expects(('2' as u8).is_base_digit(3) && !('3' as u8).is_base_digit(3) && !('9' as u8).is_base_digit(3)); + t.expects(('z' as u8).is_base_digit(36) && ('F' as u8).is_base_digit(16) && !('g' as u8).is_base_digit(16)); +} diff --git a/tests/core/function.sakura b/tests/core/function.sakura new file mode 100644 index 00000000..78890952 --- /dev/null +++ b/tests/core/function.sakura @@ -0,0 +1,235 @@ +# Tests of `function`, which holds one callable of a signature, whatever its type, +# and owns it: each kind of callable it holds, in its buffer or a box, signatures of +# every shape, closing what it holds exactly once, holding nothing, lending what it +# holds by its type, and being handed to another thread. + +import std::testing; +import std::thread; + + +# How many callables the tests gave functions have been closed, from any thread. +var callables_closed: atomic; + +# A functor of two words counting its calls, closed once where it holds a mark. +struct call_counter : invokable, owning { + var mark: u64; + var calls: u64; +} + +def call_counter::invoke(&mut this, x: i64): i64 { + this.calls++; + return x + this.calls as i64; +} + +def call_counter::close(&mut this): void { + if this.mark != 0 { + _ = callables_closed.fetch_add(1); + this.mark = 0; + } +} + +# Functors of 8, 24 and 25 bytes, the last too large for a function's buffer. +struct one_word : invokable { var word: u64; } +def one_word::invoke(&mut this): u64 { return this.word; } + +struct three_words : invokable { var bytes: u8[24]; } +def three_words::invoke(&mut this): u64 { return this.bytes[0] as u64 + this.bytes[23] as u64; } + +struct past_three_words : invokable { var bytes: u8[25]; } +def past_three_words::invoke(&mut this): u64 { return this.bytes[0] as u64 + this.bytes[24] as u64; } + +# A functor in a box, closed once where it holds a mark, as a large one held is. +struct large_counter : invokable, owning { + var mark: u64; + var calls: u64; + var pad: u64[4]; +} + +def large_counter::invoke(&mut this): u64 { + this.calls++; + return this.calls; +} + +def large_counter::close(&mut this): void { + if this.mark != 0 { + _ = callables_closed.fetch_add(1); + this.mark = 0; + } +} + +struct held_point { var x: f64; var y: f64; } +def held_point::sum(&this): f64 { return this.x + this.y; } +def held_point::origin(): held_point { return held_point {}; } + +def twice_given(x: i64): i64 { return x * 2; } +def added_up(xs: i64...): i64 { var total: i64 = 0; for x in xs { total += x; } return total; } +def nothing_given(): u64 { return 7; } +def four_given(a: u8, b: u16, c: u32, d: u64): u64 { return a as u64 + b as u64 + c as u64 + d; } +def larger_of(a: &i64, b: &i64): &i64 { + val x: i64 = a; + val y: i64 = b; + return x > y ? a : b; +} + +# A lambda using no locals, which may outlive the function making it. +def lambda_using_none(): function { + return function::new(def(x: i64): i64 => x - 1); +} + +@test def functions_are_four_words_holding_any_callable(t: &mut tester): void { + t.expects(size_of::>() == 32 && size_of::>() == 32); + + val named: function = function::new(twice_given); + t.expects(named(21) == 42); + + # A method taken through its type takes its receiver first. + val method: function = function::new(held_point::sum); + val p := held_point { x = 1.5, y = 2.0 }; + t.expects(method(&p) == 3.5); + val made: function = function::new(held_point::origin); + t.expects(made().x == 0.0); + + # A lambda refers to the locals it uses, which change under it. + var by := 10; + val lambda: function = function::new(def(x: i64): i64 => x + by); + t.expects(lambda(1) == 11); + by = 20; + t.expects(lambda(1) == 21); + + val kept := lambda_using_none(); + t.expects(kept(5) == 4); +} + +@test def functions_hold_small_functors_in_place_and_large_ones_in_a_box(t: &mut tester): void { + var bytes: u8[25]; + bytes[0] = 1; + bytes[23] = 2; + bytes[24] = 3; + val one: function = function::new(one_word { word = 9 }); + var three: three_words; + three.bytes[0] = 1; + three.bytes[23] = 2; + val in_place: function = function::new(three); + val boxed: function = function::new(past_three_words { bytes = bytes }); + t.expects(one() == 9 && in_place() == 3 && boxed() == 4); + + # What a functor changes as it is called stays changed, in place or boxed. + val counting: function = function::new(call_counter {}); + t.expects(counting(10) == 11 && counting(10) == 12); + val large: function = function::new(large_counter {}); + t.expects(large() == 1 && large() == 2 && large() == 3); +} + +@test def functions_call_a_functor_referred_to_where_it_is(t: &mut tester): void { + var counter := call_counter {}; + { + val referring: function = function::new(&mut counter); + t.expects(referring(0) == 1 && referring(0) == 2); + } + t.expects(counter.calls == 2); +} + +@test def functions_take_signatures_of_every_shape(t: &mut tester): void { + val none: function = function::new(nothing_given); + val four: function = function::new(four_given); + t.expects(none() == 7 && four(1, 2, 3, 4) == 10); + + # References are given and given back. + val larger: function = function::new(larger_of); + val a: i64 = 3; + val b: i64 = 8; + val got: i64 = larger(&a, &b); + t.expects(got == 8); + + # What gives nothing, which a lambda appending to a vector does. + var seen := vector::::new(); + val keep: function = function::new(def(x: i64) { seen.append(x); }); + keep(4); + keep(5); + t.expects(seen.length == 2 && seen[1] == 5); + + # A variadic signature takes any number of arguments, or a view of them. + val sum: function = function::new(added_up); + val more: i64[3] = [4, 5, 6]; + t.expects(sum() == 0 && sum(1, 2, 3) == 6 && sum(...more) == 15); +} + +@test def functions_close_what_they_hold_once(t: &mut tester): void { + val before := callables_closed.load(); + { + val f: function = function::new(call_counter { mark = 1 }); + val g: function = function::new(large_counter { mark = 1 }); + } + t.expects(callables_closed.load() == before + 2); + + # Written over, what it held closes; moved from, it holds nothing to close. + var f: function = function::new(call_counter { mark = 1 }); + f = function::new(call_counter { mark = 2 }); + t.expects(callables_closed.load() == before + 3); + var moved := move(&mut f); + f.close(); + t.expects(callables_closed.load() == before + 3); + moved.close(); + moved.close(); + t.expects(callables_closed.load() == before + 4); + + # A vector of them grows by moving them, and closes each once. + { + var many := vector::>::new(); + for i in 0..40u { + many.append(function::new(large_counter { mark = i + 1 })); + } + t.expects(many[39]() == 1); + } + t.expects(callables_closed.load() == before + 44); +} + +@test def empty_functions_hold_nothing_and_stop_where_called(t: &mut tester): void { + var empty: function; + t.expects(!empty.holds()); + empty = function::new(def() {}); + t.expects(empty.holds()); + val moved := move(&mut empty); + t.expects(!empty.holds() && moved.holds()); + t.expects(stops(def() { var none: function; _ = none(1); })); +} + +@test def functions_lend_what_they_hold_by_its_type(t: &mut tester): void { + val counting: function = function::new(call_counter { calls = 5 }); + _ = counting(0); + if counting.get::() is some(&held) { + t.expects(held.calls == 6); + } else { + t.expects(false); + } + t.expects(!(counting.get::() is some)); + + val large: function = function::new(large_counter {}); + _ = large(); + if large.get::() is some(&held) { + t.expects(held.calls == 1); + } else { + t.expects(false); + } + t.expects(!(large.get::() is some)); + + var empty: function; + t.expects(!(empty.get::() is some)); +} + +# Calls a function given to a thread, which then owns it. +def call_given(f: function): void { + _ = f(); + _ = f(); +} + +@test def functions_are_handed_to_other_threads(t: &mut tester): void { + val before := callables_closed.load(); + var counting: function = function::new(large_counter { mark = 1 }); + var thread := thread::spawn_with(call_given, move(&mut counting)) else { + t.expects(false); + return; + }; + thread.join(); + t.expects(!counting.holds() && callables_closed.load() == before + 1); +} diff --git a/tests/core/generics.sakura b/tests/core/generics.sakura new file mode 100644 index 00000000..8590b9ca --- /dev/null +++ b/tests/core/generics.sakura @@ -0,0 +1,244 @@ +# Tests of generics given constants, and of what calls infer. A constant parameter is +# given a value of its type, worked out while checking, and instances given equal values +# are one instance. Calls infer constants from the lengths of fixed arrays and the +# arguments of other instances, and infer type arguments from bounds, the type expected +# of their result, array literals, functions named as values, and the arguments around +# one that needs another's type first. +import std::testing; +import std::containers; + + +# A buffer of a number of elements its type gives. +struct buffer where T: zeroable { + var items: T[N]; +} + +def buffer::capacity(&this): u64 { return N; } + +def buffer::filled(value: T): buffer { + var made: buffer; + for i in 0..N { made.items[i] = value; } + return made; +} + +const four_of: u64 = 4; + +@test def constants_tell_instances_apart(t: &mut tester): void { + var b: buffer; + val c: buffer = buffer::::filled(7); + b = c; + t.expects(b.capacity() == 4 && b.items.length == 4 && b.items[3] == 7); + t.expects(name_of::>() == "buffer"); + t.expects(name_of::>() == "buffer"); +} + +enum color { red, green, blue } +struct spot { var x: i64; var y: i64 = 7; } +union figure { var circle: f64; var square: f64; } +const origin: spot = spot { x = 1 }; +const table: i64[3] = [10, 20, 30]; + +struct labelled {} +def labelled::name(&this): strview { return NAME; } + +struct painted {} +def painted::color(&this): color { return C; } + +struct placed {} +def placed

::sum(&this): i64 { return P.x + P.y; } + +struct flagged {} +def flagged::on(&this): bool { + if const B { + return true; + } + return false; +} + +struct scaled {} +def scaled::times(&this, x: f64): f64 { return x * F; } + +struct drawn {} +def drawn::size(&this): f64 { + if S is circle(r) { + return r; + } + return 0.0; +} + +def double(x: i64): i64 { return x * 2; } +def triple(x: i64): i64 { return x * 3; } +struct applied {} +def applied::run(&this, x: i64): i64 { return F(x); } + +struct indexed {} +def indexed::second(&this): i64 { return XS[1]; } + +struct aimed {} +def aimed::last(&this): i64 { return R[2]; } + +struct keeper {} +def keeper::get(&this): T { return V; } + +@test def constants_are_values_of_every_kind(t: &mut tester): void { + t.expects(labelled::<"hello"> {}.name() == "hello"); + t.expects(painted:: {}.color() == color::green); + + # A struct is the same constant as another holding the same fields, its defaults + # included, however each is written. + val here: placed = placed:: {}; + t.expects(here.sum() == 8); + + t.expects(flagged:: {}.on() && !flagged::<(1 > 2)> {}.on()); + t.expects(scaled::<1.5> {}.times(2.0) == 3.0); + t.expects(drawn::

{}.size() == 2.5); + t.expects(applied:: {}.run(5) == 10 && applied:: {}.run(5) == 15); + t.expects(indexed:: {}.second() == 20 && indexed::<[4, 5, 6]> {}.second() == 5); + t.expects(aimed::<&table> {}.last() == 30); + t.expects(keeper:: {}.get() == 200 && keeper:: {}.get() == "x"); +} + +def summed(xs: &i64[N]): i64 { + var sum: i64 = 0; + for x in xs { sum += x; } + return sum; +} + +def grown(xs: &T[N], last: T): T[N + 1] where T: zeroable { + var out: T[N + 1]; + for i, x in xs { out[i] = x; } + out[N] = last; + return out; +} + +def capacity_of(b: &buffer): u64 where T: zeroable { return N; } + +def widened(b: &buffer): buffer where T: zeroable { + var out: buffer; + for i, x in b.items { + out.items[i] = x; + out.items[i + N] = x; + } + return out; +} + +type grid_of = i64[N][N]; + +@test def constants_are_inferred_from_what_is_given(t: &mut tester): void { + val xs: i64[3] = [1, 2, 3]; + t.expects(summed(&xs) == 6 && summed::<2>(&[5, 6]) == 11); + + val ys := grown(&xs, 4); + t.expects(ys.length == 4 && ys[3] == 4); + + val b := buffer::::filled(9); + val w := widened(&b); + t.expects(capacity_of(&b) == 3 && capacity_of(&w) == 6 && w.items[5] == 9); + + val sq: grid_of<2> = [[1, 2], [3, 4]]; + t.expects(sq[1][0] == 3); +} + +def doubled(): u64 { return N * 2; } +const twelve: u64 = doubled::<6>(); + +def described(): strview { + if const N > 2 { + return "many"; + } + return "few"; +} + +@test def constants_are_known_while_compiling(t: &mut tester): void { + t.expects(twelve == 12); + t.expects(described::<1>() == "few" && described::<5>() == "many"); +} + +# What a container's elements are, as a bound gives it. +def leading(c: &C): maybe where C: iterable { + for x in c { + return x; + } + return nothing {}; +} + +struct wrapped { var value: T; } +def wrapped::new(value: T): wrapped { return wrapped:: { value = value }; } + +def itself(x: T): T { return x; } +def apply(f: def(T): U, x: T): U { return f(x); } + +def sum_of(xs: span): T where T: numeric, zeroable { + var all: T; + for x in xs { all += x; } + return all; +} + +def made_empty(): vector { return vector::::new(); } +def pick(a: T, b: T): T { return b; } +def latter(a: T, b: U): U { return b; } + +@test def calls_infer_what_their_arguments_do_not_give(t: &mut tester): void { + var xs := vector::::new(); + xs.append(4); + t.expects(leading(&xs) is some(got) && got == 4); + + # A generic type's own static method infers the type's arguments too. + val b := wrapped::new(5); + val c: wrapped = wrapped::new(5); + var v: vector = vector::new(); + v.append(1); + t.expects(b.value == 5 && c.value == 5 && v.length == 1); + + # A generic function labelled as a value is the instance the type expected gives. + val f: def(i64): i64 = itself; + t.expects(f(4) == 4 && apply(itself, 3) == 3 && apply(double, 3) == 6); + + t.expects(sum_of([1, 2, 3]) == 6 && sum_of([1.5, 2.5]) == 4.0); + + # An argument needing another's type is checked once the other gives it. + var given := vector::::new(); + given.append(1); + val picked := pick(made_empty(), move(given)); + t.expects(picked.length == 1); + + # Type arguments written are the first ones, and the call infers the rest. + t.expects(latter::(1, true)); +} + +# Says only whether a number is even, failing with the number otherwise. +def even_only(n: u64): result { + if n % 2 != 0 { return n; } + return; +} + +@test def void_is_given_to_std_generics_as_any_type(t: &mut tester): void { + # Owners, containers, and results hold `void`, its one value taking no bytes. + val held := box::::new(void {}); + t.expects(held.holds()); + var shared := rc::::new(void {}); + val also := copy(&shared); + t.expects(shared.count() == 2); + var marks := vector::::new(); + for _ in 0..5u { marks.append(void {}); } + t.expects(marks.length == 5 && size_of::() == 0); + + # A `maybe` tells a value missing from the value of `void`. + var seen: maybe = nothing {}; + t.expects(!(seen is some)); + seen = void {}; + t.expects(seen is some); + + # A result of `void` says only whether something failed. + t.expects(even_only(4) is value && even_only(3) is error); + var failed: u64 = 0; + even_only(7) else (n) { failed = n; }; + t.expects(failed == 7); + + # A function giving nothing is held, and called, as one giving any type. + var count := 0; + val f: function = function::new(def() { count++; }); + f(); + f(); + t.expects(count == 2); +} diff --git a/tests/core/iterators.sakura b/tests/core/iterators.sakura new file mode 100644 index 00000000..d50f4b55 --- /dev/null +++ b/tests/core/iterators.sakura @@ -0,0 +1,440 @@ +# Tests of iterating what an iterator gives by value: each element is the loop's own, +# closed where each pass of the body ends, however the pass ends. +import std::containers; +import std::testing; + + +# How many lines holding a number have been closed. +var lines_closed: u64 = 0; + +struct line : owning { + var n: u64; +} + +def line::close(&mut this): void { + if this.n != 0 { + lines_closed++; + this.n = 0; + } +} + +# Gives lines numbered from how many are left down to 1, each a new value. +struct lines : iterator { + var left: u64; +} + +def lines::next(&mut this): maybe { + if this.left == 0 { + return nothing {}; + } + this.left--; + return line { n = this.left + 1 }; +} + +# Gives words numbered down to 0, each a new string, as a reader gives its lines. +struct words : iterator { + var left: u64; +} + +def words::next(&mut this): maybe { + if this.left == 0 { + return nothing {}; + } + this.left--; + return $"word {this.left}"; +} + +# The first line numbered no more than the limit, the rest skipped by `continue`. +def first_within(limit: u64): u64 { + for each in (lines { left = 5 }) { + if each.n > limit { + continue; + } + return each.n; + } + return 0; +} + +@test def iterators_give_elements_the_loop_owns(t: &mut tester): void { + lines_closed = 0; + var total: u64 = 0; + for each in (lines { left = 4 }) { + total += each.n; + } + t.expects(total == 10 && lines_closed == 4); + + # 5, then 4 by `continue`, then 3, then 2 by `break`, and 1 never given. + lines_closed = 0; + for each in (lines { left = 5 }) { + if each.n == 4 { + continue; + } + if each.n == 2 { + break; + } + } + t.expects(lines_closed == 4); + + # 5 and 4 by `continue`, and 3 by `return`. + lines_closed = 0; + t.expects(first_within(3) == 3 && lines_closed == 3); + + lines_closed = 0; + for _ in (lines { left = 3 }) {} + t.expects(lines_closed == 3); + + # An iterator variable is advanced where it is, so a second loop goes on from there. + lines_closed = 0; + var walk := lines { left = 4 }; + for each in walk { + if each.n == 3 { + break; + } + } + var rest: u64 = 0; + for each in walk { + rest += each.n; + } + t.expects(rest == 3 && lines_closed == 4); +} + +@test def iterators_give_strings_the_loop_owns(t: &mut tester): void { + var joined := string::new(nothing {}); + for word in (words { left = 3 }) { + joined.append(word.view()); + joined.append(";"); + } + t.expects(joined.view() == "word 2;word 1;word 0;"); + + var counted := 0u; + for word in (words { left = 100 }) { + counted += word.length; + } + t.expects(counted == 690); +} + +@test def loops_refer_to_what_they_walk(t: &mut tester): void { + # Elements an array holds, or an iterator gives by reference, are referred to by + # `for x`, neither copied nor closed by the loop. + lines_closed = 0; + var kept: line[2]; + kept[0] = line { n = 1 }; + kept[1] = line { n = 2 }; + var sum: u64 = 0; + for &each in kept { + sum += each.n; + } + t.expects(sum == 3 && lines_closed == 0); + + var texts := vector::::new(); + texts.append(string::from("ab", nothing {})); + texts.append(string::from("cde", nothing {})); + var length: u64 = 0; + for &text in texts.view() { + length += text.length; + } + t.expects(length == 5 && texts.length == 2); +} + +# The numbers 1 to 6, which the tests of adapters and consumers walk. +def six(): vector { + var made := vector::::new(); + for i in 1..=6u { + made.append(i); + } + return made; +} + +# The text of what an iterator gives, separated by spaces. +def spaced(it: I): string where I: iterator { + return it.to_string(" "); +} + +@test def adapters_make_iterators_of_iterators(t: &mut tester): void { + val v := six(); + t.expects(spaced(v.iter().map(def(x): u64 => x * 10)).view() == "10 20 30 40 50 60"); + t.expects(spaced(v.iter().filter(def(x) => x % 2 == 0)).view() == "2 4 6"); + t.expects(spaced(v.iter().filter_map(def(x): maybe => x % 3 == 0 ? something::(x / 3) : nothing {})).view() == "1 2"); + t.expects(spaced(v.iter().enumerate().map(def(p): u64 => p.first * 10 + p.second)).view() == "1 12 23 34 45 56"); + t.expects(spaced(v.iter().zip(v.iter().skip(1)).map(def(p): u64 => p.first * p.second)).view() == "2 6 12 20 30"); + t.expects(spaced(v.iter().take(2).chain(v.iter().skip(4))).view() == "1 2 5 6"); + t.expects(spaced(v.iter().take_while(def(x) => x < 4)).view() == "1 2 3"); + t.expects(spaced(v.iter().skip_while(def(x) => x < 4)).view() == "4 5 6"); + t.expects(spaced(v.iter().step(2)).view() == "1 3 5"); + t.expects(spaced(v.iter().rev()).view() == "6 5 4 3 2 1"); + t.expects(spaced(v.iter().take(3).flat_map(def(x) => 0..x)).view() == "0 0 1 0 1 2"); + t.expects(spaced(v.iter().copied().map(def(x: u64): u64 => x + 1)).view() == "2 3 4 5 6 7"); + + var seen: u64 = 0; + t.expects(v.iter().inspect(def(x) { seen += x; }).count() == 6 && seen == 21); + + var looked := v.iter().peekable(); + t.expects(looked.peek() is some(first) && first == 1); + t.expects(spaced(looked).view() == "1 2 3 4 5 6"); +} + +@test def adapters_take_the_edges(t: &mut tester): void { + val v := six(); + val none := vector::::new(); + t.expects(none.iter().map(def(x): u64 => x).count() == 0 && none.iter().rev().count() == 0); + t.expects(v.iter().take(0).count() == 0 && v.iter().skip(9).count() == 0); + t.expects(spaced(v.iter().step(1)).view() == "1 2 3 4 5 6"); + t.expects(v.iter().zip(v.iter().take(2)).count() == 2 && v.iter().take(1).zip(v.iter()).count() == 1); + + # Walking from both ends gives each element once, until the ends meet. + var both := v.iter(); + var taken := string::new(nothing {}); + while true { + val front := both.next(); + if front is some(a) { + taken.append($"{a}<"); + } + val back := both.next_back(); + if back is some(b) { + taken.append($">{b}"); + } + break if both.remaining() == 0; + } + t.expects(taken.view() == "1<>62<>53<>4"); + t.expects(both.next() is not some(_) && both.next_back() is not some(_)); +} + +@test def consumers_walk_to_the_end(t: &mut tester): void { + val v := six(); + t.expects(v.iter().count() == 6 && v.iter().copied().sum() == 21 && v.iter().copied().product() == 720); + t.expects(v.iter().fold(100u, def(a: u64, x: &u64): u64 => a - x) == 79); + t.expects((v.iter().copied().reduce(def(a: u64, b: u64): u64 => a * b) else 0) == 720); + t.expects(v.iter().any(def(x) => x > 5) && !v.iter().any(def(x) => x > 6)); + t.expects(v.iter().all(def(x) => x > 0) && !v.iter().all(def(x) => x > 1)); + t.expects((v.iter().copied().find(def(x) => x > 3) else 0) == 4); + t.expects((v.iter().position(def(x) => x > 3) else 99) == 3 && v.iter().position(def(x) => x > 9) is not some(_)); + t.expects((v.iter().copied().min() else 0) == 1 && (v.iter().copied().max() else 0) == 6); + t.expects((v.iter().copied().min_by(def(a, b) => a > b) else 0) == 6); + t.expects((v.iter().copied().max_by_key(def(x): u64 => (x * 7) % 5) else 0) == 2); + t.expects((v.iter().copied().min_by_key(def(x): u64 => (x * 7) % 5) else 0) == 5); + t.expects((v.iter().copied().last() else 0) == 6 && (v.iter().copied().nth(2) else 0) == 3); + t.expects(v.iter().nth(6) is not some(_)); + + val none := vector::::new(); + t.expects(none.iter().copied().sum() == 0 && none.iter().copied().min() is not some(_)); + t.expects(none.iter().copied().reduce(def(a: u64, b: u64): u64 => a + b) is not some(_)); + + val doubled := v.iter().map(def(x): u64 => x * 2).to_vector(); + t.expects(doubled.length == 6 && doubled[5] == 12); + + var into := vector::::new(); + into.append(0); + v.iter().copied().into(&mut into); + t.expects(into.length == 7 && into[6] == 6); + + var walked: u64 = 0; + v.iter().for_each(def(x) { walked += x; }); + t.expects(walked == 21); +} + +# How many `ticket`s holding a number have been closed. +var tickets_closed: u64 = 0; + +struct ticket : owning { + var n: u64; +} + +def ticket::close(&mut this): void { + if this.n != 0 { + tickets_closed++; + this.n = 0; + } +} + +# Gives tickets numbered from how many are left down to 1, each a new value, and +# counts how many times it is closed itself, which one moved from is not. +var ticket_sources_closed: u64 = 0; + +struct tickets : owning, iterator { + var left: u64; + var live: bool; +} + +def tickets::next(&mut this): maybe { + return nothing {} if this.left == 0; + this.left--; + return ticket { n = this.left + 1 }; +} + +def tickets::close(&mut this): void { + if this.live { + ticket_sources_closed++; + this.live = false; + } +} + +@test def adapters_close_what_they_own_once(t: &mut tester): void { + tickets_closed = 0; + ticket_sources_closed = 0; + val total := (tickets { left = 4, live = true }).map(def(x: ticket): u64 => x.n).sum(); + t.expects(total == 10 && tickets_closed == 4 && ticket_sources_closed == 1); + + tickets_closed = 0; + ticket_sources_closed = 0; + val kept := (tickets { left = 5, live = true }).filter(def(x) => x.n % 2 == 1).take(2).to_vector(); + t.expects(kept.length == 2 && kept[0].n == 5 && kept[1].n == 3); + t.expects(tickets_closed == 1 && ticket_sources_closed == 1); + + tickets_closed = 0; + ticket_sources_closed = 0; + var found := (tickets { left = 3, live = true }).enumerate().find(def(p) => p.second.n == 2); + t.expects(found is some(&p) && p.first == 1); + t.expects(tickets_closed == 1 && ticket_sources_closed == 1); +} + +type view_cursor = span::cursor; +type view_filter = filtered<&u64, span::cursor, def(& &u64): bool>; +type list_map = mapped<&u64, u64, list::cursor, def(&u64): u64>; + +# Whether a view's cursor knows how many it has left, which it does. +def view_is_sized(): bool { if const view_cursor is sized_iterator<&u64> { return true; } return false; } + +# Whether filtering it knows, which it does not. +def filter_is_sized(): bool { if const view_filter is sized_iterator<&u64> { return true; } return false; } + +# Whether mapping a list's cursor walks backward, which it does not. +def list_map_is_backward(): bool { if const list_map is backward_iterator { return true; } return false; } + +@test def adapters_stay_sized_and_backward_as_what_they_adapt(t: &mut tester): void { + var v := six(); + val view := v.view(); + t.expects(view.iter().map(def(x): u64 => x).remaining() == 6); + t.expects(view.iter().zip(view.iter().skip(2)).remaining() == 4); + t.expects(view.iter().enumerate().rev().next() is some(p) && p.first == 5 && p.second == 6); + t.expects(view.iter().step(4).remaining() == 2 && view.iter().take(10).remaining() == 6); + t.expects(view.iter().chain(view.iter()).remaining() == 12); + t.expects(view.iter().filter(def(x) => x > 2).rev().next() is some(last) && last == 6); + t.expects(view_is_sized() && !filter_is_sized() && !list_map_is_backward()); +} + +# An enum with values no member has between its members', and one value two +# members share. +enum shade: i8 { deep = -3, dim, bright = 2, glare, plain = -2 } + +@test def ranges_are_values(t: &mut tester): void { + t.expects(spaced(0..5).view() == "0 1 2 3 4" && spaced(0..=5).view() == "0 1 2 3 4 5"); + t.expects(spaced((0..=5).rev()).view() == "5 4 3 2 1 0" && spaced((0..20).step(5)).view() == "0 5 10 15"); + t.expects((1..=100).sum() == 5050 && (3..10).length == 7 && (3..=10).length == 8); + t.expects((5..2).count() == 0 && (5..=5).count() == 1 && (5..=4).count() == 0); + + val r: range = 250..=255; + t.expects(r.length == 6 && r.contains(255) && !r.contains(249)); + val first: u8 = 250; + val last: u8 = 255; + var top := first..=last; + var counted: u64 = 0; + while top.next() is some(x) { + counted++; + } + t.expects(counted == 6); + val low: i8 = -128; + val high: i8 = 127; + t.expects((low..=high).count() == 256 && (-3..3).sum() == -3); + t.expects((0xFFFFFFFFFFFFFFFDu..=0xFFFFFFFFFFFFFFFFu).count() == 3); + + var walk := 0..10u; + t.expects(walk.nth(3) is some(x) && x == 3 && walk.next() is some(y) && y == 4); + t.expects(walk.nth(9) is not some(_) && walk.is_empty()); + + var sum: u64 = 0; + for i in 0..=4u { + sum += i; + } + for i in last..=last { + sum += i as u64; + } + t.expects(sum == 265); +} + +@test def ranges_count_through_the_members_of_enums(t: &mut tester): void { + # Each value once, in order, passing over those no member has. + t.expects(spaced(shade::deep..=shade::glare).view() == "deep dim bright glare"); + t.expects(spaced((shade::deep..shade::glare).rev()).view() == "bright dim deep"); + t.expects(spaced((shade::deep..=shade::glare).step(2)).view() == "deep bright"); + val shades := shade::dim..=shade::glare; + t.expects(shades.length == 3 && shades.contains(shade::bright) && !shades.contains(shade::deep)); + t.expects((shade::glare..shade::deep).count() == 0 && (shade::plain..=shade::dim).count() == 1); + + var along := shade::deep..=shade::glare; + t.expects(along.nth(2) is some(s) && s == shade::bright && along.remaining() == 1); + t.expects(along.next_back() is some(last) && last == shade::glare && along.is_empty()); + + var walked := 0; + for s in shade::deep..shade::glare { + walked = walked * 10 + (s as i64 + 4); + } + t.expects(walked == 126); +} + +@test def text_is_walked_lazily(t: &mut tester): void { + val text: strview = "a,,b,c"; + t.expects(text.split(',').to_string("|").view() == "a||b|c" && text.split(',').rev().to_string("|").view() == "c|b||a"); + t.expects("".split(',').count() == 1 && ",".split(',').count() == 2); + val parts := text.split(',').to_vector(); + t.expects(parts.length == 4 && parts[3] == "c"); + + val doc: strview = "one\r\ntwo\n\nthree\n"; + t.expects(doc.lines().to_string("|").view() == "one|two||three"); + t.expects("".lines().count() == 0 && "x".lines().count() == 1 && "\n".lines().count() == 1); + t.expects(" hello wide\tworld \n".words().to_string("|").view() == "hello|wide|world" && " \t".words().count() == 0); + + val utf: strview = "aé€😀"; + t.expects(utf.chars().map(def(c): u64 => c as u64).to_string(" ").view() == "97 233 8364 128512"); + var bad: u8[6] = [0x61, 0xC3, 0x28, 0xFF, 0xE2, 0x82]; + val broken: strview = strview::over(&bad[0] as *u8, 6); + t.expects(broken.chars().map(def(c): u64 => c as u64).to_string(" ").view() == "97 65533 40 65533 65533 65533"); + var overlong: u8[2] = [0xC0, 0x80]; + val long: strview = strview::over(&overlong[0] as *u8, 2); + t.expects(long.chars().count() == 2); +} + +@test def containers_are_made_of_iterators(t: &mut tester): void { + var d := dict::::new(); + d.set(1, 10); + d.set(2, 20); + d.set(3, 30); + t.expects(d.keys().copied().sum() == 6 && d.values().copied().sum() == 60 && d.keys().remaining() == 3); + + val squares := dict::from((0..4u).map(def(i: u64): pair => pair:: { first = i, second = i * i })); + t.expects(squares.length == 4 && squares[3] == 9); + (5..7u).map(def(i: u64): pair => pair:: { first = i, second = i }).into(&mut d); + t.expects(d.length == 5 && d[6] == 6); + + var v := vector::from((0..10u).filter(def(x) => x % 3 != 0)); + t.expects(v.iter().to_string(" ").view() == "1 2 4 5 7 8"); + val taken := v.drain(2..5).to_vector(); + t.expects(taken.iter().to_string(" ").view() == "4 5 7" && v.iter().to_string(" ").view() == "1 2 8"); + + tickets_closed = 0; + var held := vector::::new(); + for i in 1..=5u { + held.append(ticket { n = i }); + } + { + var some_of := held.drain(1..=3); + t.expects(some_of.remaining() == 3); + t.expects(some_of.next_back() is some(x) && x.n == 4); + } + t.expects(tickets_closed == 3 && held.length == 2 && held[1].n == 5); + + var joined := string::new(nothing {}); + "a b c".split(' ').into(&mut joined); + t.expects(joined.view() == "abc"); + + var c := chain::::new(); + c.push_back(1); + c.push_back(2); + c.push_back(3); + val read := &c; + t.expects(read.iter().rev().copied().to_string(" ").view() == "3 2 1" && read.iter().remaining() == 3); + var l := list::::new(); + l.push_front(5); + l.push_front(6); + val lread := &l; + t.expects(lread.iter().copied().sum() == 11 && lread.iter().remaining() == 2); +} diff --git a/tests/core/main.sakura b/tests/core/main.sakura new file mode 100644 index 00000000..8914da13 --- /dev/null +++ b/tests/core/main.sakura @@ -0,0 +1,111 @@ +# Runs the tests of `core` and `system`, from the root of the repository, where +# the tests that read files find them, with the standard library's repository +# beside this one. `blossom test` runs them as `sakurac.core`, or: +# +# sakurac run --lib std=../std tests/core/*.sakura +# +# Add `-- --only TEXT` to run those whose name holds the text, and `-- --here` to +# run them in one program, as a debugger wants. Built with `sakura build`, they run +# as an executable the same way. +import std::io; +import std::process; +import system; +import std::testing; + +def main(args: span): void { + exit(tester::run(args)); +} + +# Whether running the function stops the program. It runs in a copy of the program +# that writes nothing, so that this one goes on and the report of the stop is not +# mixed into the tests'. +def stops(run: def(): void): bool { + when os == windows { + val stopped := copied(run); + return !(stopped.exited && stopped.code == 0); + } + val child := fork(); + if child == 0 { + val out: fd = fd::stdout; + val err: fd = fd::stderr; + out.close(); + err.close(); + run(); + exit(0); + } + var status: process_status; + return wait(child, &mut status) >= 0 && !(status.exited && status.code == 0); +} + +# Windows cannot copy a program as it runs, as `system::fork` does, so what the tests +# run in a copy of their own runs there in a copy started again, as `std::testing` +# starts the copy each test runs in. +when os == windows { + # The variable a copy is given, listing how the copies before it stopped. + val copy_variable: strview = "SAKURA_TEST_COPY"; + + # How many functions `copied` has been asked to run, in this program or a copy, + # and how the copies running each stopped, as `exited,code,signal;` each. + var copies_asked: u64 = 0; + var copies_seen: string = string::new(nothing{}); + + # Runs a function in a copy of the program, giving how the copy stopped. The + # copy runs the test that asked again, writing nothing, and is told how each + # copy before it stopped, which it gives where it is asked for them, so it goes + # the way the test went here, though a check that fails asks again. It runs the + # function asked for after them, then exits with zero. + def copied(run: def(): void): system::process_status { + copies_asked++; + if process::variable(copy_variable) is some(given) { + if replayed(given, copies_asked) is some(status) { + return status; + } + run(); + system::exit(0); + } + + var device := path::parse(system::null_device) else (_) { return system::process_status {}; }; + var quiet := io::file::open(&device, open_flags::write) else (_) { return system::process_status {}; }; + val copy := system::respawn($"{copy_variable}={copies_seen.view()}".view(), system::fd::stdin, quiet.handle, quiet.handle); + var status := system::process_status { exited = true, code = -1 }; + if copy > 0 { + _ = system::wait(copy, &mut status); + } + copies_seen.append($"{status.exited ? 1 : 0},{status.code},{status.signal};".view()); + return status; + } + + # How the copy running the function asked for at a count stopped, as a copy's + # variable lists it, or nothing for the one after those it lists. + def replayed(given: strview, count: u64): maybe { + var seen := 0u; + for entry in given.split(';') { + if entry.length == 0 { + continue; + } + seen++; + if seen == count { + val parts := entry.split(',').to_vector(); + return system::process_status { + exited = parts[0] == "1", + code = number_in(parts[1]) as i32, + signal = number_in(parts[2]) as i32 + }; + } + } + return nothing{}; + } + + # The integer text says, or zero where it says none. + def number_in(text: strview): i64 { + if integer::parse::(text) is value(number) { + return number; + } + return 0; + } + + # A directory files may be made in for a while, as the system's `TEMP` names it. + def temporary(): strview { + return process::variable("TEMP") else { return process::variable("TMP") else { return "."; }; }; + } +} diff --git a/tests/core/mem.sakura b/tests/core/mem.sakura new file mode 100644 index 00000000..23663c85 --- /dev/null +++ b/tests/core/mem.sakura @@ -0,0 +1,91 @@ +# Tests of std's memory routines against the same work done a byte at a time: +# every length up to past where they work 16 bytes at a time, buffers that +# overlap either way, and bytes differing at every place. + +import std::testing; + +# Fills a buffer with bytes that differ from place to place. +def scramble(at: *mut u8, count: u64, seed: u64): void { + var state := seed * 0x9E3779B97F4A7C15 + 1; + for i in 0..count { + state = state ^ (state << 13); + state = state ^ (state >> 7); + state = state ^ (state << 17); + at[i] = (state & 0xFF) as u8; + } +} + +# Whether two buffers hold the same bytes. +def same_bytes(a: *u8, b: *u8, count: u64): bool { + for i in 0..count { + return false if a[i] != b[i]; + } + return true; +} + +@test def copies_agree_with_bytes_where_buffers_overlap_or_not(t: &mut tester): void { + val room: u64 = 256; + val made := raw_allocate(room); + val want := raw_allocate(room); + for length in 0..101u { + for from in 0..40u { + for to in 0..40u { + scramble(made, room, length * 131 + from * 7 + to); + scramble(want, room, length * 131 + from * 7 + to); + # The bytes copied, as `memmove` gives them: read whole before any is written. + var held: u8[128]; + for i in 0..length { + held[i] = want[64 + from + i]; + } + for i in 0..length { + want[64 + to + i] = held[i]; + } + memcpy(made + 64 + to, made + 64 + from, length); + t.expects(same_bytes(made, want, room)); + } + } + } + raw_release(made); + raw_release(want); +} + +@test def setting_agrees_with_bytes(t: &mut tester): void { + val room: u64 = 160; + val made := raw_allocate(room); + val want := raw_allocate(room); + for length in 0..101u { + for at in 0..20u { + scramble(made, room, length + at); + scramble(want, room, length + at); + for i in 0..length { + want[at + i] = 0xA5; + } + memset(made + at, 0xA5, length); + t.expects(same_bytes(made, want, room)); + } + } + raw_release(made); + raw_release(want); +} + +@test def comparing_agrees_with_bytes(t: &mut tester): void { + val a := raw_allocate(128); + val b := raw_allocate(128); + for length in 0..101u { + scramble(a, 128, length); + for i in 0..128u { + b[i] = a[i]; + } + t.expects(memcmp(a, b, length) == 0); + for place in 0..length { + for other in [0 as u8, 0x7F, 0x80, 0xFF] { + b[place] = other; + val want: i64 = a[place] == other ? 0 : (a[place] < other ? -1 : 1); + t.expects(memcmp(a, b, length) == want); + } + b[place] = a[place]; + } + } + raw_release(a); + raw_release(b); +} diff --git a/tests/core/operators.sakura b/tests/core/operators.sakura new file mode 100644 index 00000000..c6386aad --- /dev/null +++ b/tests/core/operators.sakura @@ -0,0 +1,188 @@ +# Tests of operators as calls of the methods that give them: each alone, between +# operands of different types, through compound assignment, and in generic code by +# the traits of std and those a program composes of them. +import std::testing; + + +# A length of time, which adds to another, scales by a number, and divides into a ratio. +struct stretch : additive, ordered { + var ns: i64; +} + +def stretch::equals(&this, other: &stretch): bool { return this.ns == other.ns; } +def stretch::compare(&this, other: &stretch): i64 { return this.ns - other.ns; } +def stretch::add(&this, other: &stretch): stretch { return stretch { ns = this.ns + other.ns }; } +def stretch::sub(&this, other: &stretch): stretch { return stretch { ns = this.ns - other.ns }; } +def stretch::negate(&this): stretch { return stretch { ns = -this.ns }; } +def stretch::mul(&this, by: &i64): stretch { return stretch { ns = this.ns * by }; } +def stretch::mul(&this, by: &f64): stretch { return stretch { ns = (this.ns as f64 * by) as i64 }; } +def stretch::div(&this, by: &i64): stretch { return stretch { ns = this.ns / by }; } +def stretch::div(&this, by: &stretch): f64 { return this.ns as f64 / by.ns as f64; } + +# A moment, which moves by a length of time, and is a length of time from another. +struct moment : ordered { + var ns: i64; +} + +def moment::equals(&this, other: &moment): bool { return this.ns == other.ns; } +def moment::compare(&this, other: &moment): i64 { return this.ns - other.ns; } +def moment::add(&this, by: &stretch): moment { return moment { ns = this.ns + by.ns }; } +def moment::sub(&this, by: &stretch): moment { return moment { ns = this.ns - by.ns }; } +def moment::sub(&this, since: &moment): stretch { return stretch { ns = this.ns - since.ns }; } + +# A vector, which a number scales from either side. +struct arrow : additive { + var x: f64; + var y: f64; +} + +def arrow::equals(&this, other: &arrow): bool { return this.x == other.x && this.y == other.y; } +def arrow::add(&this, other: &arrow): arrow { return arrow { x = this.x + other.x, y = this.y + other.y }; } +def arrow::sub(&this, other: &arrow): arrow { return arrow { x = this.x - other.x, y = this.y - other.y }; } +def arrow::negate(&this): arrow { return arrow { x = -this.x, y = -this.y }; } +def arrow::mul(&this, by: &f64): arrow { return arrow { x = this.x * by, y = this.y * by }; } +def arrow::mul(&this, with: &arrow): f64 { return this.x * with.x + this.y * with.y; } +def f64::mul(&this, of: &arrow): arrow { return of * this; } + +# How often a ledger was added to, which only adds. +var ledgers_added: u64 = 0; + +struct ledger { + var sum: i64; +} + +def ledger::add(&this, other: &ledger): ledger { + ledgers_added++; + return ledger { sum = this.sum + other.sum }; +} + +# What holds a ledger behind a property. +struct purse { + var kept: ledger; +} + +var purse::all: ledger { + get => this.kept; + set => this.kept = value; +} + +# What scales by an `S`, beside adding: a trait of a program's own, composing std's. +trait stretches : additive { + def mul(&this, by: &S): self; +} + +def blend(a: V, b: V, t: S): V where V: stretches { + return a + (b - a) * t; +} + +def gathered(items: span, from: T): T where T: addable { + var all := from; + for &each in items { all += each; } + return all; +} + +def mirrored(a: T, b: T): T where T: additive { + return a == b ? a : -(a - b); +} + +def product_of(a: T, b: T): T where T: multiplicative { + return a * b; +} + +def shared_out(whole: T, by: T): T where T: divisible, modular, addable { + return whole / by + whole % by; +} + +def second(count: i64): stretch { return stretch { ns = count * 1000000000 }; } + +const long_pause: stretch = second(1) + second(2) * 3 - -second(1); + +@test def an_operator_is_a_call_of_its_method(t: &mut tester): void { + val a := stretch { ns = 250 }; + val b := stretch { ns = 100 }; + t.expects((a + b).ns == 350 && (a - b).ns == 150 && (-a).ns == -250); + t.expects(a + b == b + a && a - b > b - a && a + b - b == a); + + # One with only `add` has `+`, and nothing else. + ledgers_added = 0; + val one := ledger { sum = 1 }; + t.expects((one + one + one).sum == 3 && ledgers_added == 2); +} + +@test def operands_and_results_are_what_the_method_declares(t: &mut tester): void { + val began := moment { ns = 100 }; + val now := moment { ns = 350 }; + val waited: stretch = now - began; + val due: moment = began + waited * 2; + t.expects(waited.ns == 250 && due.ns == 600 && (due - waited).ns == 350); + + # A constant takes the type of the parameter it is given to, and of two + # overloads the one it is alone. + t.expects((waited * 2).ns == 500 && (waited * 0.5).ns == 125 && (waited / 5).ns == 50); + val count: u8 = 3; + t.expects((waited * count as i64).ns == 750); + + # A result of a third type. + val ratio: f64 = (waited * 3) / waited; + t.expects(ratio == 3.0 && arrow { x = 1.0, y = 2.0 } * arrow { x = 3.0, y = 4.0 } == 11.0); + + # References are read through, on either side. + val later: &moment = &due; + val by: &stretch = &waited; + t.expects((later - by).ns == 350 && (later - began).ns == 500 && (by + by).ns == 500); +} + +@test def a_number_on_the_left_asks_its_own_type(t: &mut tester): void { + val v := arrow { x = 1.5, y = 2.0 }; + val a := v * 2.0; + val b := 2.0 * v; + val scale := 4.0; + t.expects(a == b && a.x == 3.0 && (scale * v).y == 8.0 && (0.5 * v * 2.0) == v); + + # The number is still the number it was: its own methods are beside the program's. + t.expects(2.5.mul(&2.0) == 5.0 && 2.5 * 2.0 == 5.0 && scale.mul(&scale) == 16.0); + t.expects(2.5 is numeric && 2.5 is multiplicative && product_of(1.5, 4.0) == 6.0); +} + +@test def compound_assignment_writes_what_the_method_gives(t: &mut tester): void { + var due := moment { ns = 100 }; + due += stretch { ns = 50 }; + due -= stretch { ns = 20 }; + t.expects(due.ns == 130); + + var waited := stretch { ns = 10 }; + waited += waited; + waited *= 3; + waited /= 4; + t.expects(waited.ns == 15); + + # Through a property, an element, and a reference. + ledgers_added = 0; + var held := purse { kept = ledger { sum = 2 } }; + held.all += ledger { sum = 5 }; + var many := [ledger { sum = 1 }, ledger { sum = 10 }]; + many[1] += many[0]; + val through: &mut ledger = &mut many[0]; + through += held.kept; + t.expects(held.kept.sum == 7 && many[1].sum == 11 && many[0].sum == 8 && ledgers_added == 3); +} + +@test def generic_code_has_operators_through_its_bounds(t: &mut tester): void { + val low := arrow { x = 0.0, y = 0.0 }; + val high := arrow { x = 2.0, y = 4.0 }; + t.expects(blend(1.0, 3.0, 0.5) == 2.0 && blend(low, high, 0.5) == arrow { x = 1.0, y = 2.0 }); + + t.expects(gathered([1, 2, 3][0:3], 0) == 6 && gathered([1.5, 2.5][0:2], 0.0) == 4.0); + t.expects(gathered([second(1), second(2)][0:2], second(0)) == second(3)); + t.expects(mirrored(7, 3) == -4 && mirrored(second(5), second(2)) == second(-3) && mirrored(high, high) == high); + t.expects(product_of(3, 4) == 12 && shared_out(17, 5) == 5 && shared_out(7.5, 2.0) == 5.25); + + # What satisfies which: numbers all of them, and a type what it declares. + t.expects(1 is additive && 1 is multiplicative && 1 is numeric && 1.5 is divisible && 1 is modular); + t.expects(second(1) is additive && second(1) is addable && !(second(1) is numeric)); + t.expects(high is additive && !(high is multiplicative) && !(true is addable) && !(moment { ns = 0 } is addable)); +} + +@test def operators_of_methods_make_constants(t: &mut tester): void { + t.expects(long_pause == second(8)); +} diff --git a/tests/core/owners.sakura b/tests/core/owners.sakura new file mode 100644 index 00000000..ed481798 --- /dev/null +++ b/tests/core/owners.sakura @@ -0,0 +1,74 @@ +# Tests of `core`'s owner of heap memory, `box`, owned alone, which closes what +# it holds exactly once. `rc` and `arc`, owned by every copy, are std's, and +# tested there. + +import std::testing; + + +# How many values the tests gave boxes have been closed. +var owned_closed: atomic; + +struct owned : owning { + var mark: u64; +} + +def owned::close(&mut this): void { + if this.mark != 0 { + _ = owned_closed.fetch_add(1); + this.mark = 0; + } +} + +struct linked { + var value: u64; + var next: maybe>; +} + +@test def boxes_and_maybe_boxes_are_one_word(t: &mut tester): void { + t.expects(size_of::>() == 8 && size_of::>>() == 8); + val none_held: maybe> = nothing {}; + t.expects(!(none_held is some)); +} + +@test def a_box_closes_its_value_once(t: &mut tester): void { + val before := owned_closed.load(); + { + var a := box::::new(owned { mark = 1 }); + a.get().mark = 2; + t.expects(a.holds() && a.get().mark == 2); + + # Moving leaves the box moved from empty, so it closes nothing. + var b := move(&mut a); + t.expects(!a.holds() && b.holds() && b.get().mark == 2); + a.close(); + t.expects(owned_closed.load() == before); + + # Taking the value leaves the box empty and the value its taker's. + val taken := b.take(); + t.expects(!b.holds() && taken.mark == 2 && owned_closed.load() == before); + } + t.expects(owned_closed.load() == before + 1); + + { + val c := box::::new(owned { mark = 3 }); + } + t.expects(owned_closed.load() == before + 2); +} + +@test def boxes_link_a_list_closed_with_its_front(t: &mut tester): void { + var front: maybe> = nothing {}; + for i in 0..100u { + front = box::::new(linked { value = i, next = move(&mut front) }); + } + var total: u64 = 0; + var count: u64 = 0; + var at: maybe<&linked> = nothing {}; + if front is some(&first) { at = first.get(); } + while at is some(&each) { + total += each.value; + count++; + at = nothing {}; + if each.next is some(&next) { at = next.get(); } + } + t.expects(total == 4950 && count == 100); +} diff --git a/tests/core/owning.sakura b/tests/core/owning.sakura new file mode 100644 index 00000000..2595dc5a --- /dev/null +++ b/tests/core/owning.sakura @@ -0,0 +1,209 @@ +# Tests of what is closed where its scope ends: a type naming `owning`, and what holds +# one, which is `closeable`. A `close` alone is only a method, and a reference or a +# pointer owns nothing. +import std::testing; + + +# How many values holding a number have been closed. +var shut: u64 = 0; + +struct named : owning { + var n: u64; +} + +def named::close(&mut this): void { + if this.n != 0 { + shut++; + this.n = 0; + } +} + +struct shaped { + var n: u64; +} + +def shaped::close(&mut this): void { + if this.n != 0 { + shut++; + this.n = 0; + } +} + +struct wraps { + var inner: named; +} + +def kind(): span { + if const T is owning { return "owning"; } + if const T is closeable { return "closeable"; } + return "plain"; +} + +@test def only_what_names_owning_is_closed(t: &mut tester): void { + t.expects(kind::() == "owning" && kind::() == "closeable" && kind::() == "closeable"); + t.expects(kind::() == "plain" && kind::<&mut named>() == "plain" && kind::<*mut named>() == "plain"); + + shut = 0; + { + val a := named { n = 1 }; + val b := shaped { n = 1 }; + val c := wraps { inner = named { n = 1 } }; + } + t.expects(shut == 2); + + # A `close` is still called by hand, through a reference too. + var d := shaped { n = 1 }; + val through: &mut shaped = &mut d; + through.close(); + t.expects(shut == 3 && d.n == 0); +} + +# Gives values counting down to one, then nothing. +struct countdown { + var left: u64; +} + +def countdown::next(&mut this): maybe { + if this.left == 0 { + return nothing {}; + } + this.left--; + return named { n = this.left + 1 }; +} + +def first_of(from: &mut countdown): named { + if from.next() is some(got) { + return got; + } + return named {}; +} + +@test def union_fields_are_taken_from_what_a_call_made(t: &mut tester): void { + # Named by value, each is taken out of what the call gave, and closed once, where the + # turn ends, a `continue` goes on, or a `break` leaves. + shut = 0; + var from := countdown { left = 5 }; + var seen: u64 = 0; + while from.next() is some(got) { + if got.n == 4 { + continue; + } + seen += got.n; + if got.n == 2 { + break; + } + } + t.expects(seen == 10 && shut == 4); + + from.left = 1; + if from.next() is some(got) { + seen += got.n; + } + from.left = 1; + match from.next() { + some(got) => seen += got.n; + else => {} + } + t.expects(seen == 12 && shut == 6); + + # Given away, by `return` or as an arm's value, it is closed by what took it. + from.left = 2; + { + val kept := first_of(&mut from); + val also: named = match from.next() { + some(got) => got, + else => named {}, + }; + t.expects(kept.n == 2 && also.n == 1 && shut == 6); + } + t.expects(shut == 8); + + # `is not` gives it to the rest of the block. + from.left = 1; + { + if from.next() is not some(got) { + return; + } + t.expects(got.n == 1 && shut == 8); + } + t.expects(shut == 9); +} + +@test def a_while_closes_what_its_condition_made_each_turn(t: &mut tester): void { + # Named in place, each value is still the one the call gave, closed before the + # condition makes the next. + shut = 0; + var from := countdown { left = 4 }; + var seen: u64 = 0; + while from.next() is some(&got) { + if got.n == 3 { + continue; + } + seen += got.n; + } + t.expects(seen == 7 && shut == 4); +} + +@test def names_are_given_where_their_test_holds(t: &mut tester): void { + # What the left of `&&` names is the right's to use, and of the branch, and each value + # a test takes is closed once, whichever tests a short circuit leaves unrun. + shut = 0; + var from := countdown { left = 3 }; + var seen: u64 = 0; + if from.next() is some(a) && from.next() is some(b) && a.n > b.n { + seen = a.n * 10 + b.n; + } + t.expects(seen == 32 && shut == 2); + if from.next() is some(a) && from.next() is some(b) { + seen = 0; + } + t.expects(seen == 32 && shut == 3); + + # `||` gives its right what an `is not` test names, and `!` turns a test around. + from.left = 2; + val small := from.next() is not some(c) || c.n < 3; + t.expects(small && shut == 4); + from.left = 1; + { + if !(from.next() is some(d)) { + seen = 0; + } else { + seen = d.n; + } + } + t.expects(seen == 1 && shut == 5); + + # A guard gives the rest of the block what it names. + from.left = 2; + { + if from.next() is not some(e) || from.next() is not some(f) { + return; + } + seen = e.n * 10 + f.n; + } + t.expects(seen == 21 && shut == 7); +} + +@test def bindings_holding_values_are_moved_from(t: &mut tester): void { + # A value a binding took is its own, so it is moved on, and the binding then closes + # nothing, as a `var` moved from does. + shut = 0; + var from := countdown { left = 2 }; + { + var kept := vector::::new(); + while from.next() is some(got) { + kept.append(move(got)); + } + from.left = 1; + match from.next() { + some(got) => kept.append(move(got)); + else => {} + } + from.left = 2; + for each in from { + kept.append(move(each)); + } + t.expects(kept.length == 5 && shut == 0); + } + t.expects(shut == 5); +} diff --git a/tests/core/references.sakura b/tests/core/references.sakura new file mode 100644 index 00000000..a7ae5a4b --- /dev/null +++ b/tests/core/references.sakura @@ -0,0 +1,372 @@ +# Tests of what references and pointers satisfy. A reference satisfies the traits of +# what it refers to, called through it, so a generic given one borrows what it would +# otherwise own, and it is compared and hashed as what it refers to. A pointer is an +# address: it is compared and hashed as one, and what it points at is reached by +# dereferencing it. +import std::containers; +import std::testing; + + +# Something written to, a number at a time. +trait sink { + def put(&mut this, n: u64): void; + def put_twice(&mut this, n: u64): void { this.put(n); this.put(n); } +} + +# Something whose size is read. +trait sized { + def size(&this): u64; +} + +# How many tallies holding a count have been closed. +var tallies_closed: u64 = 0; + +struct tally : sink, sized, owning { + var n: u64; +} + +def tally::put(&mut this, n: u64): void { this.n += n; } +def tally::size(&this): u64 { return this.n; } + +def tally::close(&mut this): void { + if this.n != 0 { + tallies_closed++; + this.n = 0; + } +} + +# A sink that passes each number on to what it holds, owned or borrowed, and closes +# it where it owns what closes. +struct relay : sink where S: sink { + var to: S; +} + +def relay::put(&mut this, n: u64): void { + this.to.put(n); +} + +# Puts a number through a reference to the trait, made from the field. +def relay::put_through_trait(&mut this, n: u64): void { + val to: &mut sink = &mut this.to; + to.put(n); +} + +def relay_to(to: S): relay where S: sink { + return relay:: { to = move(to) }; +} + +def size_of_it(it: T): u64 where T: sized { + return it.size(); +} + +# How many times a mark has been hashed by its own `hash`. +var marks_hashed: u64 = 0; + +struct mark : ordered, hashable { + var n: u64; +} + +def mark::equals(&this, other: &mark): bool { return this.n == other.n; } +def mark::compare(&this, other: &mark): i64 { return this.n as i64 - other.n as i64; } + +def mark::hash(&this): u64 { + marks_hashed++; + return this.n; +} + +# Something holding a field named as one of a pointer's own methods. +struct slot { + var hash: u64; +} + +def larger(a: T, b: T): T where T: ordered { + if a < b { return b; } + return a; +} + +def same(a: T, b: T): bool where T: equatable { + return a == b && a.equals(&b); +} + +def total(items: C): u64 where C: iterable { + var sum: u64 = 0; + for &each in items { + sum += each; + } + return sum; +} + +def first_and_last(items: C, count: u64): u64 where C: indexable { + return items[0] * 10 + items.at(count - 1); +} + +# How many elements lie between two pointers, by moving one along, as pointers do. +def elements_between

(first: P, last: P): i64 where P: pointer { + var at := first; + at += 1; + return last - at + 1; +} + +def no_pointer

(): P where P: pointer { + var made: P; + return made; +} + +def addressed(): span { + if const T is pointer { return "pointer"; } + return "not"; +} + +# Puts a value in a slot, whatever it is: given a reference, the slot refers anew. +def put_in(slot: &mut T, value: T): void { + slot = value; +} + +def what(): span { + if const S is owning { return "owning"; } + if const S is closeable { return "closeable"; } + if const S is sink { return "sink"; } + return "neither"; +} + +@test def references_satisfy_what_they_refer_to(t: &mut tester): void { + var kept := tally { n = 1 }; + var by_reference := relay_to(&mut kept); + by_reference.put(2); + by_reference.put_through_trait(3); + t.expects(kept.n == 6); + + # A pointer satisfies nothing of what it points at, but a reference through it does. + var by_pointer := relay_to(&mut through((&mut kept) as *mut tally)); + by_pointer.put(4); + by_pointer.put_through_trait(5); + t.expects(kept.n == 15); + + val as_trait: &mut sink = &mut kept; + var by_trait := relay_to(as_trait); + by_trait.put(6); + by_trait.put_through_trait(7); + t.expects(kept.n == 28); + + # Relays nest, each borrowing the one inside it. + var inner := relay_to(&mut kept); + var outer := relay_to(&mut inner); + outer.put(2); + outer.put_through_trait(1); + t.expects(kept.n == 31); + + # Read through a reference that only reads, since `size` takes `&this`. + t.expects(size_of_it(&kept) == 31 && size_of_it(&through((&kept) as *tally)) == 31); +} + +@test def references_take_the_types_their_referents_give(t: &mut tester): void { + # A trait asking for types is satisfied through a reference with the referent's, as + # `iterable` asks for a `cursor`, and an `@optional` method writing is not asked of + # a reference that only reads. + var numbers := vector::::new(); + numbers.append(4); + numbers.append(5); + numbers.append(6); + val viewed: &vector = &numbers; + t.expects(total(&viewed) == 15 && total(&mut numbers) == 15 && total(numbers.view()) == 15); + t.expects(first_and_last(&viewed, 3) == 46 && first_and_last(&numbers, 2) == 45); +} + +@test def references_close_nothing_they_refer_to(t: &mut tester): void { + t.expects(what::() == "owning"); + t.expects(what::>() == "closeable"); + t.expects(what::<&mut tally>() == "sink" && what::<*mut tally>() == "neither"); + t.expects(what::>() == "sink"); + + tallies_closed = 0; + var lent := tally { n = 1 }; + { + var borrowed := relay_to(&mut lent); + borrowed.put(1); + } + t.expects(tallies_closed == 0 && lent.n == 2); + { + var owned := relay_to(tally { n = 1 }); + owned.put(1); + } + t.expects(tallies_closed == 1); + + # Never closed itself, a reference still has `close` called through it on what it + # refers to, as a reference to the trait does, and what a pointer points at. + tallies_closed = 0; + var shut := tally { n = 1 }; + val by_reference: &mut tally = &mut shut; + by_reference.close(); + var pointed := tally { n = 1 }; + (*((&mut pointed) as *mut tally)).close(); + var traited := tally { n = 1 }; + val by_trait: &mut owning = &mut traited; + by_trait.close(); + t.expects(tallies_closed == 3 && shut.n == 0 && pointed.n == 0 && traited.n == 0); +} + +# A condition is the `bool` a reference refers to, and a ternary's branches are the +# values theirs refer to where only one of them is a reference. +def read_through(flag: &mut bool, by: &u64): u64 { + var total: u64 = 0; + if flag { + total += 1; + } + while flag { + flag = false; + total += 10; + } + total += flag ? 0 : 100; + return total + (flag ? 0 : by); +} + +@test def conditions_read_through_references(t: &mut tester): void { + var flag := true; + val by: u64 = 1000; + t.expects(read_through(&mut flag, &by) == 1111 && !flag); + + # `_` names nothing, so a test naming it stands anywhere a `bool` does. + val held: maybe = 4; + val empty: maybe = nothing {}; + t.expects(held is some(_) && !(empty is some(_)) && (empty is some(_) || held.some == 4)); +} + +@test def references_compare_what_they_refer_to(t: &mut tester): void { + var one := mark { n = 1 }; + var two := mark { n = 2 }; + var also := mark { n = 2 }; + t.expects(larger(&one, &two).n == 2 && larger(&two, &one).n == 2); + t.expects(same(&two, &also) && !same(&one, &two)); + + var x: i32 = 4; + val by_reference: &i32 = &x; + t.expects(larger(by_reference, &x) == 4 && hash(&by_reference) == hash(&x)); + + # Keys and elements that are references are found by what they refer to. + marks_hashed = 0; + var counts := dict::<&mark, u64>::new(); + counts.set(&two, 5); + t.expects(counts[&also] == 5 && counts.length == 1 && marks_hashed > 0); + + var refs := vector::<&mark>::new(); + refs.append(&one); + refs.append(&two); + val wanted: &mark = &also; + t.expects(refs.view().contains(&wanted)); +} + +@test def references_to_what_a_call_gives_are_what_it_gives(t: &mut tester): void { + # `&` of a call giving a reference is that reference, not one to a copy of it, + # so it is the element's address and writes reach the element. + var marks := vector::::new(); + marks.append(mark { n = 1 }); + val read := &marks.at(0); + t.expects((read as *mark) == (&marks.at(0)) as *mark && read.n == 1); + val written := &mut marks.at(0); + written.n = 7; + t.expects(marks.at(0).n == 7 && (written as *mark) == marks.view().data); +} + +@test def pointers_compare_their_addresses(t: &mut tester): void { + var two := mark { n = 2 }; + var also := mark { n = 2 }; + val p := (&two) as *mark; + val q := (&also) as *mark; + t.expects(p != q && same(p, p) && !same(p, q)); + t.expects(p.equals(&p) && !p.equals(&q) && p.compare(&p) == 0); + + # Hashed as addresses, two pointers at equal marks are two keys, and no mark is hashed. + marks_hashed = 0; + var seen := dict::<*mark, u64>::new(); + seen.set(p, 1); + seen.set(q, 2); + t.expects(seen.length == 2 && seen[p] == 1 && seen[q] == 2); + t.expects(p.hash() == hash(&p) && marks_hashed == 0); + + # What they point at is still compared through them. + t.expects(p[0] == q[0] && (*p).n == (*q).n); + val held: &*mark = &p; + t.expects(held.equals(&p) && held.hash() == p.hash() && (*held).n == 2 && marks_hashed == 0); + + # A type parameter bounded by `pointer` moves, subtracts, and starts at `null` as + # pointers do, however deep. + var xs := [1u, 2u, 3u, 4u]; + val first := (&mut xs) as *mut u64; + t.expects(elements_between(first, first + 3) == 3 && no_pointer::<*mark>() == null); + t.expects(addressed::<**mark>() == "pointer" && addressed::<&mark>() == "not" && addressed::() == "not"); + + # What a pointer points at is reached by dereferencing it, even a field named as one + # of the pointer's own methods. + var s := slot { hash = 9 }; + val at := (&mut s) as *mut slot; + t.expects((*at).hash == 9 && through(at).hash == 9 && at.hash() == hash(&at)); +} + +@test def containers_hold_references_and_pointers(t: &mut tester): void { + # A container moves what it is given, which for a reference is the reference + # itself, and closes none of what its references reach. + tallies_closed = 0; + var a := tally { n = 1 }; + var b := tally { n = 2 }; + { + var refs := vector::<&mut tally>::new(); + refs.append(&mut a); + refs.append(&mut b); + refs[1].put(18); + refs.remove_at(0); + t.expects(refs.length == 1 && refs[0].n == 20); + + var pointers := stack::<*mut tally>::new(); + pointers.push((&mut a) as *mut tally); + (*pointers.peek()).put(9); + + var named := dict::::new(); + named.set(1, &b); + t.expects(named[1].size() == 20); + } + t.expects(a.n == 10); + t.expects(b.n == 20); + t.expects(tallies_closed == 0); +} + +@test def what_a_pointer_points_at_is_reached_by_dereferencing_it(t: &mut tester): void { + var a := tally { n = 1 }; + var p := (&mut a) as *mut tally; + (*p).put_twice(1); + through(p).put(1); + + # A reference to a pointer reads through to the pointer, which is dereferenced. + val r: &mut *mut tally = &mut p; + (*r).put(5); + through(r).put_twice(1); + p[0].put(1); + t.expects(a.n == 12 && (*r).size() == 12 && r == (&mut a) as *mut tally); +} + +@test def generics_assign_references_as_their_templates_say(t: &mut tester): void { + var a: u64 = 1; + var b: u64 = 2; + var r: &mut u64 = &mut a; + + # References never stack, so `&mut r` is `r`, and the slot is `a`. + put_in(&mut r, 5); + t.expects(a == 5 && b == 2); + + var n: u64 = 0; + put_in(&mut n, 4); + t.expects(n == 4); + + # Where `T` is a reference, the template's assignment gives the slot the + # reference, as it gives any other value. + var slots := vector::<&mut u64>::new(); + slots.append(&mut a); + put_in(&mut slots[0], &mut b); + b = 9; + t.expects(slots[0] == 9 && a == 5); + + # A reference written as one points a variable elsewhere, and a value given to + # a reference is written to what it refers to. + r = &mut b; + r = 7; + t.expects(a == 5 && b == 7); +} diff --git a/tests/core/results.sakura b/tests/core/results.sakura new file mode 100644 index 00000000..41a93920 --- /dev/null +++ b/tests/core/results.sakura @@ -0,0 +1,168 @@ +# Tests of the properties and methods of `maybe` and `result`: reading what they +# hold, by a copy where they are only read and by a move where they can be +# written, making others of them, and comparing, hashing, and copying them. A +# value that closes is closed once, whichever way it leaves. + +import std::testing; + + +# How many tokens holding a mark have been closed. +var tokens_closed: u64 = 0; + +struct token : owning, copyable { + var mark: u64; +} + +def token::close(&mut this): void { + if this.mark != 0 { + tokens_closed++; + this.mark = 0; + } +} + +def token::copy_of(other: &token): token { + return token { mark = other.mark }; +} + +# Half a number, where it is even. +def halved(n: i64): maybe { + return n % 2 == 0 ? something(n / 2) : nothing {}; +} + +# How long text is, or that it is empty. +def measured(text: strview): result { + return text.length == 0 ? result::::err("empty") : result::::ok(text.length); +} + +@test def a_maybe_reads_what_it_holds(t: &mut tester): void { + val held: maybe = 8; + val empty: maybe = nothing {}; + t.expects(held.is_some && !held.is_none && empty.is_none && !empty.is_some); + t.expects(held.unwrap() == 8 && held.expect("held") == 8 && empty.unwrap_or(3) == 3 && held.unwrap_or(3) == 8); + t.expects(held.is_some_and(def(x: &i64) => x > 5) && !empty.is_some_and(def(x: &i64) => true)); + + # Plain data is copied out of what can be written, as `move` copies it. + var kept: maybe = 6; + t.expects(kept.unwrap() == 6 && kept.is_some && kept.unwrap_or(1) == 6); + var unset: maybe = nothing {}; + t.expects(unset.unwrap_or_else(def(): i64 => 11) == 11); +} + +@test def a_maybe_makes_others(t: &mut tester): void { + var six: maybe = 6; + t.expects(six.map(def(x: i64) => x * 10) == 60 && six.and_then(halved) == 3); + t.expects(six.and_then(halved).and_then(halved).is_none); + t.expects(six.filter(def(x: &i64) => x > 10).is_none && six.filter(def(x: &i64) => x > 1) == 6); + var empty: maybe = nothing {}; + t.expects(empty.or(5) == 5 && six.or(5) == 6 && empty.or_else(def(): maybe => 7) == 7); + t.expects(six.ok_or::("none").unwrap() == 6 && empty.ok_or::("none").unwrap_err() == "none"); + t.expects(six.as_ref().map(def(x: &i64) => x + 1) == 7 && empty.as_ref().is_none); + if six.as_mut() is some(&mut got) { + got += 1; + } + t.expects(six == 7); + + # `take` and `replace` leave it holding nothing, or the new value. + t.expects(six.take() == 7 && six.is_none && six.replace(4).is_none && six == 4); +} + +@test def a_maybe_compares_hashes_and_copies(t: &mut tester): void { + val a: maybe = 5; + val b: maybe = 5; + val c: maybe = 6; + val none: maybe = nothing {}; + t.expects(a == b && a != c && a != none && none == maybe:: { none = nothing {} } && a == 5); + t.expects(hash(&a) == hash(&b) && hash(&a) != hash(&none)); + val text: maybe = string::from("held", nothing {}); + val copied := copy(&text); + t.expects(copied == text && copied.as_ref().map(def(s: &string) => s.length) == 4); +} + +@test def a_maybe_moves_out_what_closes(t: &mut tester): void { + val before := tokens_closed; + { + # Moved out of what can be written, leaving it holding nothing. + var held: maybe = token { mark = 1 }; + var taken := held.unwrap(); + t.expects(taken.mark == 1 && held.is_none && tokens_closed == before); + + # Moved into what a function makes, which closes it there. + var given: maybe = token { mark = 2 }; + t.expects(given.map(def(x: token) => x.mark) == 2 && given.is_none && tokens_closed == before + 1); + + # Left behind by `filter`, `or`, and `replace`, each closed once. + var failed: maybe = token { mark = 3 }; + t.expects(failed.filter(def(x: &token) => false).is_none && tokens_closed == before + 2); + var first: maybe = token { mark = 4 }; + var other := first.or(token { mark = 5 }); + t.expects(other.as_ref().map(def(x: &token) => x.mark) == 4 && tokens_closed == before + 3); + var swapped: maybe = token { mark = 6 }; + var old := swapped.replace(token { mark = 7 }); + t.expects(old.is_some && swapped.as_ref().is_some_and(def(x) => x.mark == 7)); + + # A box held by a `maybe` in one word is taken whole. + var boxed: maybe> = box::::new(token { mark = 8 }); + var out := boxed.take(); + t.expects(boxed.is_none && out.is_some && size_of::>>() == 8); + } + # taken, other, old, swapped, and out's are closed at the end of the block. + t.expects(tokens_closed == before + 8); +} + +@test def a_result_reads_what_it_holds(t: &mut tester): void { + val good := measured("four"); + val bad := measured(""); + t.expects(good.is_ok && !good.is_err && bad.is_err && !bad.is_ok); + t.expects(good.unwrap() == 4 && good.expect("good") == 4 && bad.unwrap_err() == "empty" && bad.expect_err("bad") == "empty"); + t.expects(bad.unwrap_or(9) == 9 && good.unwrap_or(9) == 4); + t.expects(good.is_ok_and(def(x: &u64) => x == 4) && bad.is_err_and(def(e: &strview) => e.length == 5)); + var failed := measured(""); + t.expects(failed.unwrap_or_else(def(e: strview) => e.length) == 5); +} + +@test def a_result_makes_others(t: &mut tester): void { + var two := measured("ab"); + var none := measured(""); + t.expects(two.map(def(x: u64) => x + 1).unwrap() == 3 && none.map(def(x: u64) => x + 1).unwrap_err() == "empty"); + t.expects(none.map_err(def(e: strview) => e.length).unwrap_err() == 5 && two.map_err(def(e: strview) => e.length).unwrap() == 2); + t.expects(two.and_then(def(x: u64): result => result::::err("no")).unwrap_err() == "no"); + t.expects(none.or_else(def(e: strview): result => result::::ok(7)).unwrap() == 7); + t.expects(two.to_maybe() == 2 && none.to_maybe().is_none && none.err_to_maybe() == "empty" && two.err_to_maybe().is_none); + t.expects(two.as_ref().is_ok_and(def(x) => x == 2) && none.as_ref().is_err); + + # A value and an error of one type are told apart. + var same := result::::err(5); + t.expects(same.is_err && same.map(def(x: i64) => x + 100).unwrap_err() == 5); + t.expects(result::::ok(5) != result::::err(5)); + + # A result of `void` says only whether it failed. + val done := result::::ok(void {}); + done.unwrap(); + t.expects(done.is_ok); +} + +@test def a_result_compares_hashes_and_copies(t: &mut tester): void { + val a := measured("abc"); + val b := measured("xyz"); + val c := measured(""); + t.expects(a == b && a != c && c == measured("")); + t.expects(hash(&a) == hash(&b) && hash(&a) != hash(&c)); + val text := result::::ok(string::from("held", nothing {})); + val copied := copy(&text); + t.expects(copied == text && copied.as_ref().is_ok_and(def(s) => s.length == 4)); +} + +@test def a_result_moves_out_what_closes(t: &mut tester): void { + val before := tokens_closed; + { + var held := result::::ok(token { mark = 1 }); + var taken := held.unwrap(); + t.expects(taken.mark == 1 && tokens_closed == before); + + var failed := result::::err(token { mark = 2 }); + t.expects(failed.map_err(def(x: token) => x.mark).unwrap_err() == 2 && tokens_closed == before + 1); + var lost := result::::ok(token { mark = 3 }); + t.expects(lost.err_to_maybe().is_none && tokens_closed == before + 2); + } + t.expects(tokens_closed == before + 3); +} diff --git a/tests/core/scanning.sakura b/tests/core/scanning.sakura new file mode 100644 index 00000000..bd56f996 --- /dev/null +++ b/tests/core/scanning.sakura @@ -0,0 +1,76 @@ +# Tests of std's scanning of text, which an executable does sixteen bytes at a +# time: what it looks for at every place, so on either side of where each +# sixteen ends, against the same work done a byte at a time. + +import std::io; +import std::testing; + +# The text of a length whose bytes at the places a pattern sets are a byte, and +# letters otherwise. +def text_with(length: u64, pattern: u64, byte: u8): string { + var made := string::new(nothing {}); + for i in 0..length { + val set := ((pattern >> (i % 61)) & 1) != 0; + made.push(set ? byte : ('a' as u64 + i % 26) as u8); + } + return made; +} + +@test def splitting_finds_every_delimiter_wherever_it_falls(t: &mut tester): void { + for length in 0..80u { + for pattern in [0 as u64, 1, 0x8000, 0x10001, 0x5555555555555555, 0xFFFFFFFFFFFFFFFF, 0x0123456789ABCDEF] { + val text := text_with(length, pattern, ','); + val parts := text.view().split(',').to_vector(); + # Each part, joined by the delimiter, is the text again, and none holds it. + var joined := string::new(nothing {}); + var clean := true; + for i in 0..parts.length { + if i != 0 { + joined.push(','); + } + joined.append(parts[i]); + for k in 0..parts[i].length { + clean = clean && parts[i][k] != ','; + } + } + t.expects(joined.view() == text.view() && clean); + } + } +} + +@test def text_compares_as_its_bytes_do(t: &mut tester): void { + for length in 0..70u { + val a := text_with(length, 0x0F0F0F0F0F0F0F0F, 'x'); + t.expects(a.view().compare(a.view()) == 0); + for place in 0..length { + for byte in [0 as u8, 'a', 'x', 0x80, 0xFF] { + var b := text_with(length, 0x0F0F0F0F0F0F0F0F, 'x'); + b[place] = byte; + val was: u8 = a[place]; + val want: i64 = was == byte ? 0 : (was < byte ? -1 : 1); + t.expects(a.view().compare(b.view()) == want); + } + # A prefix orders first. + t.expects(a.view().substr(0, place).compare(a.view()) == -1); + } + } +} + +@test def lines_are_read_wherever_their_breaks_fall(t: &mut tester): void { + for length in 0..70u { + val text := text_with(length, 0x2104210421042104, '\n'); + var input := io::reader_of(text.view()); + var seen := string::new(nothing {}); + for line in input.lines() { + seen.append(line.view()); + seen.push('\n'); + } + # The lines, each with its break, are the text, but for a last line without one. + var want := string::new(nothing {}); + want.append(text.view()); + if want.length != 0 && want[want.length - 1] != '\n' { + want.push('\n'); + } + t.expects(seen.view() == want.view()); + } +} diff --git a/tests/core/signals.sakura b/tests/core/signals.sakura new file mode 100644 index 00000000..b3fb17f7 --- /dev/null +++ b/tests/core/signals.sakura @@ -0,0 +1,541 @@ +# Tests of signals: sending them, ignoring them, putting back what the system does +# with them, handling them, at the program's safe points and where a wait is +# interrupted, and watching for them. Each test runs in a copy of the program, so what one handles is its +# own. Windows sends a program no signal from another, so there a thread, or a +# copy of the program, sends what another program does on Linux. +import std::io; +import std::process; +import system; +import std::testing; +import std::thread; + +# A function of the program's own, which begins with a safe point. +def safe_point(): void {} + +when os == linux { + # Runs a copy of the program that puts back what the system does with a signal, + # then sends it to itself, giving the signal that stopped the copy, or zero where + # the copy went on and exited. + def raised_in_copy(sent: system::signal): i32 { + val copy := system::fork(); + if copy == 0 { + _ = system::restore(sent); + _ = system::raise(sent); + safe_point(); + system::exit(0); + } + + var status: system::process_status; + _ = system::wait(copy, &mut status); + return status.exited ? 0 : status.signal; + } + + # The signals the system says the program does something with, one bit each by + # number less one: those it handles, where `named` is `SigCgt`, or ignores, where + # it is `SigIgn`. + def dispositions(named: strview): u64 { + var at := path::parse("/proc/self/status") else (_) { return 0; }; + val text := io::read_file(&at) else (_) { return 0; }; + for line in text.view().split('\n') { + if !line.starts_with(named) || line.length < 16 { + continue; + } + + val hex := line.substr(line.length - 16, 16); + var bits: u64 = 0; + for i in 0..hex.length { + val digit := hex[i] >= 'a' ? (hex[i] - 'a') as u64 + 10 : (hex[i] - '0') as u64; + bits = bits * 16 + digit; + } + return bits; + } + return 0; + } + + # Waits until a process is in a state, as `/proc` gives it: `S` where it sleeps, + # as it does waiting in the system, so a signal sent to it then interrupts the + # wait, and `T` where it is paused. Gives whether it was. + def reaches(process: i64, state: u8): bool { + var at := path::parse($"/proc/{process}/stat") else (_) { return false; }; + for tries in 0..1000000 { + val text := io::read_file(&at) else (_) { return false; }; + val view := text.view(); + var end := view.length; + while end > 0 && view[end - 1] != ')' { + end--; + } + if end + 1 < view.length && view[end + 1] == state { + return true; + } + } + return false; + } + + # Starts a copy of the program that sends it a signal once it sleeps, then waits + # to be stopped, giving the copy's number. + def signalled_once_asleep(sent: system::signal): i64 { + val program := system::getpid(); + val copy := system::fork(); + if copy == 0 { + _ = system::restore(sent); + if reaches(program, 'S') { + _ = system::kill(program, sent); + } + system::pause(); + system::exit(0); + } + return copy; + } +} + +# Whether a read failed because a signal ended its wait. +def is_interrupted(error: maybe): bool { + if error is some(why) { + return why == io_error::interrupted; + } + return false; +} + +# A stream that gives its text in two parts, failing between them as a read does +# that a signal the program handles interrupts. +struct halting : readable { + var first: strview; + var rest: strview; + var halted: bool; +} + +def halting::read(&mut this, into: slice): result { + if this.first.length > 0 { + return this.first.read(into); + } + if !this.halted { + this.halted = true; + return io_error::interrupted; + } + return this.rest.read(into); +} + +when os == linux { + @test def signals_have_the_numbers_of_the_system(t: &mut tester): void { + # Those a program may handle are noted by the system under their numbers, and + # each handler is given the signal that came. Each is restored after, so that + # `child` interrupts no wait below. + val members: system::signal[12] = [ + system::signal::hangup, system::signal::interrupt, system::signal::quit, system::signal::user1, + system::signal::user2, system::signal::pipe, system::signal::alarm, system::signal::terminate, + system::signal::child, system::signal::resume, system::signal::suspend, system::signal::resized + ]; + val numbers: u64[12] = [1, 2, 3, 10, 12, 13, 14, 15, 17, 18, 20, 28]; + var came := system::signal::kill; + for i in 0..members.length { + t.expects(system::handle(members[i], def(s: system::signal) { came = s; }) == 0); + t.expects(((dispositions("SigCgt") >> (numbers[i] - 1)) & 1) == 1); + t.expects(system::raise(members[i]) == 0); + safe_point(); + t.expects(came == members[i]); + t.expects(system::restore(members[i]) == 0); + t.expects(((dispositions("SigCgt") >> (numbers[i] - 1)) & 1) == 0); + } + + # What stops a program by default stops a copy with its number. + t.expects(raised_in_copy(system::signal::hangup) == 1); + t.expects(raised_in_copy(system::signal::interrupt) == 2); + t.expects(raised_in_copy(system::signal::kill) == 9); + t.expects(raised_in_copy(system::signal::user1) == 10); + t.expects(raised_in_copy(system::signal::user2) == 12); + t.expects(raised_in_copy(system::signal::pipe) == 13); + t.expects(raised_in_copy(system::signal::alarm) == 14); + t.expects(raised_in_copy(system::signal::terminate) == 15); + + # `stop` pauses a copy, and `resume` lets it go on. + val copy := system::fork(); + if copy == 0 { + _ = system::raise(system::signal::stop); + system::exit(5); + } + t.expects(reaches(copy, 'T')); + _ = system::kill(copy, system::signal::resume); + var status: system::process_status; + _ = system::wait(copy, &mut status); + t.expects(status.exited && status.code == 5); + } + + @test def ignored_signals_do_nothing_until_restored(t: &mut tester): void { + t.expects(system::ignore(system::signal::user1) == 0); + t.expects(((dispositions("SigIgn") >> 9) & 1) == 1); + t.expects(system::raise(system::signal::user1) == 0); + safe_point(); + + t.expects(system::restore(system::signal::user1) == 0); + t.expects(((dispositions("SigIgn") >> 9) & 1) == 0); + t.expects(raised_in_copy(system::signal::user1) == 10); + + # Restoring a handled signal stops its handler running. + var count := 0; + t.expects(system::handle(system::signal::user2, def(s: system::signal) { count++; }) == 0); + t.expects(system::ignore(system::signal::user2) == 0); + t.expects(system::raise(system::signal::user2) == 0); + safe_point(); + t.expects(count == 0 && ((dispositions("SigCgt") >> 11) & 1) == 0); + } +} + +@test def kill_and_stop_cannot_be_handled_nor_child_ignored(t: &mut tester): void { + val nothing_done := def(s: system::signal) {}; + t.expects(system::error_of(system::handle(system::signal::kill, nothing_done)) == io_error::invalid); + t.expects(system::error_of(system::handle(system::signal::stop, nothing_done)) == io_error::invalid); + t.expects(system::error_of(system::ignore(system::signal::kill)) == io_error::invalid); + t.expects(system::error_of(system::ignore(system::signal::stop)) == io_error::invalid); + t.expects(system::error_of(system::ignore(system::signal::child)) == io_error::invalid); +} + +when os == linux { + @test def signals_watched_for_wait_to_be_asked_for(t: &mut tester): void { + t.expects(system::watch(system::signal::user1) == 0); + t.expects(((dispositions("SigCgt") >> 9) & 1) == 1); + t.expects(system::watched() == 0); + _ = system::raise(system::signal::user1); + safe_point(); + t.expects(system::watched() == 1u << 10); + t.expects(system::watched() == 0); + + # A handled signal is not given, and one watched for waits while the handlers + # run. + var count := 0; + t.expects(system::handle(system::signal::user2, def(s: system::signal) { count++; }) == 0); + _ = system::raise(system::signal::user1); + _ = system::raise(system::signal::user2); + safe_point(); + t.expects(count == 1); + t.expects(system::watched() == 1u << 10); + + # Handling a signal watched for stops it being watched for. + t.expects(system::handle(system::signal::user1, def(s: system::signal) { count++; }) == 0); + _ = system::raise(system::signal::user1); + safe_point(); + t.expects(count == 2 && system::watched() == 0); + t.expects(system::error_of(system::watch(system::signal::kill)) == io_error::invalid); + t.expects(system::error_of(system::watch(system::signal::stop)) == io_error::invalid); + } +} + +@test def handlers_run_at_the_next_safe_point(t: &mut tester): void { + var count := 0; + t.expects(system::handle(system::signal::user1, def(s: system::signal) { count++; }) == 0); + _ = system::raise(system::signal::user1); + t.expects(count == 0); + safe_point(); + t.expects(count == 1); + + # Signals that come together are handled once each. + _ = system::raise(system::signal::user1); + _ = system::raise(system::signal::user1); + safe_point(); + t.expects(count == 2); + + # A loop of the program's own runs the handler as it goes round. + var stopping := false; + t.expects(system::handle(system::signal::user2, def(s: system::signal) { stopping = true; }) == 0); + _ = system::raise(system::signal::user2); + var passes := 0; + while !stopping { + passes++; + } + t.expects(passes == 1); +} + +when os == linux { + @test def a_loop_calling_nothing_is_ended_by_its_safe_points(t: &mut tester): void { + var flag := false; + t.expects(system::handle(system::signal::user1, def(s: system::signal) { flag = true; }) == 0); + val program := system::getpid(); + val copy := system::fork(); + if copy == 0 { + _ = system::kill(program, system::signal::user1); + system::exit(0); + } + + while !flag {} + var status: system::process_status; + _ = system::wait(copy, &mut status); + t.expects(flag && status.exited); + } +} + +@test def vectors_held_across_a_safe_point_keep_their_lanes(t: &mut tester): void { + # The handler works vectors of its own, in the registers the loop holds its + # sums in, which the safe point keeps whole for it: 16 bytes, and 32 where the + # loop's code has AVX. + var ran := 0; + t.expects(system::handle(system::signal::user1, def(s: system::signal) { + var noise := f32x8::splat(-1.0); + var bytes := u32x4::splat(7); + for _ in 0..4 { + noise = noise * noise + f32x8::splat(3.0); + bytes = bytes * bytes; + } + if noise.sum() > 0.0 && bytes.sum() != 0 { + ran++; + } + }) == 0); + # Raised before the loop, which calls nothing, so the handler runs at its + # first pass's safe point, the sums in registers. + _ = system::raise(system::signal::user1); + var narrow := u32x4::splat(0); + var wide := f32x8::splat(0.0); + for i in 0..100u { + narrow = narrow + u32x4::splat(i as u32); + wide = wide + f32x8::splat(1.0); + } + t.expects(ran == 1 && narrow.sum() == 4 * 4950 && wide.sum() == 800.0); +} + +@test def handlers_do_not_nest(t: &mut tester): void { + var depth := 0; + var deepest := 0; + var runs := 0; + t.expects(system::handle(system::signal::user1, def(s: system::signal) { + depth++; + runs++; + deepest = depth > deepest ? depth : deepest; + if runs == 1 { + _ = system::raise(system::signal::user1); + safe_point(); + } + depth--; + }) == 0); + + _ = system::raise(system::signal::user1); + safe_point(); + t.expects(runs == 2 && deepest == 1); +} + +when os == linux { + @test def a_wait_a_handler_interrupts_fails_with_interrupted(t: &mut tester): void { + var count := 0; + t.expects(system::handle(system::signal::user1, def(s: system::signal) { count++; }) == 0); + val copy := signalled_once_asleep(system::signal::user1); + + # The handler has run by the time the wait ends. + var status: system::process_status; + val waited := system::wait(copy, &mut status); + t.expects(system::error_of(waited) == io_error::interrupted && count == 1); + + _ = system::kill(copy, system::signal::kill); + t.expects(system::wait(copy, &mut status) == copy && !status.exited && status.signal == 9); + } + + @test def pause_returns_once_a_handler_has_run(t: &mut tester): void { + var count := 0; + t.expects(system::handle(system::signal::user1, def(s: system::signal) { count++; }) == 0); + + # A signal sent just before is not missed. + _ = system::raise(system::signal::user1); + system::pause(); + t.expects(count == 1); + + # One sent while it waits ends the wait. + val copy := signalled_once_asleep(system::signal::user1); + system::pause(); + t.expects(count == 2); + + var status: system::process_status; + _ = system::kill(copy, system::signal::kill); + _ = system::wait(copy, &mut status); + } + + @test def exit_in_a_handler_stops_the_program(t: &mut tester): void { + val copy := system::fork(); + if copy == 0 { + _ = system::handle(system::signal::user1, def(s: system::signal) { system::exit(7); }); + _ = system::raise(system::signal::user1); + safe_point(); + system::exit(0); + } + + var status: system::process_status; + _ = system::wait(copy, &mut status); + t.expects(status.exited && status.code == 7); + } +} + +@test def a_reader_keeps_what_a_signal_cut_short(t: &mut tester): void { + # A line cut short is given whole by the next read. + var lines := io::reader_of(halting { first = "hel", rest = "lo\nworld" }); + t.expects(lines.read_line() is none && is_interrupted(lines.error)); + val line := lines.read_line() else { t.expects(false); return; }; + t.expects(line.view() == "hello" && lines.error is none); + val last := lines.read_line() else { t.expects(false); return; }; + t.expects(last.view() == "world"); + + # So are bytes asked for, and the rest of the input. + var bytes := io::reader_of(halting { first = "0123", rest = "456789" }); + t.expects(bytes.read_exactly(6) is error); + val six := bytes.read_exactly(6) else (_) { t.expects(false); return; }; + t.expects(six.view() == "012345"); + + var rest := io::reader_of(halting { first = "ab", rest = "cd" }); + t.expects(rest.read_all() is error); + val all := rest.read_all() else (_) { t.expects(false); return; }; + t.expects(all.view() == "abcd"); +} + +when os == windows { + # Runs a copy of the program that puts back what the system does with a signal, + # then sends it to itself, giving the signal that stopped the copy, or zero where + # the copy went on and exited. Windows stops a program by a signal's default with + # 128 more than its number, or by `interrupt` as the console's Ctrl-C does, which + # is the signal itself. + def raised_in_copy(sent: system::signal): i32 { + val status := copied(def() { + _ = system::restore(sent); + _ = system::raise(sent); + safe_point(); + }); + if !status.exited { + return status.signal; + } + return status.code > 128 && status.code < 192 ? status.code - 128 : 0; + } + + # Starts a thread that sends the program a signal once a little time has passed. + # The thread is given the signal, which it owns, since it outlives this call. + def sent_soon(sent: system::signal): result, io_error> { + return thread::spawn_with(def(which: system::signal) { + _ = system::sleep(50000000); + _ = system::raise(which); + }, sent); + } + + @test def signals_have_the_numbers_of_the_system(t: &mut tester): void { + # Those a program may handle are noted under their numbers, and each handler + # is given the signal that came. + val members: system::signal[12] = [ + system::signal::hangup, system::signal::interrupt, system::signal::quit, system::signal::user1, + system::signal::user2, system::signal::pipe, system::signal::alarm, system::signal::terminate, + system::signal::child, system::signal::resume, system::signal::suspend, system::signal::resized + ]; + val numbers: u64[12] = [1, 2, 3, 10, 12, 13, 14, 15, 17, 18, 20, 28]; + var came := system::signal::kill; + for i in 0..members.length { + t.expects(system::handle(members[i], def(s: system::signal) { came = s; }) == 0); + t.expects(system::raise(members[i]) == 0); + safe_point(); + t.expects(came == members[i]); + t.expects(system::watch(members[i]) == 0 && system::raise(members[i]) == 0); + t.expects(system::watched() == 1u << numbers[i]); + t.expects(system::restore(members[i]) == 0); + } + + # What stops a program by default stops a copy with its number. + t.expects(raised_in_copy(system::signal::hangup) == 1); + t.expects(raised_in_copy(system::signal::interrupt) == 2); + t.expects(raised_in_copy(system::signal::kill) == 9); + t.expects(raised_in_copy(system::signal::user1) == 10); + t.expects(raised_in_copy(system::signal::user2) == 12); + t.expects(raised_in_copy(system::signal::pipe) == 13); + t.expects(raised_in_copy(system::signal::alarm) == 14); + t.expects(raised_in_copy(system::signal::terminate) == 15); + + # Windows cannot pause a program. + t.expects(system::error_of(system::raise(system::signal::stop)) == io_error::unsupported); + } + + @test def ignored_signals_do_nothing_until_restored(t: &mut tester): void { + t.expects(system::ignore(system::signal::user1) == 0); + t.expects(system::raise(system::signal::user1) == 0); + safe_point(); + + t.expects(system::restore(system::signal::user1) == 0); + t.expects(raised_in_copy(system::signal::user1) == 10); + + # Restoring a handled signal stops its handler running. + var count := 0; + t.expects(system::handle(system::signal::user2, def(s: system::signal) { count++; }) == 0); + t.expects(system::ignore(system::signal::user2) == 0); + t.expects(system::raise(system::signal::user2) == 0); + safe_point(); + t.expects(count == 0); + } + + @test def signals_watched_for_wait_to_be_asked_for(t: &mut tester): void { + t.expects(system::watch(system::signal::user1) == 0); + t.expects(system::watched() == 0); + _ = system::raise(system::signal::user1); + safe_point(); + t.expects(system::watched() == 1u << 10); + t.expects(system::watched() == 0); + + # A handled signal is not given, and one watched for waits while the handlers + # run. + var count := 0; + t.expects(system::handle(system::signal::user2, def(s: system::signal) { count++; }) == 0); + _ = system::raise(system::signal::user1); + _ = system::raise(system::signal::user2); + safe_point(); + t.expects(count == 1); + t.expects(system::watched() == 1u << 10); + + # Handling a signal watched for stops it being watched for. + t.expects(system::handle(system::signal::user1, def(s: system::signal) { count++; }) == 0); + _ = system::raise(system::signal::user1); + safe_point(); + t.expects(count == 2 && system::watched() == 0); + t.expects(system::error_of(system::watch(system::signal::kill)) == io_error::invalid); + t.expects(system::error_of(system::watch(system::signal::stop)) == io_error::invalid); + } + + @test def a_loop_calling_nothing_is_ended_by_its_safe_points(t: &mut tester): void { + var flag := false; + t.expects(system::handle(system::signal::user1, def(s: system::signal) { flag = true; }) == 0); + var sender := sent_soon(system::signal::user1) else (_) { t.expects(false); return; }; + while !flag {} + sender.close(); + t.expects(flag); + } + + @test def a_wait_a_handler_interrupts_fails_with_interrupted(t: &mut tester): void { + var count := 0; + t.expects(system::handle(system::signal::user1, def(s: system::signal) { count++; }) == 0); + var pinger := process::command::new("ping"); + pinger.arguments(["-n", "30", "127.0.0.1"]); + pinger.output(process::stdio::none); + var running := pinger.spawn() else (_) { t.expects(false); return; }; + var sender := sent_soon(system::signal::user1) else (_) { t.expects(false); return; }; + + # The handler has run by the time the wait ends. + var status: system::process_status; + val waited := system::wait(running.id as i64, &mut status); + t.expects(system::error_of(waited) == io_error::interrupted && count == 1); + sender.close(); + + t.expects(running.kill() is value); + val stopped := running.wait() else (_) { t.expects(false); return; }; + t.expects(stopped == process::status { signaled = 9 }); + } + + @test def pause_returns_once_a_handler_has_run(t: &mut tester): void { + var count := 0; + t.expects(system::handle(system::signal::user1, def(s: system::signal) { count++; }) == 0); + + # A signal sent just before is not missed. + _ = system::raise(system::signal::user1); + system::pause(); + t.expects(count == 1); + + # One sent while it waits ends the wait. + var sender := sent_soon(system::signal::user1) else (_) { t.expects(false); return; }; + system::pause(); + t.expects(count == 2); + sender.close(); + } + + @test def exit_in_a_handler_stops_the_program(t: &mut tester): void { + val status := copied(def() { + _ = system::handle(system::signal::user1, def(s: system::signal) { system::exit(7); }); + _ = system::raise(system::signal::user1); + safe_point(); + }); + t.expects(status.exited && status.code == 7); + } +} diff --git a/tests/core/simd.sakura b/tests/core/simd.sakura new file mode 100644 index 00000000..dbadd6f1 --- /dev/null +++ b/tests/core/simd.sakura @@ -0,0 +1,431 @@ +# Tests of std's vectors: each operation of each type of lane against what the +# number's own operator or `std::math` gives lane by lane, to the bit, masks and +# selecting, loading and storing at the ends of views, and what stops the +# program. Built natively, the vectors are worked with the processor's vector +# instructions where it has them, so the same tests check those against the +# lanes; `SAKURA_CPU=x86-64` runs them as on a processor with SSE2 alone. The +# corpus program `simd_lanes_agree_everywhere_1` compares their bits between the +# compilers, the machine, executables, and constants. +import system; +import std::math; +import std::testing; + + +# Whether running the function stops the program, in a copy of the program that +# writes nothing. +def simd_stops(run: def(): void): bool { + when os == windows { + val stopped := copied(run); + return !(stopped.exited && stopped.code == 0); + } + val child := fork(); + if child == 0 { + val out: fd = fd::stdout; + val err: fd = fd::stderr; + out.close(); + err.close(); + run(); + exit(0); + } + var status: process_status; + return wait(child, &mut status) >= 0 && !(status.exited && status.code == 0); +} + +# Whether two values have the same bytes, as NaNs of the same bits do. +def same_lane_bits(a: &T, b: &T): bool { + val x := a as *u8; + val y := b as *u8; + for k in 0..size_of::() { + return false if x[k] != y[k]; + } + return true; +} + +var lane_seed: u64 = 0x2545F4914F6CDD1D; + +def next_bits(): u64 { + lane_seed = lane_seed ^ (lane_seed << 13); + lane_seed = lane_seed ^ (lane_seed >> 7); + lane_seed = lane_seed ^ (lane_seed << 17); + return lane_seed; +} + +# A lane worth testing: one of the edges of its type, or something between. +def random_lane(): L where L: numeric, ordered, zeroable { + val pick := next_bits() % 12; + if const L is real { + val edges: f64[9] = [0.0, -0.0, 1.0, -1.5, 2.5, -2.5, 1e-310, 0.75, -3.0]; + return edges[pick as u64] as L if pick < 9; + return math::infinity::() if pick == 9; + return math::nan::() if pick == 10; + return ((next_bits() % 200000) as f64 / 100.0 - 1000.0) as L; + } + if const L is integer { + return pick as L if pick < 2; + return ~(0 as L) if pick == 2; + return ~(0 as L) >> 1 if pick == 3; + var made: L; + val bits := next_bits(); + val p := (&mut made) as *mut u8; + for k in 0..size_of::() { + p[k] = ((bits >> (8 * k)) & 0xFF) as u8; + } + return made; + } + var none: L; + return none; +} + +def random_vector(): simd where L: numeric, ordered, zeroable { + var made: simd; + for i in 0..N { + made[i] = random_lane::(); + } + return made; +} + +# Whether a vector's lanes are those the scalar operation gives each pair of lanes. +def lanes_agree(made: &simd, a: &simd, b: &simd, op: def(L, L): L): bool + where L: numeric, ordered, zeroable { + for i in 0..N { + val want := op(a[i], b[i]); + val got: L = made[i]; + return false if !same_lane_bits(&got, &want); + } + return true; +} + +# Whether a vector's lanes are those the scalar operation gives each lane. +def lanes_agree1(made: &simd, a: &simd, op: def(L): L): bool + where L: numeric, ordered, zeroable { + for i in 0..N { + val want := op(a[i]); + val got: L = made[i]; + return false if !same_lane_bits(&got, &want); + } + return true; +} + +# Whether a mask has the lanes set the scalar comparison holds for. +def mask_agrees(made: &mask, a: &simd, b: &simd, op: def(L, L): bool): bool + where L: numeric, ordered, zeroable { + var bits: u32 = 0; + for i in 0..N { + val holds := op(a[i], b[i]); + return false if made.has(i) != holds; + if holds { + bits = bits | ((1 as u32) << i); + } + } + return made.bits() == bits && made.any() == (bits != 0) && made.count() == count_ones(bits); +} + +# Each operation of a type of lane, against the scalar one, over many vectors. +def all_agree(t: &mut tester): void where L: numeric, ordered, zeroable { + for _ in 0..40 { + val a := random_vector::(); + val b := random_vector::(); + val c := random_vector::(); + t.expects(lanes_agree(&(a + b), &a, &b, def(x: L, y: L): L { return x + y; })); + t.expects(lanes_agree(&(a - b), &a, &b, def(x: L, y: L): L { return x - y; })); + t.expects(lanes_agree(&(a * b), &a, &b, def(x: L, y: L): L { return x * y; })); + t.expects(lanes_agree(&a.min(&b), &a, &b, def(x: L, y: L): L { return math::min(x, y); })); + t.expects(lanes_agree(&a.max(&b), &a, &b, def(x: L, y: L): L { return math::max(x, y); })); + t.expects(lanes_agree1(&(-a), &a, def(x: L): L { return -x; })); + t.expects(mask_agrees(&a.equal(&b), &a, &b, def(x: L, y: L): bool { return x == y; })); + t.expects(mask_agrees(&a.equal(&a), &a, &a, def(x: L, y: L): bool { return x == y; })); + t.expects(mask_agrees(&a.not_equal(&b), &a, &b, def(x: L, y: L): bool { return x != y; })); + t.expects(mask_agrees(&a.less(&b), &a, &b, def(x: L, y: L): bool { return x < y; })); + t.expects(mask_agrees(&a.less_equal(&b), &a, &b, def(x: L, y: L): bool { return x <= y; })); + t.expects(mask_agrees(&a.greater(&b), &a, &b, def(x: L, y: L): bool { return x > y; })); + t.expects(mask_agrees(&a.greater_equal(&b), &a, &b, def(x: L, y: L): bool { return x >= y; })); + val m := a.less(&b); + val chosen := select(m, a, b); + for i in 0..N { + val want: L = m.has(i) ? a[i] : b[i]; + val got: L = chosen[i]; + t.expects(same_lane_bits(&got, &want)); + } + val fused := a.fma(&b, &c); + for i in 0..N { + val x: L = a[i]; + val y: L = b[i]; + val z: L = c[i]; + var want: L; + if const L is real { + want = math::fma(x, y, z); + } else { + want = x * y + z; + } + val got: L = fused[i]; + t.expects(same_lane_bits(&got, &want)); + } + if const L is real { + t.expects(lanes_agree(&(a / b), &a, &b, def(x: L, y: L): L { return x / y; })); + t.expects(lanes_agree1(&a.abs(), &a, def(x: L): L { return math::abs(x); })); + t.expects(lanes_agree1(&a.sqrt(), &a, def(x: L): L { return math::sqrt(x); })); + t.expects(lanes_agree1(&a.floor(), &a, def(x: L): L { return math::floor(x); })); + t.expects(lanes_agree1(&a.ceil(), &a, def(x: L): L { return math::ceil(x); })); + t.expects(lanes_agree1(&a.trunc(), &a, def(x: L): L { return math::trunc(x); })); + t.expects(lanes_agree1(&a.round(), &a, def(x: L): L { return math::round(x); })); + t.expects(lanes_agree1(&a.round_even(), &a, def(x: L): L { return math::round_even(x); })); + } + if const L is integer { + t.expects(lanes_agree(&(a & b), &a, &b, def(x: L, y: L): L { return x & y; })); + t.expects(lanes_agree(&(a | b), &a, &b, def(x: L, y: L): L { return x | y; })); + t.expects(lanes_agree(&(a ^ b), &a, &b, def(x: L, y: L): L { return x ^ y; })); + t.expects(lanes_agree1(&(~a), &a, def(x: L): L { return ~x; })); + val counts: u32[8] = [0, 1, 3, 7, 15, 31, 63, 64]; + val count := counts[next_bits() % 8]; + val left := a << count; + val right := a >> count; + for i in 0..N { + val want_left: L = a[i] << count; + val want_right: L = a[i] >> count; + val got_left: L = left[i]; + val got_right: L = right[i]; + t.expects(same_lane_bits(&got_left, &want_left)); + t.expects(same_lane_bits(&got_right, &want_right)); + } + } + } +} + +@test def every_operation_agrees_with_its_lanes(t: &mut tester): void { + all_agree::(t); + all_agree::(t); + all_agree::(t); + all_agree::(t); + all_agree::(t); + all_agree::(t); + all_agree::(t); + all_agree::(t); + all_agree::(t); + all_agree::(t); + all_agree::(t); + all_agree::(t); +} + +@test def lanes_wrap_and_round_as_their_numbers_do(t: &mut tester): void { + val bytes := u8x16::splat(250) + u8x16::splat(10); + t.expects(bytes[0] == 4 && bytes[15] == 4); + val most := i32x4::splat(0x7FFFFFFF) + i32x4::splat(1); + t.expects(most[2] == -2147483648); + val least := i8x16::splat(-128); + t.expects((-least)[3] == -128 && least.abs()[3] == -128); + t.expects(u16x8::splat(40000).abs()[0] == 40000); + val halves := f32x4::of([0.5, 1.5, 2.5, -2.5]); + val away: f32[4] = [1.0, 2.0, 3.0, -3.0]; + val even: f32[4] = [0.0, 2.0, 2.0, -2.0]; + t.expects(halves.round().lanes() == away); + t.expects(halves.round_even().lanes() == even); + val roots := f64x2::of([2.0, -0.0]).sqrt(); + val root: f64 = roots[0]; + val zero: f64 = roots[1]; + t.expects(root == math::sqrt(2.0) && math::sign_bit(zero)); + val floor: f32 = f32x8::splat(-0.75).floor()[7]; + val ceil: f32 = f32x8::splat(-0.75).ceil()[7]; + t.expects(floor == -1.0 && ceil == 0.0 && math::sign_bit(ceil)); +} + +@test def vector_fma_rounds_once(t: &mut tester): void { + # (1 + 2^-52)(1 - 2^-52) - 1 is -2^-104 exactly, which multiplying then adding + # rounds to 0. + val epsilon := math::epsilon::(); + val fused := f64x2::splat(1.0 + epsilon).fma(&f64x2::splat(1.0 - epsilon), &f64x2::splat(-1.0)); + t.expects(fused[0] == -(epsilon * epsilon) && fused[1] == fused[0]); + val plain := f64x2::splat(1.0 + epsilon) * f64x2::splat(1.0 - epsilon) - f64x2::splat(1.0); + t.expects(plain[0] == 0.0); +} + +@test def least_and_greatest_of_reals_are_ieee_754s(t: &mut tester): void { + val a := f32x4::of([-0.0, 0.0, math::nan::(), 1.0]); + val b := f32x4::of([0.0, -0.0, 1.0, math::nan::()]); + val least := a.min(&b); + val most := a.max(&b); + val small := least.lanes(); + val large := most.lanes(); + t.expects(math::sign_bit(small[0]) && math::sign_bit(small[1])); + t.expects(!math::sign_bit(large[0]) && !math::sign_bit(large[1])); + t.expects(math::is_nan(small[2]) && math::is_nan(small[3]) && math::is_nan(large[2]) && math::is_nan(large[3])); + t.expects(a.equal(&a).bits() == 0b1011); + t.expects(a.not_equal(&a).bits() == 0b0100); +} + +@test def masks_say_which_lanes_hold(t: &mut tester): void { + val v := i16x8::of([1, -2, 3, -4, 5, -6, 7, -8]); + val negative := v.less(&i16x8::splat(0)); + t.expects(negative.bits() == 0b10101010 && negative.count() == 4 && negative.any() && !negative.all()); + t.expects((negative.first() else 99) == 1); + t.expects((~negative).bits() == 0b01010101); + t.expects((negative | ~negative).all() && (negative & ~negative).none()); + val absolute: i16[8] = [1, 2, 3, 4, 5, 6, 7, 8]; + t.expects(select(negative, -v, v).lanes() == absolute); + val wide := u8x32::splat(9).equal(&u8x32::splat(9)); + t.expects(wide.all() && wide.count() == 32 && wide.bits() == 0xFFFFFFFF); + t.expects((u8x32::splat(1).equal(&u8x32::splat(2)).first() else 99) == 99); +} + +@test def vectors_load_and_store_within_views(t: &mut tester): void { + val text: strview = "a vector of sixteen bytes and more"; + val first := u8x16::load(text.view(), 0); + t.expects(first[0] == 'a' as u8 && first[15] == 't' as u8); + val last := u8x16::load(text.view(), text.length - 16); + t.expects(last[15] == 'e' as u8); + if const checking() { + t.expects(simd_stops(def() { val past := u8x16::load("too short".view(), 0); })); + t.expects(simd_stops(def() { val at := u8x16::load("sixteen bytes, 1".view(), 1); })); + } + + var room: f64[6] = [0.0, 0.0, 0.0, 0.0, 0.0, 0.0]; + f64x4::of([1.0, 2.0, 3.0, 4.0]).store(room[:], 2); + val stored: f64[6] = [0.0, 0.0, 1.0, 2.0, 3.0, 4.0]; + t.expects(room == stored); + if const checking() { + t.expects(simd_stops(def() { var little: f64[3]; f64x2::splat(1.0).store(little[:], 2); })); + } +} + +@test def lanes_are_reached_moved_and_converted(t: &mut tester): void { + var v := i32x4::of([10, 20, 30, 40]); + v[2] = 33; + val written: i32[4] = [10, 20, 33, 40]; + val reversed: i32[4] = [40, 33, 20, 10]; + val big: f32 = 3e9; + val converted: i32[4] = [1, -1, big as i32, 0]; + t.expects(v[2] == 33 && v.lanes() == written); + t.expects(v.shuffle([3, 2, 1, 0]).lanes() == reversed); + t.expects(v.sum() == 103 && v.product() == 10 * 20 * 33 * 40 && v.smallest() == 10 && v.largest() == 40); + t.expects(f32x4::of([1.9, -1.9, 3e9, math::nan::()]).convert::().lanes() == converted); + val ones := f32x4::splat(1.0).bits::(); + t.expects(ones[0] == 0x3F800000); + t.expects(v == i32x4::of([10, 20, 33, 40]) && v != i32x4::splat(0)); + if const checking() { + t.expects(simd_stops(def() { val w := i32x4::splat(1); val x := w[4]; })); + } +} + +@test def integer_lanes_divided_by_zero_stop(t: &mut tester): void { + val threes: i32[4] = [3, 3, 3, 3]; + val ones: i32[4] = [-1, -1, -1, -1]; + t.expects((i32x4::splat(7) / i32x4::splat(2)).lanes() == threes); + t.expects((i32x4::splat(-7) % i32x4::splat(2)).lanes() == ones); + t.expects(simd_stops(def() { val q := i32x4::splat(7) / i32x4::of([1, 1, 0, 1]); })); + val infinite: f32 = (f32x4::splat(1.0) / f32x4::splat(0.0))[0]; + t.expects(math::is_infinite(infinite)); +} + +# Whether converting each lane agrees with `as`, and with the lanes' own bits. +def converts_as_lanes(a: &simd): bool + where L: numeric, ordered, zeroable where M: numeric, ordered, zeroable { + val made := a.convert::(); + for i in 0..N { + val want: M = a[i] as M; + val got: M = made[i]; + return false if !same_lane_bits(&got, &want); + } + return true; +} + +# Whether widening each half agrees with `as` of its lanes. +def widens_as_lanes(a: &simd): bool + where L: numeric, ordered, zeroable where M: numeric, ordered, zeroable { + val low := a.widened::(); + val high := a.widened_high::(); + for i in 0..N / 2 { + val want_low: M = a[i] as M; + val want_high: M = a[N / 2 + i] as M; + val got_low: M = low[i]; + val got_high: M = high[i]; + return false if !same_lane_bits(&got_low, &want_low) || !same_lane_bits(&got_high, &want_high); + } + return true; +} + +# Whether reductions agree with the lanes worked one at a time, lane 0 first. +def reduces_as_lanes(a: &simd): bool where L: numeric, ordered, zeroable { + var sum: L = a[0]; + var least: L = a[0]; + var most: L = a[0]; + for i in 1..N { + val lane: L = a[i]; + sum = sum + lane; + least = least < lane ? least : lane; + most = most > lane ? most : lane; + } + val got_sum: L = a.sum(); + if const L is integer { + val got_least: L = a.smallest(); + val got_most: L = a.largest(); + return same_lane_bits(&got_sum, &sum) && got_least == least && got_most == most; + } + return same_lane_bits(&got_sum, &sum); +} + +@test def reshaping_agrees_with_its_lanes(t: &mut tester): void { + for _ in 0..8 { + t.expects(converts_as_lanes::(&random_vector::())); + t.expects(converts_as_lanes::(&random_vector::())); + t.expects(converts_as_lanes::(&random_vector::())); + t.expects(converts_as_lanes::(&random_vector::())); + t.expects(converts_as_lanes::(&random_vector::())); + t.expects(converts_as_lanes::(&random_vector::())); + t.expects(converts_as_lanes::(&random_vector::())); + t.expects(converts_as_lanes::(&random_vector::())); + t.expects(converts_as_lanes::(&random_vector::())); + t.expects(converts_as_lanes::(&random_vector::())); + t.expects(converts_as_lanes::(&random_vector::())); + t.expects(converts_as_lanes::(&random_vector::())); + t.expects(converts_as_lanes::(&random_vector::())); + t.expects(widens_as_lanes::(&random_vector::())); + t.expects(widens_as_lanes::(&random_vector::())); + t.expects(widens_as_lanes::(&random_vector::())); + t.expects(widens_as_lanes::(&random_vector::())); + t.expects(reduces_as_lanes::(&random_vector::())); + t.expects(reduces_as_lanes::(&random_vector::())); + t.expects(reduces_as_lanes::(&random_vector::())); + t.expects(reduces_as_lanes::(&random_vector::())); + t.expects(reduces_as_lanes::(&random_vector::())); + t.expects(reduces_as_lanes::(&random_vector::())); + t.expects(reduces_as_lanes::(&random_vector::())); + } + # Narrowing saturates, as packing does. + val words := i16x8::of([-300, 300, 1, -1, 32767, -32768, 255, 0]); + val signed: i8[16] = [-128, 127, 1, -1, 127, -128, 127, 0, 5, 5, 5, 5, 5, 5, 5, 5]; + val unsigned: u8[16] = [0, 255, 1, 0, 255, 0, 255, 0, 255, 255, 255, 255, 255, 255, 255, 255]; + t.expects(words.narrowed::(&i16x8::splat(5)).lanes() == signed); + t.expects(words.narrowed::(&i16x8::splat(1000)).lanes() == unsigned); + val big: u16[4] = [65535, 7, 65535, 7]; + t.expects(u32x4::of([70000, 7, 70000, 7]).narrowed::(&u32x4::of([70000, 7, 70000, 7])).lanes()[0:4] == big[0:4]); + # Halves taken apart and joined. + val eight := u32x8::of([1, 2, 3, 4, 5, 6, 7, 8]); + val first: u32[4] = [1, 2, 3, 4]; + val second: u32[4] = [5, 6, 7, 8]; + t.expects(eight.low().lanes() == first && eight.high().lanes() == second); + t.expects(simd::join(eight.low(), eight.high()) == eight); + # Rounding halves away from zero keeps the sign of what it does not move. + val halves := f64x4::of([-0.3, 0.49999999999999994, -2.5, 4503599627370495.5]).round(); + t.expects(math::sign_bit(halves[0]) && halves[1] == 0.0 && halves[2] == -3.0 && halves[3] == 4503599627370496.0); + # Gathered and scattered by places, a later lane's write lasting. + val table: f64[6] = [0.5, 1.5, 2.5, 3.5, 4.5, 5.5]; + val gathered := f64x4::gather(table[0:6], i32x4::of([5, 0, 5, 2])); + t.expects(gathered == f64x4::of([5.5, 0.5, 5.5, 2.5])); + var into: i32[8]; + i32x8::of([1, 2, 3, 4, 5, 6, 7, 8]).scatter(into[0:8], i32x8::of([7, 6, 5, 4, 3, 2, 1, 7])); + t.expects(into[7] == 8 && into[1] == 7 && into[0] == 0); + # Shuffles of each size, against reading each lane. + val order: u8[8] = [7, 0, 6, 1, 5, 2, 4, 3]; + val floats := random_vector::(); + val moved := floats.shuffle(order); + for i in 0..8u { + val want: f32 = floats[order[i] as u64]; + val got: f32 = moved[i]; + t.expects(same_lane_bits(&got, &want)); + } + val bytes := random_vector::(); + t.expects(bytes.shuffle([15, 14, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0])[0] == bytes[15]); + if const checking() { + t.expects(simd_stops(def() { val wrong := i32x4::splat(1).shuffle([0, 1, 4, 2]); })); + t.expects(simd_stops(def() { val far := f64x4::gather(table[0:6], i32x4::of([0, 6, 1, 2])); })); + } +} diff --git a/tests/core/swar.sakura b/tests/core/swar.sakura new file mode 100644 index 00000000..495152ec --- /dev/null +++ b/tests/core/swar.sakura @@ -0,0 +1,315 @@ +# Tests of words of bytes, `core::swar`: every test against the same choice made a +# byte at a time, for every value in every place, and the text functions that go +# by words against their loops a byte at a time, for every length to past a few +# words, wherever the bytes they look for fall. + +import std::serial; +import core::swar; +import std::testing; + + +var swar_seed: u64 = 0x2545F4914F6CDD1D; + +def swar_random(): u64 { + swar_seed = swar_seed ^ (swar_seed << 13); + swar_seed = swar_seed ^ (swar_seed >> 7); + swar_seed = swar_seed ^ (swar_seed << 17); + return swar_seed; +} + +# What a search found, or a number where it found nothing. +def swar_or(found: maybe, none: u64): u64 { + if found is some(at) { + return at; + } + return none; +} + +# The mask choosing the bytes of a word a test chooses, made a byte at a time. +def swar_choice(word: u64, test: u64, a: u8, b: u8): u64 { + var mask: u64 = 0; + for k in 0..8u { + val byte := ((word >> (k * 8)) & 0xFF) as u8; + val chosen := match test { + 0 => byte == 0, + 1 => byte == a, + 2 => byte < a, + 3 => byte > a, + 4 => byte >= a && byte <= b, + else => byte < 0x80, + }; + if chosen { + mask = mask | (0x80u << (k * 8)); + } + } + return mask; +} + +# The same choice by words. +def swar_chosen(word: swar::bytes8, test: u64, a: u8, b: u8): u64 { + return match test { + 0 => word.zero(), + 1 => word.equal(a), + 2 => word.below(a), + 3 => word.above(a), + 4 => word.within(a, b), + else => word.ascii(), + }; +} + +@test def swar_tests_choose_exactly_the_bytes_they_say(t: &mut tester): void { + # Bounds at their edges, and bytes the tests are given. + val bounds: u8[12] = [0, 1, 9, 13, 32, 127, 128, 129, 200, 254, 255, '0']; + var wrong: u64 = 0; + for place in 0..8u { + for value in 0..256u { + # Each value in each place, with the other places random, and sometimes a + # copy of the value, so a borrow from one byte would reach the next. + var word := swar_random(); + if (value & 3) == 0 { + word = word & 0x00FF00FF00FF00FF; + } + word = (word & ~(0xFFu << (place * 8))) | (value << (place * 8)); + if swar_chosen(word, 0, 0, 0) != swar_choice(word, 0, 0, 0) { wrong++; } + if swar_chosen(word, 5, 0, 0) != swar_choice(word, 5, 0, 0) { wrong++; } + for i in 0..12u { + val a := bounds[i]; + val b := bounds[(i + 3) % 12]; + for test in 1..5u { + if swar_chosen(word, test, a, b) != swar_choice(word, test, a, b) { wrong++; } + } + # The byte itself is equal, and within itself. + if swar_chosen(word, 1, value as u8, 0) != swar_choice(word, 1, value as u8, 0) { wrong++; } + if swar_chosen(word, 4, value as u8, value as u8) != swar_choice(word, 4, value as u8, value as u8) { wrong++; } + } + } + } + t.expects(wrong == 0); +} + +@test def swar_masks_say_where_and_how_many_they_choose(t: &mut tester): void { + var wrong: u64 = 0; + for bits in 0..256u { + var mask: u64 = 0; + var spread: u64 = 0; + var first: u64 = 8; + var last: u64 = 8; + var count: u64 = 0; + for k in 0..8u { + if ((bits >> k) & 1) != 0 { + mask = mask | (0x80u << (k * 8)); + spread = spread | (0xFFu << (k * 8)); + first = first == 8 ? k : first; + last = k; + count++; + } + } + val chosen: swar::mask8 = mask; + val rest: u64 = first == 8 ? 0 : mask & ~(0x80u << (first * 8)); + if chosen.any() != (bits != 0) { wrong++; } + if chosen.first() != first || chosen.last() != last || chosen.count() != count { wrong++; } + if chosen.rest() != rest || chosen.spread() != spread { wrong++; } + } + t.expects(wrong == 0); + for count in 0..10u { + val want: u64 = count >= 8 ? 0x8080808080808080 : 0x8080808080808080 & ((1u << (count * 8)) - 1); + t.expects(swar::mask8::leading(count) == want); + } +} + +@test def swar_words_change_case_and_read_digits(t: &mut tester): void { + var wrong: u64 = 0; + for place in 0..8u { + for value in 0..256u { + val word: swar::bytes8 = (swar_random() & ~(0xFFu << (place * 8))) | (value << (place * 8)); + for k in 0..8u { + val byte := word.byte(k); + if word.upper().byte(k) != byte.to_upper || word.lower().byte(k) != byte.to_lower { wrong++; } + } + } + } + t.expects(wrong == 0); + t.expects(swar::repeat(0xAB) == 0xABABABABABABABAB && swar::repeat(0) == 0); + t.expects(swar::choose(0x0000800000000080, 0x1111111111111111, 0x2222222222222222) == 0x2222112222222211); + + t.expects(swar_or(swar::load("20261016", 0).digits(), 1) == 20261016); + t.expects(swar_or(swar::load("00000000", 0).digits(), 1) == 0); + t.expects(swar_or(swar::load("99999999", 0).digits(), 1) == 99999999); + t.expects(swar_or(swar::load("01234567", 0).digits(), 1) == 1234567); + # Each place not a digit in turn, by a byte on either side of the digits. + for place in 0..8u { + for byte in ['/' as u8, ':', 'a', ' ', 0, 0xB0] { + var text := string::from("12345678", nothing {}); + text[place] = byte; + t.expects(swar::load(text.view(), 0).digits() is none); + } + } +} + +@test def swar_loads_read_only_the_bytes_of_the_view(t: &mut tester): void { + val buffer: strview = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"; + for start in 0..8u { + for length in 1..12u { + # A view whose next byte is set, so a read past its end would show. + val view := buffer.substr(start, length); + for at in 0..length { + var want: u64 = 0; + val left := length - at; + for k in 0..(left < 8 ? left : 8) { + want = want | (('A' as u64 + start + at + k) << (k * 8)); + } + t.expects(swar::load_last(view, at) == want); + if left >= 8 { + t.expects(swar::load(view, at) == want); + } + } + } + } + t.expects(swar::load_last("".data, 0) == 0); +} + +# Text of a length over a few bytes, so each is found often, after `start` bytes +# of a buffer, which then views it. +def swar_text(buffer: &mut string, start: u64, length: u64, alphabet: strview): strview { + buffer.clear(); + for _ in 0..start { + buffer.push('#'); + } + for _ in 0..length { + buffer.push(alphabet[swar_random() % alphabet.length]); + } + buffer.push('#'); + return buffer.view().substr(start, length); +} + +@test def text_functions_find_what_a_byte_at_a_time_finds(t: &mut tester): void { + var buffer := string::new(nothing {}); + var wrong: u64 = 0; + for length in 0..41u { + for start in 0..8u { + val text := swar_text(&mut buffer, start, length, length % 3 == 0 ? "abcdefgh" : "ab"); + for byte in ['a' as u8, 'b', 'h', '#', 0] { + var first: u64 = length; + var last: u64 = length; + var count: u64 = 0; + for k in 0..length { + if text[k] == byte { + first = first == length ? k : first; + last = k; + count++; + } + } + val found := text.index_of(&byte); + val found_last := text.last_index_of(&byte); + if swar_or(found, length) != first { wrong++; } + if swar_or(found_last, length) != last { wrong++; } + if text.count_of(&byte) != count || text.contains(&byte) != (count != 0) { wrong++; } + } + + # Runs of the text and others, and any of a few bytes. + for size in 0..6u { + var sought := string::new(nothing {}); + val from := length > size ? swar_random() % (length - size + 1) : 0; + for k in 0..size { + sought.push(k + from < length && (swar_random() & 3) != 0 ? text[k + from] : 'a'); + } + var want: u64 = length + 1; + if sought.length <= length { + for at in 0..(length - sought.length + 1) { + if text.substr(at, sought.length) == sought.view() { + want = at; + break; + } + } + } + val got := text.find(sought.view()); + if swar_or(got, length + 1) != want { wrong++; } + + var any: u64 = length; + for at in 0..length { + if sought.view().contains(&text[at]) { + any = at; + break; + } + } + val got_any := text.find_any(sought.view()); + if swar_or(got_any, length) != any { wrong++; } + } + } + } + t.expects(wrong == 0); + + # More than four bytes are looked for through a set. + val text: strview = "the quick brown fox jumps over the lazy dog"; + t.expects(swar_or(text.find_any("xyzq!"), 99) == 4 && text.find_any("QWERTY") is none); + t.expects(swar_or(text.find("the"), 99) == 0 && swar_or(text.find("lazy"), 99) == 35); + t.expects(swar_or(text.find("dog"), 99) == 40 && text.find("dogs") is none); + t.expects(swar_or(text.find(""), 99) == 0 && swar_or("".find(""), 99) == 0 && "".find("a") is none); +} + +@test def text_functions_change_and_check_as_a_byte_at_a_time_does(t: &mut tester): void { + var buffer := string::new(nothing {}); + var wrong: u64 = 0; + for length in 0..41u { + for start in 0..8u { + val text := swar_text(&mut buffer, start, length, "aZz@[`{ \t\n\r\x0B\x0C9"); + val upper := text.upper(); + val lower := text.lower(); + for k in 0..length { + if upper[k] != text[k].to_upper || lower[k] != text[k].to_lower { wrong++; } + } + if upper.length != length || lower.length != length { wrong++; } + + # Trimming, where the text is mostly whitespace. + var left: u64 = 0; + while left < length && text[left].is_space { left++; } + var right := length; + while right > 0 && text[right - 1].is_space { right--; } + if text.ltrim() != text.substr(left, length - left) { wrong++; } + if text.rtrim() != text.substr(0, right) { wrong++; } + if text.trim() != (left < right ? text.substr(left, right - left) : text.substr(0, 0)) { wrong++; } + + # ASCII, and a byte past it in each place. + if !text.is_ascii() || !serial::is_utf8(text) { wrong++; } + for place in 0..length { + var wide := string::from(text, nothing {}); + wide[place] = 0x80 | (place as u8); + if wide.view().is_ascii() || serial::is_utf8(wide.view()) { wrong++; } + wide[place] = 0xC3; + if place + 1 < length { + wide[place + 1] = 0xA9; + if !serial::is_utf8(wide.view()) { wrong++; } + } + } + } + } + t.expects(wrong == 0); + + # Whitespace of every length on either side. + for spaces in 0..20u { + var text := string::new(nothing {}); + for k in 0..spaces { text.push(k % 3 == 0 ? '\t' : ' '); } + text.append("word"); + for k in 0..spaces { text.push(k % 2 == 0 ? '\n' : ' '); } + t.expects(text.view().trim() == "word" && text.view().ltrim().length == 4 + spaces && text.view().rtrim().length == 4 + spaces); + } +} + +# Where a run of text is found, while compiling and while running. +def swar_found(text: strview, sought: strview): u64 { + return swar_or(text.find(sought), text.length); +} + +def swar_date(text: strview): u64 { + return swar_or(swar::load(text, 0).digits(), 0); +} + +const swar_compiled_place: u64 = swar_found("a needle in a haystack of needles", "haystack"); +const swar_compiled_date: u64 = swar_date("20261016"); +const swar_compiled_count: u64 = "one\ntwo\nthree\nfour\n".count_of(&'\n'); + +@test def swar_words_work_alike_while_compiling(t: &mut tester): void { + t.expects(swar_compiled_place == 14 && swar_compiled_place == swar_found("a needle in a haystack of needles", "haystack")); + t.expects(swar_compiled_date == 20261016 && swar_compiled_date == swar_date("20261016")); + t.expects(swar_compiled_count == 4); +} diff --git a/tests/core/text.sakura b/tests/core/text.sakura new file mode 100644 index 00000000..5911d61b --- /dev/null +++ b/tests/core/text.sakura @@ -0,0 +1,35 @@ +# Tests of text: what a literal is where nothing asks for a type, and what +# trimming gives of a view and of a string. +import std::testing; + + +# Whether the type is `strview`, which a literal is where nothing asks otherwise. +def is_view(value: &T): bool { + return name_of::() == "strview"; +} + +@test def text_literals_are_views(t: &mut tester): void { + val plain := "abc"; + val built := $"abc{1}"; + t.expects(is_view(&plain) && !is_view(&built)); + t.expects(is_view(&"abc".trim()) && "abc".length == 3); + + # Each trimmed literal views its own bytes, which last as long as the program. + val first := " x ".trim(); + val second := " y ".trim(); + t.expects(first == "x" && second == "y"); +} + +@test def text_trims_to_what_it_was_given(t: &mut tester): void { + val view: strview = " \t both \n"; + t.expects(view.trim() == "both" && view.ltrim() == "both \n" && view.rtrim() == " \t both"); + t.expects(is_view(&view.trim())); + + # A string's trims are strings of their own, which leave it as it was. + val owned := string::from(" held ", nothing {}); + var trimmed := owned.trim(); + trimmed.append("!"); + t.expects(trimmed.view() == "held!" && owned.view() == " held "); + t.expects(owned.ltrim().view() == "held " && owned.rtrim().view() == " held"); + t.expects(!is_view(&owned.trim())); +} diff --git a/tests/libraries.sakura b/tests/libraries.sakura new file mode 100644 index 00000000..188e62a4 --- /dev/null +++ b/tests/libraries.sakura @@ -0,0 +1,309 @@ +# Tests of how a program's library files are found: `core` whole, and the +# modules of the others its files refer to, a round at a time, by their paths. + +import std::io; +import std::process; +import std::testing; +import system; +module sakura::analyzer; + + +#! A resolver of the libraries a check reads: this repository's `core`, read +#! whole, and its `system` and runtime, from its root, where the tests run, and +#! the standard library. +#! @returns The resolver. +def test_finder(): resolver { + var made := resolver::new(); + made.whole("core", "core"); + made.add_library("system", "system"); + made.add_library("runtime", "runtime"); + made.add_library("std", std_folder()); + return made; +} + +#! The standard library's folder: its repository beside this one. +#! @returns The folder. +def std_folder(): strview { + return "../std"; +} + +#! Text that was lexed and parsed, with what both reported. +struct parsed { + var source: source; + var syntax: syntax; + var notes: vector; +} + +#! Lexes and parses the text as a file, as the analyzer's own tests do, with +#! the names of the program it is of, as the files a resolver is given are. +#! @param text The text. +#! @param names The program's names. +#! @returns Its source, syntax, and notes. +def parse(text: strview, names: &mut names): parsed { + var made := parsed { + source = source::from("test.sakura", text), + syntax = syntax::new(), + notes = vector::::new() + }; + var lexing := lexer::new(&mut made.source, names, &mut made.notes, 0); + lexing.tokenize_all(&mut made.syntax); + var parsing := parser::new(&mut made.syntax, names, &mut made.notes, 0); + _ = parsing.parse(); + return made; +} + +#! The library files a program of one file reads: what it refers to, then what +#! those refer to, until nothing new is, each as its path within its library, +#! as `std/io/file.sakura`. +#! @param finder The resolver. +#! @param text The program. +#! @returns The paths, in the order they were found. +def files_read(finder: &mut resolver, text: strview): vector { + var found := vector::::new(); + var names := names::new(); + val program := parse(text, &mut names); + finder.refer(&program.syntax, &names, &mut found); + var done: u64 = 0; + while done < found.length { + val to := found.length; + for i in done..to { + var at := path::parse(found[i].view()) else (_) { continue; }; + val held := io::read_file(&at) else (_) { continue; }; + val read := parse(held.view(), &mut names); + finder.refer(&read.syntax, &names, &mut found); + } + done = to; + } + return found; +} + +#! Whether a path read ends as the text does. +#! @param paths The paths. +#! @param end The text. +#! @returns Whether one does. +def reads_any(paths: &vector, end: strview): bool { + for &each in paths { + return true if each.view().ends_with(end); + } + return false; +} + +@test def a_program_reads_core_and_the_modules_its_files_refer_to(t: &mut tester): void { + # With no import, nothing but `core`, which is read whole, apart from this. + var alone := test_finder(); + val none := files_read(&mut alone, "def main(): void { var v := vector::::new(); v.append(0..4 is range ? 1 : 2); }"); + t.expects(none.length == 0); + + # `std::io`, the root holding it, and `system`, which its files name by path; + # not `std::serial`, `std::math`, or `std::testing`, which no file refers to. + var printing := test_finder(); + val io := files_read(&mut printing, "import std::io;\ndef main(): void { io::println(\"hi\"); }"); + t.expects(reads_any(&io, "std/io/console.sakura") && reads_any(&io, "std/io/path.sakura")); + t.expects(!reads_any(&io, "std/net/uri.sakura") && !reads_any(&io, "std/containers/deque.sakura")); + t.expects(reads_any(&io, "system/system.sakura") && reads_any(&io, "system/linux/linux.sakura")); + t.expects(!reads_any(&io, "std/serial/serial.sakura") && !reads_any(&io, "std/math/exp.sakura")); + t.expects(!reads_any(&io, "std/testing/testing.sakura")); + + # A path reads the module it begins with, with no import; one beginning with + # no module's name, as an enum's, reads nothing. + var pathed := test_finder(); + val exits := files_read(&mut pathed, "enum color { red }\ndef main(): void { val c := color::red; system::exit(0); }"); + t.expects(reads_any(&exits, "system/system.sakura") && !reads_any(&exits, "std/net/uri.sakura")); + + # A module's files reach a sibling they import, as `std::thread`'s do + # `std::time`'s, which is read too. + var threading := test_finder(); + val threads := files_read(&mut threading, "import std::thread;\ndef main(): void {}"); + t.expects(reads_any(&threads, "std/thread/thread.sakura") && reads_any(&threads, "std/time/duration.sakura")); + t.expects(!reads_any(&threads, "std/serial/serial.sakura")); + + + # An executable asks for the runtime, a library of its own beside `core`, + # which reads `system` and nothing of the standard library. + var building := test_finder(); + var runtime := vector::::new(); + building.want("runtime", &mut runtime); + var names := names::new(); + var done: u64 = 0; + while done < runtime.length { + val to := runtime.length; + for i in done..to { + var at := path::parse(runtime[i].view()) else (_) { continue; }; + val held := io::read_file(&at) else (_) { continue; }; + val read := parse(held.view(), &mut names); + building.refer(&read.syntax, &names, &mut runtime); + } + done = to; + } + t.expects(reads_any(&runtime, "runtime/start.sakura") && reads_any(&runtime, "runtime/memory.sakura")); + t.expects(reads_any(&runtime, "system/windows/windows.sakura")); + val library := std_folder(); + for &each in runtime { + t.expects(!each.view().starts_with(library)); + } +} + +@test def a_module_no_file_refers_to_is_never_read(t: &mut tester): void { + # A library's module whose file does not parse is no matter where nothing + # refers to it, and is read where something does. + val folder := $"{scratch_folder("libraries")}/shelf"; + write_text($"{folder}/shelf.sakura", "module shelf;\npub def one(): i64 { return 1; }\n"); + write_text($"{folder}/broken/broken.sakura", "module shelf::broken;\npub def oops( {\n"); + write_text($"{folder}/parts/a.sakura", "# A part of the root, in a folder of its own.\nmodule shelf;\npub def two(): i64 { return 2; }\n"); + write_text($"{folder}/alone.sakura", "# A module of its own, in the root's folder.\nmodule shelf::alone;\npub def three(): i64 { return 3; }\n"); + + var finder := test_finder(); + finder.add_library("shelf", folder.view()); + val root := files_read(&mut finder, "import shelf;\ndef main(): void { _ = one() + two(); }"); + t.expects(root.length == 2 && reads_any(&root, "shelf/shelf.sakura") && reads_any(&root, "shelf/parts/a.sakura")); + + # A file of a module's folder of its own is no part of the module around it, + # and is read where it is referred to. + t.expects(!reads_any(&root, "shelf/alone.sakura")); + var alone := test_finder(); + alone.add_library("shelf", folder.view()); + val own := files_read(&mut alone, "import shelf::alone;\ndef main(): void { _ = three(); }"); + t.expects(reads_any(&own, "shelf/alone.sakura")); + + var again := test_finder(); + again.add_library("shelf", folder.view()); + val broken := files_read(&mut again, "import shelf::broken;\ndef main(): void {}"); + t.expects(broken.length == 3 && reads_any(&broken, "shelf/broken/broken.sakura")); + + # Completion finds the modules within one by their folders, without reading + # them. + var segments := vector::::new(); + segments.append(string::from("shelf", nothing {})); + var shelves := vector::::new(); + shelves.append(library { name = string::from("shelf", nothing {}), folder = string::copy_of(&folder) }); + val within := modules_within(shelves.view(), segments.view()); + t.expects(within.length == 2 && within.iter().any(def(x) => x.view() == "broken") && within.iter().any(def(x) => x.view() == "alone")); + + # What the test wrote goes, deepest first. + for &each in ["shelf/broken/broken.sakura", "shelf/parts/a.sakura", "shelf/alone.sakura", "shelf/shelf.sakura", "shelf/broken", "shelf/parts", "shelf", ""] { + val at := each.length == 0 ? scratch_folder("libraries") : $"{scratch_folder("libraries")}/{each}"; + var gone := path::parse(at.view()) else (_) { continue; }; + _ = io::remove(&gone); + } +} + +@test def a_library_may_be_a_module_within_another(t: &mut tester): void { + # A library named for a module within another, as `std::yaml` is, holds that + # module and what is within it, and the library around it the rest. + val root := scratch_folder("within"); + write_text($"{root}/inner/inner.sakura", "module std::inner;\npub def one(): i64 { return 1; }\n"); + write_text($"{root}/inner/deep/deep.sakura", "module std::inner::deep;\npub def two(): i64 { return 2; }\n"); + write_text($"{root}/a/a.sakura", "module two::a;\npub def three(): i64 { return 3; }\n"); + write_text($"{root}/b/b.sakura", "module two::b;\npub def four(): i64 { return 4; }\n"); + val inner := $"{root}/inner"; + val first := $"{root}/a"; + val second := $"{root}/b"; + + var finder := test_finder(); + finder.add_library("std::inner", inner.view()); + val nested := files_read(&mut finder, "import std::inner::deep;\nimport std::io;\ndef main(): void {}"); + t.expects(reads_any(&nested, "inner/inner.sakura") && reads_any(&nested, "inner/deep/deep.sakura")); + t.expects(reads_any(&nested, "std/io/path.sakura")); + + # Two libraries within one module that is in none, as `sakura::analyzer` and + # `sakura::machine` are, are each found, and the module holding them has no + # files. + var siblings := test_finder(); + siblings.add_library("two::a", first.view()); + siblings.add_library("two::b", second.view()); + val both := files_read(&mut siblings, "import two::a;\nimport two::b;\ndef main(): void { _ = two::a::three() + two::b::four(); }"); + t.expects(both.length == 2 && reads_any(&both, "a/a.sakura") && reads_any(&both, "b/b.sakura")); + + # Completion offers the libraries within a module beside its own modules. + var shelves := vector::::new(); + shelves.append(library { name = string::from("std", nothing {}), folder = string::from(std_folder(), nothing {}) }); + shelves.append(library { name = string::from("std::inner", nothing {}), folder = string::copy_of(&inner) }); + shelves.append(library { name = string::from("two::a", nothing {}), folder = string::copy_of(&first) }); + shelves.append(library { name = string::from("two::b", nothing {}), folder = string::copy_of(&second) }); + var std_path := vector::::new(); + std_path.append(string::from("std", nothing {})); + val in_std := modules_within(shelves.view(), std_path.view()); + t.expects(in_std.iter().any(def(x) => x.view() == "inner") && in_std.iter().any(def(x) => x.view() == "io")); + var two_path := vector::::new(); + two_path.append(string::from("two", nothing {})); + val in_two := modules_within(shelves.view(), two_path.view()); + t.expects(in_two.length == 2 && in_two[0].view() == "a" && in_two[1].view() == "b"); + std_path.append(string::from("inner", nothing {})); + val in_inner := modules_within(shelves.view(), std_path.view()); + t.expects(in_inner.length == 1 && in_inner[0].view() == "deep"); + + # What the test wrote goes, deepest first. + for &each in ["inner/deep/deep.sakura", "inner/inner.sakura", "a/a.sakura", "b/b.sakura", "inner/deep", "inner", "a", "b", ""] { + val at := each.length == 0 ? string::copy_of(&root) : $"{root}/{each}"; + var gone := path::parse(at.view()) else (_) { continue; }; + _ = io::remove(&gone); + } +} + +@test def a_folder_is_of_each_module_a_file_within_it_is_of(t: &mut tester): void { + # A module's folder may hold the one file of a module within it, as + # `nest/deeper.sakura` of `lib::nest::deeper` beside `nest/nest.sakura` of + # `lib::nest`, whichever name comes first. + val root := scratch_folder("deeper"); + write_text($"{root}/lib/lib.sakura", "module lib;\npub def zero(): i64 { return 0; }\n"); + write_text($"{root}/lib/nest/nest.sakura", "module lib::nest;\npub def one(): i64 { return 1; }\n"); + write_text($"{root}/lib/nest/deeper.sakura", "module lib::nest::deeper;\npub def two(): i64 { return 2; }\n"); + val folder := $"{root}/lib"; + + var finder := test_finder(); + finder.add_library("lib", folder.view()); + val read := files_read(&mut finder, "import lib::nest;\nimport lib::nest::deeper;\ndef main(): void {}"); + t.expects(reads_any(&read, "nest/nest.sakura") && reads_any(&read, "nest/deeper.sakura")); + + # Completion offers each. + var shelves := vector::::new(); + shelves.append(library { name = string::from("lib", nothing {}), folder = string::copy_of(&folder) }); + var lib_path := vector::::new(); + lib_path.append(string::from("lib", nothing {})); + val in_lib := modules_within(shelves.view(), lib_path.view()); + t.expects(in_lib.length == 1 && in_lib[0].view() == "nest"); + lib_path.append(string::from("nest", nothing {})); + val in_nest := modules_within(shelves.view(), lib_path.view()); + t.expects(in_nest.length == 1 && in_nest[0].view() == "deeper"); + + # What the test wrote goes, deepest first. + for &each in ["lib/nest/deeper.sakura", "lib/nest/nest.sakura", "lib/lib.sakura", "lib/nest", "lib", ""] { + val at := each.length == 0 ? string::copy_of(&root) : $"{root}/{each}"; + var gone := path::parse(at.view()) else (_) { continue; }; + _ = io::remove(&gone); + } +} + +@test def a_files_module_is_its_first_module_line(t: &mut tester): void { + t.expects(module_named("#! A file.\nimport std;\n\nmodule std::io;\n").view() == "std::io"); + t.expects(module_named("extern import \"kernel32.dll\" when os == windows;\n\nextern module system::windows when os == windows;").view() == "system::windows"); + t.expects(module_named("module system when os == linux && arch == x86_64;").view() == "system"); + t.expects(module_named("import std;\ndef main(): void {}\nmodule late;").length == 0); +} + +#! A folder of its own for a test, under the system's for such files. +#! @param name The test's name. +#! @returns The folder's path. +def scratch_folder(name: strview): string { + var base: strview = "/tmp"; + if process::variable("TMPDIR") is some(found) { + base = found; + } else if process::variable("TEMP") is some(found) { + base = found; + } + return $"{base}/sakura-libraries-{system::getpid()}-{name}"; +} + +#! Writes a file, making the folders it is in. +#! @param at The file's path. +#! @param text What it holds. +def write_text(at: string, text: strview): void { + var end := at.length; + while end > 0 && at[end - 1] != '/' { + end--; + } + var folder := path::parse(at.view().substr(0, end - 1)) else (_) { return; }; + _ = io::create_directories(&folder); + var file := path::parse(at.view()) else (_) { return; }; + _ = io::write_file(&file, text); +} diff --git a/tests/machine/machine.sakura b/tests/machine/machine.sakura new file mode 100644 index 00000000..f0682cec --- /dev/null +++ b/tests/machine/machine.sakura @@ -0,0 +1,902 @@ +#! @file machine.sakura +#! @author John Christman (sorakatadzuma@gmail.com) +#! @copyright Malunal Studios, LLC. +#! @license MIT +#! +#! Contains the tests of the machine and of constant evaluation: small +#! programs, written over a standard library of their own, are checked, their +#! constants evaluated, and lowered, then run in the machine, which keeps what +#! they write rather than writing it, and what each wrote and how it stopped +#! is compared with what is expected. The collector runs at every allocation, +#! so what it loses is found. The corpus of `test/programs` runs whole programs +#! over the real standard library, by `tools/corpus.sakura`. + +import std::io; +import std::testing; +import sakura::analyzer; +import sakura::compiler; +module sakura::machine; + + +#! A `core` and standard library small enough to check quickly: views, text, a +#! `string` owning its bytes, writing to the output, and exiting. +const prelude: strview = """ + module core; + pub trait attribute {} + pub struct intrinsic : attribute {} + @intrinsic pub def raw_allocate(size: u64): *mut u8; + @intrinsic pub def raw_release(pointer: *mut u8): void; + @intrinsic pub def size_of(): u64; + pub trait owning { def close(&mut this): void; } + pub struct span { pub var _data: *T; pub var _length: u64; } + pub val span::length: u64 { get => this._length; } + pub type strview = span; + pub struct string : owning { var _owner: u64; var _data: *mut u8; var _length: u64; var _capacity: u64; } + pub def string::close(&mut this): void { raw_release(this._data); } + pub def string::view(&this): strview { return span:: { _data = this._data as *u8, _length = this._length }; } + module system; + @intrinsic def syscall(n: i64, a: u64, b: u64, c: u64, d: u64, e: u64, f: u64): i64; + @intrinsic pub def exit(code: i32): void; + @intrinsic pub def abort(): void; + pub def print(text: strview): void { syscall(1, 1, text._data as u64, text._length, 0, 0, 0); } + pub def println(text: strview): void { print(text); print("\\n"); } + @intrinsic pub def start(body: def(*mut u8): void, context: *mut u8): i64; + module std::math; + @intrinsic pub def square_root(x: f64): f64; + @intrinsic pub def ones_in(word: u64): u64; + @intrinsic pub def zeros_leading(word: u64): u64; + @intrinsic pub def zeros_trailing(word: u64): u64; + @intrinsic pub def bytes_reversed(word: u64): u64; + module core; + pub enum order : u8 { relaxed, acquire, release, acq_rel, seq_cst } + pub trait lockfree {} + @intrinsic pub def atomic_load(at: *T, how: order): T where T: lockfree; + @intrinsic pub def atomic_store(at: *mut T, value: T, how: order): void where T: lockfree; + @intrinsic pub def atomic_exchange(at: *mut T, value: T, how: order): T where T: lockfree; + @intrinsic pub def atomic_compare_exchange(at: *mut T, expected: T, desired: T, found: *mut T, success: order, failure: order): bool where T: lockfree; + @intrinsic pub def atomic_fetch(at: *mut T, operand: T, how: order): T where T: lockfree; + @intrinsic pub def atomic_fence(how: order): void; + pub struct allow : attribute {} + @intrinsic pub struct cfn {} + @intrinsic pub def fault(why: strview): void; + module std; + """; + +#! Checks a program written over the prelude, evaluates its constants, lowers +#! it, and runs it, giving what it wrote, then how it stopped where it did not +#! return from `main`: what it exited with, or the fault and its trace. Where +#! it does not check, or evaluating notes what goes wrong, the notes. +#! @param text The program. +#! @returns What it gave. +def ran(text: strview): string { + return ran_at(text, 0); +} + +#! Checks a program written over the prelude, evaluates its constants, lowers +#! and optimizes it at a level, and runs it, giving what `ran` gives. +#! @param text The program. +#! @param level How much the code is optimized. +#! @returns What it gave. +def ran_at(text: strview, level: u32): string { + return ran_with(text, level, false); +} + +#! Runs a program as `ran` does, with its memory checked, as `run --checks` +#! does, giving also the blocks it never released where it ends by returning +#! or exiting. +#! @param text The program. +#! @returns What it gave. +def ran_checked(text: strview): string { + return ran_with(text, 1, true); +} + +#! Checks a program written over the prelude, evaluates its constants, lowers +#! and optimizes it at a level, and runs it, with its memory checked where it +#! is asked to be, giving what `ran` gives. +#! @param text The program. +#! @param level How much the code is optimized. +#! @param checks Whether its memory is checked. +#! @param other A file of the program beside it, `other.sakura`, or empty +#! for none. +#! @returns What it gave. +def ran_with(text: strview, level: u32, checks: bool, other: strview = ""): string { + var held := names::new(); + var notes := vector::::new(); + var sources := vector::::new(); + var syntaxes := vector::::new(); + var roots := vector::::new(); + sources.reserve(3); + syntaxes.reserve(3); + sources.append(source::from("test.sakura", text)); + if other.length != 0 { + sources.append(source::from("other.sakura", other)); + } + sources.append(source::from("prelude.sakura", prelude)); + val count := sources.length; + for i in 0..count { + syntaxes.append(syntax::new()); + } + for i in 0..count { + var lexing := lexer::new(sources.at(i), &mut held, &mut notes, i as u32); + lexing.tokenize_all(syntaxes.at(i)); + var parsing := parser::new(syntaxes.at(i), &held, &mut notes, i as u32); + roots.append(parsing.parse()); + } + var checker := checker::new(&mut held, &mut notes); + checker.target.os = checker.names.intern(&test_os); + for i in 0..count { + checker.add(sources.at(i), syntaxes.at(i), roots.at(i)); + } + checker.check(); + + var out := string::new(nothing {}); + var results := outcomes::new(); + if notes.length == 0 { + results = evaluate(&mut checker); + } + if notes.length != 0 { + for &each in notes { + val at := sources.at(each.file).lines.place_of(each.offset); + var message := each.message(sources.at(each.file)); + out.append($"{at.line}:{at.column}: {message}\n"); + } + return out; + } + + var lowered := lowerer::new(&mut checker, lowering { verify = true, level = level, checks = checks }); + lowered.evaluated = move(&mut results); + lowered.compile(); + for &each in lowered.problems { + out.append(each.view()); + out.append("\n"); + } + return out if lowered.problems.length != 0; + + var running := interpreter::new(&mut lowered, interpreting { stack = 1048576, capture = true, checks = checks }); + val why := running.run(span::::empty()); + for &byte in running.output { + out.push(byte); + } + if why == halt::exited { + out.append($"--- exit {running.status}\n"); + } + if checks && (why == halt::exited || why == halt::none) { + running.report_leaks(&mut out); + } + if why != halt::exited && why != halt::none { + var report := string::new(nothing {}); + running.report(why, &mut report); + out.append(report.view()); + } + return out; +} + +# The system the programs are checked for, which is the one they run on, so +# what they declare for it, as C's functions, is there. +when os == linux { + val test_os: strview = "linux"; +} +when os == windows { + val test_os: strview = "windows"; +} + +#! Whether what a program gave is what is expected, but for the line breaks +#! ending them, printing what it is where it is not. +#! @param got What it gave. +#! @param want What is expected. +#! @returns Whether it is. +def gives(got: &string, want: strview): bool { + var x := got.length; + var y := want.length; + while x > 0 && got.at(x - 1) == '\n' { x--; } + while y > 0 && want.at(y - 1) == '\n' { y--; } + val same := got.substr(0, x) == want.substr(0, y); + if !same { + println(got); + } + return same; +} + + +@test def numbers_loops_and_calls_run(t: &mut tester): void { + # Values move between the words of frames, loops take their variables as + # the parameters of their heads, and narrow numbers wrap as their types do. + val got := ran(""" + import std; + import system; + def fib(n: u64): u64 { return n < 2 ? n : fib(n - 1) + fib(n - 2); } + def main(): void { + var total: u64 = 0; + for i in 0u..10u { total += i * i; } + var small: u8 = 250; + small += 10; + val third: f32 = 1f / 3f; + println($"{fib(20)} {total} {small} {-7 / 2} {-7 % 2} {third} {1.0 / 4.0} {1 << 63}"); + } + """); + t.expects(gives(&got, "6765 285 4 -3 -1 0.33333334 0.25 9223372036854775808")); +} + + +@test def structs_closures_and_traits_run(t: &mut tester): void { + # A struct is returned through the memory its call gives, a closure refers to + # the locals it captures where they are, and a trait's method is called through + # the vtable of the reference. + val got := ran(""" + import std; + import system; + struct pair { var a: i64; var b: i64; } + def swapped(p: pair): pair { return pair { a = p.b, b = p.a }; } + trait shape { def area(&this): i64; } + struct square : shape { var side: i64; } + def square::area(&this): i64 { return this.side * this.side; } + struct rect : shape { var w: i64; var h: i64; } + def rect::area(&this): i64 { return this.w * this.h; } + def area_of(s: &shape): i64 { return s.area(); } + def main(): void { + val p := swapped(pair { a = 1, b = 2 }); + var n: i64 = 10; + var m: i64 = 20; + val f := def(): i64 { n += 1; return n; }; + val g := def(): i64 { m += 1; return m; }; + val s := square { side = 3 }; + val r := rect { w = 2, h = 5 }; + println($"{p} {f()} {g()} {f()} {area_of(&s)} {area_of(&r)}"); + } + """); + t.expects(gives(&got, "pair{a = 2, b = 1} 11 21 12 9 10")); +} + + +@test def a_default_reads_the_locals_of_its_call_in_another_file(t: &mut tester): void { + # The files begin alike, so `f`'s `x` and `shown`'s `x` are nodes of the same + # index, each of its own file. The default making `got` names `shown`'s, and + # `values_of` evaluates what the call wrote for it, which names `f`'s. + t.expects(gives(&ran_with(""" + import system; + def f(x: i64): void { shown(x * 3 == 9); } + def main(): void { f(3); } + """, 0, false, """ + import system; + def shown(x: bool, got: string = values_of(x)): void { println(got.view()); } + module core; + @intrinsic pub def values_of(value: T): string; + """), "x * 3 = 9")); +} + +@test def faults_report_where_each_function_was(t: &mut tester): void { + # A fault stops the program and names each function running, where it was, + # as the C machine does; an exit stops it with its status. + val got := ran(""" + import std; + import system; + def divide(a: i64, b: i64): i64 { return a / b; } + def main(): void { + println("before"); + println($"{divide(7, 0)}"); + } + """); + t.expects(gives(&got, """ + before + sakura: runtime error: Division by zero. + at divide (test.sakura:3:44) + at main (test.sakura:6:20) + """)); + + val exited := ran(""" + import std; + import system; + def main(): void { + println("going"); + exit(3); + println("gone"); + } + """); + t.expects(gives(&exited, "going\n--- exit 3")); + + # `fault` stops it as a fault does, with the text it was given, and needs no + # import, being `core`'s. + val faulted := ran(""" + def check(n: i64): i64 { + if n > 3 { fault("Past three."); } + return n; + } + def main(): void { _ = check(5); } + """); + t.expects(gives(&faulted, """ + sakura: runtime error: Past three. + at check (test.sakura:2:19) + at main (test.sakura:5:29) + """)); +} + + +@test def contracts_stop_a_run_and_a_constant_they_fail(t: &mut tester): void { + # A contract that fails is a fault, saying which failed and what its operands + # held, made only there. + val failed := ran(""" + def divide(a: i64, b: i64): i64 { + expects(b != 0); + return a / b; + } + def main(): void { _ = divide(7, 0); } + """); + t.expects(gives(&failed, """ + sakura: runtime error: A pre-condition failed: b != 0, with b = 0. + at divide (test.sakura:2:3) + at main (test.sakura:5:30) + """)); + + # One that holds runs while compiling, and one that fails stops the constant + # it is evaluated for, saying so there. + val held := ran(""" + import system; + def half(n: i64): i64 { + asserts(n % 2 == 0); + return n / 2; + } + const four: i64 = half(8); + def main(): void { exit(four as i32); } + """); + t.expects(gives(&held, "--- exit 4")); + val stopped := ran(""" + def half(n: i64): i64 { + asserts(n % 2 == 0); + return n / 2; + } + const odd: i64 = half(7); + def main(): void { _ = odd; } + """); + t.expects(gives(&stopped, """ + 5:7: Evaluating `odd` stopped: An assertion failed: n % 2 == 0, with n % 2 = 1. + at half (test.sakura:2:3) + at odd (test.sakura:5:22) + """)); +} + +@test def checked_runs_stop_where_memory_is_not_held(t: &mut tester): void { + # A block read after its release, a block released twice, and a local read + # through a reference once its frame is gone each stop a checked run, where + # a run unchecked reads what is there. + val released := ran_checked(""" + import std; + import system; + def main(): void { + val block := raw_allocate(16) as *mut i64; + block[0] = 3; + raw_release(block as *mut u8); + println("released"); + block[1] = 4; + } + """); + t.expects(gives(&released, """ + released + sakura: runtime error: Pointer reaches memory the program does not hold, as past the end of what it points into, or memory released. + at main (test.sakura:8:8) + """)); + + val twice := ran_checked(""" + import std; + def main(): void { + val block := raw_allocate(16); + raw_release(block); + raw_release(block); + } + """); + t.expects(gives(&twice, """ + sakura: runtime error: Released memory that was not allocated, or was already released. + at main (test.sakura:5:14) + """)); + + val dangling := ran_checked(""" + import std; + struct point { var x: i64; } + @allow def made(): &mut point { var p := point { x = 7 }; return &mut p; } + def main(): void { + val p := &mut made(); + p.x = 8; + } + """); + t.expects(gives(&dangling, """ + sakura: runtime error: Pointer reaches memory the program does not hold, as past the end of what it points into, or memory released. + at main (test.sakura:6:5) + """)); +} + + +@test def checked_runs_report_the_blocks_nothing_reaches(t: &mut tester): void { + # What a global reaches, directly or through a block, and what the frames + # hold as the program exits, are kept; the rest is reported by where it was + # allocated, those of each place together, in order. + val got := ran_checked(""" + import std; + import system; + struct node { var next: *mut node; } + var kept: *mut node; + def lose(): void { _ = raw_allocate(24); } + def finish(held: *mut u8): void { + held[0] = 1; + exit(2); + } + def main(): void { + kept = raw_allocate(8) as *mut node; + kept[0].next = raw_allocate(8) as *mut node; + lose(); + lose(); + val mine := raw_allocate(5); + finish(mine); + } + """); + t.expects(gives(&got, """ + --- exit 2 + sakura: 2 blocks the program allocated, 48 bytes, were never released, and nothing it keeps reaches them: + 2 blocks, 48 bytes, allocated at lose (test.sakura:5:36) + """)); +} + + +@test def checked_runs_keep_the_frames_of_each_thread_as_the_program_exits(t: &mut tester): void { + # A thread still running as the program exits keeps what its frames hold, as + # `main` does, so the block it writes is not reported. Its frames are read + # whole for it, as `main`'s are, even the words nothing wrote. + val got := ran_checked(""" + import std; + import system; + var started: u64; + def spin(held: *mut u8): void { + held[0] = 1; + atomic_store::((&mut started) as *mut u64, 1, order::release); + while true { + held[0] = held[0] + 1; + } + } + def work(context: *mut u8): void { + spin(raw_allocate(8)); + } + def main(): void { + _ = system::start(work, null); + while atomic_load::((&started) as *u64, order::acquire) == 0 {} + exit(2); + } + """); + t.expects(gives(&got, """ + --- exit 2 + """)); +} + + +@test def a_fault_in_code_inlined_names_the_function_inlined(t: &mut tester): void { + # `divide` is inlined into `main`, and a fault within it still names it, where + # it was, then `main`, where it called it, as without inlining. + val got := ran_at(""" + import std; + import system; + def divide(a: i64, b: i64): i64 { return a / b; } + def main(): void { + println("before"); + println($"{divide(7, 0)}"); + } + """, 2); + t.expects(gives(&got, """ + before + sakura: runtime error: Division by zero. + at divide (test.sakura:3:44) + at main (test.sakura:6:20) + """)); +} + + +@test def atomics_work_while_compiling_as_they_do_running(t: &mut tester): void { + # Compiling runs one thread, where an atomic is what it reads and writes; the + # machine runs it as the program does, and each gives what it held. + val program: strview = """ + import std; + import system; + def count(): u64 { + var held: u64 = 5; + val at := (&mut held) as *mut u64; + val was := atomic_fetch::(at, 3, order::seq_cst); + atomic_store::(at, atomic_load::(at, order::acquire) * 2, order::release); + var found: u64 = 0; + val wrote := atomic_compare_exchange::(at, 16, 20, (&mut found) as *mut u64, order::seq_cst, order::seq_cst); + val refused := atomic_compare_exchange::(at, 16, 30, (&mut found) as *mut u64, order::seq_cst, order::relaxed); + val swapped := atomic_exchange::(at, 1, order::seq_cst); + atomic_fence(order::seq_cst); + var small: i8 = -5; + val least := atomic_fetch::((&mut small) as *mut i8, -7, order::relaxed); + var top: u64 = 1; + val most := atomic_fetch::((&mut top) as *mut u64, 0x8000000000000000u, order::relaxed); + val right := wrote && !refused && least == -5 && small == -7 && most == 1 && top == 0x8000000000000000u; + return was * 1000000 + found * 10000 + swapped * 100 + held + (right ? 50 : 0); + } + const counted: u64 = count(); + def main(): void { println($"{counted} {count()}"); } + """; + t.expects(ran(program).view() == "5202051 5202051\n"); + t.expects(ran_at(program, 2).view() == "5202051 5202051\n"); +} + +@test def math_operations_agree_to_the_bit(t: &mut tester): void { + # The operations of `std::math` the machine gives are the same bits run as + # written, folded by the optimizer where their operands are known, and in a + # constant: a correctly rounded square root, and counts of a word's bits, 64 + # of zero, and its bytes reversed. + val program: strview = """ + import std; + import system; + import std::math; + const root: f64 = square_root(2.0); + const ones: u64 = ones_in(0xF0F0u); + def bits(x: f64): u64 { var held := x; return ((&mut held) as *mut u64)[0]; } + def main(): void { + val zero: f64 = 0; + val reals: f64[9] = [2.0, 0.0, -0.0, -1.0, 1e-310, 1e300, 0.25, 3.0, 1.0 / zero]; + for i in 0..9u { println($"{bits(square_root(reals[i]))}"); } + val words: u64[5] = [0u, 1u, 0x8000000000000000u, 0xFFFFFFFFFFFFFFFFu, 0x0102030405060708u]; + for i in 0..5u { + val w: u64 = words[i]; + println($"{ones_in(w)} {zeros_leading(w)} {zeros_trailing(w)} {bytes_reversed(w)}"); + } + println($"{bits(root)} {ones} {bits(square_root(1e-310))} {zeros_leading(1u)} {bytes_reversed(0xFFu)}"); + } + """; + val want: strview = """ + 4609047870845172685 + 0 + 9223372036854775808 + 18444492273895866368 + 2288155682980613038 + 6850974717710472879 + 4602678819172646912 + 4610479282544200874 + 9218868437227405312 + 0 64 64 0 + 1 63 0 72057594037927936 + 1 0 63 128 + 64 0 0 18446744073709551615 + 13 7 3 578437695752307201 + 4609047870845172685 8 2288155682980613038 63 18374686479671623680 + """; + val plain := ran(program); + t.expects(gives(&plain, want)); + val optimized := ran_at(program, 2); + t.expects(gives(&optimized, want)); +} + + +@test def constants_are_evaluated_while_compiling(t: &mut tester): void { + # A constant the checker does not work out is evaluated in the machine, and + # held as data with the memory it points into; one reading another waits for + # it; a local constant is evaluated too, and so is a condition of `if const`. + val got := ran(""" + import std; + import system; + struct entry { val name: strview; val value: i64; } + def made(n: i64): span { + val at := raw_allocate(3 * 8) as *mut i64; + for i in 0..3 { at[i] = n * (i as i64 + 1); } + return span:: { _data = at as *i64, _length = 3 }; + } + const table: span = made(base); + const base: i64 = twice(21); + const first: entry = entry { name = "first", value = table._data[2] }; + def twice(x: i64): i64 { return x * 2; } + def wide(): bool { + if const size_of::() > 4 { return true; } + return false; + } + def main(): void { + const local: entry = entry { name = "local", value = twice(5) }; + println($"{table._data[0]} {table._data[1]} {first.name} {first.value} {local.name} {local.value} {wide::()} {wide::()}"); + } + """); + t.expects(gives(&got, "42 84 first 126 local 10 true false")); +} + + +@test def evaluating_notes_what_only_a_running_program_does(t: &mut tester): void { + # Evaluating stops where it reaches what only the program running has, as a + # system call, or an address taken as a number, as `print` gives the system + # its text's, and notes why at the constant, with the functions running. + val got := ran(""" + import std; + import system; + def loud(): i64 { println("now"); return 1; } + const noisy: i64 = loud(); + def main(): void { println($"{noisy}"); } + """); + t.expects(gives(&got, """ + 4:7: Evaluating `noisy` stopped: Function does not run while compiling. + at print (prelude.sakura:18:63) + at println (prelude.sakura:19:45) + at loud (test.sakura:3:26) + at noisy (test.sakura:4:24) + """)); +} + + +@test def values_share_the_words_of_frames(t: &mut tester): void { + # Values whose lives do not overlap share a word of the frame, so a long + # function with many short-lived values keeps a small frame. + var held := names::new(); + var notes := vector::::new(); + var sources := vector::::new(); + var syntaxes := vector::::new(); + sources.reserve(1); + syntaxes.reserve(1); + sources.append(source::from("test.sakura", """ + def many(x: u64): u64 { + var a := x; + a = a * 3 + 1; a = a * 3 + 1; a = a * 3 + 1; a = a * 3 + 1; + a = a * 3 + 1; a = a * 3 + 1; a = a * 3 + 1; a = a * 3 + 1; + return a; + } + def main(): void { many(1); } + """)); + syntaxes.append(syntax::new()); + var lexing := lexer::new(sources.at(0), &mut held, &mut notes, 0); + lexing.tokenize_all(syntaxes.at(0)); + var parsing := parser::new(syntaxes.at(0), &held, &mut notes, 0); + val root := parsing.parse(); + var checker := checker::new(&mut held, &mut notes); + checker.add(sources.at(0), syntaxes.at(0), root); + checker.check(); + var lowered := lowerer::new(&mut checker, lowering { verify = true }); + lowered.compile(); + lowered.assemble_all(); + for &each in lowered.program.functions { + continue if each.name.view() != "many"; + val values := each.body.origins.length; + t.expects(values > 30 && each.compiled.frame <= 8 * 8); + } +} + + +#! Checks a program written over the prelude, evaluates its constants, and +#! lowers every function of it, as a host embedding the machine does, then +#! gives a machine running it, not yet begun, to a function, which calls its +#! functions itself. Where it does not check, or does not lower, gives what was +#! noted, and otherwise nothing. +#! @param text The program. +#! @param options How it runs. +#! @param body What the host does with the machine. +#! @returns What was noted. +def hosted(text: strview, options: interpreting, body: def(&mut interpreter): void): string { + var held := names::new(); + var notes := vector::::new(); + var sources := vector::::new(); + var syntaxes := vector::::new(); + var roots := vector::::new(); + sources.reserve(2); + syntaxes.reserve(2); + sources.append(source::from("test.sakura", text)); + sources.append(source::from("prelude.sakura", prelude)); + for i in 0u..2u { + syntaxes.append(syntax::new()); + } + for i in 0u..2u { + var lexing := lexer::new(sources.at(i), &mut held, &mut notes, i as u32); + lexing.tokenize_all(syntaxes.at(i)); + var parsing := parser::new(syntaxes.at(i), &held, &mut notes, i as u32); + roots.append(parsing.parse()); + } + var checker := checker::new(&mut held, &mut notes); + checker.target.os = checker.names.intern(&test_os); + for i in 0u..2u { + checker.add(sources.at(i), syntaxes.at(i), roots.at(i)); + } + checker.check(); + var out := string::new(nothing {}); + var results := outcomes::new(); + if notes.length == 0 { + results = evaluate(&mut checker); + } + for &each in notes { + val at := sources.at(each.file).lines.place_of(each.offset); + var message := each.message(sources.at(each.file)); + out.append($"{at.line}:{at.column}: {message}\n"); + } + return out if notes.length != 0; + + var lowered := lowerer::new(&mut checker, lowering { verify = true, everything = true }); + lowered.evaluated = move(&mut results); + lowered.compile(); + for &each in lowered.problems { + out.append(each.view()); + out.append("\n"); + } + return out if lowered.problems.length != 0; + var running := interpreter::new(&mut lowered, options); + body(&mut running); + return out; +} + +#! The function of a program of a name, as a trace writes it. +#! @param running The machine running the program. +#! @param name The name. +#! @returns The function, or `no_function`. +def function_named(running: &interpreter, name: strview): u32 { + for i in 0..running.c.program.functions.length { + return i as u32 if running.c.program.functions[i].name.view() == name; + } + return no_function; +} + +#! The bits of an `f64`, as a word passes it. +def bits_of(x: f64): u64 { + var held := x; + return ((&mut held) as *mut u64)[0]; +} + +#! The `f64` of a word's bits. +def real_of(word: u64): f64 { + var held := word; + return ((&mut held) as *mut f64)[0]; +} + +@test def hosts_call_the_functions_of_a_program_they_began(t: &mut tester): void { + # A host begins a program, giving its globals their values, then calls its + # functions by their words: integers, floats as `f64`, a struct in memory + # both ways, and a function value the program gave, by its two words. + val noted := hosted(""" + import std; + import system; + var counter: i64 = 10; + pub struct triple { pub var a: i64; pub var b: i64; pub var c: i64; } + def add(x: i64, y: i64): i64 { counter += 1; return x + y + counter; } + def scaled(v: f32, by: f64): f64 { return v as f64 * by; } + def made(x: i64): triple { return triple { a = x, b = x + 1, c = x + 2 }; } + def sum(p: triple): i64 { return p.a + p.b + p.c; } + def plus_four(x: i64): i64 { return x + 4; } + def adder(): def(i64): i64 { return plus_four; } + def loud(): void { println("hello from the program"); } + """, interpreting { stack = 1048576, capture = true }, def(running: &mut interpreter): void { + t.expects(running.begin() == halt::none); + var two: u64[2] = [2, 3]; + t.expects(running.call(function_named(running, "add"), two[:]) == halt::none && running.result(0) == 16); + t.expects(running.call(function_named(running, "add"), two[:]) == halt::none && running.result(0) == 17); + var reals: u64[2] = [bits_of(1.5), bits_of(2.0)]; + t.expects(running.call(function_named(running, "scaled"), reals[:]) == halt::none && real_of(running.result(0)) == 3.0); + var made: i64[3]; + var five: u64[1] = [5]; + t.expects(running.call(function_named(running, "made"), five[:], (&mut made) as *mut u8 as u64) == halt::none); + t.expects(made[0] == 5 && made[1] == 6 && made[2] == 7); + var address: u64[1] = [(&mut made) as *mut u8 as u64]; + t.expects(running.call(function_named(running, "sum"), address[:]) == halt::none && running.result(0) == 18); + t.expects(running.call(function_named(running, "adder"), span::::empty()) == halt::none); + val function := running.result(0); + val environment := running.result(1); + var ten: u64[1] = [10]; + t.expects(running.call_value(function, environment, ten[:]) == halt::none && running.result(0) == 14); + t.expects(running.call(function_named(running, "loud"), span::::empty()) == halt::none); + val said := running.take_output(); + t.expects(said.view() == "hello from the program\n"); + # Too few words is no call. + t.expects(running.call(function_named(running, "add"), five[:]) == halt::unsupported); + }); + t.expects(gives(¬ed, "")); +} + +@test def a_call_stops_once_it_takes_more_steps_than_allowed(t: &mut tester): void { + # Each call the host makes may take as many steps as it allows, so one that + # never ends stops, and the next is allowed as many again. + val noted := hosted(""" + import std; + import system; + def spin(): void { var x: u64 = 0; while true { x += 1; } } + def count(n: u64): u64 { var x: u64 = 0; for i in 0..n { x += i; } return x; } + """, interpreting { stack = 1048576, steps = 100000 }, def(running: &mut interpreter): void { + t.expects(running.begin() == halt::none); + val stopped := running.call(function_named(running, "spin"), span::::empty()); + t.expects(stopped == halt::step_limit); + var report := string::new(nothing {}); + running.report(stopped, &mut report); + t.expects(report.view().find("at spin (test.sakura:") is some(_)); + var many: u64[1] = [1000]; + t.expects(running.call(function_named(running, "count"), many[:]) == halt::none && running.result(0) == 499500); + }); + t.expects(gives(¬ed, "")); +} + +when os == windows { + # The machine the functions the host provides call back into, and what they + # call there. + var hosting: *mut interpreter = null; + var tripled: u32 = 0; + var broken: u32 = 0; + + # Functions of the host's, which the programs of the test call. + def host_twice(x: i64): i64 { + return x * 2; + } + + def host_again(x: i64): i64 { + var args: u64[1] = [x as u64]; + return -1 if through(hosting).call(tripled, args[:]) != halt::none; + return through(hosting).result(0) as i64; + } + + def host_broken(x: i64): i64 { + var args: u64[1] = [x as u64]; + val why := through(hosting).call(broken, args[:]); + return why == halt::out_of_bounds ? 100 : 0; + } + + @test def programs_call_what_the_host_provides(t: &mut tester): void { + # A host gives a program functions of its own, which it declares as C's + # are, and those call back into the program; a fault there stops the + # program's call under way once the host returns to it, giving its trace. + val noted := hosted(""" + import std; + import system; + import host; + def triple(x: i64): i64 { return x * 3; } + def through_host(x: i64): i64 { return twice(x) + again(x); } + def past_end(i: i64): i64 { var a: i64[2] = [1, 2]; return a[i as u64]; } + def breaks_through_host(x: i64): i64 { return fails(x) + 1; } + extern module host when os == windows; + pub def twice(x: i64): i64; + pub def again(x: i64): i64; + pub def fails(x: i64): i64; + """, interpreting { stack = 1048576 }, def(running: &mut interpreter): void { + val twice: cfn = host_twice; + val again: cfn = host_again; + val fails: cfn = host_broken; + running.provide("twice", twice as u64); + running.provide("again", again as u64); + running.provide("fails", fails as u64); + hosting = running as *mut interpreter; + tripled = function_named(running, "triple"); + broken = function_named(running, "past_end"); + t.expects(running.begin() == halt::none); + var seven: u64[1] = [7]; + t.expects(running.call(function_named(running, "through_host"), seven[:]) == halt::none && running.result(0) == 35); + val why := running.call(function_named(running, "breaks_through_host"), seven[:]); + t.expects(why == halt::out_of_bounds); + var report := string::new(nothing {}); + running.report(why, &mut report); + t.expects(report.view().find("at past_end (test.sakura:") is some(_) && report.view().find("at breaks_through_host (test.sakura:") is some(_)); + # The program goes on being called after. + t.expects(running.call(function_named(running, "through_host"), seven[:]) == halt::none && running.result(0) == 35); + hosting = null; + }); + t.expects(gives(¬ed, "")); + } + + @test def c_calls_pass_values_as_c_does(t: &mut tester): void { + # On Windows a program reaches the system through C, so the machine calls C + # with Microsoft's ABI: integers and floats positional in registers and on + # the stack, an aggregate as large as an integer by value and a larger one + # by the address of a copy, a larger result through memory, and a function + # of the program C calls back. Every kind is passed to C's own library here. + val got := ran(""" + import std; + import system; + import crt; + extern import "ucrtbase.dll" when os == windows; + def compare_ints(a: *u8, b: *u8): i32 { return (a as *i32)[0] - (b as *i32)[0]; } + def main(): void { + val root := sqrt(16.0); + val cube := cbrtf(27f); + val q := div(17, 5); + val w := lldiv(100, 7); + val c := conj(complex { re = 1.5, im = 2.5 }); + var numbers: i32[5] = [5, 3, 1, 4, 2]; + qsort((&mut numbers) as *mut u8, 5, 4, compare_ints); + println($"{root} {cube} {q.quot} {q.rem} {w.quot} {w.rem} {c.re} {c.im}"); + println($"{numbers[0]} {numbers[1]} {numbers[2]} {numbers[3]} {numbers[4]}"); + } + extern module crt when os == windows; + pub struct quotient { pub var quot: i32; pub var rem: i32; } + pub struct wide_quotient { pub var quot: i64; pub var rem: i64; } + pub struct complex { pub var re: f64; pub var im: f64; } + pub def sqrt(x: f64): f64; + pub def cbrtf(x: f32): f32; + pub def div(a: i32, b: i32): quotient; + pub def lldiv(a: i64, b: i64): wide_quotient; + pub def conj(z: complex): complex; + pub def qsort(base: *mut u8, count: u64, size: u64, compare: cfn): void; + """); + t.expects(gives(&got, "4 3 3 2 14 2 1.5 -2.5\n1 2 3 4 5")); + } +} diff --git a/tests/main.sakura b/tests/main.sakura new file mode 100644 index 00000000..9edf87f0 --- /dev/null +++ b/tests/main.sakura @@ -0,0 +1,32 @@ +#! @file main.sakura +#! @author John Christman (sorakatadzuma@gmail.com) +#! @copyright Malunal Studios, LLC. +#! @license MIT +#! +#! Contains the `main` that runs this repository's unit tests, each in a copy of +#! the program of its own: those of finding libraries, in `libraries.sakura`, +#! and those of each of the compiler's libraries, in the folder of its name, as +#! `tests/analyzer/`. Each set is a program of its own, read from the root of +#! the repository, where `core`, `system`, and `runtime` are, with the standard +#! library's repository beside it. +#! +#! `blossom test` runs them as `sakurac.tests` and `sakura.analyzer.tests` and +#! the rest, or, from the root of the repository: +#! +#! ``` +#! sakurac run --lib std=../std --lib sakura::analyzer=analyzer +#! tests/main.sakura tests/libraries.sakura +#! sakurac run --lib sakura::analyzer=analyzer tests/main.sakura tests/analyzer/*.sakura +#! ``` +#! +#! Each library's README gives the libraries its tests read. +#! +#! Add `-- --only TEXT` to run the tests whose name holds the text, and +#! `-- --here` to run them in one program, as a debugger wants. + +import system; +import std::testing; + +def main(args: span): void { + exit(tester::run(args)); +} diff --git a/tests/memory/a_block_released_twice_stops_the_program_1.out b/tests/memory/a_block_released_twice_stops_the_program_1.out new file mode 100644 index 00000000..04752616 --- /dev/null +++ b/tests/memory/a_block_released_twice_stops_the_program_1.out @@ -0,0 +1,5 @@ +released once + +--- exit 1 +sakura: runtime error: Released memory that was not allocated, or was already released. + at main (tests/memory/a_block_released_twice_stops_the_program_1.sakura:6:14) diff --git a/tests/memory/a_block_released_twice_stops_the_program_1.sakura b/tests/memory/a_block_released_twice_stops_the_program_1.sakura new file mode 100644 index 00000000..20d5d37f --- /dev/null +++ b/tests/memory/a_block_released_twice_stops_the_program_1.sakura @@ -0,0 +1,8 @@ +import std::io; +def main(): void { + val block := raw_allocate(16); + raw_release(block); + println("released once"); + raw_release(block); + println("released twice"); +} diff --git a/tests/memory/a_block_used_after_its_release_stops_the_program_1.out b/tests/memory/a_block_used_after_its_release_stops_the_program_1.out new file mode 100644 index 00000000..0ce50871 --- /dev/null +++ b/tests/memory/a_block_used_after_its_release_stops_the_program_1.out @@ -0,0 +1,5 @@ +3 + +--- exit 1 +sakura: runtime error: Pointer reaches memory the program does not hold, as past the end of what it points into, or memory released. + at main (tests/memory/a_block_used_after_its_release_stops_the_program_1.sakura:7:19) diff --git a/tests/memory/a_block_used_after_its_release_stops_the_program_1.sakura b/tests/memory/a_block_used_after_its_release_stops_the_program_1.sakura new file mode 100644 index 00000000..7e6bc848 --- /dev/null +++ b/tests/memory/a_block_used_after_its_release_stops_the_program_1.sakura @@ -0,0 +1,8 @@ +import std::io; +def main(): void { + val block := raw_allocate(16) as *mut i64; + block[0] = 3; + println($"{block[0]}"); + raw_release(block as *mut u8); + println($"{block[0]}"); +} diff --git a/tests/memory/a_program_that_exits_holds_what_its_frames_hold_1.out b/tests/memory/a_program_that_exits_holds_what_its_frames_hold_1.out new file mode 100644 index 00000000..8a9104fe --- /dev/null +++ b/tests/memory/a_program_that_exits_holds_what_its_frames_hold_1.out @@ -0,0 +1,3 @@ +held by main as it exits + +--- exit 3 diff --git a/tests/memory/a_program_that_exits_holds_what_its_frames_hold_1.sakura b/tests/memory/a_program_that_exits_holds_what_its_frames_hold_1.sakura new file mode 100644 index 00000000..d5d00c40 --- /dev/null +++ b/tests/memory/a_program_that_exits_holds_what_its_frames_hold_1.sakura @@ -0,0 +1,12 @@ +import std::io; +import system; +def finish(text: &string): void { + println(text.view()); + system::exit(3); +} +def main(): void { + var text := string::from("held by main", nothing {}); + text.append(" as it exits"); + val block := raw_allocate(32); + finish(&text); +} diff --git a/tests/memory/a_reference_outliving_its_frame_stops_the_program_1.out b/tests/memory/a_reference_outliving_its_frame_stops_the_program_1.out new file mode 100644 index 00000000..ed5b3b88 --- /dev/null +++ b/tests/memory/a_reference_outliving_its_frame_stops_the_program_1.out @@ -0,0 +1,5 @@ +made + +--- exit 1 +sakura: runtime error: Pointer reaches memory the program does not hold, as past the end of what it points into, or memory released. + at main (tests/memory/a_reference_outliving_its_frame_stops_the_program_1.sakura:11:16) diff --git a/tests/memory/a_reference_outliving_its_frame_stops_the_program_1.sakura b/tests/memory/a_reference_outliving_its_frame_stops_the_program_1.sakura new file mode 100644 index 00000000..1844ab69 --- /dev/null +++ b/tests/memory/a_reference_outliving_its_frame_stops_the_program_1.sakura @@ -0,0 +1,12 @@ +import std::io; +struct point { var x: i64; var y: i64; } +# The warning that `p` ends with the function is quieted, so the program runs. +@allow def made(): &point { + var p := point { x = 7, y = 8 }; + return &p; +} +def main(): void { + val p := &made(); + println("made"); + println($"{p.x}"); +} diff --git a/tests/memory/blocks_nothing_reaches_are_reported_where_they_were_allocated_1.out b/tests/memory/blocks_nothing_reaches_are_reported_where_they_were_allocated_1.out new file mode 100644 index 00000000..47fdcb84 --- /dev/null +++ b/tests/memory/blocks_nothing_reaches_are_reported_where_they_were_allocated_1.out @@ -0,0 +1,9 @@ +done + +--- exit 0 +sakura: 7 blocks the program allocated, 127 bytes, were never released, and nothing it keeps reaches them: + 1 block, 16 bytes, allocated at chain (tests/memory/blocks_nothing_reaches_are_reported_where_they_were_allocated_1.sakura:10:28) + 1 block, 16 bytes, allocated at chain (tests/memory/blocks_nothing_reaches_are_reported_where_they_were_allocated_1.sakura:11:31) + 1 block, 40 bytes, allocated at hold (tests/memory/blocks_nothing_reaches_are_reported_where_they_were_allocated_1.sakura:17:36) + 3 blocks, 48 bytes, allocated at lose (tests/memory/blocks_nothing_reaches_are_reported_where_they_were_allocated_1.sakura:5:26) + 1 block, 7 bytes, allocated at named (tests/memory/blocks_nothing_reaches_are_reported_where_they_were_allocated_1.sakura:14:36) diff --git a/tests/memory/blocks_nothing_reaches_are_reported_where_they_were_allocated_1.sakura b/tests/memory/blocks_nothing_reaches_are_reported_where_they_were_allocated_1.sakura new file mode 100644 index 00000000..1ed1a7e3 --- /dev/null +++ b/tests/memory/blocks_nothing_reaches_are_reported_where_they_were_allocated_1.sakura @@ -0,0 +1,26 @@ +import std::io; +struct node { var value: u64; var next: *mut node; } +def lose(count: u64): void { + for i in 0..count { + val n := raw_allocate(size_of::()) as *mut node; + n[0].value = i; + } +} +def chain(): *mut node { + val first := raw_allocate(size_of::()) as *mut node; + first[0].next = raw_allocate(size_of::()) as *mut node; + return first; +} +def named(n: u64): string { return $"block {n}"; } +# What a lost block holds is lost with it, though the block holds its address. +def hold(n: u64): *mut string { + val holder := raw_allocate_zeroed(size_of::()) as *mut string; + holder[0] = named(n); + return holder; +} +def main(): void { + lose(3); + _ = chain(); + _ = hold(4); + println("done"); +} diff --git a/tests/memory/boxes_close_the_fields_of_what_they_hold_1.out b/tests/memory/boxes_close_the_fields_of_what_they_hold_1.out new file mode 100644 index 00000000..b753360a --- /dev/null +++ b/tests/memory/boxes_close_the_fields_of_what_they_hold_1.out @@ -0,0 +1 @@ +released diff --git a/tests/memory/boxes_close_the_fields_of_what_they_hold_1.sakura b/tests/memory/boxes_close_the_fields_of_what_they_hold_1.sakura new file mode 100644 index 00000000..7c4e3627 --- /dev/null +++ b/tests/memory/boxes_close_the_fields_of_what_they_hold_1.sakura @@ -0,0 +1,10 @@ +import std::io; +struct named : owning { var text: string; var more: string; } +def named::close(&mut this): void { this.text.close(); } +def main(): void { + { var held := box::new(named{ text = $"one {1}", more = $"two {2}" }); } + var many := vector::::new(); + many.append(named{ text = $"three {3}", more = $"four {4}" }); + many.close(); + println("released"); +} diff --git a/tests/memory/functions_give_back_the_boxes_they_hold_1.out b/tests/memory/functions_give_back_the_boxes_they_hold_1.out new file mode 100644 index 00000000..16607b78 --- /dev/null +++ b/tests/memory/functions_give_back_the_boxes_they_hold_1.out @@ -0,0 +1 @@ +5 6 4 diff --git a/tests/memory/functions_give_back_the_boxes_they_hold_1.sakura b/tests/memory/functions_give_back_the_boxes_they_hold_1.sakura new file mode 100644 index 00000000..c1c172ae --- /dev/null +++ b/tests/memory/functions_give_back_the_boxes_they_hold_1.sakura @@ -0,0 +1,23 @@ +import std::io; +# A functor too large for a function's buffer is held in a box, which the function +# gives back where it closes, written over, moved, or ended with its scope, so +# nothing is left for the report, the strings the functors hold included. +struct labeled : invokable { + var label: string; + var spare: u64[3]; +} +def labeled::invoke(&mut this): u64 { return this.label.length; } +def made(text: strview): function { + return function::new(labeled { label = string::from(text, nothing {}) }); +} +def main(): void { + var f := made("first"); + val n := f(); + f = made("second"); + var g := move(&mut f); + val m := g(); + var many := vector::>::new(); + for i in 0..20u { many.append(made("many")); } + g.close(); + println($"{n} {m} {many[19]()}"); +} diff --git a/tests/memory/memory_mapped_from_the_system_is_held_until_unmapped_1.out b/tests/memory/memory_mapped_from_the_system_is_held_until_unmapped_1.out new file mode 100644 index 00000000..6bc2a2ae --- /dev/null +++ b/tests/memory/memory_mapped_from_the_system_is_held_until_unmapped_1.out @@ -0,0 +1,6 @@ +10 +unmapped + +--- exit 1 +sakura: runtime error: Pointer reaches memory the program does not hold, as past the end of what it points into, or memory released. + at main (tests/memory/memory_mapped_from_the_system_is_held_until_unmapped_1.sakura:14:19) diff --git a/tests/memory/memory_mapped_from_the_system_is_held_until_unmapped_1.sakura b/tests/memory/memory_mapped_from_the_system_is_held_until_unmapped_1.sakura new file mode 100644 index 00000000..35260131 --- /dev/null +++ b/tests/memory/memory_mapped_from_the_system_is_held_until_unmapped_1.sakura @@ -0,0 +1,33 @@ +import std::io; +import system; +def main(): void { + val page := map(8192); + val words := page as *mut u64; + # Two pages, the second word past the first's end on the second. + words[0] = 1; + words[511] = 2; + words[512] = 3; + words[1023] = 4; + println($"{words[0] + words[511] + words[512] + words[1023]}"); + unmap(page, 8192); + println("unmapped"); + println($"{words[0]}"); +} +# Memory is mapped from the system and given back as each system has it: by +# `mmap` and `munmap` on Linux, and `VirtualAlloc` and `VirtualFree` on Windows. +when os == linux { + def map(bytes: u64): u64 { + return system::linux::syscall(9, 0, bytes, 3, 0x22, 0xFFFFFFFFFFFFFFFF, 0) as u64; + } + def unmap(at: u64, bytes: u64): void { + _ = system::linux::syscall(11, at, bytes, 0, 0, 0, 0); + } +} +else { + def map(bytes: u64): u64 { + return system::windows::VirtualAlloc(0, bytes, 0x3000, 0x04); + } + def unmap(at: u64, bytes: u64): void { + _ = system::windows::VirtualFree(at, 0, 0x8000); + } +} diff --git a/tests/memory/reading_an_undefined_variable_before_writing_it_stops_the_program_1.out b/tests/memory/reading_an_undefined_variable_before_writing_it_stops_the_program_1.out new file mode 100644 index 00000000..9626e44b --- /dev/null +++ b/tests/memory/reading_an_undefined_variable_before_writing_it_stops_the_program_1.out @@ -0,0 +1,6 @@ +36 + +--- exit 1 +sakura: runtime error: Memory was read before anything wrote it, as memory `raw_allocate` gives or a variable `undefined`. + at total (tests/memory/reading_an_undefined_variable_before_writing_it_stops_the_program_1.sakura:11:17) + at main (tests/memory/reading_an_undefined_variable_before_writing_it_stops_the_program_1.sakura:18:19) diff --git a/tests/memory/reading_an_undefined_variable_before_writing_it_stops_the_program_1.sakura b/tests/memory/reading_an_undefined_variable_before_writing_it_stops_the_program_1.sakura new file mode 100644 index 00000000..3fb20534 --- /dev/null +++ b/tests/memory/reading_an_undefined_variable_before_writing_it_stops_the_program_1.sakura @@ -0,0 +1,19 @@ +import std::io; + +# A variable `undefined` holds what its memory happened to until written. +def total(count: u64): u64 { + var parts: u64[8] = undefined; + for i in 0..count { + parts[i] = i + 1; + } + var sum: u64 = 0; + for i in 0..8u { + sum += parts[i]; + } + return sum; +} + +def main(): void { + println($"{total(8)}"); + println($"{total(5)}"); +} diff --git a/tests/memory/reading_past_what_was_allocated_stops_the_program_1.out b/tests/memory/reading_past_what_was_allocated_stops_the_program_1.out new file mode 100644 index 00000000..a63b0c01 --- /dev/null +++ b/tests/memory/reading_past_what_was_allocated_stops_the_program_1.out @@ -0,0 +1,5 @@ +9 + +--- exit 1 +sakura: runtime error: Pointer reaches memory the program does not hold, as past the end of what it points into, or memory released. + at main (tests/memory/reading_past_what_was_allocated_stops_the_program_1.sakura:7:19) diff --git a/tests/memory/reading_past_what_was_allocated_stops_the_program_1.sakura b/tests/memory/reading_past_what_was_allocated_stops_the_program_1.sakura new file mode 100644 index 00000000..160d7cfa --- /dev/null +++ b/tests/memory/reading_past_what_was_allocated_stops_the_program_1.sakura @@ -0,0 +1,8 @@ +import std::io; +def main(): void { + # Ten bytes are asked for, though the block is rounded up to sixteen. + val bytes := raw_allocate(10); + bytes[9] = 9; + println($"{bytes[9]}"); + println($"{bytes[12]}"); +} diff --git a/tests/memory/reading_what_raw_allocate_gave_before_writing_it_stops_the_program_1.out b/tests/memory/reading_what_raw_allocate_gave_before_writing_it_stops_the_program_1.out new file mode 100644 index 00000000..1bac5605 --- /dev/null +++ b/tests/memory/reading_what_raw_allocate_gave_before_writing_it_stops_the_program_1.out @@ -0,0 +1,5 @@ +7 9 + +--- exit 1 +sakura: runtime error: Memory was read before anything wrote it, as memory `raw_allocate` gives or a variable `undefined`. + at main (tests/memory/reading_what_raw_allocate_gave_before_writing_it_stops_the_program_1.sakura:11:19) diff --git a/tests/memory/reading_what_raw_allocate_gave_before_writing_it_stops_the_program_1.sakura b/tests/memory/reading_what_raw_allocate_gave_before_writing_it_stops_the_program_1.sakura new file mode 100644 index 00000000..968f34b7 --- /dev/null +++ b/tests/memory/reading_what_raw_allocate_gave_before_writing_it_stops_the_program_1.sakura @@ -0,0 +1,12 @@ +import std::io; + +# A block `raw_allocate` gave holds what it may until written. Copying it, as +# growing it does, reads nothing, so only what the program reads stops it. +def main(): void { + val words := raw_allocate(16) as *mut u64; + words[0] = 7; + val grown := raw_resize(words as *mut u8, 32) as *mut u64; + grown[2] = 9; + println($"{grown[0]} {grown[2]}"); + println($"{grown[1]}"); +} diff --git a/tests/memory/threads_running_as_the_program_ends_hold_what_their_frames_hold_1.out b/tests/memory/threads_running_as_the_program_ends_hold_what_their_frames_hold_1.out new file mode 100644 index 00000000..3b65352e --- /dev/null +++ b/tests/memory/threads_running_as_the_program_ends_hold_what_their_frames_hold_1.out @@ -0,0 +1 @@ +main ends diff --git a/tests/memory/threads_running_as_the_program_ends_hold_what_their_frames_hold_1.sakura b/tests/memory/threads_running_as_the_program_ends_hold_what_their_frames_hold_1.sakura new file mode 100644 index 00000000..7409c72f --- /dev/null +++ b/tests/memory/threads_running_as_the_program_ends_hold_what_their_frames_hold_1.sakura @@ -0,0 +1,23 @@ +import std::io; +import std::thread; +import std::time; +# The thread's handle is kept where nothing closes it, so the program ends +# without waiting for the thread, which holds a block in its frame. +var worker: maybe> = nothing {}; +var ready := atomic::::new(0); +def work(): void { + val mine := raw_allocate(24); + mine[0] = 1; + ready.store(1, order::release); + while true { + thread::sleep(time::milliseconds(1)); + mine[0] += 1; + } +} +def main(): void { + worker = thread::spawn(work) else (e) { return; }; + while ready.load(order::acquire) == 0 { + thread::sleep(time::milliseconds(1)); + } + println("main ends"); +} diff --git a/tests/memory/unnamed_values_stay_in_their_union_1.out b/tests/memory/unnamed_values_stay_in_their_union_1.out new file mode 100644 index 00000000..326b74a2 --- /dev/null +++ b/tests/memory/unnamed_values_stay_in_their_union_1.out @@ -0,0 +1,3 @@ +true false true true true +made +still 5 diff --git a/tests/memory/unnamed_values_stay_in_their_union_1.sakura b/tests/memory/unnamed_values_stay_in_their_union_1.sakura new file mode 100644 index 00000000..7cd71cf9 --- /dev/null +++ b/tests/memory/unnamed_values_stay_in_their_union_1.sakura @@ -0,0 +1,30 @@ +import std::io; + +# `_` names nothing, so a test or an arm naming a field's value `_` takes nothing +# out of the union: a box stays with the holder a reference reaches, and one a +# call made is closed once, with the union. +struct holder { var b: maybe>; } + +def holds(h: &holder): bool { return h.b is some(_); } +def lacks(h: &holder): bool { return h.b is not some(_); } +def arm(h: &holder): bool { + match h.b { + some(_) => { return true; } + none => { return false; } + } + return false; +} +def made(): maybe> { return box::::new(7); } + +def main(): void { + var h := holder{ b = box::::new(5) }; + val first := holds(&h); + val missing := lacks(&h); + val matched := arm(&h); + println($"{first} {missing} {matched} {holds(&h)} {made() is some(_)}"); + match made() { + some(_) => { println("made"); } + none => {} + } + if h.b is some(&b) { println($"still {b.get()}"); } +} diff --git a/tests/memory/what_the_program_still_holds_is_not_reported_1.out b/tests/memory/what_the_program_still_holds_is_not_reported_1.out new file mode 100644 index 00000000..701e6639 --- /dev/null +++ b/tests/memory/what_the_program_still_holds_is_not_reported_1.out @@ -0,0 +1 @@ +1 5 6 2 diff --git a/tests/memory/what_the_program_still_holds_is_not_reported_1.sakura b/tests/memory/what_the_program_still_holds_is_not_reported_1.sakura new file mode 100644 index 00000000..9c4105ce --- /dev/null +++ b/tests/memory/what_the_program_still_holds_is_not_reported_1.sakura @@ -0,0 +1,22 @@ +import std::io; +import std::containers; +struct node { var value: u64; var next: *mut node; } +var kept: *mut node; +var names: vector; +def main(): void { + # Blocks a global reaches, and those they reach in turn. + kept = raw_allocate(size_of::()) as *mut node; + kept[0].next = raw_allocate(size_of::()) as *mut node; + kept[0].next[0].next = raw_allocate(size_of::()) as *mut node; + names = vector::::new(); + names.append(string::from("kept", nothing {})); + + # Owners that close what they hold. + var v := vector::::new(); + v.append(1); + val b := box::::new(5); + var r := rc::::new(6); + var also := copy(&r); + val text := $"{v[0]} {b.get()} {also.get()} {r.count()}"; + println(text.view()); +} diff --git a/tests/native/native.sakura b/tests/native/native.sakura new file mode 100644 index 00000000..516b366e --- /dev/null +++ b/tests/native/native.sakura @@ -0,0 +1,1292 @@ +#! @file native.sakura +#! @author John Christman (sorakatadzuma@gmail.com) +#! @copyright Malunal Studios, LLC. +#! @license MIT +#! +#! Contains the tests of executables: the register allocator and the checker +#! replaying what it chose, and programs built and run. The encoder of x86-64 +#! instructions is tested where it is, as `binary::amd64` in `binary`'s +#! repository. +#! Programs are built over the standard library's repository beside this one, +#! else the `std` beside `sakura` or above it. The debugging information and +#! the calls of C are tested by building programs over it, then reading the +#! files written and what gdb and valgrind make of them, where those are +#! installed; where no standard library is found, those tests pass over what +#! they test. + +import std::io; +import std::process; +import system; +import std::testing; +import sakura::analyzer; +import sakura::compiler; +import sakura::machine; +import sakura::server; +import binary::amd64; +import binary::elf; +module sakura::native; + + +@test def vectors_become_values_and_functions_asking_get_versions(t: &mut tester): void { + val held := test_library(); + val library := held.view(); + val got := lowered_vectors(library, """ + import std::math; + # 16 bytes of lanes, of SSE2 alone: the sum carried around the loop is a + # vector the loop's block takes, as is the sum the loop, rotated, leaves + # with, and nothing asks the processor. + def sum_words(text: strview): u32 { + var total := u32x4::splat(0); + var at: u64 = 0; + while at + 16 <= text.length { + total = total + u8x16::load(text, at).bits::(); + at += 16; + } + return total.sum(); + } + # 32 bytes of lanes, of AVX2 and FMA3: the function asks, holding the lanes + # in memory, and its version holds the sum in a register. + def dots(xs: span, ys: span): f32 { + var acc := f32x8::splat(0.0); + var at: u64 = 0; + while at + 8 <= xs.length { + acc = f32x8::load(xs, at).fma(&f32x8::load(ys, at), &acc); + at += 8; + } + return acc.sum(); + } + # The sum is called twice, so it is optimized as a function of its own, + # rather than only where one call alone would copy it. + def main(): void { + val xs: f32[16] = [1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0]; + if sum_words("0123456789abcdef0123456789abcdef") > 0 && dots(xs[:], xs[:]) > 0.0 { return; } + if sum_words("fedcba9876543210fedcba9876543210") > 0 { return; } + } + """, "sum_words dots"); + if !t.expects(got.view() == "sum_words: v128 2 v256 0;dots: v128 0 v256 0 asks version: v128 0 v256 2 wide;") { + println(got); + } +} + +# An `f32` held as one in the register an arithmetic of `f64`s puts its result +# in is widened before the first operand is loaded there, which would lose it: +# at `-O1`, `a * c` was worked as `a * a`, so the ray met the ball at 0. +@test def a_single_where_the_result_goes_is_widened_first(t: &mut tester): void { + val held := test_library(); + val library := held.view(); + val text := """ + import std::io; + import std::math; + struct v3 { var x: f32; var y: f32; var z: f32; var _w: f32; } + def v3::sub(&this, other: &v3): v3 { return v3{ this.x - other.x, this.y - other.y, this.z - other.z }; } + def dot(a: &v3, b: &v3): f32 { return a.x * b.x + a.y * b.y + a.z * b.z; } + struct ball { var center: v3; var radius: f32; } + struct line { var origin: v3; var direction: v3; } + def hit(r: &line, s: ball): maybe { + val m := r.origin - s.center; + val c := dot(&m, &m) - s.radius * s.radius; + return 0f if c <= 0; + val b := dot(&m, &r.direction); + return nothing {} if b >= 0; + val a := dot(&r.direction, &r.direction); + val e := b * b - a * c; + return nothing {} if e < 0; + return (-b - math::sqrt(e)) / a; + } + def main(): void { + val r := line{ v3{ 0, 0, 10 }, v3{ 0, 0, -1 } }; + if hit(&r, ball{ v3{ 0, 0, 0 }, 2 }) is some(t) { io::println($"hit {t}"); } + } + """; + val directory := scratch_directory("single"); + val output := $"{directory}/single"; + for level in 0..3u { + val problems := built(library, "single.sakura", text, output.view(), level as u32, false); + if !t.expects(problems.length == 0) { + println(problems[0]); + return; + } + val alone: strview[1] = [output.view()]; + t.expects(output_of(alone[:]).view() == "hit 8\n"); + } +} + +# Each operation of 64 bytes of lanes gives the same bits whichever +# instructions work it: AVX-512's where the processor has them, as the program +# runs with every set it has, and halves of 32 bytes, quarters of 16, or a lane +# at a time where `SAKURA_CPU` names fewer. +@test def vectors_of_64_bytes_give_the_same_bits_at_every_level(t: &mut tester): void { + val held := test_library(); + val library := held.view(); + val text := """ + import std::io; + import std::math; + var seed: u64 = 0x9E3779B97F4A7C15; + def next(): u64 { + seed = seed ^ (seed << 13); + seed = seed ^ (seed >> 7); + seed = seed ^ (seed << 17); + return seed; + } + def random(): simd where L: numeric, ordered, zeroable { + var made: simd; + for i in 0..N { + if const L is real { + made[i] = ((next() % 4001) as f64 / 8.0 - 250.0) as L; + } else { + made[i] = next() as L; + } + } + return made; + } + def mix(total: &mut u64, v: &simd): void where L: numeric, ordered, zeroable { + val lanes := v.lanes(); + val bytes := (&lanes) as *u8; + for i in 0..N * size_of::() { + total = total * 31 + bytes[i] as u64; + } + } + def work(name: strview): void where L: numeric, ordered, zeroable { + var total: u64 = 0; + for round in 0..4u { + val a := random::(); + val b := random::(); + val c := random::(); + mix(&mut total, &(a + b)); + mix(&mut total, &(a - b)); + mix(&mut total, &(a * b)); + mix(&mut total, &(-a)); + mix(&mut total, &a.min(&b)); + mix(&mut total, &a.max(&b)); + mix(&mut total, &a.abs()); + mix(&mut total, &select(a.less(&b), a, b)); + mix(&mut total, &simd::::splat(a[3])); + total = total * 31 + a.less_equal(&b).bits() as u64 + a.greater(&b).bits() as u64 + a.not_equal(&c).bits() as u64; + if const L is real { + mix(&mut total, &(a / b)); + mix(&mut total, &a.fma(&b, &c)); + mix(&mut total, &a.abs().sqrt()); + mix(&mut total, &a.floor()); + mix(&mut total, &a.ceil()); + mix(&mut total, &a.trunc()); + mix(&mut total, &a.round_even()); + } + if const L is integer { + mix(&mut total, &(a & b)); + mix(&mut total, &(a | b)); + mix(&mut total, &(a ^ b)); + mix(&mut total, &(~a)); + mix(&mut total, &(a << (5 * round) as u32)); + mix(&mut total, &(a >> (7 * round) as u32)); + } + } + io::println($"{name} {total}"); + } + def main(): void { + work::("f32x16"); + work::("f64x8"); + work::("i16x32"); + work::("u16x32"); + work::("i32x16"); + work::("u32x16"); + work::("i64x8"); + work::("u64x8"); + } + """; + # As the machine works it, a lane at a time. + val worked := """ + f32x16 10445650904537259042 + f64x8 7249810911814254236 + i16x32 3398466155064983875 + u16x32 12242828003529389835 + i32x16 11519081872094451891 + u32x16 11665688344890517076 + i64x8 17535756281166082821 + u64x8 14177733201979375858 + """; + val directory := scratch_directory("wide"); + val output := $"{directory}/wide"; + val levels: u32[2] = [0, 2]; + val cpus: strview[4] = ["x86-64", "x86-64-v2", "x86-64-v3", "x86-64-v4"]; + for &level in levels { + val problems := built(library, "wide.sakura", text, output.view(), level, false); + if !t.expects(problems.length == 0) { + println(problems[0]); + return; + } + var outputs := vector::::new(); + for &cpu in cpus { + var started := process::command::new(output.view()); + started.set_variable("SAKURA_CPU", cpu); + started.input(process::stdio::none); + val got := started.capture() else (_) { t.expects(false); return; }; + t.expects(got.error.length == 0); + outputs.append(string::copy_of(&got.output)); + } + for &each in outputs { + if !t.expects(each.view() == worked) { + println($"{each}against\n{worked}"); + } + } + } +} + +@test def executables_built_on_threads_are_those_built_on_one(t: &mut tester): void { + val held := test_library(); + val library := held.view(); + val text := """ + import std::io; + struct pair { var name: string; var count: u64; } + def tally(words: span): vector { + var made := vector::::new(); + for &word in words { + var found := false; + for &mut each in made { + if each.name.view() == word { each.count += 1; found = true; } + } + if !found { made.append(pair { name = string::from(word, nothing {}), count = 1 }); } + } + return made; + } + def main(): void { + val words: strview[6] = ["a", "b", "a", "c", "b", "a"]; + val counted := tally(words[:]); + for &each in counted { println($"{each.name}: {each.count}"); } + } + """; + # Each is built to the same path in turn, read before the next is built, as + # `-g` writes into the executable the path of its debug information: its name + # alone on Linux, but the PDB file's whole path on Windows. The first is + # removed before the second is built, so what is read is what that wrote. + val directory := scratch_directory("threads"); + val output := $"{directory}/threads"; + for level in 0..3u { + for debug in 0..2u { + t.expects(built(library, "threads.sakura", text, output.view(), level as u32, debug == 1, 1).length == 0); + val one_bytes := file_bytes(output.view()); + remove_file(output.view()); + t.expects(built(library, "threads.sakura", text, output.view(), level as u32, debug == 1, 4).length == 0); + val many_bytes := file_bytes(output.view()); + t.expects(one_bytes.length != 0 && one_bytes.view() == many_bytes.view()); + } + } +} + +@test def an_executable_leaving_contracts_out_is_that_of_the_source_without_them(t: &mut tester): void { + val held := test_library(); + val library := held.view(); + val text := """ + import std::io; + def total(xs: span, limit: i64): i64 { + expects(xs.length != 0, "A total is of some numbers."); + ensures(r: r <= old(limit) * xs.length as i64); + var sum: i64 = 0; + val add := def(k: i64): i64 { + asserts(k <= limit, "Each is under the limit."); + return sum + k; + }; + for &x in xs { + ensures(sum >= 0); + sum = add(x); + } + return sum; + } + def main(): void { + val xs: i64[3] = [1, 2, 3]; + io::println($"{total(xs[:], 5)}"); + } + """; + # The same, with each contract written over with spaces, so all else is + # where it was. + var without := string::new(nothing {}); + for &line in text.split(&'\n') { + val trimmed := line.trim(); + val contract := trimmed.starts_with("expects(") || trimmed.starts_with("asserts(") || trimmed.starts_with("ensures("); + for &byte in line { + without.push(contract ? ' ' as u8 : byte); + } + without.push('\n' as u8); + } + without.resize(without.length - 1); + + val off_directory := scratch_directory("contracts_off"); + val plain_directory := scratch_directory("contracts_plain"); + for level in 0..3u { + val off := $"{off_directory}/contracts"; + val plain := $"{plain_directory}/contracts"; + t.expects(built(library, "contracts.sakura", text, off.view(), level as u32, false, 1, true).length == 0); + t.expects(built(library, "contracts.sakura", without.view(), plain.view(), level as u32, false).length == 0); + val off_bytes := file_bytes(off.view()); + val plain_bytes := file_bytes(plain.view()); + t.expects(off_bytes.length != 0 && off_bytes.view() == plain_bytes.view()); + } +} + +# A program built checked stops at an index past the end, and one built without +# its checks reads there, while both stop where the processor faults: at null, +# within the first page, and at a division by zero, which their runtime reports +# with the frames, as the checks did. +@test def executables_unchecked_stop_only_where_the_processor_faults(t: &mut tester): void { + val held := test_library(); + val library := held.view(); + val text := """ + import std::io; + struct cell { var value: i64; var next: *cell; } + def divide(a: i64, b: i64): i64 { return a / b; } + def follow(at: *cell): i64 { return at[0].next[1].value; } + def past(xs: span, i: u64): i64 { return xs[i]; } + def main(args: span): void { + val xs: i64[4] = [1, 2, 3, 4]; + if args.length == 0 { + io::println($"{checking()} {past(xs[0:2], 3)}"); + } else if args[0] == "divide" { + io::println($"{divide(7, args.length as i64 - 1)}"); + } else { + val first := cell { value = 1 }; + io::println($"{follow(&first as *cell)}"); + } + } + """; + val directory := scratch_directory("unchecked"); + for level in 0..3u { + val checked := $"{directory}/checked"; + val unchecked := $"{directory}/unchecked"; + t.expects(built(library, "faults.sakura", text, checked.view(), level as u32, false).length == 0); + t.expects(built(library, "faults.sakura", text, unchecked.view(), level as u32, false, 1, false, true).length == 0); + val alone: strview[1] = [checked.view()]; + val stopped := output_of(alone[:]); + t.expects(holds(stopped.view(), "Index or slice is out of bounds.") && holds(stopped.view(), "at past (faults.sakura:5:")); + val bare: strview[1] = [unchecked.view()]; + t.expects(output_of(bare[:]).view() == "false 4\n"); + val both: strview[2] = [checked.view(), unchecked.view()]; + for &each in both { + val dividing: strview[2] = [each, "divide"]; + val divided := output_of(dividing[:]); + t.expects(holds(divided.view(), "Division by zero.") && holds(divided.view(), "at divide (faults.sakura:3:")); + val following: strview[2] = [each, "follow"]; + val followed := output_of(following[:]); + t.expects(holds(followed.view(), "Null reference was unwrapped.") && holds(followed.view(), "at follow (faults.sakura:4:")); + } + } +} + +@test def comparisons_give_the_conditions_their_jumps_test(t: &mut tester): void { + t.expects(condition_of(op::ltu) == cc::below); + t.expects(condition_of(op::les) == cc::less_equal); + t.expects(opposite(cc::below) == cc::above_equal); + t.expects(opposite(cc::equal) == cc::not_equal); + t.expects(swapped(cc::less) == cc::greater); +} + +#! Lowers a program, places the values of every function it lowers, and +#! replays where they were placed, giving what is wrong. +#! @param text The program. +#! @returns What is wrong, or `the program does not check`. +def placing_problems(text: strview): vector { + var held := names::new(); + var notes := vector::::new(); + var sources := vector::::new(); + var syntaxes := vector::::new(); + sources.reserve(1); + syntaxes.reserve(1); + sources.append(source::from("test.sakura", text)); + syntaxes.append(syntax::new()); + var lexing := lexer::new(sources.at(0), &mut held, &mut notes, 0); + lexing.tokenize_all(syntaxes.at(0)); + var parsing := parser::new(syntaxes.at(0), &held, &mut notes, 0); + val root := parsing.parse(); + var checker := checker::new(&mut held, &mut notes); + checker.add(sources.at(0), syntaxes.at(0), root); + checker.check(); + + var problems := vector::::new(); + if notes.length != 0 { + problems.append(string::from("the program does not check", nothing {})); + return problems; + } + var lowering := lowerer::new(&mut checker, lowering { verify = true, everything = true, level = 2 }); + lowering.compile(); + for &each in lowering.problems { + problems.append(string::copy_of(&each)); + } + for i in 0..lowering.program.functions.length { + val function := &lowering.program.functions.at(i); + continue if !function.lowered; + val point := mark_scratch(); + var memory := vector::::new(scratch()); + for &each in lowering.program.signatures.at(function.signature).params { + val shape: layout = lowering.program.layouts.at(each); + if in_memory(&shape) { + memory.append(true); + continue; + } + for _ in 0..word_count(&shape) { + memory.append(false); + } + } + if function.closure { + memory.append(false); + memory.append(false); + } + val placed := place_values(&function.body, memory.view()); + for &each in check_placing(&function.body, &placed) { + problems.append($"{function.name}: {each}"); + } + release_scratch(point); + } + return problems; +} + +@test def values_are_placed_where_they_are_read_across_loops_and_calls(t: &mut tester): void { + val found := placing_problems(""" + def pick(a: u64, b: u64, c: u64): u64 { return a > b ? c : a + b; } + def many(a: u64, b: u64, c: u64, d: u64, e: u64, f: u64, g: u64, h: u64, i: u64, j: u64, k: u64, l: u64, m: u64): u64 { + return a + b * c - d + e * f + g - h + i * j + k - l + m; + } + def steps(start: u64): u64 { + var n := start; + var count: u64 = 0; + while n != 1 { + if n % 2 == 0 { n = n / 2; } else { n = 3 * n + 1; } + count += pick(count, n, 1); + } + return count; + } + def swap_round(rounds: u64): u64 { + var a: u64 = 1; + var b: u64 = 2; + for _ in 0..rounds { + val t := a; + a = b; + b = t + many(a, b, t, a, b, t, a, b, t, a, b, t, a); + } + return a ^ b; + } + def mean(xs: f64[4]): f64 { + var total := 0.0; + for x in xs { total += x * 0.5; } + return total / 4.0; + } + def main(): void { + val s := steps(27) + swap_round(10); + val m := mean([1.0, 2.0, 3.0, 4.0]); + if s > 0 && m > 0.0 { return; } + } + """); + for &each in found { + println(each); + } + t.expects(found.length == 0); +} + + +# Debugging information. + +#! The program the tests of debugging information build and debug. +const debugged: strview = "\nimport std::io;\nstruct point { var x: i64; var y: i64; }\ndef scale(p: point, by: i64): point {\n val scaled := point{p.x * by, p.y * by};\n return scaled;\n}\ndef main(): void {\n var total: i64 = 0;\n for i in 1..4 {\n val p := scale(point{i, i + 1}, 2);\n total += p.x + p.y;\n }\n println($\"{total}\");\n}\n"; + +#! Finds every file of a directory of the standard library and those within it, +#! as `entry` does, but those of a `tests` folder: the standard library's +#! repository, which may be the one found, keeps its tests there, and no module +#! is a folder of that name. +#! @param directory The directory. +#! @param found Where the paths are written. +def sakura_files(directory: strview, found: &mut vector): void { + var at := path::parse(directory) else (_) { return; }; + var listing := io::directory::open(&at) else (_) { return; }; + var inner := vector::::new(); + while listing.next() is some(each) { + continue if each.name.length == 0 || each.name.at(0) == '.'; + continue if each.kind == file_kind::directory && each.name.view() == "tests"; + var joined := $"{directory}/{each.name}"; + if each.kind == file_kind::directory { + inner.append(move(&mut joined)); + } else if each.name.length > 7 && each.name.substr(each.name.length - 7, 7) == ".sakura" { + found.append(move(&mut joined)); + } + } + for &each in inner { + sakura_files(each.view(), found); + } +} + +#! The standard library the tests build over: its repository beside this one, +#! as the corpus reads it, else the `std` beside `sakura` or above it, found as +#! `core` is. +#! @returns Its folder, made absolute, or empty where there is none. +def test_library(): string { + if path::parse("../std") is value(&beside) { + if io::absolute(&beside) is value(&whole) { + return string::from(whole.view(), nothing {}) if is_folder(whole.view()); + } + } + return toolchain_folder("std"); +} + +#! The files a program reads besides its own, as `entry` gathers them: the +#! types the syntax makes, `core`'s, `system`'s, the runtime's, and the +#! standard library's. +#! @param library Where the standard library is. +#! @param found Where the paths are written. +def library_paths(library: strview, found: &mut vector): void { + found.append(string::from(builtin_path, nothing {})); + val core := toolchain_folder("core"); + sakura_files(core.view(), found); + val platform := toolchain_folder("system"); + sakura_files(platform.view(), found); + val runtime := toolchain_folder("runtime"); + sakura_files(runtime.view(), found); + sakura_files(library, found); +} + +#! The source of a file `library_paths` gave. +#! @param at The file's path. +#! @returns Its source. +def library_source(at: strview): source { + return source::from(builtin_path, builtin_text) if at == builtin_path; + return source::open(at); +} + +#! Builds a program over a standard library into an executable, as +#! `entry build` does. +#! @param library Where the standard library is. +#! @param name The path the program is named by. +#! @param text The program. +#! @param output Where the executable is written. +#! @param level How much its code is optimized. +#! @param debug Whether its debugging information is written too. +#! @param threads How many threads optimize it and place its values. +#! @param contracts_off Whether its contracts are left out. +#! @returns What went wrong, which is nothing where it was built. +def built( + library: strview, name: strview, text: strview, output: strview, level: u32, debug: bool, threads: u32 = 1, contracts_off: bool = false, + checks_off: bool = false, for_windows: bool = false +): vector { + var paths := vector::::new(); + val program := paths.length; + paths.append(string::from(name, nothing {})); + library_paths(library, &mut paths); + + var names := names::new(); + var notes := vector::::new(); + var sources := vector::::new(); + var syntaxes := vector::::new(); + var roots := vector::::new(); + sources.reserve(paths.length); + syntaxes.reserve(paths.length); + for j in 0..paths.length { + if j == program { + sources.append(source::from(name, text)); + } else { + sources.append(library_source(paths.at(j).view())); + } + syntaxes.append(syntax::new()); + } + for j in 0..paths.length { + var lexing := lexer::new(sources.at(j), &mut names, &mut notes, j as u32); + lexing.tokenize_all(syntaxes.at(j)); + var parsing := parser::new(syntaxes.at(j), &names, &mut notes, j as u32); + roots.append(parsing.parse()); + } + var checker := checker::new(&mut names, &mut notes); + checker.target.backend = checker.names.intern(&"native"); + val system: strview = for_windows ? "windows" : test_os; + checker.target.os = checker.names.intern(&system); + checker.contracts_off = contracts_off; + checker.checks_off = checks_off; + for j in 0..paths.length { + checker.add(sources.at(j), syntaxes.at(j), roots.at(j)); + } + checker.check(); + var results := outcomes::new(); + if notes.length == 0 { + results = evaluate(&mut checker); + } + var problems := vector::::new(); + for &each in notes { + val at := sources.at(each.file).lines.place_of(each.offset); + problems.append($"{sources.at(each.file).path}:{at.line}:{at.column}: {each.code}"); + } + return problems if problems.length != 0; + + var lowered := lowerer::new(&mut checker, lowering { level = level, keep_locals = level == 0, describe = debug, threads = threads }); + lowered.evaluated = move(&mut results); + lowered.compile(); + return move(&mut lowered.problems) if lowered.problems.length != 0; + return build_executable(&mut lowered, build_options { output = output, debug = debug, windows = test_windows || for_windows, threads = threads }); +} + +# The system the tests build executables for, which is the one they run on, so +# the executables they build run. +when os == linux { + val test_os: strview = "linux"; + val test_windows: bool = false; +} +when os == windows { + val test_os: strview = "windows"; + val test_windows: bool = true; +} + +#! Lowers a program over a standard library as an executable optimized with +#! inlining, as `built` does, and describes the code of the functions named: +#! for each, the vectors its blocks take, as `v128` and `v256`, whether it asks +#! which instructions the processor has, and the same of its version for +#! x86-64-v3, where it has one. +#! @param library Where the standard library is. +#! @param text The program. +#! @param names The functions, separated by spaces. +#! @returns The description, or what went wrong. +def lowered_vectors(library: strview, text: strview, names: strview): string { + var paths := vector::::new(); + paths.append(string::from("test0.sakura", nothing {})); + library_paths(library, &mut paths); + var held := names::new(); + var notes := vector::::new(); + var sources := vector::::new(); + var syntaxes := vector::::new(); + var roots := vector::::new(); + sources.reserve(paths.length); + syntaxes.reserve(paths.length); + for j in 0..paths.length { + if j == 0 { + sources.append(source::from("test0.sakura", text)); + } else { + sources.append(library_source(paths.at(j).view())); + } + syntaxes.append(syntax::new()); + } + for j in 0..paths.length { + var lexing := lexer::new(sources.at(j), &mut held, &mut notes, j as u32); + lexing.tokenize_all(syntaxes.at(j)); + var parsing := parser::new(syntaxes.at(j), &held, &mut notes, j as u32); + roots.append(parsing.parse()); + } + var checker := checker::new(&mut held, &mut notes); + checker.target.backend = checker.names.intern(&"native"); + for j in 0..paths.length { + checker.add(sources.at(j), syntaxes.at(j), roots.at(j)); + } + checker.check(); + var out := string::new(nothing {}); + if notes.length != 0 { + out.append("the program does not check"); + return out; + } + var results := evaluate(&mut checker); + var lowered := lowerer::new(&mut checker, lowering { level = 2, verify = true }); + lowered.evaluated = move(&mut results); + lowered.compile(); + for &each in lowered.problems { + out.append(each.view()); + out.append("\n"); + } + var wanted := string::from(names, nothing {}); + val functions := &lowered.program.functions; + for name in wanted.split(' ') { + for i in 0..functions.length { + val function := &functions[i]; + continue if function.name.view() != name || function.body.wide; + out.append($"{name}:{described_vectors(&function.body)}"); + if function.version != 0 { + out.append($" version:{described_vectors(&functions[function.version - 1].body)}"); + } + out.append(";"); + } + } + return out; +} + +#! The vectors code's blocks take, and whether it asks which instructions the +#! processor has, and holds 32 bytes of lanes, as `lowered_vectors` describes. +#! @param body The code. +#! @returns The description. +def described_vectors(body: &code): string { + var narrow: u32 = 0; + var wide: u32 = 0; + for b in 0..body.blocks.length { + continue if body.blocks.at(b).gone; + for ¶m in body.blocks.at(b).params.view() { + val kind := body.origins.at(param).kind; + if kind == vt::v128 { + narrow++; + } else if kind == vt::v256 { + wide++; + } + } + } + var asks := false; + for i in 0..body.insts.length { + asks = asks || body.insts.at(i).kind == op::cpu; + } + var made := $" v128 {narrow} v256 {wide}"; + if asks { + made.append(" asks"); + } + if body.wide { + made.append(" wide"); + } + return made; +} + +#! A directory of its own for what a test writes, made where it is not yet, +#! named for the process too, so tests running at once each write their own. +#! @param name The test's name for it. +#! @returns Its path. +def scratch_directory(name: strview): string { + var base: strview = "/tmp"; + if process::variable("TMPDIR") is some(found) { + base = found; + } else if process::variable("TEMP") is some(found) { + base = found; + } else if process::variable("TMP") is some(found) { + base = found; + } + val made := $"{base}/sakura-native-{system::getpid()}-{name}"; + var at := path::parse(made.view()) else (_) { return made; }; + _ = io::create_directories(&at); + return made; +} + +#! The bytes of a file, or none where it can't be read. +#! @param at The file's path. +#! @returns The bytes. +def file_bytes(at: strview): string { + var parsed := path::parse(at) else (_) { return string::new(nothing {}); }; + var read := io::read_file(&parsed) else (_) { return string::new(nothing {}); }; + return move(&mut read); +} + +#! Whether a file is there. +#! @param at The file's path. +#! @returns Whether it is. +def file_exists(at: strview): bool { + var parsed := path::parse(at) else (_) { return false; }; + return io::exists(&parsed); +} + +#! Removes a file, where it is there. +#! @param at The file's path. +def remove_file(at: strview): void { + var parsed := path::parse(at) else (_) { return; }; + _ = io::remove(&parsed); +} + +#! A little-endian number of a file's bytes, or 0 past their end. +#! @param bytes The bytes. +#! @param at Where it begins. +#! @param size How many bytes it takes. +#! @returns The number. +def number_at(bytes: strview, at: u64, size: u64): u64 { + return 0 if at + size > bytes.length; + var value: u64 = 0; + for i in 0..size { + value = value | (bytes.at(at + i) as u64 << (8 * i)); + } + return value; +} + +#! A section of an ELF file, as its header describes it. +struct found_section { + var found: bool; + var kind: u64; + var address: u64; + var size: u64; + var bytes: strview; #! What the file holds of it, or nothing where it holds none. +} + +#! The section of an ELF file named so, or one not found. +#! @param bytes The file's bytes. +#! @param name The section's name. +#! @returns The section. +def section_named(bytes: strview, name: strview): found_section { + val headers := number_at(bytes, 40, 8); + val count := number_at(bytes, 60, 2); + val names := headers + 64 * number_at(bytes, 62, 2); + val names_at := number_at(bytes, names + 24, 8); + for i in 0..count { + val at := headers + 64 * i; + val named := names_at + number_at(bytes, at, 4); + continue if named + name.length >= bytes.length; + continue if bytes.substr(named, name.length) != name || bytes.at(named + name.length) != 0; + val kind := number_at(bytes, at + 4, 4); + val size := number_at(bytes, at + 32, 8); + val offset := number_at(bytes, at + 24, 8); + return found_section { + found = true, + kind = kind, + address = number_at(bytes, at + 16, 8), + size = size, + bytes = kind == 8 ? strview::empty() : bytes.substr(offset, size) + }; + } + return found_section { bytes = strview::empty() }; +} + +#! A loaded segment of an ELF file, as its program header describes it. +struct found_segment { + var flags: u64; + var offset: u64; + var address: u64; + var held: u64; #! The bytes the file holds of it. + var memory: u64; #! The bytes it takes loaded. +} + +#! The loaded segments of an ELF file. +#! @param bytes The file's bytes. +#! @returns The segments, in order. +def loads_of(bytes: strview): vector { + var made := vector::::new(); + val headers := number_at(bytes, 32, 8); + for i in 0..number_at(bytes, 56, 2) { + val at := headers + 56 * i; + continue if number_at(bytes, at, 4) != 1; + made.append(found_segment { + flags = number_at(bytes, at + 4, 4), + offset = number_at(bytes, at + 8, 8), + address = number_at(bytes, at + 16, 8), + held = number_at(bytes, at + 32, 8), + memory = number_at(bytes, at + 40, 8) + }); + } + return made; +} + +#! Runs a program, giving what it wrote to its output and its error, one after +#! the other, or nothing where it could not be started. +#! @param words The program, then its arguments. +#! @returns What it wrote. +def output_of(words: span): string { + var started := process::command::new(words.at(0)); + for i in 1..words.length { + started.argument(words.at(i)); + } + started.input(process::stdio::none); + val got := started.capture() else (_) { return string::new(nothing {}); }; + var made := string::copy_of(&got.output); + made.append(got.error.view()); + return made; +} + +#! Whether text holds other text. +#! @param text The text searched. +#! @param piece The text looked for. +#! @returns Whether it does. +def holds(text: strview, piece: strview): bool { + return true if piece.length == 0; + return false if piece.length > text.length; + for i in 0..text.length - piece.length + 1 { + return true if text.substr(i, piece.length) == piece; + } + return false; +} + +when os == linux { +# A program calls C's own library through an `extern module`: functions taking +# and giving numbers, pointers, and a struct by value, a union given by its +# address, and a function of the program C calls back. +@test def c_functions_are_called_through_extern_sections(t: &mut tester): void { + val standard := test_library(); + return if standard.length == 0; + val library := standard.view(); + val directory := scratch_directory("extern"); + val made := $"{directory}/calls_c"; + val problems := built(library, "calls_c.sakura", """ + import std::io; + extern import "libc.so.6" when os == linux; + + def compare_ints(a: *u8, b: *u8): i32 { return (a as *i32)[0] - (b as *i32)[0]; } + + def main(): void { + val q := clib::div(17, 5); + println($"{clib::length_of("hello\\0")} {q.quot} {q.rem}"); + var numbers: i32[5] = [5, 3, 1, 4, 2]; + clib::qsort((&mut numbers) as *mut u8, 5, 4, compare_ints); + println($"{numbers[0]} {numbers[1]} {numbers[2]} {numbers[3]} {numbers[4]}"); + var w := clib::word { whole = 0x0102030405060708 }; + var copy := clib::word { whole = 0 }; + clib::memcpy((&mut copy) as *mut u8, (&w) as *u8, 8); + println($"{copy.halves[0]} {copy.halves[1]} {copy.bytes[0]}"); + } + + extern module clib when os == linux; + + pub struct quotient { pub var quot: i32; pub var rem: i32; } + pub union word { pub var whole: u64; pub var halves: u32[2]; pub var bytes: u8[8]; } + + pub def strlen(text: *u8): u64; + pub def div(a: i32, b: i32): quotient; + pub def qsort(base: *mut u8, count: u64, size: u64, compare: cfn): void; + pub def memcpy(into: *mut u8, from: *u8, count: u64): *mut u8; + + pub def length_of(text: strview): u64 { return strlen(text.data); } + """, made.view(), 2, false); + for &each in problems { + println(each); + } + return if !t.expects(problems.length == 0); + val ran: strview[1] = [made.view()]; + t.expects(output_of(ran[:]).view() == "5 3 2\n1 2 3 4 5\n84281096 16909060 8\n"); +} + +# Debugging information goes to a file of its own beside the executable, which +# the executable names, and leaves everything the executable loads as it was. +@test def debugging_information_is_written_beside_the_executable(t: &mut tester): void { + val standard := test_library(); + return if standard.length == 0; + val library := standard.view(); + val directory := scratch_directory("described"); + val plain := $"{directory}/plain"; + val debug := $"{directory}/debug"; + val petal := $"{directory}/debug.petal"; + remove_file($"{plain}.petal".view()); + val plain_problems := built(library, "test0.sakura", debugged, plain.view(), 0, false); + val debug_problems := built(library, "test0.sakura", debugged, debug.view(), 0, true); + for &each in plain_problems { + println(each); + } + for &each in debug_problems { + println(each); + } + return if !t.expects(plain_problems.length == 0 && debug_problems.length == 0); + t.expects(file_exists(petal.view())); + t.expects(!file_exists($"{plain}.petal".view())); + val ran: strview[1] = [debug.view()]; + t.expects(output_of(ran[:]).view() == "30\n"); + + val plain_file := file_bytes(plain.view()); + val debug_file := file_bytes(debug.view()); + val petal_file := file_bytes(petal.view()); + val loaded: strview[3] = [".rodata", ".text", ".lines"]; + for &name in loaded { + val a := section_named(plain_file.view(), name); + val b := section_named(debug_file.view(), name); + val c := section_named(petal_file.view(), name); + t.expects(a.found && b.found && a.bytes == b.bytes); + # The file describes each where the executable has it, holding none of it. + t.expects(c.found && c.kind == 8 && c.address == b.address && c.size == b.size); + } + + # Debuggers match the file with the executable by the build's note and by + # the checksum the executable gives with its name. + val note := section_named(plain_file.view(), ".note.gnu.build-id"); + val noted := section_named(debug_file.view(), ".note.gnu.build-id"); + val described := section_named(petal_file.view(), ".note.gnu.build-id"); + t.expects(note.found && note.size == 36 && note.bytes.substr(12, 3) == "GNU"); + t.expects(note.bytes == noted.bytes && note.bytes == described.bytes); + t.expects(!section_named(plain_file.view(), ".gnu_debuglink").found); + val link := section_named(debug_file.view(), ".gnu_debuglink"); + val name: strview = "debug.petal"; + val at := (name.length + 1 + 3) / 4 * 4; + t.expects(link.found && link.size == at + 4 && link.bytes.substr(0, name.length) == name); + t.expects(number_at(link.bytes, at, 4) == elf::crc32(petal_file.view()) as u64); + + # The file describes the segments the executable loads, holding none of + # them, and the writable one is held in the executable's file. + val loads := loads_of(debug_file.view()); + val described_loads := loads_of(petal_file.view()); + t.expects(loads.length != 0 && loads.length == described_loads.length); + for i in 0..(loads.length < described_loads.length ? loads.length : described_loads.length) { + val a: found_segment = loads.at(i); + val b: found_segment = described_loads.at(i); + t.expects(a.offset == b.offset && a.address == b.address && a.memory == b.memory && a.flags == b.flags && b.held == 0); + t.expects((a.flags & 2) == 0 || a.held == a.memory); + } + + val debugging: strview[5] = [".debug_info", ".debug_abbrev", ".debug_line", ".debug_frame", ".debug_str"]; + for &name in debugging { + val held := section_named(petal_file.view(), name); + t.expects(held.found && held.size > 0); + t.expects(!section_named(debug_file.view(), name).found); + } +} +} + +# A section of a PE file, as its header describes it. +struct pe_found_section { + var found: bool; + var address: u64; + var size: u64; #! Of what it holds in memory. + var flags: u64; #! Its characteristics. + var bytes: strview; #! What the file holds of it. +} + +# The section of a PE file named so, or one not found. A name longer than eight +# bytes is held in the table of strings after the symbols, named by `/` and its +# offset there. +def pe_section_named(bytes: strview, name: strview): pe_found_section { + # The signature `PE\0\0` is at `pe`, and the file header's fields after it. + val pe := number_at(bytes, 0x3C, 4); + val sections := number_at(bytes, pe + 6, 2); + val optional := number_at(bytes, pe + 20, 2); + val strings := number_at(bytes, pe + 12, 4) + number_at(bytes, pe + 16, 4) * 18; + val table := pe + 24 + optional; + for i in 0..sections { + val at := table + 40 * i; + var named := true; + if bytes.at(at) == '/' as u8 { + # A long name: its offset into the table of strings, in decimal. + var offset := 0u; + for k in 1..8u { + break if at + k >= bytes.length || bytes.at(at + k) < '0' as u8 || bytes.at(at + k) > '9' as u8; + offset = offset * 10 + (bytes.at(at + k) - '0' as u8) as u64; + } + val held := strings + offset; + for k in 0..name.length { + if held + k >= bytes.length || bytes.at(held + k) != name[k] { + named = false; + break; + } + } + named = named && (held + name.length >= bytes.length || bytes.at(held + name.length) == 0); + } else { + for k in 0..8u { + val c: u8 = k < name.length ? name[k] : 0; + if bytes.at(at + k) != c { + named = false; + break; + } + } + } + continue if !named; + val size := number_at(bytes, at + 8, 4); + val offset := number_at(bytes, at + 20, 4); + val held := number_at(bytes, at + 16, 4); + return pe_found_section { + found = true, + address = number_at(bytes, at + 12, 4), + size = size, + flags = number_at(bytes, at + 36, 4), + bytes = bytes.substr(offset, held < size ? held : size) + }; + } + return pe_found_section { bytes = strview::empty() }; +} + +when os == windows { +# Debugging information is held in sections of the executable the system loads +# but only debuggers read, and leaves everything the executable loads as it was. +@test def debugging_information_is_written_within_the_executable(t: &mut tester): void { + val standard := test_library(); + return if standard.length == 0; + val library := standard.view(); + val directory := scratch_directory("described"); + val plain := $"{directory}/plain.exe"; + val debug := $"{directory}/debug.exe"; + val plain_problems := built(library, "test0.sakura", debugged, plain.view(), 0, false); + val debug_problems := built(library, "test0.sakura", debugged, debug.view(), 0, true); + for &each in plain_problems { + println(each); + } + for &each in debug_problems { + println(each); + } + return if !t.expects(plain_problems.length == 0 && debug_problems.length == 0); + t.expects(!file_exists($"{debug}.petal".view())); + val ran: strview[1] = [debug.view()]; + t.expects(output_of(ran[:]).view() == "30\n"); + + val plain_file := file_bytes(plain.view()); + val debug_file := file_bytes(debug.view()); + val loaded: strview[4] = [".rodata", ".data", ".text", ".lines"]; + for &name in loaded { + val a := pe_section_named(plain_file.view(), name); + val b := pe_section_named(debug_file.view(), name); + t.expects(a.found && b.found && a.address == b.address && a.size == b.size && a.flags == b.flags && a.bytes == b.bytes); + } + + # The sections of debugging information are only in a build asked for, and the + # system discards them when it loads the executable. + val debugging: strview[5] = [".debug_info", ".debug_abbrev", ".debug_line", ".debug_frame", ".debug_str"]; + for &name in debugging { + val held := pe_section_named(debug_file.view(), name); + t.expects(held.found && held.size > 0 && (held.flags & 0x02000000) != 0); + t.expects(!pe_section_named(plain_file.view(), name).found); + } +} +} + +# A word of a PE file at an address past its base, found by the section +# holding it, or 0 where none does. +def pe_word_at(bytes: strview, address: u64, size: u64): u64 { + val pe := number_at(bytes, 0x3C, 4); + val table := pe + 24 + number_at(bytes, pe + 20, 2); + for k in 0..number_at(bytes, pe + 6, 2) { + val at := table + 40 * k; + val begins := number_at(bytes, at + 12, 4); + if address >= begins && address < begins + number_at(bytes, at + 8, 4) { + return number_at(bytes, number_at(bytes, at + 20, 4) + address - begins, size); + } + } + return 0; +} + +# A build for Windows asking for debugging information writes a PDB file beside +# the executable, which names the file by its path, its GUID, and its age, as +# the file names itself. Every build for Windows says how each function +# unwinds. A build on another system makes them too, though it can't run them. +@test def a_build_for_windows_names_its_pdb_file(t: &mut tester): void { + val standard := test_library(); + return if standard.length == 0; + val library := standard.view(); + val directory := scratch_directory("pdb"); + val plain := $"{directory}/plain.exe"; + val debug := $"{directory}/debug.exe"; + val pdb := $"{directory}/debug.pdb"; + remove_file(pdb.view()); + remove_file($"{directory}/plain.pdb".view()); + val plain_problems := built(library, "test0.sakura", debugged, plain.view(), 0, false, 1, false, false, true); + val debug_problems := built(library, "test0.sakura", debugged, debug.view(), 0, true, 1, false, false, true); + for &each in plain_problems { + println(each); + } + for &each in debug_problems { + println(each); + } + return if !t.expects(plain_problems.length == 0 && debug_problems.length == 0); + t.expects(file_exists(pdb.view())); + t.expects(!file_exists($"{directory}/plain.pdb".view())); + + # Each says how its functions unwind, in a table the exception directory names. + val plain_file := file_bytes(plain.view()); + val debug_file := file_bytes(debug.view()); + val built_files: strview[2] = [plain_file.view(), debug_file.view()]; + for &each in built_files { + val pe := number_at(each, 0x3C, 4); + t.expects(number_at(each, pe + 24 + 112 + 8 * 3, 4) != 0 && number_at(each, pe + 24 + 116 + 8 * 3, 4) % 12 == 0); + t.expects(pe_section_named(each, ".pdata").found && pe_section_named(each, ".xdata").found); + } + t.expects(!pe_section_named(plain_file.view(), ".buildid").found); + + # The debug directory's CodeView entry names the file: `RSDS`, its GUID, its + # age, and its path. + val bytes := debug_file.view(); + val pe := number_at(bytes, 0x3C, 4); + val directory_at := number_at(bytes, pe + 24 + 112 + 8 * 6, 4); + t.expects(directory_at != 0 && number_at(bytes, pe + 24 + 116 + 8 * 6, 4) == 28); + t.expects(pe_word_at(bytes, directory_at + 12, 4) == 2); + val record := pe_word_at(bytes, directory_at + 24, 4) as u64; + t.expects(bytes.substr(record, 4) == "RSDS"); + val path_at := record + 24; + t.expects(bytes.substr(path_at, pdb.length) == pdb.view()); + + # The PDB file names itself the same way, in the stream naming it: the first + # block of the second stream, past the directory's sizes. + val held := file_bytes(pdb.view()); + val file := held.view(); + t.expects(file.substr(0, 24) == "Microsoft C/C++ MSF 7.00"); + val block := number_at(file, 32, 4); + val directory_block := number_at(file, number_at(file, 52, 4) * block, 4); + val streams := number_at(file, directory_block * block, 4); + val info := number_at(file, directory_block * block + 4 + 4 * streams, 4) * block; + t.expects(number_at(file, info, 4) == 20000404); + t.expects(number_at(file, info + 8, 4) == number_at(bytes, record + 20, 4)); + t.expects(file.substr(info + 12, 16) == bytes.substr(record + 4, 16)); +} + +#! What gdb writes debugging an executable with commands. +#! @param executable The executable. +#! @param commands The commands, each run in turn. +#! @returns What it wrote. +def debugged_by_gdb(executable: strview, commands: span): string { + var words := vector::::new(); + val start: strview[7] = ["gdb", "-batch", "-nx", "-iex", "set debuginfod enabled off", "-iex", "set auto-load no"]; + for &each in start { + words.append(each); + } + for &each in commands { + words.append("-ex"); + words.append(each); + } + words.append(executable); + return output_of(words.view()); +} + +#! Whether gdb wrote each piece of text, printing what it wrote where it did +#! not. +#! @param t The tester. +#! @param written What it wrote. +#! @param pieces The pieces. +def wrote_each(t: &mut tester, written: &string, pieces: span): void { + for &each in pieces { + if !t.expects(holds(written.view(), each)) { + println($" gdb did not write `{each}`, and wrote:\n{written}"); + } + } +} + +# Where gdb is, it stops at lines, names the functions running and those +# inlined, shows the variables of code left as compiled, in callers too, and +# those of optimized code where they are known, and unwinds from a trap's +# report to where the program stopped. +@test def debuggers_read_the_debugging_information(t: &mut tester): void { + val standard := test_library(); + return if standard.length == 0; + val library := standard.view(); + val version: strview[2] = ["gdb", "--version"]; + return if !holds(output_of(version[:]).view(), "GNU gdb"); + val directory := scratch_directory("gdb"); + val executable := $"{directory}/debugged"; + + var problems := built(library, "test0.sakura", debugged, executable.view(), 0, true); + return if !t.expects(problems.length == 0); + val unoptimized: strview[5] = ["break test0.sakura:6", "run", "bt", "info locals", "up"]; + var commands := vector::::new(); + for &each in unoptimized { + commands.append(each); + } + commands.append("info locals"); + val stopped := debugged_by_gdb(executable.view(), commands.view()); + val shown: strview[5] = [ + "scale (p=..., by=2) at test0.sakura:6", "main () at test0.sakura:11", "scaled = {x = 2, y = 4}", "i = 1", + "total = 0" + ]; + wrote_each(t, &stopped, shown[:]); + + # Optimized, a call inlined is still a frame, and variables held in values + # are shown where they are known: in a register, the frame, or as a + # constant. + problems = built(library, "test0.sakura", debugged, executable.view(), 2, true); + return if !t.expects(problems.length == 0); + val optimized: strview[3] = ["break scale", "run", "bt"]; + val inlined := debugged_by_gdb(executable.view(), optimized[:]); + val named: strview[2] = ["scale (by=2) at test0.sakura:5", "main () at test0.sakura:11"]; + wrote_each(t, &inlined, named[:]); + val looping: strview[5] = ["break test0.sakura:12", "run", "continue", "continue", "info locals"]; + val carried := debugged_by_gdb(executable.view(), looping[:]); + val totals: strview[1] = ["total = 16"]; + wrote_each(t, &carried, totals[:]); + + # A trap is reported by `fail`, which unwinds to where the program stopped. + val trapping: strview = "\nimport std::io;\ndef half(n: int): int { return 10 / n; }\ndef main(): void { println($\"{half(0)}\"); }\n"; + problems = built(library, "test0.sakura", trapping, executable.view(), 2, true); + return if !t.expects(problems.length == 0); + val reporting: strview[3] = ["break fail", "run", "bt"]; + val unwound := debugged_by_gdb(executable.view(), reporting[:]); + val stack: strview[2] = ["half (n=0) at test0.sakura:3", "main () at test0.sakura:4"]; + wrote_each(t, &unwound, stack[:]); +} + +# Where valgrind is, it reads the executable's symbols, and the lines of the +# file of its debugging information, naming a source by the absolute path it +# has. +@test def valgrind_reads_the_debugging_information(t: &mut tester): void { + val standard := test_library(); + return if standard.length == 0; + val library := standard.view(); + val version: strview[2] = ["valgrind", "--version"]; + return if !holds(output_of(version[:]).view(), "valgrind"); + val directory := scratch_directory("valgrind"); + val source := $"{directory}/debugged.sakura"; + val executable := $"{directory}/debugged"; + val problems := built(library, source.view(), debugged, executable.view(), 2, true); + return if !t.expects(problems.length == 0); + + val profile := $"{directory}/debugged.callgrind"; + val out := $"--callgrind-out-file={profile}"; + val words: strview[5] = ["valgrind", "--tool=callgrind", "--dump-line=yes", out.view(), executable.view()]; + _ = output_of(words[:]); + val written := file_bytes(profile.view()); + remove_file(profile.view()); + t.expects(holds(written.view(), ") main\n")); + t.expects(holds(written.view(), $") {source}\n".view())); +} diff --git a/tests/programs/a_file_may_begin_with_a_byte_order_mark_1.out b/tests/programs/a_file_may_begin_with_a_byte_order_mark_1.out new file mode 100644 index 00000000..ccabd9bb --- /dev/null +++ b/tests/programs/a_file_may_begin_with_a_byte_order_mark_1.out @@ -0,0 +1 @@ +read past its mark diff --git a/tests/programs/a_file_may_begin_with_a_byte_order_mark_1.sakura b/tests/programs/a_file_may_begin_with_a_byte_order_mark_1.sakura new file mode 100644 index 00000000..678007c1 --- /dev/null +++ b/tests/programs/a_file_may_begin_with_a_byte_order_mark_1.sakura @@ -0,0 +1,2 @@ +import std::io; +def main(): void { println("read past its mark"); } diff --git a/tests/programs/a_function_owns_the_values_it_is_given_1.out b/tests/programs/a_function_owns_the_values_it_is_given_1.out new file mode 100644 index 00000000..0ba5ac3a --- /dev/null +++ b/tests/programs/a_function_owns_the_values_it_is_given_1.out @@ -0,0 +1 @@ +1 2 9 4 5 8 6 true 6 diff --git a/tests/programs/a_function_owns_the_values_it_is_given_1.sakura b/tests/programs/a_function_owns_the_values_it_is_given_1.sakura new file mode 100644 index 00000000..2720924a --- /dev/null +++ b/tests/programs/a_function_owns_the_values_it_is_given_1.sakura @@ -0,0 +1,21 @@ +import std::io; +struct holder : owning { var data: *mut u8; var tag: int; } +var closed: int = 0; +def holder::of(tag: int): holder { return holder { data = raw_allocate(8), tag = tag }; } +def holder::close(&mut this): void { if this.data != null { closed++; raw_release(this.data); this.data = null; } } +def holder::taken(src: &mut holder): holder { var made := holder { data = src.data, tag = src.tag }; src.data = null; return made; } +def reads(h: holder): int { return h.tag; } +def takes(h: holder): int { val held := holder::taken(&mut h); return held.tag; } +def swaps(h: holder): int { h = holder::of(9); return h.tag; } +def hands(h: holder): int { return reads(holder::taken(&mut h)); } +def gives(h: holder): holder { return h; } +def counts(n: int): int { n++; n = n * 2; return n; } +def main(): void { + print($"{reads(holder::of(1))} {takes(holder::of(2))} "); + print($"{swaps(holder::of(3))} {hands(holder::of(4))} "); + val kept := gives(holder::of(5)); + print($"{kept.tag} {counts(3)} "); + var mine := holder::of(6); + print($"{takes(holder::taken(&mut mine))} {mine.data == null} "); + print($"{closed}\n"); +} diff --git a/tests/programs/a_test_names_the_value_a_union_holds_1.out b/tests/programs/a_test_names_the_value_a_union_holds_1.out new file mode 100644 index 00000000..92ed371c --- /dev/null +++ b/tests/programs/a_test_names_the_value_a_union_holds_1.out @@ -0,0 +1,4 @@ +number 7 | text hi +many 3 [1, 2, 3] | none +held{text = bad} held{none = empty{}} +10 z diff --git a/tests/programs/a_test_names_the_value_a_union_holds_1.sakura b/tests/programs/a_test_names_the_value_a_union_holds_1.sakura new file mode 100644 index 00000000..ff3f8ee7 --- /dev/null +++ b/tests/programs/a_test_names_the_value_a_union_holds_1.sakura @@ -0,0 +1,35 @@ +import std::io; +struct empty {} +union held { var none: empty; var number: int; var text: span; var many: span; } +def read(h: held): string { + if h is number(n) { return $"number {n}"; } + if h is text(t) { return $"text {t}"; } + if h is many(xs) { return $"many {xs.length} {xs}"; } else { return "none"; } +} +def fail_at(n: int): held { return held{ text = "bad" } if n < 0; return empty{}; } +def forward(n: int): held { + return why if fail_at(n) is text(why); + return empty{}; +} +def total(xs: span): string { + var sum := 0; + var seen := string::new(nothing {}); + var i := 0 as u64; + while i < xs.length { + val each := xs[i]; + i++; + if each is number(n) { sum += n; } + if each is text(t) { seen.append(t); } + } + return $"{sum} {seen}"; +} +def main(): void { + val words := held{ text = "hi" }; + val one := held{ text = "z" }; + var ns: int[3] = [1, 2, 3]; + println($"{read(held{ number = 7 })} | {read(words)}"); + println($"{read(held{ many = span::::over((&ns) as *int, 3) })} | {read(empty{})}"); + println($"{forward(-2)} {forward(2)}"); + var some: held[4] = [held{ number = 4 }, empty{}, one, held{ number = 6 }]; + println(total(span::::over((&some) as *held, 4))); +} diff --git a/tests/programs/aliases_satisfy_what_they_alias_1.out b/tests/programs/aliases_satisfy_what_they_alias_1.out new file mode 100644 index 00000000..29d88141 --- /dev/null +++ b/tests/programs/aliases_satisfy_what_they_alias_1.out @@ -0,0 +1 @@ +same same same diff --git a/tests/programs/aliases_satisfy_what_they_alias_1.sakura b/tests/programs/aliases_satisfy_what_they_alias_1.sakura new file mode 100644 index 00000000..0bc83ea2 --- /dev/null +++ b/tests/programs/aliases_satisfy_what_they_alias_1.sakura @@ -0,0 +1,16 @@ +import std::io; +trait same { def same(&this, other: &T): bool; } +struct pt { var x: i64; } +def pt::same(&this, other: &pt): bool { return this.x == other.x; } +type point = pt; +type spot = point; +def check(a: &T, b: &T): string { + if const T is same { return a.same(b) ? "same" : "differ"; } + return "unknown"; +} +def main(): void { + val a: point = pt { 1 }; + val b: point = pt { 1 }; + val c: spot = pt { 2 }; + println($"{check::(&a, &b)} {check::(&a, &b)} {check::(&c, &c)}"); +} diff --git a/tests/programs/allocations_give_aligned_memory_1.out b/tests/programs/allocations_give_aligned_memory_1.out new file mode 100644 index 00000000..5be98be3 --- /dev/null +++ b/tests/programs/allocations_give_aligned_memory_1.out @@ -0,0 +1,2 @@ +true true true true 7 3 true true true +released diff --git a/tests/programs/allocations_give_aligned_memory_1.sakura b/tests/programs/allocations_give_aligned_memory_1.sakura new file mode 100644 index 00000000..94432657 --- /dev/null +++ b/tests/programs/allocations_give_aligned_memory_1.sakura @@ -0,0 +1,27 @@ +import std::io; +def aligned(block: *mut u8): bool { + return block != null && (block as u64) % 16 == 0; +} +def main(): void { + var small := raw_allocate(10); + var class := raw_allocate(300); + var paged := raw_allocate(5000); + var odd := raw_allocate(1); + print($"{aligned(small)} {aligned(class)} {aligned(paged)} {aligned(odd)} "); + small[9] = 7; + # What a block grows by may hold anything, so it is written before it is read. + var grown := raw_resize(small, 40); + grown[39] = 3; + print($"{grown[9]} {grown[39]} {aligned(grown)} "); + var moved := raw_resize(paged, 9000); + print($"{aligned(moved)} "); + var fresh := raw_resize(null, 1); + println($"{aligned(fresh)}"); + raw_release(grown); + raw_release(class); + raw_release(odd); + raw_release(moved); + raw_release(fresh); + raw_release(null); + println("released"); +} diff --git a/tests/programs/an_abort_reports_where_it_was_1.out b/tests/programs/an_abort_reports_where_it_was_1.out new file mode 100644 index 00000000..2f9d9902 --- /dev/null +++ b/tests/programs/an_abort_reports_where_it_was_1.out @@ -0,0 +1,5 @@ +before +--- exit 1 +sakura: runtime error: Program aborted. + at inner (tests/programs/an_abort_reports_where_it_was_1.sakura:3:44) + at main (tests/programs/an_abort_reports_where_it_was_1.sakura:4:25) diff --git a/tests/programs/an_abort_reports_where_it_was_1.sakura b/tests/programs/an_abort_reports_where_it_was_1.sakura new file mode 100644 index 00000000..a35779ce --- /dev/null +++ b/tests/programs/an_abort_reports_where_it_was_1.sakura @@ -0,0 +1,4 @@ +import std::io; +import system; +def inner(): void { print("before "); abort(); } +def main(): void { inner(); println("after"); } diff --git a/tests/programs/arguments_are_referred_to_1.out b/tests/programs/arguments_are_referred_to_1.out new file mode 100644 index 00000000..b786a18c --- /dev/null +++ b/tests/programs/arguments_are_referred_to_1.out @@ -0,0 +1,2 @@ +[1, 9] [1, 2] 12 10 9 true +[[1, 0], [2, 9]] diff --git a/tests/programs/arguments_are_referred_to_1.sakura b/tests/programs/arguments_are_referred_to_1.sakura new file mode 100644 index 00000000..609eded3 --- /dev/null +++ b/tests/programs/arguments_are_referred_to_1.sakura @@ -0,0 +1,19 @@ +import std::io; +struct point { var x: int; } +def point::move(&mut this, by: int): void { this.x += by; } +def grow(xs: &mut int[2]): void { xs[1] = 9; } +def bump(p: &mut point): void { p.x++; } +def total(xs: &int[2]): int { var t := 0; for x in xs { t += x; } return t; } +def same(x: &T): T { return x; } +def main(): void { + var xs := [1, 2]; + val alias := xs; + grow(&mut xs); + var p := point{ 1 }; + bump(p); + p.move(same(10)); + println($"{xs} {alias} {p.x} {total(&xs)} {total(&[4, 5])} {same(true)}"); + var nested := [[1, 0], [2, 0]]; + grow(&mut nested[1]); + println($"{nested}"); +} diff --git a/tests/programs/array_literals_are_views_where_spans_are_wanted_1.out b/tests/programs/array_literals_are_views_where_spans_are_wanted_1.out new file mode 100644 index 00000000..1c84de2e --- /dev/null +++ b/tests/programs/array_literals_are_views_where_spans_are_wanted_1.out @@ -0,0 +1,3 @@ +else -2 -0.25 true 0 +2 0 3 b +11 6 0 diff --git a/tests/programs/array_literals_are_views_where_spans_are_wanted_1.sakura b/tests/programs/array_literals_are_views_where_spans_are_wanted_1.sakura new file mode 100644 index 00000000..826b5892 --- /dev/null +++ b/tests/programs/array_literals_are_views_where_spans_are_wanted_1.sakura @@ -0,0 +1,16 @@ +import std::io; +enum color { red, green, blue } +const words: span> = ["if", "else"]; +const numbers: span = [1, -2, 3]; +const reals: span = [1.5, -0.25, 2]; +const colors: span = [color::blue, color::red]; +const nested: span> = [[1, 2], [], [3]]; +const none: span = []; +def sum(xs: span): i64 { var t: i64 = 0; for x in xs { t += x; } return t; } +def main(): void { + val local: span> = ["a", "b"]; + val n: i64 = 5; + println($"{words[1]} {numbers[1]} {reals[1]} {colors[0] == color::blue} {none.length}"); + println($"{nested[0][1]} {nested[1].length} {nested[2][0]} {local[1]}"); + println($"{sum([n, n + 1])} {sum([1, 2, 3])} {sum([])}"); +} diff --git a/tests/programs/array_literals_viewed_by_a_call_close_after_it_1.out b/tests/programs/array_literals_viewed_by_a_call_close_after_it_1.out new file mode 100644 index 00000000..7c874293 --- /dev/null +++ b/tests/programs/array_literals_viewed_by_a_call_close_after_it_1.out @@ -0,0 +1,4 @@ +2 +close 2 +close 1 +done diff --git a/tests/programs/array_literals_viewed_by_a_call_close_after_it_1.sakura b/tests/programs/array_literals_viewed_by_a_call_close_after_it_1.sakura new file mode 100644 index 00000000..2abbcb69 --- /dev/null +++ b/tests/programs/array_literals_viewed_by_a_call_close_after_it_1.sakura @@ -0,0 +1,8 @@ +import std::io; +struct noisy : owning { var n: i64; } +def noisy::close(&mut this): void { println($"close {this.n}"); } +def count(xs: span): u64 { return xs.length; } +def main(): void { + println($"{count([noisy{ n = 1 }, noisy{ n = 2 }])}"); + println("done"); +} diff --git a/tests/programs/atomics_1.out b/tests/programs/atomics_1.out new file mode 100644 index 00000000..3bf6602c --- /dev/null +++ b/tests/programs/atomics_1.out @@ -0,0 +1,21 @@ +u8: 100 44 200 200 236 36 36 200 100 + wrote over 100, found 200 +i8: -100 -10 90 90 -34 -124 -124 90 -100 + wrote over -100, found 90 +u16: 32767 32751 65520 65520 65535 15 15 65520 32767 + wrote over 32767, found 65520 +i16: -30000 0 30000 30000 -16 -30016 -30016 30000 -30000 + wrote over -30000, found 30000 +u32: 5 3 4294967294 4294967294 4294967295 1 1 4294967294 5 + wrote over 5, found 4294967294 +i32: -2147483647 0 2147483647 2147483647 -1 -2147483648 -2147483648 2147483647 -2147483647 + wrote over -2147483647, found 2147483647 +u64: 1 0 18446744073709551615 18446744073709551615 18446744073709551615 0 0 18446744073709551615 1 + wrote over 1, found 18446744073709551615 +i64: -9223372036854775807 0 9223372036854775807 9223372036854775807 -1 -9223372036854775808 -9223372036854775808 9223372036854775807 -9223372036854775807 + wrote over -9223372036854775807, found 9223372036854775807 +bool: false true true false +enum: true true +pointer: 30 +struct: 45 255 +shared: true 200000 600000 diff --git a/tests/programs/atomics_1.sakura b/tests/programs/atomics_1.sakura new file mode 100644 index 00000000..ed2687ba --- /dev/null +++ b/tests/programs/atomics_1.sakura @@ -0,0 +1,171 @@ +import std::io; +import std::process; +import system; + +extern import "kernel32.dll" when os == windows; + +# Atomics of every width and kind, their operations giving what they held, and +# two processes adding to a page they share, which loses nothing. + +def show(name: strview, a: &mut atomic, low: T, high: T): void where T: integer, lockfree { + a.store(low); + val added := a.fetch_add(high); + val subtracted := a.fetch_sub(low, order::acq_rel); + val anded := a.fetch_and(high, order::relaxed); + val ored := a.fetch_or(low); + val xored := a.fetch_xor(high, order::release); + val least := a.fetch_min(low); + val most := a.fetch_max(high, order::acquire); + val swapped := a.exchange(low); + io::println($"{name}: {added} {subtracted} {anded} {ored} {xored} {least} {most} {swapped} {a.load()}"); + match a.compare_exchange(low, high) { + value(found) => io::print($" wrote over {found}"); + error(found) => io::print($" found {found}"); + } + match a.compare_exchange(low, high, order::release, order::relaxed) { + value(found) => io::println($", wrote over {found}"); + error(found) => io::println($", found {found}"); + } +} + +enum state { idle, busy, done } + +struct counters { + var hits: atomic; + var flags: atomic; +} + +def main(): void { + var a8 := atomic::::new(0); + var b8 := atomic::::new(0); + var a16 := atomic::::new(0); + var b16 := atomic::::new(0); + var a32 := atomic::::new(0); + var b32 := atomic::::new(0); + var a64 := atomic::::new(0); + var b64 := atomic::::new(0); + show::("u8", &mut a8, 100, 200); + show::("i8", &mut b8, -100, 90); + show::("u16", &mut a16, 0x7FFF, 0xFFF0); + show::("i16", &mut b16, -30000, 30000); + show::("u32", &mut a32, 5, 0xFFFFFFFE); + show::("i32", &mut b32, -2147483647, 2147483647); + show::("u64", &mut a64, 1, 0xFFFFFFFFFFFFFFFF); + show::("i64", &mut b64, -9223372036854775807, 9223372036854775807); + + var flag := atomic::::new(false); + val was := flag.exchange(true); + io::println($"bool: {was} {flag.load()} {flag.compare_exchange(true, false) is value} {flag.load()}"); + + var now := atomic::::new(state::idle); + now.store(state::busy, order::release); + val before := now.exchange(state::done); + io::println($"enum: {before == state::busy} {now.load(order::acquire) == state::done}"); + + var words: u64[4] = [10, 20, 30, 40]; + var at := atomic::<*mut u64>::new(&mut words[0] as *mut u64); + match at.compare_exchange(&mut words[0] as *mut u64, &mut words[2] as *mut u64) { + value(_) => io::println($"pointer: {at.load()[0]}"); + error(_) => io::println("pointer: refused"); + } + + var held := counters { hits = atomic::::new(0), flags = atomic::::new(0) }; + for i in 0..10u { + _ = held.hits.fetch_add(i); + _ = held.flags.fetch_or((1 << (i % 8)) as u8); + } + fence(order::seq_cst); + io::println($"struct: {held.hits.load()} {held.flags.load()}"); + + # A page both processes keep, rather than a copy each. + val page := shared_page(); + val sum := page as *mut atomic; + val tries := (page + 8) as *mut atomic; + val child := copy(); + for _ in 0..100000 { + _ = sum[0].fetch_add(1); + var seen := tries[0].load(order::relaxed); + while true { + match tries[0].compare_exchange_weak(seen, seen + 3, order::acq_rel, order::relaxed) { + value(_) => break; + error(found) => seen = found; + } + } + } + if child == 0 { + exit(0); + } + var status: process_status; + _ = wait(child, &mut status); + io::println($"shared: {status.exited} {sum[0].load()} {tries[0].load()}"); +} + +# The page both processes add to, and the copy of the program adding with this +# one, whose number `copy` gives, or zero in the copy. Linux keeps a page mapped +# shared in the copy `fork` makes. Windows cannot fork, so there the copy is the +# program started again, writing nothing, which maps the page by the name it is +# started with. +when os == linux { + def shared_page(): u64 { + return system::linux::syscall(9, 0, 4096, 3, 0x21, 0xFFFFFFFFFFFFFFFF, 0) as u64; + } + + def copy(): i64 { + return fork(); + } +} +else { + # The variable the copy is started with, holding the name of the page. + val page_variable: strview = "SAKURA_ATOMICS_PAGE"; + + # The page, as this program mapped it. + var mapped: u64 = 0; + + # The name of the page: the one the copy was given, or one of this program's + # own. + def page_name(): string { + if process::variable(page_variable) is some(given) { + return string::from(given, nothing {}); + } + return $"sakura-atomics-{getpid()}"; + } + + def shared_page(): u64 { + val name := page_name(); + var wide: u16[64]; + for i in 0..name.length { + wide[i] = name[i] as u16; + } + val mapping := pages::CreateFileMappingW(0xFFFFFFFFFFFFFFFF, null, 0x04, 0, 4096, (&wide) as *u16); + mapped = pages::MapViewOfFile(mapping, 0x02, 0, 0, 4096); + return mapped; + } + + # The copy is slow to start, so it says it has mapped the page, in the word + # after what the two add to, and the program waits for that, for ten seconds + # at most, so that the two add at once, as after `fork`. + def copy(): i64 { + val ready := (mapped + 12) as *mut atomic; + if process::variable(page_variable) is some(_) { + ready[0].store(1); + return 0; + } + var device := path::parse(null_device) else (_) { return -1; }; + var quiet := io::file::open(&device, open_flags::write) else (_) { return -1; }; + val started := respawn($"{page_variable}={page_name()}".view(), fd::stdin, quiet.handle, fd::stderr); + val until := clock(clock_kind::steady) + 10000000000; + while started > 0 && ready[0].load() == 0 && clock(clock_kind::steady) < until { + _ = sleep(1000000); + } + return started; + } +} + +# What Windows gives of memory that processes share: a mapping of the system's +# own file of pages, by a name, and a view of it. +extern module pages when os == windows; + +pub def CreateFileMappingW( + file: u64, security: *mut u8, protection: u32, size_high: u32, size_low: u32, name: *u16 +): u64; +pub def MapViewOfFile(mapping: u64, access: u32, offset_high: u32, offset_low: u32, size: u64): u64; diff --git a/tests/programs/attributes_leave_the_program_alone_1.out b/tests/programs/attributes_leave_the_program_alone_1.out new file mode 100644 index 00000000..ddcbc88b --- /dev/null +++ b/tests/programs/attributes_leave_the_program_alone_1.out @@ -0,0 +1 @@ +7 1 diff --git a/tests/programs/attributes_leave_the_program_alone_1.sakura b/tests/programs/attributes_leave_the_program_alone_1.sakura new file mode 100644 index 00000000..3e082282 --- /dev/null +++ b/tests/programs/attributes_leave_the_program_alone_1.sakura @@ -0,0 +1,11 @@ +import std::io; +struct serial : attribute { val name: span; val aliases: span[2]; } +struct weight : attribute { val value: i64 = 1; } +const def double(x: i64): i64 { return x * 2; } +@serial{ name = "point", aliases = ["p", "pt"] } +struct point { @weight{ value = double(21) } var x: i64; @weight var y: i64; } +enum axis { @weight x, y } +@weight def sum(p: point): i64 { return p.x + p.y; } +def main(): void { + println($"{sum(point{ 3, 4 })} {axis::y as i64}"); +} diff --git a/tests/programs/bitwise_operators_call_methods_1.out b/tests/programs/bitwise_operators_call_methods_1.out new file mode 100644 index 00000000..e963220d --- /dev/null +++ b/tests/programs/bitwise_operators_call_methods_1.out @@ -0,0 +1,6 @@ +61440 65520 4080 3855 +986880 3855 +30720 +240 +8 15 9 4294967283 48 3 +8 diff --git a/tests/programs/bitwise_operators_call_methods_1.sakura b/tests/programs/bitwise_operators_call_methods_1.sakura new file mode 100644 index 00000000..676de732 --- /dev/null +++ b/tests/programs/bitwise_operators_call_methods_1.sakura @@ -0,0 +1,36 @@ +import std::io; + +# A struct has the bitwise operators and shifts by the methods that give them, +# `bit_and`, `bit_or`, `bit_xor`, `bit_not`, `shift_left`, and `shift_right`, as it +# has arithmetic, their compound assignments too, and a bound asking for them +# gives a type parameter the operators. Integers give the methods as well. + +struct bits { var word: u64; } +def bits::bit_and(&this, other: &bits): bits { return bits { word = this.word & other.word }; } +def bits::bit_or(&this, other: &bits): bits { return bits { word = this.word | other.word }; } +def bits::bit_xor(&this, other: &bits): bits { return bits { word = this.word ^ other.word }; } +def bits::bit_not(&this): bits { return bits { word = ~this.word }; } +def bits::shift_left(&this, by: &u32): bits { return bits { word = this.word << by }; } +def bits::shift_right(&this, by: &u32): bits { return bits { word = this.word >> by }; } + +trait masks { def bit_and(&this, other: &self): self; def bit_not(&this): self; } + +def clear(a: T, b: T): T where T: masks { return a & ~b; } + +def main(): void { + val a := bits { word = 0xF0F0 }; + val b := bits { word = 0xFF00 }; + io::println($"{(a & b).word} {(a | b).word} {(a ^ b).word} {(~a).word & 0xFFFF}"); + io::println($"{(a << 4).word} {(a >> 4).word}"); + var c := a; + c &= b; + c |= bits { word = 1 }; + c <<= 1; + c ^= bits { word = 3 }; + c >>= 2; + io::println($"{c.word}"); + io::println($"{clear(a, b).word}"); + val x: u32 = 12; + io::println($"{x.bit_and(&10)} {x.bit_or(&3)} {x.bit_xor(&5)} {x.bit_not()} {x.shift_left(&2)} {x.shift_right(&2)}"); + io::println($"{clear(x, 4 as u32)}"); +} diff --git a/tests/programs/booleans_numbers_and_loops_1.out b/tests/programs/booleans_numbers_and_loops_1.out new file mode 100644 index 00000000..583d5468 --- /dev/null +++ b/tests/programs/booleans_numbers_and_loops_1.out @@ -0,0 +1 @@ +true [true, false, false] true true 1 true false true true true false true false 200 2.3333333333333335 1.5 true 57 [10, 21, 32] 0:10 1:20 2:30 diff --git a/tests/programs/booleans_numbers_and_loops_1.sakura b/tests/programs/booleans_numbers_and_loops_1.sakura new file mode 100644 index 00000000..326504c7 --- /dev/null +++ b/tests/programs/booleans_numbers_and_loops_1.sakura @@ -0,0 +1,26 @@ +import std::io; +struct nothing {} +union value { var none: nothing; var flag: bool; var number: i64; var real: f64; } +def main(): void { + val yes: bool = 3 > 2; + val flags: bool[3] = [true, !yes, yes && false]; + val held := value{ flag = true }; + val three := value{ number = 3 }; + print($"{yes} {flags} {held.flag} {three is number} {yes as u8} {7 as bool} {0 as bool} {flags == [true, false, false]} "); + val xs := [10, 20, 30]; + var i: i64 = -1; + val n: u64 = 3; + val small: u8 = 200; + val wide: i16 = small; + var total: f64 = 7; + print($"{i < xs.length} {xs.length > i} {i == n} {n != i} {i >= n} {wide} {total / xs.length} {n * 0.5} {i < 0.5} "); + var sum := 0; + for k in 0..xs.length { sum += xs[k]; } + for k in -2..1 { sum += k; } + for k in 3..3 { sum += 1000; } + var ys := xs; + for at, &mut y in ys { y += at as i64; } + var shown := $""; + for at, x in xs { shown.append($"{at}:{x} "); } + println($"{sum} {ys} {shown}"); +} diff --git a/tests/programs/bound_tests_narrow_the_branch_they_guard_1.out b/tests/programs/bound_tests_narrow_the_branch_they_guard_1.out new file mode 100644 index 00000000..3f756d03 --- /dev/null +++ b/tests/programs/bound_tests_narrow_the_branch_they_guard_1.out @@ -0,0 +1,2 @@ +d1 d1 d1 d1d1 d1true +? ? ? .. ? diff --git a/tests/programs/bound_tests_narrow_the_branch_they_guard_1.sakura b/tests/programs/bound_tests_narrow_the_branch_they_guard_1.sakura new file mode 100644 index 00000000..7a75a9db --- /dev/null +++ b/tests/programs/bound_tests_narrow_the_branch_they_guard_1.sakura @@ -0,0 +1,35 @@ +import std::io; +trait shows { def show(this: &shows): string; } +struct wrap { var v: T; } +def wrap::plain(this: &wrap): string { + if const T is shows { return this.v.show(); } + return "?"; +} +def wrap::inverted(this: &wrap): string { + if const T is not shows { return "?"; } else { return this.v.show(); } +} +def wrap::guarded(this: &wrap): string { + if const T is not shows { return "?"; } + return this.v.show(); +} +def wrap::looped(this: &wrap, times: int): string { + var out := string::new(nothing {}); + for i in 0..times { + if const T is not shows { out.append($"."); continue; } + out.append($"{this.v.show()}"); + } + return out; +} +def wrap::joined(this: &wrap): string { + if const !(T is shows && T is equatable) { return "?"; } + return $"{this.v.show()}{this.v == this.v}"; +} +struct dot: shows { var n: int; } +def dot::show(this: &dot): string { return $"d{this.n}"; } +def dot::equals(&this, other: &dot): bool { return this.n == other.n; } +def main(): void { + val d := wrap{ v = dot{ n = 1 } }; + val i := wrap{ v = 7 }; + println($"{d.plain()} {d.inverted()} {d.guarded()} {d.looped(2)} {d.joined()}"); + println($"{i.plain()} {i.inverted()} {i.guarded()} {i.looped(2)} {i.joined()}"); +} diff --git a/tests/programs/boxes_and_containers_close_whole_values_1.out b/tests/programs/boxes_and_containers_close_whole_values_1.out new file mode 100644 index 00000000..2e1ee21c --- /dev/null +++ b/tests/programs/boxes_and_containers_close_whole_values_1.out @@ -0,0 +1,9 @@ +node 1 +leaf 2 +leaf 1 +node 3 +leaf 4 +leaf 3 +hidden 6 +hidden 5 +done diff --git a/tests/programs/boxes_and_containers_close_whole_values_1.sakura b/tests/programs/boxes_and_containers_close_whole_values_1.sakura new file mode 100644 index 00000000..98712145 --- /dev/null +++ b/tests/programs/boxes_and_containers_close_whole_values_1.sakura @@ -0,0 +1,22 @@ +import std::io; +import lib; +struct leaf : owning { var n: int; } +def leaf::close(&mut this): void { if this.n != 0 { println($"leaf {this.n}"); } } +struct node : owning { var a: leaf; var b: leaf; } +def node::close(&mut this): void { if this.a.n != 0 { println($"node {this.a.n}"); } } +def main(): void { + { var held := box::new(node{ a = leaf{ n = 1 }, b = leaf{ n = 2 } }); } + { var many := vector::::new(); many.append(node{ a = leaf{ n = 3 }, b = leaf{ n = 4 } }); } + { var kept := holder::make(); } + println("done"); +} +module lib; +struct hidden : owning { var n: int; } +def hidden::close(&mut this): void { if this.n != 0 { println($"hidden {this.n}"); } } +pub struct holder : owning { var one: box; var many: vector; } +pub def holder::make(): holder { + var made := holder{ one = box::new(hidden{ n = 5 }), many = vector::::new() }; + made.many.append(hidden{ n = 6 }); + return made; +} +pub def holder::close(&mut this): void {} diff --git a/tests/programs/built_in_types_are_equatable_and_hashable_1.out b/tests/programs/built_in_types_are_equatable_and_hashable_1.out new file mode 100644 index 00000000..a8335476 --- /dev/null +++ b/tests/programs/built_in_types_are_equatable_and_hashable_1.out @@ -0,0 +1 @@ +true 5 7 true true 1 true true false true true true true 5 1 7 diff --git a/tests/programs/built_in_types_are_equatable_and_hashable_1.sakura b/tests/programs/built_in_types_are_equatable_and_hashable_1.sakura new file mode 100644 index 00000000..9018840c --- /dev/null +++ b/tests/programs/built_in_types_are_equatable_and_hashable_1.sakura @@ -0,0 +1,16 @@ +import std::io; +enum color { red, green } +struct pt { var x: i64; } +def pt::equals(&this, other: &pt): bool { return this.x == other.x; } +def same(a: &T, b: &T): bool where T: equatable { return a == b; } +def through(h: &hashable): u64 { return h.hash(); } +def main(): void { + val a: i64 = 5; val b: u8 = 7; val f: f64 = -0.0; val g: f64 = 0.0; + val c := color::green; val p := &a as *i64; + val arr: i64[3] = [1, 2, 3]; val other: i64[3] = [1, 2, 3]; + val pts: pt[2] = [pt{1}, pt{2}]; val more: pt[2] = [pt{1}, pt{3}]; + print($"{a.equals(&a)} {a.hash()} {b.hash()} {f.hash() == g.hash()} {f == g} {c.hash()} "); + print($"{arr.equals(&other)} {arr.hash() == other.hash()} {pts == more} {pts[0] == more[0]} "); + print($"{same::<*i64>(&p, &p)} {same::(&c, &c)} {same::(&pts, &pts)} "); + println($"{through(&a)} {through(&c)} {through(&b)}"); +} diff --git a/tests/programs/closeable_parameters_close_where_the_function_returns_1.out b/tests/programs/closeable_parameters_close_where_the_function_returns_1.out new file mode 100644 index 00000000..728b84b3 --- /dev/null +++ b/tests/programs/closeable_parameters_close_where_the_function_returns_1.out @@ -0,0 +1,11 @@ +peek seen +ends a +close a +short b +close b +close cc +2 +close e +end +close d +close seen diff --git a/tests/programs/closeable_parameters_close_where_the_function_returns_1.sakura b/tests/programs/closeable_parameters_close_where_the_function_returns_1.sakura new file mode 100644 index 00000000..5bb5da98 --- /dev/null +++ b/tests/programs/closeable_parameters_close_where_the_function_returns_1.sakura @@ -0,0 +1,20 @@ +import std::io; +struct noisy : owning { var name: span; } +def noisy::new(name: span): noisy { return noisy { name = name }; } +def noisy::close(&mut this): void { println($"close {this.name}"); } +def ends(n: noisy): void { println($"ends {n.name}"); } +def back(n: noisy): noisy { return n; } +def later(n: noisy, flag: bool = true): void { if flag { return; } } +def main(): void { + val short := def(n: noisy): void => println($"short {n.name}"); + val length := def(n: noisy): u64 => n.name.length; + var seen := noisy::new("seen"); + val peek := def(): void { println($"peek {seen.name}"); }; + peek(); + ends(noisy::new("a")); + short(noisy::new("b")); + println($"{length(noisy::new("cc"))}"); + var kept := back(noisy::new("d")); + later(noisy::new("e")); + println("end"); +} diff --git a/tests/programs/closeable_values_close_where_their_scope_ends_1.out b/tests/programs/closeable_values_close_where_their_scope_ends_1.out new file mode 100644 index 00000000..b0e534b4 --- /dev/null +++ b/tests/programs/closeable_values_close_where_their_scope_ends_1.out @@ -0,0 +1,17 @@ +close a +close b +close a +close x0 +close x1 +close inner +close gone +close first +end +close second +close m +close e1 +close e0 +owner body +close h +close p2 +close p1 diff --git a/tests/programs/closeable_values_close_where_their_scope_ends_1.sakura b/tests/programs/closeable_values_close_where_their_scope_ends_1.sakura new file mode 100644 index 00000000..d07ebdd2 --- /dev/null +++ b/tests/programs/closeable_values_close_where_their_scope_ends_1.sakura @@ -0,0 +1,40 @@ +import std::io; +struct noisy : owning { var name: span; } +def noisy::new(name: span): noisy { return noisy { name = name }; } +def noisy::close(&mut this): void { println($"close {this.name}"); } +struct pair { var first: noisy; var second: noisy; } +struct owner : owning { var held: noisy; } +def owner::close(&mut this): void { println("owner body"); } +def early(flag: bool): void { + var a := noisy::new("a"); + if flag { return; } + var b := noisy::new("b"); +} +def looped(): void { + var i := 0; + while i < 3 { + var label := $"x{i}"; + var x := noisy::new(label); + i++; + if i == 2 { break; } + continue; + } +} +def made(): noisy { + var m := noisy::new("m"); + return m; +} +def main(): void { + early(true); + early(false); + looped(); + { var inner := noisy::new("inner"); } + var p := pair { first = noisy::new("p1"), second = noisy::new("p2") }; + var o := owner { held = noisy::new("h") }; + var many: noisy[2] = [noisy::new("e0"), noisy::new("e1")]; + noisy::new("gone"); + var got := made(); + var over := noisy::new("first"); + over = noisy::new("second"); + println("end"); +} diff --git a/tests/programs/compile_error_in_a_generic_property_1.out b/tests/programs/compile_error_in_a_generic_property_1.out new file mode 100644 index 00000000..ed86a92d --- /dev/null +++ b/tests/programs/compile_error_in_a_generic_property_1.out @@ -0,0 +1,4 @@ + +--- exit 2 +tests/programs/compile_error_in_a_generic_property_1.sakura:9:39: invalid: A vector of two has no z. (In `z`) +tests/programs/compile_error_in_a_generic_property_1.sakura:14:39: invalid: A vector of fewer than four has no w to write. (In `w`) diff --git a/tests/programs/compile_error_in_a_generic_property_1.sakura b/tests/programs/compile_error_in_a_generic_property_1.sakura new file mode 100644 index 00000000..1cc7d8d0 --- /dev/null +++ b/tests/programs/compile_error_in_a_generic_property_1.sakura @@ -0,0 +1,23 @@ +import std::io; + +# A `compile_error` in the accessor of a generic type's property is reported +# in the instance a value of the type given its arguments reads or writes, as +# one in a method called is. +struct vec { var items: T[N]; } + +pub val vec::z: T { + get { if const N < 3 { compile_error("A vector of two has no z."); } return this.items[2]; } +} + +pub var vec::w: T { + get => this.items[0]; + set { if const N < 4 { compile_error("A vector of fewer than four has no w to write."); } this.items[3] = value; } +} + +def main(): void { + val three := vec:: { items = [1.0, 2.0, 3.0] }; + println($"{three.z}"); + var two := vec:: { items = [1.0, 2.0] }; + println($"{two.z}"); + two.w = 4.0; +} diff --git a/tests/programs/compile_error_says_text_worked_out_while_compiling_1.out b/tests/programs/compile_error_says_text_worked_out_while_compiling_1.out new file mode 100644 index 00000000..b5e27d49 --- /dev/null +++ b/tests/programs/compile_error_says_text_worked_out_while_compiling_1.out @@ -0,0 +1,3 @@ + +--- exit 2 +tests/programs/compile_error_says_text_worked_out_while_compiling_1.sakura:7:16: invalid: A constant says what is wrong. diff --git a/tests/programs/compile_error_says_text_worked_out_while_compiling_1.sakura b/tests/programs/compile_error_says_text_worked_out_while_compiling_1.sakura new file mode 100644 index 00000000..4781bab9 --- /dev/null +++ b/tests/programs/compile_error_says_text_worked_out_while_compiling_1.sakura @@ -0,0 +1,8 @@ +import std::io; + +# A `compile_error` given a constant holding text says that text. +const said: strview = "A constant says what is wrong."; + +def main(): void { + compile_error(said); +} diff --git a/tests/programs/compile_error_says_text_worked_out_while_compiling_2.out b/tests/programs/compile_error_says_text_worked_out_while_compiling_2.out new file mode 100644 index 00000000..47548394 --- /dev/null +++ b/tests/programs/compile_error_says_text_worked_out_while_compiling_2.out @@ -0,0 +1,4 @@ + +--- exit 2 +tests/programs/compile_error_says_text_worked_out_while_compiling_2.sakura:12:31: invalid: `b` is a field of `pair` +tests/programs/compile_error_says_text_worked_out_while_compiling_2.sakura:7:18: invalid: `u32` takes 4 bytes, and `u8` 1 (In `same_size`) diff --git a/tests/programs/compile_error_says_text_worked_out_while_compiling_2.sakura b/tests/programs/compile_error_says_text_worked_out_while_compiling_2.sakura new file mode 100644 index 00000000..3f6183ae --- /dev/null +++ b/tests/programs/compile_error_says_text_worked_out_while_compiling_2.sakura @@ -0,0 +1,19 @@ +import std::io; + +# A `compile_error` given interpolated text says what evaluating works out it +# says, in a generic's instance, and at the declaration whose `at` it is given. +def same_size(): u64 { + if const size_of::() != size_of::() { + compile_error($"`{name_of::()}` takes {size_of::()} bytes, and `{name_of::()}` {size_of::()}"); + } + return size_of::(); +} + +struct pair { var a: i64; var b: i64; } + +def main(): void { + println($"{same_size::()} {same_size::()}"); + for const f in members_of(decl_of::()) { + if const f.name == "b" { compile_error($"`{f.name}` is a field of `{name_of::()}`", f.at); } + } +} diff --git a/tests/programs/compile_error_waits_for_evaluating_to_choose_its_branch_1.out b/tests/programs/compile_error_waits_for_evaluating_to_choose_its_branch_1.out new file mode 100644 index 00000000..6f10d69f --- /dev/null +++ b/tests/programs/compile_error_waits_for_evaluating_to_choose_its_branch_1.out @@ -0,0 +1,6 @@ + +--- exit 2 +tests/programs/compile_error_waits_for_evaluating_to_choose_its_branch_1.sakura:24:41: invalid: broken +tests/programs/compile_error_waits_for_evaluating_to_choose_its_branch_1.sakura:33:43: invalid: no field is b +tests/programs/compile_error_waits_for_evaluating_to_choose_its_branch_1.sakura:34:66: invalid: no field is z +tests/programs/compile_error_waits_for_evaluating_to_choose_its_branch_1.sakura:15:23: invalid: not the same size (In `same_size`) diff --git a/tests/programs/compile_error_waits_for_evaluating_to_choose_its_branch_1.sakura b/tests/programs/compile_error_waits_for_evaluating_to_choose_its_branch_1.sakura new file mode 100644 index 00000000..11a2254c --- /dev/null +++ b/tests/programs/compile_error_waits_for_evaluating_to_choose_its_branch_1.sakura @@ -0,0 +1,37 @@ +import std::io; + +# A `compile_error` in a branch of `if const` that only evaluating decides is +# reported once evaluating chooses that branch, as one in a branch the checker +# decides is, and never where it chooses another: of a computed constant, of +# `size_of` in a generic's instance, and of what a pass of `for const` over a +# struct's fields describes. +struct outcome { val failed: bool; } +def build(n: i64): outcome { return outcome { failed = n > 5 }; } +const broken: outcome = build(7); +const fine: outcome = build(3); + +def same_size(): u64 { + if const size_of::() == size_of::() { return size_of::(); } + else { compile_error("not the same size"); } + return 0; +} + +@usage{ on = target::fields } +struct mark : attribute { val letter: u8 = 0; } +struct marked { @mark{ letter = 'q' } var a: i64; @mark{ letter = 'z' } var b: i64; } + +def main(): void { + if const broken.failed { compile_error("broken"); } + if const fine.failed { compile_error("fine, so never reported"); } + if const broken.failed && !fine.failed { + if const fine.failed { compile_error("a branch not taken within one taken"); } + } else { + compile_error("a branch not taken"); + } + println($"{same_size::()} {same_size::()}"); + for const f in members_of(decl_of::()) { + if const f.name == "b" { compile_error("no field is b"); } + if const attached::(f)[0].letter == 'z' { compile_error("no field is z"); } + if const f.name == "c" { compile_error("no field is c, so never reported"); } + } +} diff --git a/tests/programs/compile_error_waits_for_evaluating_to_choose_its_branch_2.out b/tests/programs/compile_error_waits_for_evaluating_to_choose_its_branch_2.out new file mode 100644 index 00000000..ceb885f9 --- /dev/null +++ b/tests/programs/compile_error_waits_for_evaluating_to_choose_its_branch_2.out @@ -0,0 +1,4 @@ +fine +8 1 +a +b diff --git a/tests/programs/compile_error_waits_for_evaluating_to_choose_its_branch_2.sakura b/tests/programs/compile_error_waits_for_evaluating_to_choose_its_branch_2.sakura new file mode 100644 index 00000000..4e02bdea --- /dev/null +++ b/tests/programs/compile_error_waits_for_evaluating_to_choose_its_branch_2.sakura @@ -0,0 +1,27 @@ +import std::io; + +# Where evaluating chooses no branch of `if const` holding a `compile_error`, +# the program compiles, and runs the branches chosen. +struct outcome { val failed: bool; } +def build(n: i64): outcome { return outcome { failed = n > 5 }; } +const fine: outcome = build(3); + +def same_size(): u64 { + if const size_of::() == size_of::() { return size_of::(); } + else { compile_error("not the same size"); } + return 0; +} + +@usage{ on = target::fields } +struct mark : attribute { val letter: u8 = 0; } +struct marked { @mark{ letter = 'q' } var a: i64; @mark{ letter = 'r' } var b: i64; } + +def main(): void { + if const fine.failed { compile_error("fine"); } else { println("fine"); } + println($"{same_size::()} {same_size::()}"); + for const f in members_of(decl_of::()) { + if const f.name == "c" { compile_error("no field is c"); } + if const attached::(f)[0].letter == 'z' { compile_error("no field is z"); } + println(f.name); + } +} diff --git a/tests/programs/compound_assignments_change_in_place_where_a_type_can_1.out b/tests/programs/compound_assignments_change_in_place_where_a_type_can_1.out new file mode 100644 index 00000000..68a49e69 --- /dev/null +++ b/tests/programs/compound_assignments_change_in_place_where_a_type_can_1.out @@ -0,0 +1,6 @@ +52 made 1 grown 2 +6 made 0 grown 1 +8 made 0 grown 1 +15 +top +more diff --git a/tests/programs/compound_assignments_change_in_place_where_a_type_can_1.sakura b/tests/programs/compound_assignments_change_in_place_where_a_type_can_1.sakura new file mode 100644 index 00000000..f4cda09c --- /dev/null +++ b/tests/programs/compound_assignments_change_in_place_where_a_type_can_1.sakura @@ -0,0 +1,47 @@ +import std::io; + +# A compound assignment calls the method changing its target in place where the +# target's type has one taking the value, as `+=` calls `add_assign`, which gives +# nothing, and otherwise writes what the operator's method gives over the target, +# as `x = x + y` would. So a type owning memory can grow in place. + +struct tally { var total: i64; var made: i64; var grown: i64; } +def tally::add(&this, other: &tally): tally { return tally { total = this.total + other.total, made = this.made + 1, grown = this.grown }; } +def tally::add(&this, k: &i64): tally { return tally { total = this.total + k, made = this.made + 1, grown = this.grown }; } +def tally::add_assign(&mut this, other: &tally): void { this.total += other.total; this.grown++; } +def tally::shift_left_assign(&mut this, by: &u32): void { this.total <<= by; this.grown++; } + +struct box { var held: tally; } +var box::inside: tally { get => this.held; set => this.held = value; } + +# A type owning memory grows in place, through a property's `get` and `set` too. +struct lines { var text: string; } +def lines::add_assign(&mut this, more: &strview): void { this.text.append(more); this.text.append("\n"); } +struct page { var body: lines; } +var page::lines: lines { + get => lines { text = copy(&this.body.text) }; + set => this.body = move(&mut value); +} + +def main(): void { + var t := tally { total = 1 }; + t += tally { total = 2 }; # add_assign + t += 10 as i64; # no `add_assign` takes an `i64`, so `add` + t <<= 2; # shift_left_assign + io::println($"{t.total} made {t.made} grown {t.grown}"); + + var b := box { held = tally { total = 5 } }; + b.inside += tally { total = 1 }; + io::println($"{b.held.total} made {b.held.made} grown {b.held.grown}"); + + var all := vector::::new(); + all.append(tally { total = 7 }); + all[0] += tally { total = 1 }; + io::println($"{all[0].total} made {all[0].made} grown {all[0].grown}"); + + var written := lines { text = string::new(nothing {}) }; + for i in 0..3 { written += "line"; } + var p := page { body = lines { text = string::from("top\n", nothing {}) } }; + p.lines += "more"; + io::print($"{written.text.length}\n{p.body.text}"); +} diff --git a/tests/programs/const_declarations_1.out b/tests/programs/const_declarations_1.out new file mode 100644 index 00000000..6cbcc7e3 --- /dev/null +++ b/tests/programs/const_declarations_1.out @@ -0,0 +1,5 @@ +0 green shape{circle = 1.5} +-100 green shape{count = 1} +1996959894 256 755167117 44 0.1 -5 +narrow 3 wide 4 8 is 8 bits ordered other +0 1 diff --git a/tests/programs/const_declarations_1.sakura b/tests/programs/const_declarations_1.sakura new file mode 100644 index 00000000..014e2974 --- /dev/null +++ b/tests/programs/const_declarations_1.sakura @@ -0,0 +1,53 @@ +import std::io; +enum color: u8 { red, green = 4, blue } +union shape { var circle: f32; var count: i32; } +struct entry { var weight: i16; var hue: color; var form: shape; } +def make(): entry[2] { + var out: entry[2]; + for i in 0..2 { + out[i] = entry{ weight = -(i as i16) * 100, hue = color::green, + form = i % 2 == 0 ? shape{ circle = 1.5 } : shape{ count = i as i32 } }; + } + return out; +} +const entries: entry[2] = make(); +def crc_table(): u32[256] { + var table: u32[256]; + for i in 0..256 { + var c := i as u32; + for _ in 0..8 { c = (c & 1) != 0 ? 0xEDB88320 ^ (c >> 1) : c >> 1; } + table[i] = c; + } + return table; +} +const crc: u32[256] = crc_table(); +def doubled(): int { return base * 2; } +const twice := doubled(); +const base := 21; +struct counter { var n: int; } +def counter::bump(&mut this): void { this.n++; } +def bumped(): int { var c := counter{ 0 }; c.bump(); c.bump(); return c.n; } +trait sized { const bytes: u64; } +const i32::bytes: u64 = 4; +const i64::bytes: u64 = 8; +def show(x: T): string where T: sized { + const bits := T::bytes * 8; + if const bits > 32 { return $"wide {x}"; } else { return $"narrow {x}"; } +} +def kind(x: T): string { + if const T is integer { return $"{x + 1} is {size_of::() * 8} bits"; } + else if const T is ordered { return "ordered"; } + else { return "other"; } +} +const small: f32 = 0.1; +const neg: i8 = -5; +val copied := crc; +def main(): void { + for e in entries { println($"{e.weight} {e.hue} {e.form}"); } + const local := bumped() + twice; + println($"{crc[1]} {crc.length} {copied[255]} {local} {small} {neg}"); + println($"{show(3 as i32)} {show(4)} {kind(7 as u8)} {kind(2.5)} {kind(entries)}"); + var mine := crc; + mine[0] = 1; + println($"{crc[0]} {mine[0]}"); +} diff --git a/tests/programs/const_pointers_1.out b/tests/programs/const_pointers_1.out new file mode 100644 index 00000000..c21b1ec4 --- /dev/null +++ b/tests/programs/const_pointers_1.out @@ -0,0 +1 @@ +[4, 3, 2, 1, 0] 13 7 diff --git a/tests/programs/const_pointers_1.sakura b/tests/programs/const_pointers_1.sakura new file mode 100644 index 00000000..b58edf84 --- /dev/null +++ b/tests/programs/const_pointers_1.sakura @@ -0,0 +1,40 @@ +import std::io; +struct node { var value: int; var next: *mut node; } +type block = *mut u8; +def countdown(): int[5] { + var head: *mut node = null; + var blocks: block[5]; + for i in 0..5 { + val made := raw_allocate(size_of::()) as *mut node; + (*made).value = i as int; + (*made).next = head; + head = made; + blocks[i] = made as *mut u8; + } + var out: int[5]; + var at := head; + var k := 0; + while at != null { out[k] = (*at).value; k++; at = (*at).next; } + for i in 0..5 { raw_release(blocks[i]); } + return out; +} +def total(first: *int, count: u64): int { + var sum := 0; + for i in 0..count { sum += first[i]; } + val last := first + (count - 1); + return sum + (last - first) as int; +} +def summing(): int { + var xs: int[4] = [1, 2, 3, 4]; + return total((&xs) as *int, 4); +} +def through_local(): int { + var x := 5; + val p := &mut x as *mut int; + p[0] = 7; + return x; +} +const down := countdown(); +const summed := summing(); +const written := through_local(); +def main(): void { println($"{down} {summed} {written}"); } diff --git a/tests/programs/constants_are_made_by_operators_of_methods_1.out b/tests/programs/constants_are_made_by_operators_of_methods_1.out new file mode 100644 index 00000000..a1dca2ab --- /dev/null +++ b/tests/programs/constants_are_made_by_operators_of_methods_1.out @@ -0,0 +1 @@ +7000000000 -6000000000 12000000000 diff --git a/tests/programs/constants_are_made_by_operators_of_methods_1.sakura b/tests/programs/constants_are_made_by_operators_of_methods_1.sakura new file mode 100644 index 00000000..087703b8 --- /dev/null +++ b/tests/programs/constants_are_made_by_operators_of_methods_1.sakura @@ -0,0 +1,13 @@ +import std::io; +# An operator calling a method still makes a constant while compiling. +struct length { val ns: i64; } +def length::add(&this, other: &length): length { return length { ns = this.ns + other.ns }; } +def length::mul(&this, by: &i64): length { return length { ns = this.ns * by }; } +def length::negate(&this): length { return length { ns = -this.ns }; } +def seconds(count: i64): length { return length { ns = count * 1000000000 }; } +const pause: length = seconds(1) + seconds(2) * 3; +const back: length = -pause + seconds(1); +const longest: length = seconds(2) * 3 + -seconds(1) + pause; +def main(): void { + println($"{pause.ns} {back.ns} {longest.ns}"); +} diff --git a/tests/programs/constants_hold_functions_1.out b/tests/programs/constants_hold_functions_1.out new file mode 100644 index 00000000..fd539626 --- /dev/null +++ b/tests/programs/constants_hold_functions_1.out @@ -0,0 +1 @@ +add=9 mul=18 sub=3 42 20 9 def mul diff --git a/tests/programs/constants_hold_functions_1.sakura b/tests/programs/constants_hold_functions_1.sakura new file mode 100644 index 00000000..57c989a9 --- /dev/null +++ b/tests/programs/constants_hold_functions_1.sakura @@ -0,0 +1,20 @@ +import std::io; +type op = def(i64, i64): i64; +def add(a: i64, b: i64): i64 { return a + b; } +def mul(a: i64, b: i64): i64 { return a * b; } +def twice(x: T): T where T: numeric { return x + x; } +struct entry { val name: span; val run: op; } +const ops: entry[3] = [entry{ name = "add", run = add }, entry{ name = "mul", run = mul }, + entry{ name = "sub", run = def(a: i64, b: i64): i64 { return a - b; } }]; +const dbl: def(i64): i64 = twice::; +def made(): span { + val table := raw_allocate(2 * size_of::()) as *mut op; + table[0] = mul; + table[1] = add; + return table[0:2]; +} +const kept: span = made(); +def main(): void { + for &e in ops { print($"{e.name}={e.run(6, 3)} "); } + println($"{dbl(21)} {kept[0](4, 5)} {kept[1](4, 5)} {ops[1].run}"); +} diff --git a/tests/programs/constants_keep_the_memory_they_point_into_3.out b/tests/programs/constants_keep_the_memory_they_point_into_3.out new file mode 100644 index 00000000..04063862 --- /dev/null +++ b/tests/programs/constants_keep_the_memory_they_point_into_3.out @@ -0,0 +1 @@ +hello 5 true diff --git a/tests/programs/constants_keep_the_memory_they_point_into_3.sakura b/tests/programs/constants_keep_the_memory_they_point_into_3.sakura new file mode 100644 index 00000000..f918bc89 --- /dev/null +++ b/tests/programs/constants_keep_the_memory_they_point_into_3.sakura @@ -0,0 +1,4 @@ +import std::io; +const greeting: span = "hello"; +const empty: *i64 = null; +def main(): void { println($"{greeting} {greeting.length} {empty == null}"); } diff --git a/tests/programs/constants_view_other_constants_1.out b/tests/programs/constants_view_other_constants_1.out new file mode 100644 index 00000000..e047beb7 --- /dev/null +++ b/tests/programs/constants_view_other_constants_1.out @@ -0,0 +1,7 @@ +5 28 3 7 5 2 0 +two three 2 +odd 4 26 +2 5 23 +true true true true +11 true true +8 true diff --git a/tests/programs/constants_view_other_constants_1.sakura b/tests/programs/constants_view_other_constants_1.sakura new file mode 100644 index 00000000..36b95b1e --- /dev/null +++ b/tests/programs/constants_view_other_constants_1.sakura @@ -0,0 +1,60 @@ +import std::io; + +# A constant holds views of another constant's array, which it shares rather +# than copies: a view of a view, views within a struct and within memory the +# constant allocated, an empty view at the array's end, and a reference to an +# element. +const primes: u64[5] = [2, 3, 5, 7, 11]; +const all: span = primes[:]; +const middle: span = primes[1:3]; +const inner: span = rest(middle); +const none: span = primes[5:0]; +const largest: &u64 = &primes[4]; + +const words: strview[3] = ["one", "two", "three"]; +const later: span = words[1:]; + +struct table { + var name: strview; + var rows: span; +} + +const odd: table = table{ name = "odd", rows = primes[1:] }; + +def rest(of: span): span { + return of.sub(1, of.length - 1) else { return of; }; +} + +def halves(): span> { + val made := raw_allocate(2 * size_of::>()) as *mut span; + made[0] = primes[0:2]; + made[1] = primes[2:3]; + return span::>::over(made as *span, 2); +} + +const split: span> = halves(); + +def sum(of: span): u64 { + var total := 0u; + for each in of { total += each; } + return total; +} + +def main(): void { + println($"{all.length} {sum(all)} {middle[0]} {middle[2]} {inner[0]} {inner.length} {none.length}"); + println($"{later[0]} {later[1]} {later.length}"); + println($"{odd.name} {odd.rows.length} {sum(odd.rows)}"); + println($"{split.length} {sum(split[0])} {sum(split[1])}"); + + # The views are of the array itself, not of copies of it. + println($"{all.data == primes[:].data} {inner.data == primes[2:].data} {split[1].data == primes[2:].data} {none.data == primes[5:0].data}"); + + # A reference to an element, as a constant and as the program runs, is to + # the element where the array is. + val held: &u64 = &primes[4]; + println($"{largest} {(largest as *u64) == all.data + 4} {(held as *u64) == all.data + 4}"); + + # A local constant views a global one. + const first: span = primes[1:2]; + println($"{sum(first)} {first.data == all.data + 1}"); +} diff --git a/tests/programs/contracts_1.out b/tests/programs/contracts_1.out new file mode 100644 index 00000000..e5f8c8d4 --- /dev/null +++ b/tests/programs/contracts_1.out @@ -0,0 +1,6 @@ +3 + +--- exit 1 +sakura: runtime error: A pre-condition failed: b != 0, with b = 0. + at divide (tests/programs/contracts_1.sakura:6:3) + at main (tests/programs/contracts_1.sakura:13:24) diff --git a/tests/programs/contracts_1.sakura b/tests/programs/contracts_1.sakura new file mode 100644 index 00000000..c9bbbcaf --- /dev/null +++ b/tests/programs/contracts_1.sakura @@ -0,0 +1,14 @@ +# A pre-condition that fails stops the program, saying what it checked and +# what its operands held. +import std::io; + +def divide(a: i64, b: i64): i64 { + expects(b != 0); + ensures(q: q * b + a % b == a); + return a / b; +} + +def main(): void { + io::println($"{divide(7, 2)}"); + io::println($"{divide(7, 0)}"); +} diff --git a/tests/programs/contracts_2.out b/tests/programs/contracts_2.out new file mode 100644 index 00000000..6ef7683f --- /dev/null +++ b/tests/programs/contracts_2.out @@ -0,0 +1,7 @@ +(a) closes what it opens +((b) c) closes what it opens + +--- exit 1 +sakura: runtime error: An assertion failed: A parenthesis closes one never opened, with depth = -1. + at balanced (tests/programs/contracts_2.sakura:12:7) + at main (tests/programs/contracts_2.sakura:20:11) diff --git a/tests/programs/contracts_2.sakura b/tests/programs/contracts_2.sakura new file mode 100644 index 00000000..180bf6eb --- /dev/null +++ b/tests/programs/contracts_2.sakura @@ -0,0 +1,21 @@ +# An assertion says what failed in words of its own, in place of the condition, +# and an `ensures` in a loop's block is checked at each pass's end. +import std::io; + +def balanced(lines: span): void { + for line in lines { + var depth := 0; + ensures(depth == 0); + for c in line { + continue if c == ' '; + depth += c == '(' ? 1 : c == ')' ? -1 : 0; + asserts(depth >= 0, "A parenthesis closes one never opened."); + } + io::println($"{line} closes what it opens"); + } +} + +def main(): void { + balanced(["(a)", "((b) c)"]); + balanced(["(d))"]); +} diff --git a/tests/programs/contracts_3.out b/tests/programs/contracts_3.out new file mode 100644 index 00000000..1e269389 --- /dev/null +++ b/tests/programs/contracts_3.out @@ -0,0 +1,6 @@ +first second first pass0 pass1 pass2 turn1 turn2 block + +--- exit 1 +sakura: runtime error: A post-condition failed: found == -1 || found % 2 == 0. + at first_even (tests/programs/contracts_3.sakura:40:5) + at main (tests/programs/contracts_3.sakura:54:28) diff --git a/tests/programs/contracts_3.sakura b/tests/programs/contracts_3.sakura new file mode 100644 index 00000000..79558e70 --- /dev/null +++ b/tests/programs/contracts_3.sakura @@ -0,0 +1,55 @@ +# An `ensures` is checked on every way out of its block once it is reached: a +# `return`, a `break` or `continue` leaving the block, and the block's end. Of +# several, the last written is checked first. +import std::io; + +var seen: string; + +def saw(what: strview): bool { + seen.append(what); + seen.append(" "); + return true; +} + +def returns(early: bool): i64 { + ensures(saw("first")); + return 1 if early; + ensures(saw("second")); + return 2; +} + +def loops(): void { + for i in 0..4 { + ensures(saw($"pass{i}")); + continue if i == 1; + break if i == 2; + } + var k := 0; + while k < 2 { + k++; + ensures(saw($"turn{k}")); + } + { + ensures(saw("block")); + } +} + +def first_even(xs: span): i64 { + var found: i64 = -1; + for x in xs { + ensures(found == -1 || found % 2 == 0); + if x % 2 == 1 { + found = x; + break; + } + } + return found; +} + +def main(): void { + _ = returns(true); + _ = returns(false); + loops(); + io::println(seen.view()); + io::println($"{first_even([1, 2, 3][:])}"); +} diff --git a/tests/programs/contracts_4.out b/tests/programs/contracts_4.out new file mode 100644 index 00000000..7718200a --- /dev/null +++ b/tests/programs/contracts_4.out @@ -0,0 +1,6 @@ +7 + +--- exit 1 +sakura: runtime error: A post-condition failed: left == old(from.balance) - amount, with left = 5, old(from.balance) - amount = 4. + at withdraw_wrongly (tests/programs/contracts_4.sakura:15:3) + at main (tests/programs/contracts_4.sakura:23:34) diff --git a/tests/programs/contracts_4.sakura b/tests/programs/contracts_4.sakura new file mode 100644 index 00000000..b139047c --- /dev/null +++ b/tests/programs/contracts_4.sakura @@ -0,0 +1,24 @@ +# An `ensures` names what the function returns, and `old` within it is what an +# expression was where the `ensures` was reached. +import std::io; + +struct wallet { var balance: u64; } + +def withdraw(from: &mut wallet, amount: u64): u64 { + expects(amount <= from.balance, "A wallet gives no more than it holds."); + ensures(left: left == old(from.balance) - amount); + from.balance -= amount; + return from.balance; +} + +def withdraw_wrongly(from: &mut wallet, amount: u64): u64 { + ensures(left: left == old(from.balance) - amount); + from.balance -= amount; + return from.balance + 1; +} + +def main(): void { + var held := wallet { balance = 10 }; + io::println($"{withdraw(&mut held, 3)}"); + io::println($"{withdraw_wrongly(&mut held, 3)}"); +} diff --git a/tests/programs/contracts_5.out b/tests/programs/contracts_5.out new file mode 100644 index 00000000..64764493 --- /dev/null +++ b/tests/programs/contracts_5.out @@ -0,0 +1,4 @@ +abc +9 2.5 5 +108 true true +contracts are checked diff --git a/tests/programs/contracts_5.sakura b/tests/programs/contracts_5.sakura new file mode 100644 index 00000000..28aa2e52 --- /dev/null +++ b/tests/programs/contracts_5.sakura @@ -0,0 +1,43 @@ +# Contracts that hold change nothing: a local given back by name reads as +# itself, generic code checks each instance, a lambda's `ensures` covers its own +# `return`, and `expects`, `asserts`, `ensures`, and `old` are names wherever no +# statement begins with one. +import std::io; + +struct terms { var expects: bool; var ensures: i64; } + +def asserts(n: i64): i64 { return n * 2; } + +def old(n: i64): i64 { return n + 100; } + +def named(): string { + var s := string::from("abc", nothing {}); + ensures(r: r.length == 3 && s.length == 3); + return s; +} + +def largest(a: T, b: T): T where T: ordered { + ensures(r: r >= a && r >= b); + return a > b ? a : b; +} + +def next_of(n: i64): i64 { + val step := def(k: i64): i64 { + ensures(r: r > k); + return k + 1; + }; + return step(n); +} + +def main(): void { + io::println(named().view()); + io::println($"{largest(3, 9)} {largest::(2.5, 1.5)} {next_of(4)}"); + val made := terms { expects = true, ensures = 3 }; + var expects := asserts(made.ensures) + old(1); + ensures(old(expects) == 107 && expects == 108); + expects++; + io::println($"{expects} {made.expects} {contracts()}"); + if const contracts() { + io::println("contracts are checked"); + } +} diff --git a/tests/programs/contracts_6.out b/tests/programs/contracts_6.out new file mode 100644 index 00000000..e244ad6a --- /dev/null +++ b/tests/programs/contracts_6.out @@ -0,0 +1,6 @@ +2 counted + +--- exit 1 +sakura: runtime error: A pre-condition failed: A count of 0 is above zero, with count = 0. + at counted (tests/programs/contracts_6.sakura:6:3) + at main (tests/programs/contracts_6.sakura:12:10) diff --git a/tests/programs/contracts_6.sakura b/tests/programs/contracts_6.sakura new file mode 100644 index 00000000..063428d8 --- /dev/null +++ b/tests/programs/contracts_6.sakura @@ -0,0 +1,13 @@ +# What a contract says failed may be any view of text, made only where it +# fails, and a full stop it ends with is the report's own. +import std::io; + +def counted(why: strview, count: i64): void { + expects(count > 0, why); + io::println($"{count} counted"); +} + +def main(): void { + counted("A count is above zero.", 2); + counted($"A count of {0} is above zero.", 0); +} diff --git a/tests/programs/control_flow_1.out b/tests/programs/control_flow_1.out new file mode 100644 index 00000000..4ef51798 --- /dev/null +++ b/tests/programs/control_flow_1.out @@ -0,0 +1,3 @@ +negative zero small large +1 3 5 7 9 fib 75025 +97120 98120 diff --git a/tests/programs/control_flow_1.sakura b/tests/programs/control_flow_1.sakura new file mode 100644 index 00000000..f7def75a --- /dev/null +++ b/tests/programs/control_flow_1.sakura @@ -0,0 +1,30 @@ +import std::io; +def view(text: span): span { return text; } +def classify(n: int): string { + if n < 0 { return "negative"; } + else if n == 0 { return "zero"; } + else if n < 10 { return "small"; } + return "large"; +} +def fib(n: int): int { return n < 2 ? n : fib(n - 1) + fib(n - 2); } +def main(): void { + println($"{classify(-1)} {classify(0)} {classify(5)} {classify(50)}"); + var i := 0; + while true { + i++; + if i % 2 == 0 { continue; } + if i > 9 { break; } + print($"{i} "); + } + println($"fib {fib(25)}"); + val text: span = "a,b,,c"; + for c in text { + if c == ',' { continue; } + if c == 'c' { break; } + for d in view("xy") { + if d == 'y' { break; } + print($"{c as u8}{d as u8} "); + } + } + println(""); +} diff --git a/tests/programs/core_alone_1.out b/tests/programs/core_alone_1.out new file mode 100644 index 00000000..3dfe6a1f --- /dev/null +++ b/tests/programs/core_alone_1.out @@ -0,0 +1,7 @@ +vector 5 total 30 first 0 last 16 +owner 7 +function 42 pair +maybe 16 result 12 +string core alone 10 CORE ALONE true +lanes 22 4 7 8 +atomic 5 equal true diff --git a/tests/programs/core_alone_1.sakura b/tests/programs/core_alone_1.sakura new file mode 100644 index 00000000..42ebc915 --- /dev/null +++ b/tests/programs/core_alone_1.sakura @@ -0,0 +1,62 @@ +# A program with no imports, which reads `core` alone, and names its types and +# functions with nothing before them: `vector`, `box`, and `function`, the types +# the syntax makes, traits, lanes, and atomics. It writes through `system`, by its +# path, which reads that too. + +struct tally : equatable { + var count: i64; +} + +def tally::equals(&this, other: &tally): bool { + return this.count == other.count; +} + +def say(text: strview): void { + system::fd::stdout.put(text); + system::fd::stdout.put("\n"); +} + +def total(values: span): T where T: integer { + var sum: T = 0; + for &each in values { + sum = sum + each; + } + return sum; +} + +def main(): void { + var numbers := vector::::new(); + for i in 0..5 { + numbers.append(i * i); + } + val view: span = numbers.view(); + say($"vector {numbers.length} total {total(view)} first {view[0]} last {view[4]}"); + + val boxed := box::::new(7); + say($"owner {boxed.get()}"); + + val doubled := function::::new(def(x: i64): i64 { return x * 2; }); + val both := pair:: { first = doubled(21), second = "pair" }; + say($"function {both.first} {both.second}"); + + var found: maybe = nothing {}; + if view.last() is some(&at) { + found = at; + } + val parsed: result = 12; + if found is some(value) && parsed is value(twelve) { + say($"maybe {value} result {twelve}"); + } + + var text := string::from("core", nothing {}); + text.append(" alone"); + val words: strview = text.view(); + say($"string {text} {words.length} {words.upper()} {text.view() == words}"); + + var lanes := u32x4::splat(3) + u32x4::of([1, 2, 3, 4]); + say($"lanes {lanes.sum()} {lanes.smallest()} {lanes.largest()} {count_ones(255u)}"); + + var counter := atomic::::new(1); + _ = counter.fetch_add(4); + say($"atomic {counter.load()} equal {tally { count = 1 } == tally { count = 1 }}"); +} diff --git a/tests/programs/decl_of_takes_a_type_a_declaration_makes_1.out b/tests/programs/decl_of_takes_a_type_a_declaration_makes_1.out new file mode 100644 index 00000000..f42a46f0 --- /dev/null +++ b/tests/programs/decl_of_takes_a_type_a_declaration_makes_1.out @@ -0,0 +1,3 @@ + +--- exit 2 +tests/programs/decl_of_takes_a_type_a_declaration_makes_1.sakura:3:53: invalid: `decl_of` takes a type a declaration makes, as a struct, union, enum, or trait, and `&position` is none: `name_of` and `path_of` name any type. (In `path_of_decl<&position>`) diff --git a/tests/programs/decl_of_takes_a_type_a_declaration_makes_1.sakura b/tests/programs/decl_of_takes_a_type_a_declaration_makes_1.sakura new file mode 100644 index 00000000..608ff022 --- /dev/null +++ b/tests/programs/decl_of_takes_a_type_a_declaration_makes_1.sakura @@ -0,0 +1,7 @@ +import std::io; +struct position { var x: int; } +def path_of_decl(): strview { return decl_of::().path; } +def main(): void { + println(path_of_decl::()); + println(path_of_decl::<&position>()); +} diff --git a/tests/programs/default_trait_methods_1.out b/tests/programs/default_trait_methods_1.out new file mode 100644 index 00000000..0bdbe20b --- /dev/null +++ b/tests/programs/default_trait_methods_1.out @@ -0,0 +1,2 @@ +shape of area 4, circle of area 3, shape of area 5 +18 4 9 =373 diff --git a/tests/programs/default_trait_methods_1.sakura b/tests/programs/default_trait_methods_1.sakura new file mode 100644 index 00000000..7a5f58f4 --- /dev/null +++ b/tests/programs/default_trait_methods_1.sakura @@ -0,0 +1,32 @@ +import std::io; +trait Shape { + def area(&this): f64; + def name(&this): string { return "shape"; } + def describe(&this): string { return $"{this.name()} of area {this.area()}"; } + def grow(&mut this, by: f64): void { this.scale(by); this.scale(by); } + def mix(&this, a: f64, label: span, other: &Shape): string { return $"{label}{this.area() + a + other.area()}"; } + def scale(&mut this, by: f64): void; +} +struct square: Shape { var side: f64; } +def square::area(&this): f64 { return this.side * this.side; } +def square::scale(&mut this, by: f64): void { this.side *= by; } +struct circle: Shape { var r: f64; } +def circle::area(&this): f64 { return 3 * this.r * this.r; } +def circle::name(&this): string { return "circle"; } +def circle::scale(&mut this, by: f64): void { this.r *= by; } +struct blob { var size: f64; } +def blob::area(&this): f64 { return this.size; } +def blob::scale(&mut this, by: f64): void { this.size += by; } +def show(s: &Shape): string { return s.describe(); } +def enlarge(s: &mut Shape): void { s.grow(2); } +def main(): void { + var sq := square{ 2 }; + var c := circle{ 1 }; + var b := blob{ 5 }; + println($"{sq.describe()}, {c.describe()}, {show(b)}"); + sq.grow(3); + enlarge(c); + enlarge(b); + val label := "="; + println($"{sq.side} {c.r} {b.size} {sq.mix(1, label, c)}"); +} diff --git a/tests/programs/default_values_belong_to_the_declaration_a_call_reaches_1.out b/tests/programs/default_values_belong_to_the_declaration_a_call_reaches_1.out new file mode 100644 index 00000000..d353ed7d --- /dev/null +++ b/tests/programs/default_values_belong_to_the_declaration_a_call_reaches_1.out @@ -0,0 +1,2 @@ +* 4 +> 4 diff --git a/tests/programs/default_values_belong_to_the_declaration_a_call_reaches_1.sakura b/tests/programs/default_values_belong_to_the_declaration_a_call_reaches_1.sakura new file mode 100644 index 00000000..e636f3ff --- /dev/null +++ b/tests/programs/default_values_belong_to_the_declaration_a_call_reaches_1.sakura @@ -0,0 +1,10 @@ +import std::io; +trait shows { def show(this: &shows, prefix: span = "> "): string; } +struct dot { val n: int; } +def dot::show(this: &dot, prefix: span = "* "): string { return $"{prefix}{this.n}"; } +def through(s: &shows): string { return s.show(); } +def main(): void { + val d := dot { n = 4 }; + println(d.show()); + println(through(&d)); +} diff --git a/tests/programs/dereferences_2.out b/tests/programs/dereferences_2.out new file mode 100644 index 00000000..b9856f43 --- /dev/null +++ b/tests/programs/dereferences_2.out @@ -0,0 +1,5 @@ +before + +--- exit 1 +sakura: runtime error: Null reference was unwrapped. + at main (tests/programs/dereferences_2.sakura:5:6) diff --git a/tests/programs/dereferences_2.sakura b/tests/programs/dereferences_2.sakura new file mode 100644 index 00000000..81549eec --- /dev/null +++ b/tests/programs/dereferences_2.sakura @@ -0,0 +1,6 @@ +import std::io; +def main(): void { + var p: *mut int; + println("before"); + *p = 1; +} diff --git a/tests/programs/enums_and_match_values_1.out b/tests/programs/enums_and_match_values_1.out new file mode 100644 index 00000000..b0f40973 --- /dev/null +++ b/tests/programs/enums_and_match_values_1.out @@ -0,0 +1,5 @@ +[red, green, blue] 9 paint{shade = blue, levels = [low, high]} green top bottom +red:r:low:-3 green:g:mid:-2 blue:b:mid:-2 +none; int 7; text; +[green, blue] [red, blue] false true true +10 20 diff --git a/tests/programs/enums_and_match_values_1.sakura b/tests/programs/enums_and_match_values_1.sakura new file mode 100644 index 00000000..bd921f3f --- /dev/null +++ b/tests/programs/enums_and_match_values_1.sakura @@ -0,0 +1,39 @@ +import std::io; +enum color: u8 { red, green = 4, blue } +enum level { low = -3, mid, high = 10 } +enum wide: u64 { top = 18446744073709551615, bottom = 0 } +struct nothing {} +union value { var none: nothing; var number: i64; var text: span; } +struct paint { var shade: color; var levels: span; } +def color::next(this: &color): color { + return match this { red => color::green, green => color::blue, blue => color::red }; +} +def name(v: value): string { + return match v { number(n) => $"int {n}", text(s) => s, none => "none" }; +} +def most(a: T, b: T): T where T: ordered { return a > b ? a : b; } +def main(): void { + var c := color::red; + val seen: color[3] = [c, c.next(), c.next().next()]; + var total: u32 = 0; + for s in seen { total += s; } + var ls: level[2] = [level::low, level::high]; + val p := paint{ shade = color::blue, levels = span::::over((&ls) as *level, 2) }; + println($"{seen} {total} {p} {most(color::green, color::red)} {wide::top} {wide::bottom}"); + for n in [0, 4, 5] { + val shade := n as color; + val word := match shade { red => "r", green => "g", blue => "b" }; + val lv := match n { 0 => level::low, 4, 5 => level::mid, else => level::high }; + print($"{shade}:{word}:{lv}:{lv as i32} "); + } + println(""); + var values: value[3] = [value{}, value{ number = 7 }, value{ text = "text" }]; + for v in values { print($"{name(v)}; "); } + println(""); + val bytes := [color::green, color::blue]; + var copy := bytes; + copy[0] = color::red; + println($"{bytes} {copy} {bytes == copy} {level::mid < level::high} {c == 0}"); + val pick := def(x: color): int { return match x { red => 1, else => 2 } * 10; }; + println($"{pick(color::red)} {pick(color::blue)}"); +} diff --git a/tests/programs/enums_and_match_values_2.out b/tests/programs/enums_and_match_values_2.out new file mode 100644 index 00000000..62bd71b7 --- /dev/null +++ b/tests/programs/enums_and_match_values_2.out @@ -0,0 +1,2 @@ +a 2 true c +2 3 e 3 1 diff --git a/tests/programs/enums_and_match_values_2.sakura b/tests/programs/enums_and_match_values_2.sakura new file mode 100644 index 00000000..963e56c1 --- /dev/null +++ b/tests/programs/enums_and_match_values_2.sakura @@ -0,0 +1,8 @@ +import std::io; +enum word: u8 { a, b, c, first = word::a, last = word::c } +enum next: u8 { start = word::last, d, e, stop = next::e } +def name(w: word): int { return match w { first => 1, b => 2, last => 3 }; } +def main(): void { + println($"{word::first} {word::last as u8} {word::first == word::a} {2 as word}"); + println($"{next::start as u8} {next::d as u8} {next::stop} {name(word::c)} {name(word::a)}"); +} diff --git a/tests/programs/equality_calls_what_a_type_says_it_means_1.out b/tests/programs/equality_calls_what_a_type_says_it_means_1.out new file mode 100644 index 00000000..36bc6136 --- /dev/null +++ b/tests/programs/equality_calls_what_a_type_says_it_means_1.out @@ -0,0 +1,3 @@ +true +false +false diff --git a/tests/programs/equality_calls_what_a_type_says_it_means_1.sakura b/tests/programs/equality_calls_what_a_type_says_it_means_1.sakura new file mode 100644 index 00000000..0750ff8b --- /dev/null +++ b/tests/programs/equality_calls_what_a_type_says_it_means_1.sakura @@ -0,0 +1,8 @@ +import std::io; +struct tag : equatable { var id: i64; var note: i64; } +def tag::equals(&this, other: &tag): bool { return this.id == other.id; } +def main(): void { + println($"{tag{id=1,note=7} == tag{id=1,note=9}}"); + println($"{tag{id=1,note=7} != tag{id=1,note=9}}"); + println($"{tag{id=1,note=7} == tag{id=2,note=7}}"); +} diff --git a/tests/programs/equality_is_what_equals_says_1.out b/tests/programs/equality_is_what_equals_says_1.out new file mode 100644 index 00000000..dc89e38d --- /dev/null +++ b/tests/programs/equality_is_what_equals_says_1.out @@ -0,0 +1 @@ +true false true true false true false true false true false matched diff --git a/tests/programs/equality_is_what_equals_says_1.sakura b/tests/programs/equality_is_what_equals_says_1.sakura new file mode 100644 index 00000000..e45ed005 --- /dev/null +++ b/tests/programs/equality_is_what_equals_says_1.sakura @@ -0,0 +1,37 @@ +import std::io; +struct nothing {} +struct point { var x: int; var y: f32; var tag: span; } +def point::equals(&this, other: &point): bool { + return this.x == other.x && this.y == other.y && this.tag == other.tag; +} +struct tree { var name: span; var kids: *tree; } +def tree::equals(&this, other: &tree): bool { return this.name == other.name && this.kids == other.kids; } +union value { var none: nothing; var whole: int; var text: span; var spot: point; } +def value::equals(&this, other: &value): bool { + match this { + none => return other is none; + whole(n) => { match other { whole(m) => return n == m; else => return false; } } + text(t) => { match other { text(u) => return t == u; else => return false; } } + spot(p) => { match other { spot(q) => return p == q; else => return false; } } + } +} +def main(): void { + val a := point{ x = 1, y = 0.5, tag = "a" }; + var b := a; + print($"{a == b} "); + b.tag = "b"; + val word: span = "x"; + val v := value{ text = word }; + val w := value{ spot = a }; + val x := value{ text = word }; + val three := value{ whole = 3 }; + val same := value{ spot = a }; + print($"{a == b} {a != b} {v == x} {v == three} {w == same} {w == v} "); + var kid := tree{ name = "k", kids = null }; + val t := tree{ name = "r", kids = (&mut kid) as *mut tree }; + var u := t; + print($"{t == u} "); + u.name = "z"; + print($"{t == u} {[a, b] == [a, b]} {[a] == [b]} "); + match w { spot(p) => println(p == a ? "matched" : "missed"); else => println("missed"); } +} diff --git a/tests/programs/errors_are_handled_where_they_are_made_1.out b/tests/programs/errors_are_handled_where_they_are_made_1.out new file mode 100644 index 00000000..f732174b --- /dev/null +++ b/tests/programs/errors_are_handled_where_they_are_made_1.out @@ -0,0 +1 @@ +3 -1 5 7 6 -1 close 101 leaving close 100 102 -1 8 -2 close 200 close 201 x 202 close 202 x 204 held 4 9 close 9 close 4 \ No newline at end of file diff --git a/tests/programs/errors_are_handled_where_they_are_made_1.sakura b/tests/programs/errors_are_handled_where_they_are_made_1.sakura new file mode 100644 index 00000000..7eb742bc --- /dev/null +++ b/tests/programs/errors_are_handled_where_they_are_made_1.sakura @@ -0,0 +1,32 @@ +import std::io; +enum why { empty } +struct res : owning { var id: i64; } +def res::close(&mut this): void { if this.id != 0 { print($"close {this.id} "); } } +def mk(n: i64): res { return res { id = n }; } +def parse(n: i64): result { if n == 0 { return why::empty; } return n; } +def made(n: i64): result { if n == 0 { return why::empty; } return mk(n); } +def find(n: i64): maybe { if n > 1 { return n; } return nothing {}; } +def pair(r: res, n: i64): i64 { return r.id + n; } +def total(xs: span): result { + var sum: i64 = 0; + for x in xs { sum += parse(x) else (e) { return e; }; } + return sum; +} +def early(n: i64): i64 { return pair(mk(100 + n), parse(n) else { print("leaving "); return -1; }); } +def guard(n: i64): i64 { + if parse(n) is not value(v) { return -2; } + return v * 2; +} +def main(): void { + print($"{parse(3) else 0} {parse(0) else -1} {find(5) else 0} {find(1) else 7} "); + print($"{total([1, 2, 3]) else -1} {total([1, 0]) else -1} "); + print($"{early(1)} {early(0)} {guard(4)} {guard(0)} "); + for i in 0..3 { + val x := pair(mk(200 + i), parse(i) else { continue; }); + print($"x {x} "); + } + val r := made(4) else { return; }; + val q := made(0) else mk(9); + _ = parse(1); + print($"held {r.id} {q.id} "); +} diff --git a/tests/programs/faults_2.out b/tests/programs/faults_2.out new file mode 100644 index 00000000..9630c24d --- /dev/null +++ b/tests/programs/faults_2.out @@ -0,0 +1,6 @@ +3 + +--- exit 1 +sakura: runtime error: Division by zero. + at divide (tests/programs/faults_2.sakura:2:44) + at main (tests/programs/faults_2.sakura:5:20) diff --git a/tests/programs/faults_2.sakura b/tests/programs/faults_2.sakura new file mode 100644 index 00000000..9f27c97c --- /dev/null +++ b/tests/programs/faults_2.sakura @@ -0,0 +1,6 @@ +import std::io; +def divide(a: int, b: int): int { return a / b; } +def main(): void { + println($"{divide(7, 2)}"); + println($"{divide(7, 0)}"); +} diff --git a/tests/programs/faults_3.out b/tests/programs/faults_3.out new file mode 100644 index 00000000..e2ea645d --- /dev/null +++ b/tests/programs/faults_3.out @@ -0,0 +1,4 @@ + +--- exit 1 +sakura: runtime error: Null reference was unwrapped. + at main (tests/programs/faults_3.sakura:5:31) diff --git a/tests/programs/faults_3.sakura b/tests/programs/faults_3.sakura new file mode 100644 index 00000000..74df6df2 --- /dev/null +++ b/tests/programs/faults_3.sakura @@ -0,0 +1,6 @@ +import std::io; +struct node { var value: int; var next: *node; } +def main(): void { + val first := node{}; + val second := (*first.next).value; +} diff --git a/tests/programs/fixed_arrays_hold_their_elements_1.out b/tests/programs/fixed_arrays_hold_their_elements_1.out new file mode 100644 index 00000000..c741b2a5 --- /dev/null +++ b/tests/programs/fixed_arrays_hold_their_elements_1.out @@ -0,0 +1,5 @@ +[1, 2, 3, 4] [1, 9, 3, 4] false true 4 +300 40 [10, 20, 30, 40] +6 [[1, 2, 3], [40, 5, 6]] g +[2, 3, 301, 5] +xyz [x, y, z] 6 diff --git a/tests/programs/fixed_arrays_hold_their_elements_1.sakura b/tests/programs/fixed_arrays_hold_their_elements_1.sakura new file mode 100644 index 00000000..9ed4de7b --- /dev/null +++ b/tests/programs/fixed_arrays_hold_their_elements_1.sakura @@ -0,0 +1,34 @@ +import std::io; +const N: uint = 3; +const TABLE: int[4] = [10, 20, 30, 40]; +struct grid { var cells: int[N]; var rows: int[3][2]; var name: span; } +def total(g: &grid): int { + var sum := 0; + for x in g.cells { sum = sum + x; } + return sum; +} +def folded(): int { + var a: int[3] = [1, 2, 3]; + var t := 0; + for x in a { t = t + x; } + return t; +} +def main(): void { + var a: int[4] = [1, 2, 3, 4]; + var b := a; + b[1] = 9; + println($"{a} {b} {a == b} {a == [1, 2, 3, 4]} {a.length}"); + var i: uint = 2; + a[i] = a[i] * 100; + println($"{a[i]} {TABLE[3]} {TABLE}"); + var g := grid { cells = [1, 2, 3], rows = [[1,2,3],[4,5,6]], name = "g" }; + g.rows[1][0] = 40; + println($"{total(&g)} {g.rows} {g.name}"); + for &mut x in a { x = x + 1; } + println($"{a}"); + var texts: span[3] = ["x", "y", "z"]; + var joined := string::new(nothing {}); + for t in texts { joined.append($"{t}"); } + const k := folded(); + println($"{joined} {texts} {k}"); +} diff --git a/tests/programs/for_const_counts_through_ranges_1.out b/tests/programs/for_const_counts_through_ranges_1.out new file mode 100644 index 00000000..fbbb196e --- /dev/null +++ b/tests/programs/for_const_counts_through_ranges_1.out @@ -0,0 +1,8 @@ +i0 i1 i2 +j0 j1 j2 j3 +k1 k2 k3 +n-2 n-1 n0 n1 +f0:1 f2:3 +even0 odd1 even2 odd3 even4 +decided +end diff --git a/tests/programs/for_const_counts_through_ranges_1.sakura b/tests/programs/for_const_counts_through_ranges_1.sakura new file mode 100644 index 00000000..56a65d12 --- /dev/null +++ b/tests/programs/for_const_counts_through_ranges_1.sakura @@ -0,0 +1,42 @@ +import std::io; + +# `for const` counts through a range whose ends are known while checking, a copy +# of its body for each number, in which the variable is a constant: `if const` +# is decided for each, a fixed array may take its length from it, and a constant +# parameter or a negative start may be an end. `if const` reads constants, what +# functions give, and the text of a constant. + +const count: u64 = 3; +def twice(n: u64): u64 { return n * 2; } +const name: strview = "sakura"; +const four: u64 = 2 * 2; +struct box { var a: u64; } +def box::limit(): u64 { return 2; } +def pick(): void { + for const i in 0..N { + if const i % 2 == 0 { print($"even{i} "); } else { print($"odd{i} "); } + } + println(""); +} + +def main(): void { + for const i in 0..count { print($"i{i} "); } + println(""); + for const j in 0..2 * 2 { print($"j{j} "); } + println(""); + for const k in 1..count + 1 { print($"k{k} "); } + println(""); + for const n in -2..2 { print($"n{n} "); } + println(""); + for const f in 0..four { + if const f == 1 { continue; } + if const f == 3 { break; } + var held: u8[f + 1]; + print($"f{f}:{held.length} "); + } + println(""); + pick::<5>(); + for const e in 3..1 { print("never"); } + if const twice(count) == 6 && name[1] == 'a' && box::limit() < 3 { println("decided"); } + println("end"); +} diff --git a/tests/programs/function_types_naming_a_pack_are_what_each_instance_gives_1.out b/tests/programs/function_types_naming_a_pack_are_what_each_instance_gives_1.out new file mode 100644 index 00000000..4dee1d56 --- /dev/null +++ b/tests/programs/function_types_naming_a_pack_are_what_each_instance_gives_1.out @@ -0,0 +1,3 @@ +3 10 0 42 11 +3 calls +3 0 diff --git a/tests/programs/function_types_naming_a_pack_are_what_each_instance_gives_1.sakura b/tests/programs/function_types_naming_a_pack_are_what_each_instance_gives_1.sakura new file mode 100644 index 00000000..bf9f1c2e --- /dev/null +++ b/tests/programs/function_types_naming_a_pack_are_what_each_instance_gives_1.sakura @@ -0,0 +1,81 @@ +import std::io; + +# Written in a body, a function type naming a pack, as `def(*mut u8, Ts...): R`, +# is the type each instance's pack makes of it, as the signature's is: a +# parameter of each type, or a variadic one's where the pack is a variadic +# function's parameters. A holder keeps any callable of a signature behind a +# function given where the callable is. + +def thunk(at: *mut u8, args: Ts...): R where F: invokable { + return (at as *mut F)[0](...args); +} + +struct holder : invokable { + var call: def(*mut u8, Ts...): R; + var at: *mut u8; +} + +def holder::invoke(&mut this, args: Ts...): R { + return this.call(this.at, ...args); +} + +def holder::of(f: *mut F): holder where F: invokable { + return holder:: { call = thunk::, at = f as *mut u8 }; +} + +# The same over a signature given whole, whose parts it names `S::params` and +# `S::result`. +def over_thunk(at: *mut u8, args: S::params...): S::result where S: signature where F: invokable { + return (at as *mut F)[0](...args); +} + +struct over : invokable where S: signature { + var call: def(*mut u8, S::params...): S::result; + var at: *mut u8; +} + +def over::invoke(&mut this, args: S::params...): S::result { + return this.call(this.at, ...args); +} + +def over::of(f: *mut F): over where F: invokable { + return over:: { call = over_thunk::, at = f as *mut u8 }; +} + +def counted(args: Ts...): u64 { + return args.length; +} + +# A template's function named in its body is the type its instance makes. +def count_of(args: Ts...): u64 { + val f: def(Ts...): u64 = counted::; + return f(...args); +} + +struct add : invokable { var calls: i64; } + +def add::invoke(&mut this, a: i64, b: i64): i64 { + this.calls++; + return a + b; +} + +struct summer : invokable {} + +def summer::invoke(&mut this, xs: i64...): i64 { + var total: i64 = 0; + for x in xs { total += x; } + return total; +} + +def main(): void { + var a := add {}; + var s := summer {}; + var h := holder::::of(&mut a as *mut add); + var all := holder::::of(&mut s as *mut summer); + var o: over = over::of(&mut a as *mut add); + var each := vector::>::new(); + each.append(holder::of(&mut a as *mut add)); + println($"{h(1, 2)} {all(1, 2, 3, 4)} {all()} {o(30, 12)} {each[0](5, 6)}"); + println($"{a.calls} calls"); + println($"{count_of(1, true, 2.5)} {count_of()}"); +} diff --git a/tests/programs/functions_as_values_1.out b/tests/programs/functions_as_values_1.out new file mode 100644 index 00000000..f3e1575e --- /dev/null +++ b/tests/programs/functions_as_values_1.out @@ -0,0 +1 @@ +[2, 4, 6, 8] 10 [4, 9, 16, 25] def 3 1 10 10 40 144 2 7 diff --git a/tests/programs/functions_as_values_1.sakura b/tests/programs/functions_as_values_1.sakura new file mode 100644 index 00000000..4a162fb7 --- /dev/null +++ b/tests/programs/functions_as_values_1.sakura @@ -0,0 +1,60 @@ +import std::io; +type transform = def(int): int; +struct counter { var count: int; } +# A closure refers to the locals it uses, so what outlives the function making it +# is a functor: a struct holding what it uses, called through `invoke`. +struct bumper : invokable { var target: &mut counter; } +def bumper::invoke(&mut this): void { this.target.count++; } +def counter::incrementer(this: &mut counter): bumper { return bumper{ target = this }; } +def double(n: int): int { return n * 2; } +def map(values: int[4], f: F): int[4] where F: invokable { + var out: int[4]; + for i, v in values { out[i] = f(v); } + return out; +} +def fold(values: int[4], start: int, f: def(int, int): int): int { + var acc := start; + for v in values { acc = f(acc, v); } + return acc; +} +struct composed : invokable where F: invokable where G: invokable { + var first: F; + var then: G; +} +def composed::invoke(&mut this, x: int): int { + val first := &mut this.first; + val then := &mut this.then; + return then(first(x)); +} +def compose(f: F, g: G): composed where F: invokable where G: invokable { + return composed::{ first = f, then = g }; +} +struct adds : invokable { var n: int; } +def adds::invoke(&mut this, x: int): int { return x + this.n; } +def adder(n: int): adds { return adds{ n = n }; } +struct count_up : invokable { var count: int; } +def count_up::invoke(&mut this): int { this.count++; return this.count; } +def make_counter(): count_up { return count_up{}; } +struct scale : invokable { var by: int; } +def scale::invoke(&mut this, x: int): int { return x * this.by; } +val square := def(x: int): int { return x * x; }; +def main(): void { + val values := [1, 2, 3, 4]; + print($"{map(values, double)} {fold(values, 0, def(a: int, b: int): int { return a + b; })} "); + print($"{map(values, compose(adder(1), square))} {square} "); + var next := make_counter(); + var other := make_counter(); + next(); next(); + print($"{next()} {other()} "); + var total := 0; + val add := def(x: int): void { total += x; }; + for v in values { add(v); } + var fns: scale[4]; + for at, i in values { fns[at] = scale{ by = i }; } + var fib: transform = double; + fib = def(n: int): int { return n < 2 ? n : fib(n - 1) + fib(n - 2); }; + var c := counter{}; + var inc := c.incrementer(); + inc(); inc(); + println($"{total} {fns[0](10)} {fns[3](10)} {fib(12)} {c.count} {(def(): int { return 7; })()}"); +} diff --git a/tests/programs/functions_hold_any_callable_1.out b/tests/programs/functions_hold_any_callable_1.out new file mode 100644 index 00000000..0f166d23 --- /dev/null +++ b/tests/programs/functions_hold_any_callable_1.out @@ -0,0 +1,13 @@ +announced open +announced save +announced close +tally saw 3 weighing 8 +journal holds 3: log: close +the lambda heard 3, and the second holds a tally: false +hello, sakura +save! +OK handled: false +clicked +moved: false true +journal closed with 3 lines +done diff --git a/tests/programs/functions_hold_any_callable_1.sakura b/tests/programs/functions_hold_any_callable_1.sakura new file mode 100644 index 00000000..ca1244dd --- /dev/null +++ b/tests/programs/functions_hold_any_callable_1.sakura @@ -0,0 +1,99 @@ +import std::io; + +# A `function` holds one callable of a signature, whatever its type, and owns it: +# a named function, a lambda, a method taken through its type, a functor in its +# buffer, or a larger one in a box. A list of handlers mixes them, and a functor +# holding a `string` is kept past the function making it, as no lambda can be. + +struct event { var name: strview; var weight: i64; } + +struct tally : invokable { var seen: i64; var weighed: i64; } + +def tally::invoke(&mut this, e: &event): void { + this.seen++; + this.weighed += e.weight; +} + +# Larger than a function's buffer, so it is held in a box. +struct journal : invokable, owning { + var lines: vector; + var label: string; + var spare: u64[2]; +} + +def journal::invoke(&mut this, e: &event): void { + this.lines.append($"{this.label}: {e.name}"); +} + +# A journal moved from holds nothing, and says nothing as it closes. +def journal::close(&mut this): void { + if this.label.length != 0 { + println($"journal closed with {this.lines.length} lines"); + } + this.lines.close(); + this.label.close(); +} + +def announce(e: &event): void { + println($"announced {e.name}"); +} + +struct greeter : invokable { var greeting: string; } + +def greeter::invoke(&mut this, name: strview): string { + return $"{this.greeting}, {name}"; +} + +# The string lives in the functor the function owns, so it outlives `greeting_of`. +def greeting_of(word: strview): function { + return function::new(greeter { greeting = string::from(word, nothing {}) }); +} + +def event::loudly(&this): string { + return $"{this.name}!"; +} + +struct button { + var label: strview; + var on_click: function; +} + +def main(): void { + var heard := 0; + var handlers := vector::>::new(); + handlers.append(function::new(tally {})); + handlers.append(function::new(announce)); + handlers.append(function::new(def(e: &event) { heard++; })); + handlers.append(function::new(journal { label = string::from("log", nothing {}) })); + + val events: event[3] = [event { name = "open", weight = 2 }, event { name = "save", weight = 5 }, event { name = "close", weight = 1 }]; + for &e in events { + for &h in handlers { h(&e); } + } + if handlers[0].get::() is some(t) { + println($"tally saw {t.seen} weighing {t.weighed}"); + } + if handlers[3].get::() is some(&j) { + println($"journal holds {j.lines.length}: {j.lines[2]}"); + } + println($"the lambda heard {heard}, and the second holds a tally: {handlers[1].get::() is some(_)}"); + + val hello := greeting_of("hello"); + println(hello("sakura")); + + # A method taken through its type takes its receiver first. + val loud: function = function::new(event::loudly); + println(loud(&events[1])); + + # Unset until given, as a field needs no value where its struct is made. + var b := button { label = "OK" }; + println($"{b.label} handled: {b.on_click.holds()}"); + b.on_click = function::new(def() { println("clicked"); }); + if b.on_click.holds() { b.on_click(); } + + # Moved, it leaves the one moved from empty. + var moved := move(&mut handlers[3]); + println($"moved: {handlers[3].holds()} {moved.holds()}"); + moved.close(); + println("done"); +} diff --git a/tests/programs/generic_traits_1.out b/tests/programs/generic_traits_1.out new file mode 100644 index 00000000..bb77ce3b --- /dev/null +++ b/tests/programs/generic_traits_1.out @@ -0,0 +1,3 @@ +2m [2m, 2m] 2m +39 30 s [4, 4] [30, 30] +2 2 diff --git a/tests/programs/generic_traits_1.sakura b/tests/programs/generic_traits_1.sakura new file mode 100644 index 00000000..0ab088fd --- /dev/null +++ b/tests/programs/generic_traits_1.sakura @@ -0,0 +1,40 @@ +import std::io; +trait Into { + def into(&this): T; + def twice(&this): T[2] { return [this.into(), this.into()]; } +} +trait Map { def get(&this, key: K): V; } +struct counted { var it: &Into; } +struct meters: Into> { var v: f64; } +def meters::into(&this): span { return this.v < 3.0 ? "2m" : "far"; } +struct count { var n: int; } +def count::into(&this): int { return this.n * 10; } +struct box { var value: T; } +def box::into(&this): T { return this.value; } +struct table { var keys: span>; var values: span; } +def table::get(&this, key: span): int { + for i in 0..this.keys.length { if this.keys[i] == key { return this.values[i]; } } + return -1; +} +def show(x: &Into>): span { return x.into(); } +def total(xs: span): int { var t := 0; for x in xs { t += x.it.into(); } return t; } +def pick(x: &Into): T { return x.into(); } +def convert(x: &T): U where T: Into { return x.into(); } +def lookup(m: &Map, key: K): V { return m.get(key); } +def main(): void { + val m := meters{ 2 }; + println($"{show(m)} {m.twice()} {convert::>(m)}"); + val c := count{ 3 }; + val b := box{ 4 }; + val more := box{ 5 }; + var parts: counted[3] = [counted{ &c }, counted{ &b }, counted{ &more }]; + val held := span::::over((&parts) as *counted, 3); + val word := box::>{ "s" }; + println($"{total(held)} {pick(c)} {pick(word)} {parts[1].it.twice()} {parts[0].it.twice()}"); + val keys: span[2] = ["a", "b"]; + val values: int[2] = [1, 2]; + val t := table{ span::>::over((&keys) as *span, 2), + span::::over((&values) as *int, 2) }; + val key := "b"; + println($"{lookup(t, key)} {(&t as &Map, int>).get(key)}"); +} diff --git a/tests/programs/generics_1.out b/tests/programs/generics_1.out new file mode 100644 index 00000000..0c47fa80 --- /dev/null +++ b/tests/programs/generics_1.out @@ -0,0 +1 @@ +(1, 2)(1, 2) [(1, 2)] [(1, 2)][(1, 2)] 3 -1 pair, int>{first = one, second = 1} one [3, 6] 4 7 250 6 0.75 2 1.5 diff --git a/tests/programs/generics_1.sakura b/tests/programs/generics_1.sakura new file mode 100644 index 00000000..8b7b4055 --- /dev/null +++ b/tests/programs/generics_1.sakura @@ -0,0 +1,60 @@ +import std::io; +trait Show { def show(this: &Show): string; } +struct point: Show { var x: int; var y: int; } +def point::show(this: &point): string { return $"({this.x}, {this.y})"; } +struct box: Show where T: Show { var value: T; } +def box::show(this: &box): string { return $"[{this.value.show()}]"; } +def describe(item: &Show): string { return item.show(); } +def show_all(xs: span): string where T: Show { + var out := string::new(nothing {}); + for x in xs { out.append($"{x.show()}{describe(&x)} "); } + return out; +} +union res { var value: T; var failure: span; } +def res::ok(value: T): res { return res::{ value = value }; } +def res::or(this: &res, fallback: T): T { + match this { value(value) => return value; else => return fallback; } +} +struct pair { var first: A; var second: B; } +def pair::swap(this: &pair): pair { return pair::{ this.second, this.first }; } +def map(xs: span, out: *mut U, f: def(T): U): span { + for i in 0..xs.length { out[i] = f(xs[i]); } + return span::::over(out as *U, xs.length); +} +def fold(xs: span, start: A, f: def(A, T): A): A { + var acc := start; + for x in xs { acc = f(acc, x); } + return acc; +} +def max(a: T, b: T): T where T: ordered { return a > b ? a : b; } +def sum(xs: span): T where T: numeric { + var total: T = 0; + for x in xs { total += x; } + return total; +} +struct node { var value: T; var next: *node; } +def node::length(this: &node): int { return this.next == null ? 1 : 1 + (*this.next).length(); } +def main(): void { + val p := point{ 1, 2 }; + val b := box{ value = p }; + var ps: point[1] = [p]; + var bs: box[1] = [b]; + print($"{show_all(span::::over((&ps) as *point, 1))}{describe(&b)} {show_all(span::>::over((&bs) as *box, 1))}"); + val r := res::::ok(3); + val e := res::{ failure = "no" }; + print($"{r.or(0)} {e.or(-1)} "); + val q := pair::>{ first = 1, second = "one" }; + val nested: pair>, int> = pair{ q, 2 }; + print($"{q.swap()} {nested.first.second} "); + var ns: int[2] = [1, 2]; + var tripled: int[2]; + var fs: f64[2] = [1.5, 2.5]; + print($"{map(span::::over((&ns) as *int, 2), (&mut tripled) as *mut int, def(n) => n * 3)} {fold(span::::over((&fs) as *f64, 2), 0.0, def(a, x) => a + x)} "); + var threes: int[3] = [1, 2, 3]; + var halves: f64[2] = [0.5, 0.25]; + print($"{max(3, 7)} {max::(250, 9)} {sum(span::::over((&threes) as *int, 3))} {sum(span::::over((&halves) as *f64, 2))} "); + val last := node{ 3, null }; + val first := node{ 1, &last as *node }; + val biggest := max::; + println($"{first.length()} {biggest(0.5, 1.5)}"); +} diff --git a/tests/programs/generics_2.out b/tests/programs/generics_2.out new file mode 100644 index 00000000..ab65b2e7 --- /dev/null +++ b/tests/programs/generics_2.out @@ -0,0 +1,6 @@ +3 + +--- exit 1 +sakura: runtime error: Division by zero. + at divide (tests/programs/generics_2.sakura:2:58) + at main (tests/programs/generics_2.sakura:5:26) diff --git a/tests/programs/generics_2.sakura b/tests/programs/generics_2.sakura new file mode 100644 index 00000000..05b27867 --- /dev/null +++ b/tests/programs/generics_2.sakura @@ -0,0 +1,6 @@ +import std::io; +def divide(a: T, b: T): T where T: integer { return a / b; } +def main(): void { + println($"{divide(7, 2)}"); + println($"{divide::(1, 0)}"); +} diff --git a/tests/programs/globals_1.out b/tests/programs/globals_1.out new file mode 100644 index 00000000..cb56848c --- /dev/null +++ b/tests/programs/globals_1.out @@ -0,0 +1 @@ +21 42 2 config{name = default, level = 4} config{name = default, level = 42} 200 404 diff --git a/tests/programs/globals_1.sakura b/tests/programs/globals_1.sakura new file mode 100644 index 00000000..3d1df3f1 --- /dev/null +++ b/tests/programs/globals_1.sakura @@ -0,0 +1,18 @@ +import std::io; +val early := base() + 1; +val later := early * 2; +var counter: int; +struct config { var name: span = "default"; var level := 3; } +var settings: config; +val config::fallback := config{ level = later }; +type code = u16; +val code::ok := 200; +val code::missing := 404; +def base(): int { return 20; } +def tick(): int { counter += 1; return counter; } +def main(): void { + tick(); + tick(); + settings.level++; + println($"{early} {later} {counter} {settings} {config::fallback} {code::ok} {code::missing}"); +} diff --git a/tests/programs/if_const_calls_through_type_parameters_1.out b/tests/programs/if_const_calls_through_type_parameters_1.out new file mode 100644 index 00000000..a865757b --- /dev/null +++ b/tests/programs/if_const_calls_through_type_parameters_1.out @@ -0,0 +1,2 @@ +64 bits, wide +8 bits, narrow diff --git a/tests/programs/if_const_calls_through_type_parameters_1.sakura b/tests/programs/if_const_calls_through_type_parameters_1.sakura new file mode 100644 index 00000000..2ce5efb6 --- /dev/null +++ b/tests/programs/if_const_calls_through_type_parameters_1.sakura @@ -0,0 +1,24 @@ +import std::io; + +# `if const` in a generic calls what each instance gives: a static method +# through a bound, and a generic function given the instance's type, which only +# the instance knows, so the generic's own body asks nothing of them. +trait sized_bits { def bits(): u64; } +def u64::bits(): u64 { return 64; } +def u8::bits(): u64 { return 8; } +def wide(): bool where T: sized_bits { return T::bits() > 16; } + +def describe(): void where T: sized_bits { + if const T::bits() > 32 && wide::() { + println($"{T::bits()} bits, wide"); + } else if const wide::() { + println($"{T::bits()} bits"); + } else { + println($"{T::bits()} bits, narrow"); + } +} + +def main(): void { + describe::(); + describe::(); +} diff --git a/tests/programs/if_const_compares_what_reflection_describes_1.out b/tests/programs/if_const_compares_what_reflection_describes_1.out new file mode 100644 index 00000000..84883419 --- /dev/null +++ b/tests/programs/if_const_compares_what_reflection_describes_1.out @@ -0,0 +1,4 @@ +spinner spins +spinner.speed +spinner.angle +walker walks diff --git a/tests/programs/if_const_compares_what_reflection_describes_1.sakura b/tests/programs/if_const_compares_what_reflection_describes_1.sakura new file mode 100644 index 00000000..607800bc --- /dev/null +++ b/tests/programs/if_const_compares_what_reflection_describes_1.sakura @@ -0,0 +1,27 @@ +import std::io; + +# The condition of an `if const` within a pass of `for const` reads the +# description the pass is of, as its name, even where only evaluating decides +# it, and within a pass of a pass. +struct mark : attribute {} +@mark struct spinner { var speed: f32; var angle: f32; } +@mark struct walker { var pace: f32; } + +def main(): void { + for const d in declarations() { + if const attached::(d).length == 0 { continue; } + if const d.name == "spinner" { + println($"{d.name} spins"); + } else { + println($"{d.name} walks"); + } + if const d.name == "nothing_named_so" { + compile_error("No declaration is named so."); + } + for const m in members_of(d) { + if const m.name.length > 4 && d.name != "walker" { + println($"{d.name}.{m.name}"); + } + } + } +} diff --git a/tests/programs/if_const_names_the_type_a_parameter_is_1.out b/tests/programs/if_const_names_the_type_a_parameter_is_1.out new file mode 100644 index 00000000..3202815a --- /dev/null +++ b/tests/programs/if_const_names_the_type_a_parameter_is_1.out @@ -0,0 +1,4 @@ +a view of 5 bytes +an i64, doubled 42 +something else +2 b 0 diff --git a/tests/programs/if_const_names_the_type_a_parameter_is_1.sakura b/tests/programs/if_const_names_the_type_a_parameter_is_1.sakura new file mode 100644 index 00000000..2909d661 --- /dev/null +++ b/tests/programs/if_const_names_the_type_a_parameter_is_1.sakura @@ -0,0 +1,35 @@ +import std::io; + +# Where `if const` says a type parameter is a type, the branch takes the +# parameter as that type: each instance taking it is checked with the +# parameter that type, and the branch names it by the parameter's name. + +def describe(x: T): string { + if const T is strview { + val text: strview = x; + return $"a view of {text.length} bytes"; + } else if const T is i64 { + val doubled: T = x * 2; + return $"an i64, doubled {doubled}"; + } + return "something else"; +} + +def words(values: span): vector { + if const T is strview { + var out := vector::::new(); + for &v in values { out.append(v); } + return out; + } + return vector::new(); +} + +def main(): void { + println(describe("hello")); + println(describe(21)); + println(describe(true)); + val given: strview[2] = ["a", "b"]; + val kept := words::(given[:]); + val none := words::(given[:]); + println($"{kept.length} {kept[1]} {none.length}"); +} diff --git a/tests/programs/indexes_read_through_references_1.out b/tests/programs/indexes_read_through_references_1.out new file mode 100644 index 00000000..28d1c35b --- /dev/null +++ b/tests/programs/indexes_read_through_references_1.out @@ -0,0 +1 @@ +160 7 7 2 2 diff --git a/tests/programs/indexes_read_through_references_1.sakura b/tests/programs/indexes_read_through_references_1.sakura new file mode 100644 index 00000000..edbf3210 --- /dev/null +++ b/tests/programs/indexes_read_through_references_1.sakura @@ -0,0 +1,32 @@ +import std::io; + +# An index may be a reference to a number, as `for &i in order` binds, which is +# read through as it is wherever a number is wanted. +def main(): void { + var held: u64[4] = [10, 20, 30, 40]; + var order := vector::::new(); + order.append(3); + order.append(0); + order.append(2); + + val view := held[0:4]; + var total: u64 = 0; + for &i in order { + total += held[i] + view[i]; + } + + var numbers := vector::::new(); + numbers.append(1); + numbers.append(2); + numbers.append(3); + val writes := numbers.slice(); + val at: &u64 = &order[1]; + writes[at] = 7; + + val data := numbers.view().data; + val first: &u64 = &order[1]; + val count: u64 = 2; + val two := &count; + val part := data[first:two]; + println($"{total} {numbers[0]} {data[first]} {part.length} {part[1]}"); +} diff --git a/tests/programs/indexing_gives_the_reference_at_gives_1.out b/tests/programs/indexing_gives_the_reference_at_gives_1.out new file mode 100644 index 00000000..65885681 --- /dev/null +++ b/tests/programs/indexing_gives_the_reference_at_gives_1.out @@ -0,0 +1,6 @@ +10 20 +5 6 +5 7 +xy xy +11 10 12 +2 9 diff --git a/tests/programs/indexing_gives_the_reference_at_gives_1.sakura b/tests/programs/indexing_gives_the_reference_at_gives_1.sakura new file mode 100644 index 00000000..432d9651 --- /dev/null +++ b/tests/programs/indexing_gives_the_reference_at_gives_1.sakura @@ -0,0 +1,56 @@ +import std::io; +import std::containers; + +struct pair { var a: i64; var b: i64; } + +# `v[i]` is `v.at(i)`, so a function giving a reference gives the element itself. +def first(v: &vector): &pair { return v[0]; } +def first_mut(v: &mut vector): &mut pair { return &mut v[0]; } + +def main(): void { + # `&` or `&mut` written binds the reference `at` gives, as with `at`. + var numbers := vector::::new(); + numbers.append(1); + numbers.append(2); + var by_at := &mut numbers.at(0); + by_at = 10; + var by_index := &mut numbers[1]; + by_index = 20; + println($"{numbers[0]} {numbers[1]}"); + + var pairs := vector::::new(); + pairs.append(pair { a = 1, b = 2 }); + val p := &mut pairs[0]; + p.a = 5; + first_mut(&mut pairs).b = 6; + println($"{pairs[0].a} {first(&pairs).b}"); + + # Bound without `&`, an element is copied, and changes on its own after. + val copy := pairs[0]; + pairs[0].a = 7; + println($"{copy.a} {pairs[0].a}"); + + # An element that owns what it holds is referred to, never copied. + var names := vector::::new(); + names.append(string::from("x", nothing {})); + val name := &mut names[0]; + name.append("y"); + println($"{name} {names[0]}"); + + # A dictionary's value, and a view's element, are references too. + var counts := dict::::new(nothing {}); + counts.set(1, 10); + var count := &mut counts[1]; + count = 11; + val view := numbers.view(); + val seen := view[0]; + val lent := &view[0]; + numbers[0] = 12; + println($"{counts[1]} {seen} {lent}"); + + # A fixed array is indexed by the language, and its element is copied too. + val held: u64[3] = [1, 2, 3]; + var element := held[1]; + element = 9; + println($"{held[1]} {element}"); +} diff --git a/tests/programs/inline_functions_run_as_called_1.out b/tests/programs/inline_functions_run_as_called_1.out new file mode 100644 index 00000000..b1761e6b --- /dev/null +++ b/tests/programs/inline_functions_run_as_called_1.out @@ -0,0 +1,6 @@ +9 12 9 42 2.5 4 5 +2 +--- exit 1 +sakura: runtime error: Program aborted. + at within (tests/programs/inline_functions_run_as_called_1.sakura:17:26) + at main (tests/programs/inline_functions_run_as_called_1.sakura:27:18) diff --git a/tests/programs/inline_functions_run_as_called_1.sakura b/tests/programs/inline_functions_run_as_called_1.sakura new file mode 100644 index 00000000..a1fc1e8a --- /dev/null +++ b/tests/programs/inline_functions_run_as_called_1.sakura @@ -0,0 +1,28 @@ +import std::io; +import system; + +# `@inline` functions, methods, and properties are copied where they are +# called, and give what a call would: called through a trait reference or a +# function value, or calling themselves, they are called. A fault within a copy +# names the function, then where it was called. +trait shape { def area(&this): i64; } +struct square : shape { var side: i64; } +@inline def square::area(&this): i64 { return this.side * this.side; } +@inline val square::perimeter: i64 { get => 4 * this.side; } + +@inline def twice(x: T): T where T: numeric { return x + x; } +@inline def halve(x: i64): i64 { val half := x / 2; return half; } +@inline def depth(n: u64): u64 { return n == 0 ? 0 : depth(n - 1) + 1; } +@inline def within(at: u64, length: u64): u64 { + if at >= length { abort(); } + return at; +} + +def main(): void { + val s := square { side = 3 }; + val r: &shape = &s; + val f: def(i64): i64 = halve; + println($"{s.area()} {s.perimeter} {r.area()} {twice(21)} {twice(1.25)} {f(9)} {depth(5)}"); + print($"{within(2, 3)} "); + print($"{within(7, 3)} "); +} diff --git a/tests/programs/inlined_calls_behave_like_calls_1.out b/tests/programs/inlined_calls_behave_like_calls_1.out new file mode 100644 index 00000000..83e0a5b3 --- /dev/null +++ b/tests/programs/inlined_calls_behave_like_calls_1.out @@ -0,0 +1,3 @@ +5 +7 14 1 107 +70 3 diff --git a/tests/programs/inlined_calls_behave_like_calls_1.sakura b/tests/programs/inlined_calls_behave_like_calls_1.sakura new file mode 100644 index 00000000..b4c312ec --- /dev/null +++ b/tests/programs/inlined_calls_behave_like_calls_1.sakura @@ -0,0 +1,22 @@ +import std::io; +var total: i64 = 0; +struct counter { var n: i64; } +var counter::value: i64 { + get => this.n; + set => this.n = value; +} +val counter::doubled: i64 { get => this.value * 2; } +val counter::sign: i64 { get => this.n < 0 ? -1 : 1; } +val counter::seen: i64 { get => total + this.n; } +def bump(c: &mut counter): i64 { c.n = c.n + 1; return c.n; } +def add(a: i64, b: i64): i64 { return a + b; } +def tenfold(c: &mut counter): void { c.n = c.n * 10; } +def main(): void { + var c := counter{ n = 1 }; + println($"{add(bump(&mut c), bump(&mut c))}"); + c.value = 7; + total = 100; + println($"{c.value} {c.doubled} {c.sign} {c.seen}"); + tenfold(&mut c); + println($"{c.value} {add(1, 2)}"); +} diff --git a/tests/programs/integers_1.out b/tests/programs/integers_1.out new file mode 100644 index 00000000..f460e31f --- /dev/null +++ b/tests/programs/integers_1.out @@ -0,0 +1,6 @@ +-128 255 -32768 65533 +-3 -1 -4 -56 6 7 8 -7 -4 +1333333333 3 3 3705032704 8000000000 +18446744073709551615 1 9223372036854775807 9223372036854775808 +-9223372036854775808 0 9223372036854775807 +true true true true false false diff --git a/tests/programs/integers_1.sakura b/tests/programs/integers_1.sakura new file mode 100644 index 00000000..274f8a53 --- /dev/null +++ b/tests/programs/integers_1.sakura @@ -0,0 +1,23 @@ +import std::io; +def main(): void { + var a: i8 = 127; + a++; + var b: u8 = 0; + b--; + var c: i16 = 32767; + c += 1; + var d: u16 = 65535; + d = d * 3; + println($"{a} {b} {c} {d}"); + val x := -7; + val y := 2; + println($"{x / y} {x % y} {x >> 1} {x << 3} {~x} {-x} {x & 12} {x | 1} {x ^ 5}"); + val u: u32 = 4000000000; + println($"{u / 3} {u % 7} {u >> 30} {u + u} {widen(u) + widen(u)}"); + val big: u64 = 18446744073709551615; + println($"{big} {big + 2} {big / 2} {1 << 63}"); + val min: int = -9223372036854775807 - 1; + println($"{min / -1} {min % -1} {min - 1}"); + println($"{x < y} {u > 5} {big >= 0} {x == -7} {x != -7} {!(x < y)}"); +} +def widen(value: u32): uint { return value; } diff --git a/tests/programs/invokable_values_1.out b/tests/programs/invokable_values_1.out new file mode 100644 index 00000000..4df8a392 --- /dev/null +++ b/tests/programs/invokable_values_1.out @@ -0,0 +1,6 @@ +3 30 calls 2 +12 42 +written read written +#item#7 +6 0 +81 441 hits 3 diff --git a/tests/programs/invokable_values_1.sakura b/tests/programs/invokable_values_1.sakura new file mode 100644 index 00000000..2cdd0d65 --- /dev/null +++ b/tests/programs/invokable_values_1.sakura @@ -0,0 +1,50 @@ +import std::io; + +struct adder : invokable { var calls: i64; } +def adder::invoke(&mut this, a: i64, b: i64): i64 { this.calls++; return a + b; } + +# A stateless functor takes `&this`, which meets the trait's `&mut this`. +struct doubler : invokable {} +def doubler::invoke(&this, x: i64): i64 { return x * 2; } + +# Both `&this` and `&mut this`: what can be written calls the second. +struct both : invokable {} +def both::invoke(&this): strview { return "read"; } +def both::invoke(&mut this): strview { return "written"; } + +# Wider arguments and results, through a trait reference. +struct labeler : invokable { var prefix: strview; } +def labeler::invoke(&mut this, name: strview, n: i64): string { return $"{this.prefix}{name}#{n}"; } + +# A variadic signature, through a trait reference. +struct summer : invokable {} +def summer::invoke(&mut this, xs: i64...): i64 { var t: i64 = 0; for x in xs { t += x; } return t; } + +# A functor over any signature, which calls the function it holds. +struct wrapped : invokable where F: signature { var call: F; var hits: i64; } +def wrapped::invoke(&mut this, args: F::params...): F::result { this.hits++; return this.call(...args); } + +def twice(f: &mut F, x: i64): i64 where F: invokable { return f.invoke(f.invoke(x)); } +def run(f: &mut invokable): i64 { return f.invoke(10, 20); } +def run1(f: &mut invokable): i64 { return f.invoke(21); } +def say(f: &mut invokable): strview { return f.invoke(); } +def label(f: &mut invokable): string { return f.invoke("item", 7); } +def total(f: &mut invokable): i64 { return f.invoke(1, 2, 3); } + +def square(x: i64): i64 { return x * x; } + +def main(): void { + var a := adder{}; + println($"{a.invoke(1, 2)} {run(a)} calls {a.calls}"); + var d := doubler{}; + println($"{twice(&mut d, 3)} {run1(d)}"); + var b := both{}; + val r := both{}; + println($"{b.invoke()} {r.invoke()} {say(b)}"); + var l := labeler{ prefix = "#" }; + println(label(l)); + var s := summer{}; + println($"{total(s)} {s.invoke()}"); + var w := wrapped::{ call = square, hits = 0 }; + println($"{twice(&mut w, 3)} {run1(w)} hits {w.hits}"); +} diff --git a/tests/programs/is_tests_what_a_type_satisfies_1.out b/tests/programs/is_tests_what_a_type_satisfies_1.out new file mode 100644 index 00000000..da9cbd55 --- /dev/null +++ b/tests/programs/is_tests_what_a_type_satisfies_1.out @@ -0,0 +1 @@ +true false false true true false true false true loud ? true false false [hi] not a number diff --git a/tests/programs/is_tests_what_a_type_satisfies_1.sakura b/tests/programs/is_tests_what_a_type_satisfies_1.sakura new file mode 100644 index 00000000..9e5f40bb --- /dev/null +++ b/tests/programs/is_tests_what_a_type_satisfies_1.sakura @@ -0,0 +1,21 @@ +import std::io; +trait Shown { def show(&this): span; } +struct loud { var n: i64; } +def loud::show(&this): span { return "loud"; } +struct quiet { var n: i64; } +union held { var none: i8; var number: i64; var text: span; } +def tell(x: &T): span { + return "?" if const x is not Shown; + return x.show(); +} +def main(): void { + print($"{loud{1} is Shown} {quiet{1} is Shown} "); + print($"{loud{1} is not Shown} {quiet{1} is not Shown} "); + print($"{1 is integer} {1.5 is integer} {1 is ordered} {quiet{1} is equatable} {1 is hashable} "); + print($"{tell(&loud{2})} {tell(&quiet{2})} "); + var u: held = 5; + print($"{u is number} {u is not number} {u is text} "); + u = "hi"; + if u is text(t) { print($"[{t}] "); } + if u is not number { print("not a number\n"); } +} diff --git a/tests/programs/iterator_adapters_1.out b/tests/programs/iterator_adapters_1.out new file mode 100644 index 00000000..77c08241 --- /dev/null +++ b/tests/programs/iterator_adapters_1.out @@ -0,0 +1 @@ +160 [1, 4, 9, 16] 3-5-7 0:1 1:2 2:3 3 1=one 2=two 3=three 1,2,7,8 64 40320 true false 4 5 8 4 7 8 7 001012 [0, 1, 5, 6] [2, 4, 6, 8] 4 diff --git a/tests/programs/iterator_adapters_1.sakura b/tests/programs/iterator_adapters_1.sakura new file mode 100644 index 00000000..c6436bff --- /dev/null +++ b/tests/programs/iterator_adapters_1.sakura @@ -0,0 +1,44 @@ +import std::io; + +# A functor is anything `invokable`, so an adapter is compiled for it and calls +# it directly. +struct odd : invokable {} +def odd::invoke(&this, x: &i64): bool { return x % 2 != 0; } +struct scaled : invokable { val by: i64; } +def scaled::invoke(&this, x: i64): i64 { return x * this.by; } + +def main(): void { + val v := vector::::from(1..=8); + val dash: strview = "-"; + val comma: strview = ","; + val none: strview = ""; + print($"{v.iter().copied().filter(odd {}).map(scaled { by = 10 }).sum()} "); + # A lambda given for a bound takes its parameters' types from it. + val squares := v.iter().map(def(x) => x * x).take(4).to_vector(); + print($"{squares.view()} "); + print($"{v.iter().skip(2).step(2).to_string(dash)} "); + for p in v.iter().take_while(def(x) => x < 4).enumerate() { print($"{p.first}:{p.second} "); } + print($"{v.iter().skip_while(def(x) => x < 6).count()} "); + val words: span = ["one", "two", "three"]; + for p in v.iter().zip(words.iter()) { print($"{p.first}={p.second} "); } + print($"{(1..3).chain(7..9).to_string(comma)} "); + print($"{v.iter().copied().fold(100, def(a, x) => a - x)} "); + print($"{v.iter().copied().reduce(def(a, b) => a * b) else 0} "); + print($"{v.iter().any(def(x) => x > 7)} {v.iter().all(def(x) => x > 1)} "); + print($"{v.iter().position(def(x) => x == 5) else 99} {v.iter().find(def(x) => x > 4) else &v[0]} "); + print($"{v.iter().copied().max() else 0} {v.iter().copied().min_by_key(def(x) => (x - 4) * (x - 4)) else 0} "); + print($"{v.iter().rev().nth(1) else &v[0]} {v.iter().last() else &v[0]} "); + var peeking := v.iter().peekable(); + var runs: u64 = 0; + while peeking.next() is some(x) { + if peeking.peek() is some(next) { if next > x { runs++; } } + } + print($"{runs} "); + print($"{(1..=3).flat_map(def(n) => 0..n).to_string(none)} "); + var kept := vector::::from(0..2); + (5..7).into(&mut kept); + print($"{kept.view()} "); + var seen: i64 = 0; + val evens := v.iter().copied().filter(def(x) => x % 2 == 0).inspect(def(x) { seen += 1; }).to_vector(); + println($"{evens.view()} {seen}"); +} diff --git a/tests/programs/jumps_take_a_condition_1.out b/tests/programs/jumps_take_a_condition_1.out new file mode 100644 index 00000000..075ff5c6 --- /dev/null +++ b/tests/programs/jumps_take_a_condition_1.out @@ -0,0 +1,3 @@ +low zero high 1357 +fell +d2 ? diff --git a/tests/programs/jumps_take_a_condition_1.sakura b/tests/programs/jumps_take_a_condition_1.sakura new file mode 100644 index 00000000..3de518cb --- /dev/null +++ b/tests/programs/jumps_take_a_condition_1.sakura @@ -0,0 +1,31 @@ +import std::io; +def sign(n: int): string { + return "low" if n < 0; + return "zero" if n == 0; + return "high"; +} +def odds(limit: int): string { + var out := string::new(nothing {}); + var i := 0; + while true { + i++; + continue if i % 2 == 0; + break if i > limit; + out.append($"{i}"); + } + return out; +} +def quiet(n: int): void { return if n > 0; print("fell "); } +trait shows { def show(this: &shows): string; } +struct wrap { var v: T; } +def wrap::show_it(this: &wrap): string { + return "?" if const T is not shows; + return this.v.show(); +} +struct dot: shows { var n: int; } +def dot::show(this: &dot): string { return $"d{this.n}"; } +def main(): void { + println($"{sign(-1)} {sign(0)} {sign(1)} {odds(7)}"); + quiet(1); quiet(-1); println(""); + println($"{wrap{ v = dot{ n = 2 } }.show_it()} {wrap{ v = 2 }.show_it()}"); +} diff --git a/tests/programs/lambdas_give_type_parameters_their_types_1.out b/tests/programs/lambdas_give_type_parameters_their_types_1.out new file mode 100644 index 00000000..481653f4 --- /dev/null +++ b/tests/programs/lambdas_give_type_parameters_their_types_1.out @@ -0,0 +1,4 @@ +one &int +two &mut int &bool +filtered 3 &bool +u8 diff --git a/tests/programs/lambdas_give_type_parameters_their_types_1.sakura b/tests/programs/lambdas_give_type_parameters_their_types_1.sakura new file mode 100644 index 00000000..1b70bafe --- /dev/null +++ b/tests/programs/lambdas_give_type_parameters_their_types_1.sakura @@ -0,0 +1,13 @@ +import std::io; +struct world { var n: int; } +def world::each(&mut this, f: F): void where F: invokable { println($"one {name_of::()}"); } +def world::each(&mut this, f: F): void where F: invokable { println($"two {name_of::()} {name_of::()}"); } +def world::each(&mut this, n: int, f: F): void where F: invokable { println($"filtered {n} {name_of::()}"); } +def kind_tested(test: def(&T): bool): strview { return name_of::(); } +def main(): void { + var w := world{}; + w.each(def(p: &int) {}); + w.each(def(p: &mut int, q: &bool) {}); + w.each(3, def(p: &bool) {}); + println(kind_tested(def(x: &u8) => x > 3)); +} diff --git a/tests/programs/literals_of_text_are_walked_1.out b/tests/programs/literals_of_text_are_walked_1.out new file mode 100644 index 00000000..30e6e38a --- /dev/null +++ b/tests/programs/literals_of_text_are_walked_1.out @@ -0,0 +1 @@ +294 3 diff --git a/tests/programs/literals_of_text_are_walked_1.sakura b/tests/programs/literals_of_text_are_walked_1.sakura new file mode 100644 index 00000000..f7851c94 --- /dev/null +++ b/tests/programs/literals_of_text_are_walked_1.sakura @@ -0,0 +1,10 @@ +import std::io; +def main(): void { + var sum := 0u; + for c in "abc" { sum += c as u64; } + var vowels := 0; + for c in "sakura" { + if c == 'a' || c == 'u' { vowels++; } + } + println($"{sum} {vowels}"); +} diff --git a/tests/programs/local_functions_1.out b/tests/programs/local_functions_1.out new file mode 100644 index 00000000..0ffd3ec8 --- /dev/null +++ b/tests/programs/local_functions_1.out @@ -0,0 +1,2 @@ +610 1973 +0 11 21 5 8 3 diff --git a/tests/programs/local_functions_1.sakura b/tests/programs/local_functions_1.sakura new file mode 100644 index 00000000..59a66192 --- /dev/null +++ b/tests/programs/local_functions_1.sakura @@ -0,0 +1,25 @@ +import std::io; +def twice(x: T): T where T: numeric { + def add(a: T): T { return a + x; } + return add(x); +} +def main(): void { + var calls := 0; + def fib(n: int): int { + calls++; + return n < 2 ? n : fib(n - 1) + fib(n - 2); + } + println($"{fib(15)} {calls}"); + # A local function refers to the locals it uses, so one using `i` is called + # while `i` is in scope. + var made: int[3]; + for i in 0..3 { + def scaled(x: int): int { return x * i + fib(i); } + made[i] = scaled(10); + } + def outer(n: int): int { + def inner(m: int): int { return m <= 0 ? 0 : 1 + outer(m - 1); } + return inner(n); + } + println($"{made[0]} {made[1]} {made[2]} {outer(5)} {twice(4)} {twice(1.5)}"); +} diff --git a/tests/programs/logic_short_circuits_1.out b/tests/programs/logic_short_circuits_1.out new file mode 100644 index 00000000..1d166258 --- /dev/null +++ b/tests/programs/logic_short_circuits_1.out @@ -0,0 +1 @@ +ac?ef true 1 2 diff --git a/tests/programs/logic_short_circuits_1.sakura b/tests/programs/logic_short_circuits_1.sakura new file mode 100644 index 00000000..2817438b --- /dev/null +++ b/tests/programs/logic_short_circuits_1.sakura @@ -0,0 +1,8 @@ +import std::io; +def say(text: span, value: bool): bool { print(text); return value; } +def main(): void { + if say("a", false) && say("b", true) { print("!"); } + if say("c", true) || say("d", true) { print("?"); } + val both := say("e", true) && say("f", true); + println($" {both} {true ? 1 : 2} {false ? 1.5 : 2}"); +} diff --git a/tests/programs/loops_walk_iterators_1.out b/tests/programs/loops_walk_iterators_1.out new file mode 100644 index 00000000..caebb10b --- /dev/null +++ b/tests/programs/loops_walk_iterators_1.out @@ -0,0 +1,2 @@ +1 2 3 0:10 1:20 2:30 sum 60 5 4 closed at 2 rest 1 closed at 2 first 3 10 +closed at 0 \ No newline at end of file diff --git a/tests/programs/loops_walk_iterators_1.sakura b/tests/programs/loops_walk_iterators_1.sakura new file mode 100644 index 00000000..11cc0a62 --- /dev/null +++ b/tests/programs/loops_walk_iterators_1.sakura @@ -0,0 +1,32 @@ +import std::io; +struct bag { var items: i64[4]; var count: u64; } +struct bag::reader : iterator<&i64> { val of: *i64; var at: u64; val count: u64; } +def bag::reader::next(&mut this): maybe<&i64> { if this.at >= this.count { return nothing {}; } this.at++; return &this.of[this.at - 1]; } +struct bag::writer : iterator<&mut i64> { val of: *mut i64; var at: u64; val count: u64; } +def bag::writer::next(&mut this): maybe<&mut i64> { if this.at >= this.count { return nothing {}; } this.at++; return &mut this.of[this.at - 1]; } +type bag::cursor = bag::reader; +type bag::mut_cursor = bag::writer; +def bag::iter(&this): bag::reader { return bag::reader{ of = (&this.items) as *i64, at = 0, count = this.count }; } +def bag::iter(&mut this): bag::writer { return bag::writer{ of = (&mut this.items) as *mut i64, at = 0, count = this.count }; } +struct countdown : iterator, owning { var n: i64; } +def countdown::next(&mut this): maybe { if this.n == 0 { return nothing {}; } this.n--; return this.n + 1; } +def countdown::close(&mut this): void { print($"closed at {this.n} "); } +struct upto : iterator { var n: i64; val to: i64; } +def upto::next(&mut this): maybe { if this.n >= this.to { return nothing {}; } this.n++; return this.n; } +const def total(to: i64): i64 { var t: i64 = 0; for x in (upto{ n = 0, to = to }) { t += x; } return t; } +const TEN := total(4); +def sum(c: &C): i64 where C: iterable { var t: i64 = 0; for x in c { t += x; } return t; } +def first_under(limit: i64): i64 { for n in (countdown{ n = 6 }) { if n < limit { return n; } } return -1; } +def main(): void { + var b := bag{ items = [1, 2, 3, 4], count = 3 }; + for x in b { print($"{x} "); } + for &mut x in b { x *= 10; } + for i, &x in b { print($"{i}:{x} "); } + print($"sum {sum(&b)} "); + for n in (countdown{ n = 5 }) { if n == 3 { break; } print($"{n} "); } + var it := countdown{ n = 4 }; + for n in it { if n == 2 { break; } } + for n in it { print($"rest {n} "); } + print($"first {first_under(4)} "); + println($"{TEN}"); +} diff --git a/tests/programs/matches_of_many_constants_go_straight_to_their_case_1.out b/tests/programs/matches_of_many_constants_go_straight_to_their_case_1.out new file mode 100644 index 00000000..b9e967f0 --- /dev/null +++ b/tests/programs/matches_of_many_constants_go_straight_to_their_case_1.out @@ -0,0 +1,4 @@ +0,10,4294967294 0,10,4294967295 9,10,4294967296 5,10,4294967297 0,10,4294967298 2,10,-1 21,10,4 7,4,5 4,10,6 5,10,3 -7,24,8 0,10,9 0,10,10 0,6,11 0,10,6 0,10,13 0,10,14 +437 1 -1 7 3 +black grey white red green blue cyan other other +1 2 3 4 5 diff --git a/tests/programs/matches_of_many_constants_go_straight_to_their_case_1.sakura b/tests/programs/matches_of_many_constants_go_straight_to_their_case_1.sakura new file mode 100644 index 00000000..1ed4b429 --- /dev/null +++ b/tests/programs/matches_of_many_constants_go_straight_to_their_case_1.sakura @@ -0,0 +1,45 @@ +import std::io; +enum shade : u8 { black, grey, white, red, green, blue, cyan, magenta, yellow } +def name(s: shade): strview { + return match s { + shade::black => "black", shade::grey => "grey", shade::white => "white", shade::red => "red", + shade::green => "green", shade::blue => "blue", shade::cyan => "cyan", else => "other" + }; +} +def dense(n: i64, a: i64, b: i64): i64 { + return match n { + -3 => a + b, -2 => a - b, 0 => b, 1 => a * 3, 2 => a, 3 => b * b, 4 => a ^ b, 5 => -a, else => 0 + }; +} +def sparse(n: i64, a: i64, b: i64): i64 { + return match n { + 2 => a, 8 => b, 31 => a + 1, 32 => b + 1, 5 => a * b, 33 => a - b, 1000 => b - a, 40 => 7, else => a + b + }; +} +def chained(n: u32, a: i64): i64 { + if n == 4 { return a; } + if n == 9 { return a * 2; } + if n == 4 { return 99; } + if n == 16 { return a * 4; } + if n == 25 { return a * 5; } + if n == 0 { return -1; } + return a + n as i64; +} +def huge(n: u64): i64 { + return match n { + 0xFFFFFFFFFFFFFFFF => 1, 0x8000000000000000 => 2, 0x7FFFFFFFFFFFFFFF => 3, 0 => 4, else => 5 + }; +} +def main(): void { + var total: i64 = 0; + for i in -5..12 { + total += dense(i as i64, i as i64 + 2, 10) + sparse(i as i64, i as i64 * 5, 3); + print($"{dense(i as i64, 7, 2)},{sparse(i as i64, 4, 6)},{chained(i as u32, 3)} "); + } + println($"\n{total} {sparse(1000, 1, 2)} {sparse(33, 1, 2)} {sparse(40, 1, 2)} {sparse(-1, 1, 2)}"); + for k in 0..9u { + print(name(k as u8 as shade)); + print(" "); + } + println($"\n{huge(0xFFFFFFFFFFFFFFFF)} {huge(0x8000000000000000)} {huge(0x7FFFFFFFFFFFFFFF)} {huge(0)} {huge(3)}"); +} diff --git a/tests/programs/math_functions_agree_everywhere_1.out b/tests/programs/math_functions_agree_everywhere_1.out new file mode 100644 index 00000000..50232ba7 --- /dev/null +++ b/tests/programs/math_functions_agree_everywhere_1.out @@ -0,0 +1,53 @@ +sqrt 0.7071067811865476 nan 1 nan 1.4142135623730951 nan 0.8366600265340756 3.1622776601683795 nan 10 26.636441203734407 0.0001 nan 2.2227587494850775e-162 100000 100000000000 nan 1.2533141373155001 1.7724538509055159 0 -0 inf nan nan | 0.70710677 nan 1 nan 1.4142135 nan 0.83666 3.1622777 nan 10 26.63644 0.0001 -0 0 100000 99999997952 nan 1.2533141 1.7724539 0 -0 inf nan nan +cbrt 0.7937005259840998 -0.7937005259840998 1 -1 1.2599210498948732 -1.4422495703074083 0.8879040017426006 2.154434690031884 -2.8231080866430855 4.641588833612779 8.919026752722989 0.002154434690031884 -1e-100 1.7031839360032603e-108 2154.4346900318837 21544346.90031884 -1e+100 1.1624473515096265 1.4645918875615231 0 -0 inf -inf nan | 0.7937005 -0.7937005 1 -1 1.2599211 -1.4422495 0.887904 2.1544347 -2.8231082 4.6415887 8.919026 0.0021544348 -0 0 2154.4346 21544346 -inf 1.1624473 1.4645919 0 -0 inf -inf nan +exp 1.6487212707001282 0.6065306597126334 2.718281828459045 0.36787944117144233 7.38905609893065 0.049787068367863944 2.0137527074704766 22026.465794806718 1.6918979226151304e-10 2.6881171418161356e+43 1.3549863193146328e+308 1.00000001 1 1 inf inf 0 4.810477380965351 23.140692632779267 1 1 inf 0 nan | 1.6487212 0.60653067 2.7182817 0.36787945 7.389056 0.049787067 2.0137527 22026.465 1.6918979e-10 inf inf 1 1 1 inf inf 0 4.8104777 23.140696 1 1 inf 0 nan +exp2 1.4142135623730951 0.7071067811865476 2 0.5 4 0.125 1.624504792712471 1024 1.6858739404357614e-07 1.2676506002282294e+30 3.808745232330413e+213 1.0000000069314718 1 1 inf inf 0 2.9706864235520194 8.824977827076287 1 1 inf 0 nan | 1.4142135 0.70710677 2 0.5 4 0.125 1.6245048 1024 1.6858739e-07 1.2676506e+30 inf 1 1 1 inf inf 0 2.9706864 8.824979 1 1 inf 0 nan +expm1 0.6487212707001282 -0.3934693402873666 1.718281828459045 -0.6321205588285577 6.38905609893065 -0.950212931632136 1.0137527074704764 22025.465794806718 -0.9999999998308102 2.6881171418161356e+43 1.3549863193146328e+308 1.0000000050000001e-08 -1e-300 5e-324 inf inf -1 3.8104773809653514 22.140692632779267 0 -0 inf -1 nan | 0.6487213 -0.39346933 1.7182819 -0.63212055 6.389056 -0.95021296 1.0137527 22025.465 -1 inf inf 1e-08 -0 0 inf inf -1 3.8104775 22.140696 0 -0 inf -1 nan +log -0.6931471805599453 nan 0 nan 0.6931471805599453 nan -0.35667494393873245 2.302585092994046 nan 4.605170185988092 6.564560496600097 -18.420680743952367 nan -744.4400719213812 23.025850929940457 50.65687204586901 nan 0.4515827052894548 1.1447298858494002 -inf -inf inf nan nan | -0.6931472 nan 0 nan 0.6931472 nan -0.35667497 2.3025851 nan 4.6051702 6.5645604 -18.420681 -inf -inf 23.02585 50.65687 nan 0.45158273 1.14473 -inf -inf inf nan nan +log2 -1 nan 0 nan 1 nan -0.5145731728297583 3.321928094887362 nan 6.643856189774724 9.470658874060552 -26.575424759098897 nan -1074 33.219280948873624 73.08241808752197 nan 0.6514961294723187 1.6514961294723187 -inf -inf inf nan nan | -1 nan 0 nan 1 nan -0.5145732 3.321928 nan 6.643856 9.470659 -26.575424 -inf -inf 33.21928 73.08242 nan 0.6514962 1.6514962 -inf -inf inf nan nan +log10 -0.3010299956639812 nan 0 nan 0.3010299956639812 nan -0.1549019599857432 1 nan 2 2.850952399793493 -8 nan -323.3062153431158 10 22 nan 0.19611987703015263 0.49714987269413385 -inf -inf inf nan nan | -0.30103 nan 0 nan 0.30103 nan -0.15490197 1 nan 2 2.8509524 -8 -inf -inf 10 22 nan 0.19611989 0.49714988 -inf -inf inf nan nan +log1p 0.4054651081081644 -0.6931471805599453 0.6931471805599453 -inf 1.0986122886681096 nan 0.5306282510621704 2.3978952727983707 nan 4.61512051684126 6.565968947537155 9.999999950000001e-09 -1e-300 5e-324 23.025850930040455 50.65687204586901 nan 0.9442157056960554 1.4210804127942926 0 -0 inf nan nan | 0.4054651 -0.6931472 0.6931472 -inf 1.0986123 nan 0.53062826 2.3978953 nan 4.6151204 6.565969 1e-08 -0 0 23.02585 50.65687 nan 0.9442157 1.4210805 0 -0 inf nan nan +sin 0.479425538604203 -0.479425538604203 0.8414709848078965 -0.8414709848078965 0.9092974268256817 -0.1411200080598672 0.644217687237691 -0.5440211108893698 0.4871745124605095 -0.5063656411097588 -0.4793726294152408 1e-08 -1e-300 5e-324 -0.4875060250875107 -0.8522008497671888 0.8178819121159085 1 1.2246467991473532e-16 0 -0 nan nan nan | 0.47942555 -0.47942555 0.84147096 -0.84147096 0.9092974 -0.14112 0.64421767 -0.5440211 0.4871745 -0.50636566 -0.47937262 1e-08 -0 0 -0.48750603 -0.7340815 nan 1 -8.742278e-08 0 -0 nan nan nan +cos 0.8775825618903728 0.8775825618903728 0.5403023058681398 0.5403023058681398 -0.4161468365471424 -0.9899924966004454 0.7648421872844885 -0.8390715290764524 -0.8733046400935156 0.8623188722876839 0.8776114642411631 1 1 1 0.873119622676856 0.523214785395139 -0.5753861119575491 6.123233995736766e-17 -1 1 1 nan nan nan | 0.87758255 0.87758255 0.5403023 0.5403023 -0.41614684 -0.9899925 0.7648422 -0.8390715 -0.87330467 0.8623189 0.87761146 1 1 1 0.87311965 0.67906135 nan -4.371139e-08 -1 1 1 nan nan nan +tan 0.5463024898437905 -0.5463024898437905 1.5574077246549023 -1.5574077246549023 -2.185039863261519 0.1425465430742778 0.8422883804630794 0.6483608274590866 -0.5578517393521941 -0.5872139151569291 -0.5462242107670459 1e-08 -1e-300 5e-324 -0.5583496378112418 -1.628778225606899 -1.4214488238747245 1.633123935319537e+16 -1.2246467991473532e-16 0 -0 nan nan nan | 0.5463025 -0.5463025 1.5574077 -1.5574077 -2.1850398 0.14254655 0.8422884 0.64836085 -0.55785173 -0.58721393 -0.54622424 1e-08 -0 0 -0.5583496 -1.0810239 nan -22877332 8.742278e-08 0 -0 nan nan nan +asin 0.5235987755982989 -0.5235987755982989 1.5707963267948966 -1.5707963267948966 nan nan 0.775397496610753 nan nan nan nan 1e-08 -1e-300 5e-324 nan nan nan nan nan 0 -0 nan nan nan | 0.5235988 -0.5235988 1.5707964 -1.5707964 nan nan 0.7753975 nan nan nan nan 1e-08 -0 0 nan nan nan nan nan 0 -0 nan nan nan +acos 1.0471975511965979 2.0943951023931957 0 3.141592653589793 nan nan 0.7953988301841436 nan nan nan nan 1.5707963167948966 1.5707963267948966 1.5707963267948966 nan nan nan nan nan 1.5707963267948966 1.5707963267948966 nan nan nan | 1.0471976 2.0943952 0 3.1415927 nan nan 0.79539883 nan nan nan nan 1.5707964 1.5707964 1.5707964 nan nan nan nan nan 1.5707964 1.5707964 nan nan nan +atan 0.4636476090008061 -0.4636476090008061 0.7853981633974483 -0.7853981633974483 1.1071487177940904 -1.2490457723982544 0.6107259643892086 1.4711276743037347 -1.5263811115479857 1.5607966601082315 1.5693868844582877 1e-08 -1e-300 5e-324 1.5707963266948965 1.5707963267948966 -1.5707963267948966 1.0038848218538872 1.2626272556789115 0 -0 1.5707963267948966 -1.5707963267948966 nan | 0.4636476 -0.4636476 0.7853982 -0.7853982 1.1071488 -1.2490457 0.61072594 1.4711276 -1.5263811 1.5607966 1.5693868 1e-08 -0 0 1.5707964 1.5707964 -1.5707964 1.0038848 1.2626272 0 -0 1.5707964 -1.5707964 nan +sinh 0.5210953054937474 -0.5210953054937474 1.1752011936438014 -1.1752011936438014 3.626860407847019 -10.017874927409903 0.7585837018395334 11013.232874703393 -2955261031.5116453 1.3440585709080678e+43 6.774931596573164e+307 1e-08 -1e-300 5e-324 inf inf -inf 2.3012989023072947 11.548739357257748 0 -0 inf -inf nan | 0.5210953 -0.5210953 1.1752012 -1.1752012 3.6268604 -10.017875 0.75858366 11013.232 -2955260928 inf inf 1e-08 -0 0 inf inf -inf 2.301299 11.54874 0 -0 inf -inf nan +cosh 1.1276259652063807 1.1276259652063807 1.5430806348152437 1.5430806348152437 3.7621956910836314 10.067661995777765 1.255169005630943 11013.232920103324 2955261031.5116453 1.3440585709080678e+43 6.774931596573164e+307 1 1 1 inf inf inf 2.5091784786580567 11.591953275521519 1 1 inf inf nan | 1.127626 1.127626 1.5430807 1.5430807 3.7621956 10.067662 1.255169 11013.233 2955260928 inf inf 1 1 1 inf inf inf 2.5091786 11.591954 1 1 inf inf nan +tanh 0.46211715726000974 -0.46211715726000974 0.7615941559557649 -0.7615941559557649 0.9640275800758169 -0.9950547536867305 0.6043677771171634 0.9999999958776927 -1 1 1 1e-08 -1e-300 5e-324 1 1 -1 0.9171523356672744 0.99627207622075 0 -0 1 -1 nan | 0.46211717 -0.46211717 0.7615942 -0.7615942 0.9640276 -0.9950548 0.6043678 1 -1 1 1 1e-08 -0 0 1 1 -1 0.91715235 0.9962721 0 -0 1 -1 nan +asinh 0.48121182505960347 -0.48121182505960347 0.881373587019543 -0.881373587019543 1.4436354751788103 -1.8184464592320668 0.6526665660823557 2.99822295029797 -3.8071559515338214 5.298342365610589 7.257708173792255 1e-08 -1e-300 5e-324 23.7189981105004 51.350019226428955 -691.4686750787736 1.233403117511217 1.8622957433108482 0 -0 inf -inf nan | 0.4812118 -0.4812118 0.8813736 -0.8813736 1.4436355 -1.8184465 0.65266657 2.998223 -3.8071558 5.298342 7.257708 1e-08 -0 0 23.718998 51.350018 -inf 1.2334031 1.8622957 0 -0 inf -inf nan +acosh nan nan 0 nan 1.3169578969248166 nan nan 2.993222846126381 nan 5.298292365610484 7.25770718052709 nan nan nan 23.7189981105004 51.350019226428955 nan 1.0232274785475506 1.811526272460853 nan nan inf nan nan | nan nan 0 nan 1.316958 nan nan 2.993223 nan 5.298292 7.257707 nan nan nan 23.718998 51.350018 nan 1.0232276 1.8115263 nan nan inf nan nan +atanh 0.5493061443340548 -0.5493061443340548 inf -inf nan nan 0.8673005276940531 nan nan nan nan 1.0000000000000002e-08 -1e-300 5e-324 nan nan nan nan nan 0 -0 nan nan nan | 0.54930615 -0.54930615 inf -inf nan nan 0.8673005 nan nan nan nan 1e-08 -0 0 nan nan nan nan nan 0 -0 nan nan nan +floor 0 -1 1 -1 2 -3 0 10 -23 100 709 0 -1 0 10000000000 1e+22 -1e+300 1 3 0 -0 inf -inf nan | 0 -1 1 -1 2 -3 0 10 -23 100 709 0 -0 0 10000000000 1e+22 -inf 1 3 0 -0 inf -inf nan +ceil 1 -0 1 -1 2 -3 1 10 -22 100 710 1 -0 1 10000000000 1e+22 -1e+300 2 4 0 -0 inf -inf nan | 1 -0 1 -1 2 -3 1 10 -22 100 710 1 -0 0 10000000000 1e+22 -inf 2 4 0 -0 inf -inf nan +trunc 0 -0 1 -1 2 -3 0 10 -22 100 709 0 -0 0 10000000000 1e+22 -1e+300 1 3 0 -0 inf -inf nan | 0 -0 1 -1 2 -3 0 10 -22 100 709 0 -0 0 10000000000 1e+22 -inf 1 3 0 -0 inf -inf nan +round 1 -1 1 -1 2 -3 1 10 -23 100 710 0 -0 0 10000000000 1e+22 -1e+300 2 3 0 -0 inf -inf nan | 1 -1 1 -1 2 -3 1 10 -23 100 710 0 -0 0 10000000000 1e+22 -inf 2 3 0 -0 inf -inf nan +round_even 0 -0 1 -1 2 -3 1 10 -22 100 710 0 -0 0 10000000000 1e+22 -1e+300 2 3 0 -0 inf -inf nan | 0 -0 1 -1 2 -3 1 10 -22 100 710 0 -0 0 10000000000 1e+22 -inf 2 3 0 -0 inf -inf nan +abs 0.5 0.5 1 1 2 3 0.7 10 22.5 100 709.5 1e-08 1e-300 5e-324 10000000000 1e+22 1e+300 1.5707963267948966 3.141592653589793 0 0 inf inf nan | 0.5 0.5 1 1 2 3 0.7 10 22.5 100 709.5 1e-08 0 0 10000000000 1e+22 inf 1.5707964 3.1415927 0 0 inf inf nan +pow 1.4142135623730951 -512 1e-300 5e-324 -inf 1 nan 81 nan 1 0 0.36288736930121157 | 1.4142135 -512 0 0 -inf 1 nan 81 1 1 0 0.36288738 +atan2 1.3258176636680326 -1.2120256565243244 3.108271657711546 0.00046554931459711864 -3.141592653589793 nan -1.3258176636680326 0.6435011087932844 -1.5707963267948966 3.141592653589793 2.356194490192345 2.601173153319209 | 1.3258177 -1.2120256 3.1082716 0.00046554932 -3.1415927 nan -1.3258177 0.6435011 -1.5707964 3.1415927 2.3561945 2.6011732 +hypot 2.0615528128088303 8.54400374531753 300.1666203960727 1074.0001163873308 3 nan 2.0615528128088303 5 1e+300 0 inf 2.9154759474226504 | 2.0615528 8.5440035 300.16663 1074.0001 3 nan 2.0615528 5 inf 0 inf 2.9154758 +copysign 2 8 -10 0.5 -0 -1 2 3 1e+300 -0 -inf -1.5 | 2 8 -10 0.5 -0 -1 2 3 inf -0 -inf -1.5 +min 0.5 -8 -300 0.5 -3 nan -2 3 -1e+300 -0 -inf -2.5 | 0.5 -8 -300 0.5 -3 nan -2 3 -inf -0 -inf -2.5 +max 2 3 10 1074 -0 nan 0.5 4 1e-300 0 inf 1.5 | 2 3 10 1074 -0 nan 0.5 4 0 0 inf 1.5 +sin(0.5) 0.479425538604203 true +cos(0.5) 0.8775825618903728 true +tan(0.5) 0.5463024898437905 true +exp(0.5) 1.6487212707001282 true +log(0.5) -0.6931471805599453 true +pow(0.5, 0.3) 0.8122523963562356 true +atan2(0.5, -2.0) 2.896613990462929 true +cbrt(0.5) 0.7937005259840998 true +sinh(0.5) 0.5210953054937474 true +acosh(1.5) 0.9624236501192069 true +log1p(0.5) 0.4054651081081644 true +expm1(0.5) 0.6487212707001282 true +hypot(0.5, 3.0) 3.0413812651491097 true +sin(1e300) -0.8178819121159085 true +fma(0.1, 10.0, -1.0) 5.551115123125783e-17 true +floor(-0.5) -1 true +asin(0.5) 0.5235987755982989 true +log10(0.5) -0.3010299956639812 true +exp2(0.5) 1.4142135623730951 true +tanh(0.5) 0.46211715726000974 true diff --git a/tests/programs/math_functions_agree_everywhere_1.sakura b/tests/programs/math_functions_agree_everywhere_1.sakura new file mode 100644 index 00000000..4206a2fe --- /dev/null +++ b/tests/programs/math_functions_agree_everywhere_1.sakura @@ -0,0 +1,204 @@ +import std::io; +import std::math; + +# Every function of std::math gives the same bits wherever it runs: in either +# compiler's machine, in an executable, and in a constant worked out while +# compiling. Each line is a function of the same inputs, as doubles, then as +# floats, printed as the shortest text that reads back as the same value. + +const compiled: f64[20] = [math::sin(0.5), math::cos(0.5), math::tan(0.5), math::exp(0.5), math::log(0.5), math::pow(0.5, 0.3), math::atan2(0.5, -2.0), math::cbrt(0.5), math::sinh(0.5), math::acosh(1.5), math::log1p(0.5), math::expm1(0.5), math::hypot(0.5, 3.0), math::sin(1e300), math::fma(0.1, 10.0, -1.0), math::floor(-0.5), math::asin(0.5), math::log10(0.5), math::exp2(0.5), math::tanh(0.5)]; + +def main(): void { + val zero: f64 = 0; + val doubles: f64[24] = [0.5, -0.5, 1.0, -1.0, 2.0, -3.0, 0.7, 10.0, -22.5, 100.0, 709.5, 1e-8, -1e-300, 5e-324, 1e10, 1e22, -1e300, 1.5707963267948966, 3.141592653589793, 0.0, -0.0, 1.0 / zero, -1.0 / zero, zero / zero]; + var floats: f32[24]; + for i in 0u..24u { floats[i] = doubles[i] as f32; } + val firsts: f64[12] = [2.0, -8.0, 10.0, 0.5, -0.0, 1.0, -2.0, 3.0, -1e300, 0.0, 1.0 / zero, 1.5]; + val seconds: f64[12] = [0.5, 3.0, -300.0, 1074.0, -3.0, zero / zero, 0.5, 4.0, 1e-300, -0.0, -1.0 / zero, -2.5]; + print("sqrt"); + for i in 0u..24u { print($" {math::sqrt(doubles[i])}"); } + print(" |"); + for i in 0u..24u { print($" {math::sqrt(floats[i])}"); } + println(""); + print("cbrt"); + for i in 0u..24u { print($" {math::cbrt(doubles[i])}"); } + print(" |"); + for i in 0u..24u { print($" {math::cbrt(floats[i])}"); } + println(""); + print("exp"); + for i in 0u..24u { print($" {math::exp(doubles[i])}"); } + print(" |"); + for i in 0u..24u { print($" {math::exp(floats[i])}"); } + println(""); + print("exp2"); + for i in 0u..24u { print($" {math::exp2(doubles[i])}"); } + print(" |"); + for i in 0u..24u { print($" {math::exp2(floats[i])}"); } + println(""); + print("expm1"); + for i in 0u..24u { print($" {math::expm1(doubles[i])}"); } + print(" |"); + for i in 0u..24u { print($" {math::expm1(floats[i])}"); } + println(""); + print("log"); + for i in 0u..24u { print($" {math::log(doubles[i])}"); } + print(" |"); + for i in 0u..24u { print($" {math::log(floats[i])}"); } + println(""); + print("log2"); + for i in 0u..24u { print($" {math::log2(doubles[i])}"); } + print(" |"); + for i in 0u..24u { print($" {math::log2(floats[i])}"); } + println(""); + print("log10"); + for i in 0u..24u { print($" {math::log10(doubles[i])}"); } + print(" |"); + for i in 0u..24u { print($" {math::log10(floats[i])}"); } + println(""); + print("log1p"); + for i in 0u..24u { print($" {math::log1p(doubles[i])}"); } + print(" |"); + for i in 0u..24u { print($" {math::log1p(floats[i])}"); } + println(""); + print("sin"); + for i in 0u..24u { print($" {math::sin(doubles[i])}"); } + print(" |"); + for i in 0u..24u { print($" {math::sin(floats[i])}"); } + println(""); + print("cos"); + for i in 0u..24u { print($" {math::cos(doubles[i])}"); } + print(" |"); + for i in 0u..24u { print($" {math::cos(floats[i])}"); } + println(""); + print("tan"); + for i in 0u..24u { print($" {math::tan(doubles[i])}"); } + print(" |"); + for i in 0u..24u { print($" {math::tan(floats[i])}"); } + println(""); + print("asin"); + for i in 0u..24u { print($" {math::asin(doubles[i])}"); } + print(" |"); + for i in 0u..24u { print($" {math::asin(floats[i])}"); } + println(""); + print("acos"); + for i in 0u..24u { print($" {math::acos(doubles[i])}"); } + print(" |"); + for i in 0u..24u { print($" {math::acos(floats[i])}"); } + println(""); + print("atan"); + for i in 0u..24u { print($" {math::atan(doubles[i])}"); } + print(" |"); + for i in 0u..24u { print($" {math::atan(floats[i])}"); } + println(""); + print("sinh"); + for i in 0u..24u { print($" {math::sinh(doubles[i])}"); } + print(" |"); + for i in 0u..24u { print($" {math::sinh(floats[i])}"); } + println(""); + print("cosh"); + for i in 0u..24u { print($" {math::cosh(doubles[i])}"); } + print(" |"); + for i in 0u..24u { print($" {math::cosh(floats[i])}"); } + println(""); + print("tanh"); + for i in 0u..24u { print($" {math::tanh(doubles[i])}"); } + print(" |"); + for i in 0u..24u { print($" {math::tanh(floats[i])}"); } + println(""); + print("asinh"); + for i in 0u..24u { print($" {math::asinh(doubles[i])}"); } + print(" |"); + for i in 0u..24u { print($" {math::asinh(floats[i])}"); } + println(""); + print("acosh"); + for i in 0u..24u { print($" {math::acosh(doubles[i])}"); } + print(" |"); + for i in 0u..24u { print($" {math::acosh(floats[i])}"); } + println(""); + print("atanh"); + for i in 0u..24u { print($" {math::atanh(doubles[i])}"); } + print(" |"); + for i in 0u..24u { print($" {math::atanh(floats[i])}"); } + println(""); + print("floor"); + for i in 0u..24u { print($" {math::floor(doubles[i])}"); } + print(" |"); + for i in 0u..24u { print($" {math::floor(floats[i])}"); } + println(""); + print("ceil"); + for i in 0u..24u { print($" {math::ceil(doubles[i])}"); } + print(" |"); + for i in 0u..24u { print($" {math::ceil(floats[i])}"); } + println(""); + print("trunc"); + for i in 0u..24u { print($" {math::trunc(doubles[i])}"); } + print(" |"); + for i in 0u..24u { print($" {math::trunc(floats[i])}"); } + println(""); + print("round"); + for i in 0u..24u { print($" {math::round(doubles[i])}"); } + print(" |"); + for i in 0u..24u { print($" {math::round(floats[i])}"); } + println(""); + print("round_even"); + for i in 0u..24u { print($" {math::round_even(doubles[i])}"); } + print(" |"); + for i in 0u..24u { print($" {math::round_even(floats[i])}"); } + println(""); + print("abs"); + for i in 0u..24u { print($" {math::abs(doubles[i])}"); } + print(" |"); + for i in 0u..24u { print($" {math::abs(floats[i])}"); } + println(""); + print("pow"); + for i in 0u..12u { print($" {math::pow(firsts[i], seconds[i])}"); } + print(" |"); + for i in 0u..12u { print($" {math::pow(firsts[i] as f32, seconds[i] as f32)}"); } + println(""); + print("atan2"); + for i in 0u..12u { print($" {math::atan2(firsts[i], seconds[i])}"); } + print(" |"); + for i in 0u..12u { print($" {math::atan2(firsts[i] as f32, seconds[i] as f32)}"); } + println(""); + print("hypot"); + for i in 0u..12u { print($" {math::hypot(firsts[i], seconds[i])}"); } + print(" |"); + for i in 0u..12u { print($" {math::hypot(firsts[i] as f32, seconds[i] as f32)}"); } + println(""); + print("copysign"); + for i in 0u..12u { print($" {math::copysign(firsts[i], seconds[i])}"); } + print(" |"); + for i in 0u..12u { print($" {math::copysign(firsts[i] as f32, seconds[i] as f32)}"); } + println(""); + print("min"); + for i in 0u..12u { print($" {math::min(firsts[i], seconds[i])}"); } + print(" |"); + for i in 0u..12u { print($" {math::min(firsts[i] as f32, seconds[i] as f32)}"); } + println(""); + print("max"); + for i in 0u..12u { print($" {math::max(firsts[i], seconds[i])}"); } + print(" |"); + for i in 0u..12u { print($" {math::max(firsts[i] as f32, seconds[i] as f32)}"); } + println(""); + val one: f64 = 1.0; + println($"sin(0.5) {compiled[0]} {compiled[0] == math::sin(0.5 * one)}"); + println($"cos(0.5) {compiled[1]} {compiled[1] == math::cos(0.5 * one)}"); + println($"tan(0.5) {compiled[2]} {compiled[2] == math::tan(0.5 * one)}"); + println($"exp(0.5) {compiled[3]} {compiled[3] == math::exp(0.5 * one)}"); + println($"log(0.5) {compiled[4]} {compiled[4] == math::log(0.5 * one)}"); + println($"pow(0.5, 0.3) {compiled[5]} {compiled[5] == math::pow(0.5 * one, 0.3 * one)}"); + println($"atan2(0.5, -2.0) {compiled[6]} {compiled[6] == math::atan2(0.5 * one, -2.0 * one)}"); + println($"cbrt(0.5) {compiled[7]} {compiled[7] == math::cbrt(0.5 * one)}"); + println($"sinh(0.5) {compiled[8]} {compiled[8] == math::sinh(0.5 * one)}"); + println($"acosh(1.5) {compiled[9]} {compiled[9] == math::acosh(1.5 * one)}"); + println($"log1p(0.5) {compiled[10]} {compiled[10] == math::log1p(0.5 * one)}"); + println($"expm1(0.5) {compiled[11]} {compiled[11] == math::expm1(0.5 * one)}"); + println($"hypot(0.5, 3.0) {compiled[12]} {compiled[12] == math::hypot(0.5 * one, 3.0 * one)}"); + println($"sin(1e300) {compiled[13]} {compiled[13] == math::sin(1e300 * one)}"); + println($"fma(0.1, 10.0, -1.0) {compiled[14]} {compiled[14] == math::fma(0.1 * one, 10.0 * one, -1.0 * one)}"); + println($"floor(-0.5) {compiled[15]} {compiled[15] == math::floor(-0.5 * one)}"); + println($"asin(0.5) {compiled[16]} {compiled[16] == math::asin(0.5 * one)}"); + println($"log10(0.5) {compiled[17]} {compiled[17] == math::log10(0.5 * one)}"); + println($"exp2(0.5) {compiled[18]} {compiled[18] == math::exp2(0.5 * one)}"); + println($"tanh(0.5) {compiled[19]} {compiled[19] == math::tanh(0.5 * one)}"); +} diff --git a/tests/programs/maybe_references_are_one_word_1.out b/tests/programs/maybe_references_are_one_word_1.out new file mode 100644 index 00000000..94eac168 --- /dev/null +++ b/tests/programs/maybe_references_are_one_word_1.out @@ -0,0 +1 @@ +true true true true found 4 false 1 5 cat false 12 none diff --git a/tests/programs/maybe_references_are_one_word_1.sakura b/tests/programs/maybe_references_are_one_word_1.sakura new file mode 100644 index 00000000..c38ec40b --- /dev/null +++ b/tests/programs/maybe_references_are_one_word_1.sakura @@ -0,0 +1,39 @@ +import std::io; + +# A `maybe` of a reference, a trait reference, or a function value is no larger +# than what it holds: a null one is `none`. +trait named { def name(&this): strview; } +struct cat : named { var lives: u8; } +def cat::name(&this): strview { return "cat"; } + +struct link { var value: u64; var next: maybe<&link>; } + +def find(items: span, wanted: u64): maybe<&u64> { + for &x in items { return &x if x == wanted; } + return nothing {}; +} + +def main(): void { + print($"{size_of::>() == size_of::<&u64>()} "); + print($"{size_of::>() == size_of::<&named>()} "); + print($"{size_of::>() == size_of::()} "); + print($"{size_of::>() > size_of::()} "); + val items: span = [3, 1, 4]; + if find(items, 4) is some(r) { print($"found {r} "); } + print($"{find(items, 9) is some(_)} {find(items, 1) else &items[0]} "); + val third := link { value = 3, next = nothing {} }; + val second := link { value = 2, next = &third }; + var at: maybe<&link> = link { value = 1, next = &second }.next; + var sum: u64 = 0; + while at is some(l) { sum += l.value; at = l.next; } + print($"{sum} "); + val c := cat { lives = 9 }; + var pet: maybe<&named> = &c; + if pet is some(p) { print($"{p.name()} "); } + pet = nothing {}; + print($"{pet is some(_)} "); + var f: maybe = def(v: u64): u64 => v * 3; + if f is some(g) { print($"{g(4)} "); } + f = nothing {}; + match f { none => println("none"); some(g) => println($"{g(1)}"); } +} diff --git a/tests/programs/methods_on_built_in_types_1.out b/tests/programs/methods_on_built_in_types_1.out new file mode 100644 index 00000000..66beefc2 --- /dev/null +++ b/tests/programs/methods_on_built_in_types_1.out @@ -0,0 +1,2 @@ +true false 42 63 false 1.5 10 +200 52 42 63 diff --git a/tests/programs/methods_on_built_in_types_1.sakura b/tests/programs/methods_on_built_in_types_1.sakura new file mode 100644 index 00000000..581285b2 --- /dev/null +++ b/tests/programs/methods_on_built_in_types_1.sakura @@ -0,0 +1,22 @@ +import std::io; +type byte = u8; +val u8::limit: u8 = 200; +def u8::is_decimal(this: &u8): bool { return this >= '0' && this <= '9'; } +def u8::from_digit(digit: u8): u8 { return '0' + digit; } +def int::double(this: &i64): int { return this * 2; } +def i64::triple(this: &int): i64 { return this.double() + this; } +def bool::flip(this: &bool): bool { return !this; } +def f32::half(this: &f32): f32 { return this / 2f; } +def u32::bump(this: &mut u32): void { this += 1; } +def main(): void { + val c: u8 = '7'; + val b: byte = 'x'; + val n := 21; + val yes := true; + val f := 3f; + var r: u32 = 9; + r.bump(); + val show := i64::triple; + println($"{c.is_decimal()} {b.is_decimal()} {n.double()} {show(n)} {yes.flip()} {f.half()} {r}"); + println($"{u8::limit} {u8::from_digit(4)} {int::double(&n)} {i64::triple(&n)}"); +} diff --git a/tests/programs/methods_on_numbers_stand_beside_the_compilers_1.out b/tests/programs/methods_on_numbers_stand_beside_the_compilers_1.out new file mode 100644 index 00000000..a506f1a9 --- /dev/null +++ b/tests/programs/methods_on_numbers_stand_beside_the_compilers_1.out @@ -0,0 +1,3 @@ +3 4 3 4.5 5 +5 5 10 4.5 4 6 +true true true diff --git a/tests/programs/methods_on_numbers_stand_beside_the_compilers_1.sakura b/tests/programs/methods_on_numbers_stand_beside_the_compilers_1.sakura new file mode 100644 index 00000000..3e04c44b --- /dev/null +++ b/tests/programs/methods_on_numbers_stand_beside_the_compilers_1.sakura @@ -0,0 +1,19 @@ +import std::io; +# A method a program declares on a number is beside those the compiler gives +# it, so a number on the left of an operator asks its own type for the method, +# and stays the number it was. +struct vec2 { var x: f64; var y: f64; } +def vec2::mul(&this, by: &f64): vec2 { return vec2 { x = this.x * by, y = this.y * by }; } +def f64::mul(&this, v: &vec2): vec2 { return v * this; } +def i64::add(&this, v: &vec2): vec2 { return vec2 { x = v.x + this as f64, y = v.y + this as f64 }; } +def f64::half(&this): f64 { return this / 2.0; } +def twice(x: T): T where T: numeric { return x.mul(&x).add(&x) - x * x; } +def main(): void { + val v := vec2 { x = 1.5, y = 2.0 }; + val a := 2.0 * v; + val b := v * 2.0; + val c := 3 + v; + println($"{a.x} {a.y} {b.x} {c.x} {c.y}"); + println($"{2.5.mul(&2.0)} {2.5 * 2.0} {7.add(&3)} {9.0.half()} {twice(4.0)} {twice(6)}"); + println($"{2.5 is numeric} {7 is numeric} {2.5 is multipliable}"); +} diff --git a/tests/programs/methods_shadow_the_types_aliased_1.out b/tests/programs/methods_shadow_the_types_aliased_1.out new file mode 100644 index 00000000..dedcadc4 --- /dev/null +++ b/tests/programs/methods_shadow_the_types_aliased_1.out @@ -0,0 +1 @@ +2.5 m 2.5 false true abc diff --git a/tests/programs/methods_shadow_the_types_aliased_1.sakura b/tests/programs/methods_shadow_the_types_aliased_1.sakura new file mode 100644 index 00000000..60abc742 --- /dev/null +++ b/tests/programs/methods_shadow_the_types_aliased_1.sakura @@ -0,0 +1,11 @@ +import std::io; +type name = span; +type meters = f64; +def f64::show(&this): string { return $"{this}"; } +def meters::show(&this): string { return $"{this} m"; } +def name::holds(&this, c: u8): bool { return false; } +def main(): void { + val d: meters = 2.5; + val n: name = "abc"; + println($"{d.show()} {(d as f64).show()} {n.holds('a')} {(n as span).length == 3} {n}"); +} diff --git a/tests/programs/module_exports_1.out b/tests/programs/module_exports_1.out new file mode 100644 index 00000000..dcf2a2b1 --- /dev/null +++ b/tests/programs/module_exports_1.out @@ -0,0 +1 @@ +4 inner 7 diff --git a/tests/programs/module_exports_1.sakura b/tests/programs/module_exports_1.sakura new file mode 100644 index 00000000..908063b1 --- /dev/null +++ b/tests/programs/module_exports_1.sakura @@ -0,0 +1,18 @@ +import std::io; +import lib; +import lib::inner; +def main(): void { + var c := start(); + c.bump(); + println($"{c.n} {label()} {total()}"); +} +module lib; +pub struct counter { pub var n: int; } +def step(): int { return 2; } +pub def counter::bump(&mut this): void { this.n = this.n + step(); } +pub def total(): int { return step() + deeper::extra(); } +module lib::inner; +pub def start(): counter { return counter{ n = step() }; } +pub def label(): string { return "inner"; } +module lib::deeper; +pub def extra(): int { return 5; } diff --git a/tests/programs/modules_see_nothing_of_the_program_1.out b/tests/programs/modules_see_nothing_of_the_program_1.out new file mode 100644 index 00000000..a57b07e9 --- /dev/null +++ b/tests/programs/modules_see_nothing_of_the_program_1.out @@ -0,0 +1 @@ +2 5 diff --git a/tests/programs/modules_see_nothing_of_the_program_1.sakura b/tests/programs/modules_see_nothing_of_the_program_1.sakura new file mode 100644 index 00000000..57efd931 --- /dev/null +++ b/tests/programs/modules_see_nothing_of_the_program_1.sakura @@ -0,0 +1,12 @@ +import std::io; +import tools; +import user; +struct scratch { var at: int; } +def main(): void { + val s := scratch { at = 2 }; + println($"{s.at} {count()}"); +} +module tools; +pub def scratch(): int { return 1; } +module user; +pub def count(): int { return scratch() + 4; } diff --git a/tests/programs/named_functions_are_called_as_the_type_asks_1.out b/tests/programs/named_functions_are_called_as_the_type_asks_1.out new file mode 100644 index 00000000..c2cc5ab5 --- /dev/null +++ b/tests/programs/named_functions_are_called_as_the_type_asks_1.out @@ -0,0 +1,6 @@ +8 12 +12 1 40 +3 +26 7 8 3 +5 60 +2 one three diff --git a/tests/programs/named_functions_are_called_as_the_type_asks_1.sakura b/tests/programs/named_functions_are_called_as_the_type_asks_1.sakura new file mode 100644 index 00000000..0214e62c --- /dev/null +++ b/tests/programs/named_functions_are_called_as_the_type_asks_1.sakura @@ -0,0 +1,68 @@ +import std::io; + +# A named function given where a function type it doesn't match is expected is +# called as that type asks, by a function made for it: each parameter given as +# a call gives an argument, the rest taking their defaults, and among overloads +# the one such a call chooses. + +struct rect { var w: i64; var h: i64; } +val rect::area: i64 { get => this.w * this.h; } +def rect::grow(&mut this, by: i64 = 1): i64 { this.w += by; return this.w; } + +def doubled(x: &i64): i64 { return x * 2; } +def tripled(x: i64): i64 { return x * 3; } +def scaled(x: i64, by: i64 = 10): i64 { return x * by; } +def length(text: strview): u64 { return text.length; } +def large(x: &i64): bool { return x > 2; } + +def shown(x: &i64): i64 { return x + 1; } +def shown(x: &f64): i64 { return 0; } + +def line_of(x: i64, at: site = call_site()): u64 { return at.line; } + +union outcome { var failed: strview; var made: T; } +val outcome::ok: bool { get => this is made; } +def outcome::take(&mut this): T { + if this is made(&mut held) { return move(held); } + fault("Took a failed outcome."); +} + +def parse(text: strview, base: u64 = 10): outcome { + return "empty" if text.length == 0; + return string::from(text, nothing {}); +} + +def main(): void { + # A reference parameter where a value is given, and a value where a reference is. + val by_reference: def(i64): i64 = doubled; + val by_value: def(&i64): i64 = tripled; + val four: i64 = 4; + println($"{by_reference(4)} {by_value(&four)}"); + + # Through an `invokable` bound, as adapters take them. + var xs := vector::::new(); + xs.append(1); + xs.append(3); + println($"{xs.iter().map(tripled).sum()} {xs.view().iter().filter(large).count()} {xs.iter().map(scaled).sum()}"); + + val words: strview[3] = ["a", "bc", ""]; + println($"{words[:].iter().map(length).sum()}"); + + # Properties and methods taken through their type, with their defaults. + var rs := vector::::new(); + rs.append(rect { w = 2, h = 3 }); + rs.append(rect { w = 4, h = 5 }); + val area: def(rect): i64 = rect::area; + println($"{rs.iter().map(rect::area).sum()} {area(rect { w = 1, h = 7 })} {rs.iter().map(rect::grow).sum()} {rs[0].w}"); + + # An overload a call chooses, and a default naming where the function is named. + val chosen: def(i64): i64 = shown; + val line: def(i64): u64 = line_of; + println($"{chosen(4)} {line(0)}"); + + # Values that close are lent where a reference is taken, and moved where a + # value is. + val texts: strview[3] = ["one", "", "three"]; + val kept := texts[:].iter().map(parse).filter(outcome::ok).map(outcome::take).to_vector(); + println($"{kept.length} {kept[0]} {kept[1]}"); +} diff --git a/tests/programs/names_of_core_give_way_1.out b/tests/programs/names_of_core_give_way_1.out new file mode 100644 index 00000000..d2a78cd1 --- /dev/null +++ b/tests/programs/names_of_core_give_way_1.out @@ -0,0 +1,2 @@ +own vector 25, own range 7 +core's vector 1 holding 7, core's range 0..4 summing 6 diff --git a/tests/programs/names_of_core_give_way_1.sakura b/tests/programs/names_of_core_give_way_1.sakura new file mode 100644 index 00000000..511d15cc --- /dev/null +++ b/tests/programs/names_of_core_give_way_1.sakura @@ -0,0 +1,39 @@ +# A program's own `vector` and `range` are what it names, since a name of +# `core`'s gives way to anything a program declares; `core::vector` still names +# `core`'s, and `0..4` still makes its `range`, as the syntax does whatever the +# program names so. + +import std::io; + +struct vector { + var x: f64; + var y: f64; +} + +struct range { + var low: i64; + var high: i64; +} + +def vector::length_squared(&this): f64 { + return this.x * this.x + this.y * this.y; +} + +def range::width(&this): i64 { + return this.high - this.low; +} + +def main(): void { + val v := vector { x = 3.0, y = 4.0 }; + val r := range { low = 2, high = 9 }; + var held := core::vector::::new(); + held.append(r.width()); + val made := 0..4; + val bounds := $"{made.start}..{made.end}"; + var counted := 0; + for i in made { + counted += i; + } + io::println($"own vector {v.length_squared()}, own range {r.width()}"); + io::println($"core's vector {held.length} holding {held[0]}, core's range {bounds} summing {counted}"); +} diff --git a/tests/programs/narrow_scalars_are_referred_to_in_place_1.out b/tests/programs/narrow_scalars_are_referred_to_in_place_1.out new file mode 100644 index 00000000..a8ed638f --- /dev/null +++ b/tests/programs/narrow_scalars_are_referred_to_in_place_1.out @@ -0,0 +1,2 @@ +200 5 100 true 0 true +true 4000000000 true -30000 true 0.75 diff --git a/tests/programs/narrow_scalars_are_referred_to_in_place_1.sakura b/tests/programs/narrow_scalars_are_referred_to_in_place_1.sakura new file mode 100644 index 00000000..bc64fd1a --- /dev/null +++ b/tests/programs/narrow_scalars_are_referred_to_in_place_1.sakura @@ -0,0 +1,26 @@ +import std::io; +def u8::doubled(&this): u8 { return this * 2; } +def i8::negated(&this): i8 { return -this; } +def i8::flip(&mut this): void { this = -this; } +def u8::bump(&mut this): void { this += 1; } +def bool::toggle(&mut this): void { this = !this; } +def f32::half(&this): f32 { return this / 2f; } +def read(value: &i16): i16 { return value; } +def write(value: &mut u32, to: u32): void { value = to; } +def main(): void { + val small: u8 = 100; + val negative: i8 = -5; + var signed: i8 = -100; + var count: u8 = 254; + var flag := false; + var wide: u32 = 7; + val short: i16 = -30000; + val half: f32 = 1.5; + signed.flip(); + count.bump(); + count.bump(); + flag.toggle(); + write(&mut wide, 4000000000); + println($"{small.doubled()} {negative.negated()} {signed} {signed > 0} {count} {count == 0}"); + println($"{flag} {wide} {wide > 3000000000} {read(&short)} {short < 0} {half.half()}"); +} diff --git a/tests/programs/nested_traits_run_1.out b/tests/programs/nested_traits_run_1.out new file mode 100644 index 00000000..65fd8e46 --- /dev/null +++ b/tests/programs/nested_traits_run_1.out @@ -0,0 +1 @@ +9 18 18 -1 11 2.5 diff --git a/tests/programs/nested_traits_run_1.sakura b/tests/programs/nested_traits_run_1.sakura new file mode 100644 index 00000000..eac0ea3a --- /dev/null +++ b/tests/programs/nested_traits_run_1.sakura @@ -0,0 +1,27 @@ +import std::io; +struct shape {} +trait shape::measured { def area(&this): i64; def twice(&this): i64 { return this.area() * 2; } } +struct square : shape::measured { var side: i64; } +def square::area(&this): i64 { return this.side * this.side; } +struct bag { var items: T[2]; } +trait bag::visitor { def visit(&mut this, item: &T): void; } +trait bag::mapper { def map(&this, item: &T): U; } +def bag::walk(&this, v: &mut bag::visitor): void { + var i: u64 = 0; + while i < 2 { v.visit(&this.items[i]); i++; } +} +def bag::first(&this, m: &M): U where M: bag::mapper { return m.map(&this.items[0]); } +struct summer : bag::visitor { var total: i64; } +def summer::visit(&mut this, item: &i64): void { this.total += item; } +struct halver {} +def halver::map(&this, item: &i64): f64 { return item as f64 / 2.0; } +def measure(x: &T): i64 where T: shape::measured { return x.area(); } +def twice_or(x: &T): i64 { if const T is shape::measured { return x.twice(); } return -1; } +def main(): void { + val s := square{ 3 }; + val m: &shape::measured = &s; + val b := bag::{ [5, 6] }; + var total := summer{ 0 }; + b.walk(&mut total); + println($"{measure(&s)} {m.twice()} {twice_or(&s)} {twice_or(&b)} {total.total} {b.first::(&halver{})}"); +} diff --git a/tests/programs/nested_types_run_1.out b/tests/programs/nested_types_run_1.out new file mode 100644 index 00000000..89f5f2ba --- /dev/null +++ b/tests/programs/nested_types_run_1.out @@ -0,0 +1 @@ +6 true 1=a+true #7 diff --git a/tests/programs/nested_types_run_1.sakura b/tests/programs/nested_types_run_1.sakura new file mode 100644 index 00000000..10a3f2d2 --- /dev/null +++ b/tests/programs/nested_types_run_1.sakura @@ -0,0 +1,30 @@ +import std::io; +def bag::iter::done(&this): bool { return this.at >= this.of.count; } +def bag::iter::next(&mut this): T { val v := this.of.items[this.at]; this.at++; return v; } +struct bag { var items: T[4]; var count: u64; } +struct bag::iter { val of: &bag; var at: u64; } +enum bag::state { empty, full } +def bag::begin(&this): bag::iter { return bag::::iter { this, 0 }; } +def bag::status(&this): bag::state { + return this.count == 4 ? bag::::state::full : bag::::state::empty; +} +struct table { var key: K; var value: V; } +struct table::entry { var key: K; var value: V; var extra: W; } +def table::entry::show(&this): string { return $"{this.key}={this.value}+{this.extra}"; } +def table::with(&this, extra: W): table::entry { + return table::::entry:: { this.key, this.value, extra }; +} +trait Shown { def show(&this): string; } +struct counter::shown : Shown { var n: i64; } +struct counter { var n: i64; } +def counter::shown::show(&this): string { return $"#{this.n}"; } +def describe(x: &Shown): string { return x.show(); } +def main(): void { + val xs := bag:: { [1, 2, 3, 0], 3 }; + var it := xs.begin(); + var total: i64 = 0; + while !it.done() { total += it.next(); } + val t := table::> { 1, "a" }; + val s := counter::shown { 7 }; + println($"{total} {xs.status() == bag::::state::empty} {t.with::(true).show()} {describe(&s)}"); +} diff --git a/tests/programs/operators_call_the_methods_of_ordered_and_numeric_1.out b/tests/programs/operators_call_the_methods_of_ordered_and_numeric_1.out new file mode 100644 index 00000000..efee168f --- /dev/null +++ b/tests/programs/operators_call_the_methods_of_ordered_and_numeric_1.out @@ -0,0 +1,3 @@ +9 26 -1 1 2 4 3 4 42 +true true true false 2 9 16 +1.5 -1.5 1.25 2 diff --git a/tests/programs/operators_call_the_methods_of_ordered_and_numeric_1.sakura b/tests/programs/operators_call_the_methods_of_ordered_and_numeric_1.sakura new file mode 100644 index 00000000..0cb66087 --- /dev/null +++ b/tests/programs/operators_call_the_methods_of_ordered_and_numeric_1.sakura @@ -0,0 +1,34 @@ +import std::io; +struct vec2 { var x: i64; var y: i64; } +def vec2::equals(&this, other: &vec2): bool { return this.x == other.x && this.y == other.y; } +def vec2::add(&this, other: &vec2): vec2 { return vec2{ this.x + other.x, this.y + other.y }; } +def vec2::sub(&this, other: &vec2): vec2 { return vec2{ this.x - other.x, this.y - other.y }; } +def vec2::mul(&this, other: &vec2): vec2 { return vec2{ this.x * other.x, this.y * other.y }; } +def vec2::div(&this, other: &vec2): vec2 { return vec2{ this.x / other.x, this.y / other.y }; } +def vec2::rem(&this, other: &vec2): vec2 { return vec2{ this.x % other.x, this.y % other.y }; } +def vec2::negate(&this): vec2 { return vec2{ -this.x, -this.y }; } +struct version { var major: i64; var minor: i64; } +def version::equals(&this, other: &version): bool { return this.compare(other) == 0; } +def version::compare(&this, other: &version): i64 { + return this.major != other.major ? this.major - other.major : this.minor - other.minor; +} +struct holder { var at: vec2; } +def sum(xs: span, start: T): T where T: numeric { var t := start; for x in xs { t += x; } return t; } +def most(a: T, b: T): T where T: ordered { return a < b ? b : a; } +const moved: vec2 = vec2{ 1, 2 } + vec2{ 10, 20 } * vec2{ 2, 2 }; +def main(): void { + val a := vec2{ 1, 2 }; + val b := vec2{ 3, 5 }; + val c := a + b * b - vec2{ 1, 1 }; + var h := holder{ at = a }; + h.at += b; + var arr: vec2[2] = [a, b]; + arr[1] -= a; + val ints: i64[3] = [1, 2, 3]; + val total := sum::(arr[:], a); + println($"{c.x} {c.y} {(-a).x} {(b % vec2{ 2, 2 }).y} {(b / a).y} {h.at.x} {arr[1].y} {total.x} {moved.y}"); + val old := version{ 1, 9 }; + val new := version{ 2, 0 }; + println($"{old < new} {old <= old} {new > old} {old >= new} {most(old, new).major} {most(3, 9)} {sum::(ints[:], 10)}"); + println($"{7.5 % 2.0} {-7.5 % 2.0} {7.25f % 2.0f} {5 % 3}"); +} diff --git a/tests/programs/operators_call_the_methods_of_ordered_and_numeric_2.out b/tests/programs/operators_call_the_methods_of_ordered_and_numeric_2.out new file mode 100644 index 00000000..d435623e --- /dev/null +++ b/tests/programs/operators_call_the_methods_of_ordered_and_numeric_2.out @@ -0,0 +1,2 @@ +9 30 -2 5 +0 diff --git a/tests/programs/operators_call_the_methods_of_ordered_and_numeric_2.sakura b/tests/programs/operators_call_the_methods_of_ordered_and_numeric_2.sakura new file mode 100644 index 00000000..47d39c48 --- /dev/null +++ b/tests/programs/operators_call_the_methods_of_ordered_and_numeric_2.sakura @@ -0,0 +1,24 @@ +import std::io; +var live: i64 = 0; +struct num : owning { var n: i64; } +def num::of(n: i64): num { live++; return num{ n = n }; } +def num::close(&mut this): void { live--; } +def num::equals(&this, other: &num): bool { return this.n == other.n; } +def num::add(&this, other: &num): num { return num::of(this.n + other.n); } +def num::sub(&this, other: &num): num { return num::of(this.n - other.n); } +def num::mul(&this, other: &num): num { return num::of(this.n * other.n); } +def num::div(&this, other: &num): num { return num::of(this.n / other.n); } +def num::rem(&this, other: &num): num { return num::of(this.n % other.n); } +def num::negate(&this): num { return num::of(-this.n); } +def main(): void { + { + val a := num::of(2); + val b := num::of(3); + val c := a + b * b - a; + var d := num::of(1); + d += c; + d *= b; + println($"{c.n} {d.n} {(-a).n} {live}"); + } + println($"{live}"); +} diff --git a/tests/programs/operators_call_the_methods_that_give_them_1.out b/tests/programs/operators_call_the_methods_that_give_them_1.out new file mode 100644 index 00000000..e38f6452 --- /dev/null +++ b/tests/programs/operators_call_the_methods_that_give_them_1.out @@ -0,0 +1,3 @@ +250 500 125 355 -250 125 2 200 +true true 100 250 +7 14 14 4 diff --git a/tests/programs/operators_call_the_methods_that_give_them_1.sakura b/tests/programs/operators_call_the_methods_that_give_them_1.sakura new file mode 100644 index 00000000..bbe0d0a1 --- /dev/null +++ b/tests/programs/operators_call_the_methods_that_give_them_1.sakura @@ -0,0 +1,48 @@ +import std::io; +# A type has each operator by the method that gives it, taking and giving +# whatever the method declares, so a moment less a moment is a length of time. +struct length : equatable, ordered { var ns: i64; } +def length::equals(&this, other: &length): bool { return this.ns == other.ns; } +def length::compare(&this, other: &length): i64 { return this.ns - other.ns; } +def length::add(&this, other: &length): length { return length { ns = this.ns + other.ns }; } +def length::sub(&this, other: &length): length { return length { ns = this.ns - other.ns }; } +def length::negate(&this): length { return length { ns = -this.ns }; } +def length::mul(&this, by: &i64): length { return length { ns = this.ns * by }; } +def length::mul(&this, by: &f64): length { return length { ns = (this.ns as f64 * by) as i64 }; } +def length::div(&this, by: &i64): length { return length { ns = this.ns / by }; } +def length::div(&this, by: &length): f64 { return this.ns as f64 / by.ns as f64; } +def length::rem(&this, by: &length): length { return length { ns = this.ns % by.ns }; } +struct moment : equatable, ordered { var ns: i64; } +def moment::equals(&this, other: &moment): bool { return this.ns == other.ns; } +def moment::compare(&this, other: &moment): i64 { return this.ns - other.ns; } +def moment::add(&this, by: &length): moment { return moment { ns = this.ns + by.ns }; } +def moment::sub(&this, by: &length): moment { return moment { ns = this.ns - by.ns }; } +def moment::sub(&this, since: &moment): length { return length { ns = this.ns - since.ns }; } +# One with only `add` adds, and counts how often it is asked to. +var added: i64 = 0; +struct tally { var n: i64; } +def tally::add(&this, other: &tally): tally { added++; return tally { n = this.n + other.n }; } +struct holder { var kept: tally; } +var holder::total: tally { get => this.kept; set => this.kept = value; } +def later(from: &moment, by: &length): moment { return from + by; } +def main(): void { + val began := moment { ns = 100 }; + val now := moment { ns = 350 }; + val waited := now - began; + val twice := waited * 2; + val half := waited * 0.5; + var due := began + twice; + due += length { ns = 5 }; + due -= waited; + println($"{waited.ns} {twice.ns} {half.ns} {due.ns} {(-waited).ns} {(twice / 4).ns} {twice / waited} {(twice % length { ns = 300 }).ns}"); + println($"{due > now} {later(&began, &waited) == now} {(now - (now - began)).ns} {(waited + waited - waited).ns}"); + + var t := tally { n = 1 }; + t = t + t; + t += tally { n = 5 }; + var h := holder { kept = t }; + h.total += t; + var many := [t, t]; + many[1] += many[0]; + println($"{t.n} {h.kept.n} {many[1].n} {added}"); +} diff --git a/tests/programs/operators_lend_constants_as_their_methods_take_them_1.out b/tests/programs/operators_lend_constants_as_their_methods_take_them_1.out new file mode 100644 index 00000000..a24b27bc --- /dev/null +++ b/tests/programs/operators_lend_constants_as_their_methods_take_them_1.out @@ -0,0 +1,8 @@ +2 4 6 +-0.25 -0.5 -0.75 +1.001 2.002 3.003 +3 6 9 +2 4 6 +0.5 1 1.5 +0.1 0.30000000000000004 +-3 6 -9 diff --git a/tests/programs/operators_lend_constants_as_their_methods_take_them_1.sakura b/tests/programs/operators_lend_constants_as_their_methods_take_them_1.sakura new file mode 100644 index 00000000..36962325 --- /dev/null +++ b/tests/programs/operators_lend_constants_as_their_methods_take_them_1.sakura @@ -0,0 +1,47 @@ +import std::io; + +# A constant on the right of an operator is given as the number its method's +# parameter refers to, as a call's argument is, so `v * 2.0` gives `mul` an `f32`. +# A method on a number may name a generic type whose bound asks for that method. +struct vec3 where T: numeric { + pub var x: T; + pub var y: T; + pub var z: T; +} + +def vec3::add(&this, other: &vec3): vec3 { return vec3::{ x = this.x + other.x, y = this.y + other.y, z = this.z + other.z }; } +def vec3::mul(&this, by: &T): vec3 { return vec3::{ x = this.x * by, y = this.y * by, z = this.z * by }; } +def vec3::mul(&this, other: &vec3): vec3 { return vec3::{ x = this.x * other.x, y = this.y * other.y, z = this.z * other.z }; } + +def f32::mul(&this, v: &vec3): vec3 { return v.mul(this); } + +struct gauge { var reading: vec3; } +pub var gauge::level: vec3 { + get => this.reading; + set => this.reading = value; +} + +def show(v: vec3): void { + println($"{v.x} {v.y} {v.z}"); +} + +def main(): void { + val a := vec3::{ x = 1, y = 2, z = 3 }; + show(a * 2.0); + show(a * -0.25); + show(a + a * 1e-3); + show(3.0f * a); + + var b := a; + b *= 2.0; + show(b); + + var held := gauge{ reading = a }; + held.level *= 0.5; + show(held.level); + + val d := vec3::{ x = 1, y = 2, z = 3 } * 0.1; + println($"{d.x} {d.z}"); + val n := vec3::{ x = 1, y = -2, z = 3 } * -3; + println($"{n.x} {n.y} {n.z}"); +} diff --git a/tests/programs/operators_reach_generic_code_through_bounds_1.out b/tests/programs/operators_reach_generic_code_through_bounds_1.out new file mode 100644 index 00000000..48fd372b --- /dev/null +++ b/tests/programs/operators_reach_generic_code_through_bounds_1.out @@ -0,0 +1,5 @@ +2 1 2 10 +6 4 6 +-4 -1 12 3 5 +-4 -8 1 3 +true true true false true false diff --git a/tests/programs/operators_reach_generic_code_through_bounds_1.sakura b/tests/programs/operators_reach_generic_code_through_bounds_1.sakura new file mode 100644 index 00000000..9df55dbc --- /dev/null +++ b/tests/programs/operators_reach_generic_code_through_bounds_1.sakura @@ -0,0 +1,38 @@ +import std::io; +# Generic code has an operator from any bound asking for its method: std's own, +# or a trait of the program's composing them with one of its own. +struct vec2 : additive { var x: f64; var y: f64; } +def vec2::equals(&this, o: &vec2): bool { return this.x == o.x && this.y == o.y; } +def vec2::add(&this, o: &vec2): vec2 { return vec2 { x = this.x + o.x, y = this.y + o.y }; } +def vec2::sub(&this, o: &vec2): vec2 { return vec2 { x = this.x - o.x, y = this.y - o.y }; } +def vec2::negate(&this): vec2 { return vec2 { x = -this.x, y = -this.y }; } +def vec2::mul(&this, by: &f64): vec2 { return vec2 { x = this.x * by, y = this.y * by }; } +def vec2::mul(&this, by: &vec2): f64 { return this.x * by.x + this.y * by.y; } +trait scales : additive { def mul(&this, by: &S): self; } +def lerp(a: V, b: V, t: S): V where V: scales { return a + (b - a) * t; } +def sum(items: span, from: T): T where T: addable { + var total := from; + for &each in items { total += each; } + return total; +} +def spread(a: T, b: T): T where T: additive { return a == b ? a : -(a - b); } +def area(w: T, h: T): T where T: multipliable { return w * h; } +def parts(whole: T, by: T): T where T: divisible, modular, addable { return whole / by + whole % by; } +# A generic type's operators are its instances' own. +struct pair where T: numeric { var a: T; var b: T; } +def pair::add(&this, o: &pair): pair { return pair:: { a = this.a + o.a, b = this.b + o.b }; } +def pair::mul(&this, by: &T): pair { return pair:: { a = this.a * by, b = this.b * by }; } +def pair::negate(&this): pair { return pair:: { a = -this.a, b = -this.b }; } +def main(): void { + val low := vec2 { x = 0.0, y = 0.0 }; + val high := vec2 { x = 2.0, y = 4.0 }; + val mid := lerp(low, high, 0.5); + println($"{lerp(1.0, 3.0, 0.5)} {mid.x} {mid.y} {high * mid}"); + println($"{sum([1, 2, 3][0:3], 0)} {sum([1.5, 2.5][0:2], 0.0)} {sum([high, mid][0:2], low).y}"); + println($"{spread(7, 3)} {spread(high, mid).x} {area(3, 4)} {area(1.5, 2.0)} {parts(17, 5)}"); + val p := pair:: { a = 1, b = 2 }; + val q := -(p + p * 3); + val r := pair:: { a = 0.5, b = 1.5 } * 2.0; + println($"{q.a} {q.b} {r.a} {r.b}"); + println($"{1 is additive} {1.5 is multiplicative} {low is additive} {low is numeric} {p is addable} {true is addable}"); +} diff --git a/tests/programs/ordinal_parameters_convert_to_and_from_integers_1.out b/tests/programs/ordinal_parameters_convert_to_and_from_integers_1.out new file mode 100644 index 00000000..444cd9e2 --- /dev/null +++ b/tests/programs/ordinal_parameters_convert_to_and_from_integers_1.out @@ -0,0 +1,2 @@ +5 false true +green 200 blue 9 diff --git a/tests/programs/ordinal_parameters_convert_to_and_from_integers_1.sakura b/tests/programs/ordinal_parameters_convert_to_and_from_integers_1.sakura new file mode 100644 index 00000000..f3b12f50 --- /dev/null +++ b/tests/programs/ordinal_parameters_convert_to_and_from_integers_1.sakura @@ -0,0 +1,15 @@ +import std::io; +enum bits: u32 { a = 1, b = 2, c = 4 } +enum color: u8 { red, green = 4, blue } +type flags = u32 where T: ordinal; +def flags::set(&mut this, value: T): void { this |= value as u32; } +def flags::has(&this, value: T): bool { return (this & (value as u32)) != 0; } +def back(n: u64): T where T: ordinal { return n as T; } +def most(a: T, b: T): T where T: ordinal { return a < b ? b : a; } +def main(): void { + var f: flags = 0; + f.set(bits::a); + f.set(bits::c); + println($"{f} {f.has(bits::b)} {f.has(bits::c)}"); + println($"{back::(4)} {back::(200)} {most(color::blue, color::red)} {most(3, 9)}"); +} diff --git a/tests/programs/overloads_1.out b/tests/programs/overloads_1.out new file mode 100644 index 00000000..c539690b --- /dev/null +++ b/tests/programs/overloads_1.out @@ -0,0 +1,2 @@ +int 1, float 1.5, 3 m, text abc, 2 items, pair 2 3, int 7 +6 12 [1, 2, 3, 0] 3 hi rex sir rex float 2 int 5 diff --git a/tests/programs/overloads_1.sakura b/tests/programs/overloads_1.sakura new file mode 100644 index 00000000..0c9bbe89 --- /dev/null +++ b/tests/programs/overloads_1.sakura @@ -0,0 +1,38 @@ +import std::io; +type meters = f64; +def show(n: int): string { return $"int {n}"; } +def show(n: f64): string { return $"float {n}"; } +def show(m: meters): string { return $"{m} m"; } +def show(text: span): string { return $"text {text}"; } +def show(items: T[2]): string { return $"{items.length} items"; } +def show(a: int, b: int): string { return $"pair {a} {b}"; } +struct vec { var x: f64; var y: f64; } +def vec::scale(&mut this, by: f64): void { this.x *= by; this.y *= by; } +def vec::scale(&mut this, by: vec): void { this.x *= by.x; this.y *= by.y; } +def vec::of(n: f64): vec { return vec{ n, n }; } +def vec::of(x: f64, y: f64): vec { return vec{ x, y }; } +struct stack { var items: T[4]; var count: u64; } +def stack::push(&mut this, value: T): void { this.items[this.count] = value; this.count++; } +def stack::push(&mut this, values: T[2]): void { for v in values { this.push(v); } } +trait Named { def name(&this): string; } +struct dog: Named { val n: span; } +def dog::name(&this, prefix: span): string { return $"{prefix}{this.n}"; } +def dog::name(&this): string { return this.n; } +def greet(x: &Named): string { return $"hi {x.name()}"; } +def apply(f: def(int): string, n: int): string { return f(n); } +def main(): void { + val m: meters = 3; + val small: i32 = 7; + val text := "abc"; + val sir := "sir "; + println($"{show(1)}, {show(1.5)}, {show(m)}, {show(text)}, {show([1, 2])}, {show(2, 3)}, {show(small)}"); + var v := vec::of(2); + v.scale(3); + v.scale(vec::of(1, 2)); + var s := stack::{ [0, 0, 0, 0], 0 }; + s.push(1); + s.push([2, 3]); + val d := dog{ "rex" }; + val f: def(f64): string = show; + println($"{v.x} {v.y} {s.items} {s.count} {greet(d)} {d.name(sir)} {f(2)} {apply(show, 5)}"); +} diff --git a/tests/programs/packs_in_function_types_1.out b/tests/programs/packs_in_function_types_1.out new file mode 100644 index 00000000..4a9f35e7 --- /dev/null +++ b/tests/programs/packs_in_function_types_1.out @@ -0,0 +1,5 @@ +3 +hey! +42 +sora is 30 and tall +42 diff --git a/tests/programs/packs_in_function_types_1.sakura b/tests/programs/packs_in_function_types_1.sakura new file mode 100644 index 00000000..ef26fc76 --- /dev/null +++ b/tests/programs/packs_in_function_types_1.sakura @@ -0,0 +1,19 @@ +import std::io; + +# A pack among a function type's parameters takes the types of the arguments. +def apply(f: def(Ts...): R, args: Ts...): R { return f(...args); } + +def add(a: i64, b: i64): i64 { return a + b; } +def shout(text: strview): string { var out: string = text; out.append("!"); return out; } +def answer(): i64 { return 42; } +def describe(name: strview, age: i64, tall: bool): string { + return $"{name} is {age}{tall ? " and tall" : ""}"; +} + +def main(): void { + println($"{apply(add, 1, 2)}"); + println(apply(shout, "hey")); + println($"{apply(answer)}"); + println(apply(describe, "sora", 30, true)); + println($"{apply(def(x: i64, y: i64): i64 => x * y, 6, 7)}"); +} diff --git a/tests/programs/packs_of_types_and_traits_1.out b/tests/programs/packs_of_types_and_traits_1.out new file mode 100644 index 00000000..1effc6b8 --- /dev/null +++ b/tests/programs/packs_of_types_and_traits_1.out @@ -0,0 +1,6 @@ +3 + 1 yes + 2 no + 3 yes +2 tagged +some 0 diff --git a/tests/programs/packs_of_types_and_traits_1.sakura b/tests/programs/packs_of_types_and_traits_1.sakura new file mode 100644 index 00000000..04156103 --- /dev/null +++ b/tests/programs/packs_of_types_and_traits_1.sakura @@ -0,0 +1,59 @@ +import std::io; + +trait shown { def show(&this): string; } +def i64::show(&this): string { return $"{this}"; } +def bool::show(&this): string { return this ? "yes" : "no"; } + +# A trait taking a pack, whose method takes a parameter for each of its types. +trait sink { + def put(&mut this, args: Ts...): void; +} + +# A trait composing another, passing its pack on. +trait counted_sink : sink { + def count(&this): i64; +} + +# A struct taking a pack, whose types are bounded each. +struct log : counted_sink where Ts...: shown { + var lines: vector; +} +def log::put(&mut this, args: Ts...): void { + var line: string = ""; + for const x in args { line.append(" "); line.append(x.show()); } + this.lines.append(move(&mut line)); +} +def log::count(&this): i64 { return this.lines.length as i64; } + +# A union taking a pack too, holding a count of its types. +union arity { + var none: bool; + var some: u64; +} +def arity::of(): arity { return arity::{ some = 0 }; } + +# A pack left out after the other arguments is empty. +struct tagged : sink { var hits: i64; } +def tagged::put(&mut this, args: Ts...): void { this.hits += 1 + args.length as i64; } + +def feed(into: &mut S, args: Ts...): void where S: sink { + into.put(...args); +} + +def main(): void { + var a := log::{ lines = vector::::new() }; + a.put(1, true); + feed(&mut a, 2, false); + val as_sink: &mut counted_sink = &mut a; + as_sink.put(3, true); + println($"{as_sink.count()}"); + for &line in a.lines { println(line); } + + var b := tagged::{ hits = 0 }; + b.put(); + b.put(); + println($"{b.hits} {name_of::>()}"); + + val u := arity::::of(); + if u is some(n) { println($"some {n}"); } +} diff --git a/tests/programs/packs_of_types_have_lengths_1.out b/tests/programs/packs_of_types_have_lengths_1.out new file mode 100644 index 00000000..cb253369 --- /dev/null +++ b/tests/programs/packs_of_types_have_lengths_1.out @@ -0,0 +1 @@ +3 0 3 diff --git a/tests/programs/packs_of_types_have_lengths_1.sakura b/tests/programs/packs_of_types_have_lengths_1.sakura new file mode 100644 index 00000000..a1ec2b41 --- /dev/null +++ b/tests/programs/packs_of_types_have_lengths_1.sakura @@ -0,0 +1,8 @@ +import std::io; +def count(xs: Ts...): u64 { return Ts.length; } +struct row { var n: int; } +def row::width(&this): u64 { return Ts.length; } +def main(): void { + val r := row::{}; + println($"{count(1, true, 'c')} {count()} {r.width()}"); +} diff --git a/tests/programs/packs_spread_move_their_values_1.out b/tests/programs/packs_spread_move_their_values_1.out new file mode 100644 index 00000000..05d2ed75 --- /dev/null +++ b/tests/programs/packs_spread_move_their_values_1.out @@ -0,0 +1,5 @@ +took 3 +closing 2 +closing 1 +passed +done diff --git a/tests/programs/packs_spread_move_their_values_1.sakura b/tests/programs/packs_spread_move_their_values_1.sakura new file mode 100644 index 00000000..970112c0 --- /dev/null +++ b/tests/programs/packs_spread_move_their_values_1.sakura @@ -0,0 +1,12 @@ +import std::io; +struct noisy : owning { var id: int; } +def noisy::close(&mut this): void { if this.id != 0 { println($"closing {this.id}"); } } +def take(xs: Ts...): void { println($"took {xs.length}"); } +def pass(xs: Ts...): void { + take(...xs); + println("passed"); +} +def main(): void { + pass(noisy{ id = 1 }, noisy{ id = 2 }, 3); + println("done"); +} diff --git a/tests/programs/parameters_take_default_values_1.out b/tests/programs/parameters_take_default_values_1.out new file mode 100644 index 00000000..f37e3393 --- /dev/null +++ b/tests/programs/parameters_take_default_values_1.out @@ -0,0 +1,10 @@ +18 324 +9 none +9 tag +10 1 +hi world! +hi sakura? +31:15 1 == 2 false +18:17 limit > 3 false 18:35 v == v true +18:17 limit > 3 true 18:35 v == v true +9 diff --git a/tests/programs/parameters_take_default_values_1.sakura b/tests/programs/parameters_take_default_values_1.sakura new file mode 100644 index 00000000..714f07dd --- /dev/null +++ b/tests/programs/parameters_take_default_values_1.sakura @@ -0,0 +1,36 @@ +import std::io; +struct counter { var n: int; } +def counter::bump(this: &mut counter, by: int = 1, times: int = by): void { + this.n = this.n + by * times; +} +def counter::scaled(this: &counter, by: int = this.n): int { return this.n * by; } +struct box { var it: T; } +def box::make(it: T, tag: span = "none"): string { return $"{it} {tag}"; } +var calls: int = 0; +def next(): int { calls = calls + 1; return 5; } +def twice(a: int, b: int = a): int { return a + b; } +def told(cond: bool, text: span = source_of(cond), at: site = call_site()): string { + return $"{at.line}:{at.column} {text} {cond}"; +} +def greet(name: span = "world", mark: span = "!"): string { return $"hi {name}{mark}"; } +def sized(n: int = 3): int { return n * n; } +def within(v: T, limit: int): string where T: equatable { + return $"{told(limit > 3)} {told(v == v)}"; +} +def main(): void { + var c := counter { n = 0 }; + c.bump(); + c.bump(3); + c.bump(2, 4); + println($"{c.n} {c.scaled()}"); + println(box::::make(9)); + println(box::::make(9, "tag")); + println($"{twice(next())} {calls}"); + println(greet()); + println(greet("sakura", "?")); + println(told(1 == 2)); + println(within::(1, 2)); + println(within::>("a", 9)); + const k := sized(); + println($"{k}"); +} diff --git a/tests/programs/path_of_names_the_modules_of_types_1.out b/tests/programs/path_of_names_the_modules_of_types_1.out new file mode 100644 index 00000000..ec4f8a78 --- /dev/null +++ b/tests/programs/path_of_names_the_modules_of_types_1.out @@ -0,0 +1,5 @@ +position +game::position +&mut core::vector +core::maybe +position diff --git a/tests/programs/path_of_names_the_modules_of_types_1.sakura b/tests/programs/path_of_names_the_modules_of_types_1.sakura new file mode 100644 index 00000000..554cca23 --- /dev/null +++ b/tests/programs/path_of_names_the_modules_of_types_1.sakura @@ -0,0 +1,12 @@ +import std::io; +import game; +struct position { var x: int; } +def main(): void { + println(name_of::()); + println(path_of::()); + println(path_of::<&mut vector>()); + println(path_of::>()); + println(path_of::()); +} +module game; +pub struct position { pub var x: f32; } diff --git a/tests/programs/pattern_parameters_1.out b/tests/programs/pattern_parameters_1.out new file mode 100644 index 00000000..fcce403b --- /dev/null +++ b/tests/programs/pattern_parameters_1.out @@ -0,0 +1,10 @@ +3 5 30 calls 4 +hey! +0 hits 3 +0 5 10 +44 4 +counter +counter +counter +pair +void 9 diff --git a/tests/programs/pattern_parameters_1.sakura b/tests/programs/pattern_parameters_1.sakura new file mode 100644 index 00000000..630e64f9 --- /dev/null +++ b/tests/programs/pattern_parameters_1.sakura @@ -0,0 +1,77 @@ +import std::io; + +# A pattern parameter is given a function type, and names its parts. +trait handler { + def handle(&mut this, args: Ts...): R; +} + +struct adder : handler { var calls: i64; } +def adder::handle(&mut this, a: i64, b: i64): i64 { this.calls++; return a + b; } + +struct shout : handler {} +def shout::handle(&mut this, text: strview): string { var out: string = text; out.append("!"); return out; } + +def twice(g: &mut G, x: i64, y: i64): i64 where G: handler { + return g.handle(g.handle(x, y), y); +} + +def call_with(g: &mut G, args: Ts...): R where G: handler { + return g.handle(...args); +} + +def run(g: &mut handler): i64 { return g.handle(10, 20); } + +# A struct whose own parameters are a pattern's. +struct counter : handler where R: zeroable { var hits: i64; } +def counter::handle(&mut this, args: Ts...): R { + this.hits += 1 + args.length as i64; + var out: R; + return out; +} + +# A pattern's result may be `void`, as a function's may. +struct tally : handler { var sum: i64; } +def tally::handle(&mut this, x: i64): void { this.sum += x; } +def feed(h: &mut handler): void { h.handle(4); h.handle(5); } + +# A struct with a pattern beside a plain parameter. +struct pair { var key: K; } + +# A variadic signature's parameters are those of a variadic function. +struct summer : handler {} +def summer::handle(&mut this, xs: i64...): i64 { + var t: i64 = 0; + for x in xs { t += x; } + return t; +} +def total(f: &mut handler): i64 { return f.handle(1, 2, 3, 4); } + +# Names before a pack take one parameter each, beside a plain parameter. +trait first { + def head(&this, a: A): R; + def rest(&this, args: Rest...): K; +} +struct picker : first {} +def picker::head(&this, a: i64): u8 { return a as u8; } +def picker::rest(&this, b: bool, s: strview): u64 { return s.length; } + +def main(): void { + var a := adder{}; + println($"{a.handle(1, 2)} {twice(&mut a, 1, 2)} {run(a)} calls {a.calls}"); + var s := shout{}; + val loud: string = call_with(&mut s, "hey"); + println(loud); + var c := counter::{}; + println($"{c.handle(1, true)} hits {c.hits}"); + var m := summer{}; + println($"{m.handle()} {m.handle(5)} {total(m)}"); + val p := picker{}; + println($"{p.head(300)} {p.rest(true, "four")}"); + println(name_of::>()); + println(name_of::>()); + println(name_of::>()); + println(name_of::>()); + var t := tally{}; + feed(t); + println($"void {t.sum}"); +} diff --git a/tests/programs/pattern_parameters_2.out b/tests/programs/pattern_parameters_2.out new file mode 100644 index 00000000..8647e49a --- /dev/null +++ b/tests/programs/pattern_parameters_2.out @@ -0,0 +1,4 @@ +4 110.5 11 +16 0 +-2 +3 2 diff --git a/tests/programs/pattern_parameters_2.sakura b/tests/programs/pattern_parameters_2.sakura new file mode 100644 index 00000000..b3c52d58 --- /dev/null +++ b/tests/programs/pattern_parameters_2.sakura @@ -0,0 +1,56 @@ +import std::io; + +# A pattern parameter of a fixed array, `L[N]`, is given an array type and names +# its element's type and its length, so `lanes` is four `f32`s, generic +# code is written over `L` and `N`, and inference reads them from arguments. + +struct lanes where L: numeric, zeroable { + var items: L[N]; +} + +def lanes::count(&this): u64 { + return N; +} + +def lanes::sum(&this): L { + var total: L; + for i in 0..N { + total = total + this.items[i]; + } + return total; +} + +def lanes::add(&this, other: &lanes): lanes { + var made: lanes; + for i in 0..N { + made.items[i] = this.items[i] + other.items[i]; + } + return made; +} + +def first(v: &lanes): L where L: numeric, zeroable { + return v.items[0]; +} + +# An array of arrays is given whole: its element is an array. +struct rows { var items: R[N]; } + +def rows::count(&this): u64 { + return N; +} + +type four = lanes; +type grid = rows[3]>; + +def main(): void { + val a := lanes:: { items = [1.0, 2.0, 3.0, 4.5] }; + val b: four = four { items = [10.0, 20.0, 30.0, 40.0] }; + val c := a + b; + io::println($"{c.count()} {c.sum()} {first(&c)}"); + val d := lanes:: {}; + io::println($"{d.count()} {d.sum()}"); + val e := lanes:: { items = [5, -7] }; + io::println($"{e.sum()}"); + val g := grid {}; + io::println($"{g.count()} {g.items[0].count()}"); +} diff --git a/tests/programs/pointers_and_manual_memory_2.out b/tests/programs/pointers_and_manual_memory_2.out new file mode 100644 index 00000000..4ab5fda8 --- /dev/null +++ b/tests/programs/pointers_and_manual_memory_2.out @@ -0,0 +1,5 @@ +before + +--- exit 1 +sakura: runtime error: Null reference was unwrapped. + at main (tests/programs/pointers_and_manual_memory_2.sakura:5:8) diff --git a/tests/programs/pointers_and_manual_memory_2.sakura b/tests/programs/pointers_and_manual_memory_2.sakura new file mode 100644 index 00000000..abade377 --- /dev/null +++ b/tests/programs/pointers_and_manual_memory_2.sakura @@ -0,0 +1,6 @@ +import std::io; +def main(): void { + var p: *mut int; + println("before"); + p[2] = 1; +} diff --git a/tests/programs/properties_1.out b/tests/programs/properties_1.out new file mode 100644 index 00000000..94a57d61 --- /dev/null +++ b/tests/programs/properties_1.out @@ -0,0 +1,4 @@ +12 3 +64 16 17 17 16 +1 17 +7 [7, 2] z diff --git a/tests/programs/properties_1.sakura b/tests/programs/properties_1.sakura new file mode 100644 index 00000000..f730eb64 --- /dev/null +++ b/tests/programs/properties_1.sakura @@ -0,0 +1,29 @@ +import std::io; +struct rect { var w: int; var h: int; } +val rect::area: int { get => this.w * this.h; } +var rect::width: int { + get => this.w; + set => this.w = value; +} +struct box { var items: T[2]; } +var box::first: T { + get => this.items[0]; + set => this.items[0] = value; +} +var taken := 0; +def next(r: &mut rect): &mut rect { taken += 1; return r; } +def main(): void { + var r := rect{ w = 3, h = 4 }; + println($"{r.area} {r.width}"); + r.width = 10; + r.width += 5; + r.width++; + println($"{r.area} {r.width} {++r.width} {r.width--} {r.width}"); + next(&mut r).width += 1; + println($"{taken} {r.width}"); + var b := box::{ items = [1, 2] }; + b.first += 6; + var t := box::>{ items = ["a", "b"] }; + t.first = "z"; + println($"{b.first} {b.items} {t.first}"); +} diff --git a/tests/programs/properties_2.out b/tests/programs/properties_2.out new file mode 100644 index 00000000..96d68465 --- /dev/null +++ b/tests/programs/properties_2.out @@ -0,0 +1,2 @@ +16 4 +36 6 diff --git a/tests/programs/properties_2.sakura b/tests/programs/properties_2.sakura new file mode 100644 index 00000000..afaefc78 --- /dev/null +++ b/tests/programs/properties_2.sakura @@ -0,0 +1,27 @@ +import std::io; +trait sized { + val area: int { get; } + var width: int { get; set; } +} +struct rect : sized { var w: int; var h: int; } +val rect::area: int { get => this.w * this.h; } +var rect::width: int { + get => this.w; + set => this.w = value; +} +struct square : sized { var side: int; } +val square::area: int { get => this.side * this.side; } +var square::width: int { + get => this.side; + set => this.side = value; +} +def grow(s: &mut sized): void { + s.width += 1; + println($"{s.area} {s.width}"); +} +def main(): void { + var r := rect{ w = 3, h = 4 }; + var q := square{ side = 5 }; + grow(&mut r); + grow(&mut q); +} diff --git a/tests/programs/properties_and_generic_methods_are_values_1.out b/tests/programs/properties_and_generic_methods_are_values_1.out new file mode 100644 index 00000000..9696eaeb --- /dev/null +++ b/tests/programs/properties_and_generic_methods_are_values_1.out @@ -0,0 +1,4 @@ +20 5 +3: 1 7 3 +9 +2 14 6 diff --git a/tests/programs/properties_and_generic_methods_are_values_1.sakura b/tests/programs/properties_and_generic_methods_are_values_1.sakura new file mode 100644 index 00000000..ad71c808 --- /dev/null +++ b/tests/programs/properties_and_generic_methods_are_values_1.sakura @@ -0,0 +1,43 @@ +import std::io; + +# A property named as a value is its `get`, a function of `&this`, and a method +# or property of a generic type named without its type arguments takes them +# from the function type expected, or from a parameter's `invokable` bound, as +# an adapter's is. + +struct rect { var w: f32; var h: f32; } +val rect::area: f32 { get => this.w * this.h; } +var rect::width: f32 { get => this.w; set => this.w = value; } + +union outcome { var failed: strview; var made: T; } +val outcome::ok: bool { get => this is made; } +def outcome::take(&this): T { return this.made; } + +def read(text: &strview): outcome { + return "not a digit" if text.length != 1 || text[0] < '0' || text[0] > '9'; + return (text[0] - '0') as i64; +} + +def doubled(xs: span>): vector where T: integer { + return xs.iter().copied().filter(outcome::ok).map(def(o) => o.take() * 2).to_vector(); +} + +def main(): void { + var r := rect { w = 3, h = 4 }; + val area: def(&rect): f32 = rect::area; + val width: def(&rect): f32 = rect::width; + r.width = 5; + println($"{area(&r)} {width(&r)}"); + + val texts: strview[5] = ["1", "x", "7", "", "3"]; + val read_all := texts[:].iter().map(read).to_vector(); + val kept := read_all.view().iter().copied().filter(outcome::ok).map(def(o) => o.take()).to_vector(); + println($"{kept.length}: {kept[0]} {kept[1]} {kept[2]}"); + + val take: def(&outcome): i64 = outcome::take; + val first: outcome = 9; + println($"{take(&first)}"); + + val twice := doubled(read_all.view()); + println($"{twice[0]} {twice[1]} {twice[2]}"); +} diff --git a/tests/programs/property_accessors_1.out b/tests/programs/property_accessors_1.out new file mode 100644 index 00000000..1889c9c1 --- /dev/null +++ b/tests/programs/property_accessors_1.out @@ -0,0 +1,2 @@ +5 10 105 +9 18 109 diff --git a/tests/programs/property_accessors_1.sakura b/tests/programs/property_accessors_1.sakura new file mode 100644 index 00000000..7947a869 --- /dev/null +++ b/tests/programs/property_accessors_1.sakura @@ -0,0 +1,23 @@ +import std::io; +import shapes; +def main(): void { + var b := parcel{ n = 5 }; + println($"{b.count} {b.twice} {b.label}"); + b.label = 8; + b.bump(); + println($"{b.count} {b.twice} {b.label}"); +} +module shapes; +pub struct parcel { pub var n: i64; } +var parcel::count: i64 { + pub get => this.n; + set => this.n = value; +} +var parcel::twice: i64 { + pub get => this.n * 2; +} +pub var parcel::label: i64 { + get => this.n + 100; + set => this.n = value; +} +pub def parcel::bump(&mut this): void { this.count = this.count + 1; } diff --git a/tests/programs/ranges_are_values_1.out b/tests/programs/ranges_are_values_1.out new file mode 100644 index 00000000..c06f12a3 --- /dev/null +++ b/tests/programs/ranges_are_values_1.out @@ -0,0 +1 @@ +4 4 true false 55 0 1515 0123 0615243 963 0,5,10,15, true 0 11 1 15 120 diff --git a/tests/programs/ranges_are_values_1.sakura b/tests/programs/ranges_are_values_1.sakura new file mode 100644 index 00000000..f8fac0c2 --- /dev/null +++ b/tests/programs/ranges_are_values_1.sakura @@ -0,0 +1,38 @@ +import std::io; + +# A range is a value of std's `range`: kept, passed, and walked later. +def total(r: range): u64 { + var t: u64 = 0; + for x in r { t += x; } + return t; +} + +def main(): void { + val r := 2..6; + val inclusive: range = 1..=4; + print($"{r.remaining()} {inclusive.remaining()} {r.contains(5)} {r.contains(6)} "); + print($"{total(1..=10)} {total(0..0)} "); + # `..=` reaches the type's last value without wrapping past it. + var top: u64 = 0; + for b in (250 as u8)..=255 { top += b as u64; } + print($"{top} "); + for i in 0..=3 { print($"{i}"); } + print(" "); + # A loop over a range counts where it is, so walking it from both ends meets in + # the middle. + var both := 0..7; + while both.next() is some(front) { + print($"{front}"); + if both.next_back() is some(back) { print($"{back}"); } + } + print(" "); + for i in (1..=9).rev().step(3) { print($"{i}"); } + print(" "); + for i in (0..20).step(5) { print($"{i},"); } + print(" "); + val empty := 5..2; + print($"{empty.is_empty()} {empty.remaining()} "); + var counted := 10..=12; + print($"{counted.nth(1) else 0} {counted.count()} "); + println($"{(1..=5).sum()} {(1..=5).product()}"); +} diff --git a/tests/programs/ranges_count_through_enums_1.out b/tests/programs/ranges_count_through_enums_1.out new file mode 100644 index 00000000..591a853e --- /dev/null +++ b/tests/programs/ranges_count_through_enums_1.out @@ -0,0 +1,4 @@ +6 6 12367 12367 red,green,blue,red;green; +low mid zero high top one two four high +3 true blue green red zero 2 low zero top +0 4 5 low top mid high zero 32 32 43 diff --git a/tests/programs/ranges_count_through_enums_1.sakura b/tests/programs/ranges_count_through_enums_1.sakura new file mode 100644 index 00000000..3e5005e7 --- /dev/null +++ b/tests/programs/ranges_count_through_enums_1.sakura @@ -0,0 +1,53 @@ +import std::io; + +# A range of an enum's members gives each value once, in order, passing over +# those no member has: in place, as a value, unrolled, and while checking. +enum color: u8 { red, green = 4, blue } +enum level { low = -2, mid, high = 3, top, zero = 0 } +enum bits: u64 { one = 1, two = 2, four = 4, high = 0x8000000000000000 } + +def through(n: i64): i64 { + var t := 0; + for i in 0..=n { t += i; } + return t; +} + +def levels(): i64 { + var t := 0; + for l in level::low..=level::top { t = t * 10 + (l as i64 + 3); } + return t; +} + +const six := through(3); +const counted := levels(); + +def walk(a: T, b: T): u64 where T: ordinal { + var n: u64 = 0; + for x in a..=b { n++; } + val r := a..b; + return n * 10 + r.remaining(); +} + +def main(): void { + print($"{six} {through(3)} {counted} {levels()} "); + for c in color::red..=color::blue { print($"{c},"); } + for c in color::red..color::blue { print($"{c};"); } + println(""); + for l in level::low..=level::top { print($"{l} "); } + for x in bits::one..=bits::high { print($"{x} "); } + println(""); + var r := color::red..=color::blue; + print($"{r.remaining()} {r.contains(color::green)} "); + for c in r.rev() { print($"{c} "); } + var w := level::low..=level::top; + print($"{w.nth(2) else level::low} {w.remaining()} "); + for l in (level::low..=level::top).step(2) { print($"{l} "); } + println(""); + for const c in color::red..=color::blue { print($"{c as u8} "); } + var both := level::low..=level::top; + while both.next() is some(front) { + print($"{front} "); + if both.next_back() is some(back) { print($"{back} "); } + } + println($"{walk(color::red, color::blue)} {walk(level::mid, level::high)} {walk(2, 5)}"); +} diff --git a/tests/programs/references_1.out b/tests/programs/references_1.out new file mode 100644 index 00000000..dd355730 --- /dev/null +++ b/tests/programs/references_1.out @@ -0,0 +1 @@ +3 42 3 30 true 3 holder{target = counter{count = 42}} diff --git a/tests/programs/references_1.sakura b/tests/programs/references_1.sakura new file mode 100644 index 00000000..907f5db8 --- /dev/null +++ b/tests/programs/references_1.sakura @@ -0,0 +1,31 @@ +import std::io; +struct counter { var count: int; } +struct node { var value: int; var next: *node; } +struct holder { val target: &mut counter; } +def bump(c: &mut counter): void { c.count += 1; } +def keep(c: &mut counter): holder { return holder{c}; } +def length(list: *node): int { + var count := 0; + var at := list; + while at != null { count++; at = (*at).next; } + return count; +} +def make(given: &mut counter): holder { + bump(given); + return keep(given); +} +def main(): void { + var n := counter{1}; + bump(&mut n); + var made := counter{40}; + val h := make(&mut made); + h.target.count += 1; + var third := node{3, null}; + var second := node{2, &third as *node}; + val first := node{1, &second as *node}; + third.value = 30; + val ref: &counter = &n; + val alias := &ref; + n.count++; + println($"{n.count} {h.target.count} {length(&first as *node)} {(*(*first.next).next).value} {ref.count == 3} {alias.count} {h}"); +} diff --git a/tests/programs/references_are_kept_only_where_they_must_be_1.out b/tests/programs/references_are_kept_only_where_they_must_be_1.out new file mode 100644 index 00000000..56e7149d --- /dev/null +++ b/tests/programs/references_are_kept_only_where_they_must_be_1.out @@ -0,0 +1,4 @@ +5 8 42 40 +16 16 +-2 -3 1.5 0 +8 9 diff --git a/tests/programs/references_are_kept_only_where_they_must_be_1.sakura b/tests/programs/references_are_kept_only_where_they_must_be_1.sakura new file mode 100644 index 00000000..2486f2c3 --- /dev/null +++ b/tests/programs/references_are_kept_only_where_they_must_be_1.sakura @@ -0,0 +1,35 @@ +import std::io; +struct tally { var n: i64; var small: i32; var part: f32; } +struct holder { val held: &mut tally; } +def tally::add(&mut this, by: i64): i64 { this.n += by; return this.n; } +def tally::read(&this): i64 { return this.n; } +def keep(t: &mut tally): holder { return holder { held = t }; } +def back(t: &mut tally): &mut tally { return t; } +def twice(t: &mut tally): void { once(t); once(t); } +def once(t: &mut tally): void { t.add(1); } +def down(t: &mut tally, depth: i64): i64 { return depth == 0 ? t.read() : down(t, depth - 1) + 1; } +def dec(x: &mut i32): void { x -= 3; } +def halve(x: &mut f32): void { x /= 2f; } +def made(): tally { return tally { n = 40 }; } +def main(): void { + var a := tally { n = 1 }; + a.add(2); + twice(&mut a); + println($"{a.n} {down(&mut a, 3)} {made().add(2)} {made().read()}"); + var kept := tally { n = 10 }; + val h := keep(&mut kept); + h.held.add(5); + back(&mut kept).add(1); + println($"{kept.n} {h.held.n}"); + var small: i32 = 1; + dec(&mut small); + dec(&mut a.small); + var part: f32 = 3; + halve(&mut part); + halve(&mut a.part); + println($"{small} {a.small} {part} {a.part}"); + var seen := tally { n = 7 }; + val look := def(): i64 => seen.add(1); + look(); + println($"{seen.n} {look()}"); +} diff --git a/tests/programs/references_are_lent_and_values_given_1.out b/tests/programs/references_are_lent_and_values_given_1.out new file mode 100644 index 00000000..542276ed --- /dev/null +++ b/tests/programs/references_are_lent_and_values_given_1.out @@ -0,0 +1,7 @@ +1 7 +9 70 20 +70 4 +5 2 +6 +2 9 +8 3 8 diff --git a/tests/programs/references_are_lent_and_values_given_1.sakura b/tests/programs/references_are_lent_and_values_given_1.sakura new file mode 100644 index 00000000..f467c378 --- /dev/null +++ b/tests/programs/references_are_lent_and_values_given_1.sakura @@ -0,0 +1,68 @@ +import std::io; +import std::containers; + +# Where a value goes says what happens to it: a reference type lends it, and +# any other type gives it, copied where it closes nothing. Only `&` or `&mut` +# written, or a reference parameter at a call, makes a reference, and +# references never stack. + +struct point { var x: i64; var y: i64; } + +def larger(a: T, b: T): T where T: ordered { return a < b ? b : a; } +def bump(n: &mut i64): void { n += 1; } + +def main(): void { + # A binding copies an element, and `&` refers to it. + var xs := vector::::new(); + xs.append(1); + xs.append(2); + val copied := xs[0]; + val lent := &xs[0]; + xs[0] = 7; + println($"{copied} {lent}"); + + # So does `for`, and `for &mut` writes each in place. + var total: i64 = 0; + for x in xs { total += x; } + for &mut x in xs { x *= 10; } + println($"{total} {xs[0]} {xs[1]}"); + + # Inference sees values, so `larger` gives a copy, not an element. + val big := larger(xs[0], xs[1]); + xs[1] = 0; + println($"{big} {std::math::sqrt(16.0)}"); + + # A pattern copies what a reference reaches, and `&` refers to it. + var marks := dict::::new(); + marks.set(1, point { x = 1, y = 2 }); + if marks.get(&1) is some(&mut p) { p.x = 5; } + if marks.get(&1) is some(seen) { println($"{seen.x} {seen.y}"); } + + # `&` of a reference is that reference, wherever it is held. + var m: maybe = 3 as i64; + if m is some(&mut held) { + bump(&mut held); + bump(held); + val again := &mut held; + again += 1; + } + println($"{m.some}"); + + # Assigning writes through a reference, and only a reference written as one + # points it elsewhere. + var a: i64 = 1; + var b: i64 = 2; + var r := &mut a; + val s := &mut b; + r = s; + r = &mut b; + r = 9; + println($"{a} {b}"); + + # A reference written as one is a pointer where one is expected. + var c := point { x = 3, y = 4 }; + val p: *mut point = &mut c; + p[0].y = 8; + val q := address(c); + println($"{c.y} {q[0].x} {through(q).y}"); +} diff --git a/tests/programs/references_reach_the_types_holding_them_1.out b/tests/programs/references_reach_the_types_holding_them_1.out new file mode 100644 index 00000000..d242ecf6 --- /dev/null +++ b/tests/programs/references_reach_the_types_holding_them_1.out @@ -0,0 +1 @@ +5 nodes, summing to 10 diff --git a/tests/programs/references_reach_the_types_holding_them_1.sakura b/tests/programs/references_reach_the_types_holding_them_1.sakura new file mode 100644 index 00000000..71653368 --- /dev/null +++ b/tests/programs/references_reach_the_types_holding_them_1.sakura @@ -0,0 +1,33 @@ +import std::io; + +# A type holding, within another type, a reference to itself: `node` holds a +# `maybe<&node>`. However the types are first met, each node holds all of its +# fields, and the list built holds every node, each linked to the one held +# before it. + +struct node { + var value: u64; + var next: maybe<&node>; +} + +def build(nodes: &mut node[5]): maybe<&node> { + var front: maybe<&node> = nothing {}; + for i in 0..5u { + nodes[i] = node { value = i, next = front }; + front = &nodes[i]; + } + return front; +} + +def main(): void { + var nodes: node[5]; + var at := build(&mut nodes); + var sum: u64 = 0; + var length: u64 = 0; + while at is some(&each) { + sum += each.value; + length++; + at = each.next; + } + io::println($"{length} nodes, summing to {sum}"); +} diff --git a/tests/programs/references_stay_where_they_cannot_be_kept_1.out b/tests/programs/references_stay_where_they_cannot_be_kept_1.out new file mode 100644 index 00000000..98dc4fe5 --- /dev/null +++ b/tests/programs/references_stay_where_they_cannot_be_kept_1.out @@ -0,0 +1 @@ +101 start end 8 8 8 shape{size = 3} shape{size = 0.5} 6 2 0 diff --git a/tests/programs/references_stay_where_they_cannot_be_kept_1.sakura b/tests/programs/references_stay_where_they_cannot_be_kept_1.sakura new file mode 100644 index 00000000..6bca8467 --- /dev/null +++ b/tests/programs/references_stay_where_they_cannot_be_kept_1.sakura @@ -0,0 +1,40 @@ +import std::io; +struct counter { var count: int; } +struct pair { var a: counter; var b: int; } +union shape { var none: bool; var size: f64; } +enum step { start, middle, end } +def step::next(&this): step { return match this { step::start => step::middle, else => step::end }; } +def even(c: &mut counter, n: int): void { if n > 0 { c.count += 2; odd(c, n - 1); } } +def odd(c: &mut counter, n: int): void { if n > 0 { c.count += 1; even(c, n - 1); } } +def set(v: &mut int, to: int): void { v = to; } +def bump(v: &mut int): void { v++; } +def copied(c: &counter): pair { return pair{ a = c, b = c.count }; } +def doubled(s: &mut shape): void { + match s { + size(&mut v) => { v = v * 2; } + none(b) => { } + } +} +def halved(s: &mut shape): void { if s is size(&mut v) { v = v / 4; } } +def deepest(c: &mut counter, n: int): &mut counter { return n == 0 ? c : deepest(c, n - 1); } +def word(text: span): int { return match text { "one" => 1, "two" => 2, else => 0 }; } +def main(): void { + var c := counter{0}; + even(&mut c, 5); + var at := step::start; + val later := at.next().next(); + var n := 1; + set(&mut n, 7); + bump(&mut n); + val p := copied(&c); + c.count = 100; + var s: shape = 1.5; + doubled(&mut s); + var t: shape = 2.0; + halved(&mut t); + deepest(&mut c, 3).count += 1; + var x := counter{5}; + val raw := &mut x as *mut counter; + x.count = 6; + println($"{c.count} {at} {later} {n} {p.a.count} {p.b} {s} {t} {(*raw).count} {word("two")} {word("six")}"); +} diff --git a/tests/programs/references_to_new_values_1.out b/tests/programs/references_to_new_values_1.out new file mode 100644 index 00000000..e6ac1bdb --- /dev/null +++ b/tests/programs/references_to_new_values_1.out @@ -0,0 +1,4 @@ +first 1 +second 2 +200 [1, 2] [1, 9] [1, 9] [1, 9] 6 6 +true diff --git a/tests/programs/references_to_new_values_1.sakura b/tests/programs/references_to_new_values_1.sakura new file mode 100644 index 00000000..ee8008da --- /dev/null +++ b/tests/programs/references_to_new_values_1.sakura @@ -0,0 +1,25 @@ +import std::io; +struct tally { var name: span; var count: int; } +val primary := &mut tally{ name = "primary" }; +def bump(t: &mut tally): void { t.count++; } +def run(name: span, body: def(&mut tally): void): void { + body(primary); + println($"{name} {primary.count}"); +} +def peek(n: &u8): u8 { return n; } +def grow(xs: &mut int[2]): int[2] { xs[1] = 9; return xs; } +def made(): int[2] { return [1, 0]; } +def main(): void { + run(&"first", bump); + run(&"second", bump); + var kept := [1, 2]; + var alias := kept; + val grown := grow(&mut alias); + val r := &mut 5; + r += 1; + val nested := &(&r); + var fresh := made(); + println($"{peek(&200)} {kept} {alias} {grown} {grow(&mut fresh)} {r} {nested}"); + val hello: span = "hello"; + println($"{hello.length > 0 && hello == "hello"}"); +} diff --git a/tests/programs/refined_functions_as_values_1.out b/tests/programs/refined_functions_as_values_1.out new file mode 100644 index 00000000..218058d9 --- /dev/null +++ b/tests/programs/refined_functions_as_values_1.out @@ -0,0 +1 @@ +15 6 49 5 5 102 610 go reading{value = value{text = yes}} no text reading{value = value{real = 1.5}} 9 9 diff --git a/tests/programs/refined_functions_as_values_1.sakura b/tests/programs/refined_functions_as_values_1.sakura new file mode 100644 index 00000000..3738ee6f --- /dev/null +++ b/tests/programs/refined_functions_as_values_1.sakura @@ -0,0 +1,47 @@ +import std::io; +struct failure { val message: span; } +union value { var whole: int; var real: float; var text: span; } +union reading { var value: value; var failure: failure; } +union callable { var failure: failure; var call: def(int): int; } +struct counter { var count: int; } +def counter::add(this: &mut counter, by: int): int { this.count += by; return this.count; } +def apply(f: def(int): int, x: int): int { return f(x); } +def read(text: span, fail: bool): reading { + return fail ? reading{ failure = failure{ message = text } } : reading{ value = value{ text = text } }; +} +def shown(given: &value): string { return given is text ? given.text : "other"; } +# A closure refers to the locals it uses, so what outlives the function making it +# holds what it uses itself, as a functor. +struct adding : invokable { var local: counter; } +def adding::invoke(&mut this, by: int): int { return this.local.add(by); } +def taken(): adding { + return adding{ local = counter{ count = 100 } }; +} +struct command { val name: span; var run: def(&command): void = idle; } +def idle(cmd: &command): void {} +def main(): void { + def fib(n: int): int { return n < 2 ? n : fib(n - 1) + fib(n - 2); } + print($"{apply(def(x) => x * 3, 5)} {apply(def(x) { return x + 1; }, 5)} "); + val inferred := def(x: int) => x * x; + print($"{inferred(7)} "); + var c := counter{}; + val add := counter::add; + add(c, 2); + print($"{apply(def(x) => c.add(x), 3)} {c.count} "); + var kept := taken(); + kept(1); + print($"{kept(1)} "); + print($"{fib(15)} "); + var cmd := command{ name = "go" }; + cmd.run(&cmd); + cmd.run = def(me) => print($"{me.name} "); + cmd.run(&cmd); + val ok := read("yes", false); + val bad := read("no", true); + val v := value{ text = "text" }; + val nested := reading{ value = value{ real = 1.5 } }; + print($"{ok} {bad.failure.message} {shown(&v)} {nested} "); + val either := callable{ call = def(x) => x - 1 }; + val maybe: def(): int = c.count > 0 ? def() => 9 : def() => 0; + println($"{either.call(10)} {maybe()}"); +} diff --git a/tests/programs/reflection_reaches_declarations_by_name_1.out b/tests/programs/reflection_reaches_declarations_by_name_1.out new file mode 100644 index 00000000..c952d729 --- /dev/null +++ b/tests/programs/reflection_reaches_declarations_by_name_1.out @@ -0,0 +1,5 @@ +adds:=2 muls:second=6 doubles=42 +point x=3 y=4 sum()=7 twice=14 +red=0 green=4 blue=5 first=0 circle square none +a1 b3 3 variables counter 8 +point.x point.y point.sum point.twice point 9 false unions diff --git a/tests/programs/reflection_reaches_declarations_by_name_1.sakura b/tests/programs/reflection_reaches_declarations_by_name_1.sakura new file mode 100644 index 00000000..0be0489a --- /dev/null +++ b/tests/programs/reflection_reaches_declarations_by_name_1.sakura @@ -0,0 +1,59 @@ +import std::io; +@usage{ on = target::functions | target::constants } +struct check : attribute { val name: span = ""; val skip: bool = false; } +@usage{ many = true } +struct tag : attribute { val text: span; val weight: u8 = 1; } +struct other : attribute {} +struct nil {} +union shape { var none: nil; var circle: f64; var square: i64; } +struct point { var x: i64; var y: i64; } +def point::sum(&this): i64 { return this.x + this.y; } +val point::twice: i64 { get => this.sum() * 2; } +type spot = point; +enum color: u8 { red, green = 4, blue, first = color::red } +def doubled(x: T): T where T: numeric { return x + x; } +@check def adds(): i64 { return 1 + 1; } +@check{ name = "second" } def muls(): i64 { return 2 * 3; } +@check{ skip = true } def skipped(): i64 { return 0; } +@check const doubles := doubled::; +@tag{ text = "a" } @other @tag{ text = "b", weight = 3 } +var counter: i64 = 0; +def which(s: shape): span { + for const f in members_of(decl_of::()) { + if s is (f) { return f.name; } + } + return "?"; +} +def show(x: &T): void { + print(name_of::()); + for const f in members_of(decl_of::()) { + if const f.kind == target::fields { print($" {f.name}={x.(f)}"); } + if const f.kind == target::methods { print($" {f.name}()={x.(f)()}"); } + if const f.kind == target::properties { print($" {f.name}={x.(f)}"); } + } + println(""); +} +def main(): void { + for const d in declarations() { + if const attached::(d).length == 0 { continue; } + val found := attached::(d)[0]; + if found.skip { continue; } + if const d.kind == target::functions { print($"{d.name}:{found.name}={value_of(d)()} "); } + if const d.kind == target::constants { print($"{d.name}={value_of(d)(21)} "); } + } + println(""); + show(&point{ x = 3, y = 4 }); + for const m in members_of(decl_of::()) { print($"{m.name}={value_of(m) as u8} "); } + println($"{which(shape{ circle = 1.5 })} {which(shape{ square = 2 })} {which(shape{})}"); + for const d in declarations() { + if const attached::(d).length == 0 { continue; } + val tags := attached::(d); + for i in 0..tags.length { print($"{tags[i].text}{tags[i].weight} "); } + value_of(d) = 7; + value_of(d) += 1; + println($"{attributes_of(d).length} {d.kind} {d.path} {counter}"); + } + for const m in members_of(decl_of::()) { print($"{owner_of(m).name}.{m.name} "); } + val here := decl_of::(); + println($"{here.name} {here.at.line} {here.exported} {decl_of::().kind}"); +} diff --git a/tests/programs/reflection_spells_types_and_instances_1.out b/tests/programs/reflection_spells_types_and_instances_1.out new file mode 100644 index 00000000..13d4a698 --- /dev/null +++ b/tests/programs/reflection_spells_types_and_instances_1.out @@ -0,0 +1,3 @@ +name:parameters:span times:parameters:int def(span, int): int 6 +twice 42 2.5 +this:&mut box bump by:int bump 4 4 true diff --git a/tests/programs/reflection_spells_types_and_instances_1.sakura b/tests/programs/reflection_spells_types_and_instances_1.sakura new file mode 100644 index 00000000..19042aef --- /dev/null +++ b/tests/programs/reflection_spells_types_and_instances_1.sakura @@ -0,0 +1,23 @@ +import std::io; +struct mark : attribute {} +struct box { var n: i64; } +def box::bump(&mut this, by: i64): void { this.n += by; } +@mark def greet(name: span, times: i64): i64 { return name.length as i64 * times; } +@mark def twice(x: T): T where T: numeric { return x + x; } +def parse(text: span): T where T: integer { return text.length as T; } +struct row { var a: i64; var b: u8; } +def main(): void { + for const d in declarations() { + if const attached::(d).length == 0 { continue; } + if const d.generic { println($"{d.name} {value_of(d)::(21)} {value_of(d)::(1.25)}"); continue; } + for const p in params_of(d) { print($"{p.name}:{p.kind}:{name_of::()} "); } + val f: type_of(d) = value_of(d); + println($"{name_of::()} {f("abc", 2)}"); + } + for const m in members_of(decl_of::()) { + for const p in params_of(m) { print($"{p.name}:{name_of::()} {owner_of(p).name} "); } + } + var r: row; + for const f in members_of(decl_of::()) { r.(f) = parse::("abcd"); } + println($"{r.a} {r.b} {r.b is u8}"); +} diff --git a/tests/programs/signature_bounds_hold_wherever_their_parameter_is_declared_1.out b/tests/programs/signature_bounds_hold_wherever_their_parameter_is_declared_1.out new file mode 100644 index 00000000..7a32453a --- /dev/null +++ b/tests/programs/signature_bounds_hold_wherever_their_parameter_is_declared_1.out @@ -0,0 +1,3 @@ +9 +21 +5 diff --git a/tests/programs/signature_bounds_hold_wherever_their_parameter_is_declared_1.sakura b/tests/programs/signature_bounds_hold_wherever_their_parameter_is_declared_1.sakura new file mode 100644 index 00000000..f22edbda --- /dev/null +++ b/tests/programs/signature_bounds_hold_wherever_their_parameter_is_declared_1.sakura @@ -0,0 +1,31 @@ +import std::io; + +# A pattern given a type parameter that is a `signature`, as `invokable`, finds +# it bounded wherever `S` is declared among the parameters: before the one the +# pattern bounds, or after. + +def before(f: &mut F, args: S::params...): S::result where S: signature where F: invokable { + return f(...args); +} + +def after(f: &mut F, args: S::params...): S::result where F: invokable where S: signature { + return f(...args); +} + +struct scale : invokable { var by: i64; } + +def scale::invoke(&mut this, a: i64, b: i64): i64 { + return (a + b) * this.by; +} + +def joined(a: strview, b: strview): u64 { + return a.length + b.length; +} + +def main(): void { + var s := scale { by = 3 }; + var j := joined; + println($"{before::(&mut s, 1, 2)}"); + println($"{after::(&mut s, 3, 4)}"); + println($"{after::(&mut j, "abc", "de")}"); +} diff --git a/tests/programs/signatures_1.out b/tests/programs/signatures_1.out new file mode 100644 index 00000000..188c89ff --- /dev/null +++ b/tests/programs/signatures_1.out @@ -0,0 +1,8 @@ +int of def(int, int): int +int of def(int...): int +string of def(strview): string +3 6 0 +hi you +3 9 hits 2 +wrapped +0 6 hits 2 diff --git a/tests/programs/signatures_1.sakura b/tests/programs/signatures_1.sakura new file mode 100644 index 00000000..a6e106da --- /dev/null +++ b/tests/programs/signatures_1.sakura @@ -0,0 +1,45 @@ +import std::io; + +# A pattern parameter, given a signature whole. +trait handler { + def handle(&mut this, args: Ts...): R; +} + +# What a signature names of a function type: its result, and its parameters. +def gives(f: F): string where F: signature { + return $"{name_of::()} of {name_of::()}"; +} + +# A function over any signature, forwarding its arguments. +def forward(f: F, args: F::params...): F::result where F: signature { + return f(...args); +} + +# A functor over any signature, which calls the function it holds. +struct wrapped : handler where F: signature { + var call: F; + var hits: i64; +} +def wrapped::handle(&mut this, args: F::params...): F::result { + this.hits += 1; + return this.call(...args); +} + +def sum(xs: i64...): i64 { var t: i64 = 0; for x in xs { t += x; } return t; } +def add(a: i64, b: i64): i64 { return a + b; } +def greet(name: strview): string { return $"hi {name}"; } + +def run(h: &mut handler): i64 { return h.handle(4, 5); } + +def main(): void { + println(gives(add)); + println(gives(sum)); + println(gives(greet)); + println($"{forward(add, 1, 2)} {forward(sum, 1, 2, 3)} {forward(sum)}"); + println(forward(greet, "you")); + var w := wrapped::{ call = add, hits = 0 }; + println($"{w.handle(1, 2)} {run(w)} hits {w.hits}"); + println(name_of::>()); + var s := wrapped::{ call = sum, hits = 0 }; + println($"{s.handle()} {s.handle(1, 2, 3)} hits {s.hits}"); +} diff --git a/tests/programs/simd_lanes_agree_everywhere_1.out b/tests/programs/simd_lanes_agree_everywhere_1.out new file mode 100644 index 00000000..330d9dfd --- /dev/null +++ b/tests/programs/simd_lanes_agree_everywhere_1.out @@ -0,0 +1,1205 @@ +compiled 4 -6 0.75 4 43690 +f32x4 +a 000080ff00002040000020400000003f +b 0000807f00004040cd8c0ec30000e8c0 +add 0000c0ff0000b040cd0c0cc30000d8c0 +sub 000080ff000000bfcd0c11430000f840 +mul 000080ff0000f0400030b2c3000068c0 +negate 0000807f000020c0000020c0000000bf +min 000080ff00002040cd8c0ec30000e8c0 +max 0000807f00004040000020400000003f +abs 0000807f00002040000020400000003f +fma 0000c07f0000a04000b0b2c3000080ff +equal 0 false false true 0 maybe{none = nothing{}} +equal_self 15 true true false 4 maybe{some = 0} +not_equal 15 true true false 4 maybe{some = 0} +less 3 true false false 2 maybe{some = 0} +less_equal 3 true false false 2 maybe{some = 0} +greater 12 true false false 2 maybe{some = 2} +greater_equal 12 true false false 2 maybe{some = 2} +greater_self 15 true true false 4 maybe{some = 0} +select 000080ff00002040cd8c0ec30000e8c0 +select_not 0000807f00004040000020400000003f +sum -inf smallest -inf largest 2.5 +div 0000c0ff5555553f3cab8fbccb3d8dbd +sqrt 0000c0ffc262ca3fc262ca3ff304353f +floor 000080ff000000400000004000000000 +ceil 000080ff00004040000040400000803f +trunc 000080ff000000400000004000000000 +round 000080ff00004040000040400000803f +round_even 000080ff000000400000004000000000 +a 0000c07fe73bcfc200000080000020c0 +b 502543c4000080ffcbb114440000c07f +add 0000c07f000080ffcbb114440000c07f +sub 0000c07f0000807fcbb114c40000c07f +mul 0000c07f0000807f000000800000c07f +negate 0000c0ffe73bcf420000000000002040 +min 0000c07f000080ff000000800000c07f +max 0000c07fe73bcfc2cbb114440000c07f +abs 0000c07fe73bcf420000000000002040 +fma 0000c07f0000807f000080bf0000c07f +equal 0 false false true 0 maybe{none = nothing{}} +equal_self 14 true false false 3 maybe{some = 1} +not_equal 15 true true false 4 maybe{some = 0} +less 4 true false false 1 maybe{some = 2} +less_equal 4 true false false 1 maybe{some = 2} +greater 2 true false false 1 maybe{some = 1} +greater_equal 2 true false false 1 maybe{some = 1} +greater_self 14 true false false 3 maybe{some = 1} +select 502543c4000080ff000000800000c07f +select_not 0000c07fe73bcfc2cbb11444000020c0 +sum nan smallest nan largest nan +div 0000c07f00000000000000800000c07f +sqrt 0000c07f0000c0ff000000800000c0ff +floor 0000c07f0000d0c200000080000040c0 +ceil 0000c07f0000cec200000080000000c0 +trunc 0000c07f0000cec200000080000000c0 +round 0000c07f0000d0c200000080000040c0 +round_even 0000c07f0000d0c200000080000000c0 +f32x8 +a 000080ff0000807f000020c0010000000000807f000080ff0000803f00002040 +b 00004040000080bf000000000000c07f0000803f000040400000807f0000e8c0 +add 000080ff0000807f000020c00000c07f0000807f000080ff0000807f000098c0 +sub 000080ff0000807f000020c00000c07f0000807f000080ff000080ff00001c41 +mul 000080ff000080ff000000800000c07f0000807f000080ff0000807f000091c1 +negate 0000807f000080ff0000204001000080000080ff0000807f000080bf000020c0 +min 000080ff000080bf000020c00000c07f0000803f000080ff0000803f0000e8c0 +max 000040400000807f000000000000c07f0000807f000040400000807f00002040 +abs 0000807f0000807f00002040010000000000807f0000807f0000803f00002040 +fma 000080ff000080ff000020c00000c07f0000807f000080ff0000807f000089c1 +equal 0 false false true 0 maybe{none = nothing{}} +equal_self 255 true true false 8 maybe{some = 0} +not_equal 255 true true false 8 maybe{some = 0} +less 101 true false false 4 maybe{some = 0} +less_equal 101 true false false 4 maybe{some = 0} +greater 146 true false false 3 maybe{some = 1} +greater_equal 146 true false false 3 maybe{some = 1} +greater_self 255 true true false 8 maybe{some = 0} +select 000080ff000080bf000020c00000c07f0000803f000080ff0000803f0000e8c0 +select_not 000040400000807f00000000010000000000807f000040400000807f00002040 +sum nan smallest -inf largest inf +div 000080ff000080ff000080ff0000c07f0000807f000080ff000000003e8db0be +sqrt 0000c0ff0000807f0000c0fff304351a0000807f0000c0ff0000803fc262ca3f +floor 000080ff0000807f000040c0000000000000807f000080ff0000803f00000040 +ceil 000080ff0000807f000000c00000803f0000807f000080ff0000803f00004040 +trunc 000080ff0000807f000000c0000000000000807f000080ff0000803f00000040 +round 000080ff0000807f000040c0000000000000807f000080ff0000803f00004040 +round_even 000080ff0000807f000000c0000000000000807f000080ff0000803f00000040 +a 000000000000204000002040000040406dc7f343000080bf000000800000807f +b 000020c0000080bf000020c00000c07f00000080000040400000c07f000080ff +add 000020c00000c03f000000000000c07f6dc7f343000000400000c07f0000c0ff +sub 00002040000060400000a0400000c07f6dc7f343000080c00000c07f0000807f +mul 00000080000020c00000c8c00000c07f00000080000040c00000c07f000080ff +negate 00000080000020c0000020c0000040c06dc7f3c30000803f00000000000080ff +min 000020c0000080bf000020c00000c07f00000080000080bf0000c07f000080ff +max 0000000000002040000020400000c07f6dc7f343000040400000c07f0000807f +abs 000000000000204000002040000040406dc7f3430000803f000000000000807f +fma 000040400000c0bf0000807f0000c07f000080bfe15a41c40000c07f000080ff +equal 0 false false true 0 maybe{none = nothing{}} +equal_self 255 true true false 8 maybe{some = 0} +not_equal 255 true true false 8 maybe{some = 0} +less 32 true false false 1 maybe{some = 5} +less_equal 32 true false false 1 maybe{some = 5} +greater 151 true false false 5 maybe{some = 0} +greater_equal 151 true false false 5 maybe{some = 0} +greater_self 255 true true false 8 maybe{some = 0} +select 000020c0000080bf000020c00000c07f00000080000080bf0000c07f000080ff +select_not 000000000000204000002040000040406dc7f34300004040000000800000807f +sum inf smallest -1 largest inf +div 00000080000020c0000080bf0000c07f000080ffabaaaabe0000c07f0000c0ff +sqrt 00000000c262ca3fc262ca3fd7b3dd3f4ea5b0410000c0ff000000800000807f +floor 000000000000004000000040000040400080f343000080bf000000800000807f +ceil 000000000000404000004040000040400000f443000080bf000000800000807f +trunc 000000000000004000000040000040400080f343000080bf000000800000807f +round 000000000000404000004040000040400000f443000080bf000000800000807f +round_even 000000000000004000000040000040400000f443000080bf000000800000807f +f64x2 +a b96a37ad01d6963696438b6ce7868ac0 +b 0000000000000440b96a37ad01d69636 +add 000000000000044096438b6ce7868ac0 +sub 00000000000004c096438b6ce7868ac0 +mul 67458518828bac36a82014aa26ee32b7 +negate b96a37ad01d696b696438b6ce7868a40 +min b96a37ad01d6963696438b6ce7868ac0 +max 0000000000000440b96a37ad01d69636 +abs b96a37ad01d6963696438b6ce7868a40 +fma 00000000000004c000000000000004c0 +equal 0 false false true 0 maybe{none = nothing{}} +equal_self 3 true true false 2 maybe{some = 0} +not_equal 3 true true false 2 maybe{some = 0} +less 3 true true false 2 maybe{some = 0} +less_equal 3 true true false 2 maybe{some = 0} +greater 0 false false true 0 maybe{none = nothing{}} +greater_equal 0 false false true 0 maybe{none = nothing{}} +greater_self 3 true true false 2 maybe{some = 0} +select b96a37ad01d6963696438b6ce7868ac0 +select_not 0000000000000440b96a37ad01d69636 +sum -848.863 smallest -848.863 largest 1e-45 +div 61552c24ce448236c7c319ab0a96e2c9 +sqrt 2489eb3d631d433b000000000000f8ff +floor 00000000000000000000000000888ac0 +ceil 000000000000f03f0000000000808ac0 +trunc 00000000000000000000000000808ac0 +round 00000000000000000000000000888ac0 +round_even 00000000000000000000000000888ac0 +a 000000000000e03f0000000000000440 +b 78be9f1a2f517b40000000000000f07f +add 78be9f1a2f597b40000000000000f07f +sub 78be9f1a2f497bc0000000000000f0ff +mul 78be9f1a2f516b40000000000000f07f +negate 000000000000e0bf00000000000004c0 +min 000000000000e03f0000000000000440 +max 78be9f1a2f517b40000000000000f07f +abs 000000000000e03f0000000000000440 +fma 78be9f1a2f716b40000000000000f07f +equal 0 false false true 0 maybe{none = nothing{}} +equal_self 3 true true false 2 maybe{some = 0} +not_equal 3 true true false 2 maybe{some = 0} +less 3 true true false 2 maybe{some = 0} +less_equal 3 true true false 2 maybe{some = 0} +greater 0 false false true 0 maybe{none = nothing{}} +greater_equal 0 false false true 0 maybe{none = nothing{}} +greater_self 3 true true false 2 maybe{some = 0} +select 000000000000e03f0000000000000440 +select_not 78be9f1a2f517b40000000000000f07f +sum 3 smallest 0.5 largest 2.5 +div 3e2a208e29be523f0000000000000000 +sqrt cd3b7f669ea0e63f535bda3a584cf93f +floor 00000000000000000000000000000040 +ceil 000000000000f03f0000000000000840 +trunc 00000000000000000000000000000040 +round 000000000000f03f0000000000000840 +round_even 00000000000000000000000000000040 +f64x4 +a 000000000000f07f000000000000f03f0000000000001dc0002085eb51b8e2bf +b 000000000000f87f0000000000001dc09c7500883ce4377e00000000000004c0 +add 000000000000f87f00000000000019c09c7500883ce4377e0048e17a14ae08c0 +sub 000000000000f87f00000000008020409c7500883ce437fe00703d0ad7a3fe3f +mul 000000000000f87f0000000000001dc0956a40dbd6a665fe006866666666f73f +negate 000000000000f0ff000000000000f0bf0000000000001d40002085eb51b8e23f +min 000000000000f87f0000000000001dc00000000000001dc000000000000004c0 +max 000000000000f87f000000000000f03f9c7500883ce4377e002085eb51b8e2bf +abs 000000000000f07f000000000000f03f0000000000001d40002085eb51b8e23f +fma 000000000000f87f00000000000011c0956a40dbd6a665fe9c7500883ce4377e +equal 0 false false true 0 maybe{none = nothing{}} +equal_self 15 true true false 4 maybe{some = 0} +not_equal 15 true true false 4 maybe{some = 0} +less 4 true false false 1 maybe{some = 2} +less_equal 4 true false false 1 maybe{some = 2} +greater 10 true false false 2 maybe{some = 1} +greater_equal 10 true false false 2 maybe{some = 1} +greater_self 15 true true false 4 maybe{some = 0} +select 000000000000f87f0000000000001dc00000000000001dc000000000000004c0 +select_not 000000000000f07f000000000000f03f9c7500883ce4377e002085eb51b8e2bf +sum inf smallest -7.25 largest inf +div 000000000000f87f967b1a61b9a7c1bf889cb1c8cc6bd381cdcca145b6f3cd3f +sqrt 000000000000f07f000000000000f03f000000000000f8ff000000000000f8ff +floor 000000000000f07f000000000000f03f00000000000020c0000000000000f0bf +ceil 000000000000f07f000000000000f03f0000000000001cc00000000000000080 +trunc 000000000000f07f000000000000f03f0000000000001cc00000000000000080 +round 000000000000f07f000000000000f03f0000000000001cc0000000000000f0bf +round_even 000000000000f07f000000000000f03f0000000000001cc0000000000000f0bf +a 00000000000000000000000000001dc0000000000000f0ff000000000000f03f +b 000000000000f0bf0000000000001dc0000000000000e03f000000000000f87f +add 000000000000f0bf0000000000002dc0000000000000f0ff000000000000f87f +sub 000000000000f03f0000000000000000000000000000f0ff000000000000f87f +mul 00000000000000800000000000484a40000000000000f0ff000000000000f87f +negate 00000000000000800000000000001d40000000000000f07f000000000000f0bf +min 000000000000f0bf0000000000001dc0000000000000f0ff000000000000f87f +max 00000000000000000000000000001dc0000000000000e03f000000000000f87f +abs 00000000000000000000000000001d40000000000000f07f000000000000f03f +fma 00000000000008400000000000c84b40000000000000f0ff000000000000f87f +equal 2 true false false 1 maybe{some = 1} +equal_self 15 true true false 4 maybe{some = 0} +not_equal 13 true false false 3 maybe{some = 0} +less 4 true false false 1 maybe{some = 2} +less_equal 6 true false false 2 maybe{some = 1} +greater 1 true false false 1 maybe{some = 0} +greater_equal 3 true false false 2 maybe{some = 0} +greater_self 15 true true false 4 maybe{some = 0} +select 000000000000f0bf0000000000001dc0000000000000f0ff000000000000f87f +select_not 00000000000000000000000000001dc0000000000000e03f000000000000f03f +sum -inf smallest -inf largest 1 +div 0000000000000080000000000000f03f000000000000f0ff000000000000f87f +sqrt 0000000000000000000000000000f8ff000000000000f8ff000000000000f03f +floor 000000000000000000000000000020c0000000000000f0ff000000000000f03f +ceil 00000000000000000000000000001cc0000000000000f0ff000000000000f03f +trunc 00000000000000000000000000001cc0000000000000f0ff000000000000f03f +round 00000000000000000000000000001cc0000000000000f0ff000000000000f03f +round_even 00000000000000000000000000001cc0000000000000f0ff000000000000f03f +i8x16 +a 01e10229e4a3a63f240275013e028fc4 +b 213ff4fb02e6baff01007bd2ff998830 +add 2220f624e689603e2502f0d33d9b17f4 +sub e0a20e2ee2bdec402302fa2f3f690794 +mul 215fe833c8729cc1240037d2c232f8c0 +negate ff1ffed71c5d5ac1dcfe8bffc2fe713c +min 01e1f4fbe4a3a6ff010075d2ff9988c4 +max 213f022902e6ba3f24027b013e028f30 +abs 011f02291c5d5a3f240275013e02713c +fma be913fabca873d16ca398137c1aff9c1 +equal 0 false false true 0 maybe{none = nothing{}} +equal_self 65535 true true false 16 maybe{some = 0} +not_equal 65535 true true false 16 maybe{some = 0} +less 33907 true false false 7 maybe{some = 0} +less_equal 33907 true false false 7 maybe{some = 0} +greater 31628 true false false 9 maybe{some = 2} +greater_equal 31628 true false false 9 maybe{some = 2} +greater_self 65535 true true false 16 maybe{some = 0} +select 01e1f4fbe4a3a6ff010075d2ff9988c4 +select_not 213f022902e6ba3f24027b013e028f30 +sum -88 smallest -113 largest 117 +div 0000000200ff01fe0c003a000100c8ff +and 0121002900a2a23f000071003e008800 +or 21fff6fbe6e7beff25027fd3ff9b8ff4 +xor 20def6d2e6451cc025020ed3c19b07f4 +not fe1efdd61b5c59c0dbfd8afec1fd703b +shl 01e10229e4a3a63f240275013e028fc4 +shr 01e10229e4a3a63f240275013e028fc4 +shl2 80800080008000800000808000008000 +shr2 00ff0000ffffff00000000000000ffff +a 060099ac156701376bc0ffcb98eb2f01 +b 0e00d50201e502c04002f502010b31ff +add 14006eae164c03f7abc2f4cd99f66000 +sub f800c4aa1482ff772bbe0ac997e0fe02 +mul 54004d5815230240c0800b969819ffff +negate fa006754eb99ffc9954001356815d1ff +min 060099ac01e501c040c0f5cb98eb2fff +max 0e00d502156702376b02ff02010b3101 +abs 06006754156701376b40013568152f01 +fma 1c73b45953f54dc622900b98f81489ab +equal 2 true false false 1 maybe{some = 1} +equal_self 65535 true true false 16 maybe{some = 0} +not_equal 65533 true false false 15 maybe{some = 0} +less 31309 true false false 9 maybe{some = 0} +less_equal 31311 true false false 10 maybe{some = 0} +greater 34224 true false false 6 maybe{some = 4} +greater_equal 34226 true false false 7 maybe{some = 1} +greater_self 65535 true true false 16 maybe{some = 0} +select 060099ac01e501c040c0f5cb98eb2fff +select_not 0e00d502156702376b02ff02010b3101 +sum -89 smallest -104 largest 107 +div 000067010067001235eb003500150f00 +and 06009100016500004000f502000b2101 +or 0e00ddae15e703f76bc2ffcb99eb3fff +xor 08004cae148203f72bc20ac999e01efe +not f9ff6653ea98fec8943f00346714d0fe +shl 0c0032582ace026ed680fe9630d65e02 +shr 0300ccd60a33001b35e0ffe5ccf51700 +shl2 00000000000000000000000000000000 +shr2 0000ffff0000000000ffffffffff0000 +i8x32 +a 8b00013a8531b6018cbd02344b97aeff0f9d97c3f8ffdea948677ec7aaff02ff +b 026f014a3fff4c00026531ff540059ff7aa28129b99300023687843d67ffa7fe +add 8d6f0284c43002018e2233339f9707fe893f18ecb192deab7eee020411fea9fd +sub 899100f046326a018a58d135f797550095fb169a3f6cdea712e0fa8a43005b01 +mul 160001c4bbcf0800189162cc9c007e01265a173b386d00523051f86b66014e02 +negate 7500ffc67bcf4aff7443feccb5695201f163693d08012257b89982395601fe01 +min 8b00013a85ffb6008cbd02ff4b97aeff0f9d81c3b993dea9368784c7aaffa7fe +max 026f014a3f314c0102653134540059ff7aa29729f8ff000248677e3d67ff02ff +abs 7500013a7b314a01744302344b6952010f63693d0801225748677e3956010201 +fma fcffeb6c1acfa899e4df6455c6eb6fed2759c2103bc1d39a304d7d6b2f012f02 +equal 536903684 true false false 3 maybe{some = 2} +equal_self 4294967295 true true false 32 maybe{some = 0} +not_equal 3758063611 true false false 29 maybe{some = 0} +less 415987547 true false false 18 maybe{some = 0} +less_equal 952891231 true false false 21 maybe{some = 0} +greater 3342076064 true false false 11 maybe{some = 5} +greater_equal 3878979748 true false false 14 maybe{some = 2} +greater_self 4294967295 true true false 32 maybe{some = 0} +select 8b00013a85ffb6008cbd02ff4b97aeff0f9d81c3b993dea9368784c7aaffa7fe +select_not 026f014a3f314c0102653134540059ff7aa29729f8ff000248677e3d67ff02ff +sum 99 smallest -123 largest 126 +div ff0000020110ff00040000ffff0aff000563020000000006fffe04edfd000000 +and 0200010a0531040000250034400008ff0a808101b89300000007040522ff02fe +or 8b6f017abffffe018efd33ff5f97ffff7fbf97ebf9ffdeab7ee7feffefffa7ff +xor 896f0070bacefa018ed833cb1f97f700753f16ea416cdeab7ee0fafacd00a501 +not 74fffec57ace49fe7342fdcbb4685100f062683c07002156b79881385500fd00 +shl 8b00013a8531b6018cbd02344b97aeff0f9d97c3f8ffdea948677ec7aaff02ff +shr 8b00013a8531b6018cbd02344b97aeff0f9d97c3f8ffdea948677ec7aaff02ff +shl2 8000800080800080008000008080008080808080008000800080008000800080 +shr2 ff000000ff00ff00ffff000000ffffff00ffffffffffffff000000ffffff00ff +a 02b5b0c6930dcc01ffea8affd0330127fc34907560bdfb0208009b0202f3f692 +b 7326a3229b05ffde39010266003b0102f001018d248eff00f64a00b780a186ff +add 75db53e82e12cbdf38eb8c65d06e0229ec359102844bfa02fe4a9bb982947c91 +sub 8f8f0da4f808cd23c6e98899d0f800250c338fe83c2ffc0212b69b4b82527093 +mul e6de104c014134dec7ea149a00c1014e4034907180d60500b000006e00d3c46e +negate fe4b503a6df334ff0116760130cdffd904cc708ba04305fef80065fefe0d0a6e +min 02b5a3c69305ccdeffea8affd0330102f001908d248efb00f6009bb780a18692 +max 7326b0229b0dff0139010266003b0127fc34017560bdff02084a000202f3f6ff +abs 024b503a6d0d34010116760130330127043470756043050208006502020d0a6e +fma 8905ba4bd31d356ceb8d43b9e3fa00821c1491e8a6d830614549155f9f8667ca +equal 16384 true false false 1 maybe{some = 14} +equal_self 4294967295 true true false 32 maybe{some = 0} +not_equal 4294950911 true false false 31 maybe{some = 0} +less 2252619611 true false false 16 maybe{some = 0} +less_equal 2252635995 true false false 17 maybe{some = 0} +greater 2042331300 true false false 15 maybe{some = 2} +greater_equal 2042347684 true false false 16 maybe{some = 2} +greater_self 4294967295 true true false 32 maybe{some = 0} +select 02b5a3c69305ccdeffea8affd0330102f001908d248efb00f6009bb780a18692 +select_not 7326b0229b0dff0139010266003b0127fc34017560bdff02084a000202f3f6ff +sum -88 smallest -118 largest 117 +div 00ff0100eb00fa000000ffff03000027001190fc60000000ff00650000000000 +and 0224a0029305cc003900026600330102f0000005208cfb000000000200a18692 +or 73b7b3e69b0dffdfffeb8affd03b0127fc3591fd64bfff02fe4a9bb782f3f6ff +xor 719313e4080833dfc6eb8899d00800250c3591f844330402fe4a9bb58252706d +not fd4a4f396cf233fe001575002fccfed803cb6f8a9f4204fdf7ff64fdfd0c096d +shl 046a608c261a9802fed414fea066024ef86820eac07af6041000360404e6ec24 +shr 01dad8e3c906e600fff5c5ffe8190013fe1ac83a30defd010400cd0101f9fbc9 +shl2 0000000000000000000000000000000000000000000000000000000000000000 +shr2 00ffffffff00ff00ffffffffff000000ff00ff0000ffff000000ff0000ffffff +u8x16 +a 9385134e0050cbf6ff8801dd00883b90 +b ff1a024f01d7f302a50002e0ffd11bff +add 929f159d0127bef8a48803bdff59568f +sub 946b11ffff79d8f45a88fffd01b72091 +mul 6d8226120030b1ec5b00026000083970 +negate 6d7bedb200b0350a0178ff230078c570 +min 931a024e0050cb02a50001dd00881b90 +max ff85134f01d7f3f6ff8802e0ffd13bff +abs 9385134e0050cbf6ff8801dd00883b90 +fma 043774f9093110ed7ae3f9620207ff6f +equal 0 false false true 0 maybe{none = nothing{}} +equal_self 65535 true true false 16 maybe{some = 0} +not_equal 65535 true true false 16 maybe{some = 0} +less 48249 true false false 10 maybe{some = 0} +less_equal 48249 true false false 10 maybe{some = 0} +greater 17286 true false false 6 maybe{some = 1} +greater_equal 17286 true false false 6 maybe{some = 1} +greater_self 65535 true true false 16 maybe{some = 0} +select 931a024e0050cb02a50001dd00881b90 +select_not ff85134f01d7f3f6ff8802e0ffd13bff +sum 66 smallest 0 largest 255 +div 0c2c00010000017b0201001200001d00 +and 9300024e0050c302a50000c000801b90 +or ff9f134f01d7fbf6ff8803fdffd93bff +xor 6c9f1101018738f45a88033dff59206f +not 6c7aecb1ffaf34090077fe22ff77c46f +shl 9385134e0050cbf6ff8801dd00883b90 +shr 9385134e0050cbf6ff8801dd00883b90 +shl2 80808000000080008000808000008000 +shr2 01010000000001010101000100010001 +a 0115a902e4934a026113f801ffbe47a2 +b 8b54ce2608c06d01a1f502ff11f16c00 +add 8c697728ec53b7030208fa0010afb3a2 +sub 76c1dbdcdcd3dd01c01ef602eecddba2 +mul 8be4fe4c20408202012ff0ffefdef400 +negate ffeb57fe1c6db6fe9fed08ff0142b95e +min 0115a90208934a016113020111be4700 +max 8b54ce26e4c06d02a1f5f8fffff16ca2 +abs 0115a902e4934a026113f801ffbe47a2 +fma 1bb0ccf3c7428c7fc869f235c5dfe695 +equal 0 false false true 0 maybe{none = nothing{}} +equal_self 65535 true true false 16 maybe{some = 0} +not_equal 65535 true true false 16 maybe{some = 0} +less 27503 true false false 11 maybe{some = 0} +less_equal 27503 true false false 11 maybe{some = 0} +greater 38032 true false false 5 maybe{some = 4} +greater_equal 38032 true false false 5 maybe{some = 4} +greater_self 65535 true true false 16 maybe{some = 0} +select 0115a90208934a016113020111be4700 +select_not 8b54ce26e4c06d02a1f5f8fffff16ca2 +sum 151 smallest 1 largest 255 +div 000000000d93000020000000013f0002 +and 01148802008048002111000111b04400 +or 8b55ef26ecd36f03e1f7faffffff6fa2 +xor 8a416724ec532703c0e6fafeee4f2ba2 +not feea56fd1b6cb5fd9eec07fe0041b85d +shl 022a5204c8269404c226f002fe7c8e44 +shr 000a54017249250130097c007f5f2351 +shl2 00000000000000000000000000000000 +shr2 00000000000000000000000000000000 +u8x32 +a 74eff040d0dccd9632d6cb00df00afda20948da093dd0000da01025d0150beff +b 68dbd22602015f7839954b5b624bb0d0cb7fb6ff02f8fdb53000b70800189d02 +add dccac266d2dd2c0e6b6b165b414b5faaeb13439f95d5fdb50a01b96501685b01 +sub 0c141e1acedb6e1ef94180a57db5ff0a5515d7a191e5034baa014b55013821fd +mul 2075e080a0dc1350228e79005e005020606c3e6026180000e0006ee8008086fe +negate 8c1110c03024336ace2a350021005126e06c73606d23000026fffea3ffb04201 +min 68dbd22602015f7832954b006200afd0207f8da002dd00003000020800189d02 +max 74eff040d0dccd9639d6cb5bdf4bb0dacb94b6ff93f8fdb5da01b75d0150beff +abs 74eff040d0dccd9632d6cb00df00afda20948da093dd0000da01025d0150beff +fma 01773710a12d1b8d81ff7a407000332061c2403ecf185f07ed01aeeaf386f7fd +equal 0 false false true 0 maybe{none = nothing{}} +equal_self 4294967295 true true false 32 maybe{some = 0} +not_equal 4294967295 true true false 32 maybe{some = 0} +less 82667776 true false false 11 maybe{some = 8} +less_equal 82667776 true false false 11 maybe{some = 8} +greater 4212299519 true false false 21 maybe{some = 0} +greater_equal 4212299519 true false false 21 maybe{some = 0} +greater_self 4294967295 true true false 32 maybe{some = 0} +select 68dbd22602015f7832954b006200afd0207f8da002dd00003000020800189d02 +select_not 74eff040d0dccd9639d6cb5bdf4bb0dacb94b6ff93f8fdb5da01b75d0150beff +sum 118 smallest 0 largest 255 +div 0104000168050200000100000e0001da00020000314900000600001200000103 +and 60cbd00000004d1030944b004200a0d0001484a002d800001000020800109c02 +or 7cfff266d2dddffe3bd7cb5bff4bbfdaebffbfff93fdfdb5fa01b75d0158bfff +xor 1c342266d2dd92ee0b43805bbd4b1f0aebeb3b5f9125fdb5ea01b555014823fd +not 8b100fbf2f233269cd2934ff20ff5025df6b725f6c22ffff25fefda2feaf4100 +shl 74eff040d0dccd9632d6cb00df00afda20948da093dd0000da01025d0150beff +shr 74eff040d0dccd9632d6cb00df00afda20948da093dd0000da01025d0150beff +shl2 0080000000008000000080008000800000008000808000000080008080000080 +shr2 0001010001010101000101000100010100010101010100000100000000000101 +a 5e02c10378024d014f4123ff8e0145f40102f2c135ff48ff02db003c3bffff02 +b 3ab59401ffff02b281004db1b819f28500ff0cecf2c0f3552e02ca6e5a8d79ff +add 98b7550477014fb3d04170b0461a37790101fead27bf3b5430ddcaaa958c7801 +sub 244d2d0279034b4fce41d64ed6e8536f0103e6d5433f55aad4d936cee1728603 +mul 4c6a940388fe9ab2cf00874f10193ac400fe58ec1a4058ab5cb600c8be7387fe +negate a2fe3ffd88feb3ffb1bfdd0172ffbb0cfffe0e3fcb01b801fe2500c4c50101fe +min 3a029401780202014f0023b18e01458500020cc135c048550202003c3b8d7902 +max 5eb5c103ffff4db281414dffb819f2f401fff2ecf2fff3ff2edbca6e5affffff +abs 5e02c10378024d014f4123ff8e0145f40102f2c135ff48ff02db003c3bffff02 +fma a19d5b05895813a2cf022a076d3d80c499d69c4ae64c92ad5cea605f46dc86c1 +equal 0 false false true 0 maybe{none = nothing{}} +equal_self 4294967295 true true false 32 maybe{some = 0} +not_equal 4294967295 true true false 32 maybe{some = 0} +less 2639951282 true false false 18 maybe{some = 1} +less_equal 2639951282 true false false 18 maybe{some = 1} +greater 1655016013 true false false 14 maybe{some = 0} +greater_equal 1655016013 true false false 14 maybe{some = 0} +greater_self 4294967295 true true false 32 maybe{some = 0} +select 3a029401780202014f0023b18e01458500020cc135c048550202003c3b8d7902 +select_not 5eb5c103ffff4db281414dffb819f2f401fff2ecf2fff3ff2edbca6e5affffff +sum 235 smallest 0 largest 255 +div 2f020100010007001a2000078e000201010150c11101000100010001017f0100 +and 1a00800178020000010001b188014084000200c030c040550202002c1a8d7902 +or 7eb7d503ffff4fb3cf416fffbe19f7f501fffeedf7fffbff2edbca7e7bffffff +xor 64b7550287fd4fb3ce416e4e3618b77101fdfe2dc73fbbaa2cd9ca52617286fd +not a1fd3efc87fdb2feb0bedc0071feba0bfefd0d3eca00b700fd24ffc3c40000fd +shl bc048206f0049a029e8246fe1c028ae80204e4826afe90fe04b6007876fefe04 +shr 2f0160013c0126002720117f4700227a000179601a7f247f016d001e1d7f7f01 +shl2 0000000000000000000000000000000000000000000000000000000000000000 +shr2 0000000000000000000000000000000000000000000000000000000000000000 +i16x8 +a f5320000ffff16f48603010056f02aa0 +b a9d7b6b30100ffff2cd6000001009016 +add 9e0ab6b3000015f4b2d9010057f0bab6 +sub 4c5b4a4cfeff17f45a2d010055f09a89 +mul bd660000ffffea0b089f000056f0a0b3 +negate 0bcd00000100ea0b7afcffffaa0fd65f +min a9d7b6b3ffff16f42cd6000056f02aa0 +max f53200000100ffff8603010001009016 +abs f53200000100ea0b86030100aa0fd65f +fma 2d2342135613eb0b089f8485caf9ea19 +equal 0 false false true 0 maybe{none = nothing{}} +equal_self 255 true true false 8 maybe{some = 0} +not_equal 255 true true false 8 maybe{some = 0} +less 204 true false false 4 maybe{some = 2} +less_equal 204 true false false 4 maybe{some = 2} +greater 51 true false false 4 maybe{some = 0} +greater_equal 51 true false false 4 maybe{some = 0} +greater_self 255 true true false 8 maybe{some = 0} +select a9d7b6b3ffff16f42cd6000056f02aa0 +select_not f53200000100ffff8603010001009016 +sum -17647 smallest -24534 largest 13045 +div 000000000000000000000000efff0000 +and a1120000010016f40402000000000000 +or fdf7b6b3ffffffffaed7010057f0bab6 +xor 5ce5b6b3feffe90baad5010057f0bab6 +not 0acdffff0000e90b79fcfeffa90fd55f +shl f5320000ffff16f48603010056f02aa0 +shr f5320000ffff16f48603010056f02aa0 +shl2 807a000080ff000b00c38000002b0015 +shr2 65000000ffffe8ff07000000e0ff40ff +a ffff000025f1d41de6e19e4344a8005e +b 4144f08ff6a56f0324bb02006f0a604e +add 4044f08f1b9743210a9da043b3b260ac +sub bebb10702f4b651ac2269c43d59da00f +mul bfbb00008e92ec6a58c63c877c9d0040 +negate 01000000db0e2ce21a1e62bcbc5700a2 +min fffff08ff6a56f0324bb020044a8604e +max 4144000025f1d41de6e19e436f0a005e +abs 01000000db0ed41d1a1e9e43bc57005e +fma e4382af58e92ad204731b9d57d9d0240 +equal 0 false false true 0 maybe{none = nothing{}} +equal_self 255 true true false 8 maybe{some = 0} +not_equal 255 true true false 8 maybe{some = 0} +less 65 true false false 2 maybe{some = 0} +less_equal 65 true false false 2 maybe{some = 0} +greater 190 true false false 6 maybe{some = 1} +greater_equal 190 true false false 6 maybe{some = 1} +greater_self 255 true true false 8 maybe{some = 0} +select fffff08ff6a56f0324bb020044a8604e +select_not 4144000025f1d41de6e19e436f0a005e +sum 15040 smallest -22460 largest 24064 +div 00000000fffffcff1a1e04000100002f +and 4144000024a1440124a102004408004e +or fffff08ff7f5ff1fe6fb9e436faa605e +xor bebbf08fd354bb1ec25a9c432ba26010 +not 0000ffffda0e2be2191e61bcbb57ffa1 +shl feff00004ae2a83bccc33c87885000bc +shr ffff000092f8ea0ef3f0cf2122d4002f +shl2 00800000008000000000000000000000 +shr2 ffff0000ffff0000ffff0000ffff0000 +i16x16 +a fdff0200a8d3b3ebbd33c7a1ca5ebe61d0cbdf5ba5bc8d544ef89212efd3eb4f +b 7340ffffffff020064f3020073d0ffff010002000000aba7308ce695330dc677 +add 70400100a7d3b5eb2127c9a13d2fbd61d1cbe15ba5bc38fc7e8478a822e1b1c7 +sub 8abf0300a9d3b1eb5940c5a1578ebf61cfcbdd5ba5bce2ac1e6cac7cbcc625d8 +mul a73efeff582c66d7d49c8e43beb4429ed0cbbeb700002f75a0362ca99d5bc20c +negate 0300feff582c4d1443cc395e36a1429e303421a45b4373abb2076eed112c15b0 +min fdffffffa8d3b3eb64f3c7a173d0ffffd0cb0200a5bcaba7308ce695efd3eb4f +max 73400200ffff0200bd330200ca5ebe610100df5b00008d544ef89212330dc677 +abs 03000200582c4d14bd33395eca5ebe613034df5b5b438d54b2079212112ceb4f +fma f39a8de3ef0e68d7ffb88d43a8071cb8b7d7beb79dba5c47b0b2fd4dc004c30c +equal 0 false false true 0 maybe{none = nothing{}} +equal_self 65535 true true false 16 maybe{some = 0} +not_equal 65535 true true false 16 maybe{some = 0} +less 50477 true false false 8 maybe{some = 0} +less_equal 50477 true false false 8 maybe{some = 0} +greater 15058 true false false 8 maybe{some = 1} +greater_equal 15058 true false false 8 maybe{some = 1} +greater_self 65535 true true false 16 maybe{some = 0} +select fdffffffa8d3b3eb64f3c7a173d0ffffd0cb0200a5bcaba7308ce695efd3eb4f +select_not 73400200ffff0200bd330200ca5ebe610100df5b00008d544ef89212330dc677 +sum -17151 smallest -24121 largest 25022 +div 0000000000002300de190100faffffffe8e5feff53de000006000000efd30400 +and 71400200a8d30200243302004250be610000020000008904008882102301c247 +or ffffffffffffb3ebfdf3c7a1fbdeffffd1cbdf5ba5bcaff77efcf697ffdfef7f +xor 8ebffdff572cb1ebd9c0c5a1b98e419ed1cbdd5ba5bc26f37e747487dcde2d38 +not 0200fdff572c4c1442cc385e35a1419e2f3420a45a4372abb1076ded102c14b0 +shl fdff0200a8d3b3ebbd33c7a1ca5ebe61d0cbdf5ba5bc8d544ef89212efd3eb4f +shr fdff0200a8d3b3ebbd33c7a1ca5ebe61d0cbdf5ba5bc8d544ef89212efd3eb4f +shl2 80fe000100d480d980de80e3006500df00e880ef805280460027004980f780f5 +shr2 ffff0000a7ffd7ff670043ffbd00c30097ffb70079ffa900f0ff2500a7ff9f00 +a 58c747254cc0b574e2d9010011bf079afffffcce01009f870000422dd7dddb26 +b 5620a9cc0000c737905c997610358403ffff1123bd08572b010042bb61e9ffff +add aee7f0f14cc07cac72369a7621f48b9dfeff0df2be08f6b2010084e838c7da26 +sub 02a79e584cc0ee3c527d6889018a83960000ebab44f7485cffff007276f4dc26 +mul 90f7df2f0000b39b20c7997610769c800100bc32bd0809cc000004e177bd25d9 +negate a838b9dab43f4b8b1e26ffffef40f96501000431ffff61780000bed2292225d9 +min 58c7a9cc4cc0c737e2d9010011bf079afffffcce01009f87000042bbd7ddffff +max 562047250000b574905c997610358403ffff1123bd08572b0100422d61e9db26 +abs a8384725b43fb5741e260100ef40f96501000431010061780000422d2922db26 +fma 92f74d4da963a77d014e0c2e40ad08eda0a39ed57eaee0d814d204e170b225d9 +equal 256 true false false 1 maybe{some = 8} +equal_self 65535 true true false 16 maybe{some = 0} +not_equal 65279 true false false 15 maybe{some = 0} +less 24309 true false false 11 maybe{some = 0} +less_equal 24565 true false false 12 maybe{some = 0} +greater 40970 true false false 4 maybe{some = 1} +greater_equal 41226 true false false 5 maybe{some = 1} +greater_self 65535 true true false 16 maybe{some = 0} +select 58c7a9cc4cc0c737e2d9010011bf079afffffcce01009f87000042bbd7ddffff +select_not 562047250000b574905c997610358403ffff1123bd08572b0100422d61e9db26 +sum -8918 smallest -30817 largest 29877 +div 00000c007f0007000000000000000200000000000000ffff000000000000ffff +and 50000104000085348058010010350402ffff1002010017030000422941c9db26 +or 5ee7efed4cc0f777f2dd997611bf879bfffffdefbd08dfaf010042bff7fdffff +xor 0ee7eee94cc0724372859876018a83990000ededbc08c8ac01000096b63424d9 +not a738b8dab33f4a8b1d26feffee40f86500000331feff6078ffffbdd2282224d9 +shl b08e8e4a98806ae9c4b30200227e0e34fefff89d02003e0f0000845aaebbb64d +shr ace3a31226e05a3af1ec000088df03cdffff7ee70000cfc30000a116ebee6d13 +shl2 0000008000000080000000800080008000800000008000800000000000800080 +shr2 ffff0000ffff0000ffff0000ffffffffffffffff0000ffff00000000ffff0000 +u16x8 +a 56d8564e38c82775fd824d298bd16d74 +b d620ad5132810000010000006273365b +add 2cf903a06a492775fe824d29ed44a3cf +sub 80b7a9fc06472775fc824d29295e3719 +mul e4971e26f0520000fd82000036a8fe4d +negate aa27aab1c837d98a037db3d6752e938b +min d620564e32810000010000006273365b +max 56d8ad5138c82775fd824d298bd16d74 +abs 56d8564e38c82775fd824d298bd16d74 +fma e4971e266f4b9ff87c40e6181f5f81bb +equal 0 false false true 0 maybe{none = nothing{}} +equal_self 255 true true false 8 maybe{some = 0} +not_equal 255 true true false 8 maybe{some = 0} +less 2 true false false 1 maybe{some = 1} +less_equal 2 true false false 1 maybe{some = 1} +greater 253 true false false 7 maybe{some = 0} +greater_equal 253 true false false 7 maybe{some = 0} +greater_self 255 true true false 8 maybe{some = 0} +select d620564e32810000010000006273365b +select_not 56d8ad5138c82775fd824d298bd16d74 +sum 22093 smallest 10573 largest 55382 +div 00000200010000000100a61401000000 +and 56000440308000000100000002512450 +or d6f8ff5f3ac92775fd824d29ebf37f7f +xor 80f8fb1f0a492775fc824d29e9a25b2f +not a927a9b1c737d88a027db2d6742e928b +shl 56d8564e38c82775fd824d298bd16d74 +shr 56d8564e38c82775fd824d298bd16d74 +shl2 002b002b001c8093807e80a680c58036 +shr2 b0019c009001ea0005015200a301e800 +a 2c3b168d178d9e11799fb30d6a770e91 +b 6f647538cbb9e48e600102000000199e +add 9b9f8bc5e24682a0d9a0b50d6a77272f +sub bdd6a1544cd3ba82199eb10d6a77f5f2 +mul 14d80e4b3d80b8546046661b00005ece +negate d4c4ea72e97262ee87604df29688f26e +min 2c3b7538178d9e116001020000000e91 +max 6f64168dcbb9e48e799fb30d6a77199e +abs 2c3b168d178d9e11799fb30d6a770e91 +fma 13fc965979dbc73361464b570200ef3b +equal 0 false false true 0 maybe{none = nothing{}} +equal_self 255 true true false 8 maybe{some = 0} +not_equal 255 true true false 8 maybe{some = 0} +less 141 true false false 4 maybe{some = 0} +less_equal 141 true false false 4 maybe{some = 0} +greater 114 true false false 4 maybe{some = 1} +greater_equal 114 true false false 4 maybe{some = 1} +greater_self 255 true true false 8 maybe{some = 0} +select 2c3b7538178d9e116001020000000e91 +select_not 6f64168dcbb9e48e799fb30d6a77199e +sum 7323 smallest 3507 largest 40825 +div 00000100030000000000000000000000 +and 2c201408038984006001020000000890 +or 6f7f77bddfbdfe9f799fb30d6a771f9f +xor 435f63b5dc347a9f199eb10d6a77170f +not d3c4e972e87261ee86604cf29588f16e +shl 58762c1a2e1a3c23f23e661bd4ee1c22 +shr 961d8b468b46cf08bc4fd906b53b8748 +shl2 00000000008000000080008000000000 +shr2 00000100010000000100000000000100 +u16x16 +a 2d68a2de3cb15ca2d81a508496f692723659dc017e2db9bc0000ffff02000200 +b fffff4c511f436907f60754486e8660fadf3789106505871059201000100ffff +add 2c6896a44da59232577bc5c81cdff881e34c5493847d112e0592000003000100 +sub 2e68ae182bbd261259badb3f100e2c638965647078dd614bfb6dfeff01000300 +mul d39768dcfcf468ff285190b884022c347e8b207bf47098880000ffff0200feff +negate d3975e21c44ea45d28e5b07b6a096e8dcaa624fe82d2474300000100fefffeff +min 2d68f4c53cb13690d81a754486e8660f3659dc017e2d58710000010001000200 +max ffffa2de11f45ca27f60508496f69272adf378910650b9bc0592ffff0200ffff +abs 2d68a2de3cb15ca2d81a508496f692723659dc017e2db9bc0000ffff02000200 +fma 8e464c6adc8082d95021cb53f016ce41450bb1d624b709caffffdc7e020075f3 +equal 0 false false true 0 maybe{none = nothing{}} +equal_self 65535 true true false 16 maybe{some = 0} +not_equal 65535 true true false 16 maybe{some = 0} +less 38677 true false false 8 maybe{some = 0} +less_equal 38677 true false false 8 maybe{some = 0} +greater 26858 true false false 8 maybe{some = 1} +greater_equal 26858 true false false 8 maybe{some = 1} +greater_self 65535 true true false 16 maybe{some = 0} +select 2d68f4c53cb13690d81a754486e8660f3659dc017e2d58710000010001000200 +select_not ffffa2de11f45ca27f60508496f69272adf378910650b9bc0592ffff0200ffff +sum 59395 smallest 0 largest 65535 +div 2d680100143b1e36d81a040001009272bc1d0000000016000000010001000000 +and 2d68a0c410b014805800500486e0020224515801060018300000010000000200 +or fffff6df3df57eb2ff7a75c496fef67fbffbfc917e7df9fd0592ffff0300ffff +xor d297561b2d456a32a77a25c0101ef47d9baaa490787de1cd0592feff0300fdff +not d2975d21c34ea35d27e5af7b69096d8dc9a623fe81d24643ffff0000fdfffdff +shl 2d68a2de3cb15ca2d81a508496f692723659dc017e2db9bc0000ffff02000200 +shr 2d68a2de3cb15ca2d81a508496f692723659dc017e2db9bc0000ffff02000200 +shl2 80160051009e002e006c0028004b0049009b00ee00bf805c000080ff00010001 +shr2 d000bd016201440135000801ed01e500b20003005a0079010000ff0100000000 +a a0decf5191890200bf7df9e7d245c24ece33fdf2d0f9ffffffff00004a8e01fc +b 6a182b264ad4020033de5d5026ec8e7f01000000de15a1bc8775ada285a489f7 +add 0af7fa77db5d0400f25b5638f83150cecf33fdf2ae0fa0bc8675ada2cf328af3 +sub 36c6a42b47b500008c9f9c97ac5934cfcd33fdf2f2e35e43788a535dc5e97804 +mul 402ec577ead704000daf75152cf59cedce33000060b25f43798a0000725489d3 +negate 602131ae6f76feff418207182eba3eb132cc030d3006010001000000b671ff03 +min 6a182b2691890200bf7d5d50d245c24e01000000de15a1bc877500004a8e89f7 +max a0decf514ad4020033def9e726ec8e7fce33fdf2d0f9ffffffffada285a401fc +abs a0decf5191890200bf7df9e7d245c24ece33fdf2d0f9ffffffff00004a8e01fc +fma aafdd578ecd7c46d423976159aa6979efee5bedd0eb4ecd852fcbc5d55e99131 +equal 8 true false false 1 maybe{some = 3} +equal_self 65535 true true false 16 maybe{some = 0} +not_equal 65527 true false false 15 maybe{some = 0} +less 24788 true false false 6 maybe{some = 2} +less_equal 24796 true false false 7 maybe{some = 2} +greater 40739 true false false 9 maybe{some = 0} +greater_equal 40747 true false false 10 maybe{some = 0} +greater_self 65535 true true false 16 maybe{some = 0} +select 6a182b2691890200bf7d5d50d245c24e01000000de15a1bc877500004a8e89f7 +select_not a0decf514ad4020033def9e726ec8e7fce33fdf2d0f9ffffffffada285a401fc +sum 24370 smallest 0 largest 65535 +div 0100000091890000000000001700000000000000010004000200000000000100 +and 20180b0000800200335c59400244824e00000000d011a1bc87750000008401f4 +or eadeef77dbdd0200bffffdf7f6edce7fcf33fdf2defdffffffffada2cfae89ff +xor cac6e477db5d00008ca3a4b7f4a94c31cf33fdf20eec5e43788aada2cf2a880b +not 5f2130ae6e76fdff408206182dba3db131cc020d2f0600000000ffffb571fe03 +shl 40bd9ea3221304007efbf2cfa48b849d9c67fae5a0f3fefffeff0000941c02f8 +shr 506fe728c8440100df3efc73e9226127e7197e79e87cff7fff7f00002547007e +shl2 0000008000800000008000800000000000000080000000800080000000000080 +shr2 0100000001000000000001000000000000000100010001000100000001000100 +i32x4 +a 0200000006f399190000000002000000 +b 42cff520340cc48a3eda752d76a8cae1 +add 44cff5203aff5da43eda752d78a8cae1 +sub c0300adfd2e6d58ec2258ad28c57351e +mul 849eeb4138a541b700000000ec5095c3 +negate fefffffffa0c66e600000000feffffff +min 02000000340cc48a0000000076a8cae1 +max 42cff52006f399193eda752d02000000 +abs 0200000006f399190000000002000000 +fma 6b69badb3aa541b7f76b89bfec5095c3 +equal 0 false false true 0 maybe{none = nothing{}} +equal_self 15 true true false 4 maybe{some = 0} +not_equal 15 true true false 4 maybe{some = 0} +less 5 true false false 2 maybe{some = 0} +less_equal 5 true false false 2 maybe{some = 0} +greater 10 true false false 2 maybe{some = 1} +greater_equal 10 true false false 2 maybe{some = 1} +greater_self 15 true true false 4 maybe{some = 0} +select 02000000340cc48a0000000076a8cae1 +select_not 42cff52006f399193eda752d02000000 +sum 429519626 smallest 0 largest 429519622 +div 00000000010000000000000000000000 +and 02000000040080080000000002000000 +or 42cff52036ffdd9b3eda752d76a8cae1 +xor 40cff52032ff5d933eda752d74a8cae1 +not fdfffffff90c66e6fffffffffdffffff +shl 0200000006f399190000000002000000 +shr 0200000006f399190000000002000000 +shl2 000100000083f9cc0000000000010000 +shr2 00000000e63333000000000000000000 +a 086380fa0d33faf7a39355c024baf541 +b 00000000000000009e76fc43ffffffff +add 086380fa0d33faf7410a520423baf541 +sub 086380fa0d33faf7051d597c25baf541 +mul 00000000000000009a405224dc450abe +negate f89c7f05f3cc05085d6caa3fdc450abe +min 086380fa0d33faf7a39355c0ffffffff +max 00000000000000009e76fc4324baf541 +abs f89c7f05f3cc05085d6caa3f24baf541 +fma 00000000c561b14efc42e34c7346800a +equal 0 false false true 0 maybe{none = nothing{}} +equal_self 15 true true false 4 maybe{some = 0} +not_equal 15 true true false 4 maybe{some = 0} +less 7 true false false 3 maybe{some = 0} +less_equal 7 true false false 3 maybe{some = 0} +greater 8 true false false 1 maybe{some = 3} +greater_equal 8 true false false 1 maybe{some = 3} +greater_self 15 true true false 4 maybe{some = 0} +select 086380fa0d33faf7a39355c0ffffffff +select_not 00000000000000009e76fc4324baf541 +sum -188357668 smallest -1068133469 largest 1106623012 +div 000000000000000047000000dc450abe +and 00000000000000008212544024baf541 +or 086380fa0d33faf7bff7fdc3ffffffff +xor 086380fa0d33faf73de5a983db450abe +not f79c7f05f2cc05085c6caa3fdb450abe +shl 10c600f51a66f4ef4627ab804874eb83 +shr 843140fd8619fdfbd1c92ae012ddfa20 +shl2 00008431008086190080d1c9000012dd +shr2 00f5fffff4efffffab80ffffeb830000 +i32x8 +a ffffffffffffffffffffffff020000000000000001000000c29af81e810ddd83 +b b57a26d800000000785ed79019934f966ba0c99db8d15cdfd74e28f89de33e7a +add b47a26d8ffffffff775ed7901b934f966ba0c99db9d15cdf99e920171ef11bfe +sub 4a85d927ffffffff87a1286fe96cb069955f3662492ea320eb4bd026e4299e09 +mul 4b85d9270000000088a1286f32269f2c00000000b8d15cdfee1441e01dabc8a0 +negate 010000000100000001000000feffffff00000000ffffffff3e6507e17ff2227c +min b57a26d8ffffffff785ed79019934f966ba0c99db8d15cdfd74e28f8810ddd83 +max ffffffff00000000ffffffff020000000000000001000000c29af81e9de33e7a +abs 010000000100000001000000020000000000000001000000c29af81e7ff2227c +fma 7339e85f00000000c2a5e0d534269f2c77142f6ce88612ececf8c4576bd1a918 +equal 0 false false true 0 maybe{none = nothing{}} +equal_self 255 true true false 8 maybe{some = 0} +not_equal 255 true true false 8 maybe{some = 0} +less 130 true false false 2 maybe{some = 1} +less_equal 130 true false false 2 maybe{some = 1} +greater 125 true false false 6 maybe{some = 0} +greater_equal 125 true false false 6 maybe{some = 0} +greater_self 255 true true false 8 maybe{some = 0} +select b57a26d8ffffffff785ed79019934f966ba0c99db8d15cdfd74e28f8810ddd83 +select_not ffffffff00000000ffffffff020000000000000001000000c29af81e9de33e7a +sum -1563056061 smallest -2082665087 largest 519609026 +div 00000000000000000000000000000000000000000000000040de520a00000000 +and b57a26d800000000785ed790000000000000000000000000c20a281881011c02 +or ffffffffffffffffffffffff1b934f966ba0c99db9d15cdfd7def8fe9deffffb +xor 4a85d927ffffffff87a1286f1b934f966ba0c99db9d15cdf15d4d0e61ceee3f9 +not 000000000000000000000000fdfffffffffffffffeffffff3d6507e17ef2227c +shl ffffffffffffffffffffffff020000000000000001000000c29af81e810ddd83 +shr ffffffffffffffffffffffff020000000000000001000000c29af81e810ddd83 +shl2 80ffffff80ffffff80ffffff00010000000000008000000000614d7c80c086ee +shr2 ffffffffffffffffffffffff00000000000000000000000035f13d001bba07ff +a 2e1e9348020000008a4308ad2e613ecd400e0a91482a1da9186c2bf400000000 +b 8cd45a07e19ea2fe1b1ccb47ffffffff099b144b1fd9a4a74304964afa22636b +add baf2ed4fe39ea2fea55fd3f42d613ecd49a91edc6703c2505b70c13efa22636b +sub a249384121615d016f273d652f613ecd3773f54529517801d56795a906dd9c94 +mul 28999e63c23d45fd8e37b0fbd29ec1324040fb0cb8267f4148aa1ddb00000000 +negate d2e16cb7feffffff76bcf752d29ec132c0f1f56eb8d5e256e893d40b00000000 +min 8cd45a07e19ea2fe8a4308ad2e613ecd400e0a911fd9a4a7186c2bf400000000 +max 2e1e9348020000001b1ccb47ffffffff099b144b482a1da94304964afa22636b +abs 2e1e93480200000076bcf752d29ec132c0f1f56eb8d5e256e893d40b00000000 +fma f366f444c23d45fdfb10aea1be988f4b2d7e42153fb61b917e4aa6578fe71319 +equal 0 false false true 0 maybe{none = nothing{}} +equal_self 255 true true false 8 maybe{some = 0} +not_equal 255 true true false 8 maybe{some = 0} +less 220 true false false 5 maybe{some = 2} +less_equal 220 true false false 5 maybe{some = 2} +greater 35 true false false 3 maybe{some = 0} +greater_equal 35 true false false 3 maybe{some = 0} +greater_self 255 true true false 8 maybe{some = 0} +select 8cd45a07e19ea2fe8a4308ad2e613ecd400e0a911fd9a4a7186c2bf400000000 +select_not 2e1e9348020000001b1ccb47ffffffff099b144b482a1da94304964afa22636b +sum -248748152 smallest -1861611968 largest 1217601070 +div 0f0a311800000000000000000000000002000000ffffffff0000000000000000 +and 0c141200000000000a0008052e613ecd000a0001080804a10004024000000000 +or aededb4fe39ea2fe9b5fcbefffffffff499f1edb5ffbbdaf5b6cbffefa22636b +xor a2cac94fe39ea2fe915fc3ead19ec13249951eda57f3b90e5b68bdbefa22636b +not d1e16cb7fdffffff75bcf752d19ec132bff1f56eb7d5e256e793d40bffffffff +shl 5c3c2691040000001487105a5cc27c9a801c142290543a5230d856e800000000 +shr 178f492401000000c52184d697309fe6200785c824958ed40cb615fa00000000 +shl2 0000178f000001000000c52100009730000020070000249500000cb600000000 +shr2 2691000000000000105affff7c9affff1422ffff3a52ffff56e8ffff00000000 +u32x4 +a a2be69a5957fec486ea11802bbe2628f +b ed99a72a05807121814054c400000000 +add 8f5811d09aff5d6aefe16cc6bbe2628f +sub b524c27a90ff7a27ed60c43dbbe2628f +mul fa4d8245e9fd2d326ed8dc6600000000 +negate 5e41965a6b8013b7925ee7fd451d9d70 +min ed99a72a058071216ea1180200000000 +max a2be69a5957fec48814054c4bbe2628f +abs a2be69a5957fec486ea11802bbe2628f +fma fa4d8245e8fd2d326fd8dc6600000000 +equal 0 false false true 0 maybe{none = nothing{}} +equal_self 15 true true false 4 maybe{some = 0} +not_equal 15 true true false 4 maybe{some = 0} +less 4 true false false 1 maybe{some = 2} +less_equal 4 true false false 1 maybe{some = 2} +greater 11 true false false 3 maybe{some = 0} +greater_equal 11 true false false 3 maybe{some = 0} +greater_self 15 true true false 4 maybe{some = 0} +select ed99a72a058071216ea1180200000000 +select_not a2be69a5957fec48814054c4bbe2628f +sum 2144453216 smallest 35168622 largest 2775170722 +div 02000000000000006ea1180202000000 +and a0982120050060000000100000000000 +or efbfefaf95fffd69efe15cc6bbe2628f +xor 4f27ce8f90ff9d69efe14cc6bbe2628f +not 5d41965a6a8013b7915ee7fd441d9d70 +shl a2be69a5957fec486ea11802bbe2628f +shr a2be69a5957fec486ea11802bbe2628f +shl2 0051dfb480ca3f7600b7500c805d71b1 +shr2 7dd34a01ffd8910042310400c5c51e01 +a c116cf619d21b2bc1b7c9d6bffffffff +b ffffffff02000000d54d3bd8525031ea +add c016cf619f21b2bcf0c9d843515031ea +sub c216cf619b21b2bc462e6293adafce15 +mul 3fe9309e3a4364797761954aaeafce15 +negate 3fe9309e63de4d43e583629401000000 +min c116cf61020000001b7c9d6b525031ea +max ffffffff9d21b2bcd54d3bd8ffffffff +abs c116cf619d21b2bc1b7c9d6bffffffff +fma 41e9309ef0da92060e0c315fb0afce15 +equal 0 false false true 0 maybe{none = nothing{}} +equal_self 15 true true false 4 maybe{some = 0} +not_equal 15 true true false 4 maybe{some = 0} +less 5 true false false 2 maybe{some = 0} +less_equal 5 true false false 2 maybe{some = 0} +greater 10 true false false 2 maybe{some = 1} +greater_equal 10 true false false 2 maybe{some = 1} +greater_self 15 true true false 4 maybe{some = 0} +select c116cf61020000001b7c9d6b525031ea +select_not ffffffff9d21b2bcd54d3bd8ffffffff +sum 2317268088 smallest 1640961729 largest 4294967295 +div 608be730010000000dbece3501000000 +and c116cf6100000000114c1948525031ea +or ffffffff9f21b2bcdf7dbffbffffffff +xor 3ee9309e9f21b2bcce31a6b3adafce15 +not 3ee9309e62de4d43e483629400000000 +shl 822d9ec33a43647936f83ad7feffffff +shr 608be730ce10595e0dbece35ffffff7f +shl2 0080608b0080ce1000800dbe0080ffff +shr2 9ec30000647901003ad70000ffff0100 +u32x8 +a a6c11a035e308c14c16d49c0840483c58a6744d71e8cfe196b14432bffffffff +b 02000000bf8c9471322d6bce07987e8c3e0465d6356afdfb01000000a398d519 +add a8c11a031dbd2086f39ab48e8b9c0152c86ba9ad53f6fb156c14432ba298d519 +sub a4c11a039fa3f7a28f40def17d6c04394c63df00e921011e6a14432b5c672ae6 +mul 4c833506227e6373b25c4da49c7f3b9a6c3ba169366e5dab6b14432b5d672ae6 +negate 5a3ee5fca2cf73eb3f92b63f7cfb7c3a7698bb28e27301e695ebbcd401000000 +min 020000005e308c14c16d49c007987e8c3e0465d61e8cfe1901000000a398d519 +max a6c11a03bf8c9471322d6bce840483c58a6744d7356afdfb6b14432bffffffff +abs a6c11a035e308c14c16d49c0840483c58a6744d71e8cfe196b14432bffffffff +fma 4e8335065c91dccdf5006d72781085f1402aee1b03c53cfd6b14432b503b9554 +equal 0 false false true 0 maybe{none = nothing{}} +equal_self 255 true true false 8 maybe{some = 0} +not_equal 255 true true false 8 maybe{some = 0} +less 38 true false false 3 maybe{some = 1} +less_equal 38 true false false 3 maybe{some = 1} +greater 217 true false false 5 maybe{some = 0} +greater_equal 217 true false false 5 maybe{some = 0} +greater_self 255 true true false 8 maybe{some = 0} +select 020000005e308c14c16d49c007987e8c3e0465d61e8cfe1901000000a398d519 +select_not a6c11a03bf8c9471322d6bce840483c58a6744d7356afdfb6b14432bffffffff +sum 3120131163 smallest 52085158 largest 4294967295 +div 0000000000000000030000004282c16201000000000000000000000001000000 +and 020000001e008410002d49c0040002840a0444d61408fc1901000000a398d519 +or a6c11a03ffbc9c75f36d6bce879cffcdbe6765d73feefffb6b14432bffffffff +xor a4c11a03e1bc1865f340220e839cfd49b46321012be603e26a14432b5c672ae6 +not 593ee5fca1cf73eb3e92b63f7bfb7c3a7598bb28e17301e694ebbcd400000000 +shl a6c11a035e308c14c16d49c0840483c58a6744d71e8cfe196b14432bffffffff +shr a6c11a035e308c14c16d49c0840483c58a6744d71e8cfe196b14432bffffffff +shl2 00d3608d002f184680e0b624004282c100c533a2000f46ff80358aa180ffffff +shr2 8335060060182900db92800109068b01cf88ae0118fd330028865600ffffff01 +a e7d69fe96b3112f6d6674a3b549b671e02000000000000004cd7bed002000000 +b 01000000ba7439dfffffffff0200000090b2dc9fea1dce9e0100000097be14a7 +add e8d69fe925a64bd5d5674a3b569b671e92b2dc9fea1dce9e4dd7bed099be14a7 +sub e6d69fe9b1bcd816d7674a3b529b671e724d236016e231614bd7bed06b41eb58 +mul e7d69fe9be636f3d2a98b5c4a836cf3c2065b93f000000004cd7bed02e7d294e +negate 1929601695ceed092a98b5c4ac6498e1feffffff00000000b428412ffeffffff +min 01000000ba7439dfd6674a3b0200000002000000000000000100000002000000 +max e7d69fe96b3112f6ffffffff549b671e90b2dc9fea1dce9e4cd7bed097be14a7 +abs e7d69fe96b3112f6d6674a3b549b671e02000000000000004cd7bed002000000 +fma f5d5f39cbe636f3d8fb06f6da7de31232065b93f294da5744bd7bed0a9e121ce +equal 0 false false true 0 maybe{none = nothing{}} +equal_self 255 true true false 8 maybe{some = 0} +not_equal 255 true true false 8 maybe{some = 0} +less 180 true false false 4 maybe{some = 2} +less_equal 180 true false false 4 maybe{some = 2} +greater 75 true false false 4 maybe{some = 0} +greater_equal 75 true false false 4 maybe{some = 0} +greater_self 255 true true false 8 maybe{some = 0} +select 01000000ba7439dfd6674a3b0200000002000000000000000100000002000000 +select_not e7d69fe96b3112f6ffffffff549b671e90b2dc9fea1dce9e4cd7bed097be14a7 +sum 170058444 smallest 0 largest 4128387435 +div 000000000500000000000000aacd330f00000000000000004cd7bed000000000 +and 010000002a3010d6d6674a3b0000000000000000000000000000000002000000 +or e7d69fe9fb753bffffffffff569b671e92b2dc9fea1dce9e4dd7bed097be14a7 +xor e6d69fe9d1452b292998b5c4569b671e92b2dc9fea1dce9e4dd7bed095be14a7 +not 1829601694ceed092998b5c4ab6498e1fdffffffffffffffb328412ffdffffff +shl cead3fd3d66224ecaccf9476a836cf3c040000000000000098ae7da104000000 +shr 73ebcf74b518097beb33a51daacd330f0100000000000000a66b5f6801000000 +shl2 008073eb0080b5180000eb330000aacd00000100000000000000a66b00000100 +shr2 3fd3010024ec010094760000cf3c000000000000000000007da1010000000000 +i64x2 +a f291c4a11f8a1d580100000000000000 +b c590ffacddb1160f59f285a66e202571 +add b722c44efd3b34675af285a66e202571 +sub 2d01c5f441d80649a80d7a5991dfda8e +mul 3a6f6a061c9a058b59f285a66e202571 +negate 0e6e3b5ee075e2a7ffffffffffffffff +min c590ffacddb1160f0100000000000000 +max f291c4a11f8a1d5859f285a66e202571 +abs f291c4a11f8a1d580100000000000000 +fma 5c8985faec3b49dc38ad80a1fa2ce92e +equal 0 false false true 0 maybe{none = nothing{}} +equal_self 3 true true false 2 maybe{some = 0} +not_equal 3 true true false 2 maybe{some = 0} +less 2 true false false 1 maybe{some = 1} +less_equal 2 true false false 1 maybe{some = 1} +greater 1 true false false 1 maybe{some = 0} +greater_equal 1 true false false 1 maybe{some = 0} +greater_self 3 true true false 2 maybe{some = 0} +select c590ffacddb1160f0100000000000000 +select_not f291c4a11f8a1d5859f285a66e202571 +sum 6.3493829181249e+18 smallest 1 largest 6.3493829181249e+18 +div feffffffffffffff0000000000000000 +and c090c4a01d8014080100000000000000 +or f791ffaddfbb1f5f59f285a66e202571 +xor 37013b0dc23b0b5758f285a66e202571 +not 0d6e3b5ee075e2a7feffffffffffffff +shl f291c4a11f8a1d580100000000000000 +shr f291c4a11f8a1d580100000000000000 +shl2 00f948e2d00fc50e8000000000000000 +shr2 2389433f143bb0000000000000000000 +a 000000000000000072e4415bd64e6437 +b cc5d5f6653262a4c97cbcf82b603fb12 +add cc5d5f6653262a4c09b011de8c525f4a +sub 34a2a099acd9d5b3db1872d81f4b6924 +mul 00000000000000003e2532b0227aa576 +negate 00000000000000008e1bbea429b19bc8 +min 000000000000000097cbcf82b603fb12 +max cc5d5f6653262a4c72e4415bd64e6437 +abs 000000000000000072e4415bd64e6437 +fma 00000000000000003d2532b0227aa576 +equal 0 false false true 0 maybe{none = nothing{}} +equal_self 3 true true false 2 maybe{some = 0} +not_equal 3 true true false 2 maybe{some = 0} +less 1 true false false 1 maybe{some = 0} +less_equal 1 true false false 1 maybe{some = 0} +greater 2 true false false 1 maybe{some = 1} +greater_equal 2 true false false 1 maybe{some = 1} +greater_self 3 true true false 2 maybe{some = 0} +select 000000000000000097cbcf82b603fb12 +select_not cc5d5f6653262a4c72e4415bd64e6437 +sum 3.991401852318115e+18 smallest 0 largest 3.991401852318115e+18 +div 000000000000000039f2a02d6b27b21b +and 000000000000000012c0410296026012 +or cc5d5f6653262a4cf7efcfdbf64fff37 +xor cc5d5f6653262a4ce52f8ed9604d9f25 +not ffffffffffffffff8d1bbea429b19bc8 +shl 0000000000000000e4c883b6ac9dc86e +shr 000000000000000039f2a02d6b27b21b +shl2 0000000000000000000039f2a02d6b27 +shr2 000000000000000083b6ac9dc86e0000 +i64x4 +a ef465101dc2caea702000000000000005d092251886adf2bbbb696d72ee2852d +b 3c0e46686abb205f00000000000000007ab7edde997b0ecb7122fda357b5be09 +add 2b55976946e8ce060200000000000000d7c00f3022e6edf62cd9937b86974437 +sub b3380b9971718d480200000000000000e3513472eeeed0604a949933d72cc723 +mul 04b2473ea3e04ff1000000000000000052f102502c1f1c8e8b7e9ad52766e740 +negate 11b9aefe23d35158feffffffffffffffa3f6ddae779520d445496928d11d7ad2 +min ef465101dc2caea700000000000000007ab7edde997b0ecb7122fda357b5be09 +max 3c0e46686abb205f02000000000000005d092251886adf2bbbb696d72ee2852d +abs 11b9aefe23d3515802000000000000005d092251886adf2bbbb696d72ee2852d +fma 0128cd06907bfa5d96c068b04393d5fd102a72e1158e92ff282dde2eda2a564f +equal 0 false false true 0 maybe{none = nothing{}} +equal_self 15 true true false 4 maybe{some = 0} +not_equal 15 true true false 4 maybe{some = 0} +less 1 true false false 1 maybe{some = 0} +less_equal 1 true false false 1 maybe{some = 0} +greater 14 true false false 3 maybe{some = 1} +greater_equal 14 true false false 3 maybe{some = 1} +greater_self 15 true true false 4 maybe{some = 0} +select ef465101dc2caea700000000000000007ab7edde997b0ecb7122fda357b5be09 +select_not 3c0e46686abb205f02000000000000005d092251886adf2bbbb696d72ee2852d +sum 7.753929156788405e+16 smallest -6.364099900001401e+18 largest 3.280276594422626e+18 +div 50c2c55549648fe2000000000000000000000000000000000000000000000000 +and 2c06400048282007000000000000000058012050886a0e0b3122948306a08409 +or ff4e5769febfaeff02000000000000007fbfefdf997bdfebfbb6fff77ff7bf2d +xor d3481769b6978ef8020000000000000027becf8f1111d1e0ca946b7479573b24 +not 10b9aefe23d35158fdffffffffffffffa2f6ddae779520d444496928d11d7ad2 +shl ef465101dc2caea702000000000000005d092251886adf2bbbb696d72ee2852d +shr ef465101dc2caea702000000000000005d092251886adf2bbbb696d72ee2852d +shl2 8077a3a8006e16d7000100000000000080ae04912844b5ef805d5bcb6b17f1c2 +shr2 8da202b8595c4fff00000000000000001244a210d5be57006d2daf5dc40b5b00 +a 0000000000000000a213e2b18255250fbbe8d266ab3861fe2d65f41655089062 +b aa79f2fd4794cc5ef64076eb96cac638944c23c56adc2845132941b8e59d6b86 +add aa79f2fd4794cc5e9854589d1920ec474f35f62b16158a43408e35cf3aa6fbe8 +sub 56860d02b86b33a1acd26bc6eb8a5ed6279cafa1405c38b91a3cb35e6f6a24dc +mul 0000000000000000ac5dd33636b30a841c1097c7f912242a57b7c4e004d69aea +negate 00000000000000005eec1d4e7daadaf045172d9954c79e01d39a0be9aaf76f9d +min 0000000000000000a213e2b18255250fbbe8d266ab3861fe132941b8e59d6b86 +max aa79f2fd4794cc5ef64076eb96cac638944c23c56adc28452d65f41655089062 +abs 0000000000000000a213e2b18255250f45172d9954c79e012d65f41655089062 +fma 01000000000000005be0626c647f40746217b3d8a97f7012ecc96d1ce04cdfba +equal 0 false false true 0 maybe{none = nothing{}} +equal_self 15 true true false 4 maybe{some = 0} +not_equal 15 true true false 4 maybe{some = 0} +less 7 true false false 3 maybe{some = 0} +less_equal 7 true false false 3 maybe{some = 0} +greater 8 true false false 1 maybe{some = 3} +greater_equal 8 true false false 1 maybe{some = 3} +greater_self 15 true true false 4 maybe{some = 0} +select 0000000000000000a213e2b18255250fbbe8d266ab3861fe132941b8e59d6b86 +select_not aa79f2fd4794cc5ef64076eb96cac638944c23c56adc28452d65f41655089062 +sum 8.076808471920075e+18 smallest -1.16749806519261e+17 largest 7.10218577391363e+18 +div 0000000000000000000000000000000045172d9954c79e010000000000000000 +and 0000000000000000a20062a182400408904802442a1820440121401045080002 +or aa79f2fd4794cc5ef653f6fb96dfe73fbfecf3e7ebfc69ff3f6df5bef59dfbe6 +xor aa79f2fd4794cc5e5453945a149fe3372fa4f1a3c1e449bb3e4cb5aeb095fbe4 +not ffffffffffffffff5dec1d4e7daadaf044172d9954c79e01d29a0be9aaf76f9d +shl 00000000000000004427c46305ab4a1e76d1a5cd5671c2fc5acae82daa1020c5 +shr 0000000000000000d109f158c1aa92075d7469b3559c30ff96327a8b2a044831 +shl2 00000000000000000000d109f158c1aa00805d7469b3559c008096327a8b2a04 +shr2 0000000000000000c46305ab4a1e0000a5cd5671c2fcffffe82daa1020c50000 +u64x2 +a 3521d3b7f8bd6a53237f221e26bb5547 +b 7b4b48b182b316faa794f57f7cd3347f +add b06c1b697b71814dca13189ea28e8ac6 +sub bad58a06760a54597cea2c9ea9e720c8 +mul 777b13299cbdfa54d52b80a353812855 +negate cbde2c48074295acdd80dde1d944aab8 +min 3521d3b7f8bd6a53237f221e26bb5547 +max 7b4b48b182b316faa794f57f7cd3347f +abs 3521d3b7f8bd6a53237f221e26bb5547 +fma 19a662b0243258b4e4ee463b7042e2af +equal 0 false false true 0 maybe{none = nothing{}} +equal_self 3 true true false 2 maybe{some = 0} +not_equal 3 true true false 2 maybe{some = 0} +less 3 true true false 2 maybe{some = 0} +less_equal 3 true true false 2 maybe{some = 0} +greater 0 false false true 0 maybe{none = nothing{}} +greater_equal 0 false false true 0 maybe{none = nothing{}} +greater_self 3 true true false 2 maybe{some = 0} +select 3521d3b7f8bd6a53237f221e26bb5547 +select_not 7b4b48b182b316faa794f57f7cd3347f +sum 1.1151045850714972e+19 smallest 5.140220322102018e+18 largest 6.010825528612954e+18 +div 00000000000000000100000000000000 +and 310140b180b102522314201e24931447 +or 7f6bdbb7fabf7efba7fff77f7efb757f +xor 4e6a9b067a0e7ca984ebd7615a686138 +not cade2c48074295acdc80dde1d944aab8 +shl 3521d3b7f8bd6a53237f221e26bb5547 +shr 3521d3b7f8bd6a53237f221e26bb5547 +shl2 809a90e95bfc5eb580913f110f93ddaa +shr2 42a66ff17bd5a600fe443c4c76ab8e00 +a 413e3b7db69589c8cd3e07748d177a90 +b 0000000000000000acdf11db0436bb4c +add 413e3b7db69589c8791e194f924d35dd +sub 413e3b7db69589c8215ff59888e1be43 +mul 0000000000000000bcc42fcf842b4e12 +negate bfc1c482496a763733c1f88b72e8856f +min 0000000000000000acdf11db0436bb4c +max 413e3b7db69589c8cd3e07748d177a90 +abs 413e3b7db69589c8cd3e07748d177a90 +fma ffffffffffffffff9020df6e99e31a88 +equal 0 false false true 0 maybe{none = nothing{}} +equal_self 3 true true false 2 maybe{some = 0} +not_equal 3 true true false 2 maybe{some = 0} +less 0 false false true 0 maybe{none = nothing{}} +less_equal 0 false false true 0 maybe{none = nothing{}} +greater 3 true true false 2 maybe{some = 0} +greater_equal 3 true true false 2 maybe{some = 0} +greater_self 3 true true false 2 maybe{some = 0} +select 0000000000000000acdf11db0436bb4c +select_not 413e3b7db69589c8cd3e07748d177a90 +sum 6.414160801627799e+18 smallest 1.0410659384924783e+19 largest 1.4450245490412569e+19 +div 00000000000000000000000000000000 +and 00000000000000008c1e015004163a00 +or 413e3b7db69589c8edff17ff8d37fbdc +xor 413e3b7db69589c861e116af8921c1dc +not bec1c482496a763732c1f88b72e8856f +shl 827c76fa6c2b13919a7d0ee81a2ff420 +shr 209f9d3edbca4464669f03bac60b3d48 +shl2 0080209f9d3edbca0080669f03bac60b +shr2 76fa6c2b139101000ee81a2ff4200100 +u64x4 +a a5397763a3e046182bb560b6c5df621a0100000000000000d88423649a2ae73e +b 01000000000000007615a817536720a26d46b2334ba7d59b0100000000000000 +add a6397763a3e04618a1ca08ce184783bc6e46b2334ba7d59bd98423649a2ae73e +sub a4397763a3e04618b59fb89e7278427894b94dccb4582a64d78423649a2ae73e +mul a5397763a3e04618d208a8c0c6c6afc86d46b2334ba7d59bd88423649a2ae73e +negate 5bc6889c5c1fb9e7d54a9f493a209de5ffffffffffffffff287bdc9b65d518c1 +min 01000000000000002bb560b6c5df621a01000000000000000100000000000000 +max a5397763a3e046187615a817536720a26d46b2334ba7d59bd88423649a2ae73e +abs a5397763a3e046182bb560b6c5df621a0100000000000000d88423649a2ae73e +fma a7397763a3e046186a6504b0bd895de96e46b2334ba7d59b3aacff92b202f06e +equal 0 false false true 0 maybe{none = nothing{}} +equal_self 15 true true false 4 maybe{some = 0} +not_equal 15 true true false 4 maybe{some = 0} +less 6 true false false 2 maybe{some = 1} +less_equal 6 true false false 2 maybe{some = 1} +greater 9 true false false 2 maybe{some = 0} +greater_equal 9 true false false 2 maybe{some = 0} +greater_self 15 true true false 4 maybe{some = 0} +select 01000000000000002bb560b6c5df621a01000000000000000100000000000000 +select_not a5397763a3e046187615a817536720a26d46b2334ba7d59bd88423649a2ae73e +sum 8.183298923163252e+18 smallest 1 largest 4.532638392565073e+18 +div 0000000000000000000000000000000000000000000000006cc211324d95731f +and 0100000000000000221520164147200201000000000000000000000000000000 +or a5397763a3e046187fb5e8b7d7ff62ba6d46b2334ba7d59bd98423649a2ae73e +xor a4397763a3e046185da0c8a196b842b86c46b2334ba7d59bd98423649a2ae73e +not 5ac6889c5c1fb9e7d44a9f493a209de5feffffffffffffff277bdc9b65d518c1 +shl a5397763a3e046182bb560b6c5df621a0100000000000000d88423649a2ae73e +shr a5397763a3e046182bb560b6c5df621a0100000000000000d88423649a2ae73e +shl2 80d29cbbb151702380955a30dbe26f318000000000000000006cc211324d9573 +shr2 73eec646c18d30006ac16c8bbfc5340000000000000000000947c83455ce7d00 +a ffffffffffffffff668cace5595deddb679b0c3018936ca00100000000000000 +b cbab4671ff012ba734bc06d03a40783134812f0bf9f63d189038d848f93a0102 +add caab4671ff012ba79a48b3b5949d650d9b1c3c3b118aaab89138d848f93a0102 +sub 3454b98e00fed45832d0a5151f1d75aa331add241f9c2e8871c727b706c5fefd +mul 3554b98e00fed458b86c8b8827de7db9ec77c7114d8fd1e09038d848f93a0102 +negate 01000000000000009a73531aa6a212249964f3cfe76c935fffffffffffffffff +min cbab4671ff012ba734bc06d03a40783134812f0bf9f63d180100000000000000 +max ffffffffffffffff668cace5595deddb679b0c3018936ca09038d848f93a0102 +abs ffffffffffffffff668cace5595deddb679b0c3018936ca00100000000000000 +fma 3654b98e00fed458877b6e92dc39038cee77c7114d8fd1e03155b2b868b6d77c +equal 0 false false true 0 maybe{none = nothing{}} +equal_self 15 true true false 4 maybe{some = 0} +not_equal 15 true true false 4 maybe{some = 0} +less 8 true false false 1 maybe{some = 3} +less_equal 8 true false false 1 maybe{some = 3} +greater 7 true false false 3 maybe{some = 0} +greater_equal 7 true false false 3 maybe{some = 0} +greater_self 15 true true false 4 maybe{some = 0} +select cbab4671ff012ba734bc06d03a40783134812f0bf9f63d180100000000000000 +select_not ffffffffffffffff668cace5595deddb679b0c3018936ca09038d848f93a0102 +sum 8.960457306411706e+18 smallest 1 largest 1.8446744073709552e+19 +div 01000000000000000100000000000000228959655d8679350000000000000000 +and cbab4671ff012ba7248c04c01840681124810c0018922c000000000000000000 +or ffffffffffffffff76bcaef57b5dfdfb779b2f3bf9f77db89138d848f93a0102 +xor 3454b98e00fed4585230aa35631d95ea531a233be16551b89138d848f93a0102 +not 00000000000000009973531aa6a212249864f3cfe76c935ffeffffffffffffff +shl feffffffffffffffcc1859cbb3badab7ce3619603026d9400200000000000000 +shr ffffffffffffff7f3346d6f2acaef66db34d06188c4936500000000000000000 +shl2 0080ffffffffffff00003346d6f2acae0080b34d06188c490080000000000000 +shr2 ffffffffffff010059cbb3badab7010019603026d94001000000000000000000 diff --git a/tests/programs/simd_lanes_agree_everywhere_1.sakura b/tests/programs/simd_lanes_agree_everywhere_1.sakura new file mode 100644 index 00000000..c5895749 --- /dev/null +++ b/tests/programs/simd_lanes_agree_everywhere_1.sakura @@ -0,0 +1,177 @@ +import std::io; +import std::math; + +# Every operation of std's vectors gives the same bits wherever it runs: in either +# compiler's machine, in an executable, where the processor's vector instructions +# work the lanes, and in constants worked out while compiling. Each line is an +# operation's result, its bytes in hex, for vectors of each type of lane made of +# random lanes and the edges of their types. + +const compiled: f32[4] = (f32x4::of([1.5, -2.0, 0.25, 8.0]) * f32x4::splat(3.0) + f32x4::splat(-0.0)).min(&f32x4::splat(4.0)).lanes(); +const counted: u32 = u8x16::splat(7).less(&u8x16::of([0, 9, 1, 8, 2, 10, 3, 11, 4, 12, 5, 13, 6, 14, 7, 15])).bits(); + +var seed: u64 = 0x9E3779B97F4A7C15; + +def next(): u64 { + seed = seed ^ (seed << 13); + seed = seed ^ (seed >> 7); + seed = seed ^ (seed << 17); + return seed; +} + +const digits: strview = "0123456789abcdef"; + +def hex_of(bytes: *u8, count: u64, out: &mut string): void { + for i in 0..count { + val b := bytes[i]; + out.push(digits[(b >> 4) as u64]); + out.push(digits[(b & 15) as u64]); + } +} + +def show(name: strview, v: &simd): void where L: numeric, ordered, zeroable { + var out := string::from(name, nothing {}); + out.append(" "); + val held := v.lanes(); + hex_of((&held) as *u8, N * size_of::(), &mut out); + io::println(out.view()); +} + +def show_mask(name: strview, m: &mask): void where L: numeric, ordered, zeroable { + val bits := m.bits(); + io::println($"{name} {bits} {m.any()} {m.all()} {m.none()} {m.count()} {m.first()}"); +} + +# A lane worth testing: random bits, or a special value of its type. +def lane(): L where L: numeric, ordered, zeroable { + val pick := next() % 16; + if const L is real { + val specials: f64[12] = [0.0, -0.0, 1.0, -1.0, 0.5, -2.5, 2.5, 1e300, -1e-310, 3.0, 1e-45, -7.25]; + if pick < 12 { + return specials[pick] as L; + } + if pick == 12 { + return math::infinity::(); + } + if pick == 13 { + return -math::infinity::(); + } + if pick == 14 { + return math::nan::(); + } + return ((next() % 2000000) as f64 / 1000.0 - 1000.0) as L; + } + if const L is integer { + if pick < 3 { + return pick as L; + } + if pick == 3 { + return ~(0 as L); + } + var made: L; + val bits := next(); + val p := (&mut made) as *mut u8; + for k in 0..size_of::() { + p[k] = ((bits >> (8 * k)) & 0xFF) as u8; + } + return made; + } + var none: L; + return none; +} + +def vector(): simd where L: numeric, ordered, zeroable { + var made: simd; + for i in 0..N { + made[i] = lane::(); + } + return made; +} + +def nonzero(): simd where L: numeric, ordered, zeroable { + var made := vector::(); + for i in 0..N { + if made[i] == 0 as L { + made[i] = 3 as L; + } + } + return made; +} + +def exercise(name: strview): void where L: numeric, ordered, zeroable { + io::println(name); + for round in 0..2 { + val a := vector::(); + val b := vector::(); + val c := vector::(); + show("a", &a); + show("b", &b); + show("add", &(a + b)); + show("sub", &(a - b)); + show("mul", &(a * b)); + show("negate", &(-a)); + show("min", &a.min(&b)); + show("max", &a.max(&b)); + show("abs", &a.abs()); + show("fma", &a.fma(&b, &c)); + show_mask("equal", &a.equal(&b)); + show_mask("equal_self", &a.equal(&a)); + show_mask("not_equal", &a.not_equal(&b)); + show_mask("less", &a.less(&b)); + show_mask("less_equal", &a.less_equal(&b)); + show_mask("greater", &a.greater(&b)); + show_mask("greater_equal", &a.greater_equal(&b)); + show_mask("greater_self", &a.greater_equal(&a)); + val m := a.less(&b); + show("select", &select(m, a, b)); + show("select_not", &select(~m, a, b)); + io::println($"sum {a.sum() as f64} smallest {a.smallest() as f64} largest {a.largest() as f64}"); + if const L is real { + show("div", &(a / b)); + show("sqrt", &a.sqrt()); + show("floor", &a.floor()); + show("ceil", &a.ceil()); + show("trunc", &a.trunc()); + show("round", &a.round()); + show("round_even", &a.round_even()); + } + if const L is integer { + show("div", &(a / nonzero::())); + show("and", &(a & b)); + show("or", &(a | b)); + show("xor", &(a ^ b)); + show("not", &(~a)); + val counts: u32[8] = [0, 1, 7, 15, 31, 63, 64, 100]; + val count := counts[round as u64]; + show("shl", &(a << count)); + show("shr", &(a >> count)); + val other := counts[(round + 2) as u64]; + show("shl2", &(a << other)); + show("shr2", &(a >> other)); + } + } +} + +def main(): void { + io::println($"compiled {compiled[0]} {compiled[1]} {compiled[2]} {compiled[3]} {counted}"); + exercise::("f32x4"); + exercise::("f32x8"); + exercise::("f64x2"); + exercise::("f64x4"); + exercise::("i8x16"); + exercise::("i8x32"); + exercise::("u8x16"); + exercise::("u8x32"); + exercise::("i16x8"); + exercise::("i16x16"); + exercise::("u16x8"); + exercise::("u16x16"); + exercise::("i32x4"); + exercise::("i32x8"); + exercise::("u32x4"); + exercise::("u32x8"); + exercise::("i64x2"); + exercise::("i64x4"); + exercise::("u64x2"); + exercise::("u64x4"); +} diff --git a/tests/programs/simd_lanes_agree_everywhere_2.out b/tests/programs/simd_lanes_agree_everywhere_2.out new file mode 100644 index 00000000..35513ecd --- /dev/null +++ b/tests/programs/simd_lanes_agree_everywhere_2.out @@ -0,0 +1,481 @@ +compiled 4 4 4294967295 +f32x16 +a 000080ff00002040000020400000003f0000807f00004040cd8c0ec30000e8c00000c07f000020c0000080bf000080ff0000c07fe73bcfc200000080000020c0 +b 502543c4000080ffcbb114440000c07f000080ff0000003f000080bfe5c087c3000080ff0000807f000020c0010000000000807f000080ff0000803f00002040 +add 000080ff000080ffcb5115440000c07f0000c0ff00006040cd8c0fc3e5608bc30000c07f0000807f000060c0000080ff0000c07f000080ff0000803f00000000 +sub 000080ff0000807fcb1114c40000c07f0000807f00002040cd8c0dc3e52084430000c07f000080ff0000c03f000080ff0000c07f0000807f000080bf0000a0c0 +mul 0000807f000080ff3edeb9440000c07f000080ff0000c03fcd8c0e439f0df6440000c07f000080ff00002040000080ff0000c07f0000807f000000800000c8c0 +negate 0000807f000020c0000020c0000000bf000080ff000040c0cd8c0e430000e8400000c0ff000020400000803f0000807f0000c0ffe73bcf420000000000002040 +min 000080ff000080ff000020400000c07f000080ff0000003fcd8c0ec3e5c087c30000c07f000020c0000020c0000080ff0000c07f000080ff00000080000020c0 +max 502543c400002040cbb114440000c07f0000807f00004040000080bf0000e8c00000c07f0000807f000080bf010000000000c07fe73bcfc20000803f00002040 +abs 0000807f00002040000020400000003f0000807f00004040cd8c0e430000e8400000c07f000020400000803f0000807f0000c07fe73bcf420000000000002040 +fma 0000807f000080ff3edeb9440000c07f000080ff000090400000807f9f25f5440000c07f000080ff00000000000080ff0000c07f0000807f000020400000a8c0 +equal 0 false false true 0 maybe{none = nothing{}} +equal_self 61183 true false false 14 maybe{some = 0} +not_equal 65535 true true false 16 maybe{some = 0} +less 51781 true false false 7 maybe{some = 0} +less_equal 51781 true false false 7 maybe{some = 0} +greater 9394 true false false 6 maybe{some = 1} +greater_equal 9394 true false false 6 maybe{some = 1} +greater_self 61183 true false false 14 maybe{some = 0} +select 000080ff000080ff000020400000c07f000080ff0000003fcd8c0ec3e5c087c3000080ff000020c0000020c0000080ff0000807f000080ff00000080000020c0 +select_not 502543c400002040cbb114440000003f0000807f00004040000080bf0000e8c00000c07f0000807f000080bf010000000000c07fe73bcfc20000803f00002040 +sum nan smallest nan largest nan +div 0000807f0000008068bb893b0000c07f0000c0ff0000c040cd8c0e43dbbfda3c0000c07f00000080cdcccc3e000080ff0000c07f0000000000000080000080bf +sqrt 0000c0ffc262ca3fc262ca3ff304353f0000807fd7b3dd3f0000c0ff0000c0ff0000c07f0000c0ff0000c0ff0000c0ff0000c07f0000c0ff000000800000c0ff +floor 000080ff0000004000000040000000000000807f0000404000000fc3000000c10000c07f000040c0000080bf000080ff0000c07f0000d0c200000080000040c0 +ceil 000080ff00004040000040400000803f0000807f0000404000000ec30000e0c00000c07f000000c0000080bf000080ff0000c07f0000cec200000080000000c0 +trunc 000080ff0000004000000040000000000000807f0000404000000ec30000e0c00000c07f000000c0000080bf000080ff0000c07f0000cec200000080000000c0 +round 000080ff00004040000040400000803f0000807f0000404000000fc30000e0c00000c07f000040c0000080bf000080ff0000c07f0000d0c200000080000040c0 +round_even 000080ff0000004000000040000000000000807f0000404000000fc30000e0c00000c07f000000c0000080bf000080ff0000c07f0000d0c200000080000000c0 +a 000000000000204000002040000040406dc7f343000080bf000000800000807f000020c0000080bf000020c00000c07f00000080000040400000c07f000080ff +b 000040400000803f0000807f00000000000080bfe19a40c40000c07f00000000010000003b3754c40000204001000000000020c0000020c00000003f00002040 +add 00004040000060400000807f000040406d47f343e1da40c40000c07f0000807f000020c03b7754c4000000000000c07f000020c00000003f0000c07f000080ff +sub 000040c00000c03f000080ff000040406d47f443e15a40440000c07f0000807f000020c03bf753440000a0c00000c07f000020400000b0400000c07f000080ff +mul 00000000000020400000807f000000006dc7f3c3e19a40440000c07f0000c0ff020000803b3754440000c8c00000c07f000000000000f0c00000c07f000080ff +negate 00000080000020c0000020c0000040c06dc7f3c30000803f00000000000080ff000020400000803f000020400000c0ff00000000000040c00000c0ff0000807f +min 000000000000803f0000204000000000000080bfe19a40c40000c07f00000000000020c03b3754c4000020c00000c07f000020c0000020c00000c07f000080ff +max 00004040000020400000807f000040406dc7f343000080bf0000c07f0000807f01000000000080bf000020400000c07f00000080000040400000c07f00002040 +abs 000000000000204000002040000040406dc7f3430000803f000000000000807f000020400000803f000020400000c07f00000000000040400000c07f0000807f +fma 7989da430000807f0000807f010000000000807fe1da40440000c07f0000c0ff0000c07f3b6752440000807f0000c07f0000003f000090c00000c07f0000c0ff +equal 0 false false true 0 maybe{none = nothing{}} +equal_self 47103 true false false 14 maybe{some = 0} +not_equal 65535 true true false 16 maybe{some = 0} +less 34053 true false false 5 maybe{some = 0} +less_equal 34053 true false false 5 maybe{some = 0} +greater 12986 true false false 8 maybe{some = 1} +greater_equal 12986 true false false 8 maybe{some = 1} +greater_self 47103 true false false 14 maybe{some = 0} +select 000000000000803f0000204000000000000080bfe19a40c40000c07f00000000000020c03b3754c4000020c001000000000020c0000020c00000003f000080ff +select_not 00004040000020400000807f000040406dc7f343000080bf000000800000807f01000000000080bf000020400000c07f00000080000040400000c07f00002040 +sum nan smallest nan largest nan +div 0000000000002040000000000000807f6dc7f3c36e21aa3a0000c07f0000807f000080ffae689a3a000080bf0000c07f000000009a9999bf0000c07f000080ff +sqrt 00000000c262ca3fc262ca3fd7b3dd3f4ea5b0410000c0ff000000800000807f0000c0ff0000c0ff0000c0ff0000c07f00000080d7b3dd3f0000c07f0000c0ff +floor 000000000000004000000040000040400080f343000080bf000000800000807f000040c0000080bf000040c00000c07f00000080000040400000c07f000080ff +ceil 000000000000404000004040000040400000f443000080bf000000800000807f000000c0000080bf000000c00000c07f00000080000040400000c07f000080ff +trunc 000000000000004000000040000040400080f343000080bf000000800000807f000000c0000080bf000000c00000c07f00000080000040400000c07f000080ff +round 000000000000404000004040000040400000f443000080bf000000800000807f000040c0000080bf000040c00000c07f00000080000040400000c07f000080ff +round_even 000000000000004000000040000040400000f443000080bf000000800000807f000000c0000080bf000000c00000c07f00000080000040400000c07f000080ff +f64x8 +a 00000000000000000000000000001dc0000000000000f0ff000000000000f03f000000000000f0bf0000000000001dc0000000000000e03f000000000000f87f +b 00000000000008400000000000000840000000000000f0ffb96a37ad01d696360000000000000080000000000000f07f0000000000000080000000000000f03f +add 000000000000084000000000000011c0000000000000f0ff000000000000f03f000000000000f0bf000000000000f07f000000000000e03f000000000000f87f +sub 00000000000008c000000000008024c0000000000000f8ff000000000000f03f000000000000f0bf000000000000f0ff000000000000e03f000000000000f87f +mul 00000000000000000000000000c035c0000000000000f07fb96a37ad01d696360000000000000000000000000000f0ff0000000000000080000000000000f87f +negate 00000000000000800000000000001d40000000000000f07f000000000000f0bf000000000000f03f0000000000001d40000000000000e0bf000000000000f8ff +min 00000000000000000000000000001dc0000000000000f0ffb96a37ad01d69636000000000000f0bf0000000000001dc00000000000000080000000000000f87f +max 00000000000008400000000000000840000000000000f0ff000000000000f03f0000000000000080000000000000f07f000000000000e03f000000000000f87f +abs 00000000000000000000000000001d40000000000000f07f000000000000f03f000000000000f03f0000000000001d40000000000000e03f000000000000f87f +fma b96a37ad01d696360000000000c032c0000000000000f8ff000000000000e03f4e62105839138040000000000000f0ff0000000000000440000000000000f87f +equal 4 true false false 1 maybe{some = 2} +equal_self 127 true false false 7 maybe{some = 0} +not_equal 251 true false false 7 maybe{some = 0} +less 51 true false false 4 maybe{some = 0} +less_equal 55 true false false 5 maybe{some = 0} +greater 72 true false false 2 maybe{some = 3} +greater_equal 76 true false false 3 maybe{some = 2} +greater_self 127 true false false 7 maybe{some = 0} +select 00000000000000000000000000001dc0000000000000f0ffb96a37ad01d69636000000000000f0bf0000000000001dc00000000000000080000000000000f03f +select_not 00000000000008400000000000000840000000000000f0ff000000000000f03f0000000000000080000000000000f07f000000000000e03f000000000000f87f +sum nan smallest nan largest nan +div 000000000000000055555555555503c0000000000000f8ff9f5c43f0b76b4649000000000000f07f0000000000000080000000000000f0ff000000000000f87f +sqrt 0000000000000000000000000000f8ff000000000000f8ff000000000000f03f000000000000f8ff000000000000f8ffcd3b7f669ea0e63f000000000000f87f +floor 000000000000000000000000000020c0000000000000f0ff000000000000f03f000000000000f0bf00000000000020c00000000000000000000000000000f87f +ceil 00000000000000000000000000001cc0000000000000f0ff000000000000f03f000000000000f0bf0000000000001cc0000000000000f03f000000000000f87f +trunc 00000000000000000000000000001cc0000000000000f0ff000000000000f03f000000000000f0bf0000000000001cc00000000000000000000000000000f87f +round 00000000000000000000000000001cc0000000000000f0ff000000000000f03f000000000000f0bf0000000000001cc0000000000000f03f000000000000f87f +round_even 00000000000000000000000000001cc0000000000000f0ff000000000000f03f000000000000f0bf0000000000001cc00000000000000000000000000000f87f +a a8c64b3789295dc0000000000000e03f000000000000f03f00000000000004c000000000000004c00000000000000080000000000000f87f000000000000f87f +b 000000000000f03f000000000000f07f448b6ce7fb8b8ec0000000000000e03f00000000000004c000000000000000800000000000000840a8f1d24d625c6a40 +add a8c64b3789e95cc0000000000000f07f448b6ce7fb838ec000000000000000c000000000000014c00000000000000080000000000000f87f000000000000f87f +sub a8c64b3789695dc0000000000000f0ff448b6ce7fb938e4000000000000008c000000000000000000000000000000000000000000000f87f000000000000f87f +mul a8c64b3789295dc0000000000000f07f448b6ce7fb8b8ec0000000000000f4bf00000000000019400000000000000000000000000000f87f000000000000f87f +negate a8c64b3789295d40000000000000e0bf000000000000f0bf000000000000044000000000000004400000000000000000000000000000f8ff000000000000f8ff +min a8c64b3789295dc0000000000000e03f448b6ce7fb8b8ec000000000000004c000000000000004c00000000000000080000000000000f87f000000000000f87f +max 000000000000f03f000000000000f07f000000000000f03f000000000000e03f00000000000004c00000000000000080000000000000f87f000000000000f87f +abs a8c64b3789295d40000000000000e03f000000000000f03f000000000000044000000000000004400000000000000000000000000000f87f000000000000f87f +fma a8c64b3789095dc0000000000000f07f448b6ce7fbc58ec0000000000000d0bf000000000000f0bf0000000000000440000000000000f87f000000000000f87f +equal 48 true false false 2 maybe{some = 4} +equal_self 63 true false false 6 maybe{some = 0} +not_equal 207 true false false 6 maybe{some = 0} +less 11 true false false 3 maybe{some = 0} +less_equal 59 true false false 5 maybe{some = 0} +greater 4 true false false 1 maybe{some = 2} +greater_equal 52 true false false 3 maybe{some = 2} +greater_self 63 true false false 6 maybe{some = 0} +select a8c64b3789295dc0000000000000e03f448b6ce7fb8b8ec000000000000004c000000000000004c000000000000000800000000000000840a8f1d24d625c6a40 +select_not 000000000000f03f000000000000f07f000000000000f03f000000000000e03f00000000000004c00000000000000080000000000000f87f000000000000f87f +sum nan smallest nan largest nan +div a8c64b3789295dc00000000000000000108f3f5bdbc250bf00000000000014c0000000000000f03f000000000000f8ff000000000000f87f000000000000f87f +sqrt 000000000000f8ffcd3b7f669ea0e63f000000000000f03f000000000000f8ff000000000000f8ff0000000000000080000000000000f87f000000000000f87f +floor 0000000000405dc00000000000000000000000000000f03f00000000000008c000000000000008c00000000000000080000000000000f87f000000000000f87f +ceil 0000000000005dc0000000000000f03f000000000000f03f00000000000000c000000000000000c00000000000000080000000000000f87f000000000000f87f +trunc 0000000000005dc00000000000000000000000000000f03f00000000000000c000000000000000c00000000000000080000000000000f87f000000000000f87f +round 0000000000405dc0000000000000f03f000000000000f03f00000000000008c000000000000008c00000000000000080000000000000f87f000000000000f87f +round_even 0000000000405dc00000000000000000000000000000f03f00000000000000c000000000000000c00000000000000080000000000000f87f000000000000f87f +i16x32 +a ffff010000dd7b23d218ffff996e8832306f9d6c320d571d7895020015a7a13e5551a62d39d64a9b65f3ffff7dae010001007d45c654e0c50f7b51b25364b3fb +b e1e000008318020059b133dcc564021a27b4066b0000996faccc1507671b010037ed6bbec009ffffcbbb98e7eb562fdf01000e570000d59302000100e5630200 +add e0e0010083f57d232bca32dc5ed38a4c5723a3d7320df08c246217077cc2a23e8c3e11ecf9df499b30af97e7680530df02008b9cc654b559117b52b238c8b5fb +sub 1e1f01007dc479237967cc23d409861809bb9701320dbeadccc8edf8ae8ba03e1e643b6f79cc4b9b9a3767189257d22000006feec6540b320d7b50b26e00b1fb +mul 1f1f00000017f64602d3cd23bddf103550b0ae2a0000ff41a00c2a0e7370a13e432a6248c0abb66417c86818bf2a2fdf0100d647000060431ef651b23fd766f7 +negate 0100ffff002385dc2ee70100679178cdd0906393cef2a9e2886afeffeb585fc1abae5ad2c729b6649b0c01008351ffffffff83ba3aab203af184af4dad9b4d04 +min e1e0000000dd020059b133dcc564021a27b4066b0000571d7895020015a7010037ed6bbe39d64a9bcbbb98e77dae2fdf01007d450000d593020051b2e563b3fb +max ffff010083187b23d218ffff996e8832306f9d6c320d996faccc1507671ba13e5551a62dc009ffff65f3ffffeb56010001000e57c654e0c50f7b010053640200 +abs 0100010000237b23d2180100996e8832306f9d6c320d571d886a0200eb58a13e5551a62dc729b6649b0c01008351010001007d45c654203a0f7baf4d53644d04 +fma df5c40790217ebca04d3ce23c8a9412e4fb0761a7353665da10c68d145adec44c91ac42cd043b66419c8c8deba2bb9a7ad94badee4cb5f43e2bf72da40d78860 +equal 16777216 true false false 1 maybe{some = 24} +equal_self 4294967295 true true false 32 maybe{some = 0} +not_equal 4278190079 true false false 31 maybe{some = 0} +less 2722920452 true false false 11 maybe{some = 2} +less_equal 2739697668 true false false 12 maybe{some = 2} +greater 1555269627 true false false 20 maybe{some = 0} +greater_equal 1572046843 true false false 21 maybe{some = 0} +greater_self 4294967295 true true false 32 maybe{some = 0} +select e1e0000000dd020059b133dcc564021a27b4066b0000571d7895020015a7010037ed6bbe39d64a9bcbbb98e77dae2fdf01007d450000d593020051b2e563b3fb +select_not ffff010083187b23d218ffff996e8832306f9d6c320d996faccc1507671ba13e5551a62dc009ffff65f3ffffeb56010001000e57c654e0c50f7b010053640200 +sum -17443 smallest -27272 largest 31503 +div 000000000200d30b2ee700006791d8100100feff6604571d000000000f00fdff5551ffff0000a5cd0000000000000000ffff000002000100ffff0000ad9b0000 +and e1e0000000180200501033dc81640012202404680000110d28840000050301001541222c00004a9b41b398e76906010001000c450000c0810200010041600200 +or ffff010083dd7b23dbb9ffffdd6e8a3a37ff9f6f320ddf7ffcdd170777bfa13e77fdefbff9dfffffeffbfffffffe2fdf01007f57c654f5d70f7b51b2f767b3fb +xor 1e1f010083c579238ba9cc235c0a8a2817db9b07320dce72d459170772bca03e62bccd93f9dfb564ae48671896f82edf00007312c65435560d7b50b2b607b1fb +not 0000feffff2284dc2de70000669177cdcf906293cdf2a8e2876afdffea585ec1aaae59d2c629b5649a0c00008251fefffeff82ba39ab1f3af084ae4dac9b4c04 +shl ffff010000dd7b23d218ffff996e8832306f9d6c320d571d7895020015a7a13e5551a62d39d64a9b65f3ffff7dae010001007d45c654e0c50f7b51b25364b3fb +shr ffff010000dd7b23d218ffff996e8832306f9d6c320d571d7895020015a7a13e5551a62d39d64a9b65f3ffff7dae010001007d45c654e0c50f7b51b25364b3fb +shl2 80ff8000008080bd006980ff804c00440098804e009980ab00bc0001808a805080aa00d3801c00a580b280ff803e8000800080be006300f080878028802980d9 +shr2 ffff0000baff46003100ffffdd006500de00d9001a003a002aff00004eff7d00a2005b00acff36ffe6ffffff5cff000000008a00a9008bfff60064ffc800f7ff +a a94f48c267967e81c7a5aa74ffff0200ffff02006fef01004a0e3f3effff4c2600000200658431e1ffff54320000590dffff7a62a286811f2910b99093010000 +b 020036b1871184f53d1c67caffffa7bdfefbe6eaffffeaefa8e95f2b001aa06d9972cc2d4ece020089fe2a3eebe7f146ec460100ffffabc6d51703a55456d38f +add ab4f7e73eea7027704c2113ffeffa9bdfdfbe8ea6eefebeff2f79e69ff19ec939972ce2db35233e188fe7e70ebe74a54eb467b62a1862ce6fe27bc35e757d38f +sub a74f1211e084fa8b8a8943aa00005b4201041c1570ef1710a224e012ffe5acb8678d36d217b62fe176012af4151868c613b97962a386d65854f8b6eb3fab2d70 +mul 529f30c35127f85a6b44661401004e7b0204ccd59110eaef90ba61ae00e6804b0000985bc69c62c27701c8990000c9e614b97a625e792bd11d212bef3ce60000 +negate 57b0b83d9969827e395a568b0100feff0100feff9110ffffb6f1c1c10100b4d90000feff9b7bcf1e0100accd0000a7f20100869d5e797fe0d7ef476f6dfe0000 +min 020036b167967e81c7a567caffffa7bdfefbe6ea6fefeaefa8e95f2bffff4c2600000200658431e189fe5432ebe7590dffff0100a286abc62910b9909301d38f +max a94f48c2871184f53d1caa74ffff0200ffff0200ffff01004a0e3f3e001aa06d9972cc2d4ece0200ffff2a3e0000f146ec467a62ffff811fd51703a554560000 +abs a94fb83d9969827e395aaa740100020001000200911001004a0e3f3e01004c26000002009b7bcf1e010054320000590d01007a625e79811f2910476f93010000 +fma 9ace30df4dec7d7d6b442f3901002f6402043cf2a99adc16ab32180200e6b5f471777c9860ce99684d4394b6f68804ef36d27a625d79078a854fcb23c8a3d409 +equal 64 true false false 1 maybe{some = 6} +equal_self 4294967295 true true false 32 maybe{some = 0} +not_equal 4294967231 true false false 31 maybe{some = 0} +less 1974453276 true false false 17 maybe{some = 2} +less_equal 1974453340 true false false 18 maybe{some = 2} +greater 2320513955 true false false 14 maybe{some = 0} +greater_equal 2320514019 true false false 15 maybe{some = 0} +greater_self 4294967295 true true false 32 maybe{some = 0} +select 020036b167967e81c7a567caffffa7bdfefbe6ea6fefeaefa8e95f2bffff4c2600000200658431e189fe5432ebe7590dffff0100a286abc62910b9909301d38f +select_not a94f48c2871184f53d1caa74ffff0200ffff0200ffff01004a0e3f3e001aa06d9972cc2d4ece0200ffff2a3e0000f146ec467a62ffff811fd51703a554560000 +sum -2334 smallest -32386 largest 29866 +div 010000000300ffffede1feff0000000000000100000000000000ffff000000000000fefffffffaff0100ffff0000590d0000ffff010000000000000000000000 +and 000000800710048105042240ffff0200fefb02006fef000008081f2a001a0024000000004484000089fe003200005104ec460000a28681060110018010000000 +or ab4f7ef3e797fef5ffbdeffeffffa7bdffffe6eaffffebefeaef7f3fffffec6f9972ce2d6fce33e1ffff7e3eebe7f94fffff7b62ffffabdffd17bbb5d757d38f +xor ab4f7e73e087fa74fab9cdbe0000a5bd0104e4ea9010ebefe2e76015ffe5ec4b9972ce2d2b4a33e176017e0cebe7a84b13b97b625d792ad9fc07ba35c757d38f +not 56b0b73d9869817e385a558b0000fdff0000fdff9010feffb5f1c0c10000b3d9fffffdff9a7bce1e0000abcdffffa6f20000859d5d797ee0d6ef466f6cfeffff +shl 529f9084ce2cfc028e4b54e9feff0400feff0400dede0200941c7e7cfeff984c00000400ca0862c2feffa8640000b21afefff4c4440d023f5220722126030000 +shr d42724e133cbbfc0e3d2553affff0100ffff0100b7f7000025071f1fffff26130000010032c298f0ffff2a190000ac06ffff3d3151c3c00f14085cc8c9000000 +shl2 00800000008000000080000000800000008000000080008000000080008000000000000000800080008000000000008000800000000000800080008000800000 +shr2 0000ffffffffffffffff0000ffff0000ffff0000ffff000000000000ffff000000000000ffffffffffff000000000000ffff0000ffff00000000ffff00000000 +u16x32 +a 0200085400009b3402000200f30ff6cc920c732f2689a30f220c9beb0513ffffde3139e401000200660b00003b1d01000200f078010001008dfd243d8e4effff +b 0000f6ff4a8d0000b716804aa1f78652ffffa35a27a1aa44ffffd2d6dc2e01008e582451a3652fd31fc8e3f53905ffff34b8dcbbe0d80100778f264202002bfe +add 0200fe534a8d9b34b916824a94077c1f910c168a4d2a4d54210c6dc2e14100006c8a5d35a46531d385d3e3f57422000036b8cc34e1d80200048d4a7f904e2afe +sub 02001254b6729b344be982b55218707a930cd0d4ffe7f9ca230cc91429e4feff50d915935e9ad32c47431d0a02180200ce4714bd21270000166efefa8c4ed401 +mul 0000b0b7000000006e2d0095d37cc4146ef339a4caca3eaedef326d74c3effff24f90421a3655ea65a11000023a9ffff6870403ee0d801008b9f585b1c9dd501 +negate fefff8ab000065cbfefffeff0df00a336ef38dd0da765df0def36514fbec010022cec71bfffffeff9af40000c5e2fffffeff1087ffffffff7302dcc272b10100 +min 000008540000000002000200f30f8652920c732f2689a30f220cd2d605130100de31245101000200660b0000390501000200f07801000100778f243d02002bfe +max 0200f6ff4a8d9b34b716804aa1f7f6ccffffa35a27a1aa44ffff9bebdc2effff8e5839e4a3652fd31fc8e3f53b1dffff34b8dcbbe0d801008dfd26428e4effff +abs 0200085400009b3402000200f30ff6cc920c732f2689a30f220c9beb0513ffffde3139e401000200660b00003b1d01000200f078010001008dfd243d8e4effff +fma 610b4561491e15a75fb49f6986c267baca67d46f077ef7ae5ff92be8efc9075424f9692e865baffe5b11f286e84d40a869707af3e0d80200735c595b92c51636 +equal 134217728 true false false 1 maybe{some = 27} +equal_self 4294967295 true true false 32 maybe{some = 0} +not_equal 4160749567 true false false 31 maybe{some = 0} +less 666722166 true false false 21 maybe{some = 1} +less_equal 800939894 true false false 22 maybe{some = 1} +greater 3494027401 true false false 10 maybe{some = 0} +greater_equal 3628245129 true false false 11 maybe{some = 0} +greater_self 4294967295 true true false 32 maybe{some = 0} +select 000008540000000002000200f30f8652920c732f2689a30f220cd2d605130100de31245101000200660b0000390501000200f07801000100778f243d02002bfe +select_not 0200f6ff4a8d9b34b716804aa1f7f6ccffffa35a27a1aa44ffff9bebdc2effff8e5839e4a3652fd31fc8e3f53b1dffff34b8dcbbe0d801008dfd26428e4effff +sum 34319 smallest 0 largest 65535 +div 0000020000000000000000000000000000000000040000000000894e000005000200000000000200000000000000000000000000000000000100243d00000300 +and 000000540000000002000000a1078640920c230a2681a204220c92c2040201008e1020400100020006080000390501000000d03800000100058d240002002bfe +or 0200feff4a8d9b34b716824af3fff6defffff37f27a9ab4fffffdbffdd3fffffde793df5a3652fd37fcbe3f53b1dffff36b8fcfbe1d80100ffff267f8e4effff +xor 0200feab4a8d9b34b516824a52f8709e6df3d0750128094bddf3493dd93dfeff50691db5a2652dd379c3e3f50218feff36b82cc3e1d80000fa72027f8c4ed401 +not fdfff7abffff64cbfdfffdff0cf009336df38cd0d9765cf0ddf36414faec000021cec61bfefffdff99f4ffffc4e2fefffdff0f87fefffeff7202dbc271b10000 +shl 0200085400009b3402000200f30ff6cc920c732f2689a30f220c9beb0513ffffde3139e401000200660b00003b1d01000200f078010001008dfd243d8e4effff +shr 0200085400009b3402000200f30ff6cc920c732f2689a30f220c9beb0513ffffde3139e401000200660b00003b1d01000200f078010001008dfd243d8e4effff +shl2 000100040000804d0001000180f9007b004980b9009380d1001180cd808280ff00ef801c8000000100b30000809d8000000100788000800080c60092004780ff +shr2 0000a80000006900000000001f00990119005e0012011f001800d7012600ff016300c80100000000160000003a0000000000f10000000000fb017a009d00ff01 +a 0200a57200000200e0e2ff52d1ae1be4ffff974eb5544eace768099401005fe701001fd0e34ef79a02000200ffffc6eaffff0c6e0000ffff4d260100cfd07334 +b 02736e214d80adeb0c15da09f7720200b2a101001581a90d0200e45c93274a0c020061af13b3f8c40100ffffbeb04781a2228b9a5439cec9267c0806c0746d36 +add 047313944d80afebecf7d95cc8211de4b1a1984ecad5f7b9e968edf09427a9f30300807ff601ef5f03000100bdb00d6ca12297085439cdc973a209068f45e06a +sub 008d3751b37f5514d4cd2549da3b19e44d5e964ea0d3a59ee56825376ed815dbffffbe20d09bffd501000300414f7f695ddd81d3acc6313627aaf9f90f5c06fe +mul 04e6e68700005ad7800226a4a7bd36c84e5e974ed9277eb5ced10414932776550200bf0cd993483b0200feff424feae25edd84f8000032366efb08064067f796 +negate feff5b8d0000feff201d01ad2f51e51b010069b14babb2531997f76bffffa118ffffe12f1db10965fefffeff01003a150100f49100000100b3d9ffff312f8dcb +min 02006e21000002000c15da09f7720200b2a10100b554a90d0200e45c01004a0c010061afe34ef79a01000200beb04781a2220c6e0000cec94d260100c0747334 +max 0273a5724d80adebe0e2ff52d1ae1be4ffff974e15814eace768099493275fe702001fd013b3f8c40200ffffffffc6eaffff8b9a5439ffff267c0806cfd06d36 +abs 0200a57200000200e0e2ff52d1ae1be4ffff974eb5544eace768099401005fe701001fd0e34ef79a02000200ffffc6eaffff0c6e0000ffff4d260100cfd07334 +fma 05e687a7f52b5cd77f0237b6982aa2b64e5e2782a5634c3975c1ab26952780107f2d86c213784a3b38eed4f3434fdc96f34bcef0bc97313641c619664167e9c5 +equal 0 false false true 0 maybe{none = nothing{}} +equal_self 4294967295 true true false 32 maybe{some = 0} +not_equal 4294967295 true true false 32 maybe{some = 0} +less 3056419853 true false false 14 maybe{some = 0} +less_equal 3056419853 true false false 14 maybe{some = 0} +greater 1238547442 true false false 18 maybe{some = 1} +greater_equal 1238547442 true false false 18 maybe{some = 1} +greater_self 4294967295 true true false 32 maybe{some = 0} +select 02006e21000002000c15da09f7720200b2a10100b554a90d0200e45c01004a0c010061afe34ef79a01000200beb04781a2220c6e0000cec94d260100c0747334 +select_not 0273a5724d80adebe0e2ff52d1ae1be4ffff974e15814eace768099493275fe702001fd013b3f8c40200ffffffffc6eaffff8b9a5439ffff267c0806cfd06d36 +sum 44474 smallest 0 largest 65535 +div 000037260000000001000000453a04000a0000000200030002002600000003000000020000000400000000005555010001000100000001000000000000007b11 +and 02002420000000000000da00d1220200b2a101001500080c0200001401004a04000001800302f08000000200beb04680a222080a0000cec904240000c0506134 +or 0273ef734d80afebecf7ff5bf7fe1be4ffff974eb5d5efade768eddc93275fef03007ffff3ffffde0300ffffffffc7ebffff8ffe5439ffff6f7e0906cff47f36 +xor 0073cb534d80afebecf7255b26dc19e44d5e964ea0d5e7a1e568edc8922715eb03007e7ff0fd0f5e0300fdff414f816b5ddd87f4543931366b5a09060fa41e02 +not fdff5a8dfffffdff1f1d00ad2e51e41b000068b14aabb1531897f66bfeffa018feffe02f1cb10865fdfffdff000039150000f391ffff0000b2d9feff302f8ccb +shl 04004ae500000400c0c5fea5a25d36c8feff2e9d6aa99c58ced112280200bece02003ea0c69dee3504000400feff8cd5feff18dc0000feff9a4c02009ea1e668 +shr 010052390000010070717f2968570d72ff7f4b275a2a27567334044a0000af7300000f6871277b4d01000100ff7f6375ff7f06370000ff7f261300006768391a +shl2 00000080000000000000008000800080008000800080000000800080008000800080008000800080000000000080000000800000000000800080008000800080 +shr2 00000000000000000100000001000100010000000000010000000100000001000000010000000100000000000100010001000000000001000000000001000000 +i32x16 +a 00000000da55112101000000020000005d4e8dd9010000005095f139be8eb5f0ffffffff68c061fddb0ff9f7d26617c72632c1f702000000010000005f1d7207 +b 78735f293930bcb69510a5314b533d195b21f5f16224a6cb4b9a477ab02d9e16d0d74c11cb7a542a7f890d4eb6ea1f7bffffffff02000000f8404e6afd930d7e +add 78735f291386cdd79610a5314d533d19b86f82cb6324a6cb9b2f39b46ebc5307cfd74c11333bb6275a990646885137422532c1f704000000f9404e6a5cb17f85 +sub 888ca0d6a125556a6cef5aceb7acc2e6022d98e79fdb593405fba9bf0e6117da2f28b3ee9d450dd35c86eba91c7cf74b2732c1f70000000009bfb19562896489 +mul 000000008afd0ca59510a53196a67a320fd855186224a6cb70dec8d6a0882dd43028b3ee782255b4a5102ad64c0d0d48dacd3e0804000000f8404e6ae3937722 +negate 0000000026aaeedefffffffffeffffffa3b17226ffffffffb06a0ec642714a0f01000000983f9e0225f006082e99e838dacd3e08feffffffffffffffa1e28df8 +min 000000003930bcb601000000020000005d4e8dd96224a6cb5095f139be8eb5f0ffffffff68c061fddb0ff9f7d26617c72632c1f702000000010000005f1d7207 +max 78735f29da5511219510a5314b533d195b21f5f1010000004b9a477ab02d9e16d0d74c11cb7a542a7f890d4eb6ea1f7bffffffff02000000f8404e6afd930d7e +abs 00000000da5511210100000002000000a3b17226010000005095f13942714a0f01000000983f9e0225f006082e99e838dacd3e0802000000010000005f1d7207 +fma b5cc7740ba1df9239510a5314de6135617c4c8206224a6cb882e2b653d982ae93228b3ee593c130ea7102ad6a32c988f6a8e3a250500000049941ae1ebe343f8 +equal 8192 true false false 1 maybe{some = 13} +equal_self 65535 true true false 16 maybe{some = 0} +not_equal 57343 true false false 15 maybe{some = 0} +less 57309 true false false 13 maybe{some = 0} +less_equal 65501 true false false 14 maybe{some = 0} +greater 34 true false false 2 maybe{some = 1} +greater_equal 8226 true false false 3 maybe{some = 1} +greater_self 65535 true true false 16 maybe{some = 0} +select 000000003930bcb601000000020000005d4e8dd96224a6cb5095f139be8eb5f0ffffffff68c061fddb0ff9f7d26617c72632c1f702000000010000005f1d7207 +select_not 78735f29da5511219510a5314b533d195b21f5f1010000004b9a477ab02d9e16d0d74c11cb7a542a7f890d4eb6ea1f7bffffffff02000000f8404e6afd930d7e +sum -521449755 smallest -954767662 largest 972133712 +div 00000000010000000000000002000000f5ffffff000000001a875013000000000000000000000000ffffffff69b38be300000000000000000000000000000000 +and 00000000181010200100000002000000590085d10000000040904138b00c9410d0d74c11484040285b090946926217432632c1f702000000000000005d110006 +or 78735f29fb75bdb79510a5314b533d195f6ffdf96324a6cb5b9ff77bbeafbff6ffffffffebfa75ffff8ffdfff6ee1fffffffffff02000000f9404e6aff9f7f7f +xor 78735f29e365ad979410a53149533d19066f78286324a6cb1b0fb6430ea32be62f28b3eea3ba35d7a486f4b9648c08bcd9cd3e0800000000f9404e6aa28e7f79 +not ffffffff25aaeedefefffffffdffffffa2b17226feffffffaf6a0ec641714a0f00000000973f9e0224f006082d99e838d9cd3e08fdfffffffeffffffa0e28df8 +shl 00000000da55112101000000020000005d4e8dd9010000005095f139be8eb5f0ffffffff68c061fddb0ff9f7d26617c72632c1f702000000010000005f1d7207 +shr 00000000da55112101000000020000005d4e8dd9010000005095f139be8eb5f0ffffffff68c061fddb0ff9f7d26617c72632c1f702000000010000005f1d7207 +shl2 0000000000edaa888000000000010000802ea7c68000000000a8caf8005fc75a80ffffff0034e0b080ed87fc0069b38b001399e0000100008000000080af0eb9 +shr2 00000000ab22420000000000000000009c1ab3ff000000002ae373001d6be1ffffffffff80c3faff1ff2efffcd2e8eff6482efff00000000000000003ae40e00 +a 076db2510d2ea386010000004019a37302000000f31ac34206257d2f71c950e1ffffffff520ff0093b2c3c30ffffffff2a5c3950020000002645f98b50b3e5fe +b ee84b3ff971df39290939132de8124d1e346c7ca0ffdaedb73b48936ac2e47db01000000bf4308a441ccb006e2b2b837b148ae7e00000000000000004c81b40a +add f5f16551a44b9619919391321e9bc744e546c7ca0218721e79d906661df897bc000000001153f8ad7cf8ec36e1b2b837dba4e7ce020000002645f98b9c349a09 +sub 19e8fe517610b0f3716c6ecd62977ea21fb93835e41d14679370f3f8c59a0906feffffff93cbe765fa5f8b291d4d47c879138bd1020000002645f98b043231f4 +mul 82f8fd28aba2ce069093913280252944c68d8e953dbb3aedb2d97567eca5d06fffffffff2ee4ad40fb3e16fd1e4d47c80a8920ea0000000000000000c08bcc9f +negate f9924daef3d15c79ffffffffc0e65c8cfeffffff0de53cbdfada82d08f36af1e01000000aef00ff6c5d3c3cf01000000d6a3c6affeffffffdaba0674b04c1a01 +min ee84b3ff0d2ea38601000000de8124d1e346c7ca0ffdaedb06257d2fac2e47dbffffffffbf4308a441ccb006ffffffff2a5c3950000000002645f98b50b3e5fe +max 076db251971df392909391324019a37302000000f31ac34273b4893671c950e101000000520ff0093b2c3c30e2b2b837b148ae7e02000000000000004c81b40a +abs 076db251f3d15c79010000004019a37302000000f31ac34206257d2f8f36af1e01000000520ff0093b2c3c30010000002a5c395002000000daba0674b04c1a01 +fma 3a395fcacc51834733ddac8980252944cb8e66ba649a8c2d659dad0da15dfc4140ca1f728c3a0cd4fd3e16fddfd36f480d3f0f1c78fd92ca020000000d32cebb +equal 0 false false true 0 maybe{none = nothing{}} +equal_self 65535 true true false 16 maybe{some = 0} +not_equal 65535 true true false 16 maybe{some = 0} +less 55622 true false false 8 maybe{some = 1} +less_equal 55622 true false false 8 maybe{some = 1} +greater 9913 true false false 8 maybe{some = 0} +greater_equal 9913 true false false 8 maybe{some = 0} +greater_self 65535 true true false 16 maybe{some = 0} +select ee84b3ff0d2ea38601000000de8124d1e346c7ca0ffdaedb06257d2fac2e47dbffffffffbf4308a441ccb006ffffffff2a5c3950000000002645f98b50b3e5fe +select_not 076db251971df392909391324019a37302000000f31ac34273b4893671c950e101000000520ff0093b2c3c30e2b2b837b148ae7e02000000000000004c81b40a +sum -1261548050 smallest -2036126195 largest 1940068672 +div 076db251010000000000000051000000feffffff0000000006257d2f0100000000000000520ff0091d161e18000000000500000000000000daba067400000000 +and 0604b251050ca3820000000040012051020000000318824202240926200840c10100000012030000010c3000e2b2b8372048285000000000000000004081a40a +or efedb3ff9f3ff39691939132de99a7f3e346c7caffffefdb77b5fd3ffdef57fbffffffffff4ff8ad7becbc36ffffffffbb5cbf7e020000002645f98b5cb3f5fe +xor e9e901ae9a335014919391329e9887a2e146c7cafce76d997591f419dde7173afeffffffed4cf8ad7ae08c361d4d47c89b14972e020000002645f98b1c3251f4 +not f8924daef2d15c79feffffffbfe65c8cfdffffff0ce53cbdf9da82d08e36af1e00000000adf00ff6c4d3c3cf00000000d5a3c6affdffffffd9ba0674af4c1a01 +shl 0eda64a31a5c460d02000000803246e704000000e63586850c4afa5ee292a1c2feffffffa41ee01376587860feffffff54b872a0040000004c8af217a066cbfd +shr 8336d928069751c300000000a08cd13901000000798d61218392be17b864a8f0ffffffffa907f8041d161e18ffffffff15ae1c280100000093a2fcc5a8d972ff +shl2 0080833600800697008000000000a08c000001000080798d000083920080b8640080ffff0000a90700801d160080ffff000015ae00000100000093a20000a8d9 +shr2 64a30000460dffff0000000046e700000000000086850000fa5e0000a1c2ffffffffffffe013000078600000ffffffff72a0000000000000f217ffffcbfdffff +u32x16 +a ff7612ee02000000db75a2cc000000003c6cc6553b649d43ffffffffffffffff020000003a960465b5f4dea0945ae32001000000ffffffffffffffff02000000 +b b28feac38118be74000000004d9826b0b16f5423b8462f7d19e869f6f2837310852aa1a500000000ffffffff0c8d39c7ec0acaf1f2f2225bc0fe04fbf3f6d77f +add b106fdb18318be74db75a2cc4d9826b0eddb1a79f3aaccc018e869f6f1837310872aa1a53a960465b4f4dea0a0e71ce8ed0acaf1f1f2225bbffe04fbf5f6d77f +sub 4de7272a81e7418bdb75a2ccb367d94f8bfc7132831d6ec6e61796090d7c8cef7dd55e5a3a960465b6f4dea088cda95915f5350e0d0ddda43f01fb040f092880 +mul 4e2e65db02317ce900000000000000007cd9ce0e682c5dd8e71796090e7c8cef0a55424b000000004b0b215ff0c27ffaec0acaf10e0ddda44001fb04e6edafff +negate 0189ed11feffffff258a5d3300000000c49339aac59b62bc0100000001000000feffffffc669fb9a4b0b215f6ca51cdfffffffff0100000001000000feffffff +min b28feac3020000000000000000000000b16f54233b649d4319e869f6f28373100200000000000000b5f4dea0945ae32001000000f2f2225bc0fe04fb02000000 +max ff7612ee8118be74db75a2cc4d9826b03c6cc655b8462f7dffffffffffffffff852aa1a53a960465ffffffff0c8d39c7ec0acaf1fffffffffffffffff3f6d77f +abs ff7612ee02000000db75a2cc000000003c6cc6553b649d43ffffffffffffffff020000003a960465b5f4dea0945ae32001000000ffffffffffffffff02000000 +fma a38be95f30e74b0e02000000ca560065eac5ef28c2d33bd774d2c23c87c1740f0955424b553f032b7e852ca7b73df181ee0acaf10f0ddda49a915eae5f596d54 +equal 0 false false true 0 maybe{none = nothing{}} +equal_self 65535 true true false 16 maybe{some = 0} +not_equal 65535 true true false 16 maybe{some = 0} +less 40234 true false false 8 maybe{some = 1} +less_equal 40234 true false false 8 maybe{some = 1} +greater 25301 true false false 8 maybe{some = 0} +greater_equal 25301 true false false 8 maybe{some = 0} +greater_self 65535 true true false 16 maybe{some = 0} +select b28feac3020000000000000000000000b16f54233b649d4319e869f6f28373100200000000000000b5f4dea0945ae32001000000f2f2225bc0fe04fb02000000 +select_not ff7612ee8118be74db75a2cc4d9826b03c6cc655b8462f7dffffffffffffffff852aa1a53a960465ffffffff0c8d39c7ec0acaf1fffffffffffffffff3f6d77f +sum 2061476567 smallest 0 largest 4294967295 +div 0200000000000000ed3a516600000000010000000700000001000000090000000000000000000000000000000000000000000000030000000200000000000000 +and b20602c2000000000000000000000000306c440138440d4119e869f6f28373100000000000000000b5f4dea00408210000000000f2f2225bc0fe04fb02000000 +or fffffaef8318be74db75a2cc4d9826b0bd6fd677bb66bf7fffffffffffffffff872aa1a53a960465ffffffff9cdffbe7ed0acaf1fffffffffffffffff3f6d77f +xor 4df9f82d8318be74db75a2cc4d9826b08d0392768322b23ee61796090d7c8cef872aa1a53a9604654a0b215f98d7dae7ed0acaf10d0ddda43f01fb04f1f6d77f +not 0089ed11fdffffff248a5d33ffffffffc39339aac49b62bc0000000000000000fdffffffc569fb9a4a0b215f6ba51cdffeffffff0000000000000000fdffffff +shl ff7612ee02000000db75a2cc000000003c6cc6553b649d43ffffffffffffffff020000003a960465b5f4dea0945ae32001000000ffffffffffffffff02000000 +shr ff7612ee02000000db75a2cc000000003c6cc6553b649d43ffffffffffffffff020000003a960465b5f4dea0945ae32001000000ffffffffffffffff02000000 +shl2 807f3b090001000080ed3a5100000000001e36e3801db2ce80ffffff80ffffff00010000001d4b82805a7a6f004aad718000000080ffffff80ffffff00010000 +shr2 ed24dc0100000000eb44990100000000d88cab00c83a8700ffffff01ffffff01000000002c09ca00e9bd4101b5c6410000000000ffffff01ffffff0100000000 +a 020000000000000034a8932160f371b59726f5548868f9026985508bffffffffc3d8b4090200000001000000b92eca70cde3f4d4785b5a2d2d489c2c0ad5b7e5 +b 00000000000000000200000091abbe9723f999ee01000000aa7289e61a7e51a4d2d18fa00100000002a15ca80000000001000000000000008c18d49dda58ee0b +add 020000000000000036a89321f19e304dba1f8f438968f90213f8d971197e51a495aa44aa0300000003a15ca8b92eca70cee3f4d4785b5a2db96070cae42da6f1 +sub 020000000000000032a89321cf47b31d742d5b668768f902bf12c7a4e581ae5bf106256901000000ff5ea357b92eca70cce3f4d4785b5a2da12fc88e307cc9d9 +mul 00000000000000006850274360f95b24a5254c828868f902ba59121ae681ae5bf6023e900200000002a15ca800000000cde3f4d4000000009cb07f6a84da124d +negate feffffff00000000cc576cdea00c8e4a69d90aab789706fd977aaf74010000003d274bf6feffffffffffffff47d1358f331c0b2b88a4a5d2d3b763d3f62a481a +min 00000000000000000200000091abbe979726f554010000006985508b1a7e51a4c3d8b40901000000010000000000000001000000000000002d489c2cda58ee0b +max 020000000000000034a8932160f371b523f999ee8868f902aa7289e6ffffffffd2d18fa00200000002a15ca8b92eca70cde3f4d4785b5a2d8c18d49d0ad5b7e5 +abs 020000000000000034a8932160f371b59726f5548868f9026985508bffffffffc3d8b4090200000001000000b92eca70cde3f4d4785b5a2d2d489c2c0ad5b7e5 +fma ce6d36f6b012c1661422b786e5215428cc4b80f0acb3f071bc59121aae45aa48f9e04b58f732730d02a15ca8ffffffffe3d77b2f860377e09db07f6adaca88cc +equal 2 true false false 1 maybe{some = 1} +equal_self 65535 true true false 16 maybe{some = 0} +not_equal 65533 true false false 15 maybe{some = 0} +less 17744 true false false 5 maybe{some = 4} +less_equal 17746 true false false 6 maybe{some = 1} +greater 47789 true false false 10 maybe{some = 0} +greater_equal 47791 true false false 11 maybe{some = 0} +greater_self 65535 true true false 16 maybe{some = 0} +select 00000000000000000200000091abbe979726f554010000006985508b1a7e51a4c3d8b40901000000010000000000000001000000000000002d489c2cda58ee0b +select_not 020000000000000034a8932160f371b523f999ee8868f902aa7289e6ffffffffd2d18fa00200000002a15ca8b92eca70cde3f4d4785b5a2d8c18d49d0ad5b7e5 +sum 1231492120 smallest 0 largest 4294967295 +div 00000000000000000a00000060f371b50000000000000000782c702effffffff00000000000000000000000000000000cde3f4d47d1e1e0f0000000000000000 +and 00000000000000000000000000a330950320914400000000280000821a7e51a4c2d0840000000000000000000000000001000000000000000c08940c0a50a601 +or 020000000000000036a89321f1fbffb7b7fffdfe8968f902ebf7d9efffffffffd3d9bfa90300000003a15ca8b92eca70cde3f4d4785b5a2dad58dcbddaddffef +xor 020000000000000036a89321f158cf22b4df6cba8968f902c3f7d96de581ae5b11093ba90300000003a15ca8b92eca70cce3f4d4785b5a2da15048b1d08d59ee +not fdffffffffffffffcb576cde9f0c8e4a68d90aab779706fd967aaf74000000003c274bf6fdfffffffeffffff46d1358f321c0b2b87a4a5d2d2b763d3f52a481a +shl 040000000000000068502743c0e6e36a2e4deaa910d1f205d20aa116feffffff86b169130400000002000000725d94e19ac7e9a9f0b6b45a5a90385914aa6fcb +shr 01000000000000001ad4c910b0f9b85a4b937a2a44b47c01b442a845ffffff7f616cda0401000000000000005c176538e6717a6abc2dad1616244e1685eadb72 +shl2 000001000000000000001ad40000b0f900804b93000044b40080b4420080ffff0080616c000001000080000000805c170080e6710000bc2d00801624000085ea +shr2 000000000000000027430000e36a0100eaa90000f2050000a1160100ffff010069130000000000000000000094e10000e9a90100b45a0000385900006fcb0100 +i64x8 +a 4a6654a906d2c10abe692abff5048d1c88ce669ab66ee793177154c4eb47c7038dc1ea6842f3e05e6089fa4dcbc0e8340200000000000000e700ae99a244e3dc +b ac972ac707981434ffffffffffffffff000000000000000025f1682a0fc3b9e4d41d4605da07679be6e1f253fea570e99e43155afd708cd644a8d97d739bcb5e +add f6fd7e700e6ad63ebd692abff5048d1c88ce669ab66ee7933c62bdeefa0a81e861df306e1cfb47fa466beda1c966591ea043155afd708cd62ba9871716e0ae3b +sub 9ece29e2fe39add6bf692abff5048d1c88ce669ab66ee793f27feb99dc840d1fb9a3a46368eb79c37aa707facc1a784b64bceaa5028f7329a358d41b2fa9177e +mul b85f2edbbc29a6f34296d5400afb72e3000000000000000053ff02961b1b3615c441e327ecebfbdf40cc943ed10427983c872ab4fae118ad5cd59e91bf6f2a51 +negate b699ab56f92d3ef54296d5400afb72e3783199654991186ce98eab3b14b838fc733e1597bd0c1fa1a07605b2343f17cbfeffffffffffffff19ff51665dbb1c23 +min 4a6654a906d2c10affffffffffffffff88ce669ab66ee79325f1682a0fc3b9e4d41d4605da07679be6e1f253fea570e99e43155afd708cd6e700ae99a244e3dc +max ac972ac707981434be692abff5048d1c0000000000000000177154c4eb47c7038dc1ea6842f3e05e6089fa4dcbc0e834020000000000000044a8d97d739bcb5e +abs 4a6654a906d2c10abe692abff5048d1c783199654991186c177154c4eb47c7038dc1ea6842f3e05e6089fa4dcbc0e834020000000000000019ff51665dbb1c23 +fma b8bdbe15deb254ef83dac93c5adf463ff08f8f626e0aafc949a5cba139aea6a83345d22537ad67bc6487873b79e49e903e872ab4fae118adcbdf9ce260d8c10e +equal 0 false false true 0 maybe{none = nothing{}} +equal_self 255 true true false 8 maybe{some = 0} +not_equal 255 true true false 8 maybe{some = 0} +less 133 true false false 3 maybe{some = 0} +less_equal 133 true false false 3 maybe{some = 0} +greater 122 true false false 5 maybe{some = 1} +greater_equal 122 true false false 5 maybe{some = 1} +greater_self 255 true true false 8 maybe{some = 0} +select 4a6654a906d2c10affffffffffffffff88ce669ab66ee79325f1682a0fc3b9e4d41d4605da07679be6e1f253fea570e99e43155afd708cd6e700ae99a244e3dc +select_not ac972ac707981434be692abff5048d1c0000000000000000177154c4eb47c7038dc1ea6842f3e05e6089fa4dcbc0e834020000000000000044a8d97d739bcb5e +sum 3.4347053400832973e+18 smallest -7.789135299960451e+18 largest 6.836731700902019e+18 +div 00000000000000000000000000000000feffffffffffffff5dd0c6964e6d4201010000000000000004000000000000000000000000000000e700ae99a244e3dc +and 0806008106900000be692abff5048d1c0000000000000000057140000b438100840142004203601a6081f241ca8060200200000000000000440088192200c35c +or eef77eef07dad53effffffffffffffff88ce669ab66ee79337f17ceeefc7ffe7ddddee6ddaf7e7dfe6e9fa5fffe5f8fd9e43155afd708cd6e7a8fffdf3dfebde +xor e6f17e6e014ad53e4196d5400afb72e388ce669ab66ee79332803ceee4847ee759dcac6d98f487c58668081e356598dd9c43155afd708cd6a3a877e4d1df2882 +not b599ab56f92d3ef54196d5400afb72e3773199654991186ce88eab3b14b838fc723e1597bd0c1fa19f7605b2343f17cbfdffffffffffffff18ff51665dbb1c23 +shl 4a6654a906d2c10abe692abff5048d1c88ce669ab66ee793177154c4eb47c7038dc1ea6842f3e05e6089fa4dcbc0e8340200000000000000e700ae99a244e3dc +shr 4a6654a906d2c10abe692abff5048d1c88ce669ab66ee793177154c4eb47c7038dc1ea6842f3e05e6089fa4dcbc0e8340200000000000000e700ae99a244e3dc +shl2 002533aa5403e96000df3495df7a8246004467334d5bb7f3808b382ae2f5a3e380c6607534a1797000b044fda66560740001000000000000807300d74c51a271 +shr2 cca8520da4831500d3547eeb091a39009dcd346dddce27ffe2a888d78f8e070083d5d184e6c1bd0012f59b9681d169000000000000000000015c334589c6b9ff +a 02000000000000002fc0a2226f1a32e0730d1da3422677e9fe09c06e636a26e441f9d35736f961f4ffffffffffffffff3a0f5de060084c36d3b02dd92428db1a +b 0200000000000000fdff2a3e360087bf0200000000000000a8d38323e3063aebb3eb35ddb1c992e6bd334949721710fbc7a1bba374dc26c6ca5e7454795ba9ab +add 04000000000000002cc0cd60a51ab99f750d1da3422677e9a6dd4392467160cff4e40935e8c2f4dabc334949721710fb01b11884d5e472fc9d0fa22d9e8384c6 +sub 000000000000000032c077e4381aab20710d1da3422677e956363c4b8063ecf88e0d9e7a842fcf0d42ccb6b68de8ef04736da13cec2b25700952b984abcc316f +mul 040000000000000073bffc417e769572e61a3a46854ceed2b0e83ccd6583fc8d73f37ab69fafad0743ccb6b68de8ef04165048fc5c53db957e00978046305f82 +negate feffffffffffffffd13f5ddd90e5cd1f8df2e25cbdd9881602f63f919c95d91bbf062ca8c9069e0b0100000000000000c6f0a21f9ff7b3c92d4fd226dbd724e5 +min 0200000000000000fdff2a3e360087bf730d1da3422677e9fe09c06e636a26e4b3eb35ddb1c992e6bd334949721710fbc7a1bba374dc26c6ca5e7454795ba9ab +max 02000000000000002fc0a2226f1a32e00200000000000000a8d38323e3063aeb41f9d35736f961f4ffffffffffffffff3a0f5de060084c36d3b02dd92428db1a +abs 0200000000000000d13f5ddd90e5cd1f8df2e25cbdd9881602f63f919c95d91bbf062ca8c9069e0b01000000000000003a0f5de060084c36d3b02dd92428db1a +fma c2617cec1b476fbb438b06682291ce45c5765feef678f35355a59b3d8358959c00485c725d806eae91c415aff79c2b3ea862c50a0772d2ac6dd493d6ac5e0b10 +equal 1 true false false 1 maybe{some = 0} +equal_self 255 true true false 8 maybe{some = 0} +not_equal 254 true false false 7 maybe{some = 1} +less 12 true false false 2 maybe{some = 2} +less_equal 13 true false false 3 maybe{some = 0} +greater 242 true false false 5 maybe{some = 1} +greater_equal 243 true false false 6 maybe{some = 0} +greater_self 255 true true false 8 maybe{some = 0} +select 0200000000000000fdff2a3e360087bf730d1da3422677e9fe09c06e636a26e4b3eb35ddb1c992e6bd334949721710fbc7a1bba374dc26c6ca5e7454795ba9ab +select_not 02000000000000002fc0a2226f1a32e00200000000000000a8d38323e3063aeb41f9d35736f961f4ffffffffffffffff3a0f5de060084c36d3b02dd92428db1a +sum -9.11744929257058e+17 smallest -2.2917401957533778e+18 largest 3.9125113884521964e+18 +div 000000000000000001000000000000008df2e25cbdd9881602f63f919c95d91ba1fce92b9bfc30fa00000000000000009d872e703004261b0000000000000000 +and 02000000000000002dc02222260002a00200000000000000a8018022630222e001e9115530c900e4bd334949721710fb020119a060080406c21024502008890a +or 0200000000000000ffffaa3e7f1ab7ff730d1da3422677e9fedbc36fe36e3eeff3fbf7dfb7f9f3f6ffffffffffffffffffafffe374dc6ef6dbfe7ddd7d7bfbbb +xor 0000000000000000d23f881c591ab55f710d1da3422677e956da434d806c1c0ff212e68a8730f31242ccb6b68de8ef04fdaee64314d46af019ee598d5d7372b1 +not fdffffffffffffffd03f5ddd90e5cd1f8cf2e25cbdd9881601f63f919c95d91bbe062ca8c9069e0b0000000000000000c5f0a21f9ff7b3c92c4fd226dbd724e5 +shl 04000000000000005e804545de3464c0e61a3a46854ceed2fc1380ddc6d44cc882f2a7af6cf2c3e8feffffffffffffff741ebac0c110986ca6615bb24950b635 +shr 010000000000000017605191370d19f0b9868e512193bbf4ff0460b7313513f2a0fce92b9bfc30faffffffffffffffff9d872e703004261b69d8966c12946d0d +shl2 0000010000000000008017605191370d0080b9868e5121930000ff0460b731350080a0fce92b9bfc0080ffffffffffff00009d872e703004008069d8966c1294 +shr2 00000000000000004545de3464c0ffff3a46854ceed2ffff80ddc6d44cc8ffffa7af6cf2c3e8ffffffffffffffffffffbac0c110986c00005bb24950b6350000 +u64x8 +a ffffffffffffffff010000000000000002000000000000000000000000000000aba75380d6962d0a308c736d3ae8996be695597523f90650330d8bf8f40c68f6 +b c6778afff3f95d024c5c39ef9207f7eb8fe3b7f4f3ad111f97e240412c3b97f402000000000000002b1c2c9ec9909fb7ffffffffffffffffea5261b39a5de203 +add c5778afff3f95d024d5c39ef9207f7eb91e3b7f4f3ad111f97e240412c3b97f4ada75380d6962d0a5ba89f0b04793923e595597523f906501d60ecab8f6a4afa +sub 398875000c06a2fdb5a3c6106df80814731c480b0c52eee0691dbfbed3c4680ba9a75380d6962d0a057047cf7057fab3e795597523f9065049ba29455aaf85f2 +mul 3a8875000c06a2fd4c5c39ef9207f7eb1ec76fe9e75b233e0000000000000000564fa700ad2d5b1410ccfdbdda973c321a6aa68adc06f9af9e66a762202e5509 +negate 0100000000000000fffffffffffffffffeffffffffffffff00000000000000005558ac7f2969d2f5d0738c92c51766941a6aa68adc06f9afcdf274070bf39709 +min c6778afff3f95d020100000000000000020000000000000000000000000000000200000000000000308c736d3ae8996be695597523f90650ea5261b39a5de203 +max ffffffffffffffff4c5c39ef9207f7eb8fe3b7f4f3ad111f97e240412c3b97f4aba75380d6962d0a2b1c2c9ec9909fb7ffffffffffffffff330d8bf8f40c68f6 +abs ffffffffffffffff010000000000000002000000000000000000000000000000aba75380d6962d0a308c736d3ae8996be695597523f90650330d8bf8f40c68f6 +fma 14a2990010f134693368e1bc483244301ec76fe9e75b233e9dbaff070347ec19832102d53f54797a204830dd7f3023c7eb0e0de55747f7a8c10f6f185ad64916 +equal 0 false false true 0 maybe{none = nothing{}} +equal_self 255 true true false 8 maybe{some = 0} +not_equal 255 true true false 8 maybe{some = 0} +less 110 true false false 5 maybe{some = 1} +less_equal 110 true false false 5 maybe{some = 1} +greater 145 true false false 3 maybe{some = 0} +greater_equal 145 true false false 3 maybe{some = 0} +greater_self 255 true true false 8 maybe{some = 0} +select c6778afff3f95d020100000000000000020000000000000000000000000000000200000000000000308c736d3ae8996be695597523f90650ea5261b39a5de203 +select_not ffffffffffffffff4c5c39ef9207f7eb8fe3b7f4f3ad111f97e240412c3b97f4aba75380d6962d0a2b1c2c9ec9909fb7ffffffffffffffff330d8bf8f40c68f6 +sum 1.356217374055097e+19 smallest 0 largest 1.8446744073709552e+19 +div ffffffffffffffff000000000000000000000000000000000000000000000000000000000000000018c6b9361df4cc3501000000000000000100000000000000 +and c6778afff3f95d020000000000000000020000000000000000000000000000000200000000000000200c200c08809923e695597523f90650220001b0900c6002 +or ffffffffffffffff4d5c39ef9207f7eb8fe3b7f4f3ad111f97e240412c3b97f4aba75380d6962d0a3b9c7ffffbf89ffffffffffffffffffffb5febfbfe5deaf7 +xor 398875000c06a2fd4d5c39ef9207f7eb8de3b7f4f3ad111f97e240412c3b97f4a9a75380d6962d0a1b905ff3f37806dc196aa68adc06f9afd95fea4b6e518af5 +not 0000000000000000fefffffffffffffffdffffffffffffffffffffffffffffff5458ac7f2969d2f5cf738c92c5176694196aa68adc06f9afccf274070bf39709 +shl ffffffffffffffff010000000000000002000000000000000000000000000000aba75380d6962d0a308c736d3ae8996be695597523f90650330d8bf8f40c68f6 +shr ffffffffffffffff010000000000000002000000000000000000000000000000aba75380d6962d0a308c736d3ae8996be695597523f90650330d8bf8f40c68f6 +shl2 80ffffffffffffff80000000000000000001000000000000000000000000000080d5d329406bcb160018c6b9361df4cc00f3caacba917c03809986457c7a0634 +shr2 ffffffffffffff010000000000000000000000000000000000000000000000004fa700ad2d5b140018e7da74d033d7002bb3ea46f20da0001a16f1e919d0ec01 +a 72c8db1843c5b09d02000000000000009bd406c9494e30180200000000000000116e232c6a70a33ad4fe6af7cd9eee1b55d2b03baf5cea420100000000000000 +b 8711c78df45277cd58c70c8bd06ee18247253a2ce6abbf4d4cc0f7557cc6b786b57403602bd4d4d6e2d9e5332293eba8010000000000000011bf5723c5c876db +add f9d9a2a63718286b5ac70c8bd06ee182e2f940f52ffaef654ec0f7557cc6b786c6e2268c95447811b6d8502bf031dac456d2b03baf5cea4212bf5723c5c876db +sub ebb6148b4e7239d0aa38f3742f911e7d54afcc9c63a270cab63f08aa833948795cf91fcc3e9cce63f22485c3ab0b037354d2b03baf5cea42f040a8dc3a378924 +mul 1e46d44ef06bd8bfb08e1916a1ddc205fd5dbd8cdda4c6869880efabf88c6f0d05861fed9cf577c328ab1a4e3000f35c55d2b03baf5cea4211bf5723c5c876db +negate 8e3724e7bc3a4f62feffffffffffffff652bf936b6b1cfe7feffffffffffffffef91dcd3958f5cc52c019508326111e4ab2d4fc450a315bdffffffffffffffff +min 72c8db1843c5b09d02000000000000009bd406c9494e30180200000000000000116e232c6a70a33ad4fe6af7cd9eee1b01000000000000000100000000000000 +max 8711c78df45277cd58c70c8bd06ee18247253a2ce6abbf4d4cc0f7557cc6b786b57403602bd4d4d6e2d9e5332293eba855d2b03baf5cea4211bf5723c5c876db +abs 72c8db1843c5b09d02000000000000009bd406c9494e30180200000000000000116e232c6a70a33ad4fe6af7cd9eee1b55d2b03baf5cea420100000000000000 +fma 25e08696ba9ddcf9af8e1916a1ddc205f92cf5e9632e528e9980efabf88c6f0da40d3a60a8b3db0128ab1a4e3000f35c97ffbd6307eb75a1e89c112fe47de47a +equal 0 false false true 0 maybe{none = nothing{}} +equal_self 255 true true false 8 maybe{some = 0} +not_equal 255 true true false 8 maybe{some = 0} +less 191 true false false 7 maybe{some = 0} +less_equal 191 true false false 7 maybe{some = 0} +greater 64 true false false 1 maybe{some = 6} +greater_equal 64 true false false 1 maybe{some = 6} +greater_self 255 true true false 8 maybe{some = 0} +select 72c8db1843c5b09d02000000000000009bd406c9494e30180200000000000000116e232c6a70a33ad4fe6af7cd9eee1b01000000000000000100000000000000 +select_not 8711c78df45277cd58c70c8bd06ee18247253a2ce6abbf4d4cc0f7557cc6b786b57403602bd4d4d6e2d9e5332293eba855d2b03baf5cea4211bf5723c5c876db +sum 5.71886723911607e+18 smallest 1 largest 1.1362798751826299e+19 +div 00000000000000000000000000000000000000000000000000000000000000000100000000000000000000000000000001000000000000000000000000000000 +and 0200c3084040308d000000000000000003040208400a30080000000000000000116403202a508012c0d860330092ea0801000000000000000100000000000000 +or f7d9df9df7d7f7dd5ac70c8bd06ee182dff53eedefefbf5d4ec0f7557cc6b786b57e236c6bf4f7fef6ffeff7ef9fefbb55d2b03baf5cea4211bf5723c5c876db +xor f5d91c95b797c7505ac70c8bd06ee182dcf13ce5afe58f554ec0f7557cc6b786a41a204c41a477ec36278fc4ef0d05b354d2b03baf5cea4210bf5723c5c876db +not 8d3724e7bc3a4f62fdffffffffffffff642bf936b6b1cfe7fdffffffffffffffee91dcd3958f5cc52b019508326111e4aa2d4fc450a315bdfeffffffffffffff +shl e490b731868a613b040000000000000036a90d92939c6030040000000000000022dc4658d4e04675a8fdd5ee9b3ddd37aaa461775eb9d4850200000000000000 +shr 39e46d8ca162d84e01000000000000004d6a83e42427180c010000000000000008b7111635b8511d6a7fb5fb664ff70d2a69d89d572e75210000000000000000 +shl2 000039e46d8ca162000001000000000000804d6a83e424270000010000000000008008b7111635b800006a7fb5fb664f00802a69d89d572e0080000000000000 +shr2 b731868a613b010000000000000000000d92939c6030000000000000000000004658d4e046750000d5ee9b3ddd37000061775eb9d48500000000000000000000 diff --git a/tests/programs/simd_lanes_agree_everywhere_2.sakura b/tests/programs/simd_lanes_agree_everywhere_2.sakura new file mode 100644 index 00000000..8614eedc --- /dev/null +++ b/tests/programs/simd_lanes_agree_everywhere_2.sakura @@ -0,0 +1,165 @@ +import std::io; +import std::math; + +# Every operation of std's vectors of 64 bytes gives the same bits wherever it +# runs: in the machine, in an executable, where AVX-512 works the lanes or they +# are worked a half or a quarter at a time, and in constants worked out while +# compiling. Each line is an operation's result, its bytes in hex, for vectors of +# each type of lane made of random lanes and the edges of their types. + +const compiled: f32[16] = (f32x16::splat(1.5) * f32x16::splat(3.0) + f32x16::splat(-0.0)).min(&f32x16::splat(4.0)).lanes(); +const counted: u32 = u16x32::splat(7).less(&u16x32::splat(9)).bits(); + +var seed: u64 = 0x9E3779B97F4A7C15; + +def next(): u64 { + seed = seed ^ (seed << 13); + seed = seed ^ (seed >> 7); + seed = seed ^ (seed << 17); + return seed; +} + +const digits: strview = "0123456789abcdef"; + +def hex_of(bytes: *u8, count: u64, out: &mut string): void { + for i in 0..count { + val b := bytes[i]; + out.push(digits[(b >> 4) as u64]); + out.push(digits[(b & 15) as u64]); + } +} + +def show(name: strview, v: &simd): void where L: numeric, ordered, zeroable { + var out := string::from(name, nothing {}); + out.append(" "); + val held := v.lanes(); + hex_of((&held) as *u8, N * size_of::(), &mut out); + io::println(out.view()); +} + +def show_mask(name: strview, m: &mask): void where L: numeric, ordered, zeroable { + val bits := m.bits(); + io::println($"{name} {bits} {m.any()} {m.all()} {m.none()} {m.count()} {m.first()}"); +} + +# A lane worth testing: random bits, or a special value of its type. +def lane(): L where L: numeric, ordered, zeroable { + val pick := next() % 16; + if const L is real { + val specials: f64[12] = [0.0, -0.0, 1.0, -1.0, 0.5, -2.5, 2.5, 1e300, -1e-310, 3.0, 1e-45, -7.25]; + if pick < 12 { + return specials[pick] as L; + } + if pick == 12 { + return math::infinity::(); + } + if pick == 13 { + return -math::infinity::(); + } + if pick == 14 { + return math::nan::(); + } + return ((next() % 2000000) as f64 / 1000.0 - 1000.0) as L; + } + if const L is integer { + if pick < 3 { + return pick as L; + } + if pick == 3 { + return ~(0 as L); + } + var made: L; + val bits := next(); + val p := (&mut made) as *mut u8; + for k in 0..size_of::() { + p[k] = ((bits >> (8 * k)) & 0xFF) as u8; + } + return made; + } + var none: L; + return none; +} + +def vector(): simd where L: numeric, ordered, zeroable { + var made: simd; + for i in 0..N { + made[i] = lane::(); + } + return made; +} + +def nonzero(): simd where L: numeric, ordered, zeroable { + var made := vector::(); + for i in 0..N { + if made[i] == 0 as L { + made[i] = 3 as L; + } + } + return made; +} + +def exercise(name: strview): void where L: numeric, ordered, zeroable { + io::println(name); + for round in 0..2 { + val a := vector::(); + val b := vector::(); + val c := vector::(); + show("a", &a); + show("b", &b); + show("add", &(a + b)); + show("sub", &(a - b)); + show("mul", &(a * b)); + show("negate", &(-a)); + show("min", &a.min(&b)); + show("max", &a.max(&b)); + show("abs", &a.abs()); + show("fma", &a.fma(&b, &c)); + show_mask("equal", &a.equal(&b)); + show_mask("equal_self", &a.equal(&a)); + show_mask("not_equal", &a.not_equal(&b)); + show_mask("less", &a.less(&b)); + show_mask("less_equal", &a.less_equal(&b)); + show_mask("greater", &a.greater(&b)); + show_mask("greater_equal", &a.greater_equal(&b)); + show_mask("greater_self", &a.greater_equal(&a)); + val m := a.less(&b); + show("select", &select(m, a, b)); + show("select_not", &select(~m, a, b)); + io::println($"sum {a.sum() as f64} smallest {a.smallest() as f64} largest {a.largest() as f64}"); + if const L is real { + show("div", &(a / b)); + show("sqrt", &a.sqrt()); + show("floor", &a.floor()); + show("ceil", &a.ceil()); + show("trunc", &a.trunc()); + show("round", &a.round()); + show("round_even", &a.round_even()); + } + if const L is integer { + show("div", &(a / nonzero::())); + show("and", &(a & b)); + show("or", &(a | b)); + show("xor", &(a ^ b)); + show("not", &(~a)); + val counts: u32[8] = [0, 1, 7, 15, 31, 63, 64, 100]; + val count := counts[round as u64]; + show("shl", &(a << count)); + show("shr", &(a >> count)); + val other := counts[(round + 2) as u64]; + show("shl2", &(a << other)); + show("shr2", &(a >> other)); + } + } +} + +def main(): void { + io::println($"compiled {compiled[0]} {compiled[15]} {counted}"); + exercise::("f32x16"); + exercise::("f64x8"); + exercise::("i16x32"); + exercise::("u16x32"); + exercise::("i32x16"); + exercise::("u32x16"); + exercise::("i64x8"); + exercise::("u64x8"); +} diff --git a/tests/programs/simd_values_in_registers_1.out b/tests/programs/simd_values_in_registers_1.out new file mode 100644 index 00000000..20526a10 --- /dev/null +++ b/tests/programs/simd_values_in_registers_1.out @@ -0,0 +1,7 @@ +bytes 21828 +pressure 1757775 1757775 1757775 1757775 +calls 1855618120 3692818858 1487609312 4086318392 +tagged 3 3.375 -6.75 11.8125 0.84375 +array 104 +dots 138 +clamped -2 -1 0 3 7 10 10 -2 diff --git a/tests/programs/simd_values_in_registers_1.sakura b/tests/programs/simd_values_in_registers_1.sakura new file mode 100644 index 00000000..a3fe1d52 --- /dev/null +++ b/tests/programs/simd_values_in_registers_1.sakura @@ -0,0 +1,134 @@ +import std::io; +import std::math; + +# Vectors an executable holds in registers between operations: carried around +# loops, more of them at once than there are registers, across calls, in the +# fields of structs and in arrays, and 32 bytes of them in code for processors +# with AVX2, which runs where this one has it. Every result is the same as the +# virtual machine's, lane by lane. + +def show(name: strview, v: &u32x4): void { + val lanes := v.lanes(); + io::println($"{name} {lanes[0]} {lanes[1]} {lanes[2]} {lanes[3]}"); +} + +# A sum carried around a loop, each byte widened to 16 bits. +def byte_sum(text: strview): u64 { + var total := u16x16::splat(0); + var at: u64 = 0; + while at + 16 <= text.length { + total = total + u8x16::load(text, at).convert::(); + at += 16; + } + var sum: u64 = 0; + for i in 0..16u { + sum += total[i] as u64; + } + for i in at..text.length { + sum += text[i] as u64; + } + return sum; +} + +# Twelve vectors live at once, more than the registers holding them. +def pressure(seed: u32): u32x4 { + val a := u32x4::splat(seed); + val b := a + u32x4::splat(1); + val c := b * u32x4::splat(3); + val d := c ^ a; + val e := d + b; + val f := e * c; + val g := f - d; + val h := g + e; + val i := h ^ f; + val j := i + g; + val k := j * h; + val l := k - i; + return a + b + c + d + e + f + g + h + i + j + k + l; +} + +# A call made while vectors are live, which holds them in memory across it. +def opaque(x: u32): u32 { + return x * 2654435761 + 7; +} + +def across_calls(rounds: u32): u32x4 { + var acc := u32x4::of([1, 2, 3, 4]); + val step := u32x4::of([5, 6, 7, 8]); + for r in 0..rounds { + acc = acc * step + u32x4::splat(opaque(r)); + } + return acc; +} + +# A vector in a struct beside a word, and vectors in an array. +struct tagged { + var count: u64; + var lanes: f32x4; +} + +def scaled(t: tagged, by: f32): tagged { + return tagged { count = t.count + 1, lanes = t.lanes * f32x4::splat(by) }; +} + +def array_of(n: u32): u32 { + var vs: u32x4[4]; + for i in 0..4u { + vs[i] = u32x4::splat(n + i as u32); + } + var total := u32x4::splat(0); + for i in 0..4u { + total = total + vs[i]; + } + return total.sum(); +} + +# 32 bytes of lanes, with operations that ask the processor, so the function has +# a version for x86-64-v3 which holds them in registers. +def dots(xs: span, ys: span): f32 { + var acc := f32x8::splat(0.0); + var at: u64 = 0; + while at + 8 <= xs.length { + acc = f32x8::load(xs, at).fma(&f32x8::load(ys, at), &acc); + at += 8; + } + return acc.sum(); +} + +# Masks, selection, and comparison chains. +def clamped(v: i32x8, low: i32, high: i32): i32x8 { + val lo := i32x8::splat(low); + val hi := i32x8::splat(high); + val raised := select(v.less(&lo), lo, v); + return select(raised.greater(&hi), hi, raised); +} + +def main(): void { + var text := string::new(nothing {}); + for i in 0..200u { + text.push(('a' as u64 + i % 26) as u8); + } + io::println($"bytes {byte_sum(text.view())}"); + + show("pressure", &pressure(7)); + show("calls", &across_calls(10)); + + var t := tagged { count = 0, lanes = f32x4::of([1.0, -2.0, 3.5, 0.25]) }; + for _ in 0..3 { + t = scaled(t, 1.5); + } + val l := t.lanes.lanes(); + io::println($"tagged {t.count} {l[0]} {l[1]} {l[2]} {l[3]}"); + io::println($"array {array_of(5)}"); + + var xs := vector::::new(); + var ys := vector::::new(); + for i in 0..100u { + xs.append((i % 7) as f32 * 0.5); + ys.append((i % 5) as f32 - 1.0); + } + io::println($"dots {dots(xs.view(), ys.view())}"); + + val c := clamped(i32x8::of([-9, -1, 0, 3, 7, 12, 100, -100]), -2, 10).lanes(); + io::println($"clamped {c[0]} {c[1]} {c[2]} {c[3]} {c[4]} {c[5]} {c[6]} {c[7]}"); +} diff --git a/tests/programs/static_trait_methods_1.out b/tests/programs/static_trait_methods_1.out new file mode 100644 index 00000000..ea646fde --- /dev/null +++ b/tests/programs/static_trait_methods_1.out @@ -0,0 +1,3 @@ +-2147483648..2147483647 0..255 +point (1, 2) (1, 2) hi (1, 2) +7 7 99 diff --git a/tests/programs/static_trait_methods_1.sakura b/tests/programs/static_trait_methods_1.sakura new file mode 100644 index 00000000..be1700f3 --- /dev/null +++ b/tests/programs/static_trait_methods_1.sakura @@ -0,0 +1,35 @@ +import std::io; +trait limits { def max(): T; def min(): T; } +def i32::max(): i32 { return 2147483647; } +def i32::min(): i32 { return -2147483648; } +def u8::max(): u8 { return 255; } +def u8::min(): u8 { return 0; } +trait named { + def type_name(): string; + def describe(&this): string; + def greet(&this): string { return $"hi {this.describe()}"; } +} +struct point: named { var x: int; var y: int; } +def point::type_name(): string { return "point"; } +def point::describe(&this): string { return $"({this.x}, {this.y})"; } +trait maker { def make(): S; } +struct box: maker> where T: numeric { var v: T; } +def box::make(): box { return box{ v = 7 }; } +trait ceiling where T: ceiling { + def max(): T; + def top(&this): T { return T::max(); } +} +struct level: ceiling { var n: int; } +def level::max(): level { return level{ 99 }; } +def span(): string where T: limits { return $"{T::min()}..{T::max()}"; } +def show(x: &T): string where T: named { return $"{T::type_name()} {x.describe()}"; } +def fresh(): S where S: maker { return S::make(); } +def peak(x: &ceiling): level { return x.top(); } +def main(): void { + println($"{span::()} {span::()}"); + val p := point{ 1, 2 }; + val r: &named = &p; + println($"{show(p)} {r.describe()} {r.greet()}"); + val b: box = fresh(); + println($"{b.v} {fresh::>().v} {peak(level{ 1 }).n}"); +} diff --git a/tests/programs/strings_unions_shadowing_and_ternaries_1.out b/tests/programs/strings_unions_shadowing_and_ternaries_1.out new file mode 100644 index 00000000..d239d8c5 --- /dev/null +++ b/tests/programs/strings_unions_shadowing_and_ternaries_1.out @@ -0,0 +1 @@ +a! b1! hey! true true true false false true 9 value{number = 5} diff --git a/tests/programs/strings_unions_shadowing_and_ternaries_1.sakura b/tests/programs/strings_unions_shadowing_and_ternaries_1.sakura new file mode 100644 index 00000000..626e275b --- /dev/null +++ b/tests/programs/strings_unions_shadowing_and_ternaries_1.sakura @@ -0,0 +1,27 @@ +import std::io; +struct nothing {} +union value { var none: nothing; var number: i64; var text: span; } +type kind = u8; +val kind::text := 2; +struct holder { val name: span; var held: value; } +def shout(text: span): string { return $"{text}!"; } +def check(kind: kind): bool { return kind == kind::text; } +def loud(text: span): string { return $"{text}!"; } +def main(): void { + val word := "hey"; + print($"{loud("a")} {shout($"b{1}")} "); + val spoken := shout(word); + var h := holder{ name = spoken }; + var v: value; + print($"{h.name} {h.held is none} {v is none} {check(2)} {check(3)} "); + h.held.number = 5; + var n := 1; + var i := 0; + while i < 2 { + val target := i == 0 ? &mut n as *mut int : null; + if target != null { target[0] = 9; } + print($"{target == null} "); + i++; + } + println($"{n} {h.held}"); +} diff --git a/tests/programs/structs_1.out b/tests/programs/structs_1.out new file mode 100644 index 00000000..a34508b4 --- /dev/null +++ b/tests/programs/structs_1.out @@ -0,0 +1,4 @@ +point{x = 1, y = 0} point{x = 1, y = 5} point{x = 0, y = 0} 3 8 +rect{pos = point{x = 3, y = 0}, size = size{w = 4, h = 2}, name = unnamed} +11 13 point{x = 4, y = 8} 8 +13 99 unnamed copy pair{a = 3, b = 1.5} diff --git a/tests/programs/structs_1.sakura b/tests/programs/structs_1.sakura new file mode 100644 index 00000000..38f834a1 --- /dev/null +++ b/tests/programs/structs_1.sakura @@ -0,0 +1,30 @@ +import std::io; +struct point { var x := 1; var y: int; } +struct size { var w: f32; var h: f32 = 2; } +struct rect { + var pos: ...point { x as left }; + var size: ...size; + var name: span = "unnamed"; +} +struct pair { var a: int; var b: f32; } +val point::origin := point{0, 0}; +def point::moved(this: &point, by: int): point { return point{this.x + by, this.y + by}; } +def point::shift(this: &mut point): void { this.x += 10; } +def rect::area(this: &rect): f32 { return this.w * this.h; } +def main(): void { + var p: point; + var q := point{ y = 5 }; + var r: rect; + r.left = 3; + r.w = 4; + println($"{p} {q} {point::origin} {r.left} {r.area()}"); + println($"{r}"); + p.shift(); + r.pos.shift(); + val moved := q.moved(1).moved(2); + println($"{p.x} {r.left} {moved} {point{7, 8}.moved(1).x}"); + var copy := r; + copy.left = 99; + copy.name = "copy"; + println($"{r.left} {copy.left} {r.name} {copy.name} {pair{3, 1.5}}"); +} diff --git a/tests/programs/structs_of_no_fields_are_returned_1.out b/tests/programs/structs_of_no_fields_are_returned_1.out new file mode 100644 index 00000000..c53f37b1 --- /dev/null +++ b/tests/programs/structs_of_no_fields_are_returned_1.out @@ -0,0 +1,3 @@ +12 7 2 +1 1 +7 14 2 2 diff --git a/tests/programs/structs_of_no_fields_are_returned_1.sakura b/tests/programs/structs_of_no_fields_are_returned_1.sakura new file mode 100644 index 00000000..a00af7a8 --- /dev/null +++ b/tests/programs/structs_of_no_fields_are_returned_1.sakura @@ -0,0 +1,25 @@ +import std::io; + +struct counter { var calls: i64; } +def counter::bump(&mut this): i64 { this.calls++; return this.calls; } + +# A struct of no fields is returned, called, and held as any other. +struct empty {} +def empty::twice(&this, x: i64): i64 { return x * 2; } +def empty::invoke(&this, x: i64): i64 { return x + 1; } +def empty::again(&this): empty { return empty{}; } +def make(): empty { return empty{}; } +def pass(value: T): T { return value; } + +struct holder { var n: i64; var e: empty; } + +def main(): void { + var a := counter{}; + val r: &mut counter = &mut a; + println($"{make().twice(6)} {make()(6)} {make().again().twice(1)}"); + println($"{r.bump()} {a.calls}"); + var h := holder{ n = 7, e = make() }; + h.e = pass(make()); + val kept := pass(h.e); + println($"{h.n} {kept.twice(h.n)} {r.bump()} {a.calls}"); +} diff --git a/tests/programs/swar_words_agree_everywhere_1.out b/tests/programs/swar_words_agree_everywhere_1.out new file mode 100644 index 00000000..058bebd0 --- /dev/null +++ b/tests/programs/swar_words_agree_everywhere_1.out @@ -0,0 +1,96 @@ +0: 7381153994262081367 + space:00000100 first 5 last 5 count 1 + zero:00000000 first 8 last 8 count 0 + below 0x20:00000000 first 8 last 8 count 0 + above 'r':00001000 first 4 last 4 count 1 + digit:00000000 first 8 last 8 count 0 + ascii:11111111 first 0 last 7 count 8 + letters first 0, rest first 1, not first 5 + upper 5066303647815716695 lower 7381153994262081399 spread 18446463698244468735 +8: 664970774573572640 + space:10000000 first 0 last 0 count 1 + zero:00000000 first 8 last 8 count 0 + below 0x20:00000001 first 7 last 7 count 1 + above 'r':00110100 first 2 last 5 count 3 + digit:00000000 first 8 last 8 count 0 + ascii:11111111 first 0 last 7 count 8 + letters first 1, rest first 2, not first 0 + upper 664935452223554080 lower 664970774573572640 spread 281474976710400 +16: 7234303152770606451 + space:00000000 first 8 last 8 count 0 + zero:00000000 first 8 last 8 count 0 + below 0x20:00000000 first 8 last 8 count 0 + above 'r':10000000 first 0 last 0 count 1 + digit:00000000 first 8 last 8 count 0 + ascii:11111111 first 0 last 7 count 8 + letters first 0, rest first 1, not first 8 + upper 4919417621952152915 lower 7234303152770606451 spread 18446744073709551615 +24: 6998721812694132000 + space:10000010 first 0 last 6 count 2 + zero:00000000 first 8 last 8 count 0 + below 0x20:00000000 first 8 last 8 count 0 + above 'r':00000100 first 5 last 5 count 1 + digit:00000000 first 8 last 8 count 0 + ascii:11111111 first 0 last 7 count 8 + letters first 1, rest first 2, not first 0 + upper 4692843481130419488 lower 6998721812694132000 spread 18374967954648334080 +32: 7308613717772542068 + space:01010000 first 1 last 3 count 2 + zero:00000000 first 8 last 8 count 0 + below 0x20:00000000 first 8 last 8 count 0 + above 'r':10001000 first 0 last 4 count 2 + digit:00000000 first 8 last 8 count 0 + ascii:11111111 first 0 last 7 count 8 + letters first 0, rest first 2, not first 1 + upper 4993728187490967636 lower 7308613717772542068 spread 18446744069431296255 +40: 3472616376864219180 + space:01000000 first 1 last 1 count 1 + zero:00000000 first 8 last 8 count 0 + below 0x20:00000000 first 8 last 8 count 0 + above 'r':00000000 first 8 last 8 count 0 + digit:00111111 first 2 last 7 count 6 + ascii:11111111 first 0 last 7 count 8 + letters first 8, rest first 8, not first 0 + upper 3472616376864219180 lower 3472616376864219180 spread 0 +48: 8031449901867742769 + space:00010000 first 3 last 3 count 1 + zero:00000000 first 8 last 8 count 0 + below 0x20:00000000 first 8 last 8 count 0 + above 'r':00000010 first 6 last 6 count 1 + digit:11000000 first 0 last 1 count 2 + ascii:11111111 first 0 last 7 count 8 + letters first 5, rest first 6, not first 0 + upper 5716564509027218993 lower 8031449901867742769 spread 18446742974197923840 +56: 6998631678325581172 + space:00000010 first 6 last 6 count 1 + zero:00000000 first 8 last 8 count 0 + below 0x20:00000000 first 8 last 8 count 0 + above 'r':10000000 first 0 last 0 count 1 + digit:00000000 first 8 last 8 count 0 + ascii:11111111 first 0 last 7 count 8 + letters first 0, rest first 1, not first 3 + upper 4692788531670828372 lower 6998631678325581172 spread 18374687574905061375 +64: 3343199723092730990 + space:00100000 first 2 last 2 count 1 + zero:00000000 first 8 last 8 count 0 + below 0x20:00000000 first 8 last 8 count 0 + above 'r':00000000 first 8 last 8 count 0 + digit:00000000 first 8 last 8 count 0 + ascii:11111111 first 0 last 7 count 8 + letters first 0, rest first 1, not first 2 + upper 3334157201490068558 lower 3343199723092730990 spread 72057594021216255 +72: 663584 + space:11000000 first 0 last 1 count 2 + zero:00011111 first 3 last 7 count 5 + below 0x20:00111111 first 2 last 7 count 6 + above 'r':00000000 first 8 last 8 count 0 + digit:00000000 first 8 last 8 count 0 + ascii:11111111 first 0 last 7 count 8 + letters first 8, rest first 8, not first 0 + upper 663584 lower 663584 spread 0 +find 25 36 999 71 +find_any 14 15 999 +index_of 53 last 70 count 7 +ascii true false upper WORDS OF BYTES: lower words of bytes: +digits 20261016 999 +constants 52 20261016 12, running 52 20261016 12 diff --git a/tests/programs/swar_words_agree_everywhere_1.sakura b/tests/programs/swar_words_agree_everywhere_1.sakura new file mode 100644 index 00000000..e320e660 --- /dev/null +++ b/tests/programs/swar_words_agree_everywhere_1.sakura @@ -0,0 +1,56 @@ +import std::io; +import core::swar; + +# Words of bytes, and the text functions that go by them, give the same results +# wherever they run: in either compiler's machine, in an executable, and in +# constants worked out while compiling. A mask made of masks by operators is a +# mask, with a mask's methods. + +const text: strview = "Words of bytes:\tsearched eight at a time, 20261016, \"quoted\\n\" and done. \n"; + +def place(found: maybe): u64 { + if found is some(at) { + return at; + } + return 999; +} + +const found_quote: u64 = place(text.find("\"quoted")); +const date: u64 = place(swar::load(text, 42).digits()); +const spaces: u64 = text.count_of(&' '); + +def show_mask(name: strview, mask: swar::mask8): void { + print($"{name}:"); + for k in 0..8u { + print((mask & (0x80u << (k * 8))) != 0 ? "1" : "0"); + } + println($" first {mask.first()} last {mask.last()} count {mask.count()}"); +} + +def main(): void { + # Each test of each word of the text. + var at: u64 = 0; + while at < text.length { + val word := swar::load_last(text, at); + println($"{at}: {word}"); + show_mask(" space", word.equal(' ')); + show_mask(" zero", word.zero()); + show_mask(" below 0x20", word.below(0x20)); + show_mask(" above 'r'", word.above('r')); + show_mask(" digit", word.within('0', '9')); + show_mask(" ascii", word.ascii()); + # Operators keep the mask, so its methods are called on what they give. + val letters := word.within('a', 'z') | word.within('A', 'Z'); + println($" letters first {letters.first()}, rest first {letters.rest().first()}, not first {(~letters & 0x8080808080808080).first()}"); + println($" upper {word.upper()} lower {word.lower()} spread {letters.spread()}"); + at += 8; + } + + # The text functions. + println($"find {place(text.find("eight"))} {place(text.find("time,"))} {place(text.find("absent"))} {place(text.find("."))}"); + println($"find_any {place(text.find_any(",:"))} {place(text.find_any("\t\""))} {place(text.find_any("!?;#@"))}"); + println($"index_of {place(text.index_of(&'q'))} last {place(text.last_index_of(&'e'))} count {text.count_of(&'e')}"); + println($"ascii {text.is_ascii()} {"caf\xC3\xA9".is_ascii()} upper {text.upper().view().substr(0, 15)} lower {text.lower().view().substr(0, 15)}"); + println($"digits {place(swar::load(text, 42).digits())} {place(swar::load(text, 41).digits())}"); + println($"constants {found_quote} {date} {spaces}, running {place(text.find("\"quoted"))} {place(swar::load(text, 42).digits())} {text.count_of(&' ')}"); +} diff --git a/tests/programs/ternaries_name_what_their_tests_give_1.out b/tests/programs/ternaries_name_what_their_tests_give_1.out new file mode 100644 index 00000000..b7a587aa --- /dev/null +++ b/tests/programs/ternaries_name_what_their_tests_give_1.out @@ -0,0 +1 @@ +5 0 8 -1 diff --git a/tests/programs/ternaries_name_what_their_tests_give_1.sakura b/tests/programs/ternaries_name_what_their_tests_give_1.sakura new file mode 100644 index 00000000..4ef9c16a --- /dev/null +++ b/tests/programs/ternaries_name_what_their_tests_give_1.sakura @@ -0,0 +1,8 @@ +import std::io; +def bumped(m: maybe): int { return m is some(v) ? v + 1 : 0; } +def doubled(m: maybe): int { return m is not some(v) ? -1 : v * 2; } +def main(): void { + val none: maybe = nothing {}; + val four: maybe = maybe::{ some = 4 }; + println($"{bumped(four)} {bumped(none)} {doubled(four)} {doubled(none)}"); +} diff --git a/tests/programs/ternary_branches_take_fallbacks_1.out b/tests/programs/ternary_branches_take_fallbacks_1.out new file mode 100644 index 00000000..f44b982f --- /dev/null +++ b/tests/programs/ternary_branches_take_fallbacks_1.out @@ -0,0 +1,10 @@ +out/prog.exe | out/prog | out/prog.exe [out/prog] | out/prog [] +out/prog.exe | out/prog.o | out/prog.exe [out/prog.o] | out/prog.o [] +out.exe | out | out.exe [out] | out [] +0: 200 300 3 0 +1: 200 300 1 5 +2: 1 1 2 1 +left: odd +7 2 -1 calls 102 +zero +5 -7 diff --git a/tests/programs/ternary_branches_take_fallbacks_1.sakura b/tests/programs/ternary_branches_take_fallbacks_1.sakura new file mode 100644 index 00000000..89926ec1 --- /dev/null +++ b/tests/programs/ternary_branches_take_fallbacks_1.sakura @@ -0,0 +1,73 @@ +import std::io; + +# The branch a ternary takes where its condition holds ends at `:`, so it may be a +# fallback, `ok ? parse(text) else 0 : 1`, which is only worked out where that +# branch is taken. An owning value the union of a result holds is named with +# `is value(&p)`, then copied or moved by name. + +struct flags { var build: bool; } +struct job { var flags: flags; var system: strview; } + +# A path is written with its system's delimiter, `\` on Windows, so each is shown +# with `/` to read the same on every system. +def shown(text: strview): string { + var made := string::new(nothing {}); + for byte in text { made.push(byte == path_delim ? '/' : byte); } + return made; +} + +def named(asked: &job, given: strview): string { + val outpath := path::parse(given); + if outpath is not value(&p) { return string::from("bad", nothing {}); } + val final := asked.flags.build && asked.system == "windows" + ? p.with_extension("exe") else copy(p) + : copy(p); + return shown(final.view()); +} + +def moved(asked: &job, given: strview): string { + var outpath := path::parse(given); + if outpath is not value(&mut p) { return string::from("bad", nothing {}); } + val final := asked.flags.build && asked.system == "windows" + ? p.with_extension("exe") else move(p) + : move(p); + return string::from($"{shown(final.view())} [{shown(p.view())}]", nothing {}); +} + +def half(n: i64): maybe { + return nothing {} if n % 2 != 0; + return n / 2; +} +def halve(n: i64): result { + return "odd" if n % 2 != 0; + return n / 2; +} + +var calls: i64 = 0; +def counted(n: i64): maybe { calls++; return half(n); } +def fallen(): i64 { calls += 100; return -1; } + +const known: i64 = true ? half(10) else 0 : 99; +const unknown: i64 = true ? half(7) else -7 : 99; + +def main(): void { + val win := job { flags = flags { build = true }, system = "windows" }; + val lin := job { flags = flags { build = true }, system = "linux" }; + for &each in ["out/prog", "out/prog.o", "out/"] { + println($"{named(&win, each)} | {named(&lin, each)} | {moved(&win, each)} | {moved(&lin, each)}"); + } + for n in 0..4 { + val a := n > 1 ? half(n) else 100 : 200; + val b := n > 1 ? halve(n) else (e) { println($"left: {e}"); continue; } : 300; + val c := n > 2 ? half(n) else 1 : n > 0 ? half(n + 1) else 2 : 3; + val d := n > 1 ? half(n) else 4 : (half(n) else 5); + println($"{n}: {a} {b} {c} {d}"); + } + calls = 0; + val e := false ? counted(4) else fallen() : 7; + val f := true ? counted(4) else fallen() : 7; + val g := true ? counted(5) else fallen() : 7; + println($"{e} {f} {g} calls {calls}"); + if (true ? half(3) else 0 : 1) == 0 { println("zero"); } + println($"{known} {unknown}"); +} diff --git a/tests/programs/text_constants_are_indexed_as_views_1.out b/tests/programs/text_constants_are_indexed_as_views_1.out new file mode 100644 index 00000000..6a6174ec --- /dev/null +++ b/tests/programs/text_constants_are_indexed_as_views_1.out @@ -0,0 +1 @@ +66 120 3 true diff --git a/tests/programs/text_constants_are_indexed_as_views_1.sakura b/tests/programs/text_constants_are_indexed_as_views_1.sakura new file mode 100644 index 00000000..86cabce8 --- /dev/null +++ b/tests/programs/text_constants_are_indexed_as_views_1.sakura @@ -0,0 +1,6 @@ +import std::io; +def count(of: u8): u64 { var n := 0u; for _ in 0u..3u { for i in 0u..5u { if "ABCDE"[i] == of { n++; } } } return n; } +def main(): void { + val first := "xyz"[0]; + println($"{"ABCDE"[1]} {first} {count(68)} {"ABCDE"[4] == 69}"); +} diff --git a/tests/programs/text_is_a_view_of_the_program_own_bytes_1.out b/tests/programs/text_is_a_view_of_the_program_own_bytes_1.out new file mode 100644 index 00000000..f4168d92 --- /dev/null +++ b/tests/programs/text_is_a_view_of_the_program_own_bytes_1.out @@ -0,0 +1,5 @@ +5 119 100 +true false true +world +0 true +14 still an array diff --git a/tests/programs/text_is_a_view_of_the_program_own_bytes_1.sakura b/tests/programs/text_is_a_view_of_the_program_own_bytes_1.sakura new file mode 100644 index 00000000..98bbdc2c --- /dev/null +++ b/tests/programs/text_is_a_view_of_the_program_own_bytes_1.sakura @@ -0,0 +1,17 @@ +import std::io; +def takes(text: span): u64 { return text.length; } +def main(): void { + val v: span = "world"; + println($"{takes(v)} {v[0]} {v[4]}"); + val same := v == "world"; + val diff := v == "other"; + val ne := v != "other"; + println($"{same} {diff} {ne}"); + var out: u8[5]; + for i in 0..v.length { out[i] = v[i]; } + println(span::::over((&out) as *u8, 5)); + val empty: span = ""; + println($"{empty.length} {empty.data == null}"); + val array: span = "still an array"; + println($"{array.length} {array}"); +} diff --git a/tests/programs/text_is_split_lazily_1.out b/tests/programs/text_is_split_lazily_1.out new file mode 100644 index 00000000..0a8b6406 --- /dev/null +++ b/tests/programs/text_is_split_lazily_1.out @@ -0,0 +1 @@ +[a][bb][][c] 4 [bb] <> a-bb-c 3 4 (one two)(three)(four) 6 5 threefour 1 0 diff --git a/tests/programs/text_is_split_lazily_1.sakura b/tests/programs/text_is_split_lazily_1.sakura new file mode 100644 index 00000000..9003e277 --- /dev/null +++ b/tests/programs/text_is_split_lazily_1.sakura @@ -0,0 +1,27 @@ +import std::io; + +# `split`, `lines`, `words`, and `chars` give their parts one at a time, as views +# of the text, so nothing is made until a caller collects them. +def main(): void { + val csv: strview = "a,bb,,c"; + for part in csv.split(',') { print($"[{part}]"); } + print(" "); + val parts := csv.split(',').to_vector(); + print($"{parts.length} [{parts[1]}] "); + # A split also walks from its far end. + for part in csv.split(',').rev() { print($"<{part}>"); } + print(" "); + val dash: strview = "-"; + print($"{csv.split(',').filter(def(p) => p.length > 0).to_string(dash)} "); + val text: strview = "one two\n three\r\nfour"; + print($"{text.lines().count()} {text.words().count()} "); + for line in text.lines() { print($"({line.trim()})"); } + print(" "); + val word: strview = "héllo"; + print($"{word.length} {word.chars().count()} "); + var owned := string::new(nothing {}); + text.words().filter(def(w) => w.length > 3).into(&mut owned); + print($"{owned} "); + val empty: strview = ""; + println($"{empty.split(',').count()} {empty.words().count()}"); +} diff --git a/tests/programs/text_spanning_lines_1.out b/tests/programs/text_spanning_lines_1.out new file mode 100644 index 00000000..1892c4ef --- /dev/null +++ b/tests/programs/text_spanning_lines_1.out @@ -0,0 +1,6 @@ +sakura +====== +trailing spaces go: +one written stays: + +after a blank line, a "quote" and a tab: done diff --git a/tests/programs/text_spanning_lines_1.sakura b/tests/programs/text_spanning_lines_1.sakura new file mode 100644 index 00000000..172e6cc9 --- /dev/null +++ b/tests/programs/text_spanning_lines_1.sakura @@ -0,0 +1,14 @@ +import std::io; +const banner: span = """ + sakura + ====== + """; +def main(): void { + print(banner); + print(""" + trailing spaces go: + one written stays:\x20 + + after a blank line, a "quote" and a tab:\tdone + """); +} diff --git a/tests/programs/text_spanning_lines_2.out b/tests/programs/text_spanning_lines_2.out new file mode 100644 index 00000000..42283946 --- /dev/null +++ b/tests/programs/text_spanning_lines_2.out @@ -0,0 +1,4 @@ +hello world, +2 and 3 +nested +done diff --git a/tests/programs/text_spanning_lines_2.sakura b/tests/programs/text_spanning_lines_2.sakura new file mode 100644 index 00000000..ac53a650 --- /dev/null +++ b/tests/programs/text_spanning_lines_2.sakura @@ -0,0 +1,12 @@ +import std::io; +def main(): void { + val n := 2; + val who := "world"; + print($""" + hello {who}, + {n} and {n + 1} + {$""" + nested + """.view()}done + """.view()); +} diff --git a/tests/programs/text_spanning_lines_3.out b/tests/programs/text_spanning_lines_3.out new file mode 100644 index 00000000..7e5ba670 --- /dev/null +++ b/tests/programs/text_spanning_lines_3.out @@ -0,0 +1,3 @@ + +[a +] \ No newline at end of file diff --git a/tests/programs/text_spanning_lines_3.sakura b/tests/programs/text_spanning_lines_3.sakura new file mode 100644 index 00000000..934a88e0 --- /dev/null +++ b/tests/programs/text_spanning_lines_3.sakura @@ -0,0 +1,11 @@ +import std::io; +def main(): void { + print(""" + + """); + print("["); + print(""" + a + """); + print("]"); +} diff --git a/tests/programs/the_compiler_gives_a_call_its_own_site_1.out b/tests/programs/the_compiler_gives_a_call_its_own_site_1.out new file mode 100644 index 00000000..25306f45 --- /dev/null +++ b/tests/programs/the_compiler_gives_a_call_its_own_site_1.out @@ -0,0 +1,4 @@ +6:71 def check(n: int, flag: bool): string | n != 0 | n = 0 +8:97 def plain(flag: bool): string | flag | flag = false +10:87 def joined(a: int, b: int): string | a > 0 && b > 0 | +12:102 def both(a: int, b: int): string | a < b | a = 2, b = 5 diff --git a/tests/programs/the_compiler_gives_a_call_its_own_site_1.sakura b/tests/programs/the_compiler_gives_a_call_its_own_site_1.sakura new file mode 100644 index 00000000..08b8fa50 --- /dev/null +++ b/tests/programs/the_compiler_gives_a_call_its_own_site_1.sakura @@ -0,0 +1,18 @@ +import std::io; +def report(text: span, got: span, at: site): string { + return $"{at.line}:{at.column} {at.signature} | {text} | {got}"; +} +def check(n: int, flag: bool): string { + return report(source_of(n != 0), values_of(n != 0).view(), call_site()); +} +def plain(flag: bool): string { return report(source_of(flag), values_of(flag).view(), call_site()); } +def joined(a: int, b: int): string { + return report(source_of(a > 0 && b > 0), values_of(a > 0 && b > 0).view(), call_site()); +} +def both(a: int, b: int): string { return report(source_of(a < b), values_of(a < b).view(), call_site()); } +def main(): void { + println(check(0, true)); + println(plain(false)); + println(joined(1, 0)); + println(both(2, 5)); +} diff --git a/tests/programs/the_receiver_chooses_the_overload_1.out b/tests/programs/the_receiver_chooses_the_overload_1.out new file mode 100644 index 00000000..b73e8c1d --- /dev/null +++ b/tests/programs/the_receiver_chooses_the_overload_1.out @@ -0,0 +1 @@ +rwR rR wR 42 3 3 4 4 5 8 diff --git a/tests/programs/the_receiver_chooses_the_overload_1.sakura b/tests/programs/the_receiver_chooses_the_overload_1.sakura new file mode 100644 index 00000000..b9486491 --- /dev/null +++ b/tests/programs/the_receiver_chooses_the_overload_1.sakura @@ -0,0 +1,34 @@ +import std::io; +trait peek { + def first(&this): span; + @optional def first(&mut this): span; +} +struct both { var n: i64; } +def both::first(&this): span { return "r"; } +def both::first(&mut this): span { return "w"; } +struct reads { var n: i64; } +def reads::first(&this): span { return "R"; } +def dynamic(p: &mut peek): span { return p.first(); } +def generic(x: &mut T): span where T: peek { return x.first(); } +var writes: int = 0; +struct box4 : indexable { var items: T[4]; } +def box4::at(&this, key: u64): &T { return &this.items[key]; } +def box4::at(&mut this, key: u64): &mut T { writes++; return &mut this.items[key]; } +struct frozen : indexable { var items: i64[4]; } +def frozen::at(&this, key: u64): &i64 { return &this.items[key]; } +def main(): void { + val vb := both{1}; + var mb := both{1}; + var mr := reads{1}; + print($"{vb.first()}{mb.first()}{mr.first()} "); + print($"{dynamic(&mut mb)}{dynamic(&mut mr)} {generic(&mut mb)}{generic(&mut mr)} "); + var mc := box4:: { items = [1, 2, 3, 4] }; + val ic := box4:: { items = [1, 2, 3, 4] }; + mc[0] = 42; + mc[1] += 1; + val a := ic[2]; + val r := &ic[3]; + print($"{mc[0]} {mc[1]} {a} {r} {writes} "); + var f := frozen { items = [5, 6, 7, 8] }; + print($"{f[0]} {f[3]}\n"); +} diff --git a/tests/programs/threads_1.out b/tests/programs/threads_1.out new file mode 100644 index 00000000..1212d7b3 --- /dev/null +++ b/tests/programs/threads_1.out @@ -0,0 +1,7 @@ +parts 499950000 +count 20000 +squares 338350 +once 1 +carried 9 +closed a parcel of 9 +cpus true diff --git a/tests/programs/threads_1.sakura b/tests/programs/threads_1.sakura new file mode 100644 index 00000000..1e4283f1 --- /dev/null +++ b/tests/programs/threads_1.sakura @@ -0,0 +1,97 @@ +import std::io; +import std::thread; + +# Threads giving back what they computed, a count under a mutex, a pipeline of +# channels, something run once, and a value a thread owns, each the same in the +# machine, which runs them by turns, and in an executable, which runs them at +# once. + +struct parcel : owning { + var weight: u64; +} + +def parcel::close(&mut this): void { + if this.weight != 0 { + io::println($"closed a parcel of {this.weight}"); + this.weight = 0; + } +} + +def main(): void { + # Sums of parts, each its own thread's, which it takes from a count they + # share, as a closure refers to the locals it uses. + var parts := vector::>::new(); + var next_part := atomic::::new(1); + for _ in 1..5u { + var started := thread::spawn(def(): u64 { + val part := next_part.fetch_add(1); + var sum: u64 = 0; + for i in 0..10000u { sum += i * part; } + return sum; + }) else (e) { io::println($"no thread: {e}"); return; }; + parts.append(move(started)); + } + var total: u64 = 0; + for i in 0..parts.length { total += parts[i].join(); } + io::println($"parts {total}"); + + # A count four threads add to under a mutex. + var count := thread::mutex::::new(0); + { + var adders := vector::>::new(); + for _ in 0..4u { + var started := thread::spawn(def() { + for _ in 0..5000u { + var held := count.lock(); + held.value() += 1; + } + }) else (e) { return; }; + adders.append(move(started)); + } + } + { + var held := count.lock(); + io::println($"count {held.value()}"); + } + + # A pipeline: numbers, squared by one thread, summed by another. + var numbers := thread::channel::::new(4); + var squares := thread::channel::::new(4); + var squarer := thread::spawn(def() { + while numbers.receive() is some(n) { _ = squares.send(n * n); } + squares.close(); + }) else (e) { return; }; + var summer := thread::spawn(def(): u64 { + var sum: u64 = 0; + var seen: u64 = 0; + while seen < 100 { + if squares.receive() is some(s) { sum += s; } + seen++; + } + return sum; + }) else (e) { return; }; + for n in 1..101u { _ = numbers.send(n); } + io::println($"squares {summer.join()}"); + numbers.close(); + squarer.close(); + + # Something eight threads ask for, run once. + var setup := thread::once::new(); + var runs := atomic::::new(0); + { + var askers := vector::>::new(); + for _ in 0..8u { + var started := thread::spawn(def() { setup.run(def() { _ = runs.fetch_add(1); }); }) else (e) { return; }; + askers.append(move(started)); + } + } + io::println($"once {runs.load()}"); + + # A value given to a thread, which closes it where its function ends. + var given := parcel { weight = 9 }; + var carried := thread::spawn_with(def(p: parcel) { io::println($"carried {p.weight}"); }, move(&mut given)) else (e) { + return; + }; + carried.close(); + io::println($"cpus {thread::cpu_count() >= 1}"); +} diff --git a/tests/programs/trait_composition_1.out b/tests/programs/trait_composition_1.out new file mode 100644 index 00000000..0ce92ac4 --- /dev/null +++ b/tests/programs/trait_composition_1.out @@ -0,0 +1,4 @@ +hi box 5 +hi dot 0 +hi box 5 +hi box 5 t diff --git a/tests/programs/trait_composition_1.sakura b/tests/programs/trait_composition_1.sakura new file mode 100644 index 00000000..1c2b6a02 --- /dev/null +++ b/tests/programs/trait_composition_1.sakura @@ -0,0 +1,31 @@ +import std::io; +trait named { + def tag(&this): string { return "t"; } + def name(&this): string; + def greet(&this): string { return $"hi {this.name()}"; } +} +trait sized { + def name(&this): string; + var width: i64 { get; set; } +} +trait shape: sized, named { + def describe(&this): string { return $"{this.greet()} {this.width}"; } +} +struct box: shape { var w: i64; } +def box::name(&this): string { return "box"; } +var box::width: i64 { get => this.w; set => this.w = value; } +struct dot {} +def dot::name(&this): string { return "dot"; } +var dot::width: i64 { get => 0; set {} } +def render(s: &mut shape): string { s.width = s.width + 1; return s.describe(); } +def only_named(n: &named): string { return n.greet(); } +def only_sized(z: &sized): i64 { return z.width; } +def main(): void { + var b := box{ w = 4 }; + var d := dot{}; + println(render(&mut b)); + println(render(&mut d)); + println(b.describe()); + val s: &shape = &b; + println($"{only_named(s)} {only_sized(s)} {s.tag()}"); +} diff --git a/tests/programs/trait_composition_2.out b/tests/programs/trait_composition_2.out new file mode 100644 index 00000000..f7541b50 --- /dev/null +++ b/tests/programs/trait_composition_2.out @@ -0,0 +1 @@ +5 card 2 diff --git a/tests/programs/trait_composition_2.sakura b/tests/programs/trait_composition_2.sakura new file mode 100644 index 00000000..e8d92c8b --- /dev/null +++ b/tests/programs/trait_composition_2.sakura @@ -0,0 +1,20 @@ +import std::io; +trait into { def into(&this): T; } +trait pair: into { + def twice(&this): T { return this.into(); } +} +trait shown { def show(&this): string; } +trait both { def first(&this): i64; def show(&this): string; } +struct one: pair { var v: i64; } +def one::into(&this): i64 { return this.v; } +struct card { var n: i64; } +def card::show(&this): string { return "card"; } +def card::first(&this): i64 { return this.n; } +def tell(x: &shown): string { return x.show(); } +def main(): void { + val o := one{ v = 5 }; + val p: &pair = &o; + val c := card{ n = 2 }; + val b: &both = &c; + println($"{p.twice()} {tell(b)} {b.first()}"); +} diff --git a/tests/programs/trait_composition_3.out b/tests/programs/trait_composition_3.out new file mode 100644 index 00000000..df3e0b41 --- /dev/null +++ b/tests/programs/trait_composition_3.out @@ -0,0 +1 @@ +1 2 116 6 116 diff --git a/tests/programs/trait_composition_3.sakura b/tests/programs/trait_composition_3.sakura new file mode 100644 index 00000000..bac40286 --- /dev/null +++ b/tests/programs/trait_composition_3.sakura @@ -0,0 +1,25 @@ +import std::io; +trait base { + def id(&this): i64; + def f(&this): i64 { return 1; } + def twice(&this): i64 { return this.id() * 2; } +} +trait keeps: base { def f(&this): i64; } +trait owns: base { def f(&this): i64 { return 2; } } +trait left: base { def l(&this): i64; } +trait right: base { def r(&this): i64; } +trait all: left, right { + def sum(&this): i64 { return this.twice() + this.l() + this.r(); } +} +struct z: all { var n: i64; } +def z::id(&this): i64 { return this.n; } +def z::l(&this): i64 { return 10; } +def z::r(&this): i64 { return 100; } +def main(): void { + val x := z{ n = 3 }; + val k: &keeps = &x; + val o: &owns = &x; + val a: &all = &x; + val b: &base = a; + println($"{k.f()} {o.f()} {a.sum()} {b.twice()} {x.sum()}"); +} diff --git a/tests/programs/trait_defaults_per_type_1.out b/tests/programs/trait_defaults_per_type_1.out new file mode 100644 index 00000000..ebbacc54 --- /dev/null +++ b/tests/programs/trait_defaults_per_type_1.out @@ -0,0 +1 @@ +4 15 42 19 first 2 trio6 3 <1.5> 5 4 2 1 diff --git a/tests/programs/trait_defaults_per_type_1.sakura b/tests/programs/trait_defaults_per_type_1.sakura new file mode 100644 index 00000000..f3009a7f --- /dev/null +++ b/tests/programs/trait_defaults_per_type_1.sakura @@ -0,0 +1,60 @@ +import std::io; + +# A trait naming `self` is only a bound, so its defaults are compiled for each type +# implementing it, generic ones too, and a default may ask more of `self` or of the +# trait's parameters than the trait does. +trait shelf { + def get(&this, at: u64): T; + def size(&this): u64; + def first(&this): T { return this.get(0); } + def pick(&this, at: u64, f: F): U where F: invokable { return f(this.get(at)); } + def total(&this): T where T: numeric { + var t: T = 0; + for i in 0..this.size() { t += this.get(i); } + return t; + } + def tagged(&this, other: &self): string where self: labeled { + return $"{this.label()}{this.size() + other.size()}"; + } +} + +trait labeled { def label(&this): strview; } + +struct trio : shelf, labeled { var items: i64[3]; } +def trio::label(&this): strview { return "trio"; } +def trio::get(&this, at: u64): i64 { return this.items[at]; } +def trio::size(&this): u64 { return 3; } + +struct names : shelf { var a: strview; var b: strview; } +def names::get(&this, at: u64): strview { return at == 0 ? this.a : this.b; } +def names::size(&this): u64 { return 2; } + +# A type's own method stands in for the default. +def names::first(&this): strview { return "first"; } + +# A method of a generic type exists only for the types meeting its `where`. +struct holder { var held: T; } +def holder::doubled(&this): T where T: numeric { return this.held + this.held; } +def holder::shown(&this): string { return $"<{this.held}>"; } + +def first_of(s: &S): i64 where S: shelf { return s.first() + s.total(); } + +# An iterator of the program's own takes the adapters, compiled for it. +struct countdown : iterator { var n: u32; } +def countdown::next(&mut this): maybe { + return nothing {} if this.n == 0; + this.n--; + return this.n + 1; +} + +def main(): void { + val t := trio { items = [4, 5, 6] }; + val n := names { a = "ann", b = "bo" }; + print($"{t.first()} {t.total()} {t.pick(2, def(x) => x * 7)} {first_of(&t)} "); + print($"{n.first()} {n.pick(1, def(s) => s.length)} {t.tagged(&t)} "); + val h := holder:: { held = 1.5 }; + val w := holder:: { held = "w" }; + print($"{h.doubled()} {h.shown()} {w.shown()} "); + val dash: strview = " "; + println($"{(countdown { n = 5 }).filter(def(x) => x != 3).to_string(dash)}"); +} diff --git a/tests/programs/traits_1.out b/tests/programs/traits_1.out new file mode 100644 index 00000000..77eecc60 --- /dev/null +++ b/tests/programs/traits_1.out @@ -0,0 +1 @@ +25 square{side = 5} 12 circle{radius = 2} 25 diff --git a/tests/programs/traits_1.sakura b/tests/programs/traits_1.sakura new file mode 100644 index 00000000..6da42445 --- /dev/null +++ b/tests/programs/traits_1.sakura @@ -0,0 +1,21 @@ +import std::io; +trait shape { + def area(this: &shape): f64; + def grow(this: &mut shape, by: f64): void; +} +struct square: shape { var side: f64; } +struct circle { var radius: f64; } +def square::area(this: &square): f64 { return this.side * this.side; } +def square::grow(this: &mut square, by: f64): void { this.side += by; } +def circle::area(this: &circle): f64 { return 3 * this.radius * this.radius; } +def circle::grow(this: &mut circle, by: f64): void { this.radius *= by; } +def report(s: &shape): string { return $"{s.area()} {s}"; } +def enlarge(s: &mut shape): void { s.grow(2); } +def main(): void { + var sq := square{3}; + var ci := circle{1}; + enlarge(&mut sq); + enlarge(&mut ci); + val shape_ref: &shape = &sq; + println($"{report(&sq)} {report(&ci)} {shape_ref.area()}"); +} diff --git a/tests/programs/traits_ask_for_types_1.out b/tests/programs/traits_ask_for_types_1.out new file mode 100644 index 00000000..38cf7a5b --- /dev/null +++ b/tests/programs/traits_ask_for_types_1.out @@ -0,0 +1 @@ +11 6 10 maybe{some = 2} 8 1 diff --git a/tests/programs/traits_ask_for_types_1.sakura b/tests/programs/traits_ask_for_types_1.sakura new file mode 100644 index 00000000..f4aee171 --- /dev/null +++ b/tests/programs/traits_ask_for_types_1.sakura @@ -0,0 +1,31 @@ +import std::io; +trait cloneable { def clone(&this): self; } +trait stepper { def step(&mut this): maybe; } +trait walk { type cursor: stepper; @optional type back: stepper; def start(&this): cursor; @optional def rewind(&this): back; } +trait stored { type storage = self; } +struct ctr { var at: i64; var to: i64; } +def ctr::step(&mut this): maybe { if this.at >= this.to { return nothing {}; } this.at++; return this.at; } +def ctr::clone(&this): ctr { return ctr{ at = this.at + 10, to = this.to }; } +struct one { var to: i64; } +type one::cursor = ctr; +def one::start(&this): ctr { return ctr{ at = 0, to = this.to }; } +struct two { var to: i64; } +type two::cursor = ctr; +type two::back = ctr; +def two::start(&this): ctr { return ctr{ at = 0, to = this.to }; } +def two::rewind(&this): ctr { return ctr{ at = 1, to = this.to }; } +struct bit { var on: bool; } +type bool::storage = bit; +def sum(c: &C): i64 where C: walk { + var w: C::cursor = c.start(); + var t: i64 = 0; + while w.step() is some(v) { t += v; } + return t; +} +def size(): u64 where T: stored { return size_of::(); } +def twice(x: &T): T where T: cloneable { return x.clone(); } +def main(): void { + val c := twice(&ctr{ at = 1, to = 2 }); + var r := two{ to = 4 }.rewind(); + println($"{c.at} {sum(&one{ to = 3 })} {sum(&two{ to = 4 })} {r.step()} {size::()} {size::()}"); +} diff --git a/tests/programs/traits_have_functions_of_their_own_1.out b/tests/programs/traits_have_functions_of_their_own_1.out new file mode 100644 index 00000000..c9de618a --- /dev/null +++ b/tests/programs/traits_have_functions_of_their_own_1.out @@ -0,0 +1,5 @@ +13 1 +42 +4 +1 +1.5 200 diff --git a/tests/programs/traits_have_functions_of_their_own_1.sakura b/tests/programs/traits_have_functions_of_their_own_1.sakura new file mode 100644 index 00000000..2794190d --- /dev/null +++ b/tests/programs/traits_have_functions_of_their_own_1.sakura @@ -0,0 +1,37 @@ +import std::io; + +# A trait's own functions, declared through it outside it, are named through it, +# generic as any function is, and std reads numbers by `real::parse::` and +# `integer::parse::`. +trait shape { + def area(&this): f64; +} +def shape::total(shapes: span): f64 where S: shape { + var sum := 0.0; + for &each in shapes { sum += each.area(); } + return sum; +} +def shape::unit(): f64 { return 1.0; } + +trait holder { + def held(&this): T; +} +def holder::pair(x: T): T[2] { return [x, x]; } + +struct square : shape { var side: f64; } +def square::area(&this): f64 { return this.side * this.side; } +struct cell : holder { var v: i64; } +def cell::held(&this): i64 { return this.v; } + +def main(): void { + val squares: square[2] = [square { side = 2.0 }, square { side = 3.0 }]; + println($"{shape::total(squares[:])} {shape::unit()}"); + val p := holder::::pair(21); println($"{p[0] + p[1]}"); + val c := cell { v = 4 }; + println($"{c.held()}"); + val f := shape::unit; + println($"{f()}"); + val r: f32 = real::parse::("1.5").value; + val n: u8 = integer::parse::("200").value; + println($"{r} {n}"); +} diff --git a/tests/programs/traits_see_through_aliases_1.out b/tests/programs/traits_see_through_aliases_1.out new file mode 100644 index 00000000..0cfbf088 --- /dev/null +++ b/tests/programs/traits_see_through_aliases_1.out @@ -0,0 +1 @@ +2 diff --git a/tests/programs/traits_see_through_aliases_1.sakura b/tests/programs/traits_see_through_aliases_1.sakura new file mode 100644 index 00000000..df1fa54d --- /dev/null +++ b/tests/programs/traits_see_through_aliases_1.sakura @@ -0,0 +1,11 @@ +import std::io; +type bytes = span; +type count = u64; +trait viewer { def see(&this, from: u64): span; } +struct box : viewer { var n: u8[3]; } +def box::see(&this, from: count): bytes { return this.n[from:3 - from]; } +def use(v: &viewer): u64 { return v.see(1).length; } +def main(): void { + val b := box{ n = [1, 2, 3] }; + println($"{use(&b)}"); +} diff --git a/tests/programs/type_parameters_given_references_pass_them_1.out b/tests/programs/type_parameters_given_references_pass_them_1.out new file mode 100644 index 00000000..06ab6e33 --- /dev/null +++ b/tests/programs/type_parameters_given_references_pass_them_1.out @@ -0,0 +1,2 @@ +1 3 5 7 9 +first odd past 1: 3 diff --git a/tests/programs/type_parameters_given_references_pass_them_1.sakura b/tests/programs/type_parameters_given_references_pass_them_1.sakura new file mode 100644 index 00000000..1769b3a8 --- /dev/null +++ b/tests/programs/type_parameters_given_references_pass_them_1.sakura @@ -0,0 +1,45 @@ +import std::io; + +# A test given a reference to each element. +struct is_odd : invokable {} +def is_odd::invoke(&this, x: &u64): bool { return x % 2 == 1; } + +# Where a parameter's type is a type parameter, as `T` of the bound below, what +# the template gives it is the value, so an instance where `T` is a reference +# passes the reference itself, not one to where it is held. +struct kept where I: iterator where F: invokable { + var from: I; + var test: F; +} + +def kept::next(&mut this): maybe { + while true { + val got := this.from.next(); + if got is not some(x) { + return nothing {}; + } + if this.test(x) { + return x; + } + } + return nothing {}; +} + +def first_passing(from: &mut I, test: F): maybe where I: iterator where F: invokable { + while from.next() is some(x) { + return x if test(x); + } + return nothing {}; +} + +def main(): void { + var v := vector::::new(); + for i in 0..10u { v.append(i); } + var odd := kept::<&u64, span::cursor, is_odd> { from = v.view().iter(), test = is_odd {} }; + while odd.next() is some(x) { print($"{x} "); } + println(""); + var walk := v.view().iter(); + _ = walk.next(); + _ = walk.next(); + if first_passing::<&u64, span::cursor, is_odd>(&mut walk, is_odd {}) is some(x) { println($"first odd past 1: {x}"); } +} diff --git a/tests/programs/types_implementing_indexable_are_indexed_1.out b/tests/programs/types_implementing_indexable_are_indexed_1.out new file mode 100644 index 00000000..b93a2bed --- /dev/null +++ b/tests/programs/types_implementing_indexable_are_indexed_1.out @@ -0,0 +1,3 @@ +1 4 10 +[10, 7, 4, 4] 4 6 +9 0 diff --git a/tests/programs/types_implementing_indexable_are_indexed_1.sakura b/tests/programs/types_implementing_indexable_are_indexed_1.sakura new file mode 100644 index 00000000..113d94cb --- /dev/null +++ b/tests/programs/types_implementing_indexable_are_indexed_1.sakura @@ -0,0 +1,19 @@ +import std::io; +struct holder : indexable { var items: int[4]; var reads: int; var writes: int; } +def holder::at(&this, key: u64): &int { return &this.items[key]; } +def holder::at(&mut this, key: u64): &mut int { + this.writes = this.writes + 1; + return &mut this.items[key]; +} +def sum(h: &holder): int { return h[0] + h[1] + h[2] + h[3]; } +def main(): void { + var d := holder { items = [1, 2, 3, 4], reads = 0, writes = 0 }; + println($"{d[0]} {d[3]} {sum(&d)}"); + d[0] = 10; + d[1] += 5; + d[2]++; + val r := &d[3]; + println($"{d.items} {r} {d.writes}"); + val fixed := holder { items = [9, 9, 9, 9], reads = 0, writes = 0 }; + println($"{fixed[1]} {fixed.writes}"); +} diff --git a/tests/programs/types_implementing_indexable_are_indexed_2.out b/tests/programs/types_implementing_indexable_are_indexed_2.out new file mode 100644 index 00000000..4888a4c3 --- /dev/null +++ b/tests/programs/types_implementing_indexable_are_indexed_2.out @@ -0,0 +1 @@ +[1, 5, 4, 4] diff --git a/tests/programs/types_implementing_indexable_are_indexed_2.sakura b/tests/programs/types_implementing_indexable_are_indexed_2.sakura new file mode 100644 index 00000000..3daa5e3f --- /dev/null +++ b/tests/programs/types_implementing_indexable_are_indexed_2.sakura @@ -0,0 +1,10 @@ +import std::io; +struct holder : indexable { var items: int[4]; } +def holder::at(&this, key: u64): &int { return &this.items[key]; } +def holder::at(&mut this, key: u64): &mut int { return &mut this.items[key]; } +def main(): void { + var d := holder { items = [1, 2, 3, 4] }; + d[1] = 5; + d[2] += 1; + println($"{d.items}"); +} diff --git a/tests/programs/types_name_their_own_without_them_1.out b/tests/programs/types_name_their_own_without_them_1.out new file mode 100644 index 00000000..af105daf --- /dev/null +++ b/tests/programs/types_name_their_own_without_them_1.out @@ -0,0 +1,3 @@ +number true 5 false +word true +9 2 top diff --git a/tests/programs/types_name_their_own_without_them_1.sakura b/tests/programs/types_name_their_own_without_them_1.sakura new file mode 100644 index 00000000..c3e1a4ce --- /dev/null +++ b/tests/programs/types_name_their_own_without_them_1.sakura @@ -0,0 +1,60 @@ +import std::io; + +# A field and a type declared through its type share a name: the field is +# reached through a value, and the type through its type. +struct token { + var kind: token::kind; + var at: span; +} + +enum token::kind { word, number, mark } + +struct token::span { var start: u64; var end: u64; } + +# Within a type, and what is declared through it, its nested types, associated +# variables, and an enum's members are named without it. +val token::plain: kind = kind::word; + +def token::of(&this, genus: kind): bool { return this.kind == genus; } +def token::width(&this): u64 { val s: span = this.at; return s.end - s.start; } +def token::kind::name(&this): strview { + return match this { + word => "word", + number => "number", + mark => "mark" + }; +} +def token::kind::is_plain(&this): bool { return this == plain; } + +# A generic type gives what is nested in it its own arguments. +struct stack : owning { var top: *mut node; var count: u64; } +struct stack::node { var value: T; var below: *mut node; } + +def stack::push(&mut this, value: T): void { + val made := raw_allocate(size_of::()) as *mut node; + made[0] = node { value = value, below = this.top }; + this.top = made; + this.count++; +} +def stack::peek(&this): T { val n: node = this.top[0]; return n.value; } +def stack::close(&mut this): void { + while this.top != null { + val below := this.top[0].below; + raw_release(this.top as *mut u8); + this.top = below; + } +} + +def main(): void { + val t := token { kind = token::kind::number, at = token::span { start = 3, end = 8 } }; + println($"{t.kind.name()} {t.of(token::kind::number)} {t.width()} {t.kind.is_plain()}"); + val w := token { kind = token::plain }; + println($"{w.kind.name()} {w.kind.is_plain()}"); + + var s := stack:: {}; + s.push(4); + s.push(9); + var names := stack:: {}; + names.push("top"); + println($"{s.peek()} {s.count} {names.peek()}"); +} diff --git a/tests/programs/union_fields_are_named_by_reference_1.out b/tests/programs/union_fields_are_named_by_reference_1.out new file mode 100644 index 00000000..8d90a652 --- /dev/null +++ b/tests/programs/union_fields_are_named_by_reference_1.out @@ -0,0 +1,5 @@ +holds a +still renamed +code 7 +end +close renamed diff --git a/tests/programs/union_fields_are_named_by_reference_1.sakura b/tests/programs/union_fields_are_named_by_reference_1.sakura new file mode 100644 index 00000000..7083513a --- /dev/null +++ b/tests/programs/union_fields_are_named_by_reference_1.sakura @@ -0,0 +1,18 @@ +import std::io; +struct noisy : owning { var name: span; } +def noisy::new(name: span): noisy { return noisy { name = name }; } +def noisy::close(&mut this): void { println($"close {this.name}"); } +def noisy::rename(&mut this, name: span): void { this.name = name; } +union held { var code: i64; var one: noisy; } +def main(): void { + var h: held = noisy::new("a"); + match h { + one(&mut got) => { println($"holds {got.name}"); got.rename("renamed"); } + code(n) => { println($"code {n}"); } + } + if h is one(&got) { println($"still {got.name}"); } + var c: held = 7; + if c is one(&got) { println("wrong"); } + if c is code(n) { println($"code {n}"); } + println("end"); +} diff --git a/tests/programs/unions_hold_what_is_given_1.out b/tests/programs/unions_hold_what_is_given_1.out new file mode 100644 index 00000000..e57ccc54 --- /dev/null +++ b/tests/programs/unions_hold_what_is_given_1.out @@ -0,0 +1,2 @@ +shape{size = 1.5} shape{name = box} shape{names = [a, b]} +[shape{none = true}, shape{size = 2.5}, shape{name = c}] shape{size = 0.5} shape{name = three} 3 empty result>{value = w} diff --git a/tests/programs/unions_hold_what_is_given_1.sakura b/tests/programs/unions_hold_what_is_given_1.sakura new file mode 100644 index 00000000..d2c47c6d --- /dev/null +++ b/tests/programs/unions_hold_what_is_given_1.sakura @@ -0,0 +1,25 @@ +import std::io; +struct failure { val message: span; } +union result { var value: T; var failure: failure; } +union shape { var none: bool; var size: f64; var name: span; var names: span>; } +def parse(text: span): result { + if text.length == 0 { return failure{ "empty" }; } + return text.length as int; +} +def show(r: result): string { + return match r { value(v) => $"{v}", failure(f) => f.message }; +} +def wrap(x: T): result { return x; } +def main(): void { + var s: shape = 1.5; + print($"{s} "); + s = "box"; + print($"{s} "); + val two: span[2] = ["a", "b"]; + s = span::>::over((&two) as *span, 2); + println($"{s}"); + val all: shape[3] = [true, 2.5, "c"]; + val t: shape = all.length > 5 ? "big" : 0.5; + val m: shape = match all.length { 3 => "three", else => false }; + println($"{all} {t} {m} {show(parse("abc"))} {show(parse(""))} {wrap::>("w")}"); +} diff --git a/tests/programs/unsigned_literals_1.out b/tests/programs/unsigned_literals_1.out new file mode 100644 index 00000000..dd7574ea --- /dev/null +++ b/tests/programs/unsigned_literals_1.out @@ -0,0 +1 @@ +45 44 18446744073709551615 255 3 diff --git a/tests/programs/unsigned_literals_1.sakura b/tests/programs/unsigned_literals_1.sakura new file mode 100644 index 00000000..0cec2e83 --- /dev/null +++ b/tests/programs/unsigned_literals_1.sakura @@ -0,0 +1,7 @@ +import std::io; +def main(): void { + var total := 0u; + for i in 0..10u { total += i; } + val small: u8 = 200u; + println($"{total} {small + 100u} {~0u} {0xFFu} {1 + 2u}"); +} diff --git a/tests/programs/values_are_called_through_invoke_1.out b/tests/programs/values_are_called_through_invoke_1.out new file mode 100644 index 00000000..24986256 --- /dev/null +++ b/tests/programs/values_are_called_through_invoke_1.out @@ -0,0 +1,11 @@ +7 calls 2 +10 12 +2 14 calls 1 +4 30 calls 4 +12 +int text +16 81 25 +201 105 +3 6 +ababab +told diff --git a/tests/programs/values_are_called_through_invoke_1.sakura b/tests/programs/values_are_called_through_invoke_1.sakura new file mode 100644 index 00000000..86cb9676 --- /dev/null +++ b/tests/programs/values_are_called_through_invoke_1.sakura @@ -0,0 +1,56 @@ +import std::io; + +struct adder : invokable { var calls: i64; } +def adder::invoke(&mut this, a: i64, b: i64): i64 { this.calls++; return a + b; } + +struct doubler {} +def doubler::invoke(&this, x: i64): i64 { return x * 2; } + +# Overloads are chosen by their arguments, as a method's are. +struct shape {} +def shape::invoke(&this, x: i64): strview { return "int"; } +def shape::invoke(&this, x: strview): strview { return "text"; } + +struct holder { var f: adder; var g: doubler; } +def make(): doubler { return doubler{}; } + +def twice(f: &mut F, x: i64): i64 where F: invokable { return f(f(x)); } +def run(f: &mut invokable): i64 { return f(10, 20); } +def run1(f: &mut invokable): i64 { return f(5); } +def total(f: &mut invokable): i64 { return f(1, 2, 3); } +def say(f: &mut invokable): string { return f("ab", 3); } +def tell(f: &mut invokable): void { f("told"); } + +def square(x: i64): i64 { return x * x; } +def sum(xs: i64...): i64 { var t: i64 = 0; for x in xs { t += x; } return t; } +def greet(name: strview, times: i64): string { var out: string = ""; for i in 0..times { out.append(name); } return out; } +def shout(text: strview): void { println(text); } + +def main(): void { + # A value of a type with an `invoke` is called as a function is. + var a := adder{}; + _ = a(1, 2); + println($"{a(3, 4)} calls {a.calls}"); + val d := doubler{}; + println($"{d(5)} {make()(6)}"); + var h := holder{ f = adder{}, g = doubler{} }; + println($"{h.f(1, 1)} {h.g(7)} calls {h.f.calls}"); + val r: &mut adder = &mut a; + println($"{r(2, 2)} {run(a)} calls {a.calls}"); + var t := doubler{}; + println($"{twice(&mut t, 3)}"); + val s := shape{}; + println($"{s(1)} {s("one")}"); + + # A function value is `invokable` of its own type, through its `invoke`. + var sq: def(i64): i64 = square; + println($"{sq.invoke(4)} {twice(&mut sq, 3)} {run1(sq)}"); + var lam := def(x: i64): i64 => x + 100; + println($"{twice(&mut lam, 1)} {run1(lam)}"); + var all: def(i64...): i64 = sum; + println($"{all.invoke(1, 2)} {total(all)}"); + var g := greet; + println(say(g)); + var sh := shout; + tell(sh); +} diff --git a/tests/programs/values_kept_by_branches_not_taken_are_not_closed_1.out b/tests/programs/values_kept_by_branches_not_taken_are_not_closed_1.out new file mode 100644 index 00000000..f8d31176 --- /dev/null +++ b/tests/programs/values_kept_by_branches_not_taken_are_not_closed_1.out @@ -0,0 +1,8 @@ +close right +close arm +0 held 0 true 3 +close held +close made +1 held 4 true 7 +close held +end diff --git a/tests/programs/values_kept_by_branches_not_taken_are_not_closed_1.sakura b/tests/programs/values_kept_by_branches_not_taken_are_not_closed_1.sakura new file mode 100644 index 00000000..d1b5fc5e --- /dev/null +++ b/tests/programs/values_kept_by_branches_not_taken_are_not_closed_1.sakura @@ -0,0 +1,16 @@ +import std::io; +struct noisy : owning { var name: span; } +def noisy::new(name: span): noisy { return noisy { name = name }; } +def noisy::close(&mut this): void { if this.name.length > 0 { println($"close {this.name}"); } } +def noisy::size(&this): u64 { return this.name.length; } +def pair(a: span, b: span): noisy { return noisy { name = a.length > b.length ? a : b }; } +def main(): void { + for i in 0..2 { + val held := pair("held", "x"); + val n := i == 0 ? 0u : noisy::new("made").size(); + val m := i == 1 || noisy::new("right").size() > 0; + val w := match i { 0 => noisy::new("arm").size(), else => 7u }; + println($"{i} {held.name} {n} {m} {w}"); + } + println("end"); +} diff --git a/tests/programs/variadic_arguments_are_closed_where_they_belong_1.out b/tests/programs/variadic_arguments_are_closed_where_they_belong_1.out new file mode 100644 index 00000000..dd4d1299 --- /dev/null +++ b/tests/programs/variadic_arguments_are_closed_where_they_belong_1.out @@ -0,0 +1,6 @@ +2 +close 2 +close 1 +taking 2 +close 4 +close 3 diff --git a/tests/programs/variadic_arguments_are_closed_where_they_belong_1.sakura b/tests/programs/variadic_arguments_are_closed_where_they_belong_1.sakura new file mode 100644 index 00000000..adb53817 --- /dev/null +++ b/tests/programs/variadic_arguments_are_closed_where_they_belong_1.sakura @@ -0,0 +1,9 @@ +import std::io; +struct noisy : owning { var n: i64; } +def noisy::close(&mut this): void { println($"close {this.n}"); } +def count(xs: noisy...): u64 { return xs.length; } +def take(args: Ts...): void { println($"taking {args.length}"); } +def main(): void { + println($"{count(noisy{ n = 1 }, noisy{ n = 2 })}"); + take(noisy{ n = 3 }, noisy{ n = 4 }); +} diff --git a/tests/programs/variadic_function_values_1.out b/tests/programs/variadic_function_values_1.out new file mode 100644 index 00000000..5c75ca65 --- /dev/null +++ b/tests/programs/variadic_function_values_1.out @@ -0,0 +1,6 @@ +0 1 6 +22 11 +44 +a +a,b,c +w,x,y diff --git a/tests/programs/variadic_function_values_1.sakura b/tests/programs/variadic_function_values_1.sakura new file mode 100644 index 00000000..3b761630 --- /dev/null +++ b/tests/programs/variadic_function_values_1.sakura @@ -0,0 +1,30 @@ +import std::io; + +def sum(xs: i64...): i64 { + var total: i64 = 0; + for x in xs { total += x; } + return total; +} + +def joined(head: strview, rest: strview...): string { + var out: string = head; + for each in rest { out.append(","); out.append(each); } + return out; +} + +# A variadic function type is written with `...` after its last parameter type. +def twice(f: def(i64...): i64, xs: span): i64 { return f(...xs) * 2; } + +def main(): void { + val f: def(i64...): i64 = sum; + println($"{f()} {f(1)} {f(1, 2, 3)}"); + val numbers: i64[4] = [4, 5, 6, 7]; + println($"{f(...numbers)} {f(...numbers[1:2])}"); + println($"{twice(sum, numbers[:])}"); + + val g := joined; + println(g("a")); + println(g("a", "b", "c")); + val words: strview[2] = ["x", "y"]; + println(g("w", ...words)); +} diff --git a/tests/programs/variadic_functions_take_a_view_of_their_arguments_1.out b/tests/programs/variadic_functions_take_a_view_of_their_arguments_1.out new file mode 100644 index 00000000..6cab4835 --- /dev/null +++ b/tests/programs/variadic_functions_take_a_view_of_their_arguments_1.out @@ -0,0 +1,4 @@ +0 5 60 60 10 +2 4 +9 1.5 one many many +60 diff --git a/tests/programs/variadic_functions_take_a_view_of_their_arguments_1.sakura b/tests/programs/variadic_functions_take_a_view_of_their_arguments_1.sakura new file mode 100644 index 00000000..e479426c --- /dev/null +++ b/tests/programs/variadic_functions_take_a_view_of_their_arguments_1.sakura @@ -0,0 +1,22 @@ +import std::io; +def sum(xs: i64...): i64 { var t: i64 = 0; for x in xs { t += x; } return t; } +def label(name: span, sep: span = ",", parts: span...): u64 { + return name.length + sep.length * parts.length; +} +def largest(first: T, rest: T...): T where T: ordered { + var best := first; + for x in rest { best = x > best ? x : best; } + return best; +} +def show(n: i64): span { return "one"; } +def show(xs: i64...): span { return "many"; } +const total := sum(1, 2, 3, 4); +def main(): void { + val arr: i64[3] = [10, 20, 30]; + val view: span = arr[:]; + println($"{sum()} {sum(5)} {sum(...arr)} {sum(...view)} {total}"); + println($"{label("ab")} {label("ab", "-", "x", "y")}"); + println($"{largest(3, 9, 2)} {largest(1.5)} {show(1)} {show(1, 2)} {show()}"); + val f: def(span): i64 = sum; + println($"{f(view)}"); +} diff --git a/tests/programs/variadic_generics_unroll_over_their_packs_1.out b/tests/programs/variadic_generics_unroll_over_their_packs_1.out new file mode 100644 index 00000000..d9b13b1e --- /dev/null +++ b/tests/programs/variadic_generics_unroll_over_their_packs_1.out @@ -0,0 +1,2 @@ +31 0 3 2 7 +50 6 6 2 10 diff --git a/tests/programs/variadic_generics_unroll_over_their_packs_1.sakura b/tests/programs/variadic_generics_unroll_over_their_packs_1.sakura new file mode 100644 index 00000000..7e7c2741 --- /dev/null +++ b/tests/programs/variadic_generics_unroll_over_their_packs_1.sakura @@ -0,0 +1,37 @@ +import std::io; +trait Show { def show(&this): i64; } +def i64::show(&this): i64 { return this * 10; } +def bool::show(&this): i64 { return this == true ? 1 : 0; } +def total(args: Ts...): i64 where Ts...: Show { + var t: i64 = 0; + for const x in args { t += x.show(); } + return t; +} +def count(args: Ts...): u64 { return args.length; } +def known(args: Ts...): i64 { + var t: i64 = 0; + for const x in args { continue if const !(x is Show); t += 1; } + return t; +} +def pair(args: Ts...): i64 where Ts...: integer { return (args[0] + args[1]) as i64; } +def forward(args: Ts...): i64 where Ts...: Show { return total(...args); } +def add3(a: i64, b: i64, c: i64): i64 { return a + b + c; } +def spread(args: Ts...): i64 { return add3(...args); } +def sum(first: T, rest: Ts...): T where T: numeric where Ts...: numeric { + return first if const rest.length == 0; + return first + sum(...rest) as T; +} +def until(args: Ts...): u64 { + var n: u64 = 0; + for const x in args { break if const !(x is Show); n++; } + return n; +} +def bump(args: Ts...): i64 where Ts...: integer { + for const x in args { x += 1; } + return args[0] as i64; +} +const three := count(1, 2, 3); +def main(): void { + println($"{total(1, true, 2)} {count()} {three} {known(1, 2.5, true)} {pair(3, 4)}"); + println($"{forward(5, false)} {spread(1, 2, 3)} {sum(1, 2, 3.5)} {until(1, true, 2.5, 3)} {bump(9)}"); +} diff --git a/tests/programs/views_are_indexed_and_walked_1.out b/tests/programs/views_are_indexed_and_walked_1.out new file mode 100644 index 00000000..8fbb2148 --- /dev/null +++ b/tests/programs/views_are_indexed_and_walked_1.out @@ -0,0 +1,5 @@ +10 40 of 4 +sees 99 +sum 179 +0:10 1:99 2:30 3:40 +empty 0 diff --git a/tests/programs/views_are_indexed_and_walked_1.sakura b/tests/programs/views_are_indexed_and_walked_1.sakura new file mode 100644 index 00000000..c7bd8f5e --- /dev/null +++ b/tests/programs/views_are_indexed_and_walked_1.sakura @@ -0,0 +1,17 @@ +import std::io; +def main(): void { + var a: i64[4] = [10, 20, 30, 40]; + val s := span::::over(&a as *i64, 4); + println($"{s[0]} {s[3]} of {s.length}"); + a[1] = 99; + println($"sees {s[1]}"); + var total := 0; + for x in s { total += x; } + println($"sum {total}"); + for i, x in s { print($"{i}:{x} "); } + println(""); + val none := span::::over(null, 0); + var seen := 0; + for x in none { seen++; } + println($"empty {seen}"); +} diff --git a/tests/programs/views_of_fixed_arrays_write_where_the_array_can_1.out b/tests/programs/views_of_fixed_arrays_write_where_the_array_can_1.out new file mode 100644 index 00000000..2d816a2f --- /dev/null +++ b/tests/programs/views_of_fixed_arrays_write_where_the_array_can_1.out @@ -0,0 +1,3 @@ +[2, 3, 4, 5] [3, 4] 14 4 +[7, 8, 9] 24 [4, 5] [2, 3] +Hello ell diff --git a/tests/programs/views_of_fixed_arrays_write_where_the_array_can_1.sakura b/tests/programs/views_of_fixed_arrays_write_where_the_array_can_1.sakura new file mode 100644 index 00000000..8e84f214 --- /dev/null +++ b/tests/programs/views_of_fixed_arrays_write_where_the_array_can_1.sakura @@ -0,0 +1,16 @@ +import std::io; +def total(xs: span): int { var t := 0; for x in xs { t += x; } return t; } +def bump(xs: slice): void { for i in 0..xs.length { xs[i] = xs[i] + 1; } } +def main(): void { + var a: int[4] = [1, 2, 3, 4]; + val all := a[0:4]; + val mid := a[1:2]; + bump(all); + println($"{a} {mid} {total(all)} {all.length}"); + val b: int[3] = [7, 8, 9]; + println($"{b[0:3]} {total(b[:])} {a[2:]} {a[:2]}"); + var text: u8[5] = ['h', 'e', 'l', 'l', 'o']; + val word := text[0:5]; + word[0] = 'H'; + println($"{word} {text[1:3]}"); +} diff --git a/tests/programs/void_is_a_value_of_its_own_1.out b/tests/programs/void_is_a_value_of_its_own_1.out new file mode 100644 index 00000000..2deceffa --- /dev/null +++ b/tests/programs/void_is_a_value_of_its_own_1.out @@ -0,0 +1,16 @@ +said 1 +said 2 +again +again +0 16 0 24 +said 3 +failed: negative +error: negative +false +said 4 +true +said 5 +said 6 +2 nothing held +in a thread +joined diff --git a/tests/programs/void_is_a_value_of_its_own_1.sakura b/tests/programs/void_is_a_value_of_its_own_1.sakura new file mode 100644 index 00000000..edabb144 --- /dev/null +++ b/tests/programs/void_is_a_value_of_its_own_1.sakura @@ -0,0 +1,71 @@ +import std::io; +import std::thread; + +# `void` is a type of one value, `void {}`, holding nothing and taking no bytes, +# which a function giving nothing gives. It is a type argument, a field, a local, +# an element, a constant, and what a signature gives, so generic code serves it as +# any type, and `return;` gives it where a union holds it, as `result`. + +struct holder : invokable where S: signature { + var call: def(S::params...): S::result; +} + +def holder::invoke(&mut this, args: S::params...): S::result { + return this.call(...args); +} + +struct labeled { + var label: strview; + var held: T; +} + +def said(x: i64): void { println($"said {x}"); } +def give(x: T): T { return x; } +def twice(f: def(): T): T { f(); return f(); } + +# Says only whether something failed. +def checked(n: i64): result { + if n < 0 { return "negative"; } + said(n); + return; +} + +const quiet: void = void {}; + +def main(): void { + val v := void {}; + var w: void; + w = v; + val x := said(1); + give::(said(2)); + twice(def() { println("again"); }); + println($"{size_of::()} {size_of::>()} {size_of::()} {size_of::>()}"); + + checked(3) else (e) { println("not reached"); return; }; + checked(-1) else (e) { println($"failed: {e}"); }; + match checked(-2) { + value(_) => println("fine"); + error(e) => println($"error: {e}"); + } + + # A `maybe` tells a value missing from the value of `void`. + var seen: maybe = nothing {}; + println($"{seen is some}"); + seen = said(4); + println($"{seen is some}"); + + # A signature giving nothing is given whole. + var h := holder:: { call = said }; + h(5); + + var marks := vector::::new(); + marks.append(quiet); + marks.append(said(6)); + val tag := labeled:: { label = "nothing held" }; + println($"{marks.length} {tag.label}"); + + # A thread's function giving nothing is joined for `void`. + var worker := thread::spawn(def() { println("in a thread"); }) else (e) { return; }; + worker.join(); + println("joined"); +} diff --git a/tests/programs/when_runs_what_the_target_takes_1.out b/tests/programs/when_runs_what_the_target_takes_1.out new file mode 100644 index 00000000..84c9cb54 --- /dev/null +++ b/tests/programs/when_runs_what_the_target_takes_1.out @@ -0,0 +1 @@ +picked 105 diff --git a/tests/programs/when_runs_what_the_target_takes_1.sakura b/tests/programs/when_runs_what_the_target_takes_1.sakura new file mode 100644 index 00000000..0517fef8 --- /dev/null +++ b/tests/programs/when_runs_what_the_target_takes_1.sakura @@ -0,0 +1,22 @@ +import std::io; +when backend == vm { val label: span = "picked"; } +when backend == native { val label: span = "picked"; } +def main(): void { + var total := 0; + when backend == vm || backend == native { + var step := 2; + val add := def(n: int): void { total += n * step; step++; }; + add(1); + add(1); + } + when backend == vm && backend == native { + total = nothing_here; + } + else when backend == vm { + total += 100; + } + else { + total += 100; + } + println($"{label} {total}"); +} diff --git a/tests/programs/writing_through_references_1.out b/tests/programs/writing_through_references_1.out new file mode 100644 index 00000000..ecc8836c --- /dev/null +++ b/tests/programs/writing_through_references_1.out @@ -0,0 +1 @@ +7 20 42 9 [101, 4, 9] -101 42 true diff --git a/tests/programs/writing_through_references_1.sakura b/tests/programs/writing_through_references_1.sakura new file mode 100644 index 00000000..e21c6725 --- /dev/null +++ b/tests/programs/writing_through_references_1.sakura @@ -0,0 +1,24 @@ +import std::io; +struct counter { var count: int; } +def bump(value: &mut int, by: &i32): void { value += by; value++; } +def swap(a: &mut int, b: &mut int): void { val t := a + 0; a = b; b = t; } +def set(maybe: *mut int): void { if maybe != null { maybe[0] = 42; } } +def main(): void { + var n := 1; + val step: i32 = 5; + bump(&mut n, &step); + var x := 10; + var y := 20; + swap(&mut x, &mut y); + var c := counter{3}; + bump(&mut c.count, &step); + var values := [1, 2, 3]; + for &mut v in values { v = v * v; } + val first := &mut values[0]; + first += 100; + set(&mut y as *mut int); + set(null); + var r := &x; + r = &y; + println($"{n} {x} {y} {c.count} {values} {-first} {r + 0} {r == 42}"); +} diff --git a/tests/server/server.sakura b/tests/server/server.sakura new file mode 100644 index 00000000..06e6bbad --- /dev/null +++ b/tests/server/server.sakura @@ -0,0 +1,127 @@ +#! @file server.sakura +#! @author John Christman (sorakatadzuma@gmail.com) +#! @copyright Malunal Studios, LLC. +#! @license MIT +#! +#! Contains the tests of what the language server reads and writes of the +#! protocol itself: positions in a file whose lines end in CR LF, which its +#! source holds with the LF alone, and the path a `file:` URI names and the URI +#! of a path, as each system spells them. + +import std::io; +import std::testing; +import sakura::analyzer; +module sakura::server; + + +@test def positions_in_text_with_cr_lf_are_those_of_its_lines(t: &mut tester): void { + var files := vector::::new(); + files.append(gathered { + path = string::from("a.sakura", nothing {}), + text = string::from("def f(): void {\r\n val label := \"日🌸\"; val x := 1;\r\n}\r\n", nothing {}) + }); + var roots := vector::::new(); + var documents := vector::::new(); + var held := program::parse(&files, false, false, "windows", &gathering { roots = &roots, documents = &documents }); + val text := held.source_text(0); + t.expects(text.length + 3 == held.texts[0].length); + + # `x` follows a character of three bytes and one of four, which is two units + # of UTF-16, and is a byte further into the text the editor has, past the CR + # ending the line before it. + val offset := locate(text, 1, 26); + t.expects(offset == 46 && text[46] == 'x'); + t.expects(locate(held.texts[0].view(), 1, 26) == 47); + val at := position_of(text, &held.sources[0].lines, offset); + t.expects(at.line == 1 && at.character == 26); +} + +@test def messages_are_json_whatever_a_file_holds(t: &mut tester): void { + # Each byte that breaks UTF-8 is U+FFFD, and the rest is escaped as JSON is. + var made := message_writer(); + made.begin_object(); + made.member("message"); + made.text("ok \xFF\"\n\xE2\x82"); + made.member("range"); + var starts := vector::::new(); + starts.append(0); + starts.append(4); + write_range(&mut made, "abc\ndé🌸f", &starts, 5, 11); + made.end_object(); + var out := string::new(nothing {}); + append_written(&mut out, &mut made); + t.expects(out.view() == "{\"message\":\"ok \\ufffd\\\"\\n\\ufffd\\ufffd\",\"range\":{\"start\":{\"line\":1,\"character\":1},\"end\":{\"line\":1,\"character\":4}}}"); +} + +# The path a URI names, or `none` where it names none. +def path_of(uri: strview): string { + var found := uri_path(uri); + if found is some(&mut named) { + return move(named); + } + return string::from("none", nothing {}); +} + +# The URI of a path. +def uri_of(path: strview): string { + var made := string::new(nothing {}); + append_uri(&mut made, path); + return made; +} + +when os == linux { + @test def uris_name_paths_as_linux_spells_them(t: &mut tester): void { + t.expects(path_of("file:///home/a%20b/").view() == "/home/a b"); + t.expects(path_of("file://localhost/x").view() == "/x"); + t.expects(path_of("untitled:Untitled-1").view() == "none"); + t.expects(uri_of("/home/a b").view() == "file:///home/a%20b"); + } +} + +when os == windows { + # Text with the letter of a drive between two others. + def with_drive(before: strview, letter: u8, after: strview): string { + var made := string::from(before, nothing {}); + made.push(letter); + made.append(after); + return made; + } + + @test def uris_name_paths_as_windows_spells_them(t: &mut tester): void { + val here := io::working_directory() else (_) { t.expects(false); return; }; + val whole := here.view(); + return if whole.length < 2 || whole[1] != ':'; + val letter: u8 = whole[0] >= 'a' ? whole[0] - 32 : whole[0]; + val lower: u8 = letter + 32; + + # Past a folder that is not there, the path is kept as it is given, made + # absolute, with the drive's letter upper case and no `/` at its end. + val named := path_of(with_drive("file:///", lower, "%3A/sakura-test-gone/a%20b.sakura").view()); + t.expects(named.view() == with_drive("", letter, ":/sakura-test-gone/a b.sakura").view()); + val ended := path_of(with_drive("file:///", letter, ":/sakura-test-gone/").view()); + t.expects(ended.view() == with_drive("", letter, ":/sakura-test-gone").view()); + val local := path_of(with_drive("file://localhost/", lower, ":/sakura-test-gone/x/./y/../z").view()); + t.expects(local.view() == with_drive("", letter, ":/sakura-test-gone/x/z").view()); + val root := path_of(with_drive("file:///", lower, "%3A").view()); + t.expects(root.view() == with_drive("", letter, ":/").view()); + t.expects(path_of("untitled:Untitled-1").view() == "none"); + + # The working directory, spelled in upper case, is spelled as on disk. + var slashed := string::new(nothing {}); + var shouted := string::new(nothing {}); + for i in 0..whole.length { + val byte: u8 = whole[i] == '\\' ? '/' : whole[i]; + slashed.push(byte); + shouted.push(byte >= 'a' && byte <= 'z' ? byte - 32 : byte); + } + val spelled := path_of(uri_of(shouted.view()).view()); + t.expects(spelled.view() == path_of(uri_of(slashed.view()).view()).view()); + t.expects(spelled.length != 0 && spelled[0] == letter && spelled[1] == ':'); + } + + @test def paths_are_named_by_uris_as_vs_code_spells_them(t: &mut tester): void { + t.expects(uri_of("C:/Users/a b/日.sakura").view() == "file:///c%3A/Users/a%20b/%E6%97%A5.sakura"); + t.expects(uri_of("C:/").view() == "file:///c%3A/"); + t.expects(uri_of("//server/share/x").view() == "file://server/share/x"); + } +} diff --git a/tools/corpus.sakura b/tools/corpus.sakura new file mode 100644 index 00000000..91739900 --- /dev/null +++ b/tools/corpus.sakura @@ -0,0 +1,204 @@ +#! @file corpus.sakura +#! @author John Christman (sorakatadzuma@gmail.com) +#! @copyright Malunal Studios, LLC. +#! @license MIT +#! +#! Contains the runner of the corpus, the programs of `tests/programs`: each is +#! run by a command given, and what it writes and how it stops are compared +#! with `NAME.out` beside it, so the C compiler and the rebuild are held to one +#! corpus. Run it from the root of the repository: +#! +#! sakura run --lib std=STD tools/corpus.sakura -- [--write] [--only TEXT] [--dir DIR] COMMAND... +#! +#! The command is given each program's path after its own words, as +#! `sakura run --lib std=STD`, the C compiler's `sakura run --std STD`, or the +#! rebuild's `entry run --lib std=STD` built as an executable. `--write` writes what each program gives as its `NAME.out` +#! rather than comparing, as the C compiler does to make them, `--only TEXT` +#! runs only the programs whose name holds the text, and `--dir DIR` runs those +#! of another directory: `tests/checked`, whose programs stop only where the +#! program checks, as `run` and `build --checks` make it, and `tests/memory`, +#! whose programs are run with `run --checks`. +#! +#! `NAME.out` holds what the program wrote to its output, and, where it stopped +#! with any status but 0 or wrote to its error, a line `--- exit N`, or +#! `--- signal N`, after it, then what it wrote to its error. + +import std::io; +import std::process; +import system; + +#! Where the programs are, from the root of the repository, unless `--dir` +#! names another directory. +const corpus: strview = "tests/programs"; + +def main(args: span): void { + var writes := false; + var only := string::new(nothing {}); + var directory: strview = corpus; + var command := vector::::new(); + var i := 0u; + while i < args.length { + val arg := args.at(i); + if command.length == 0 && arg == "--write" { + writes = true; + } else if command.length == 0 && arg == "--only" && i + 1 < args.length { + i++; + only = string::from(args.at(i), nothing {}); + } else if command.length == 0 && arg == "--dir" && i + 1 < args.length { + i++; + directory = args.at(i); + } else { + command.append(arg); + } + i++; + } + if command.length == 0 { + system::fd::stderr.put("corpus: give the command each program is run by, as `sakura run --lib std=../std`\n"); + exit(2); + } + + var names := program_names(directory); + var passed := 0u; + var failed := 0u; + for &name in names { + continue if only.length != 0 && !contains(name.view(), only.view()); + val program := $"{directory}/{name}.sakura"; + val expected_at := $"{directory}/{name}.out"; + var got := run(command.view(), program.view()); + + var at := path::parse(expected_at.view()) else (_) { continue; }; + if writes { + _ = io::write_file(&at, got.view()); + continue; + } + + var expected := io::read_file(&at) else (_) { + println($"[ FAIL ] {name}: it has no `{name}.out`"); + failed++; + continue; + }; + if expected.view() == got.view() { + passed++; + continue; + } + failed++; + println($"[ FAIL ] {name}"); + show_difference(expected.view(), got.view()); + } + if writes { + println($"wrote what {names.length} programs give"); + return; + } + println($"{passed} passed, {failed} failed"); + exit(failed == 0 ? 0 : 1); +} + +#! The name of each program of a directory, without `.sakura`, in order. +#! @param directory The directory. +#! @returns The names. +def program_names(directory: strview): vector { + var made := vector::::new(); + var at := path::parse(directory) else (_) { return made; }; + var listing := io::directory::open(&at) else (_) { return made; }; + while listing.next() is some(each) { + val name := each.name; + continue if name.length <= 7 || name.substr(name.length - 7, 7) != ".sakura"; + made.append(string::from(name.substr(0, name.length - 7), nothing {})); + } + + # In order, so the runs read the same each time. + var sorted := vector::::new(); + for &each in made { + var at := sorted.length; + while at > 0 && sorted.at(at - 1).compare(each.view()) > 0 { + at--; + } + sorted.insert_at(at, string::copy_of(&each)); + } + return sorted; +} + +#! Runs a program by the command, and gives what it wrote and how it stopped, +#! as `NAME.out` holds them. +#! @param command The command's words. +#! @param program The program's path. +#! @returns The text. +def run(command: span, program: strview): string { + var started := process::command::new(command.at(0)); + for i in 1..command.length { + started.argument(command.at(i)); + } + started.argument(program); + var made := string::new(nothing {}); + val got := started.capture() else (why) { + made.append($"--- not started: {why}\n"); + return made; + }; + made.append(got.output.view()); + + var stopped := string::new(nothing {}); + if got.status is exited(code) { + if code != 0 { + stopped.append($"--- exit {code}"); + } + } else if got.status is signaled(number) { + stopped.append($"--- signal {number}"); + } + if stopped.length == 0 && got.error.length != 0 { + stopped.append("--- exit 0"); + } + if stopped.length != 0 { + made.append("\n"); + made.append(stopped.view()); + made.append("\n"); + made.append(got.error.view()); + } + return made; +} + +#! Whether text holds other text. +#! @param text The text searched. +#! @param piece The text looked for. +#! @returns Whether it does. +def contains(text: strview, piece: strview): bool { + return true if piece.length == 0; + return false if piece.length > text.length; + for i in 0..text.length - piece.length + 1 { + return true if text.substr(i, piece.length) == piece; + } + return false; +} + +#! Shows the first line where what a program gave differs from what was +#! expected. +#! @param expected What was expected. +#! @param got What it gave. +def show_difference(expected: strview, got: strview): void { + var line := 1u; + var at := 0u; + while at < expected.length && at < got.length && expected.at(at) == got.at(at) { + if expected.at(at) == '\n' { + line++; + } + at++; + } + println($" line {line}:"); + println($" expected: {line_at(expected, at)}"); + println($" got: {line_at(got, at)}"); +} + +#! The line of text holding a byte, without its line break. +#! @param text The text. +#! @param at The byte. +#! @returns The line. +def line_at(text: strview, at: u64): strview { + var start := at < text.length ? at : text.length; + while start > 0 && text.at(start - 1) != '\n' { + start--; + } + var end := start; + while end < text.length && text.at(end) != '\n' { + end++; + } + return text.substr(start, end - start); +} diff --git a/tools/function.sakura b/tools/function.sakura new file mode 100644 index 00000000..b0443f7d --- /dev/null +++ b/tools/function.sakura @@ -0,0 +1,96 @@ +#! @file function.sakura +#! @author John Christman (sorakatadzuma@gmail.com) +#! @copyright Malunal Studios, LLC. +#! @license MIT +#! +#! Contains the probe of what a call costs, as `docs/performance.md` records +#! it: `t = t ^ f(i)` over many calls, `f` held each way a program holds a +#! callable. +#! Build it as an executable and run it on one core, or run it in the machine +#! with fewer calls: +#! +#! sakura build --lib std=../std -O2 -o calls tools/function.sakura +#! taskset -c 2 ./calls +#! taskset -c 2 sakura run --lib std=../std tools/function.sakura -- 10000000 +#! +#! A functor a `function` holds should cost what a function value does. + +import std::io; +import std::time; + +# A functor of two words, which a function holds in its buffer. +struct small : invokable { var a: i64; var b: i64; } +def small::invoke(&mut this, x: i64): i64 { return x + this.a * this.b; } + +# A functor of four words, which a function holds in a box. +struct large : invokable { var a: i64; var b: i64; var pad: u64[2]; } +def large::invoke(&mut this, x: i64): i64 { return x + this.a * this.b; } + +# Each callable is kept in a global, read where it is called, so that nothing +# calling it knows which it is. +var a_small: small; +var a_value: maybe = nothing {}; +var a_trait: maybe<&mut invokable> = nothing {}; +var in_place: function; +var boxed: function; +var a_lambda: function; + +def with_generic(f: &mut F, calls: i64): i64 where F: invokable { + var t: i64 = 0; + for i in 0..calls { t = t ^ f(i); } + return t; +} + +def with_value(f: def(i64): i64, calls: i64): i64 { + var t: i64 = 0; + for i in 0..calls { t = t ^ f(i); } + return t; +} + +def with_trait(f: &mut invokable, calls: i64): i64 { + var t: i64 = 0; + for i in 0..calls { t = t ^ f(i); } + return t; +} + +def with_function(f: &function, calls: i64): i64 { + var t: i64 = 0; + for i in 0..calls { t = t ^ f(i); } + return t; +} + +# Prints how long each call took, in nanoseconds. +def report(name: strview, start: time::instant, calls: i64, t: i64): void { + val ns := (time::instant::now() - start) / time::nanoseconds(1); + println($"{name}: {ns / (calls as f64)} ns ({t})"); +} + +@allow def main(args: span): void { + var calls: i64 = 300000000; + if args.length != 0 { + calls = integer::parse::(args[0]) else { return; }; + } + val a := 3; + val b := 5; + a_small = small { a = 3, b = 5 }; + a_value = def(x: i64): i64 => x + a * b; + a_trait = &mut a_small; + in_place = function::new(small { a = 3, b = 5 }); + boxed = function::new(large { a = 3, b = 5 }); + a_lambda = function::new(def(x: i64): i64 => x + a * b); + val value := a_value else { return; }; + val by_trait := a_trait else { return; }; + + var start := time::instant::now(); + report("a generic F, inlined", start, calls, with_generic(&mut a_small, calls)); + start = time::instant::now(); + report("a function value, its lambda using two locals", start, calls, with_value(value, calls)); + start = time::instant::now(); + report("a trait reference to invokable", start, calls, with_trait(by_trait, calls)); + start = time::instant::now(); + report("a function holding a functor of 16 bytes", start, calls, with_function(&in_place, calls)); + start = time::instant::now(); + report("a function holding a functor of 32 bytes, boxed", start, calls, with_function(&boxed, calls)); + start = time::instant::now(); + report("a function holding a function value", start, calls, with_function(&a_lambda, calls)); +} diff --git a/tools/iterators.sakura b/tools/iterators.sakura new file mode 100644 index 00000000..7fbbd1bf --- /dev/null +++ b/tools/iterators.sakura @@ -0,0 +1,121 @@ +#! @file iterators.sakura +#! @author John Christman (sorakatadzuma@gmail.com) +#! @copyright Malunal Studios, LLC. +#! @license MIT +#! +#! Contains the probe of what iterators cost: one sum, of the squares of the +#! even numbers among the first N, worked out by loops written out and by +#! adapters, over a vector and over a range, each ten times. Build it as an +#! executable, as its measure is of the code a compiler makes, and run it on +#! one core: +#! +#! sakura build --lib std=STD -O2 -o iterators tools/iterators.sakura +#! taskset -c 2 ./iterators [N] +#! +#! N is 10,000,000 where it is not given. The measure the iterators plan set is +#! the adapters given functors within 10% of `for &x in v`, which the last line +#! says. + +import std::io; +import std::time; + +#! Tests an element a view's iterator gives, a reference, by reference. +struct is_even : invokable {} +def is_even::invoke(&mut this, x: & &u64): bool { return x % 2 == 0; } + +#! Squares an element a view's iterator gives. +struct square : invokable {} +def square::invoke(&mut this, x: &u64): u64 { return x * x; } + +#! Tests a number a range gives, by reference. +struct is_even_number : invokable {} +def is_even_number::invoke(&mut this, x: &u64): bool { return x % 2 == 0; } + +#! Squares a number a range gives. +struct square_number : invokable {} +def square_number::invoke(&mut this, x: u64): u64 { return x * x; } + +def counted(n: u64): u64 { + var total: u64 = 0; + for x in 0..n { + if x % 2 == 0 { total += x * x; } + } + return total; +} + +def referred(v: &vector): u64 { + var total: u64 = 0; + for &x in v { + if x % 2 == 0 { total += x * x; } + } + return total; +} + +def indexed(v: &vector): u64 { + var total: u64 = 0; + for i in 0..v.length { + val x := v[i]; + if x % 2 == 0 { total += x * x; } + } + return total; +} + +def functors(v: &vector): u64 { + return v.iter().filter(is_even {}).map(square {}).sum(); +} + +def lambdas(v: &vector): u64 { + return v.iter().filter(def(x) => x % 2 == 0).map(def(x): u64 => x * x).sum(); +} + +def range_functors(n: u64): u64 { + return (0..n).filter(is_even_number {}).map(square_number {}).sum(); +} + +def range_lambdas(n: u64): u64 { + return (0..n).filter(def(x) => x % 2 == 0).map(def(x: u64): u64 => x * x).sum(); +} + +#! Runs a way ten times, writing how long it took and what it gave. +#! @param name What it is called. +#! @param run The way. +#! @returns How long it took, in nanoseconds. +def timed(name: strview, run: def(): u64): u64 { + val start := instant::now(); + var sum: u64 = 0; + for _ in 0..10u { + sum += run(); + } + val took := (instant::now() - start).in_nanoseconds as u64; + val ms := $"{took / 1000000}"; + println($"{name.rpad(24, ' ')} {ms.lpad(6, ' ')} ms {sum}"); + return took; +} + +def main(args: span): void { + var n: u64 = 10000000; + if args.length > 0 { + n = integer::parse::(args[0]) else { + println("The count is a number, as 10000000."); + return; + }; + } + + var v := vector::::new(); + v.reserve(n); + for i in 0..n { + v.append(i); + } + val r := &v; + timed("for x in 0..n", def(): u64 => counted(n)); + val loop := timed("for &x in v", def(): u64 => referred(r)); + timed("v[i]", def(): u64 => indexed(r)); + val adapted := timed("adapters, functors", def(): u64 => functors(r)); + timed("adapters, lambdas", def(): u64 => lambdas(r)); + timed("range, functors", def(): u64 => range_functors(n)); + timed("range, lambdas", def(): u64 => range_lambdas(n)); + + val ratio := adapted as f64 / (loop == 0 ? 1 : loop) as f64; + val verdict: strview = ratio <= 1.1 ? "within" : "outside"; + println($"functors / for &x in v: {ratio}, {verdict} the measure of 1.1"); +} diff --git a/tools/memory.sakura b/tools/memory.sakura new file mode 100644 index 00000000..3f9d7456 --- /dev/null +++ b/tools/memory.sakura @@ -0,0 +1,148 @@ +#! @file memory.sakura +#! @author John Christman (sorakatadzuma@gmail.com) +#! @copyright Malunal Studios, LLC. +#! @license MIT +#! +#! Contains the probe of how fast a program's memory is, as `docs/performance.md` +#! records it: a list of 1,000,000 nodes built and summed, ten times over, its +#! nodes held each way std holds memory. Build it as an executable and run it on +#! one core: +#! +#! sakura build --lib std=../std -O2 -o memory tools/memory.sakura +#! taskset -c 2 ./memory +#! +#! A `box` should cost no more than a tenth more than `raw_allocate` does. + +import std::allocators; +import std::io; +import std::time; + +const nodes: u64 = 1000000; +const rounds: u64 = 10; + +struct boxed { + var value: u64; + var next: maybe>; +} + +struct raw { + var value: u64; + var next: *mut raw; +} + +# Nodes in a `box` each, owned by the node before, and taken out one by one from +# the front, since closing the first would close the rest within it, a frame each. +def with_boxes(): u64 { + var sum: u64 = 0; + for _ in 0..rounds { + var front: maybe> = nothing {}; + for i in 0..nodes { + front = box::::new(boxed { value = i, next = move(&mut front) }); + } + var at: maybe<&boxed> = nothing {}; + if front is some(&first) { + at = first.get(); + } + while at is some(&each) { + sum += each.value; + at = nothing {}; + if each.next is some(&next) { + at = next.get(); + } + } + while front is some(&mut first) { + var node := first.take(); + front = move(&mut node.next); + } + } + return sum; +} + +# Nodes `raw_allocate` gives, each released by itself. +def with_blocks(): u64 { + var sum: u64 = 0; + for _ in 0..rounds { + var front: *mut raw = null; + for i in 0..nodes { + val made := raw_allocate(size_of::()) as *mut raw; + made[0] = raw { value = i, next = front }; + front = made; + } + var at := front; + while at != null { + sum += at[0].value; + at = at[0].next; + } + while front != null { + val next := front[0].next; + raw_release(front as *mut u8); + front = next; + } + } + return sum; +} + +# Nodes of an arena, freed together as it resets. +def with_an_arena(): u64 { + var sum: u64 = 0; + var a := arena::new(); + val alloc: maybe<&mut allocator> = &mut a; + for _ in 0..rounds { + var front: *mut raw = null; + for i in 0..nodes { + val made := acquire::(alloc, 1); + made[0] = raw { value = i, next = front }; + front = made; + } + var at := front; + while at != null { + sum += at[0].value; + at = at[0].next; + } + a.reset(); + } + return sum; +} + +# Nodes of a pool, each given back by itself. +def with_a_pool(): u64 { + var sum: u64 = 0; + var p := pool::of::(); + for _ in 0..rounds { + var front: *mut raw = null; + for i in 0..nodes { + front = p.make(raw { value = i, next = front }); + } + var at := front; + while at != null { + sum += at[0].value; + at = at[0].next; + } + while front != null { + val next := front[0].next; + p.unmake(front); + front = next; + } + } + return sum; +} + +# Runs a way of holding the nodes, printing how long it took. +def timed(name: strview, way: def(): u64): f64 { + val start := time::instant::now(); + val sum := way(); + val took := (time::instant::now() - start) / time::milliseconds(1); + if sum != rounds * nodes * (nodes - 1) / 2 { + println($"{name}: the sum is {sum}, which is wrong"); + } + println($"{name}: {took} ms"); + return took; +} + +def main(): void { + val boxes := timed("box, released one by one", with_boxes); + val blocks := timed("raw_allocate and raw_release, one by one", with_blocks); + _ = timed("an arena, reset once each time", with_an_arena); + _ = timed("a pool, each given back by itself", with_a_pool); + println($"box / raw_allocate: {boxes / blocks}"); +} diff --git a/tools/profile/__pycache__/inlined.cpython-314.pyc b/tools/profile/__pycache__/inlined.cpython-314.pyc new file mode 100644 index 0000000000000000000000000000000000000000..89b96ee9a2698b154171d2e0affa9c0b95431f09 GIT binary patch literal 2642 zcmb7GO>7%Q6rS0?#9ljb{#;T@?6fq*ZE82Ifg}wHQAzkIgs=@R6w}JJH_3vtUd^u4 zGzVn3&>yM>CIw~RbBU?C4tWGwMV1#n$3{vpp$f}Ik!uFc8xEIj`Xx`a6 zQM4+WaNW6wkitd5CTj}UQ<>O(7+WIP^K27UrxT6;mMOer<-Y1>svn^}=tXg&>ECbf zY**oXc5l7=e|&Y$4j@I?g)EmMLhn{2=w$`(L!r7~nc;DYBh-Cz(5JOR>0nI>hCq*b;OM&B-4~-2XbRO)G<`~-P zVzF8hobXM9p56reD7ih=^&o(Y2%85$3V^7ACC;vAw-|O( z?2HDE3(oG&wWwf)iy?(q1Vs!>inJ3Pl)7Dzc3-V-9qURx{9F%KPnfXz!a1!nPIzx$ zvy~z_`UV$4iu(*AlLj9X2*G0PQ^ny;J+QSEC`tq@5~RksaF(a8rAjcD%*$ zBPN~kMXPZ&gfKc4?SieCcn0@u^VJYfJONTcRhYKD>llFXKRrEWdm7#D=|tN$#p*OB z#dkT)O1}Xvl-J0PHDun27=vFSv|>$rw1fyb%4P?6s9hwdW0<&xI^qoz%vDpMzQ-g z(qc$B3eRRAbbC<%a5{;`d_YKe3$I%!okuw_fKEV;87U}03itCG4&m_-ru>XLAL1w% zK1^}KWC`mE60n4*Yj9fC)p>&q(e~s_LetIgAglVcITWsKvG|&P=zaws3f;#)Z(kj` z*0S=6OAh_y^S^B__rLW@(btuG{HD8gF?>0^d@ygVoL*~Pv%Z=vv_DY}?EB!tyBF43 zbc)@_i-F_i?w-}?A0j9B|J*nV}-qg z8=i-1+CS9H$iCc@1h8{EO)@fM&*p#~2l&3#h!OUopJ!n&lkP-=FJ=40|n2)oU6=>uMfOB@cPiJLrXm+K5(56lm%}|Xk8atmy~x- vzj-?ExzTp0)D~TDi>{t5w)L+aztJ|lAw2xMAmY~F8=7&`AKe%qvHki7dVmId literal 0 HcmV?d00001 diff --git a/tools/profile/annotate.py b/tools/profile/annotate.py new file mode 100644 index 00000000..017bb704 --- /dev/null +++ b/tools/profile/annotate.py @@ -0,0 +1,32 @@ +# Disassembles a function of an executable built with `sakura build -g`, beside what +# each instruction cost and the line and function it came from. +# +# python3 annotate.py PROFILE EXECUTABLE FUNCTION +# +# The profile is one costs.py has read; FUNCTION is a symbol, as `checker::slot`. +import os, pickle, re, subprocess, sys +sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) +import inlined + +profile, executable, name = sys.argv[1], sys.argv[2], sys.argv[3] +events, own, calls, counts, found = pickle.load(open(profile + '.pkl', 'rb')) +for line in subprocess.run(['nm', '-S', executable], capture_output=True, text=True).stdout.split('\n'): + parts = line.split(None, 3) + if len(parts) != 4 or parts[3] != name: + continue + start, size = int(parts[0], 16), int(parts[1], 16) + listing = subprocess.run(['objdump', '-d', '--no-show-raw-insn', f'--start-address={start}', + f'--stop-address={start + size}', executable], capture_output=True, text=True).stdout + mapped = inlined.chains(executable, range(start, start + size)) + last = None + for each in listing.split('\n'): + m = re.match(r'\s*([0-9a-f]+):\s*(.*)', each) + if not m: + continue + address = int(m.group(1), 16) + chain = inlined.frames(mapped, address) + if chain[0] != last: + print(f' ; {chain[0][1]} [{chain[0][0]}]') + last = chain[0] + print(f'{own.get(address, [0])[0]:>12,} {m.group(2)}') + break diff --git a/tools/profile/costs.py b/tools/profile/costs.py new file mode 100644 index 00000000..260a1709 --- /dev/null +++ b/tools/profile/costs.py @@ -0,0 +1,145 @@ +# Reads a callgrind profile of an executable built with `sakura build -g` and prints +# its costs with inlined code counted where it came from. +# +# valgrind --tool=callgrind --dump-instr=yes --compress-pos=no --compress-strings=no \ +# --callgrind-out-file=PROFILE EXECUTABLE ARGS... +# python3 costs.py PROFILE EXECUTABLE [EVENT [MODE [COUNT [FUNCTION]]]] +# +# EVENT is one callgrind counted, `Ir` by default; with `--cache-sim=yes +# --branch-sim=yes` there are also `D1mr`, `DLmw`, `I1mr`, `Bcm`, and the others. +# MODE is one of: +# fn self cost by source function +# incl inclusive cost by source function (recursion counts more than once) +# line self cost by source line +# sym self cost by symbol, the function the code was emitted in +# callees F what F's code calls, inlined code included +# callers F the call sites of F, where it is called rather than inlined +# inlined F where F's code was inlined +# lines F the lines of F +# users REGEX the cost of functions matching REGEX by the first frame outside +# them and std that led there, which is the analyzer code using them +# calls out-of-line calls of each function, and its instructions per call +# The mapping is cached beside the profile, as PROFILE.pkl. +import collections, os, pickle, re, sys +sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) +import inlined + +profile, executable = sys.argv[1], sys.argv[2] +event = sys.argv[3] if len(sys.argv) > 3 else 'Ir' +mode = sys.argv[4] if len(sys.argv) > 4 else 'fn' +count = int(sys.argv[5]) if len(sys.argv) > 5 else 40 +target = sys.argv[6] if len(sys.argv) > 6 else None + +cache = profile + '.pkl' +if os.path.exists(cache) and os.path.getmtime(cache) > os.path.getmtime(profile): + events, own, calls, counts, found = pickle.load(open(cache, 'rb')) +else: + events, own, calls, counts = [], {}, [], collections.Counter() + callee = None + pending = False + positions = 1 + for line in open(profile): + if line.startswith('positions:'): + positions = len(line.split()) - 1 + elif line.startswith('events:'): + events = line.split()[1:] + elif line.startswith('cfn='): + callee = line[4:].strip() + elif line.startswith('calls='): + counts[callee] += int(line.split()[0][6:]) + pending = True + elif line.startswith('0x'): + parts = line.split() + address = int(parts[0], 16) + # With --dump-line=yes a line number follows the address. + numbers = [int(x) for x in parts[positions:]] + numbers += [0] * (len(events) - len(numbers)) + if pending: + calls.append((address, callee, numbers)) + pending = False + elif address in own: + own[address] = [a + b for a, b in zip(own[address], numbers)] + else: + own[address] = numbers + found = inlined.chains(executable, list(own) + [a for a, _, _ in calls]) + pickle.dump((events, own, calls, counts, found), open(cache, 'wb')) + +index = events.index(event) +total = sum(c[index] for c in own.values()) or 1 + +def show(title, counter): + print(f'== {title} ({event}, total {total:,})') + for key, value in counter.most_common(count): + print(f'{100 * value / total:6.2f}% {value:>13,} {key[:110]}') + +def outside(chain, pattern): + for function, location in chain: + if not pattern.search(function) and not location.startswith('std/'): + return function + ' @ ' + location + return None + +result = collections.Counter() +if mode in ('fn', 'line', 'sym'): + for address, cost in own.items(): + chain = inlined.frames(found, address) + key = {'fn': chain[0][0], 'line': chain[0][1], 'sym': chain[-1][0]}[mode] + result[key] += cost[index] + show({'fn': 'self cost by source function', 'line': 'self cost by line', 'sym': 'self cost by symbol'}[mode], result) +elif mode == 'incl': + for address, cost in own.items(): + for function in set(f for f, _ in inlined.frames(found, address)): + result[function] += cost[index] + for address, called, cost in calls: + for function in set(f for f, _ in inlined.frames(found, address)): + if function != called: + result[function] += cost[index] + show('inclusive cost by source function', result) +elif mode == 'callees': + for address, called, cost in calls: + names = [f for f, _ in inlined.frames(found, address)] + if target in names: + within = names[:names.index(target)] + result[called + (' via ' + '/'.join(reversed(within)) if within else '')] += cost[index] + show(f'calls made by {target}, inclusive', result) +elif mode == 'callers': + for address, called, cost in calls: + if called == target: + chain = inlined.frames(found, address) + result[chain[0][0] + ' @ ' + chain[0][1]] += cost[index] + show(f'calls of {target}, inclusive, by call site', result) +elif mode == 'inlined': + for address, cost in own.items(): + chain = inlined.frames(found, address) + names = [f for f, _ in chain] + if target in names and names.index(target) + 1 < len(names): + outer = chain[names.index(target) + 1] + result[outer[0] + ' @ ' + outer[1]] += cost[index] + show(f'{target} inlined into', result) +elif mode == 'lines': + for address, cost in own.items(): + chain = inlined.frames(found, address) + if chain[0][0] == target: + result[chain[0][1]] += cost[index] + show(f'lines of {target}', result) +elif mode == 'users': + pattern = re.compile(target) + for address, cost in own.items(): + chain = inlined.frames(found, address) + if pattern.search(chain[0][0]): + user = outside(chain, pattern) + if user: + result[user] += cost[index] + for address, called, cost in calls: + chain = inlined.frames(found, address) + if pattern.search(called) and not pattern.search(chain[-1][0]): + user = outside(chain, pattern) + if user: + result[user] += cost[index] + show(f'/{target}/ by the code using it', result) +elif mode == 'calls': + symbols = collections.Counter() + for address, cost in own.items(): + symbols[inlined.frames(found, address)[-1][0]] += cost[0] + print(' calls instructions per call function') + for function, n in counts.most_common(count): + print(f'{n:>10,} {symbols[function]:>12,} {symbols[function] / n:8.1f} {function}') diff --git a/tools/profile/count.c b/tools/profile/count.c new file mode 100644 index 00000000..3b3f5eb4 --- /dev/null +++ b/tools/profile/count.c @@ -0,0 +1,78 @@ +// Runs a program pinned to one processor and counts its work with the processor's +// own counters, which need no kernel profiling support beyond `perf_event_open`. +// +// cc -O2 -o count count.c +// count CPU PROGRAM ARGS... +// +// Prints to the standard error, on one line: the wall time in seconds, the peak +// resident memory in KB, the instructions and the cycles the program and its threads +// ran outside the kernel, and its exit status. A CPU below 0 doesn't pin it. The +// program's output is discarded. +// +// The counters are the performance cores' (`cpu_core`), as this processor's efficiency +// cores count no cycles, so pin to a performance core. They need +// `/proc/sys/kernel/perf_event_paranoid` at 2 or less. +#define _GNU_SOURCE +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +static int open_counter(pid_t pid, unsigned long long type, unsigned long long config) { + struct perf_event_attr a; + memset(&a, 0, sizeof a); + a.size = sizeof a; + a.type = PERF_TYPE_HARDWARE; + a.config = (type << 32) | config; + a.disabled = 1; + a.enable_on_exec = 1; + a.inherit = 1; + a.exclude_kernel = 1; + a.exclude_hv = 1; + return (int)syscall(SYS_perf_event_open, &a, pid, -1, -1, 0); +} + +int main(int argc, char **argv) { + int cpu = atoi(argv[1]); + FILE *f = fopen("/sys/bus/event_source/devices/cpu_core/type", "r"); + unsigned long long type = 0; + if (f) { if (fscanf(f, "%llu", &type) != 1) type = 0; fclose(f); } + int go[2]; + if (pipe(go)) return 1; + struct timespec t0, t1; + pid_t pid = fork(); + if (pid == 0) { + if (cpu >= 0) { + cpu_set_t set; CPU_ZERO(&set); CPU_SET(cpu, &set); + sched_setaffinity(0, sizeof set, &set); + } + close(go[1]); + char c; if (read(go[0], &c, 1) != 1) _exit(127); + int null = open("/dev/null", O_WRONLY); + dup2(null, 1); + execvp(argv[2], argv + 2); + _exit(127); + } + close(go[0]); + int ins = open_counter(pid, type, PERF_COUNT_HW_INSTRUCTIONS); + int cyc = open_counter(pid, type, PERF_COUNT_HW_CPU_CYCLES); + clock_gettime(CLOCK_MONOTONIC, &t0); + if (write(go[1], "x", 1) != 1) return 1; + int status; struct rusage ru; + wait4(pid, &status, 0, &ru); + clock_gettime(CLOCK_MONOTONIC, &t1); + long long ni = -1, nc = -1; + if (ins >= 0 && read(ins, &ni, sizeof ni) != sizeof ni) ni = -1; + if (cyc >= 0 && read(cyc, &nc, sizeof nc) != sizeof nc) nc = -1; + double wall = (t1.tv_sec - t0.tv_sec) + (t1.tv_nsec - t0.tv_nsec) / 1e9; + fprintf(stderr, "%.4f %ld %lld %lld %d\n", wall, ru.ru_maxrss, ni, nc, + WIFEXITED(status) ? WEXITSTATUS(status) : -1); + return 0; +} diff --git a/tools/profile/inlined.py b/tools/profile/inlined.py new file mode 100644 index 00000000..ecec33d1 --- /dev/null +++ b/tools/profile/inlined.py @@ -0,0 +1,40 @@ +# Maps code addresses of an executable built with `sakura build -g` to the functions +# they were inlined from, through `addr2line -i`, which reads the executable's +# `.petal` file. Shared by the scripts beside it. +import os, re, subprocess + +# Paths are shown relative to the current directory, and to the standard library +# where SAKURA_STD names it. +_prefixes = [os.getcwd().rstrip('/') + '/'] +if os.environ.get('SAKURA_STD'): + _prefixes.append(os.environ['SAKURA_STD'].rstrip('/') + '/') + +def _short(location): + location = re.sub(r' \(discriminator.*\)', '', location) + for i, prefix in enumerate(_prefixes): + if location.startswith(prefix): + return ('std/' if i > 0 else '') + location[len(prefix):] + return location + +def chains(executable, addresses): + """Each address's frames, innermost first: (function, file:line).""" + addresses = sorted(set(addresses)) + out = subprocess.run(['addr2line', '-e', executable, '-a', '-f', '-i'], + input='\n'.join(hex(a) for a in addresses), + capture_output=True, text=True).stdout.split('\n') + found, current, i = {}, None, 0 + while i < len(out): + line = out[i] + if line.startswith('0x'): + current = int(line, 16) + found[current] = [] + i += 1 + elif current is not None and i + 1 < len(out): + found[current].append((line, _short(out[i + 1]))) + i += 2 + else: + i += 1 + return found + +def frames(found, address): + return found.get(address) or [('??', '??:0')] diff --git a/tools/profile/kinds.py b/tools/profile/kinds.py new file mode 100644 index 00000000..9bb3d616 --- /dev/null +++ b/tools/profile/kinds.py @@ -0,0 +1,52 @@ +# Classifies the instructions a callgrind profile counted by what they do, which +# shows how much of the code is moving values between frame slots and registers, +# calling, and checking, rather than computing. +# +# python3 kinds.py PROFILE EXECUTABLE +# +# The profile is one costs.py has read. +import collections, os, pickle, re, subprocess, sys +sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) + +profile, executable = sys.argv[1], sys.argv[2] +events, own, calls, counts, found = pickle.load(open(profile + '.pkl', 'rb')) +listing = subprocess.run(['objdump', '-d', '--no-show-raw-insn', executable], capture_output=True, text=True).stdout +instructions, order = {}, [] +for line in listing.splitlines(): + m = re.match(r'\s*([0-9a-f]+):\s+(.*)$', line) + if m: + address = int(m.group(1), 16) + instructions[address] = m.group(2).strip() + order.append(address) +following = {order[i]: order[i + 1] for i in range(len(order) - 1)} + +def kind(text, after): + if text.startswith('rep stos'): return 'zeroing: rep stos' + if text.startswith('rep movs'): return 'copying: rep movs' + if re.match(r'movq\s+\$0x0,-?(0x[0-9a-f]+)?\(%rbx\)', text): return 'zeroing: slot' + if text.startswith(('push %rbp', 'mov %rsp,%rbp', 'leave', 'ret')): return 'call: frame link' + if re.match(r'(add|sub)\s+\$0x[0-9a-f]+,%rbx$', text): return 'call: moving rbx' + if text.startswith('call'): return 'call: call' + # The prologue's check of the frames' limit: lea from rbx, then cmp with a global. + if re.match(r'lea\s+-?(0x[0-9a-f]+)?\(%rbx\),%rax$', text) and re.match(r'cmp\s+0x[0-9a-f]+,%rax$', after): return 'call: stack check' + if re.match(r'cmp\s+0x[0-9a-f]+,%rax$', text): return 'call: stack check' + if re.match(r'test\s+(%\w+),\1$', text) and after.startswith('jne'): return 'null check' + if re.search(r'\(%rbx\)', text) and text.startswith('mov'): + return 'slot: store' if re.match(r'mov\w*\s+%\w+,', text) else 'slot: load' + if re.match(r'lea\s+-?(0x[0-9a-f]+)?\(%rbx\)', text): return 'slot: address' + if re.match(r'mov\s+%\w+,%\w+$', text): return 'register copy' + if re.match(r'mov\w*\s+\$', text): return 'constant' + if re.match(r'mov\w*\s+[^,]*\([^)]*\),%\w+$', text): return 'load through a pointer' + if re.match(r'mov\w*\s+%\w+,[^,]*\(', text): return 'store through a pointer' + if text.startswith('j'): return 'branch' + if text.startswith(('cmp', 'test')): return 'compare' + return 'computing: ' + text.split()[0] + +result = collections.Counter() +for address, cost in own.items(): + text = instructions.get(address, '?') + result[kind(text, instructions.get(following.get(address), ''))] += cost[0] +total = sum(result.values()) or 1 +for name, value in result.most_common(30): + print(f'{value:>14,} {100 * value / total:5.1f}% {name}') +print(f'{total:>14,} total') diff --git a/tools/profile/measure.py b/tools/profile/measure.py new file mode 100644 index 00000000..ffa26f68 --- /dev/null +++ b/tools/profile/measure.py @@ -0,0 +1,110 @@ +# Times the compilers at their work, in turns, through `count`, as docs/performance.md +# measures them: each checking and building the rebuild's sources of its day, checking a +# one-line program, and running the rebuild's compiler on its VM. +# +# cc -O2 -o count count.c +# python3 -I measure.py WORK [GROUP...] +# +# WORK is a directory holding what's measured, laid out as below, and GROUP any of +# `hello`, `check`, `build`, `vm` and `threads` (all by default). Prints a line for +# each command and writes them to WORK/results.json. +# +# count the counter, built from count.c +# c_start/sakura C as it was, and c_start/std its std +# r_start/ the rebuild's sources and std as they were +# r_start_c the rebuild as they were, built by c_start/sakura +# r_start_s2 the same, its own fixed point +# c_now/sakura C as it is, and c_now/std its std +# r_now/ the rebuild's sources and std as they are, with `std::json` and +# `std::args`, packages since 2026-10-24, copied back into its std +# as `std/json` and `std/args`, since C can't take `--lib std::json` +# r_now_c the rebuild as it is, built by c_now/sakura +# r_now_s2 the same, its own fixed point +# +# Each group's commands are pinned to CPU (2 by default, or $CPU), but for `threads`, +# which lets the rebuild run its threads where it will. +import glob, json, os, statistics, subprocess, sys + +W = os.path.abspath(sys.argv[1]) +CPU = int(os.environ.get("CPU", "2")) + +def sources(root, dirs): + found = ["entry.sakura"] + for d in dirs: + found += sorted(os.path.relpath(f, root) for f in glob.glob(f"{root}/{d}/**/*.sakura", recursive=True)) + return found + +ST, NW = W + "/r_start", W + "/r_now" +SS = sources(ST, ["analyzer", "compiler", "machine", "native"]) +SN = sources(NW, ["analyzer", "compiler", "machine", "native", "server"]) +STDS, STDN = ST + "/std", NW + "/std" +CS, CN = W + "/c_start/sakura", W + "/c_now/sakura" +RS, RSC = W + "/r_start_s2", W + "/r_start_c" +RN, RNC = W + "/r_now_s2", W + "/r_now_c" +HS, HN, OUT = W + "/hello_start.sakura", W + "/hello_now.sakura", W + "/out.bin" +with open(HS, "w") as f: f.write("import std::io;\n\ndef main(): void { io::println(\"hi\"); }\n") +with open(HN, "w") as f: f.write("import std::io;\n\ndef main(): void { io::println(\"hi\"); }\n") + +groups = { + "hello": (21, [ + ("start C checks one line", W, [CS, "check", "--std", W + "/c_start/std", HS]), + ("start rebuild checks one line", W, [RS, "--std", STDS, HS]), + ("now C checks one line", W, [CN, "check", "--std", W + "/c_now/std", HN]), + ("now rebuild checks one line -j1", W, [RN, "check", "-j", "1", "--std", STDN, HN]), + ]), + "check": (9, [ + ("start C checks rebuild", ST, [CS, "check", "--std", STDS] + SS), + ("start rebuild checks itself", ST, [RS, "--std", STDS] + SS), + ("now C checks rebuild", NW, [CN, "check", "--std", STDN] + SN), + ("now rebuild checks itself -j1", NW, [RN, "check", "-j", "1", "--std", STDN] + SN), + ]), + "build": (5, [ + ("start C builds rebuild", ST, [CS, "build", "--std", STDS, "-O2", "-o", OUT] + SS), + ("start rebuild (self-built) builds itself", ST, [RS, "build", "--std", STDS, "-O2", "-o", OUT] + SS), + ("start rebuild (C-built) builds itself", ST, [RSC, "build", "--std", STDS, "-O2", "-o", OUT] + SS), + ("now C builds rebuild", NW, [CN, "build", "--std", STDN, "-O2", "-o", OUT] + SN), + ("now rebuild (self-built) builds itself -j1", NW, [RN, "build", "-j", "1", "--std", STDN, "-O2", "-o", OUT] + SN), + ("now rebuild (C-built) builds itself -j1", NW, [RNC, "build", "-j", "1", "--std", STDN, "-O2", "-o", OUT] + SN), + ]), + "vm": (3, [ + ("start C VM runs rebuild checking one line", ST, [CS, "run", "--std", STDS] + SS + ["--", "--std", STDS, HS]), + ("start rebuild VM runs itself checking one line", ST, [RS, "run", "--std", STDS] + SS + ["--", "--std", STDS, HS]), + ("now C VM runs rebuild checking one line", NW, [CN, "run", "--std", STDN] + SN + ["--", "check", "--std", STDN, HN]), + ("now rebuild VM runs itself checking one line -j1", NW, [RN, "run", "-j", "1", "--std", STDN] + SN + ["--", "check", "-j", "1", "--std", STDN, HN]), + ]), + "threads": (5, [ + ("now rebuild builds itself, default threads", NW, [RN, "build", "--std", STDN, "-O2", "-o", OUT] + SN), + ("now rebuild builds itself -j1 (unpinned)", NW, [RN, "build", "-j", "1", "--std", STDN, "-O2", "-o", OUT] + SN), + ("now rebuild checks itself, default threads", NW, [RN, "check", "--std", STDN] + SN), + ]), +} + +def once(cpu, cwd, argv): + run = subprocess.run([W + "/count", str(cpu)] + argv, cwd=cwd, stderr=subprocess.PIPE, text=True) + wall, rss, ins, cyc, status = run.stderr.strip().splitlines()[-1].split() + if status != "0": + print("FAILED", " ".join(argv[:3]), run.stderr[-400:], file=sys.stderr) + return float(wall), int(rss), int(ins), int(cyc) + +results = {} +for group in sys.argv[2:] or list(groups): + rounds, commands = groups[group] + cpu = -1 if group == "threads" else CPU + runs = {name: [] for name, _, _ in commands} + for _ in range(rounds): + for name, cwd, argv in commands: + runs[name].append(once(cpu, cwd, argv)) + for name, rs in runs.items(): + walls = [r[0] for r in rs] + results[name] = { + "best": min(walls), "median": statistics.median(walls), + "rss_mb": max(r[1] for r in rs) / 1024, + "instructions": statistics.median(r[2] for r in rs), + "cycles": statistics.median(r[3] for r in rs), "runs": rounds, + } + r = results[name] + print(f"{name:50s} best {r['best']:7.3f}s median {r['median']:7.3f}s " + f"rss {r['rss_mb']:6.1f}MB instr {r['instructions'] / 1e9:6.3f}G " + f"cycles {r['cycles'] / 1e9:6.3f}G", flush=True) +with open(W + "/results.json", "w") as f: json.dump(results, f, indent=1) +if os.path.exists(OUT): os.remove(OUT) diff --git a/tools/profile/sampler.c b/tools/profile/sampler.c new file mode 100644 index 00000000..a6244b26 --- /dev/null +++ b/tools/profile/sampler.c @@ -0,0 +1,69 @@ +// Samples a program's instruction pointer and its chain of return addresses with +// ptrace, which needs no kernel profiling support. +// +// cc -O2 -o sampler sampler.c +// sampler OUT INTERVAL_US PROGRAM ARGS... +// +// Writes one line per sample to OUT: the instruction pointer, then each return +// address the `rbp` chain gives, in hex. The program's output is discarded. +#define _GNU_SOURCE +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +int main(int argc, char **argv) { + FILE *out = fopen(argv[1], "w"); + long interval = atol(argv[2]); + pid_t pid = fork(); + if (pid == 0) { + int null = open("/dev/null", O_WRONLY); dup2(null, 1); + ptrace(PTRACE_TRACEME, 0, 0, 0); + raise(SIGSTOP); + execv(argv[3], argv + 3); + _exit(127); + } + int status; + waitpid(pid, &status, 0); + ptrace(PTRACE_SETOPTIONS, pid, 0, PTRACE_O_EXITKILL); + ptrace(PTRACE_CONT, pid, 0, 0); + // Wait for the exec stop. + waitpid(pid, &status, 0); + ptrace(PTRACE_CONT, pid, 0, 0); + long samples = 0; + for (;;) { + struct timespec ts = { 0, interval * 1000 }; + nanosleep(&ts, 0); + if (kill(pid, SIGSTOP) != 0) break; + if (waitpid(pid, &status, 0) < 0) break; + if (WIFEXITED(status) || WIFSIGNALED(status)) break; + int sig = WSTOPSIG(status); + if (sig != SIGSTOP) { ptrace(PTRACE_CONT, pid, 0, sig); continue; } + struct user_regs_struct r; + if (ptrace(PTRACE_GETREGS, pid, 0, &r) == 0) { + fprintf(out, "%llx", r.rip); + unsigned long bp = r.rbp; + for (int i = 0; i < 400 && bp; i++) { + errno = 0; + long ret = ptrace(PTRACE_PEEKDATA, pid, bp + 8, 0); + long next = ptrace(PTRACE_PEEKDATA, pid, bp, 0); + if (errno) break; + fprintf(out, " %lx", ret); + if ((unsigned long)next <= bp) break; + bp = next; + } + fputc('\n', out); + samples++; + } + ptrace(PTRACE_CONT, pid, 0, 0); + } + fclose(out); + fprintf(stderr, "%ld samples\n", samples); + return 0; +} diff --git a/tools/profile/samples.py b/tools/profile/samples.py new file mode 100644 index 00000000..1ddbf6a0 --- /dev/null +++ b/tools/profile/samples.py @@ -0,0 +1,87 @@ +# Reads the samples `sampler` wrote of an executable built with `sakura build -g`, +# and prints where the time went, with inlined code counted where it came from. +# +# python3 samples.py SAMPLES EXECUTABLE [MODE [COUNT [REGEX]]] [--profile PROFILE] +# +# MODE is one of: +# fn time by source function; with `--profile`, a callgrind profile of +# the same executable that costs.py has read, also its share of +# instructions and the ratio of the two, which is high where the +# code waits on memory, mispredicted branches, or the kernel +# incl time by every function on the stack +# line time by source line +# users REGEX time in functions matching REGEX by the first frame outside them +# and std that led there +import collections, os, pickle, re, sys +sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) +import inlined + +arguments = sys.argv[1:] +profile = None +if '--profile' in arguments: + at = arguments.index('--profile') + profile = arguments[at + 1] + del arguments[at:at + 2] +samples, executable = arguments[0], arguments[1] +mode = arguments[2] if len(arguments) > 2 else 'fn' +count = int(arguments[3]) if len(arguments) > 3 else 40 +target = arguments[4] if len(arguments) > 4 else None + +rows = [[int(x, 16) for x in line.split()] for line in open(samples) if line.strip()] +addresses = set() +for row in rows: + addresses.add(row[0]) + addresses.update(a - 1 for a in row[1:]) +found = inlined.chains(executable, addresses) +n = len(rows) or 1 + +def stack(row): + chain = list(inlined.frames(found, row[0])) + for a in row[1:]: + chain += found.get(a - 1) or [] + return chain + +result = collections.Counter() +if mode == 'fn': + for row in rows: + result[inlined.frames(found, row[0])[0][0]] += 1 + shares = collections.Counter() + if profile: + events, own, calls, counts, mapped = pickle.load(open(profile + '.pkl', 'rb')) + for address, cost in own.items(): + shares[inlined.frames(mapped, address)[0][0]] += cost[0] + whole = sum(shares.values()) or 1 + print(f'{len(rows)} samples time instr ratio function') + for function, c in result.most_common(count): + t, s = 100 * c / n, 100 * shares[function] / whole + print(f' {t:6.2f}% {s:6.2f}% {t / s if s else 0:5.2f} {function[:90]}') + else: + for function, c in result.most_common(count): + print(f'{100 * c / n:6.2f}% {function[:100]}') +elif mode == 'incl': + for row in rows: + for function in set(f for f, _ in stack(row)): + result[function] += 1 + for function, c in result.most_common(count): + print(f'{100 * c / n:6.2f}% {function[:100]}') +elif mode == 'line': + for row in rows: + result[inlined.frames(found, row[0])[0][1]] += 1 + for location, c in result.most_common(count): + print(f'{100 * c / n:6.2f}% {location[:100]}') +elif mode == 'users': + pattern = re.compile(target) + hits = 0 + for row in rows: + if not pattern.search(inlined.frames(found, row[0])[0][0]): + continue + hits += 1 + user = '?' + for function, location in stack(row): + if not pattern.search(function) and not location.startswith('std/'): + user = function + ' @ ' + location + break + result[user] += 1 + print(f'== {100 * hits / n:.2f}% of the time in /{target}/, by the code using it') + for user, c in result.most_common(count): + print(f'{100 * c / n:6.2f}% {user[:110]}')