From 658289861e8d971cd9e449e66a749c9c2d65f623 Mon Sep 17 00:00:00 2001 From: Cliff Click Date: Mon, 10 Aug 2026 11:11:18 -0700 Subject: Chapter 31: Software Drawing, Time, and Graphical Games Co-authored-by: Hsiang-Ying Fu <66062782+fuhsnn@users.noreply.github.com> Co-authored-by: fuhsnn <66062782+fuhsnn@users.noreply.github.com> Co-authored-by: Symious <14933944+symious@users.noreply.github.com> Co-authored-by: Jun Kawasaki Co-authored-by: Claude Opus 5 --- .argsT.txt | 1 - .out.txt | 304 ----------------- Makefile | 26 +- README.ja.md | 2 +- README.md | 2 +- audio.mk | 31 ++ chapter30.iml | 31 -- chapter31.iml | 31 ++ docs/chapter31/31-grammar.ja.md | 182 ++++++++++ docs/chapter31/31-grammar.md | 273 +++++++++++++++ docs/chapter31/README.ja.md | 25 ++ docs/chapter31/README.md | 293 ++++++++++++++++ docs/chapter31/examples/A_helloWorld.smp | 2 + docs/chapter31/examples/Breakout.smp | 369 +++++++++++++++++++++ docs/chapter31/examples/BubbleSort.smp | 38 +++ docs/chapter31/examples/Capitalize.smp | 23 ++ docs/chapter31/examples/Clock.smp | 128 +++++++ docs/chapter31/examples/Dijkstra.smp | 71 ++++ docs/chapter31/examples/FileIO.smp | 52 +++ docs/chapter31/examples/Graphics.smp | 26 ++ docs/chapter31/examples/README.md | 119 +++++++ docs/chapter31/examples/TicTacToe.smp | 132 ++++++++ docs/chapter31/examples/TicTacToeGraphical.smp | 169 ++++++++++ graphics.mk | 78 +++++ src/main/c/simple_audio.c | 40 +++ src/main/c/simple_audio.h | 16 + src/main/c/simple_crt.c | 23 ++ src/main/c/simple_graphics.c | 108 ++++++ src/main/c/simple_graphics.h | 23 ++ src/main/c/simple_miniaudio.c | 123 +++++++ src/main/c/simple_minifb.c | 144 ++++++++ src/main/c/simple_time.c | 61 ++++ src/main/java/com/seaofnodes/simple/README.md | 2 +- .../com/seaofnodes/simple/codegen/CodeGen.java | 6 +- .../com/seaofnodes/simple/codegen/ElfWriter.java | 15 +- .../com/seaofnodes/simple/codegen/Encoding.java | 10 +- .../simple/codegen/GlobalCodeMotion.java | 10 +- .../com/seaofnodes/simple/codegen/IterPeeps.java | 4 +- .../seaofnodes/simple/codegen/ListScheduler.java | 2 +- .../com/seaofnodes/simple/codegen/ParseAll.java | 5 +- .../com/seaofnodes/simple/codegen/RegAlloc.java | 14 +- .../com/seaofnodes/simple/codegen/Serialize.java | 16 +- .../com/seaofnodes/simple/codegen/StaticData.java | 10 +- .../com/seaofnodes/simple/codegen/TypeCheck.java | 6 +- .../com/seaofnodes/simple/node/ArrayInitNode.java | 70 ++++ .../com/seaofnodes/simple/node/BulkMemPhiNode.java | 24 +- .../com/seaofnodes/simple/node/CallEndNode.java | 4 + .../java/com/seaofnodes/simple/node/CallNode.java | 12 + .../com/seaofnodes/simple/node/EscapeNode.java | 6 + .../java/com/seaofnodes/simple/node/Intrinsic.java | 119 +++++++ .../java/com/seaofnodes/simple/node/LoadNode.java | 26 +- .../com/seaofnodes/simple/node/MemMergeNode.java | 16 +- .../java/com/seaofnodes/simple/node/MemOpNode.java | 3 +- .../java/com/seaofnodes/simple/node/ModFNode.java | 49 +++ .../java/com/seaofnodes/simple/node/ModNode.java | 16 + src/main/java/com/seaofnodes/simple/node/Node.java | 5 +- .../java/com/seaofnodes/simple/node/StoreNode.java | 4 + .../simple/node/cpus/arm/BitCastARM.java | 23 ++ .../seaofnodes/simple/node/cpus/arm/ModARM.java | 29 ++ .../com/seaofnodes/simple/node/cpus/arm/arm.java | 4 +- .../simple/node/cpus/riscv/BitCastRISC.java | 23 ++ .../seaofnodes/simple/node/cpus/riscv/DivRISC.java | 17 +- .../simple/node/cpus/riscv/SplitRISC.java | 2 +- .../seaofnodes/simple/node/cpus/riscv/riscv.java | 2 + .../simple/node/cpus/x86_64_v2/BitCastX86.java | 23 ++ .../simple/node/cpus/x86_64_v2/CmpX86.java | 7 + .../simple/node/cpus/x86_64_v2/DivX86.java | 36 +- .../simple/node/cpus/x86_64_v2/JmpX86.java | 27 +- .../simple/node/cpus/x86_64_v2/MemOpX86.java | 6 +- .../simple/node/cpus/x86_64_v2/NegFX86.java | 25 ++ .../simple/node/cpus/x86_64_v2/NegX86.java | 2 +- .../simple/node/cpus/x86_64_v2/NotX86.java | 2 +- .../simple/node/cpus/x86_64_v2/SetX86.java | 18 +- .../simple/node/cpus/x86_64_v2/StoreX86.java | 3 + .../simple/node/cpus/x86_64_v2/x86_64_v2.java | 51 ++- .../com/seaofnodes/simple/parser/Allocations.java | 17 +- .../simple/parser/ArrayInitializers.java | 187 +++++++++++ .../com/seaofnodes/simple/parser/Conversions.java | 2 +- .../com/seaofnodes/simple/parser/Declarations.java | 4 + .../com/seaofnodes/simple/parser/Expressions.java | 6 +- .../com/seaofnodes/simple/parser/Functions.java | 64 +++- .../java/com/seaofnodes/simple/parser/Lexer.java | 39 ++- .../com/seaofnodes/simple/parser/MethodAccess.java | 130 ++++++++ .../java/com/seaofnodes/simple/parser/Parser.java | 12 +- .../java/com/seaofnodes/simple/parser/README.md | 15 +- .../com/seaofnodes/simple/parser/References.java | 13 +- .../com/seaofnodes/simple/parser/Statements.java | 1 + .../java/com/seaofnodes/simple/parser/Strings.java | 2 +- .../java/com/seaofnodes/simple/parser/Types.java | 11 +- .../java/com/seaofnodes/simple/parser/Var.java | 5 + .../com/seaofnodes/simple/parser/package-info.java | 2 +- .../com/seaofnodes/simple/print/ASMPrinter.java | 15 +- src/main/java/com/seaofnodes/simple/type/Type.java | 2 +- .../com/seaofnodes/simple/type/TypeConAry.java | 147 +++++--- .../com/seaofnodes/simple/type/TypeConAryB.java | 20 -- .../com/seaofnodes/simple/type/TypeConAryI.java | 16 - .../java/com/seaofnodes/simple/type/TypeFloat.java | 8 +- .../java/com/seaofnodes/simple/type/TypeMem.java | 9 +- .../com/seaofnodes/simple/type/TypeStruct.java | 11 +- src/main/smp/sys.smp | 6 + src/main/smp/sys/adt/bitset.smp | 4 +- src/main/smp/sys/ary.smp | 8 +- src/main/smp/sys/aryi64.smp | 6 +- src/main/smp/sys/aryu8.smp | 13 +- src/main/smp/sys/audio.md | 84 +++++ src/main/smp/sys/audio.smp | 30 ++ src/main/smp/sys/draw.smp | 19 ++ src/main/smp/sys/draw/Button.smp | 41 +++ src/main/smp/sys/draw/Canvas.smp | 201 +++++++++++ src/main/smp/sys/draw/README.md | 124 +++++++ src/main/smp/sys/gfx.md | 154 +++++++++ src/main/smp/sys/gfx.smp | 61 ++++ src/main/smp/sys/integer.smp | 6 + src/main/smp/sys/io.smp | 2 +- src/main/smp/sys/libc.smp | 8 +- src/main/smp/sys/math.smp | 27 ++ src/main/smp/sys/rt/simple_args.smp | 8 +- src/main/smp/sys/text.smp | 84 ++--- src/main/smp/sys/time.smp | 219 ++++++++++++ src/main/smp/sys/time/DateTime.smp | 13 + src/main/smp/sys/time/README.md | 133 ++++++++ src/main/smp/sys/time/Timers.smp | 80 +++++ src/test/c/audio_test.c | 48 +++ .../java/com/seaofnodes/simple/ArithNodeTest.java | 3 +- .../java/com/seaofnodes/simple/ArrayInitTest.java | 211 ++++++++++++ .../com/seaofnodes/simple/AssemblyDumpTest.java | 61 ++++ src/test/java/com/seaofnodes/simple/AudioTest.java | 94 ++++++ .../java/com/seaofnodes/simple/BrainFuckTest.java | 8 +- .../java/com/seaofnodes/simple/BreakoutTest.java | 216 ++++++++++++ .../java/com/seaofnodes/simple/BulkMemPhiTest.java | 25 ++ .../java/com/seaofnodes/simple/Chapter01Test.java | 9 +- .../java/com/seaofnodes/simple/Chapter17bTest.java | 4 +- .../java/com/seaofnodes/simple/Chapter21Test.java | 4 +- .../java/com/seaofnodes/simple/Chapter22Test.java | 4 +- .../java/com/seaofnodes/simple/Chapter23Test.java | 5 +- .../java/com/seaofnodes/simple/Chapter25Test.java | 4 +- .../com/seaofnodes/simple/ConstantArrayTest.java | 123 +++++++ .../com/seaofnodes/simple/ConvertNodeTest.java | 2 +- src/test/java/com/seaofnodes/simple/DrawTest.java | 250 ++++++++++++++ .../java/com/seaofnodes/simple/EscapeFlowTest.java | 31 ++ src/test/java/com/seaofnodes/simple/Eval2.java | 28 +- .../simple/FloatComparisonNativeTest.java | 65 ++++ .../seaofnodes/simple/FloatNegationNativeTest.java | 21 ++ .../java/com/seaofnodes/simple/GraphicsTest.java | 248 ++++++++++++++ .../com/seaofnodes/simple/IntegerLiteralTest.java | 46 +++ .../java/com/seaofnodes/simple/IntrinsicTest.java | 188 +++++++++++ src/test/java/com/seaofnodes/simple/MathTest.java | 79 +++++ .../com/seaofnodes/simple/MemoryEncodingTest.java | 25 ++ .../com/seaofnodes/simple/MethodAccessTest.java | 118 +++++++ .../com/seaofnodes/simple/MethodFieldsTest.java | 131 ++++++++ src/test/java/com/seaofnodes/simple/ModTest.java | 201 +++++++++++ .../seaofnodes/simple/ParserDiagnosticTest.java | 82 ++++- .../java/com/seaofnodes/simple/SchedulingTest.java | 47 +++ .../seaofnodes/simple/SeparateCompilationTest.java | 16 + .../java/com/seaofnodes/simple/StreamIOTest.java | 6 +- .../com/seaofnodes/simple/StringFormatTest.java | 9 + src/test/java/com/seaofnodes/simple/TestC.java | 7 +- src/test/java/com/seaofnodes/simple/TimeTest.java | 183 ++++++++++ src/test/java/com/seaofnodes/simple/TypeTest.java | 20 ++ .../simple/codegen/PrintRegTestSupport.java | 26 +- 160 files changed, 7782 insertions(+), 635 deletions(-) delete mode 100644 .argsT.txt delete mode 100644 .out.txt create mode 100644 audio.mk delete mode 100644 chapter30.iml create mode 100644 chapter31.iml create mode 100644 docs/chapter31/31-grammar.ja.md create mode 100644 docs/chapter31/31-grammar.md create mode 100644 docs/chapter31/README.ja.md create mode 100644 docs/chapter31/README.md create mode 100644 docs/chapter31/examples/A_helloWorld.smp create mode 100644 docs/chapter31/examples/Breakout.smp create mode 100644 docs/chapter31/examples/BubbleSort.smp create mode 100644 docs/chapter31/examples/Capitalize.smp create mode 100644 docs/chapter31/examples/Clock.smp create mode 100644 docs/chapter31/examples/Dijkstra.smp create mode 100644 docs/chapter31/examples/FileIO.smp create mode 100644 docs/chapter31/examples/Graphics.smp create mode 100644 docs/chapter31/examples/README.md create mode 100644 docs/chapter31/examples/TicTacToe.smp create mode 100644 docs/chapter31/examples/TicTacToeGraphical.smp create mode 100644 graphics.mk create mode 100644 src/main/c/simple_audio.c create mode 100644 src/main/c/simple_audio.h create mode 100644 src/main/c/simple_graphics.c create mode 100644 src/main/c/simple_graphics.h create mode 100644 src/main/c/simple_miniaudio.c create mode 100644 src/main/c/simple_minifb.c create mode 100644 src/main/c/simple_time.c create mode 100644 src/main/java/com/seaofnodes/simple/node/ArrayInitNode.java create mode 100644 src/main/java/com/seaofnodes/simple/node/Intrinsic.java create mode 100644 src/main/java/com/seaofnodes/simple/node/ModFNode.java create mode 100644 src/main/java/com/seaofnodes/simple/node/ModNode.java create mode 100644 src/main/java/com/seaofnodes/simple/node/cpus/arm/BitCastARM.java create mode 100644 src/main/java/com/seaofnodes/simple/node/cpus/arm/ModARM.java create mode 100644 src/main/java/com/seaofnodes/simple/node/cpus/riscv/BitCastRISC.java create mode 100644 src/main/java/com/seaofnodes/simple/node/cpus/x86_64_v2/BitCastX86.java create mode 100644 src/main/java/com/seaofnodes/simple/node/cpus/x86_64_v2/NegFX86.java create mode 100644 src/main/java/com/seaofnodes/simple/parser/ArrayInitializers.java create mode 100644 src/main/java/com/seaofnodes/simple/parser/MethodAccess.java delete mode 100644 src/main/java/com/seaofnodes/simple/type/TypeConAryB.java delete mode 100644 src/main/java/com/seaofnodes/simple/type/TypeConAryI.java create mode 100644 src/main/smp/sys/audio.md create mode 100644 src/main/smp/sys/audio.smp create mode 100644 src/main/smp/sys/draw.smp create mode 100644 src/main/smp/sys/draw/Button.smp create mode 100644 src/main/smp/sys/draw/Canvas.smp create mode 100644 src/main/smp/sys/draw/README.md create mode 100644 src/main/smp/sys/gfx.md create mode 100644 src/main/smp/sys/gfx.smp create mode 100644 src/main/smp/sys/integer.smp create mode 100644 src/main/smp/sys/math.smp create mode 100644 src/main/smp/sys/time.smp create mode 100644 src/main/smp/sys/time/DateTime.smp create mode 100644 src/main/smp/sys/time/README.md create mode 100644 src/main/smp/sys/time/Timers.smp create mode 100644 src/test/c/audio_test.c create mode 100644 src/test/java/com/seaofnodes/simple/ArrayInitTest.java create mode 100644 src/test/java/com/seaofnodes/simple/AssemblyDumpTest.java create mode 100644 src/test/java/com/seaofnodes/simple/AudioTest.java create mode 100644 src/test/java/com/seaofnodes/simple/BreakoutTest.java create mode 100644 src/test/java/com/seaofnodes/simple/ConstantArrayTest.java create mode 100644 src/test/java/com/seaofnodes/simple/DrawTest.java create mode 100644 src/test/java/com/seaofnodes/simple/FloatComparisonNativeTest.java create mode 100644 src/test/java/com/seaofnodes/simple/FloatNegationNativeTest.java create mode 100644 src/test/java/com/seaofnodes/simple/GraphicsTest.java create mode 100644 src/test/java/com/seaofnodes/simple/IntegerLiteralTest.java create mode 100644 src/test/java/com/seaofnodes/simple/IntrinsicTest.java create mode 100644 src/test/java/com/seaofnodes/simple/MathTest.java create mode 100644 src/test/java/com/seaofnodes/simple/MethodAccessTest.java create mode 100644 src/test/java/com/seaofnodes/simple/MethodFieldsTest.java create mode 100644 src/test/java/com/seaofnodes/simple/ModTest.java create mode 100644 src/test/java/com/seaofnodes/simple/SchedulingTest.java create mode 100644 src/test/java/com/seaofnodes/simple/TimeTest.java diff --git a/.argsT.txt b/.argsT.txt deleted file mode 100644 index 827ddba7..00000000 --- a/.argsT.txt +++ /dev/null @@ -1 +0,0 @@ - src/test/java/com/seaofnodes/simple/Chapter09Test.java src/test/java/com/seaofnodes/simple/ParserTest.java src/test/java/com/seaofnodes/simple/Chapter16Test.java src/test/java/com/seaofnodes/simple/TicTacToeTest.java src/test/java/com/seaofnodes/simple/ConstructionGroupTest.java src/test/java/com/seaofnodes/simple/Chapter23Test.java src/test/java/com/seaofnodes/simple/NativeExecutionTest.java src/test/java/com/seaofnodes/simple/Chapter14Test.java src/test/java/com/seaofnodes/simple/ArithNodeTest.java src/test/java/com/seaofnodes/simple/CompoundAssignmentTest.java src/test/java/com/seaofnodes/simple/Chapter14FloatTest.java src/test/java/com/seaofnodes/simple/Chapter10Test.java src/test/java/com/seaofnodes/simple/BulkMemPhiTest.java src/test/java/com/seaofnodes/simple/MemoryEncodingTest.java src/test/java/com/seaofnodes/simple/ConstructionRequirementsTest.java src/test/java/com/seaofnodes/simple/Chapter13Test.java src/test/java/com/seaofnodes/simple/Chapter06Test.java src/test/java/com/seaofnodes/simple/TestRunner.java src/test/java/com/seaofnodes/simple/Chapter03Test.java src/test/java/com/seaofnodes/simple/FuzzerWrap.java src/test/java/com/seaofnodes/simple/EscapeFlowTest.java src/test/java/com/seaofnodes/simple/Int32Test.java src/test/java/com/seaofnodes/simple/Chapter24Test.java src/test/java/com/seaofnodes/simple/TerminalInputTest.java src/test/java/com/seaofnodes/simple/ConstructorCompletionTest.java src/test/java/com/seaofnodes/simple/RuntimeArgsTest.java src/test/java/com/seaofnodes/simple/Chapter04Test.java src/test/java/com/seaofnodes/simple/ChainedComparisonTest.java src/test/java/com/seaofnodes/simple/SeparateCompilationTest.java src/test/java/com/seaofnodes/simple/MutabilityTest.java src/test/java/com/seaofnodes/simple/FinalConstructionTest.java src/test/java/com/seaofnodes/simple/Chapter28bTest.java src/test/java/com/seaofnodes/simple/Chapter21Test.java src/test/java/com/seaofnodes/simple/Chapter07Test.java src/test/java/com/seaofnodes/simple/BrainFuckTest.java src/test/java/com/seaofnodes/simple/Chapter05Test.java src/test/java/com/seaofnodes/simple/PhaseTest.java src/test/java/com/seaofnodes/simple/Eval2.java src/test/java/com/seaofnodes/simple/TestArm64.java src/test/java/com/seaofnodes/simple/Chapter12Test.java src/test/java/com/seaofnodes/simple/StringFormatTest.java src/test/java/com/seaofnodes/simple/TestC.java src/test/java/com/seaofnodes/simple/IncrementalBuildTest.java src/test/java/com/seaofnodes/simple/Simple.java src/test/java/com/seaofnodes/simple/SelectiveLoadingTest.java src/test/java/com/seaofnodes/simple/Chapter02Test.java src/test/java/com/seaofnodes/simple/Chapter15Test.java src/test/java/com/seaofnodes/simple/BoundaryTest.java src/test/java/com/seaofnodes/simple/Chapter25Test.java src/test/java/com/seaofnodes/simple/Chapter22Test.java src/test/java/com/seaofnodes/simple/PartialReadTest.java src/test/java/com/seaofnodes/simple/MergeSortTest.java src/test/java/com/seaofnodes/simple/SpillStats.java src/test/java/com/seaofnodes/simple/Chapter17bTest.java src/test/java/com/seaofnodes/simple/CallEndTest.java src/test/java/com/seaofnodes/simple/Chapter01Test.java src/test/java/com/seaofnodes/simple/MinusNodeTest.java src/test/java/com/seaofnodes/simple/Chapter18Test.java src/test/java/com/seaofnodes/simple/TypeTest.java src/test/java/com/seaofnodes/simple/StaticDataTest.java src/test/java/com/seaofnodes/simple/TestRisc5.java src/test/java/com/seaofnodes/simple/ClassInitDependenciesTest.java src/test/java/com/seaofnodes/simple/ConvertNodeTest.java src/test/java/com/seaofnodes/simple/Chapter08Test.java src/test/java/com/seaofnodes/simple/Chapter17aTest.java src/test/java/com/seaofnodes/simple/Chapter19Test.java src/test/java/com/seaofnodes/simple/ParserDiagnosticTest.java src/test/java/com/seaofnodes/simple/PrefixUpdateTest.java src/test/java/com/seaofnodes/simple/Chapter20Test.java src/test/java/com/seaofnodes/simple/Main.java src/test/java/com/seaofnodes/simple/StreamIOTest.java src/test/java/com/seaofnodes/simple/codegen/ParseAllTestSupport.java src/test/java/com/seaofnodes/simple/codegen/PrintRegTestSupport.java src/test/java/com/seaofnodes/simple/codegen/FlagSpillTestSupport.java src/test/java/com/seaofnodes/simple/codegen/RegAllocTestSupport.java src/test/java/com/seaofnodes/simple/fuzzer/Reducer.java src/test/java/com/seaofnodes/simple/fuzzer/ScriptGenerator.java src/test/java/com/seaofnodes/simple/fuzzer/FuzzerUtils.java src/test/java/com/seaofnodes/simple/fuzzer/Fuzzer.java ../isa/src/test-support/java/com/seaofnodes/isa/eval/EvalArm64.java ../isa/src/test-support/java/com/seaofnodes/isa/eval/EvalRisc5.java diff --git a/.out.txt b/.out.txt deleted file mode 100644 index be785578..00000000 --- a/.out.txt +++ /dev/null @@ -1,304 +0,0 @@ -src\test\java\com\seaofnodes\simple\Chapter09Test.java:6: error: package org.junit does not exist -import org.junit.Assert; - ^ -src\test\java\com\seaofnodes\simple\Chapter09Test.java:7: error: package org.junit does not exist -import org.junit.Test; - ^ -src\test\java\com\seaofnodes\simple\Chapter09Test.java:8: error: package org.junit does not exist -import org.junit.Ignore; - ^ -src\test\java\com\seaofnodes\simple\Chapter09Test.java:10: error: package org.junit does not exist -import static org.junit.Assert.*; - ^ -src\test\java\com\seaofnodes\simple\ParserTest.java:5: error: package org.junit does not exist -import org.junit.Test; - ^ -src\test\java\com\seaofnodes\simple\ParserTest.java:6: error: package org.junit does not exist -import static org.junit.Assert.*; - ^ -src\test\java\com\seaofnodes\simple\Chapter16Test.java:4: error: package org.junit does not exist -import org.junit.Ignore; - ^ -src\test\java\com\seaofnodes\simple\Chapter16Test.java:5: error: package org.junit does not exist -import org.junit.Test; - ^ -src\test\java\com\seaofnodes\simple\Chapter16Test.java:6: error: package org.junit does not exist -import static org.junit.Assert.assertEquals; - ^ -src\test\java\com\seaofnodes\simple\Chapter16Test.java:6: error: static import only from classes and interfaces -import static org.junit.Assert.assertEquals; -^ -src\test\java\com\seaofnodes\simple\Chapter16Test.java:7: error: package org.junit does not exist -import static org.junit.Assert.fail; - ^ -src\test\java\com\seaofnodes\simple\Chapter16Test.java:7: error: static import only from classes and interfaces -import static org.junit.Assert.fail; -^ -src\test\java\com\seaofnodes\simple\TicTacToeTest.java:8: error: package org.junit does not exist -import org.junit.BeforeClass; - ^ -src\test\java\com\seaofnodes\simple\TicTacToeTest.java:9: error: package org.junit does not exist -import org.junit.Test; - ^ -src\test\java\com\seaofnodes\simple\TicTacToeTest.java:10: error: package org.junit does not exist -import static org.junit.Assert.*; - ^ -src\test\java\com\seaofnodes\simple\ConstructionGroupTest.java:5: error: package org.junit does not exist -import org.junit.Test; - ^ -src\test\java\com\seaofnodes\simple\ConstructionGroupTest.java:6: error: package org.junit does not exist -import static org.junit.Assert.*; - ^ -src\test\java\com\seaofnodes\simple\codegen\RegAllocTestSupport.java:7: error: package org.junit does not exist -import static org.junit.Assert.*; - ^ -src\test\java\com\seaofnodes\simple\Chapter23Test.java:17: error: package org.junit does not exist -import org.junit.Ignore; - ^ -src\test\java\com\seaofnodes\simple\Chapter23Test.java:18: error: package org.junit does not exist -import org.junit.Test; - ^ -src\test\java\com\seaofnodes\simple\Chapter23Test.java:19: error: package org.junit does not exist -import static org.junit.Assert.*; - ^ -src\test\java\com\seaofnodes\simple\NativeExecutionTest.java:6: error: package org.junit does not exist -import org.junit.Test; - ^ -src\test\java\com\seaofnodes\simple\NativeExecutionTest.java:7: error: package org.junit does not exist -import static org.junit.Assert.*; - ^ -src\test\java\com\seaofnodes\simple\NativeExecutionTest.java:8: error: package org.junit does not exist -import static org.junit.Assume.assumeTrue; - ^ -src\test\java\com\seaofnodes\simple\NativeExecutionTest.java:8: error: static import only from classes and interfaces -import static org.junit.Assume.assumeTrue; -^ -src\test\java\com\seaofnodes\simple\Chapter14Test.java:5: error: package org.junit does not exist -import org.junit.Ignore; - ^ -src\test\java\com\seaofnodes\simple\Chapter14Test.java:6: error: package org.junit does not exist -import org.junit.Test; - ^ -src\test\java\com\seaofnodes\simple\Chapter14Test.java:7: error: package org.junit does not exist -import static org.junit.Assert.assertEquals; - ^ -src\test\java\com\seaofnodes\simple\Chapter14Test.java:7: error: static import only from classes and interfaces -import static org.junit.Assert.assertEquals; -^ -src\test\java\com\seaofnodes\simple\Chapter14Test.java:8: error: package org.junit does not exist -import static org.junit.Assert.fail; - ^ -src\test\java\com\seaofnodes\simple\Chapter14Test.java:8: error: static import only from classes and interfaces -import static org.junit.Assert.fail; -^ -src\test\java\com\seaofnodes\simple\ArithNodeTest.java:8: error: package org.junit does not exist -import org.junit.Test; - ^ -src\test\java\com\seaofnodes\simple\ArithNodeTest.java:9: error: package org.junit does not exist -import static org.junit.Assert.*; - ^ -src\test\java\com\seaofnodes\simple\CompoundAssignmentTest.java:5: error: package org.junit does not exist -import org.junit.Test; - ^ -src\test\java\com\seaofnodes\simple\CompoundAssignmentTest.java:6: error: package org.junit does not exist -import static org.junit.Assert.*; - ^ -src\test\java\com\seaofnodes\simple\Chapter14FloatTest.java:4: error: package org.junit does not exist -import org.junit.Ignore; - ^ -src\test\java\com\seaofnodes\simple\Chapter14FloatTest.java:5: error: package org.junit does not exist -import org.junit.Test; - ^ -src\test\java\com\seaofnodes\simple\Chapter14FloatTest.java:6: error: package org.junit does not exist -import static org.junit.Assert.assertEquals; - ^ -src\test\java\com\seaofnodes\simple\Chapter14FloatTest.java:6: error: static import only from classes and interfaces -import static org.junit.Assert.assertEquals; -^ -src\test\java\com\seaofnodes\simple\Chapter10Test.java:5: error: package org.junit does not exist -import org.junit.Test; - ^ -src\test\java\com\seaofnodes\simple\Chapter10Test.java:6: error: package org.junit does not exist -import static org.junit.Assert.assertEquals; - ^ -src\test\java\com\seaofnodes\simple\Chapter10Test.java:6: error: static import only from classes and interfaces -import static org.junit.Assert.assertEquals; -^ -src\test\java\com\seaofnodes\simple\Chapter10Test.java:7: error: package org.junit does not exist -import static org.junit.Assert.fail; - ^ -src\test\java\com\seaofnodes\simple\Chapter10Test.java:7: error: static import only from classes and interfaces -import static org.junit.Assert.fail; -^ -src\test\java\com\seaofnodes\simple\BulkMemPhiTest.java:7: error: package org.junit does not exist -import org.junit.Test; - ^ -src\test\java\com\seaofnodes\simple\BulkMemPhiTest.java:8: error: package org.junit does not exist -import static org.junit.Assert.*; - ^ -src\test\java\com\seaofnodes\simple\MemoryEncodingTest.java:6: error: package org.junit does not exist -import org.junit.Test; - ^ -src\test\java\com\seaofnodes\simple\MemoryEncodingTest.java:7: error: package org.junit does not exist -import static org.junit.Assert.*; - ^ -src\test\java\com\seaofnodes\simple\ConstructionRequirementsTest.java:5: error: package org.junit does not exist -import org.junit.Test; - ^ -src\test\java\com\seaofnodes\simple\ConstructionRequirementsTest.java:6: error: package org.junit does not exist -import static org.junit.Assert.*; - ^ -src\test\java\com\seaofnodes\simple\ConstructionRequirementsTest.java:8: error: package org.junit does not exist -@org.junit.Ignore("Deferred: inferred field requirements and incomplete-object traversal") - ^ -src\test\java\com\seaofnodes\simple\Chapter13Test.java:5: error: package org.junit does not exist -import org.junit.Test; - ^ -src\test\java\com\seaofnodes\simple\Chapter13Test.java:6: error: package org.junit does not exist -import static org.junit.Assert.assertEquals; - ^ -src\test\java\com\seaofnodes\simple\Chapter13Test.java:6: error: static import only from classes and interfaces -import static org.junit.Assert.assertEquals; -^ -src\test\java\com\seaofnodes\simple\Chapter06Test.java:6: error: package org.junit does not exist -import org.junit.Test; - ^ -src\test\java\com\seaofnodes\simple\Chapter06Test.java:8: error: package org.junit does not exist -import static org.junit.Assert.*; - ^ -src\test\java\com\seaofnodes\simple\TestRunner.java:3: error: package org.junit.internal does not exist -import org.junit.internal.TextListener; - ^ -src\test\java\com\seaofnodes\simple\TestRunner.java:4: error: package org.junit.runner does not exist -import org.junit.runner.JUnitCore; - ^ -src\test\java\com\seaofnodes\simple\TestRunner.java:5: error: package org.junit.runner does not exist -import org.junit.runner.Request; - ^ -src\test\java\com\seaofnodes\simple\Chapter03Test.java:4: error: package org.junit does not exist -import org.junit.Test; - ^ -src\test\java\com\seaofnodes\simple\Chapter03Test.java:5: error: package org.junit does not exist -import static org.junit.Assert.*; - ^ -src\test\java\com\seaofnodes\simple\FuzzerWrap.java:5: error: package org.junit does not exist -import org.junit.Ignore; - ^ -src\test\java\com\seaofnodes\simple\FuzzerWrap.java:6: error: package org.junit does not exist -import org.junit.Test; - ^ -src\test\java\com\seaofnodes\simple\FuzzerWrap.java:7: error: package org.junit does not exist -import static org.junit.Assert.assertTrue; - ^ -src\test\java\com\seaofnodes\simple\FuzzerWrap.java:7: error: static import only from classes and interfaces -import static org.junit.Assert.assertTrue; -^ -src\test\java\com\seaofnodes\simple\EscapeFlowTest.java:6: error: package org.junit does not exist -import org.junit.Test; - ^ -src\test\java\com\seaofnodes\simple\EscapeFlowTest.java:7: error: package org.junit does not exist -import static org.junit.Assert.*; - ^ -src\test\java\com\seaofnodes\simple\Int32Test.java:10: error: package org.junit does not exist -import org.junit.Test; - ^ -src\test\java\com\seaofnodes\simple\Int32Test.java:11: error: package org.junit does not exist -import static org.junit.Assert.*; - ^ -src\test\java\com\seaofnodes\simple\Chapter24Test.java:15: error: package org.junit does not exist -import org.junit.Ignore; - ^ -src\test\java\com\seaofnodes\simple\Chapter24Test.java:16: error: package org.junit does not exist -import org.junit.Test; - ^ -src\test\java\com\seaofnodes\simple\Chapter24Test.java:17: error: package org.junit does not exist -import static org.junit.Assert.*; - ^ -src\test\java\com\seaofnodes\simple\TerminalInputTest.java:12: error: package org.junit does not exist -import org.junit.Test; - ^ -src\test\java\com\seaofnodes\simple\TerminalInputTest.java:13: error: package org.junit does not exist -import static org.junit.Assert.*; - ^ -src\test\java\com\seaofnodes\simple\ConstructorCompletionTest.java:5: error: package org.junit does not exist -import org.junit.Test; - ^ -src\test\java\com\seaofnodes\simple\ConstructorCompletionTest.java:6: error: package org.junit does not exist -import static org.junit.Assert.*; - ^ -src\test\java\com\seaofnodes\simple\RuntimeArgsTest.java:4: error: package org.junit does not exist -import org.junit.Test; - ^ -src\test\java\com\seaofnodes\simple\RuntimeArgsTest.java:5: error: package org.junit does not exist -import static org.junit.Assert.*; - ^ -src\test\java\com\seaofnodes\simple\TestC.java:21: error: package org.junit does not exist -import static org.junit.Assert.*; - ^ -src\test\java\com\seaofnodes\simple\Chapter04Test.java:6: error: package org.junit does not exist -import org.junit.Test; - ^ -src\test\java\com\seaofnodes\simple\Chapter04Test.java:7: error: package org.junit does not exist -import org.junit.Ignore; - ^ -src\test\java\com\seaofnodes\simple\Chapter04Test.java:9: error: package org.junit does not exist -import static org.junit.Assert.*; - ^ -src\test\java\com\seaofnodes\simple\ChainedComparisonTest.java:5: error: package org.junit does not exist -import org.junit.Test; - ^ -src\test\java\com\seaofnodes\simple\ChainedComparisonTest.java:6: error: package org.junit does not exist -import static org.junit.Assert.*; - ^ -src\test\java\com\seaofnodes\simple\SeparateCompilationTest.java:9: error: package org.junit does not exist -import org.junit.Test; - ^ -src\test\java\com\seaofnodes\simple\SeparateCompilationTest.java:10: error: package org.junit does not exist -import static org.junit.Assert.*; - ^ -src\test\java\com\seaofnodes\simple\MutabilityTest.java:3: error: package org.junit does not exist -import org.junit.Test; - ^ -src\test\java\com\seaofnodes\simple\MutabilityTest.java:4: error: package org.junit does not exist -import static org.junit.Assert.*; - ^ -src\test\java\com\seaofnodes\simple\FinalConstructionTest.java:5: error: package org.junit does not exist -import org.junit.Test; - ^ -src\test\java\com\seaofnodes\simple\FinalConstructionTest.java:6: error: package org.junit does not exist -import static org.junit.Assert.*; - ^ -src\test\java\com\seaofnodes\simple\Chapter28bTest.java:4: error: package org.junit does not exist -import org.junit.Ignore; - ^ -src\test\java\com\seaofnodes\simple\Chapter28bTest.java:5: error: package org.junit does not exist -import org.junit.Test; - ^ -src\test\java\com\seaofnodes\simple\Chapter28bTest.java:7: error: package org.junit does not exist -import static org.junit.Assert.*; - ^ -src\test\java\com\seaofnodes\simple\Chapter21Test.java:13: error: package org.junit does not exist -import org.junit.Ignore; - ^ -src\test\java\com\seaofnodes\simple\Chapter21Test.java:14: error: package org.junit does not exist -import org.junit.Test; - ^ -src\test\java\com\seaofnodes\simple\Chapter21Test.java:15: error: package org.junit does not exist -import static org.junit.Assert.*; - ^ -src\test\java\com\seaofnodes\simple\Chapter07Test.java:5: error: package org.junit does not exist -import org.junit.Test; - ^ -src\test\java\com\seaofnodes\simple\Chapter07Test.java:7: error: package org.junit does not exist -import static org.junit.Assert.*; - ^ -src\test\java\com\seaofnodes\simple\BrainFuckTest.java:9: error: package org.junit does not exist -import org.junit.Test; - ^ -src\test\java\com\seaofnodes\simple\BrainFuckTest.java:10: error: package org.junit does not exist -import static org.junit.Assert.assertEquals; - ^ -Note: Some input files use unchecked or unsafe operations. -Note: Recompile with -Xlint:unchecked for details. -100 errors -only showing the first 100 errors, of 2590 total; use -Xmaxerrs if you would like to see more diff --git a/Makefile b/Makefile index 4503c993..c9a398e8 100644 --- a/Makefile +++ b/Makefile @@ -37,6 +37,9 @@ RELEASE:= build/release TEST_SYS:= $(OBJS)/lib_$(CPU_ABI)/sys.o RELEASE_SYS:= $(RELEASE)/$(CPU_ABI)/sys.o RELEASE_CRT:= $(RELEASE)/$(CPU_ABI)/simple_crt.o +RELEASE_GRAPHICS:= $(RELEASE)/$(CPU_ABI)/simple_graphics.o +RELEASE_AUDIO:= $(RELEASE)/$(CPU_ABI)/simple_audio.o +RELEASE_TIME:= $(RELEASE)/$(CPU_ABI)/simple_time.o RELEASE_ARGS:= $(RELEASE)/$(CPU_ABI)/simple_args.o C_CALL_CONV:= $(if $(filter win64,$(CALL_CONV)),ms_abi,sysv_abi) GAME_DIR:= build/examples/$(CPU_ABI) @@ -65,11 +68,32 @@ $(RELEASE_ARGS): src/main/smp/sys/rt/simple_args.smp $(CLZDIR)/main/.mtag $(simp @echo "simping " $@ @$(JVM) com.seaofnodes.simple.Simple --cpu $(CPU_PORT) --abi $(CALL_CONV) --norun -o $@ $< -$(RELEASE_CRT): src/main/c/simple_crt.c $(RELEASE_ARGS) Makefile +$(RELEASE_CRT): src/main/c/simple_crt.c $(RELEASE_ARGS) $(RELEASE_GRAPHICS) $(RELEASE_AUDIO) $(RELEASE_TIME) Makefile @echo "compiling " $@ @[ -d $(dir $@) ] || mkdir -p $(dir $@) @gcc -c -O2 -DCALL_CONV=$(C_CALL_CONV) -o $@ $< +$(RELEASE_GRAPHICS): src/main/c/simple_graphics.c src/main/c/simple_graphics.h Makefile + @echo "compiling " $@ + @mkdir -p $(dir $@) + @gcc -c -O2 -Wall -Wextra -o $@ $< + +# Optional native graphics backend. Nothing in the default build depends on it. +include graphics.mk +include audio.mk + +$(RELEASE_AUDIO): src/main/c/simple_audio.c src/main/c/simple_audio.h Makefile + @mkdir -p $(dir $@) + @gcc -c -O2 -Wall -Wextra -o $@ $< + +$(RELEASE_TIME): src/main/c/simple_time.c Makefile + @mkdir -p $(dir $@) + @gcc -c -O2 -Wall -Wextra -o $@ $< + +.PHONY: tests_nographics +tests_nographics: + @SIMPLE_MINIFB=off SIMPLE_MINIAUDIO=off $(MAKE) tests + ####################################################### # Base launch line for JVM tests diff --git a/README.ja.md b/README.ja.md index 77f2d0b2..c331e47f 100644 --- a/README.ja.md +++ b/README.ja.md @@ -70,7 +70,7 @@ Simple 言語のスタイルは、C または Java のサブセットに倣っ * [第28b章](docs/chapter28b/README.ja.md):分離コンパイル * [第29章](docs/chapter29/README.ja.md):技術的負債の整理 * [第30章](docs/chapter30/README.ja.md):テキスト整形と診断 -* 第31章:ソフトウェア描画とグラフィカルゲーム(作業中) +* [第31章](docs/chapter31/README.ja.md):ソフトウェア描画とグラフィカルゲーム(作業中) 付録:[ネイティブライブラリ](docs/appendices/native-libraries.md)、 [最適化とバックエンドの調整](docs/appendices/optimizer-tuning.ja.md)。 diff --git a/README.md b/README.md index 97d86c4e..78ea3855 100644 --- a/README.md +++ b/README.md @@ -84,7 +84,7 @@ The Simple language is styled after a subset of C or Java. * [Chapter 28b](docs/chapter28b/README.md): Separate Compilation * [Chapter 29](docs/chapter29/README.md): Tech Debt Cleanup, Partial Objects * [Chapter 30](docs/chapter30/README.md): Text Formatting and Diagnostics -* Chapter 31: Software Drawing and Graphical Games (work in progress) +* [Chapter 31](docs/chapter31/README.md): Software Drawing and Graphical Games (work in progress) Appendices: [Native libraries](docs/appendices/native-libraries.md), [optimizer and backend tuning](docs/appendices/optimizer-tuning.md). diff --git a/audio.mk b/audio.mk new file mode 100644 index 00000000..4aeeec20 --- /dev/null +++ b/audio.mk @@ -0,0 +1,31 @@ +# Optional miniaudio, independent of the default build and MiniFB. +MINIAUDIO_REV := 0.11.23 +MINIAUDIO_SRC := lib/miniaudio-$(MINIAUDIO_REV) +MINIAUDIO_HEADER := $(MINIAUDIO_SRC)/miniaudio.h +ifeq ($(OS),Windows_NT) + AUDIO_CC := x86_64-w64-mingw32-gcc + AUDIO_LIB := $(RELEASE)/$(CPU_ABI)/simple_miniaudio.dll + AUDIO_FLAGS := -D_WIN32_WINNT=0x0601 + AUDIO_LIBS := -lm +else + AUDIO_CC := gcc + AUDIO_LIB := $(RELEASE)/$(CPU_ABI)/libsimple_miniaudio.so + AUDIO_FLAGS := -fPIC + AUDIO_LIBS := -lpthread -lm -ldl +endif +.PHONY: audio +audio: $(AUDIO_LIB) +.PHONY: test-audio +test-audio: $(MINIAUDIO_HEADER) + @mkdir -p build/objs + @$(AUDIO_CC) -O2 -Wall -Wextra $(AUDIO_FLAGS) -I$(MINIAUDIO_SRC) src/test/c/audio_test.c $(AUDIO_LIBS) -o build/objs/audio_test$(if $(filter Windows_NT,$(OS)),.exe,) + @build/objs/audio_test$(if $(filter Windows_NT,$(OS)),.exe,) +lib libs init: $(MINIAUDIO_HEADER) + +$(MINIAUDIO_HEADER): + @$(call download-library,https://raw.githubusercontent.com/mackron/miniaudio/$(MINIAUDIO_REV)/miniaudio.h) +$(AUDIO_LIB): $(MINIAUDIO_HEADER) src/main/c/simple_miniaudio.c src/main/c/simple_audio.h audio.mk + @echo "building " $@ + @mkdir -p $(dir $@) + @$(AUDIO_CC) -shared -O2 -Wall -Wextra $(AUDIO_FLAGS) -I$(MINIAUDIO_SRC) src/main/c/simple_miniaudio.c $(AUDIO_LIBS) -o $@ + @sed -n '/^This software is available as a choice of the following licenses/,$$p' $(MINIAUDIO_HEADER) > $(dir $@)miniaudio-LICENSE diff --git a/chapter30.iml b/chapter30.iml deleted file mode 100644 index 793144ee..00000000 --- a/chapter30.iml +++ /dev/null @@ -1,31 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/chapter31.iml b/chapter31.iml new file mode 100644 index 00000000..f4007a98 --- /dev/null +++ b/chapter31.iml @@ -0,0 +1,31 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/docs/chapter31/31-grammar.ja.md b/docs/chapter31/31-grammar.ja.md new file mode 100644 index 00000000..eca363c1 --- /dev/null +++ b/docs/chapter31/31-grammar.ja.md @@ -0,0 +1,182 @@ +# 第31章の文法 + +[English](31-grammar.md) | 日本語 + +```antlrv4 +grammar SimpleLanguage; + +// Name lookup, assignable operands, type compatibility, and access permissions +// are checked by the compiler in addition to these syntax rules. +// A file is a compilation unit; its path supplies its namespace. +// Qualified names resolve nested types and other units without an import keyword. +program : statement* EOF ; + +block : '{' statement* '}' ; + +statement + : block + | returnStatement + | ifStatement + | whileStatement + | forStatement + | breakStatement + | continueStatement + | structDeclaration + | declaration ';' + | assignment ';' + | ';' + ; + +returnStatement : 'return' assignment ';' ; +ifStatement : 'if' '(' assignment ')' statement ('else' statement)? ; +whileStatement : 'while' '(' assignment ')' statement ; +breakStatement : 'break' ';' ; +continueStatement : 'continue' ';' ; + +forStatement + : 'for' '(' (declaration | assignment)? ';' assignment? ';' assignment? ')' statement + ; + +structDeclaration : 'struct' IDENTIFIER '{' structMember* '}' ';' ; +structMember : constructorDeclaration | methodDeclaration | statement ; + +// The constructor name must match the enclosing struct's name. +constructorDeclaration : 'new' IDENTIFIER '=' constructorExpression ';' ; +constructorExpression : '{' constructorParameterList? '->' statement* '}' ; +constructorParameterList : (constructorParameter ','?)+ ; +constructorParameter : type '^'? bindingModifier? IDENTIFIER ; +// ^ accepts an unfinished struct reference; ? independently permits null. +// Only self may be read while incomplete; ^ arguments may be stored/forwarded. +// A new result is incomplete iff an actual argument is. See ../../chapter29/README.md#incomplete-types. + +// A method is an ordinary fixed function binding in a struct definition. +// The compiler supplies self; it is not written in parameterList. +// Function types and expressions both receive their implicit receiver here. +methodDeclaration : 'val' bindingModifier? IDENTIFIER '=' functionExpression ';' ; + +declaration : declarationType binding (',' binding)* ; +declarationType : type | 'var' | 'val' ; +binding : bindingModifier? IDENTIFIER ('=' initializer)? ; +bindingModifier : '!' | '~' ; +// A declaration initializer consisting of the string "C" declares an extern +// symbol: a function, or explicit numeric native storage. Ordinary strings +// elsewhere are array-valued expressions. +initializer : assignment ; + +// The prefix qualifies the named struct reference, not an enclosing array. +// Each [] / [~] suffix qualifies its own array layer. ? requires a reference. +type + : functionType + | primitiveType typeSuffix* + | accessModifier? typeName typeSuffix* + ; +accessModifier : '!' | '~' ; +typeSuffix : '?' | '[]' | '[~]' ; +typeName : IDENTIFIER ('.' IDENTIFIER)* ; + +primitiveType + : 'int' | 'i8' | 'i16' | 'i32' | 'i64' + | 'u1' | 'u8' | 'u16' | 'u32' | 'byte' | 'bool' + | 'flt' | 'f32' | 'f64' + ; + +assignment : expression (assignmentOperator assignment)? ; +assignmentOperator + : '=' | '+=' | '-=' | '*=' | '/=' | '%=' | '&=' | '|=' | '^=' + | '<<=' | '>>=' | '>>>=' + ; + +expression : logicalExpression ('?' assignment (':' assignment)?)? ; + +// Both logical operators short-circuit and associate to the right here. +logicalExpression : bitwiseExpression (('&&' | '||') logicalExpression)? ; + +bitwiseExpression + : equalityExpression (('&' | '|' | '^') equalityExpression)* + ; + +equalityExpression : comparisonExpression (('==' | '!=') comparisonExpression)* ; + +// Chained comparisons test adjacent operands and short-circuit. A chain must +// keep its direction; equality has lower precedence and does not join a chain. +comparisonExpression + : shiftExpression + ( (('<' | '<=') shiftExpression)+ | (('>' | '>=') shiftExpression)+ )? + ; + +shiftExpression + : additiveExpression (('<<' | '>>' | '>>>') additiveExpression)* + ; + +additiveExpression + : multiplicativeExpression (('+' | '-') multiplicativeExpression)* + ; + +multiplicativeExpression + : unaryExpression (('*' | '/' | '%') unaryExpression)* + ; + +unaryExpression + : ('-' | '!') unaryExpression + | updateOperator IDENTIFIER + | postfixExpression + ; + +// Prefix updates require a local name; postfix updates also allow fields +// and array elements. All updates require an assignable operand. +updateOperator : '++' | '--' ; +postfixExpression : primaryExpression postfixSuffix* updateOperator? ; +postfixSuffix : '.' IDENTIFIER | '[' assignment ']' | '#' | callSuffix | methodCallSuffix ; + +// For a fixed function-valued member, object.name(args) passes object as self. +// This overlaps ordinary field selection followed by a call syntactically; +// name/type resolution determines which call form applies. +methodCallSuffix : '.' IDENTIFIER callSuffix ; + +primaryExpression + : INTEGER_LITERAL + | FLOAT_LITERAL + | STRING_LITERAL + | CHARACTER_LITERAL + | 'true' + | 'false' + | 'null' + | IDENTIFIER + | '(' assignment ')' + | newExpression + | functionExpression + ; + +// A function is an expression bound with an ordinary declaration. +// Its last statement supplies the implicit result; return can exit earlier. +functionExpression : '{' parameterList? '->' statement* '}' ; +parameterList : (parameter ','?)+ ; +parameter : type bindingModifier? IDENTIFIER ; + +// Function types have unnamed, space-separated argument types. +// {int} is the zero-argument type; its function expression still uses ->. +functionType + : '{' type+ '->' type '}' '?'? + | '{' type '}' '?'? + ; + +callSuffix : '(' argumentList? ')' ; +argumentList : assignment (',' assignment)* ','? ; + +// Allocation invokes the declared constructor; inline initializer blocks from +// earlier chapters are replaced by constructor arguments. +newExpression : 'new' type ('[' assignment ']' | callSuffix)? ; + +INTEGER_LITERAL : [1-9] DIGIT* | '0' [0-7]* | '0' [xX] HEX_DIGIT+ ; +FLOAT_LITERAL : DIGIT+ ('.' DIGIT* ('e' DIGIT+)? | 'e' '-'? DIGIT+) ; +STRING_LITERAL : '"' (ESCAPE | ~["\\])* '"' ; +CHARACTER_LITERAL : '\'' (ESCAPE | ~['\\]) '\'' ; +fragment ESCAPE : '\\' [0ntr\\'"] ; +IDENTIFIER : NON_DIGIT (NON_DIGIT | DIGIT)* ; +fragment NON_DIGIT : [a-zA-Z_] ; +fragment DIGIT : [0-9] ; +fragment HEX_DIGIT : [0-9a-fA-F] ; +WHITESPACE : [ \t\r\n]+ -> skip ; +LINE_COMMENT : '//' ~[\r\n]* -> skip ; +BLOCK_COMMENT : '/*' .*? '*/' -> skip ; +``` diff --git a/docs/chapter31/31-grammar.md b/docs/chapter31/31-grammar.md new file mode 100644 index 00000000..b1f563e4 --- /dev/null +++ b/docs/chapter31/31-grammar.md @@ -0,0 +1,273 @@ +# Grammar for Chapter 31 + +English | [日本語](31-grammar.ja.md) + +The handwritten recursive-descent implementation lives in +[`com.seaofnodes.simple.parser`](../../src/main/java/com/seaofnodes/simple/parser/). +The production-to-code map below the grammar describes where syntax ends and +name resolution or graph construction begins. This grammar documents the +language; it is not input to a parser generator. + +`int` is an alias for `i32`; `i64` explicitly selects 64-bit integer storage. +This alias does not change literal inference or intermediate arithmetic. + +Integer literals use decimal (`42`), leading-zero octal (`052`), or hexadecimal +(`0x2a`, `0X2A`). Octal digits are 0–7; `08` and `09` are errors. Hexadecimal +and octal literals can spell any 64-bit bit pattern: the high bit gives the +usual signed value, so `0xffffffffffffffff` is -1. Decimal literals retain +their signed 64-bit limit. Floating literals remain decimal, including forms +such as `012.5` and `012f`. A radix prefix does not change integer inference +or storage width. + +```antlrv4 +grammar SimpleLanguage; + +// Name lookup, assignable operands, type compatibility, and access permissions +// are checked by the compiler in addition to these syntax rules. +// A file is a compilation unit; its path supplies its namespace. +// Qualified names resolve nested types and other units without an import keyword. +program : statement* EOF ; + +block : '{' statement* '}' ; + +statement + : block + | returnStatement + | ifStatement + | whileStatement + | forStatement + | breakStatement + | continueStatement + | structDeclaration + | declaration ';' + | assignment ';' + | ';' + ; + +returnStatement : 'return' assignment ';' ; +ifStatement : 'if' '(' assignment ')' statement ('else' statement)? ; +whileStatement : 'while' '(' assignment ')' statement ; +breakStatement : 'break' ';' ; +continueStatement : 'continue' ';' ; + +forStatement + : 'for' '(' (declaration | assignment)? ';' assignment? ';' assignment? ')' statement + ; + +structDeclaration : 'struct' IDENTIFIER '{' structMember* '}' ';' ; +structMember : constructorDeclaration | methodDeclaration | statement ; + +// The constructor name must match the enclosing struct's name. +constructorDeclaration : 'new' IDENTIFIER '=' constructorExpression ';' ; +constructorExpression : '{' constructorParameterList? '->' statement* '}' ; +constructorParameterList : (constructorParameter ','?)+ ; +constructorParameter : type '^'? bindingModifier? IDENTIFIER ; +// ^ accepts an unfinished struct reference; ? independently permits null. +// Only self may be read while incomplete; ^ arguments may be stored/forwarded. +// A new result is incomplete iff an actual argument is. See ../../chapter29/README.md#incomplete-types. + +// A method is an ordinary fixed function binding in a struct definition. +// The compiler supplies self; it is not written in parameterList. +// Function types and expressions both receive their implicit receiver here. +methodDeclaration : 'val' bindingModifier? memberName '=' functionExpression ';' ; +memberName : IDENTIFIER | primitiveType ; + +declaration : declarationType binding (',' binding)* ; +declarationType : type | 'var' | 'val' ; +binding : bindingModifier? IDENTIFIER ('=' initializer)? ; +// At class/struct member scope, memberName also permits primitive type names. +// Ordinary locals and parameters still require a non-keyword IDENTIFIER. +bindingModifier : '!' | '~' ; +// A declaration initializer consisting of the string "C" declares an extern +// symbol: a function, or explicit numeric native storage. Ordinary strings +// elsewhere are array-valued expressions. +initializer : assignment ; + +// The prefix qualifies the named struct reference, not an enclosing array. +// Each [] / [~] suffix qualifies its own array layer. ? requires a reference. +type + : functionType + | primitiveType typeSuffix* + | accessModifier? typeName typeSuffix* + ; +accessModifier : '!' | '~' ; +typeSuffix : '?' | '[]' | '[~]' ; +typeName : IDENTIFIER ('.' IDENTIFIER)* ; + +primitiveType + : 'int' | 'i8' | 'i16' | 'i32' | 'i64' + | 'u1' | 'u8' | 'u16' | 'u32' | 'byte' | 'bool' + | 'flt' | 'f32' | 'f64' + ; + +assignment : expression (assignmentOperator assignment)? ; +assignmentOperator + : '=' | '+=' | '-=' | '*=' | '/=' | '%=' | '&=' | '|=' | '^=' + | '<<=' | '>>=' | '>>>=' + ; + +expression : logicalExpression ('?' assignment (':' assignment)?)? ; + +// Both logical operators short-circuit and associate to the right here. +logicalExpression : bitwiseExpression (('&&' | '||') logicalExpression)? ; + +bitwiseExpression + : equalityExpression (('&' | '|' | '^') equalityExpression)* + ; + +equalityExpression : comparisonExpression (('==' | '!=') comparisonExpression)* ; + +// Chained comparisons test adjacent operands and short-circuit. A chain must +// keep its direction; equality has lower precedence and does not join a chain. +comparisonExpression + : shiftExpression + ( (('<' | '<=') shiftExpression)+ | (('>' | '>=') shiftExpression)+ )? + ; + +shiftExpression + : additiveExpression (('<<' | '>>' | '>>>') additiveExpression)* + ; + +additiveExpression + : multiplicativeExpression (('+' | '-') multiplicativeExpression)* + ; + +multiplicativeExpression + : unaryExpression (('*' | '/' | '%') unaryExpression)* + ; + +unaryExpression + : ('-' | '!') unaryExpression + | updateOperator IDENTIFIER + | postfixExpression + ; + +// Prefix updates require a local name; postfix updates also allow fields +// and array elements. All updates require an assignable operand. +updateOperator : '++' | '--' ; +postfixExpression : primaryExpression postfixSuffix* updateOperator? ; +postfixSuffix : '.' memberName | '[' assignment ']' | '#' | callSuffix | methodCallSuffix ; + +// For a fixed function-valued member, object.name(args) passes object as self. +// This overlaps ordinary field selection followed by a call syntactically; +// name/type resolution determines which call form applies. +methodCallSuffix : '.' memberName callSuffix ; + +primaryExpression + : INTEGER_LITERAL + | FLOAT_LITERAL + | stringExpression + | CHARACTER_LITERAL + | 'true' + | 'false' + | 'null' + | IDENTIFIER + | '(' assignment ')' + | newExpression + | functionExpression + ; + +// A function is an expression bound with an ordinary declaration. +// Its last statement supplies the implicit result; return can exit earlier. +functionExpression : '{' parameterList? '->' statement* '}' ; +parameterList : (parameter ','?)+ ; +parameter : type bindingModifier? IDENTIFIER ; + +// Function types have unnamed, space-separated argument types. +// {int} is the zero-argument type; its function expression still uses ->. +functionType + : '{' type+ '->' type '}' '?'? + | '{' type '}' '?'? + ; + +callSuffix : '(' argumentList? ')' ; +argumentList : assignment (',' assignment)* ','? ; + +// Allocation invokes the declared constructor; inline initializer blocks from +// earlier chapters are replaced by constructor arguments. +newExpression + : 'new' type ('[' '~'? assignment ']' arrayInitializer? | arrayInitializer | callSuffix)? + ; +// With no explicit length, type must end in [] or [~] and the initializer is a list. +arrayInitializer + : '{' (assignment (',' assignment)* ','?)? '}' + | '{' ('int' | 'i32' | 'i64' | 'u32') IDENTIFIER '->' statement* '}' + ; + +INTEGER_LITERAL : [1-9] DIGIT* | '0' [0-7]* | '0' [xX] HEX_DIGIT+ ; +// The f suffix also accepts an integer-shaped token, e.g. 12f. +FLOAT_LITERAL : DIGIT+ ('.' DIGIT* ('e' DIGIT+)? | 'e' '-'? DIGIT+) 'f'? + | DIGIT+ 'f' ; +// String text uses a lexical mode: whitespace/comments are literal here. +// Interpolation re-enters the ordinary expression grammar, recursively. +stringExpression : '"' (STRING_TEXT | ESCAPE | '%%' | interpolation)* '"' ; +interpolation : '%' format? '(' assignment ')' ; +format : FORMAT_FLAG* FORMAT_WIDTH? ('.' FORMAT_WIDTH?)? FORMAT_KIND TIME_STYLE? ; +// Flags: - + space # 0. Width/precision: decimal digits, no expressions. +// Kinds: d i u o x X f F e E g G a A c s b t. +// TIME_STYLE: F r R M D T, allowed only after t; default F (ISO UTC). +// Time styles: ISO, 12-hour, 24-hour, elapsed MM:SS.mmm, DD/MM/YY, HH:MM:SS. +// Duplicate/inapplicable flags and precision on c/b/t are rejected. +// Time accepts width and left alignment only; see time.md. +// STRING_TEXT excludes double quote, backslash, and percent. +CHARACTER_LITERAL : '\'' (ESCAPE | ~['\\]) '\'' ; +fragment ESCAPE : '\\' [0ntr\\'"%] ; +IDENTIFIER : NON_DIGIT (NON_DIGIT | DIGIT)* ; +fragment NON_DIGIT : [a-zA-Z_] ; +fragment DIGIT : [0-9] ; +fragment HEX_DIGIT : [0-9a-fA-F] ; +WHITESPACE : [ \t\r\n]+ -> skip ; +LINE_COMMENT : '//' ~[\r\n]* -> skip ; +BLOCK_COMMENT : '/*' .*? '*/' -> skip ; +``` + +## Reading the parser alongside the grammar + +All paths below are within `src/main/java/com/seaofnodes/simple/parser/`. +The components share one `Parser` instance containing the cursor, active scope, +compilation unit, and graph utilities. They are package-private collaborators; +there is no inheritance chain, AST, or additional compiler pass. + +| Productions | Implementation | +| --- | --- | +| `program` | [`Parser.parse`](../../src/main/java/com/seaofnodes/simple/parser/Parser.java): establish the source-unit scope, parse its initializer, resolve remaining file names, publish its class | +| `statement`, `block`, loops, jumps, `returnStatement` | [`Statements`](../../src/main/java/com/seaofnodes/simple/parser/Statements.java), starting at `parseStatement` | +| `declaration`, `binding`, `bindingModifier` | [`Declarations`](../../src/main/java/com/seaofnodes/simple/parser/Declarations.java): declaration/expression lookahead, then each binding and initializer | +| `structDeclaration`, `constructorDeclaration` | [`Structs`](../../src/main/java/com/seaofnodes/simple/parser/Structs.java), starting at `parseStruct` and `parseConstructorDeclaration`; field discovery and initialization checks follow these entry points | +| `type`, `typeName`, `functionType` | [`Types`](../../src/main/java/com/seaofnodes/simple/parser/Types.java): `parseType` and `parseFunctionType`; qualified-name lookup lives in `typeName`, `dottedName`, and `rootedName` | +| `assignment` through `primaryExpression` | [`Expressions`](../../src/main/java/com/seaofnodes/simple/parser/Expressions.java): `parseAssignment`, `parseExpression`, `parseLogical`, `parseBitwise`, `parseEquality`, `parseComparison`, `parseShift`, `parseAddition`, `parseMultiplication`, `parseUnary`, `parsePrimary` | +| `postfixExpression`, member selection and updates | `Expressions.parsePostfix` / `parsePostfixMethod` dispatch to [`References.parseField`](../../src/main/java/com/seaofnodes/simple/parser/References.java); `References.parseName` handles bare names, implicit receivers, and forward references | +| `functionExpression`, `parameterList`, calls, `argumentList` | [`Functions`](../../src/main/java/com/seaofnodes/simple/parser/Functions.java): `parseFunction`, `parseConstructor`, shared `parameters` and `arguments`, then `parseBody` | +| `newExpression`, `arrayInitializer` | [`Allocations.parseNew`](../../src/main/java/com/seaofnodes/simple/parser/Allocations.java), [`ArrayInitializers`](../../src/main/java/com/seaofnodes/simple/parser/ArrayInitializers.java); private initialization, list checks, and generator loops | +| `stringExpression`, `interpolation` | [`Strings.parse`](../../src/main/java/com/seaofnodes/simple/parser/Strings.java), using `Lexer.stringPart` / `stringFormat`; normal expression parsing resumes inside each interpolation | +| Literals, identifiers, comments, token matching | [`Lexer`](../../src/main/java/com/seaofnodes/simple/parser/Lexer.java); it also supplies source-location snapshots used by diagnostics and serialized IR | + +`ControlFlow` shares guarded scope merging between `if`, `?:`, `&&`, and `||`. +`Conversions` shares binding, field, and result conversions. These +operations are compiler semantics rather than additional grammar productions. +`Parser` retains the type registry and the small control/memory/peephole helpers +used by several productions and by the rest of the compiler. + +There are a few deliberate differences between a syntax-only parser and this +one-pass IR builder: + +- A statement beginning with `{` might be a block or a function-type binding. + `Declarations` and `Types` use speculative parsing and cursor restore; + qualified type lookup also stops before a suffix that belongs to an expression. +- Bare assignment, field assignment, and compound updates share the grammar's + precedence but use different IR paths. `References` decides between an SSA + local, a constructor field's local value, and an actual memory access. A + function-valued field may also supply an implicit receiver to a call. +- `for` updates are scanned first and parsed after the body, where their effects + belong. Explicit constructor bodies are scanned first and parsed after field + discovery, so later fields have local slots. Both use `Lexer.skipTo`, which + ignores delimiters inside comments and quoted text. +- `Structs.parseInitializer` parses a file or struct body as a function while + discovering fields. `Functions.parseBody` still owns function scope/return + construction; moving it does not change constructor or memory semantics. + +The syntax chart does not describe all name/type restrictions. In particular, +prefix updates require an already-known non-pointer binding, and a private-class +privacy policy is separate from recognizing a qualified type name. The existing +same-named function binding inside a struct is also recognized as a constructor; +`new Name = { ... };` is the explicit constructor spelling above. diff --git a/docs/chapter31/README.ja.md b/docs/chapter31/README.ja.md new file mode 100644 index 00000000..511c72ee --- /dev/null +++ b/docs/chapter31/README.ja.md @@ -0,0 +1,25 @@ +# 第31章:ソフトウェア描画とグラフィカルゲーム + +[English](README.md) | 日本語 + +[前の章:第30章 — テキスト整形と診断](../chapter30/README.ja.md) + +第30章で完成したコンパイラと標準ライブラリを出発点とする章です。 +Simple で描画する `sys.draw.Canvas` と、MiniFB を使うオプションの +ウィンドウ・入力 API `sys.gfx` を使って、グラフィカルな三目並べを実装します。 +矩形、円、太い線、色、ビットマップ文字を扱えます。 +詳細は[英語版の描画ライブラリとゲームの説明](../../src/main/smp/sys/draw/README.md)を参照してください。 +通常のビルドとテストに MiniFB や画面表示は必要ありません。 + +```sh +make -C chapter31 run-graphical-tictactoe +``` + +`%` は Java の `%` と同じ符号規則を使う剰余演算子です。`*`、`/` と同じ優先順位で、 +左から右に結合します。例えば `-17 % 5` は `-2`、`17 % -5` は `2` です。 +整数と浮動小数点数に対応し、整数のゼロ除算は Simple の `/` と同様にゼロを返します。 +詳しい意味と実装は[英語版の説明](README.md#remainder)を参照してください。 + +このスナップショットの[文法](31-grammar.ja.md)と +[実行可能な例](examples/)を用意しています。 +ビルド手順は[英語版](README.md)を参照してください。 diff --git a/docs/chapter31/README.md b/docs/chapter31/README.md new file mode 100644 index 00000000..8debaf03 --- /dev/null +++ b/docs/chapter31/README.md @@ -0,0 +1,293 @@ +# Chapter 31: Software Drawing, Time, and Graphical Games + +[Previous: Chapter 30 — Text Formatting and Diagnostics](../chapter30/README.md) + +In this chapter we use small graphical games to drive the language and library +work. We add graphics, sound, and time support, with a few small C adapters +for native services. We also add array initializers and read-only arrays, hex, +octal parsing, move constant arrays into the ELF constant pool. We then write +a few games, with the drawing and game logic written in Simple. + + +## Games and demos + +All graphical demos support resizing. Canvas scales their base layouts and +mouse coordinates together, preserving proportions; Breakout's physics remains +in base coordinates. The pixel gradient fills the resized window. + +[Clock](examples/Clock.smp) is a classic clock demo. It shows local time as +digital digits or an analog dial. Click its button or press Space to switch +views. It combines timers, mouse input, text, and drawing in one event loop. + +[Graphical Tic-tac-toe](examples/TicTacToeGraphical.smp) accepts mouse +clicks or keys 1 through 9. It highlights the winning line and plays move and +result sounds. Game logic is the same as in the terminal version from +the prior chapter, with the graphics added to the event loop. + +[Breakout](examples/Breakout.smp) has a ball, a paddle, and a wall of +bricks. Move the paddle with the arrow keys or mouse. The ball's bounce angle +depends on where it hits the paddle. Deeper bricks score more points, make +higher-pitched sounds, and increase the ball's speed. Hitting the *back* of a +brick gives a one-time larger speed boost. Clear all the bricks before using +up three balls. + + +## Remainder + +`%` computes remainder with Java's sign convention. It has the same +precedence as `*` and `/`, and associates left to right. For example, +`17 % 5` is `2`, `-17 % 5` is `-2`, and `17 % -5` is `2`. +The remainder follows the dividend's sign; it is not always nonnegative. +Integer `MIN_I64 % -1` is zero. Like Simple's integer division, integer +remainder by zero produces zero. Unused arithmetic can be removed. + +Floating-point operands use the same truncating-quotient rule: `7.5 % 2.0` +is `1.5`. A zero divisor or infinite dividend produces NaN; a finite dividend +modulo infinity is unchanged, and a zero result retains the dividend's sign. +Mixed integer/float operands convert to floating point, as with `*` and `/`. +The compound assignment `x %= y` stores `x % y` back into `x`. +`mod` is an ordinary identifier. + +Clock uses `second % 10` for its last digit and `i % 5 == 0` for major +dial ticks. The time library uses the operator for leap years and calendar +fields, adding a positive period when it needs a nonnegative result. + +[`ModNode`](../../src/main/java/com/seaofnodes/simple/node/ModNode.java) follows +`DivNode`: two operands, one result, and shared arithmetic folding and type +checking. It has no control or memory effects. Integer machine encodings handle +zero divisors and signed overflow to preserve the ideal operations' results +without hardware faults. Floating remainder uses a memory-preserving runtime +helper selected as a machine operation; the ideal graph stays ordinary arithmetic. +`make test CLASS=ModTest` covers folding, evaluation, native execution, imports, +and code generation for all three targets. + + +## Graphics and sound + +Graphics and sound are optional. The Simple language and compiler do not need +them. The `sys` library includes bindings to the native C backends, but you do +not need those backends for programs without a display or sound. Their +dependencies download with the existing `make init` setup command. + +Each pixel holds 24 bits of RGB color in a `u32`. A pixel buffer is a `u32[]`. + +[`sys.draw.Canvas`](../../src/main/smp/sys/draw/Canvas.smp) draws pixels, rectangles, +circles, thick lines, and text into a `u32[]` pixel buffer. Shapes clip to the +canvas. The 3x5 font includes digits, letters, and punctuation such as colons +and slashes. Its glyphs are stored in a read-only array. + +`sys.draw` supplies a few color constants plus `rgb(r,g,b)` to clamp and pack +computed color components. + +`sys.draw.Button` handles button hover, press, release, and disabled states. + +`sys.gfx` opens a window, presents pixels, and reads keyboard and mouse input. +The window backend uses MiniFB. `gfx.wait(timeout_ms)` waits for input or a +timeout, so animation need not spin continuously. + +`sys.audio` plays built-in cues or sample arrays generated in Simple. Its +optional miniaudio backend plays sound while the game continues. The games +can run silently when audio is unavailable. + +See [drawing](../../src/main/smp/sys/draw/README.md), [windows](../../src/main/smp/sys/gfx.md), and +[audio](../../src/main/smp/sys/audio.md) for the APIs. + + +## Time library + +[`sys.time`](../../src/main/smp/sys/time.smp) provides wall-clock time, monotonic +time, sleep, calendar conversion, ISO date parsing, and formatting. Use +wall-clock time for dates. Use monotonic time for elapsed time and deadlines - +perfect for games. + +Instants and durations normally use `i64` milliseconds. Constants show their +units directly: `SECOND=1000`, `MINUTE=60*SECOND`, and `HOUR=60*MINUTE`. + +`sys.time.Timers` supports one-shot and repeating timers. The event loop polls +for due timer IDs; no timer thread or callback is needed. This might be a mindset +change for you game writers, it depends on what era you started writing them. +Here it is all single-threaded and event-loop driven - but when there is nothing +left to do, you need to wait for an event. + +Time also works in string interpolation: + +```simple +sys.io.p("UTC %tT(sys.time.now())\n"); +``` + +Millisecond parameters and fields end in `_ms` to distinguish them from other +integers. + +See [time and timers](../../src/main/smp/sys/time/README.md) for local-time formatting and other forms. + + +## Array initializers + +An array can use a list of values or an expression evaluated for each index: + +```simple +val primes = new int[]{2,3,5,7}; +val squares = new int[10]{int i -> i*i;}; +val names = new u8[~][~2]{"Alice","Bob"}; +``` + +The generator runs once per element, from index zero through length minus one. +Its body can contain statements and return the element value. It can read +surrounding locals but cannot reassign them; it is not a true function. + +If the array has a fixed initialization list, then the length can be inferred. + + +`[~n]` (or `[~]` with a list) makes an array read-only. `val` prevents +reassignment of the array variable, but not changes to its contents. In C, +this is the classic `const u8* const` distinction: the first `const` protects +the contents; the second protects the pointer. Array initialization normally +runs at runtime; read-only does not require compile-time evaluation. + +When the compiler knows a read-only integer array's complete contents, it can +emit them as static ELF data. Identical constant arrays can share storage, +just like strings. Canvas's font now uses this path instead of allocating +and filling its table at startup. The trigger is a `TypeConAry` constant type, +regardless of which node computes it. Constant lists are the first new +producer; generators still run at runtime. + +Initializers also allow arrays of non-null references: every element is +supplied before the array becomes accessible. In the example, `names` is a +read-only array of two non-null, read-only strings. + + +## Math support and intrinsics + +[`sys.math`](../../src/main/smp/sys/math.smp) provides `PI`, `E`, `min`, `max`, and +five native math functions, each with signature `{ f64 -> f64 }`: + +| Function | Result | +| --- | --- | +| `sin(x)` | Sine of an angle in radians | +| `cos(x)` | Cosine of an angle in radians | +| `exp(x)` | e raised to x | +| `log(x)` | Natural logarithm of x | +| `sqrt(x)` | Nonnegative square root of x | + +```simple +f64 diagonal = sys.math.sqrt(2.0); +f64 height = sys.math.sin(sys.math.PI/6.0); +f64 power = sys.math.exp(2.0); +f64 exponent = sys.math.log(power); +``` + +These are direct bindings to the host's libm; the standard linker already +includes `-lm`. Results and domain/range errors, including `errno`, follow +that library. See the native references for +[trigonometry](https://sourceware.org/glibc/manual/2.43/html_node/Trig-Functions.html) +and [exponents, logarithms, and square roots](https://sourceware.org/glibc/manual/latest/html_node/Exponents-and-Logarithms.html). +They remain ordinary C calls, so they are not constant-folded or discarded as +pure intrinsics. Clock uses `sin` and `cos` for its dial and hands. +`make test CLASS=MathTest` checks native results, special values, indirect calls, +and code generation for all three targets. + +Two representation operations are compiler intrinsics: + +```simple +i64 bits = sys.math.f64Bits(1.0); // 0x3ff0000000000000 +f64 value = sys.math.f64FromBits(bits); // 1.0 +``` + +They *reinterpret* the same 64 bits, preserving signed zero, infinities, +subnormals, and NaN signs and payloads, including the signaling bit. They perform +no arithmetic and have no memory effects. Applying either operation followed +by the other is an identity. Ordinary assignments between integer and +floating-point types still perform numeric conversion; floating-point +arithmetic may change a NaN representation. + +These functions introduce compiler intrinsics: ordinary C bindings with reserved +external symbols, fixed signatures, and known meanings. The compiler recognizes +the external function's identity, including aliases and imported bindings, and +can replace its calls with ideal IR nodes. It does not recognize the spelling of +a local variable or an unrelated Simple function with the same name. No new +expression syntax is needed. + +| External C symbol | Signature | Public alias | +| --- | --- | --- | +| `simple_f64_bits` | `{ f64 -> i64 }` | `sys.math.f64Bits` | +| `simple_f64_from_bits` | `{ i64 -> f64 }` | `sys.math.f64FromBits` | + +[`Intrinsic.java`](../../src/main/java/com/seaofnodes/simple/node/Intrinsic.java) owns the +reserved-symbol table, signatures, effect queries, inlining, and ideal nodes. +Call/CallEnd delegate to it. The cheap inliner checks intrinsics before requiring +a Simple body or Return edge. It validates the signature and actual arguments, +then replaces the complete control/memory/value state. For these pure operations, +control and memory pass through unchanged. + +Unknown indirect targets keep ordinary calls. The runtime's +[`simple_crt.c`](../../src/main/c/simple_crt.c) supplies C definitions using `memcpy` +to preserve representations without aliasing tricks. A replacement definition +must honor the same contract. Ordinary C functions remain opaque to the optimizer. + +The ideal nodes support constant folding, inverse cancellation, evaluation, and +serialization. Floating-point constant interning and serialization retain raw +NaN bits. x86 emits `MOVQ` between XMM and integer registers; ARM emits `FMOV`, +and RISC-V emits `FMV.X.D` / `FMV.D.X`. Register allocation may add copies or +spills, and normal module-initialization checks still apply. + +Future intrinsics such as compare-and-swap or fences must define their memory +and escape effects explicitly, using nodes with the required ordering +dependencies. They must not inherit the pure conversions' passthrough memory +behavior. Atomic operations and hardware square root are not introduced here. + +`make test CLASS=IntrinsicTest` checks representation preservation, folding, +type errors, side effects, indirect C fallback, binary imports, and instruction +selection on all three backends, including emulation and native x86 execution. + +Simple also now recognizes hexadecimal (`0xff0000`) and leading-zero octal +(`025755`) integer literals. + + +## Compiler fixes + +- Syntax errors raised through JUnit now show the source line and error pointer. + Actual compiler failures still report Java stack traces. +- Integer memory operations on x86 use the correct register class. This fixes + the instruction-encoding failure exposed by Dijkstra. +- Floating-point comparisons handle NaNs correctly in branches and Boolean + results. Floating-point negation also handles signed zero correctly. +- Array-initializer memory tracking no longer adds an unrelated function to + the returned result. Loop-load optimization checks that the pointer is + available before moving a load. +- Imported read-only primitive arrays retain their types. Object files can + represent more than 255 distinct memory regions. +- Floating-point constants and register copies preserve raw NaN bits. + +## Further reading + +The [grammar and code map](31-grammar.md) is this chapter's language +reference. Runnable programs and their controls are in the +[examples](examples/README.md). Library API references live beside their +implementations: [drawing](../../src/main/smp/sys/draw/README.md), +[windows](../../src/main/smp/sys/gfx.md), [audio](../../src/main/smp/sys/audio.md), and +[time](../../src/main/smp/sys/time/README.md). + +For inherited compiler behavior, start with [escape analysis in Chapter 27](../chapter27/README.md) +and [construction and partial references in Chapter 29](../chapter29/README.md). +Chapter 29 also links the detailed construction and escape implementation notes. + +## Build and run + +From the `chapter31` directory: + +```sh +make libs # Download dependencies once. +make run-graphical-tictactoe +make run-clock +make run-breakout +``` + +Dependencies stay cached across `make clean`. The run targets build the needed +window and audio backends. Use `graphical-tictactoe`, `clock-example`, or +`breakout` to build an executable without opening a window. + +Run the ordinary tests without a display or audio device: + +```sh +make tests_nographics +``` diff --git a/docs/chapter31/examples/A_helloWorld.smp b/docs/chapter31/examples/A_helloWorld.smp new file mode 100644 index 00000000..4ed6abdf --- /dev/null +++ b/docs/chapter31/examples/A_helloWorld.smp @@ -0,0 +1,2 @@ +sys.io.p("Hello, World!\n"); +return 0; diff --git a/docs/chapter31/examples/Breakout.smp b/docs/chapter31/examples/Breakout.smp new file mode 100644 index 00000000..d60894ac --- /dev/null +++ b/docs/chapter31/examples/Breakout.smp @@ -0,0 +1,369 @@ +// Clear 24 x 8 bricks. Arrows or mouse move; Space/click serves; P pauses; +// R restarts; Q/Escape exits. Any argument runs ten frames as a smoke test. +u32 WIDTH = 1008, HEIGHT = 760, COLS = 24, ROWS = 8; +int LEFT = 24, RIGHT = 984, TOP = 84, BOTTOM = 718; +int BRICK_TOP = 152, BRICK_DX = 40, BRICK_DY = 22, BRICK_W = 36, BRICK_H = 18; +int RADIUS = 5, PADDLE_HALF = 56, PADDLE_Y = 674; +int READY = 0, PLAY = 1, WON = 2, LOST = 3; +int KEY_LEFT = 263, KEY_RIGHT = 262; // MiniFB key codes; gfx.LEFT is a mouse button. +i64 STEP_ms = 8, FRAME_ms = 16; +u32 BACKGROUND = 0x0b1220, WHITE = 0xeef7ff, MUTED = 0x8aabc4, CYAN = 0x4ce0ef; +val COLORS = new u32[~]{0xff5268,0xff8050,0xffb548,0xffdb58, + 0x9bdd58,0x45d8b0,0x49b9f5,0x8d94ff}; +val DIGITS = new u8[~][~]{"0","1","2","3","4","5","6","7","8","9"}; + +struct Game { + u8[] bricks = new u8[COLS*ROWS]{int i -> 1;}; + int score = 0, remaining = COLS*ROWS, lives = 3, depth = 1, phase = READY; + bool boosted = false, backWall = false, paused = false; + f64 x = 504.0, y = 663.0, dx = 0.4, dy = -0.916515138991168; + + // Fixed 8 ms simulation, split further to travel at most two pixels per step. + // Even at maximum boosted speed a ball cannot tunnel through an 18 px brick. + val _tick = { int direction -> + if( paused || phase == WON || phase == LOST ) return 0; + _paddle(paddle+direction*6.4); + if( phase == READY ) { x = paddle; y = PADDLE_Y-RADIUS-6; return 0; } + f64 seconds = 0.008; // 8ms + while( seconds > 0.000000001 && phase == PLAY ) { + f64 dt = 2.0/speed; + if( dt > seconds ) dt = seconds; + seconds -= dt; + f64 oldX = x, oldY = y; + x += dx*speed*dt; + y += dy*speed*dt; + if( x < LEFT+RADIUS && dx < 0.0 ) { + x = 2.0*(LEFT+RADIUS)-x; dx = -dx; _cue(1); + } + if( x > RIGHT-RADIUS && dx > 0.0 ) { + x = 2.0*(RIGHT-RADIUS)-x; dx = -dx; _cue(1); + } + if( y < TOP+RADIUS && dy < 0.0 ) { + y = 2.0*(TOP+RADIUS)-y; dy = -dy; + backWall = true; _cue(1); + } + if( dy > 0.0 && oldY <= PADDLE_Y-RADIUS && y >= PADDLE_Y-RADIUS && + paddle-PADDLE_HALF-RADIUS <= x <= paddle+PADDLE_HALF+RADIUS ) _rebound(); + if( y > BOTTOM+RADIUS ) { + _lostBall(); + break; + } + // Map the center into the grid of radius-expanded brick boxes. + // Their overlap is smaller than one cell: at most 2 x 2 candidates. + if( x <= LEFT+2 -RADIUS || x >= LEFT+2 +(COLS-1)*BRICK_DX+BRICK_W+RADIUS || + y <= BRICK_TOP-RADIUS || y >= BRICK_TOP+(ROWS-1)*BRICK_DY+BRICK_H+RADIUS ) + continue; + int col = (x-(LEFT+2 -RADIUS))/BRICK_DX; + int row = (y-(BRICK_TOP-RADIUS))/BRICK_DY; + bool hit = false; + for( int r = row > 0 ? row-1 : 0; r <= row && r < ROWS && !hit; r++ ) + for( int c = col > 0 ? col-1 : 0; c <= col && c < COLS; c++ ) { + int i = r*COLS+c; + if( bricks[i] == 0 ) continue; + f64 left = LEFT+2 +c*BRICK_DX-RADIUS; + f64 top = BRICK_TOP+r*BRICK_DY-RADIUS; + f64 right = left+BRICK_W+2*RADIUS; + f64 bottom= top +BRICK_H+2*RADIUS; + if( left < x < right && top < y < bottom ) { + bool back = false; + // Resolve the face crossed this step, using the previous center. + // Vertical faces win a simultaneous corner contact. + if( oldY <= top && dy > 0.0 ) { + y = top; dy = -dy; back = true; + } else if( oldY >= bottom && dy < 0.0 ) { + y = bottom; dy = -dy; + } else if( oldX <= left && dx > 0.0 ) { + x = left; dx = -dx; + } else if( oldX >= right && dx < 0.0 ) { + x = right; dx = -dx; + } else continue; // Missed all bricks + _brick(i,back); + hit = true; + break; + } + } + } + return 0; + }; + + + // Several sound things might happen in this event, pick one + int sound = 0; // Increasing priority: wall, paddle, brick, boost, miss, win. + val _cue = { int snd -> if( snd > sound ) sound = snd; }; + + // Ball speed is a fraction of deepest brick hit, plus backwall boost + f64 speed; + val _speed = { -> speed = (320.0+35.0*(depth-1))*(boosted ? 1.65 : 1.0); }; + + // Clamp paddle to wall sides + f64 paddle; + val _paddle = { f64 x -> + paddle = x < LEFT +PADDLE_HALF ? LEFT +PADDLE_HALF : + x > RIGHT-PADDLE_HALF ? RIGHT-PADDLE_HALF : + x; + }; + + // Hit the paddle + val _rebound = { -> + // Where along the paddle did you hit? + f64 offset = (x-paddle)/PADDLE_HALF; + if( offset < -1.0 ) offset = -1.0; + if( offset > 1.0 ) offset = 1.0; + dx = 0.88*offset; + // A near-center hit still drifts sideways instead of repeating forever. + if( -0.12 < dx < 0.12 ) dx = dx < 0.0 ? -0.12 : 0.12; + dy = -_sqrt(1.0-dx*dx); // Bounce upwards speed + y = PADDLE_Y-RADIUS; // Reset ball hit to top of paddle + backWall = false; // Did not hit back wall + _cue(2); // Paddle bounce sound + }; + + // Hit a brick? + int soundDepth; // Which brick depth for the boop + val _brick = { int index, bool back -> + if( bricks[index] == 0 ) return 0; // No brick to hit! + bricks[index] = 0; // Clear brick + int row = ROWS-index/COLS; // Get brick row + score += row; // Score by row + remaining--; // Fewer bricks to iwn + if( row > depth ) depth = row; // Max depth seen + // Brick-hit sound + if( sound <= 3 ) { _cue(3); soundDepth = row; } + if( back && backWall && !boosted ) { _cue(3); boosted = true; } + if( remaining == 0 ) { _cue(6); phase = WON; } + _speed(); + return 0; + }; + + // Missed ball with paddle + val _lostBall = { -> + lives--; + phase = lives == 0 ? LOST : READY; + backWall = false; + depth = 1; + boosted = false; + _speed(); + x = paddle; y = PADDLE_Y-RADIUS-6; + _cue(5); + }; + + // Reset for another round + val _reset = { -> + for( int i = 0; i < bricks#; i++ ) bricks[i] = 1; + score = 0; + remaining = COLS*ROWS; + lives = 3; + depth = 1; + phase = READY; + boosted = false; + backWall = false; + paused = false; + sound = 0; + soundDepth = 1; + paddle = 504.0; + x = paddle; + y = PADDLE_Y-RADIUS-6; + _speed(); + }; + + // -------------------------------- + // Drawing code + val _hud = { !sys.draw.Canvas c -> + c.text(24,22,"BREAKOUT",5,WHITE); + c.text(264,20,"SCORE",2,MUTED); + _number(c,264,40,score,3,4,WHITE); + c.text(424,20,"BRICKS",2,MUTED); + _number(c,424,40,remaining,3,4,WHITE); + c.text(584,20,"BALLS",2,MUTED); + for( int i = 0; i < lives; i++ ) c.fillCircle(590+23*i,50,5,CYAN); + c.text(714,20,"SPEED",2,MUTED); + int ispeed = speed; + _number(c,714,40,ispeed,3,4,boosted ? COLORS[0] : WHITE); + c.text(838,40,boosted ? "BOOST!" : "NORMAL",3,boosted ? COLORS[0] : MUTED); + }; + + + val _bricks = { !sys.draw.Canvas c -> + c.fillRect(LEFT-4,TOP-4,RIGHT-LEFT+8,4,MUTED); + c.fillRect(LEFT-4,TOP,4,BOTTOM-TOP,0x29435a); + c.fillRect(RIGHT,TOP,4,BOTTOM-TOP,0x29435a); + c.text(376,108,boosted ? "BACK WALL BOOST ACTIVE" : "BREAK THROUGH FOR A BOOST",2,boosted ? COLORS[0] : MUTED); + for( int i = 0; i < bricks#; i++ ) { + if( bricks[i] == 0 ) continue; + int row = i/COLS; + i64 x = LEFT+2+(i%COLS)*BRICK_DX, y = BRICK_TOP+row*BRICK_DY; + c.fillRect(x,y,BRICK_W,BRICK_H,COLORS[row]); + c.fillRect(x,y,BRICK_W,2,WHITE); + } + }; + + val _overlay = { !sys.draw.Canvas c -> + if( phase != PLAY || paused ) { + c.fillRect(246,422,516,108,0x17263a).rect(246,422,516,108,2,0x29435a); + u8[~] title = paused ? "PAUSED" : phase == WON ? "WALL CLEARED!" : phase == LOST ? "GAME OVER" : "READY?"; + c.text(504-(title#*4-1)*4/2,442,title,4,WHITE); + u8[~] help = paused ? "P TO CONTINUE" : phase == WON || phase == LOST ? "R TO PLAY AGAIN" : "SPACE OR CLICK TO SERVE"; + c.text(504-(help#*4-1)*2/2,490,help,2,CYAN); + } + return 0; + }; + + // With this Canvas, we draw into the blank canvas, then "present". The + // underlying graphics lib copies the bits, and we are then free to clear + // and draw again while the old bits continue to be presented. + val _draw = { !sys.draw.Canvas c -> + c.clear(BACKGROUND); + _hud(c); + _bricks(c); + i64 paddle = paddle, ballX = x, ballY = y; + int glowRadius = RADIUS+3; + c.fillRect(paddle-PADDLE_HALF,PADDLE_Y,2*PADDLE_HALF,12,CYAN); + c.fillRect(paddle-PADDLE_HALF+4,PADDLE_Y+2,2*PADDLE_HALF-8,2,WHITE); + c.fillCircle(ballX,ballY,glowRadius,boosted ? 0x672a42 : 0x224b61); + c.fillCircle(ballX,ballY,RADIUS,boosted ? COLORS[0] : WHITE); + _overlay(c); + c.text(24,738,"ARROWS / MOUSE: MOVE SPACE / CLICK: SERVE P: PAUSE R: RESTART Q / ESC: QUIT",2,MUTED); + }; + + // Served and still holding serve key + bool serveHeld; + // Paused and still holding pause key + bool pauseHeld; + // Restart and still holding restart key + bool restartHeld; + // Last mouse position; track moving mouse + int lastMouse; + + // Read and act on the controls + val _input = { sys.draw.Canvas c -> + val gfx = sys.gfx; + bool serve = gfx.key(' ') || gfx.button(gfx.LEFT); + bool pause = gfx.key('P'); + bool restart= gfx.key('R'); + + // Keyboard direction and mouse position + int direction = (gfx.key(KEY_RIGHT) ? 1 : 0)-(gfx.key(KEY_LEFT) ? 1 : 0); + int mouse = c.localX(gfx.mouseX()); + + // Restart requested + restartHeld = debounce( restart, restartHeld, { -> _reset(); sys.audio.stop(); } ); + + // Playing or ready to play game? + if( phase == READY || phase == PLAY ) { + // Flip pause state + pauseHeld = debounce( pause, pauseHeld, { -> paused = !paused; } ); + + // If no key and mouse moved, set paddle to mouse + if( mouse >= 0 && mouse != lastMouse && direction == 0 && !paused ) { + _paddle(mouse*1.0); // Set paddle to mouse + // If READY and not PLAY, ball tracks paddle directly + if( phase == READY ) x = paddle; + } + lastMouse = mouse; + + } + + // Serve requested + serveHeld = debounce( serve, serveHeld, _serve ); + + // Return key direction, so the tick tracking can slide paddle smoothly + return direction; + }; + + val debounce = { bool b, bool bHeld, { int } action -> + if( b && !bHeld ) // Action requested and repeating + action(); // Do action + b; // Dont action again, until 'b' is released + }; + + + // Serve the ball; give it a nominal direction and speed + val _serve = { -> + if( phase == READY && !paused ) { + phase = PLAY; + dx = 0.4; + dy = -_sqrt(1.0-dx*dx); + } + return 0; + }; +}; + +// Fixed-width decimal labels avoid allocating new strings on every frame. +val _number = { !sys.draw.Canvas c, i64 x, i64 y, int value, int digits, int scale, u32 color -> + for( int i = 0; i < digits; i++ ) { + c.text(x+(digits-1-i)*4*scale,y,DIGITS[value%10],scale,color); + value /= 10; + } +}; + +// Short, fading triangle waves; the array initializer builds PCM once at startup. +val _tone = { int period -> + val samples = new i16[~2400]{int i -> + int phase = i%period; + int triangle = phase < period/2 ? phase : period-phase; + return (triangle*4-period)*6000/period*(2400-i)/2400; + }; + int handle = sys.audio.load(samples); + return handle < 0 ? sys.audio.BOOP : handle; +}; + + +// Fast low accuracy sqrt +val _sqrt = { f64 n -> + f64 r = 1.0; + for( int i = 0; i < 8; i++ ) r = (r+n/r)*0.5; + return r; +}; + +val main = { u8[~][] args -> + // Shortcuts + val gfx = sys.gfx, audio = sys.audio; + + // Open a window + if( gfx.open("Simple Breakout",WIDTH,HEIGHT) != gfx.OK ) return 1; + + // Audio setup; pre-specify a series of sounds + audio.open(); // Optional: a missing audio backend leaves play silent. + val sounds = new int[~]{0,_tone(120),_tone(80),audio.BOOP,audio.WIN,audio.LOSE,audio.WIN}; + // Bottom to top: roughly 333..800 Hz, below the old 1000 Hz brick tone. + val brickSounds = new int[~ROWS]{int i -> int period = 144-i*12; _tone(period);}; + + // Setup drawing board + val c = new sys.draw.Canvas(WIDTH,HEIGHT); + + // Setup game contents + val g = new Game; + g._reset(); + + // + int frames = 0, status = gfx.OK; + i64 last_ms = sys.time.monotonic(), pending_ms = 0, frame_ms = last_ms; + + while( status == gfx.OK ) { + if( gfx.key('Q') || gfx.key(gfx.ESCAPE) ) break; + // Physics stays in base coordinates; only drawing and input scale. + if( c.resize(gfx.width(),gfx.height()) ) { + g.lastMouse = c.localX(gfx.mouseX()); + frame_ms = 0; + } + int direction = g._input(c); + i64 now_ms = sys.time.monotonic(), elapsed_ms = now_ms-last_ms; + last_ms = now_ms; + // Drop long stalls instead of teleporting the ball after a window drag. + pending_ms += elapsed_ms < 0 ? 0 : elapsed_ms > 64 ? 64 : elapsed_ms; + while( pending_ms >= STEP_ms ) { g._tick(direction); pending_ms -= STEP_ms; } + if( g.sound != 0 ) { + audio.play(g.sound == 3 ? brickSounds[g.soundDepth-1] : sounds[g.sound]); + g.sound = 0; + } + if( now_ms >= frame_ms ) { + g._draw(c); + status = gfx.presentSize(c.pixels,c.width,c.height); + frame_ms = now_ms+FRAME_ms; + if( args# > 1 && ++frames == 10 ) break; + } + if( status == gfx.OK ) status = gfx.wait(STEP_ms-pending_ms); + } + audio.close(); gfx.close(); + return status == gfx.ERROR ? 1 : 0; +}; diff --git a/docs/chapter31/examples/BubbleSort.smp b/docs/chapter31/examples/BubbleSort.smp new file mode 100644 index 00000000..6bdb13a9 --- /dev/null +++ b/docs/chapter31/examples/BubbleSort.smp @@ -0,0 +1,38 @@ + +// An implementation of +// https://sampleprograms.io/projects/bubble-sort/ +// +// Bubble sort, with reading (parsing) and writing (formatting) the data. + +val sort = { !sys.aryi64 nums -> + sys.aryi64?! more = nums; + while( more ) { + more = null; + for( u32 i = 0; i < nums.len-1; i++ ) + if( nums.buf[i] > nums.buf[i+1] ) { + u32 next = i+1; + more = nums.swap(i,next); + } + } +}; + +// Read one process argument of the form "[ 4, 3, 2, 1]" and print it sorted. +// args[0] is the executable name, as with native C argc/argv. +val main = { u8[~][] args -> + val usage = { -> + sys.io.p("Usage: please provide a list of at least two integers to sort in the format \"[1, 2, 3, 4, 5]\"\n"); + return 0; + }; + if( args# != 2 ) return usage(); + + var nums = sys.aryi64.parseAryI64(args[1]); + if( !nums ) return usage(); + if( nums.len < 2 ) return usage(); + + // Bubble sort array of integers + sort(nums); + + // Print the same bracketed array-list format accepted as input. + nums.str().add('\n').write(1); + return 0; +}; diff --git a/docs/chapter31/examples/Capitalize.smp b/docs/chapter31/examples/Capitalize.smp new file mode 100644 index 00000000..00fdd481 --- /dev/null +++ b/docs/chapter31/examples/Capitalize.smp @@ -0,0 +1,23 @@ + +// An implementation of +// https://sampleprograms.io/projects/capitalize/ + +val main = { u8[~][] args -> + if( args# > 2 ) { + sys.io.p("Use quotes around multiple strings.\n"); + return 0; + } + if( args# != 2 || args[1]# == 0 ) { + sys.io.p("Usage: please provide a string\n"); + return 0; + } + + u8[~] input = args[1]; + var output = new u8[input# + 1]; + u32 len = input#; + sys.ary.copy(output,0,input,0,len); + output[0] = sys.char.toupper(input[0]); + output[input#] = '\n'; + sys.io.p(output); + return 0; +}; diff --git a/docs/chapter31/examples/Clock.smp b/docs/chapter31/examples/Clock.smp new file mode 100644 index 00000000..fb50f84e --- /dev/null +++ b/docs/chapter31/examples/Clock.smp @@ -0,0 +1,128 @@ +// Local clocks; click the button or press Space to switch. Q/Escape exits. +// Any argument runs ten frames, exercising both faces for smoke tests. +u32 GREEN = 0x62ff70, DIM = 0x123d20, BACKGROUND = 0x020b05; + +val main = { u8[~][] args -> + val gfx = sys.gfx; + val time = sys.time; + // The main Canvas + val screen = new sys.draw.Canvas(720,540); + if( gfx.open("Simple digital and analog clocks",screen.width,screen.height) != gfx.OK ) return 1; + + // Button to flip clock style + val button = new sys.draw.Button(220,454,280,52,"ANALOG CLOCK"); + val timers = new sys.time.Timers(); + u32 frame_id = timers.every(33); + if( frame_id == 0 ) { gfx.close(); return 1; } + + bool analog = false, held = false; + int frames = 0, status = gfx.OK; + + // Main event loop + while( status == gfx.OK ) { + bool resized = screen.resize(gfx.width(),gfx.height()); + // Did the user press space bar? + bool space = gfx.key(' '); + // Did the left mouse button go down? + bool down = gfx.button(gfx.LEFT); + // ANd did it go down over this button? + bool click = button.update(screen.localX(gfx.mouseX()),screen.localY(gfx.mouseY()),down); + // If clicked, flip the clock mode + if( click || (space && !held) ) analog = !analog; + held = space; + if( gfx.key('Q') ) break; + // Change button label + button.label = analog ? "DIGITAL CLOCK" : "ANALOG CLOCK"; + // If the next timer event is the every-33-msec event + if( timers.poll(time.monotonic()) == frame_id || resized ) { + // Draw the clock screen and button + _draw(screen,time.now(),analog); + button.draw(screen,3,GREEN,BACKGROUND,DIM); + // Presne the canvas on screen + status = gfx.presentSize(screen.pixels,screen.width,screen.height); + // Testing only: show 5 frames, flip to analog, show 5 more and exit + if( args# > 1 ) { + frames++; + if( frames == 5 ) analog = true; + if( frames == 10 ) break; + } + } + if( status != gfx.OK ) break; + // Stall until next timer event + status = gfx.wait(time.remaining(timers.nextDeadline(),time.monotonic())); + } + gfx.close(); + return status == gfx.ERROR ? 1 : 0; +}; + +val _draw = { !sys.draw.Canvas screen, i64 wall_ms, i64 analog -> + val d = sys.time.local(wall_ms); + screen.clear(BACKGROUND); + screen.text(266,24,"SIMPLE CLOCK",4,GREEN); + if( analog ) _analog(screen,d.hour,d.minute,d.second,d.millisecond); + else _digital(screen,d.hour,d.minute,d.second); + screen.text(298,412,"%(sys.time.formatLocal(wall_ms,sys.time.DATE))",4,GREEN); + screen.text(249,520,"SPACE SWITCH Q OR ESC QUIT",2,GREEN); +}; + +// a..g bits: top, upper-right, lower-right, bottom, lower-left, upper-left, +// middle. Faint unlit bars retain the old LED figure-eight silhouette. +val _digitFont = new u8[~]{ + // 0 1 2 3 4 5 6 7 8 9 + 0x3f, 0x06, 0x5b, 0x4f, 0x66, 0x6d, 0x7d, 0x07, 0x7f, 0x6f +}; +val _digitBars = new u8[~]{ + // x0 y0 x1 y1 + 14, 0, 58, 0, // a: top + 68, 12, 68, 60, // b: upper-right + 68, 84, 68, 132, // c: lower-right + 14, 144, 58, 144, // d: bottom + 4, 84, 4, 132, // e: lower-left + 4, 12, 4, 60, // f: upper-left + 14, 72, 58, 72 // g: middle +}; +val _digit = { !sys.draw.Canvas c, int x, int y, i64 digit -> + int bits = 0 <= digit < _digitFont# ? _digitFont[digit] : 0; + for( int i = 0; i < 7; i++ ) { + u32 color = (bits&(1< + _digit(c, 68,166, hour/10); _digit(c,154,166, hour%10); + _digit(c,284,166,minute/10); _digit(c,370,166,minute%10); + _digit(c,500,166,second/10); _digit(c,586,166,second%10); + for( int i = 0; i < 2; i++ ) { + c.fillCircle(254+i*216,214,6,GREEN); + c.fillCircle(254+i*216,262,6,GREEN); + } + c.text(272,352,"LOCAL TIME 24H",3,GREEN); +}; +val _hand = { !sys.draw.Canvas c, f64 turn, int length, int thickness, u32 color -> + f64 angle = turn*2*sys.math.PI; + int x = 360+sys.math.sin(angle)*length, y = 232-sys.math.cos(angle)*length; + c.line(360,232,x,y,thickness,color); +}; +val _analog = { !sys.draw.Canvas c, int hour, int minute, int second, int millisecond -> + c.circle(360,232,154,3,GREEN); + for( int i = 0; i < 60; i++ ) { + f64 angle = i/60.0*2*sys.math.PI; + bool major = i%5 == 0; + int inner = major ? 133 : 143; + f64 sine = sys.math.sin(angle), cosine = sys.math.cos(angle); + int x0 = 360+sine*inner, y0 = 232-cosine*inner; + int x1 = 360+sine* 149 , y1 = 232-cosine* 149 ; + c.line(x0,y0,x1,y1,major ? 3 : 1,GREEN); + } + c.text(349,100,"12",2,GREEN); c.text(484,227,"3",2,GREEN); + c.text(357,354, "6",2,GREEN); c.text(230,227,"9",2,GREEN); + f64 seconds = second+millisecond/1000.0; + f64 minutes = minute+seconds/60.0; + _hand(c,(hour%12+minutes/60.0)/12.0,78,8,GREEN); + _hand(c,minutes/60.0,112,5,GREEN); + _hand(c,seconds/60.0,128,2,0xc3ffcb); + c.fillCircle(360,232,6,GREEN); +}; diff --git a/docs/chapter31/examples/Dijkstra.smp b/docs/chapter31/examples/Dijkstra.smp new file mode 100644 index 00000000..6591b310 --- /dev/null +++ b/docs/chapter31/examples/Dijkstra.smp @@ -0,0 +1,71 @@ + +// An implementation of +// https://sampleprograms.io/projects/dijkstra/ + +val shortestPath = { !sys.aryi64 matrix, int nodes, int src, int dst -> + i64 infinity = sys.integer.MAX_I64; + var visited = new sys.adt.bitset(); + // All nodes are infinitely far from each other, except the starting point + var dist = new i64[nodes]{ int i -> i == src ? 0 : infinity; }; + + i64 result = -1; + int count = 0; + while( count < nodes && result < 0 ) { + int nearest = -1; + i64 best = infinity; + for( int node = 0; node < nodes; node++ ) + if( !visited.get(node) && dist[node] < best ) { + nearest = node; + best = dist[node]; + } + if( nearest < 0 ) count = nodes; + else { + if( nearest == dst ) return best; + visited.set(nearest); + for( int node = 0; node < nodes; node++ ) { + u32 index = nearest*nodes + node; + i64 weight = matrix.get(index); + if( weight > 0 && !visited.get(node) && best+weight < dist[node] ) + dist[node] = best+weight; + } + } + count++; + } + return result; +}; + +val usage = { -> + sys.io.p("Usage: please provide three inputs: a serialized matrix, a source node and a destination node\n"); + return 0; +}; + +val main = { u8[~][] args -> + // Exactly 3 args + if( args# != 4 ) return usage(); + // First is a serialized square matrix of positive numbers + var matrix = sys.aryi64.parseAryI64(args[1]); + if( !matrix ) return usage(); + if( !matrix.len ) return usage(); + // All numbers are positive + for( u32 i = 0; i < matrix.len; i++ ) + if( matrix.get(i) < 0 ) return usage(); + // Matrix is square + int nodes = 0; + while( nodes*nodes < matrix.len ) nodes++; + if( nodes*nodes != matrix.len ) + return usage(); // Not a square matrix + + // src,dst are values within the matrix + i64 src = sys.aryu8.atoi(args[2]); + i64 dst = sys.aryu8.atoi(args[3]); + if( src < 0 || src >= nodes || dst < 0 || dst >= nodes ) + return usage(); // Source and destination land within the graph + + int source = src, destination = dst; + i64 cost = shortestPath(matrix,nodes,source,destination); + if( cost >= 0 ) { + new sys.aryu8().num(cost).add('\n').write(1); + return 0; + } + return usage(); +}; diff --git a/docs/chapter31/examples/FileIO.smp b/docs/chapter31/examples/FileIO.smp new file mode 100644 index 00000000..59b3159e --- /dev/null +++ b/docs/chapter31/examples/FileIO.smp @@ -0,0 +1,52 @@ + +// An implementation of +// https://sampleprograms.io/projects/file-input-output/ + +val FILE = "output.txt"; + +val main = { u8[~][] args -> + var str = new sys.aryu8(); + str.addAry("Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.\n"); + str.addAry("Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.\n"); + str.addAry("Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur.\n"); + str.addAry("Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.\n"); + + // Create + i32 fd = sys.io.create(FILE); + if( fd == -1 ) return _error(); + // Write + u32 len = str.len; + int wrote = sys.io.writeOff(fd,str.buf,0,len); + if( wrote == -1 ) return _error(); + if( wrote != str.len ) return _error2(-2); + // Close + if( sys.io.close(fd) != 0 ) return _error(); + + // Open + i32 fd2 = sys.io.open(FILE); + if( fd2 == -1 ) return _error(); + // Read + var got = sys.io.read(fd2); + if( !got ) return _error(); + if( got# != str.len ) return _error2(-3); + // Close + if( sys.io.close(fd2) != 0 ) return _error(); + + // Check contents are equal + if( sys.ary.cmp(got,0,str.buf,0,len) ) + return _error2(-4); + + // Remove + if( sys.io.remove(FILE) != 0 ) return _error(); + + sys.io.p("File I/O succeeded\n"); + return 0; +}; + +val _error2 = { i32 errno -> + sys.io.remove(FILE); + new sys.aryu8().addAry("Failed with error code ").num(errno).add('\n').write(sys.libc.STDERR); + sys.libc._exit(errno); +}; + +val _error = { -> _error2(sys.libc.errno()); }; diff --git a/docs/chapter31/examples/Graphics.smp b/docs/chapter31/examples/Graphics.smp new file mode 100644 index 00000000..1878e97d --- /dev/null +++ b/docs/chapter31/examples/Graphics.smp @@ -0,0 +1,26 @@ +// Optional graphics smoke test: pixels are drawn entirely in Simple. +// Pass any argument for a short, self-closing test; otherwise close or press Esc. +val main = { u8[~][] args -> + if( sys.gfx.open("Simple pixels",320,240) != sys.gfx.OK ) return 1; + val c = new sys.draw.Canvas(320,240); + int result = sys.gfx.OK; + bool dirty = true; + int frames = 0; + while( result == sys.gfx.OK ) { + if( c.resize(sys.gfx.width(),sys.gfx.height()) ) dirty = true; + if( dirty ) { + // The gradient fills the window, including non-4:3 shapes. + int dx = c.width > 1 ? c.width-1 : 1, dy = c.height > 1 ? c.height-1 : 1; + for( int y = 0; y < c.height; y++ ) + for( int x = 0; x < c.width; x++ ) + c.pixels[y*c.width+x] = (x*255/dx << 16) | (y*255/dy << 8) | 64; + result = sys.gfx.presentSize(c.pixels,c.width,c.height); + if( result != sys.gfx.OK ) break; + dirty = false; + } + result = sys.gfx.poll(true); + if( args# > 1 && ++frames == 5 ) break; + } + sys.gfx.close(); + return result == sys.gfx.ERROR ? 1 : 0; +}; diff --git a/docs/chapter31/examples/README.md b/docs/chapter31/examples/README.md new file mode 100644 index 00000000..05dcf6cb --- /dev/null +++ b/docs/chapter31/examples/README.md @@ -0,0 +1,119 @@ +# Runnable examples + +These programs live beside the documentation so readers can find and run them. +Their non-graphical native regression tests run as part of `make tests`. +All four graphical demos support window resizing. Clock, Tic-tac-toe, and +Breakout scale their base layouts uniformly and center them in the window; +mouse input follows the same transform. Breakout keeps its physics in base +coordinates, so resizing preserves the current game and ball speed. The pixel +gradient fills the entire window at its new resolution. +The optional [pixel-window example](Graphics.smp) uses MiniFB; see +[graphics setup](../../src/main/smp/sys/gfx.md). `make run-graphics` opens it explicitly. +The [graphical tic-tac-toe](TicTacToeGraphical.smp) uses the Simple +[drawing library](../../src/main/smp/sys/draw/README.md). Run it with +`make run-graphical-tictactoe`; click a cell or press 1–9, R/Space to +replay, and Q/Escape to quit. The terminal game below remains available. +Optional [background audio](../../src/main/smp/sys/audio.md) supplies soft move and win/loss cues. + +The [digital and analog clock](Clock.smp) demonstrates the [time library](../../src/main/smp/sys/time/README.md), +green seven-segment digits, smooth clock hands, and a reusable software button. +Run `make run-clock`; click the button or press Space to switch faces, +and Q/Escape to exit. Both faces show system-local time. +`make clock-example` builds it without starting a window. + +The [Breakout game](Breakout.smp) has 24 columns and 8 rows, with colors and +point values by depth: 1 at the bottom through 8 at the top, 864 points total. +Clear the wall before losing all three balls. Mouse movement or the arrow keys +move the paddle; Space/left click serves, P pauses, R restarts, Q/Escape exits. +Run `make run-breakout` or build only with `make breakout`. +The familiar paddle, serve, and limited-ball rules follow +[Atari's Breakout instructions](https://atari.com/pages/breakout). + +The deepest row reached with the current ball sets the base speed: 320 pixels/second plus 35 for +each additional depth. After touching the back wall, hitting the top of a brick +activates a **one-time 1.65x speed boost**; side/front hits do not. Returning to +the paddle disarms that trip's back-wall opportunity. Losing a ball resets depth +and boost, so each new ball starts at 320 pixels/second and can earn its own +back-wall boost. Edge hits on the paddle give a wider +rebound than center hits. Clear all bricks to win; no new wall replaces them. + +Physics uses fixed 8 ms ticks with movement split into steps of at most two +pixels, including at boosted speed. Rendering runs roughly every 16 ms. The +brick and sound tables demonstrate array initializers; the short bounce tones +use read-only PCM arrays made by index functions. Brick boops rise in pitch with +row depth, from about 333 Hz at the bottom to 800 Hz at the top. Audio is optional. Native +tests in `BreakoutTest` exercise collisions, scoring, lives, pause, paddle angles, +the boost, and clearing the whole wall without a display or audio device. + +From `chapter31`, build the tic-tac-toe executable (without starting it): + +```sh +make lib tictactoe +``` + +Run the Windows build from PowerShell: + +```powershell +.\build\examples\x86_64_v2_win64\TicTacToe.exe +``` + +Or from Command Prompt (`cmd.exe`): + +```bat +.\build\examples\x86_64_v2_win64\TicTacToe.exe +``` + +Or from Bash (Cygwin, using the Windows build): + +```bash +./build/examples/x86_64_v2_win64/TicTacToe.exe +``` + +The Windows executable uses Cygwin's runtime; its `bin` directory must be on +`PATH` (as it is when building with Cygwin GCC). + +For a native Linux build, run these commands from this same `chapter31` +directory in WSL. Separate Java and native output directories let the Windows +and Linux builds coexist: + +```sh +make lib tictactoe CLZDIR=build/classes-linux +./build/examples/x86_64_v2_SystemV/TicTacToe +``` + +From PowerShell, prefix either command with `wsl -d Ubuntu-24.04 --`. +On a standalone Linux checkout, `CLZDIR` can be omitted. +The compiler's `--link` option produces an executable without running it; +`--norun` continues to produce object files only. + +`TicTacToe.smp` currently prints the welcome, square numbering, and empty board, +then waits for a move. Press **1–9** without Enter to place X, or +**q**, Escape, Ctrl-C, or Ctrl-D to quit. Enter is silently ignored; other +invalid keys and occupied squares prompt again without taking a turn. The board +is printed after each player and CPU move; only accepted move digits are echoed. +Play continues until someone wins or the board is +full. The CPU takes an immediate win, blocks an immediate loss, then prefers +the center, corners, and edges. + +Other examples are Hello World (`A_helloWorld.smp`), `BubbleSort.smp`, +`Capitalize.smp`, `Dijkstra.smp`, and `FileIO.smp`. The latter creates, checks, +and removes `output.txt` in the working directory. + +## Single-keystroke input + +`sys.io.getch()` blocks for one byte without terminal editing or echo. It returns +0–255 for a byte, or -1 for EOF or an error. On -1, `sys.libc.errno()` is +`sys.libc.EOF` (-1) for end-of-input, otherwise the OS error code. +Terminal Ctrl-C and Ctrl-D are bytes 3 +and 4, so the application decides how to handle them. Unicode and function keys +may produce multiple bytes; this is an ASCII-oriented byte API, not a key-event +decoder. + +The small C runtime adapter uses [POSIX terminal modes](https://man7.org/linux/man-pages/man3/termios.3.html), +including Cygwin on Windows. It restores the saved mode before returning, +including after an interrupted read. Files and pipes use an ordinary one-byte +read. `make test CLASS=TerminalInputTest` runs the Java regression tests for +redirected input, errors, prompt output, Enter, and Escape. Check terminal +editing, echo, and mode restoration by running the executable in a terminal. +`make test CLASS=TicTacToeTest` checks complete games, all eight winning lines, +draws, occupied squares, and CPU blocking. diff --git a/docs/chapter31/examples/TicTacToe.smp b/docs/chapter31/examples/TicTacToe.smp new file mode 100644 index 00000000..ee4e3182 --- /dev/null +++ b/docs/chapter31/examples/TicTacToe.smp @@ -0,0 +1,132 @@ +// Player is X, CPU is O. Squares are numbered left-to-right, top-to-bottom. +val main = { u8[~][] args -> + sys.io.p("Tic-tac-toe!\nYou are X; the CPU is O. You go first.\n"); + sys.io.p("Press a square's number (no Enter needed), or q/Esc to quit.\n"); + sys.io.p("Squares:\n 1 | 2 | 3 \n---+---+---\n 4 | 5 | 6 \n---+---+---\n 7 | 8 | 9 \n\n"); + val board = new u8[9]{ int i -> ' '; }; // Initialize the board + // Draw empty board + _draw(board); + + while( true ) { + sys.io.p("Your move (1-9): "); + // Valid user move 1-9, or 0 for quitting + int square = _validMove(board) - 1; + if( square < 0 ) return 0; + // Set user choice; print board + board[square] = 'X'; + sys.io.p("\n"); + _draw(board); + // A winner? + if( _finished(board) ) return 0; + // Compute CPU move + int reply = _cpu(board); + // Set CPU choice; print board + board[reply] = 'O'; + sys.io.p("CPU plays %(reply+1).\n"); + _draw(board); + // A winner? + if( _finished(board) ) return 0; + } +}; + +// Return with a valid user move 1-9, or 0 to exit +val _validMove = { u8[~] board -> + while( true ) { + int key = sys.io.getch(); + if( key == -1 && sys.libc.errno() != sys.libc.EOF ) { + sys.io.err("\nUnable to read the keyboard.\n"); + return 0; + } + // Various quitting conditions + if( key == -1 || key == 'q' || key == 'Q' || key == 27 || key == 3 || key == 4 ) { + sys.io.p("\nGoodbye!\n"); + return 0; + } + // Ignore CR/LF + if( key == '\r' || key == '\n' ) continue; + + // Valid choice + if( key < '1' || key > '9' ) { + sys.io.p("\nChoose a square from 1 to 9: "); + continue; + } + if( board[key-'1'] != ' ' ) { + sys.io.p("\nThat square is occupied. Your move (1-9): "); + continue; + } + sys.io.p("%c(key)"); + return key-'0'; + } +}; + +// Return the winning mark, or zero. +val _winner = { u8[~] board -> + for( int i = 0; i < 3; i++ ) { + int row = i*3; + if( board[row] != ' ' && board[row] == board[row+1] && board[row] == board[row+2] ) + return board[row]; + if( board[i] != ' ' && board[i] == board[i+3] && board[i] == board[i+6] ) + return board[i]; + } + if( board[4] != ' ' ) { + if( board[0] == board[4] && board[4] == board[8] ) return board[4]; + if( board[2] == board[4] && board[4] == board[6] ) return board[4]; + } + return 0; +}; + +val _finished = { u8[~] board -> + int winner = _winner(board); + if( winner == 'X' ) { sys.io.p("You win!\n"); return true; } + if( winner == 'O' ) { sys.io.p("CPU wins!\n"); return true; } + for( int i = 0; i < board#; i++ ) + if( board[i] == ' ' ) return false; + sys.io.p("It's a draw!\n"); + return true; +}; + +// Try each empty square, restoring it before returning. +val _threat = { u8[] board, u8 mark -> + for( int i = 0; i < board#; i++ ) { + if( board[i] == ' ' ) { + board[i] = mark; + bool wins = _winner(board) == mark; + board[i] = ' '; // Restore board + if( wins ) return i; + } + } + return -1; +}; + +// Win if possible, otherwise block, then prefer center, corners, and edges. +// Called only after _finished has ruled out a full board. +val _cpu = { u8[] board -> + // If O can win, do so + int win = _threat(board,'O'); + if( win >= 0 ) return win; + // If X will win next move, block + int block = _threat(board,'X'); + if( block >= 0 ) return block; + // If center is open, take it + if( board[4] == ' ' ) return 4; + // If a corner is open, take it + for( int i = 0; i < board#; i += 2 ) + if( board[i] == ' ' ) return i; + // Take whatever is available + for( int i = 0; i < board#; i++ ) + if( board[i] == ' ' ) return i; + return -1; +}; + +val _draw = { u8[~] board -> + val out = new sys.aryu8(); + for( int row = 0; row < 3; row++ ) { + for( int col = 0; col < 3; col++ ) { + out.add(' ').add(board[row*3+col]).add(' '); + if( col < 2 ) out.add('|'); + } + out.add('\n'); + if( row < 2 ) out.addAry("---+---+---\n"); + } + out.write(sys.libc.STDOUT); +}; diff --git a/docs/chapter31/examples/TicTacToeGraphical.smp b/docs/chapter31/examples/TicTacToeGraphical.smp new file mode 100644 index 00000000..72ee6522 --- /dev/null +++ b/docs/chapter31/examples/TicTacToeGraphical.smp @@ -0,0 +1,169 @@ +// Player is X, CPU is O. Squares are numbered left-to-right, top-to-bottom. +// Graphical tic-tac-toe; the same strategy as TicTacToe.smp. +// Click an empty square or press 1-9. R/Space replays; Q/Escape quits. +// Pass any argument for a five-poll window smoke test. +val main = { u8[~][] args -> + val screen = new sys.draw.Canvas(600,780); + val board = new u8[9]; + _reset(board); + if( sys.gfx.open("Simple tic-tac-toe",screen.width,screen.height) != sys.gfx.OK ) return 1; + sys.audio.open(); // Audio is optional; failure leaves the game silent. + _draw(screen,board,-1); + int result = sys.gfx.presentSize(screen.pixels,screen.width,screen.height); + bool mouseHeld = false, keyHeld = false, replayHeld = false; + int hover = -1, frames = 0; + + while( result == sys.gfx.OK ) { + result = sys.gfx.wait(17); + if( result != sys.gfx.OK ) break; + if( sys.gfx.key('Q') ) break; + bool down = sys.gfx.button(sys.gfx.LEFT); + bool replay = sys.gfx.key('R') || sys.gfx.key(' '); + bool resized = screen.resize(sys.gfx.width(),sys.gfx.height()); + int square = _square(screen.localX(sys.gfx.mouseX()),screen.localY(sys.gfx.mouseY())); + bool dirty = resized || square != hover; + hover = square; + if( replay && !replayHeld ) { sys.audio.stop(); _reset(board); dirty = true; } + bool digit = false; + int choice = down && !mouseHeld ? square : -1; + for( int i = 0; i < 9; i++ ) { + int key = '1'+i; + if( sys.gfx.key(key) ) { + digit = true; + if( !keyHeld ) choice = i; + } + } + if( !(replay && !replayHeld) && _move(board,choice) ) { + sys.audio.play(_sound(board)); + dirty = true; + } + mouseHeld = down; + keyHeld = digit; + replayHeld = replay; + if( dirty ) { + _draw(screen,board,hover); + result = sys.gfx.presentSize(screen.pixels,screen.width,screen.height); + } + if( args# > 1 && ++frames == 5 ) break; + } + sys.audio.close(); + sys.gfx.close(); + return result == sys.gfx.ERROR ? 1 : 0; +}; + +// Called only for an accepted move; invalid input never requests a sound. +val _sound = { u8[~] board -> + int winner = _winner(board); + return winner == 'X' ? sys.audio.WIN : winner == 'O' ? sys.audio.LOSE : sys.audio.BOOP; +}; + +val _reset = { u8[] board -> + for( int i = 0; i < 9; i++ ) board[i] = ' '; +}; +val _square = { int x, int y -> + if( x < 48 || x >= 552 || y < 168 || y >= 672 ) return -1; + return (y-168)/168*3+(x-48)/168; +}; + +// One player turn followed by one CPU turn. Invalid/finished moves do nothing. +val _move = { u8[] board, int square -> + if( square < 0 || square >= 9 || board[square] != ' ' || _finished(board) ) return false; + board[square] = 'X'; + if( !_finished(board) ) { + int reply = _cpu(board); + if( reply >= 0 ) board[reply] = 'O'; + } + return true; +}; + +val _finished = { u8[~] board -> + if( _winner(board) ) return true; + for( int i = 0; i < 9; i++ ) if( board[i] == ' ' ) return false; + return true; +}; + +val _winningLine = { u8[~] board -> + for( int i = 0; i < 3; i++ ) { + int row = i*3; + if( board[row] != ' ' && board[row] == board[row+1] && board[row] == board[row+2] ) return i; + if( board[i] != ' ' && board[i] == board[i+3] && board[i] == board[i+6] ) return 3+i; + } + if( board[4] != ' ' ) { + if( board[0] == board[4] && board[4] == board[8] ) return 6; + if( board[2] == board[4] && board[4] == board[6] ) return 7; + } + return -1; +}; +// Return the winning mark, or zero. +val _winner = { u8[~] board -> + int line = _winningLine(board); + return line < 0 ? 0 : line < 3 ? board[line*3] : line < 6 ? board[line-3] : board[4]; +}; + +// Try each empty square, restoring it before returning. +val _threat = { u8[] board, u8 mark -> + for( int i = 0; i < 9; i++ ) + if( board[i] == ' ' ) { + board[i] = mark; + bool wins = _winner(board) == mark; + board[i] = ' '; // Restore board + if( wins ) return i; + } + return -1; +}; +// Win if possible, otherwise block, then prefer center, corners, and edges. +// Called only after _finished has ruled out a full board. +val _cpu = { u8[] board -> + // If O can win, do so + int win = _threat(board,'O'); + if( win >= 0 ) return win; + // If X will win next move, block + int block = _threat(board,'X'); + if( block >= 0 ) return block; + // If center is open, take it + if( board[4] == ' ' ) return 4; + // If a corner is open, take it + for( int i = 0; i < 9; i += 2 ) if( board[i] == ' ' ) return i; + // Take whatever is available + for( int i = 0; i < 9; i++ ) if( board[i] == ' ' ) return i; + return -1; +}; + +val _draw = { !sys.draw.Canvas screen, u8[~] board, int hover -> + u32 background = 0x142e36, paper = 0xf2eddf, ink = 0x35535a; + u32 cross = 0xe47b57, ring = 0x248b89, accent = 0xf0c778; + int winner = _winner(board); + bool finished = _finished(board); + screen.clear(background); + screen.text(48,34,"TIC TAC TOE",6,paper); + screen.fillRect(48,90,504,3,ink); + screen.text(48,116,finished ? (winner == 'X' ? "YOU WIN!" : winner == 'O' ? "CPU WINS" : "DRAW") : "YOUR TURN",4,accent); + screen.line(428,112,450,134,5,cross).line(450,112,428,134,5,cross); + screen.circle(496,123,13,5,0x70c9bf); + screen.text(428,145,"YOU",2,0xa2b9b7); + screen.text(484,145,"CPU",2,0xa2b9b7); + screen.fillRect(48,168,504,504,paper); + if( !finished && hover >= 0 && hover < 9 && board[hover] == ' ' ) + screen.fillRect(48+(hover%3)*168,168+hover/3*168,168,168,0xd9e8de); + for( int i = 1; i < 3; i++ ) { + screen.fillRect(48+i*168-3,168,6,504,ink); + screen.fillRect(48,168+i*168-3,504,6,ink); + } + for( int i = 0; i < 9; i++ ) { + int cx = 132+(i%3)*168, cy = 252+i/3*168; + if( board[i] == 'X' ) + screen.line(cx-38,cy-38,cx+38,cy+38,12,cross).line(cx+38,cy-38,cx-38,cy+38,12,cross); + else if( board[i] == 'O' ) screen.circle(cx,cy,48,11,ring); + else screen.text(cx-6,cy-10,i == 0 ? "1" : i == 1 ? "2" : i == 2 ? "3" : + i == 3 ? "4" : i == 4 ? "5" : i == 5 ? "6" : i == 6 ? "7" : i == 7 ? "8" : "9",4,0x95a59e); + } + int line = _winningLine(board); + if( line >= 0 ) { + int first = line < 3 ? line*3 : line < 6 ? line-3 : line == 6 ? 0 : 2; + int last = line < 3 ? first+2 : line < 6 ? first+6 : line == 6 ? 8 : 6; + screen.line(132+(first%3)*168,252+first/3*168,132+(last%3)*168,252+last/3*168,5,0xeab64e); + } + screen.text(48,704,"CLICK A SQUARE OR PRESS 1-9",3,paper); + screen.text(48,738,"R OR SPACE REPLAY Q OR ESC QUIT",3,0xa2b9b7); + screen.rect(48,168,504,504,3,ink); +}; diff --git a/graphics.mk b/graphics.mk new file mode 100644 index 00000000..2b557eea --- /dev/null +++ b/graphics.mk @@ -0,0 +1,78 @@ +# Optional MiniFB build, pinned independently of Simple's default build. +# A C-only GDI/X11 subset: no OpenGL, C++ wrapper, examples, or CMake required. +MINIFB_REV := f92be8e966f194004853c10196e704f4510f58d4 +MINIFB_SRC := lib/minifb-$(MINIFB_REV) +MINIFB_ARCHIVE := lib/minifb-$(MINIFB_REV).tar.gz +MINIFB_STAMP := $(MINIFB_SRC)/.simple-$(MINIFB_REV) +MINIFB_COMMON := MiniFB_common MiniFB_cpu_x86 MiniFB_internal MiniFB_stretch \ + MiniFB_stretch_sse2 MiniFB_stretch_avx2 MiniFB_stretch_neon MiniFB_timer MiniFB_utf8 +ifeq ($(OS),Windows_NT) + GRAPHICS_CC := x86_64-w64-mingw32-gcc + GRAPHICS_LIB := $(RELEASE)/$(CPU_ABI)/simple_minifb.dll + MINIFB_PLATFORM := windows/WinMiniFB + MINIFB_LIBS := -lgdi32 -luser32 -lwinmm + MINIFB_FLAGS := -D_WIN32_WINNT=0x0601 +else + GRAPHICS_CC := gcc + GRAPHICS_LIB := $(RELEASE)/$(CPU_ABI)/libsimple_minifb.so + MINIFB_PLATFORM := x11/X11MiniFB x11/X11MiniFB_scale_funcs x11/X11MiniFB_text \ + MiniFB_linux MiniFB_evdev_keys + MINIFB_LIBS := -lX11 -lm + MINIFB_FLAGS := -fPIC -D_POSIX_C_SOURCE=200809L +endif +MINIFB_SOURCES = $(addprefix $(MINIFB_SRC)/src/,$(addsuffix .c,$(MINIFB_COMMON) $(MINIFB_PLATFORM))) +GRAPHICS_EXAMPLE := $(GAME_DIR)/Graphics$(if $(filter Windows_NT,$(OS)),.exe,) +GRAPHICAL_TICTACTOE := $(GAME_DIR)/TicTacToeGraphical$(if $(filter Windows_NT,$(OS)),.exe,) +CLOCK_EXAMPLE := $(GAME_DIR)/Clock$(if $(filter Windows_NT,$(OS)),.exe,) +BREAKOUT := $(GAME_DIR)/Breakout$(if $(filter Windows_NT,$(OS)),.exe,) + +.PHONY: breakout run-breakout +breakout: $(BREAKOUT) +$(BREAKOUT): docs/examples/Breakout.smp $(CLZDIR)/test/.ttag $(RELEASE_SYS) $(RELEASE_CRT) graphics.mk + @$(JVM) com.seaofnodes.simple.Simple --link --cpu $(CPU_PORT) --abi $(CALL_CONV) -L $(dir $(RELEASE_SYS)) -o $(GAME_DIR)/Breakout.o $< +run-breakout: graphics audio breakout + SIMPLE_MINIFB="$(abspath $(GRAPHICS_LIB))" SIMPLE_MINIAUDIO="$(abspath $(AUDIO_LIB))" $(BREAKOUT) + +.PHONY: clock-example run-clock +clock-example: $(CLOCK_EXAMPLE) +$(CLOCK_EXAMPLE): docs/examples/Clock.smp $(CLZDIR)/test/.ttag $(RELEASE_SYS) $(RELEASE_CRT) graphics.mk + @$(JVM) com.seaofnodes.simple.Simple --link --cpu $(CPU_PORT) --abi $(CALL_CONV) -L $(dir $(RELEASE_SYS)) -o $(GAME_DIR)/Clock.o $< +run-clock: graphics clock-example + SIMPLE_MINIFB="$(abspath $(GRAPHICS_LIB))" $(CLOCK_EXAMPLE) + +.PHONY: graphics graphics-example run-graphics +.PHONY: graphical-tictactoe run-graphical-tictactoe +graphical-tictactoe: $(GRAPHICAL_TICTACTOE) +$(GRAPHICAL_TICTACTOE): docs/examples/TicTacToeGraphical.smp $(CLZDIR)/test/.ttag $(RELEASE_SYS) $(RELEASE_CRT) graphics.mk + @$(JVM) com.seaofnodes.simple.Simple --link --cpu $(CPU_PORT) --abi $(CALL_CONV) -L $(dir $(RELEASE_SYS)) -o $(GAME_DIR)/TicTacToeGraphical.o $< + +run-graphical-tictactoe: graphics audio graphical-tictactoe + SIMPLE_MINIFB="$(abspath $(GRAPHICS_LIB))" SIMPLE_MINIAUDIO="$(abspath $(AUDIO_LIB))" $(GRAPHICAL_TICTACTOE) +graphics: $(GRAPHICS_LIB) + +lib libs init: $(MINIFB_STAMP) + +$(MINIFB_ARCHIVE): + @$(call download-library,https://codeload.github.com/emoon/minifb/tar.gz/$(MINIFB_REV)) + +$(MINIFB_STAMP): $(MINIFB_ARCHIVE) + @mkdir -p $(MINIFB_SRC) + @tar -xzf $< --strip-components=1 -C $(MINIFB_SRC) + @touch $@ + +$(GRAPHICS_LIB): $(MINIFB_STAMP) src/main/c/simple_minifb.c src/main/c/simple_graphics.h graphics.mk + @echo "building " $@ + @mkdir -p $(dir $@) + @$(GRAPHICS_CC) -shared -O2 -Wall -Wextra -Wno-unused-parameter -Wno-implicit-fallthrough $(MINIFB_FLAGS) \ + -I$(MINIFB_SRC)/include -I$(MINIFB_SRC)/src \ + src/main/c/simple_minifb.c $(MINIFB_SOURCES) $(MINIFB_LIBS) -o $@ + @cp $(MINIFB_SRC)/LICENSE $(dir $@)MiniFB-LICENSE + +# This executable also builds without MiniFB, to exercise the missing-backend path. +graphics-example: $(GRAPHICS_EXAMPLE) +$(GRAPHICS_EXAMPLE): docs/examples/Graphics.smp $(CLZDIR)/test/.ttag $(RELEASE_SYS) $(RELEASE_CRT) graphics.mk + @$(JVM) com.seaofnodes.simple.Simple --link --cpu $(CPU_PORT) --abi $(CALL_CONV) -L $(dir $(RELEASE_SYS)) -o $(GAME_DIR)/Graphics.o $< + +# An interactive target, never part of default/tests. +run-graphics: graphics graphics-example + SIMPLE_MINIFB="$(abspath $(GRAPHICS_LIB))" $(GRAPHICS_EXAMPLE) diff --git a/src/main/c/simple_audio.c b/src/main/c/simple_audio.c new file mode 100644 index 00000000..b8ed62de --- /dev/null +++ b/src/main/c/simple_audio.c @@ -0,0 +1,40 @@ +#include "simple_audio.h" +#include +#include +#include +#include + +static const struct simple_audio_api *api; +static void *library; + +int32_t simple_audio_open(void) { + const char *path = getenv("SIMPLE_MINIAUDIO"); + if (path && strcmp(path,"off")==0) return -1; + if (!api) { + if (!path || !*path) return -1; // Optional: games may run silently. + library = dlopen(path,RTLD_NOW | RTLD_LOCAL); + if (!library) { + fprintf(stderr,"Simple audio: cannot load backend '%s': %s\n",path,dlerror()); + return -1; + } + const struct simple_audio_api *(*get_api)(void) = + (const struct simple_audio_api *(*)(void))dlsym(library,"simple_miniaudio_api"); + const struct simple_audio_api *candidate = get_api ? get_api() : NULL; + if (!candidate || candidate->version!=SIMPLE_AUDIO_VERSION || !candidate->open || + !candidate->load || !candidate->play || !candidate->stop || + !candidate->playing || !candidate->close) { + fprintf(stderr,"Simple audio: incompatible backend; rebuild with make audio.\n"); + dlclose(library); + library=NULL; + return -1; + } + api=candidate; + atexit(api->close); + } + return api->open(); +} +int32_t simple_audio_load(const int16_t *samples, uint32_t count) { return api ? api->load(samples,count) : -1; } +int32_t simple_audio_play(int32_t sound) { return api ? api->play(sound) : -1; } +int32_t simple_audio_stop(void) { return api ? api->stop() : 0; } +int32_t simple_audio_playing(void) { return api ? api->playing() : 0; } +int32_t simple_audio_close(void) { if (api) api->close(); return 0; } diff --git a/src/main/c/simple_audio.h b/src/main/c/simple_audio.h new file mode 100644 index 00000000..77cce530 --- /dev/null +++ b/src/main/c/simple_audio.h @@ -0,0 +1,16 @@ +#ifndef SIMPLE_AUDIO_H +#define SIMPLE_AUDIO_H +#include + +// Main-thread API. Samples are copied; no Simple heap pointer is retained. +struct simple_audio_api { + int32_t version; + int32_t (*open)(void); + int32_t (*load)(const int16_t *, uint32_t); + int32_t (*play)(int32_t); + int32_t (*stop)(void); + int32_t (*playing)(void); + void (*close)(void); +}; +#define SIMPLE_AUDIO_VERSION 1 +#endif diff --git a/src/main/c/simple_crt.c b/src/main/c/simple_crt.c index 438ae5f9..e50042c2 100644 --- a/src/main/c/simple_crt.c +++ b/src/main/c/simple_crt.c @@ -3,9 +3,32 @@ #include #include #include +#include #include #include +// Fixed-semantics compiler intrinsics. Keep these definitions for indirect +// calls; direct calls may inline to representation-preserving register moves. +int64_t simple_f64_bits(double value) { + int64_t bits; + memcpy(&bits, &value, sizeof(bits)); + return bits; +} +double simple_f64_from_bits(int64_t bits) { + double value; + memcpy(&value, &bits, sizeof(value)); + return value; +} + +// Floating remainder's machine instruction uses this memory-preserving helper. +double simple_f64_mod(double x, double y) { + // fmod can set errno for NaN-producing inputs; arithmetic leaves it alone. + int saved_errno = errno; + double result = fmod(x, y); + errno = saved_errno; + return result; +} + // errno may be thread-local or a macro calling a platform accessor. int32_t simple_errno(void) { return errno; } int32_t simple_set_errno(int32_t error) { errno = error; return -1; } diff --git a/src/main/c/simple_graphics.c b/src/main/c/simple_graphics.c new file mode 100644 index 00000000..a35c28a6 --- /dev/null +++ b/src/main/c/simple_graphics.c @@ -0,0 +1,108 @@ +#define _POSIX_C_SOURCE 200809L +#include "simple_graphics.h" +#include +#include +#include +#include +#include + +#ifdef __CYGWIN__ +#define BACKEND_NAME "simple_minifb.dll" +#define BACKEND_ABI "x86_64_v2_win64" +#else +#define BACKEND_NAME "libsimple_minifb.so" +#define BACKEND_ABI "x86_64_v2_SystemV" +#endif + +// Executable-relative paths work even when launched outside the checkout. +// Working-directory paths also cover test executables and chapter/root shells. +static void *find_backend(void) { + char executable[4096], path[8192]; + ssize_t n=readlink("/proc/self/exe",executable,sizeof(executable)-1); + if (n>0 && n<(ssize_t)sizeof(executable)-1) { + executable[n]=0; + char *slash=strrchr(executable,'/'); + if (slash) { + *slash=0; + const char *relative[]={"/" BACKEND_NAME, + "/../../release/" BACKEND_ABI "/" BACKEND_NAME, + "/../release/" BACKEND_ABI "/" BACKEND_NAME}; + for (unsigned i=0;iversion != SIMPLE_GRAPHICS_VERSION || + !candidate->open || !candidate->present || !candidate->poll || + !candidate->mouse_x || !candidate->mouse_y || !candidate->button || + !candidate->key || !candidate->close || !candidate->wait || + !candidate->width || !candidate->height || !candidate->present_size) { + fprintf(stderr, "Simple graphics: incompatible MiniFB backend '%s'. Rebuild with make graphics.\n", path); + dlclose(library); + library = NULL; + return -1; + } + api = candidate; + // Keep the library loaded until process exit; its window callbacks may + // still be registered. Closing a window releases its native resources. + atexit(api->close); + return 0; +} + +int32_t simple_gfx_open(const char *title, uint32_t width, uint32_t height) { + return load_graphics() ? -1 : api->open(title, width, height); +} +int32_t simple_gfx_present(const uint32_t *pixels, uint32_t count) { + return api ? api->present(pixels, count) : -1; +} +int32_t simple_gfx_present_size(const uint32_t *pixels, uint32_t count, uint32_t width, uint32_t height) { + return api ? api->present_size(pixels, count, width, height) : -1; +} +uint32_t simple_gfx_width(void) { return api ? api->width() : 0; } +uint32_t simple_gfx_height(void) { return api ? api->height() : 0; } +int32_t simple_gfx_poll(int32_t wait) { return api ? api->poll(wait) : -1; } +int32_t simple_gfx_mouse_x(void) { return api ? api->mouse_x() : 0; } +int32_t simple_gfx_mouse_y(void) { return api ? api->mouse_y() : 0; } +int32_t simple_gfx_button(int32_t button) { return api ? api->button(button) : 0; } +int32_t simple_gfx_key(int32_t key) { return api ? api->key(key) : 0; } +int32_t simple_gfx_close(void) { if (api) api->close(); return 0; } +int32_t simple_gfx_wait(int64_t timeout) { return api ? api->wait(timeout) : -1; } diff --git a/src/main/c/simple_graphics.h b/src/main/c/simple_graphics.h new file mode 100644 index 00000000..d19cac46 --- /dev/null +++ b/src/main/c/simple_graphics.h @@ -0,0 +1,23 @@ +#ifndef SIMPLE_GRAPHICS_H +#define SIMPLE_GRAPHICS_H +#include + +// Private, versioned boundary between the tiny runtime loader and MiniFB. +// All calls run on the main thread. Pixel memory is borrowed for present only. +struct simple_graphics_api { + int32_t version; + int32_t (*open)(const char *, uint32_t, uint32_t); + int32_t (*present)(const uint32_t *, uint32_t); + int32_t (*poll)(int32_t); + int32_t (*mouse_x)(void); + int32_t (*mouse_y)(void); + int32_t (*button)(int32_t); + int32_t (*key)(int32_t); + void (*close)(void); + int32_t (*wait)(int64_t); + uint32_t (*width)(void); + uint32_t (*height)(void); + int32_t (*present_size)(const uint32_t *, uint32_t, uint32_t, uint32_t); +}; +#define SIMPLE_GRAPHICS_VERSION 3 +#endif diff --git a/src/main/c/simple_miniaudio.c b/src/main/c/simple_miniaudio.c new file mode 100644 index 00000000..03dbadd7 --- /dev/null +++ b/src/main/c/simple_miniaudio.c @@ -0,0 +1,123 @@ +#include "simple_audio.h" +#define MA_NO_DECODING +#define MA_NO_ENCODING +#define MA_NO_RESOURCE_MANAGER +#define MA_NO_NODE_GRAPH +#define MA_NO_ENGINE +#define MINIAUDIO_IMPLEMENTATION +#include +#include +#include +#include +#include + +#define RATE 48000 +#define SLOTS 32 +static ma_device device; +static ma_mutex mutex; +static int opened, active; +static uint32_t cursor; +static struct { int16_t *pcm; uint32_t count; } sounds[SLOTS]; + +// Only native-owned immutable PCM is read on the audio thread. The lock covers +// a bounded copy, never allocation, synthesis, device calls, or Simple code. +static void output(ma_device *unused, void *out, const void *in, ma_uint32 frames) { + (void)unused; (void)in; + memset(out,0,frames*sizeof(int16_t)); + ma_mutex_lock(&mutex); + if (active) { + uint32_t count=sounds[active].count-cursor; + if (count>frames) count=frames; + memcpy(out,sounds[active].pcm+cursor,count*sizeof(int16_t)); + cursor+=count; + if (cursor==sounds[active].count) active=0; + } + ma_mutex_unlock(&mutex); +} +static int32_t load(const int16_t *pcm, uint32_t count) { + if (!opened || !pcm || !count || count>RATE*10) return -1; + int slot; + for (slot=4; slot=SLOTS || !sounds[sound].pcm) return -1; + ma_mutex_lock(&mutex); + active=sound; cursor=0; + ma_mutex_unlock(&mutex); + return 0; +} +static int32_t stop(void) { + if (opened) { ma_mutex_lock(&mutex); active=0; ma_mutex_unlock(&mutex); } + return 0; +} +static int32_t playing(void) { + if (!opened) return 0; + ma_mutex_lock(&mutex); + int result=active!=0; + ma_mutex_unlock(&mutex); + return result; +} +static void close_audio(void) { + if (!opened) return; + ma_device_uninit(&device); // Joins callback before freeing buffers/mutex. + ma_mutex_uninit(&mutex); + for (int i=1;i +#include +#include +#include +#include +#ifdef _WIN32 +#include +#else +#include +#include +#include +#include "WindowData.h" +#include "x11/WindowData_X11.h" +#endif + +// One resizable window. No Simple pointer survives a native call: +// MiniFB retains its last draw buffer for OS repaint events, so copy it here. +static struct mfb_window *window; +static uint32_t *frame; +static uint32_t width, height; +static size_t capacity; + +static uint32_t window_width(void) { return window ? mfb_get_window_width(window) : 0; } +static uint32_t window_height(void) { return window ? mfb_get_window_height(window) : 0; } + +static void resize_window(struct mfb_window *w, int x, int y) { + if (x > 0 && y > 0) mfb_set_viewport(w, 0, 0, (unsigned)x, (unsigned)y); +} + +// The C-only build never installs the upstream C++ callback wrappers. +void release_cpp_stub(struct mfb_window *unused) { (void)unused; } + +static void close_window(void) { + if (window) { + mfb_close(window); // Requests close. + mfb_update_events(window); // Actually destroys the window. + window = NULL; + } + free(frame); + frame = NULL; + capacity = 0; +} + +static int32_t open_window(const char *title, uint32_t w, uint32_t h) { + if (window || !w || !h || w > UINT32_MAX / 4 || + (uint64_t)w * h > UINT32_MAX || (uint64_t)w * h > SIZE_MAX / 4) { + fprintf(stderr, "Simple graphics: invalid dimensions or a window is already open.\n"); + return -1; + } + frame = calloc((size_t)w * h, sizeof(*frame)); + if (!frame) { + fprintf(stderr, "Simple graphics: cannot allocate the display buffer.\n"); + return -1; + } + capacity = (size_t)w * h; + window = mfb_open_ex(title, w, h, MFB_WF_RESIZABLE); + if (!window) { + fprintf(stderr, "Simple graphics: MiniFB could not open a window (is a graphical display available?).\n"); + close_window(); + return -1; + } + width = w; + height = h; + mfb_set_resize_callback(window, resize_window); + return 0; +} + +static int32_t status(mfb_update_state state) { + if (state == MFB_STATE_OK) return 0; + if (state == MFB_STATE_EXIT) { + window = NULL; // MiniFB has already destroyed it. + close_window(); + return 1; + } + fprintf(stderr, "Simple graphics: MiniFB update failed (%d).\n", state); + close_window(); + return -1; +} + +static int32_t present_size(const uint32_t *pixels, uint32_t count, uint32_t w, uint32_t h) { + if (!window) return 1; + if (!pixels || !w || !h || w > UINT32_MAX / 4 || + count != (uint64_t)w * h || (uint64_t)w * h > SIZE_MAX / 4) { + fprintf(stderr, "Simple graphics: pixel array length must equal width * height.\n"); + return -1; + } + if (count > capacity) { + uint32_t *larger = realloc(frame, (size_t)count * sizeof(*frame)); + if (!larger) { + fprintf(stderr, "Simple graphics: cannot resize the display buffer.\n"); + return -1; + } + frame = larger; + capacity = count; + } + memcpy(frame, pixels, (size_t)count * sizeof(*frame)); + return status(mfb_update_ex(window, frame, w, h)); +} + +// Compatibility for clients drawing at their original resolution. +static int32_t present(const uint32_t *pixels, uint32_t count) { + return present_size(pixels, count, width, height); +} + +static int32_t wait_events(int64_t timeout) { + if (!window) return 1; + if (timeout < -1) return -1; + // May return early; the game recomputes its deadlines after every wakeup. + int ms=timeout>INT_MAX ? INT_MAX : (int)timeout; +#ifdef _WIN32 + if (MsgWaitForMultipleObjectsEx(0,NULL,ms<0 ? INFINITE : (DWORD)ms, + QS_ALLINPUT,MWMO_INPUTAVAILABLE)==WAIT_FAILED) return -1; +#else + // The pinned MiniFB X11 backend owns this connection. Check already queued + // Xlib events before waiting on its socket; no new event thread is needed. + SWindowData *data=(SWindowData *)window; + SWindowData_X11 *native=(SWindowData_X11 *)data->specific; + if (!XPending(native->display)) { + struct pollfd fd={ConnectionNumber(native->display),POLLIN,0}; + if (poll(&fd,1,ms)<0 && errno!=EINTR) return -1; + } +#endif + return status(mfb_update_events(window)); +} +static int32_t poll_events(int32_t wait) { return wait_events(wait ? 17 : 0); } +static int32_t mouse_x(void) { return window ? mfb_get_mouse_x(window) : 0; } +static int32_t mouse_y(void) { return window ? mfb_get_mouse_y(window) : 0; } +static int32_t button(int32_t b) { + return window && b >= 0 && b < 8 ? mfb_get_mouse_button_buffer(window)[b] != 0 : 0; +} +static int32_t key(int32_t k) { + return window && k >= 0 && k <= MFB_KB_KEY_LAST ? mfb_get_key_buffer(window)[k] != 0 : 0; +} + +static const struct simple_graphics_api api = { + SIMPLE_GRAPHICS_VERSION, open_window, present, poll_events, + mouse_x, mouse_y, button, key, close_window, wait_events, + window_width, window_height, present_size +}; +#ifdef _WIN32 +__declspec(dllexport) +#endif +const struct simple_graphics_api *simple_minifb_api(void) { return &api; } diff --git a/src/main/c/simple_time.c b/src/main/c/simple_time.c new file mode 100644 index 00000000..2e579922 --- /dev/null +++ b/src/main/c/simple_time.c @@ -0,0 +1,61 @@ +#define _POSIX_C_SOURCE 200809L +#include +#include +#include + +// Fixed-width bridge; no native struct layout or retained Simple pointers. +static int64_t clock_value(clockid_t clock, int64_t scale) { + struct timespec t; + if (clock_gettime(clock,&t)) return -1; + if (t.tv_sec>INT64_MAX/scale || t.tv_secINT64_MAX-fraction) { errno=EOVERFLOW; return -1; } + return base+fraction; +} +int64_t simple_time_now(void) { return clock_value(CLOCK_REALTIME,1000); } +int64_t simple_time_mono(void) { return clock_value(CLOCK_MONOTONIC,1000); } +int64_t simple_time_nano(void) { return clock_value(CLOCK_MONOTONIC,1000000000); } +int32_t simple_time_sleep(int64_t ms, int32_t absolute) { + if (ms<0) { errno=EINVAL; return -1; } + struct timespec t={ms/1000,(ms%1000)*1000000}; + int result; + if (!absolute) { + // Retry the remaining duration after signals; no busy waiting. + do { result=nanosleep(&t,&t); } while (result && errno==EINTR); + return result; + } + do { result=clock_nanosleep(CLOCK_MONOTONIC,TIMER_ABSTIME,&t,NULL); } while (result==EINTR); + if (result) { errno=result; return -1; } + return 0; +} +static int leap(int y) { return y%4==0 && (y%100!=0 || y%400==0); } +static int local_fields(int64_t ms, struct tm *local, struct tm *utc) { + tzset(); + int64_t sec=ms/1000; + if (ms%1000<0) --sec; + time_t t=(time_t)sec; + if ((int64_t)t!=sec || !localtime_r(&t,local) || !gmtime_r(&t,utc)) return -1; + if (local->tm_year < -1899 || local->tm_year > 8099) { errno=EOVERFLOW; return -1; } + return 0; +} +int32_t simple_time_local(int64_t ms, int64_t *out) { + struct tm t,u; + if (local_fields(ms,&t,&u)) return -1; + int days=t.tm_yday-u.tm_yday; + if (t.tm_year>u.tm_year) days+=365+leap(u.tm_year+1900); + if (t.tm_year0; + return 0; +} +int32_t simple_time_zone(int64_t ms, char *out, uint32_t capacity) { + struct tm t,u; + if (!capacity || local_fields(ms,&t,&u)) return -1; + return (int32_t)strftime(out,capacity,"%Z",&t); +} diff --git a/src/main/java/com/seaofnodes/simple/README.md b/src/main/java/com/seaofnodes/simple/README.md index af86f21e..a8916aa8 100644 --- a/src/main/java/com/seaofnodes/simple/README.md +++ b/src/main/java/com/seaofnodes/simple/README.md @@ -2,7 +2,7 @@ | Directory | Contents | | --- | --- | -| `parser/` | Recursive-descent grammar routines, lexing, name resolution, and construction of the initial IR. `Var` describes a lexical binding. See the [grammar map](../../../../../../docs/chapter30/30-grammar.md). | +| `parser/` | Recursive-descent grammar routines, lexing, name resolution, and construction of the initial IR. `Var` describes a lexical binding. See the [grammar map](../../../../../../docs/chapter31/31-grammar.md). | | `node/` | Sea-of-Nodes IR nodes: graph edges, type computation, and local peephole rewrites. | | `node/cpus/` | Machine-specific nodes and instruction selection support for `arm`, `riscv`, and `x86_64_v2`. | | `codegen/` | Compilation driver and passes: module loading, optimization, scheduling, register allocation, serialization, and machine-code emission. `IterPeeps` runs the peephole worklist. | diff --git a/src/main/java/com/seaofnodes/simple/codegen/CodeGen.java b/src/main/java/com/seaofnodes/simple/codegen/CodeGen.java index b4c93e1e..8618b47b 100644 --- a/src/main/java/com/seaofnodes/simple/codegen/CodeGen.java +++ b/src/main/java/com/seaofnodes/simple/codegen/CodeGen.java @@ -786,7 +786,11 @@ public class CodeGen { public boolean _asmLittle=true; public String asm() { return asm(new SB()).toString(); } SB asm(SB sb) { - ASMPrinter.print(sb,this); + if( _encodings.isEmpty() ) ASMPrinter.print(sb,this); + else for( var entry : _encodings.entrySet() ) { + sb.p("\n=== Compilation unit: ").p(entry.getKey()._cname).p(" ===\n"); + ASMPrinter.print(sb,this,entry.getValue()); + } return sb; } diff --git a/src/main/java/com/seaofnodes/simple/codegen/ElfWriter.java b/src/main/java/com/seaofnodes/simple/codegen/ElfWriter.java index fcf5c287..c5b25be0 100644 --- a/src/main/java/com/seaofnodes/simple/codegen/ElfWriter.java +++ b/src/main/java/com/seaofnodes/simple/codegen/ElfWriter.java @@ -318,11 +318,15 @@ public class ElfWriter { _strtab = new StringSection(); // place all the symbols + Encoding enc = _code._encoding; int nlocals = 1/*null*/+9/*number of sections*/+1/*Simple section*/; + int debugLocals=0; + for( StaticData.ObjectData obj : enc._data.objects.values() ) + if( !obj.external ) debugLocals+=obj.debugNames.size(); + nlocals+=debugLocals; SymbolSection symbols = new SymbolSection(nlocals); // we've already constructed these entire sections in the encoding phase - Encoding enc = _code._encoding; // Append ELF-only thunks to a copy. Export must not change instruction // offsets or the image used by the in-memory linker and emulators. BAOS textBits = new BAOS(enc._bits.toByteArray(),enc._bits.size()); @@ -402,10 +406,17 @@ public class ElfWriter { SimpleSection simple = new SimpleSection(_code._serial); // Write the local section header symbols - assert nlocals == 1+_sections._len; + assert nlocals == 1+_sections._len+debugLocals; symbols.symbol("",0,0,0); // Null symbol at index 0 for( Section s : _sections ) symbols.symbol(s._name, s._index, SYM_BIND_LOCAL, SYM_TYPE_SECTION, 0, s.size()); + // Local aliases describe the pooled object without changing linkage. + // Several source constants may name the same bytes. + for( StaticData.ObjectData obj : enc._data.objects.values() ) + if( !obj.external ) + for( String name : obj.debugNames ) + symbols.symbol(name,obj.readOnly ? rodata._index : rwdata._index, + SYM_BIND_LOCAL,SYM_TYPE_OBJECT,obj.offset,obj.size); int size = 64; // ELF header size // size of all section data diff --git a/src/main/java/com/seaofnodes/simple/codegen/Encoding.java b/src/main/java/com/seaofnodes/simple/codegen/Encoding.java index b07a8fec..eb62c36a 100644 --- a/src/main/java/com/seaofnodes/simple/codegen/Encoding.java +++ b/src/main/java/com/seaofnodes/simple/codegen/Encoding.java @@ -39,7 +39,9 @@ public class Encoding implements com.seaofnodes.isa.CodeSink { public final BAOS _bits = new BAOS(); // Instructions / encodings public final BAOS _cpool = new BAOS(); // Constant r/o pool public final BAOS _sdata = new BAOS(); // Static r/w pool - public final HashMap _bigCons = new HashMap<>(); + // Relocations belong to instruction occurrences, including equal constant + // loads cloned by scheduling/register allocation. Structural keys lose sites. + public final IdentityHashMap _bigCons = new IdentityHashMap<>(); public final StaticData _data; public final HashMap _externalAddresses = new HashMap<>(); @@ -157,7 +159,7 @@ public class Encoding implements com.seaofnodes.isa.CodeSink { // Nodes need "relocation" patching; things done after code is placed. // Record src and dst Nodes. - private final HashMap _internals = new HashMap<>(); + private final IdentityHashMap _internals = new IdentityHashMap<>(); // Source is a Call, destination in the Fun. public Encoding relo( CallNode call ) { FunNode fun = _code.link(call.tfp()); @@ -187,13 +189,13 @@ public class Encoding implements com.seaofnodes.isa.CodeSink { } // External references only located by Strings a link-time - public final HashMap _externals = new HashMap<>(); + public final IdentityHashMap _externals = new IdentityHashMap<>(); public Encoding external( Node n, String extern ) { _externals.put(n,extern); return this; } - public final HashMap _externData = new HashMap<>(); + public final IdentityHashMap _externData = new IdentityHashMap<>(); public void externalData(Node n, String name) { _externData.put(n,name); } // Store t as a 32/64 bit constant in the code space; generate RIP-relative diff --git a/src/main/java/com/seaofnodes/simple/codegen/GlobalCodeMotion.java b/src/main/java/com/seaofnodes/simple/codegen/GlobalCodeMotion.java index 86cb2e98..83c0677d 100644 --- a/src/main/java/com/seaofnodes/simple/codegen/GlobalCodeMotion.java +++ b/src/main/java/com/seaofnodes/simple/codegen/GlobalCodeMotion.java @@ -141,10 +141,11 @@ public abstract class GlobalCodeMotion { if( def!=null && !(def instanceof PhiNode) ) _schedEarly(def,code,start); - // An existing edge 0 already supplies control (or a Phi/Proj binding). - if( n.in(0)==null ) { + // A memory op's control is a lower bound, not a complete early schedule: + // instruction selection may have folded in an operand defined later. + if( n.in(0)==null || n instanceof MemOpNode ) { // Schedule at deepest input - CFGNode early = start; // Maximally early, lowest idepth + CFGNode early = n.in(0) instanceof CFGNode ctrl ? ctrl : start; for( int i=1; i early.idepth() ) early = n.in(i).cfg0(); // Latest/deepest input @@ -251,6 +252,9 @@ public abstract class GlobalCodeMotion { if( use != null ) lca = use_block(n,use, late).domLCA(lca,null); + assert lca!=null && early.dominates(lca,null) : + "Early schedule must dominate uses of "+n.getClass().getSimpleName()+"#"+n._nid; + // Loads may need anti-dependencies, raising their LCA if( n instanceof MemOpNode load && load._isLoad ) lca = find_anti_dep(lca,load,early,late,anti, antideps); diff --git a/src/main/java/com/seaofnodes/simple/codegen/IterPeeps.java b/src/main/java/com/seaofnodes/simple/codegen/IterPeeps.java index 985cd4d2..f4acb729 100644 --- a/src/main/java/com/seaofnodes/simple/codegen/IterPeeps.java +++ b/src/main/java/com/seaofnodes/simple/codegen/IterPeeps.java @@ -65,8 +65,10 @@ public class IterPeeps { * Iterate peepholes and inlining to a fixed point */ public void iterate( CodeGen code ) { + assert !CodeGen.expensiveAssert(0) || (progressOnList(code, _work) && schedulableUses(code)); boolean didInline = false; Ary defer = new Ary<>(Node.class); + while( true ) { // Clean up everything that does not grow the code iteratePeeps(code); @@ -97,8 +99,6 @@ public class IterPeeps { // Run all the code-reduction and type-lifting peeps as possible private void iteratePeeps( CodeGen code ) { - assert !CodeGen.expensiveAssert(0) || (progressOnList(code, _work) && schedulableUses(code)); - Node n; while( (n = _work.pop()) != null ) { if( n.isDead() ) continue; diff --git a/src/main/java/com/seaofnodes/simple/codegen/ListScheduler.java b/src/main/java/com/seaofnodes/simple/codegen/ListScheduler.java index c3b603e5..f90d8d4e 100644 --- a/src/main/java/com/seaofnodes/simple/codegen/ListScheduler.java +++ b/src/main/java/com/seaofnodes/simple/codegen/ListScheduler.java @@ -49,7 +49,7 @@ public abstract class ListScheduler { else computeSingleRDef(bb,n); - if( n instanceof NewNode || n instanceof CallNode ) + if( n instanceof NewNode || n instanceof CallNode || n instanceof ModFNode ) bb.fun()._hasCalls = true; return this; } diff --git a/src/main/java/com/seaofnodes/simple/codegen/ParseAll.java b/src/main/java/com/seaofnodes/simple/codegen/ParseAll.java index 3306ff8f..882a0f8a 100644 --- a/src/main/java/com/seaofnodes/simple/codegen/ParseAll.java +++ b/src/main/java/com/seaofnodes/simple/codegen/ParseAll.java @@ -150,7 +150,8 @@ public abstract class ParseAll { } private static void addRequiredTypes(CodeGen code, CompUnit cunit) { - for( String typeName : code.P._requiredTypes ) { + for( var required : code.P._requiredTypes.entrySet() ) { + String typeName = required.getKey(); // A forward use can have been resolved later in this source file. if( Parser.TYPES.get(typeName) instanceof TypeStruct ts && !ts._fref ) continue; try { @@ -158,7 +159,7 @@ public abstract class ParseAll { if( xcunit != null ) cunit.addDep(xcunit); else - assert false : "expected to find required type"; + throw Parser.error("Unknown type '"+typeName+"'",required.getValue()); } catch( IOException ioe ) { throw new RuntimeException(ioe); } diff --git a/src/main/java/com/seaofnodes/simple/codegen/RegAlloc.java b/src/main/java/com/seaofnodes/simple/codegen/RegAlloc.java index 3991cd48..303fd355 100644 --- a/src/main/java/com/seaofnodes/simple/codegen/RegAlloc.java +++ b/src/main/java/com/seaofnodes/simple/codegen/RegAlloc.java @@ -184,6 +184,7 @@ public class RegAlloc { if( bb instanceof CallEndMach cend ) cend.cacheRegs(_code); for( Node n : bb._outputs ) if( n instanceof NewNode nnn ) nnn.cacheRegs(_code); + else if( n instanceof ModFNode mod ) mod.cacheRegs(_code); } // Expensive assert: useful when chasing cross-function allocator edges. //assert verifyFunctionLocalEdges(); @@ -215,7 +216,7 @@ public class RegAlloc { _deferredLoopSelf.clear(); for( byte round=0; !graphColor(round); round++ ) { split(round); - if( round >= 7 ) { + if( round >= 10 ) { FunNode fun = _cfg.at(0).fun(); throw new IllegalStateException("Register allocation failed after eight rounds in "+ (fun==null ? "" : fun.label())); @@ -680,7 +681,14 @@ public class RegAlloc { if( cfg==def.cfg0() && def.nOuts()==1 && !singleReg ) return; } - makeSplit(def,kind,round,lrg,umask).insertBefore(n, i); + // If isolating a loop Phi's uses did not relieve pressure, cloning its + // constant input again cannot help: it still forces the Phi into a GPR. + // A real transfer on this retry lets the Phi live on the stack. + Node split = n instanceof PhiNode phi && phi.region() instanceof LoopNode && + lrg._machUse instanceof SplitNode prior && prior._round debugNames = new TreeSet<>(); public int offset; + public String label() { return debugNames.isEmpty() ? symbol : String.join(", ",debugNames); } ObjectData(Type t, String name, boolean ro, boolean ext) { type=t; symbol=name; readOnly=ro; external=ext; alignment=t.alignment(); @@ -73,7 +76,12 @@ public final class StaticData { // Register before following fields: class objects may refer to each other. if( !obj.external && t instanceof TypeStruct ts ) for( Field f : ts._fields ) - if( !f._extern && f._t.isConstant() ) target(f._t); + if( !f._extern && f._t.isConstant() ) { + target(f._t); + if( clz && f._final && f._t instanceof TypeMemPtr ptr && + pointerConstant(ptr) && !isClass(ptr._obj) ) + object(ptr._obj).debugNames.add(ts._name.substring(TypeStruct.CLZ.length())+"."+f._fname); + } return obj; } diff --git a/src/main/java/com/seaofnodes/simple/codegen/TypeCheck.java b/src/main/java/com/seaofnodes/simple/codegen/TypeCheck.java index a86cd18a..418edaf6 100644 --- a/src/main/java/com/seaofnodes/simple/codegen/TypeCheck.java +++ b/src/main/java/com/seaofnodes/simple/codegen/TypeCheck.java @@ -21,12 +21,14 @@ abstract class TypeCheck { Ary errs = new Ary<>(Node.class); Ary constructs = new Ary<>(ConstructNode.class); Ary views = new Ary<>(InitViewNode.class); + Ary arrays = new Ary<>(ArrayInitNode.class); code._stop.walk( n -> { if( n.err() != null ) errs.add(n); if( n instanceof CLInitNode ) code.add(n); if( n instanceof ConstructNode con ) constructs.add(con); if( n instanceof InitViewNode view ) views.add(view); + if( n instanceof ArrayInitNode array ) arrays.add(array); return null; }); @@ -57,13 +59,15 @@ abstract class TypeCheck { if( !con.isDead() ) con.subsume(con.in(1)); for( InitViewNode view : views ) if( !view.isDead() ) view.subsume(view.in(1)); + for( ArrayInitNode array : arrays ) + if( !array.isDead() ) array.subsume(array.in(2)); } private static int errorRank(Node n) { // Bad memory access originates the error. Missing construction fields // in turn explain generic-scalar arithmetic further downstream. if( n instanceof MemOpNode && noBottomInputs(n) ) return 0; - if( n instanceof ConstructNode ) return 1; + if( n instanceof ConstructNode || n instanceof ArrayInitNode ) return 1; return noBottomInputs(n) ? 2 : 3; } diff --git a/src/main/java/com/seaofnodes/simple/node/ArrayInitNode.java b/src/main/java/com/seaofnodes/simple/node/ArrayInitNode.java new file mode 100644 index 00000000..c6ae90ea --- /dev/null +++ b/src/main/java/com/seaofnodes/simple/node/ArrayInitNode.java @@ -0,0 +1,70 @@ +package com.seaofnodes.simple.node; + +import com.seaofnodes.print.ExprPrinter; +import com.seaofnodes.simple.parser.Lexer; +import com.seaofnodes.simple.parser.Parser; +import com.seaofnodes.simple.type.*; +import com.seaofnodes.simple.util.Ary; + +/** Source checks for array construction and its yielded elements. Erased by + * TypeCheck before serialization and scheduling. */ +public final class ArrayInitNode extends Node { + private final int _count; // List size, -1 for a generator, -2 for a yielded element. + private final Lexer _loc; + public ArrayInitNode(Node ctrl, Node mem, Node ptr, Node len, int count, Lexer loc, Ary values) { + super(ctrl,mem,ptr,len); + _count=count; _loc=loc; + for( Node value : values ) addDef(value); + } + public ArrayInitNode(Node ctrl, Node value, Lexer loc) { + super(ctrl,null,value); + _count=-2; _loc=loc; + } + @Override public String label() { return "ArrayInit"; } + @Override protected ExprPrinter _print1(ExprPrinter p) { return p.p("arrayInit(").n(in(2)).p(")"); } + @Override public Type compute() { + if( in(0)._type != Type.CONTROL ) return Type.TOP; + Type ptr = in(2)._type; + if( _count < 0 ) return ptr; + // A list is strict in all its inputs. Wait for every input before + // choosing a constant payload or falling to the ordinary array type. + // Otherwise one SCCP worklist order can return PtrTop (or an array) + // before another unresolved input sends the result back up to Top. + if( ptr.isHigh() || in(3)._type.isHigh() ) return Type.TOP; + for( int i = 4; i < nIns(); i++ ) + if( in(i)._type.isHigh() ) return Type.TOP; + if( !(ptr instanceof TypeMemPtr tmp) ) return ptr; + Field body = tmp._obj.field("[]"); + if( body == null || !body._final || !(body._t instanceof TypeInteger storage) ) return ptr; + if( !(in(3)._type instanceof TypeInteger length) || !length.isConstant() || length.value() != _count ) return ptr; + long[] values = new long[_count]; + for( int i = 0; i < _count; i++ ) { + Type value = in(i+4)._type; + if( !(value instanceof TypeInteger integer) || !integer.isConstant() ) return ptr; + values[i] = integer.value(); + } + TypeConAry contents = TypeConAry.make(storage,values); + TypeStruct array = TypeStruct.makeAry(tmp._obj._name,tmp._obj.field("#")._alias,body._alias,contents); + // The surrounding ReadOnlyNode supplies the public view. Keep this + // node's access flags consistent when its contents cease to be constant. + return TypeMemPtr.make((byte)2,array,true).withAccess(tmp._ro); + } + @Override public Node idealize() { return null; } + @Override public Parser.ParseException err() { + if( in(0)._type==Type.XCONTROL ) return null; + if( _count==-2 ) + return TypeMemPtr.mayBePartial(in(2)._type) + ? Parser.error("Array initializer requires fully initialized elements",_loc) : null; + if( !(in(3)._type instanceof TypeInteger len) ) + return Parser.error("Array length must be an integer",_loc); + if( len.isConstant() && (len.value()<0 || len.value()>TypeInteger.U32._max) ) + return Parser.error("Array length is outside the u32 range",_loc); + if( _count>=0 && (!len.isConstant() || len.value()!=_count) ) + return Parser.error("Array initializer has "+_count+" elements; length must equal that constant",_loc); + for( int i=4; i