diff options
| author | Cliff Click <cliffc@acm.org> | 2026-11-14 12:41:16 -0800 |
|---|---|---|
| committer | Cliff Click <cliffc@acm.org> | 2026-11-14 12:41:16 -0800 |
| commit | 3d0f3f38d9d8345b6508b3289dc94b0500c53d9e (patch) | |
| tree | 1b769cdc4e415fad5c1b18afa23ffc6fe56db18a | |
| parent | afcf96444366fb4b7c83f938763013cbc360aade (diff) | |
| download | Simple-3d0f3f38d9d8345b6508b3289dc94b0500c53d9e.tar.gz Simple-3d0f3f38d9d8345b6508b3289dc94b0500c53d9e.zip | |
Breakout, Clock demos
Math lib with simple constants raw bit converters
TypeConAry unified
Big Formatting change
Debug symbols for constant data
IterPeeps was endlessly running asserts with much inlining
RegAlloc rounds raised
75 files changed, 2117 insertions, 523 deletions
diff --git a/chapter30/README.md b/chapter30/README.md index 3e27c874..9ac38576 100644 --- a/chapter30/README.md +++ b/chapter30/README.md @@ -1,7 +1,5 @@ # Chapter 30: Text Formatting and Diagnostics -English | [日本語](README.ja.md) - [Previous: Chapter 29 — Tech Debt Cleanup](../chapter29/README.md) This chapter uses a small game to drive improvements in the compiler and the diff --git a/chapter31/README.md b/chapter31/README.md index 356b9cdb..f6141950 100644 --- a/chapter31/README.md +++ b/chapter31/README.md @@ -1,87 +1,185 @@ # Chapter 31: Software Drawing, Time, and Graphical Games -English | [日本語](README.ja.md) - [Previous: Chapter 30 — Text Formatting and Diagnostics](../chapter30/README.md) -Small graphical games drive this chapter's language and library work, starting -with a pixel window for a Simple-written 2-D graphics library. MiniFB supplies -the optional native window/input backend; drawing stays in Simple. - -The [drawing library](docs/drawing.md) provides a pixel canvas, colors, -rectangles, circles, thick lines, and bitmap labels. The -[graphical tic-tac-toe game](docs/examples/TicTacToeGraphical.smp) uses it for -mouse/keyboard play against the terminal game's CPU strategy. -The optional [audio library](docs/audio.md) adds soft move sounds and rising -or falling win/loss cues, played in the background by miniaudio. -Hexadecimal colors (`0xe47b57`) and leading-zero octal font masks (`025755`) -are supported by this chapter's integer literal syntax. - -The [time library](docs/time.md) adds millisecond clocks, calendar conversion, -absolute ISO parsing, built-in time formatting, sleeps, and cooperative timers. -The [digital and analog clock](docs/examples/Clock.smp) demonstrates single-threaded -animation and the reusable `sys.draw.Button` widget: -`make -C chapter31 run-clock CTAGS=`. Click its button or press Space to switch -between green seven-segment digits and an analog dial. +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 + +[Clock](docs/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](docs/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](docs/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. + + +## 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](docs/drawing.md), [windows](docs/graphics.md), and +[audio](docs/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](docs/time.md) for local-time formatting and other forms. + ## Array initializers -Arrays can be filled with a list or an index-based initializer: +An array can use a list of values or an expression evaluated for each index: ```simple -val glyphs = new u16[~]{075557,026227,061247}; // Read-only, inferred length. +val primes = new int[]{2,3,5,7}; val squares = new int[10]{int i -> i*i;}; -val names = new u8[~][~2]{"Alice","Bob"}; // Read-only, non-null strings. +val names = new u8[~][~2]{"Alice","Bob"}; ``` -An explicit list length must be a constant equal to the number of elements. -A generator evaluates its length once and runs in index order, once per element -(zero times for an empty array). Its body supports statements and `return`, or -uses its last expression as the result. It can read surrounding locals but -cannot reassign them. Use `int`, `i64`, or `u32` for the index. +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. -`[~n]` (or `[~]` with a list) makes the array read-only; `val` alone only fixes -the binding. Initializers can construct arrays of non-null references because -every element is supplied before the array becomes accessible. Read-only access -propagates to referenced elements, following the existing view rules. Initialization runs at runtime; -read-only does not require compile-time evaluation. Canvas's font now uses a -read-only `u16` table, and `sys.text.end` uses a generator for its byte copy. +If the array has a fixed initialization list, then the length can be inferred. -## Running the examples -```sh -make -C chapter31 libs CTAGS= # Once while online (also: init or lib). -make -C chapter31 run-graphical-tictactoe CTAGS= +`[~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 the `PI` and `E` constants, +plus two operations: + +```simple +i64 bits = sys.math.f64Bits(1.0); // 0x3ff0000000000000 +f64 value = sys.math.f64FromBits(bits); // 1.0 ``` -This explicitly builds the optional graphics/audio backends and opens a window. Use -`graphical-tictactoe` instead to build the executable without starting it or -requiring MiniFB. -Dependencies stay cached under `chapter31/lib`, including across `make clean`. -Only explicit `libs`/`init`/`lib` setup targets access the internet; other -targets use local files and fail promptly if something needs downloading. +They *reinterpret* the same 64 bits, preserving signed zero and NaN payloads. +Ordinary assignments between integer and floating-point types still perform +numeric conversion. + +These functions introduce compiler intrinsics: C functions with fixed meanings +that the compiler recognizes and replaces with internal operations. For the +bit-reinterpretation operations, Simple uses plain register moves. Calls whose +targets remain unknown at compile time use the C implementations. Recognition +and expansion live in `Intrinsic.java`. + +See [the intrinsic contract](docs/intrinsics.md) for the implemented behavior. + +Simple also now recognizes hexadecimal (`0xff0000`) and leading-zero octal +(`025755`) integer literals. -The default build and test suite need no graphics dependencies. See -[optional graphics](docs/graphics.md) for building MiniFB, running the pixel -example, and handling a missing backend. `make tests_nographics CTAGS=` runs -all ordinary tests with graphics explicitly disabled. -The inherited language and library are described in [Chapter 30](../chapter30/README.md). -The [grammar and code map](docs/31-grammar.md), -[source layout](src/main/java/com/seaofnodes/simple/README.md), and -[runnable examples](docs/examples/) describe this snapshot. +## Compiler fixes -From the repository root: +- 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. + +## Build and run + +From the `chapter31` directory: ```sh -make lib tests release CHAPTERS=chapter31 CTAGS= -make -C chapter31 tictactoe CTAGS= +make libs CTAGS= # Download dependencies once. +make run-graphical-tictactoe CTAGS= +make run-clock CTAGS= +make run-breakout CTAGS= ``` -The game binary is `chapter31/build/examples/x86_64_v2_win64/TicTacToe.exe` -on Windows and `chapter31/build/examples/x86_64_v2_SystemV/TicTacToe` on Linux. -For a WSL build in the same checkout, use `CLZDIR=build/classes-linux` to keep -Linux Java outputs separate from Windows outputs. +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: -IntelliJ has a `chapter31` module and a **chapter31 tests** run configuration. -Inherited Java test names retain their historical chapter numbers. +```sh +make tests_nographics CTAGS= +``` diff --git a/chapter31/docs/examples/Breakout.smp b/chapter31/docs/examples/Breakout.smp new file mode 100644 index 00000000..e5757b45 --- /dev/null +++ b/chapter31/docs/examples/Breakout.smp @@ -0,0 +1,293 @@ +// 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. +int 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; + int soundDepth = 1; + + // 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; + }; + + // 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? + 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 ) { soundDepth = row; _cue(3); } + if( back && backWall && !boosted ) { boosted = true; _cue(4); } + if( remaining == 0 ) { phase = WON; _cue(6); } + _speed(); + return 0; + }; + + // 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; + paddle = 504.0; + x = paddle; + y = PADDLE_Y-RADIUS-6; + _speed(); + }; +}; + +// 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 = { !Game g, int direction -> + if( g.paused || g.phase == WON || g.phase == LOST ) return 0; + g._paddle(g.paddle+direction*6.4); + if( g.phase == READY ) { g.x = g.paddle; g.y = PADDLE_Y-RADIUS-6; return 0; } + f64 seconds = 0.008; + while( seconds > 0.000000001 && g.phase == PLAY ) { + f64 dt = 2.0/g.speed; + if( dt > seconds ) dt = seconds; + seconds -= dt; + f64 oldX = g.x, oldY = g.y; + g.x += g.dx*g.speed*dt; + g.y += g.dy*g.speed*dt; + if( g.x < LEFT+RADIUS && g.dx < 0.0 ) { + g.x = 2.0*(LEFT+RADIUS)-g.x; g.dx = -g.dx; g._cue(1); + } + if( g.x > RIGHT-RADIUS && g.dx > 0.0 ) { + g.x = 2.0*(RIGHT-RADIUS)-g.x; g.dx = -g.dx; g._cue(1); + } + if( g.y < TOP+RADIUS && g.dy < 0.0 ) { + g.y = 2.0*(TOP+RADIUS)-g.y; g.dy = -g.dy; + g.backWall = true; g._cue(1); + } + if( g.dy > 0.0 && oldY <= PADDLE_Y-RADIUS && g.y >= PADDLE_Y-RADIUS && + g.paddle-PADDLE_HALF-RADIUS <= g.x <= g.paddle+PADDLE_HALF+RADIUS ) g._rebound(); + if( g.y > BOTTOM+RADIUS ) { + g.lives--; + g.phase = g.lives == 0 ? LOST : READY; + g.backWall = false; + g.depth = 1; + g.boosted = false; + g._speed(); + g.x = g.paddle; g.y = PADDLE_Y-RADIUS-6; + g._cue(5); + break; + } + for( int i = 0; i < g.bricks#; i++ ) { + if( g.bricks[i] == 0 ) continue; + f64 left = LEFT+2+(i-i/COLS*COLS)*BRICK_DX-RADIUS; + f64 top = BRICK_TOP+(i/COLS)*BRICK_DY-RADIUS; + f64 right = left+BRICK_W+2*RADIUS, bottom = top+BRICK_H+2*RADIUS; + if( left < g.x < right && top < g.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 && g.dy > 0.0 ) { + g.y = top; g.dy = -g.dy; back = true; + } else if( oldY >= bottom && g.dy < 0.0 ) { + g.y = bottom; g.dy = -g.dy; + } else if( oldX <= left && g.dx > 0.0 ) { + g.x = left; g.dx = -g.dx; + } else if( oldX >= right && g.dx < 0.0 ) { + g.x = right; g.dx = -g.dx; + } else continue; + g._brick(i,back); + break; + } + } + } + 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-value/10*10],scale,color); + value /= 10; + } +}; +val _hud = { !sys.draw.Canvas c, Game g -> + c.text(24,22,"BREAKOUT",5,WHITE); + c.text(264,20,"SCORE",2,MUTED); + _number(c,264,40,g.score,3,4,WHITE); + c.text(424,20,"BRICKS",2,MUTED); + _number(c,424,40,g.remaining,3,4,WHITE); + c.text(584,20,"BALLS",2,MUTED); + for( int i = 0; i < g.lives; i++ ) c.fillCircle(590+23*i,50,5,CYAN); + c.text(714,20,"SPEED",2,MUTED); + int speed = g.speed; + _number(c,714,40,speed,3,4,g.boosted ? COLORS[0] : WHITE); + c.text(838,40,g.boosted ? "BOOST!" : "NORMAL",3,g.boosted ? COLORS[0] : MUTED); +}; +val _bricks = { !sys.draw.Canvas c, Game g -> + 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,g.boosted ? "BACK WALL BOOST ACTIVE" : "BREAK THROUGH FOR A BOOST",2,g.boosted ? COLORS[0] : MUTED); + for( int i = 0; i < g.bricks#; i++ ) { + if( g.bricks[i] == 0 ) continue; + int row = i/COLS; + i64 x = LEFT+2+(i-row*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, Game g -> + if( g.phase != PLAY || g.paused ) { + c.fillRect(246,422,516,108,0x17263a).rect(246,422,516,108,2,0x29435a); + u8[~] title = g.paused ? "PAUSED" : g.phase == WON ? "WALL CLEARED!" : g.phase == LOST ? "GAME OVER" : "READY?"; + c.text(504-(title#*4-1)*4/2,442,title,4,WHITE); + u8[~] help = g.paused ? "P TO CONTINUE" : g.phase == WON || g.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; +}; +val _draw = { !sys.draw.Canvas c, Game g -> + c.clear(BACKGROUND); + _hud(c,g); + _bricks(c,g); + i64 paddle = g.paddle, ballX = g.x, ballY = g.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,g.boosted ? 0x672a42 : 0x224b61); + c.fillCircle(ballX,ballY,RADIUS,g.boosted ? COLORS[0] : WHITE); + _overlay(c,g); + c.text(24,738,"ARROWS / MOUSE: MOVE SPACE / CLICK: SERVE P: PAUSE R: RESTART Q / ESC: QUIT",2,MUTED); +}; + +// 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-i/period*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; +}; +struct Controls { + bool serveHeld = false, pauseHeld = false, restartHeld = false; + int lastMouse = 504; +}; +val _input = { !Game g, !Controls keys -> + val gfx = sys.gfx; + bool serve = gfx.key(' ') || gfx.button(gfx.LEFT); + bool pause = gfx.key('P'), restart = gfx.key('R'); + if( restart && !keys.restartHeld ) { g._reset(); sys.audio.stop(); } + if( pause && !keys.pauseHeld && (g.phase == READY || g.phase == PLAY) ) g.paused = !g.paused; + int direction = (gfx.key(KEY_RIGHT) ? 1 : 0)-(gfx.key(KEY_LEFT) ? 1 : 0); + int mouse = gfx.mouseX(); + if( mouse != keys.lastMouse && direction == 0 && !g.paused && (g.phase == READY || g.phase == PLAY) ) { + g._paddle(mouse*1.0); + if( g.phase == READY ) g.x = g.paddle; + } + keys.lastMouse = mouse; + if( serve && !keys.serveHeld ) g._serve(); + keys.serveHeld = serve; keys.pauseHeld = pause; keys.restartHeld = restart; + return direction; +}; + +// 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 -> + val gfx = sys.gfx, audio = sys.audio, time = sys.time; + val c = new sys.draw.Canvas(WIDTH,HEIGHT); + val g = new Game; + if( gfx.open("Simple Breakout",c.width,c.height) != gfx.OK ) return 1; + 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);}; + val keys = new Controls; + keys.lastMouse = gfx.mouseX(); + int frames = 0, status = gfx.OK; + i64 last_ms = time.monotonic(), pending_ms = 0, frame_ms = last_ms; + while( status == gfx.OK ) { + if( gfx.key('Q') || gfx.key(gfx.ESCAPE) ) break; + int direction = _input(g,keys); + i64 now_ms = 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 ) { _tick(g,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 ) { + _draw(c,g); + status = gfx.present(c.pixels); + 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/chapter31/docs/examples/Clock.smp b/chapter31/docs/examples/Clock.smp index 11449810..ecf0fae1 100644 --- a/chapter31/docs/examples/Clock.smp +++ b/chapter31/docs/examples/Clock.smp @@ -1,25 +1,25 @@ // 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; +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; + 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; } + if( frame_id == 0 ) { gfx.close(); return 1; } - bool analog=false, held=false; - int frames=0, status=gfx.OK; + bool analog = false, held = false; + int frames = 0, status = gfx.OK; // Main event loop - while( status==gfx.OK ) { + while( status == gfx.OK ) { // Did the user press space bar? bool space = gfx.key(' '); // Did the left mouse button go down? @@ -27,31 +27,31 @@ val main = { u8[~][] args -> // ANd did it go down over this button? bool click = button.update(gfx.mouseX(),gfx.mouseY(),down); // If clicked, flip the clock mode - if( click || (space && !held) ) analog=!analog; + 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 ) { + if( timers.poll(time.monotonic()) == frame_id ) { // 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.present(screen.pixels); // Testing only: show 5 frames, flip to analog, show 5 more and exit - if( args#>1 ) { + if( args# > 1 ) { frames++; - if( frames==5 ) analog=true; - if( frames==10 ) break; + if( frames == 5 ) analog = true; + if( frames == 10 ) break; } } - if( status!=gfx.OK ) 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; + return status == gfx.ERROR ? 1 : 0; }; val _draw = { !sys.draw.Canvas screen, i64 wall_ms, i64 analog -> @@ -67,17 +67,17 @@ val _draw = { !sys.draw.Canvas screen, i64 wall_ms, i64 analog -> // 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 _digit = { !sys.draw.Canvas c, int x, int y, i64 digit -> - int bits=digit==0 ? 0x3f : digit==1 ? 0x06 : digit==2 ? 0x5b : - digit==3 ? 0x4f : digit==4 ? 0x66 : digit==5 ? 0x6d : - digit==6 ? 0x7d : digit==7 ? 0x07 : digit==8 ? 0x7f : digit==9 ? 0x6f : 0; - for( int i=0; i<7; i++ ) { - u32 color=(bits&(1<<i))!=0 ? GREEN : DIM; - if( i==0 || i==3 || i==6 ) { - int dy=i==0 ? 0 : i==3 ? 144 : 72; + int bits = digit == 0 ? 0x3f : digit == 1 ? 0x06 : digit == 2 ? 0x5b : + digit == 3 ? 0x4f : digit == 4 ? 0x66 : digit == 5 ? 0x6d : + digit == 6 ? 0x7d : digit == 7 ? 0x07 : digit == 8 ? 0x7f : digit == 9 ? 0x6f : 0; + for( int i = 0; i < 7; i++ ) { + u32 color = (bits&(1<<i)) != 0 ? GREEN : DIM; + if( i == 0 || i == 3 || i == 6 ) { + int dy = i == 0 ? 0 : i == 3 ? 144 : 72; c.line(x+14,y+dy,x+58,y+dy,10,color); } else { - bool right=i==1 || i==2; - int dx=right ? 68 : 4, dy=i==1 || i==5 ? 12 : 84; + bool right = i == 1 || i == 2; + int dx = right ? 68 : 4, dy = i == 1 || i == 5 ? 12 : 84; c.line(x+dx,y+dy,x+dx,y+dy+48,10,color); } } @@ -87,7 +87,7 @@ val _digital = { !sys.draw.Canvas c, int hour, int minute, int second -> _digit(c,68,166,hour/10); _digit(c,154,166,hour-hour/10*10); _digit(c,284,166,minute/10); _digit(c,370,166,minute-minute/10*10); _digit(c,500,166,second/10); _digit(c,586,166,second-second/10*10); - for( int i=0; i<2; i++ ) { + for( int i = 0; i < 2; i++ ) { c.fillCircle(254+i*216,214,6,GREEN); c.fillCircle(254+i*216,262,6,GREEN); } @@ -96,31 +96,31 @@ val _digital = { !sys.draw.Canvas c, int hour, int minute, int second -> // Rational sine approximation, accurate enough for pixel clock geometry. // Arguments are nonnegative turns; no additional native math dependency. val _sin = { f64 turn -> - i64 whole=turn; turn-=whole; - bool negative=turn>0.5; - f64 x=(negative ? turn-0.5 : turn)*6.283185307179586; - f64 product=x*(3.141592653589793-x); - f64 numerator=negative ? -16.0 : 16.0; + i64 whole = turn; turn -= whole; + bool negative = turn > 0.5; + f64 x = (negative ? turn-0.5 : turn)*6.283185307179586; + f64 product = x*(3.141592653589793-x); + f64 numerator = negative ? -16.0 : 16.0; return numerator*product/(49.34802200544679-4*product); }; val _hand = { !sys.draw.Canvas c, f64 turn, int length, int thickness, u32 color -> - int x=360+_sin(turn)*length, y=232-_sin(turn+0.25)*length; + int x = 360+_sin(turn)*length, y = 232-_sin(turn+0.25)*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 turn=i/60.0; - bool major=i-i/5*5==0; - int inner=major ? 133 : 143; - int x0=360+_sin(turn)*inner, y0=232-_sin(turn+0.25)*inner; - int x1=360+_sin(turn)*149, y1=232-_sin(turn+0.25)*149; + for( int i = 0; i < 60; i++ ) { + f64 turn = i/60.0; + bool major = i-i/5*5 == 0; + int inner = major ? 133 : 143; + int x0 = 360+_sin(turn)*inner, y0 = 232-_sin(turn+0.25)*inner; + int x1 = 360+_sin(turn)*149, y1 = 232-_sin(turn+0.25)*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; + f64 seconds = second+millisecond/1000.0; + f64 minutes = minute+seconds/60.0; _hand(c,(hour-hour/12*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); diff --git a/chapter31/docs/examples/Dijkstra.smp b/chapter31/docs/examples/Dijkstra.smp index a8fcf3da..6591b310 100644 --- a/chapter31/docs/examples/Dijkstra.smp +++ b/chapter31/docs/examples/Dijkstra.smp @@ -6,14 +6,14 @@ 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; }; + 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++ ) + for( int node = 0; node < nodes; node++ ) if( !visited.get(node) && dist[node] < best ) { nearest = node; best = dist[node]; @@ -22,8 +22,8 @@ val shortestPath = { !sys.aryi64 matrix, int nodes, int src, int dst -> else { if( nearest == dst ) return best; visited.set(nearest); - for( int node=0; node<nodes; node++ ) { - u32 index=nearest*nodes + node; + 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; @@ -47,7 +47,7 @@ val main = { u8[~][] args -> if( !matrix ) return usage(); if( !matrix.len ) return usage(); // All numbers are positive - for( u32 i=0; i<matrix.len; i++ ) + for( u32 i = 0; i < matrix.len; i++ ) if( matrix.get(i) < 0 ) return usage(); // Matrix is square int nodes = 0; @@ -61,7 +61,7 @@ val main = { u8[~][] args -> if( src < 0 || src >= nodes || dst < 0 || dst >= nodes ) return usage(); // Source and destination land within the graph - int source=src, destination=dst; + int source = src, destination = dst; i64 cost = shortestPath(matrix,nodes,source,destination); if( cost >= 0 ) { new sys.aryu8().num(cost).add('\n').write(1); diff --git a/chapter31/docs/examples/Graphics.smp b/chapter31/docs/examples/Graphics.smp index 7ba5c6e7..8b251fa2 100644 --- a/chapter31/docs/examples/Graphics.smp +++ b/chapter31/docs/examples/Graphics.smp @@ -3,8 +3,8 @@ val main = { u8[~][] args -> if( sys.gfx.open("Simple pixels",320,240) != sys.gfx.OK ) return 1; val pixels = new u32[320*240]; - for( int y=0; y<240; y++ ) - for( int x=0; x<320; x++ ) + for( int y = 0; y < 240; y++ ) + for( int x = 0; x < 320; x++ ) pixels[y*320+x] = (x*255/319 << 16) | (y*255/239 << 8) | 64; int result = sys.gfx.present(pixels); int frames = 0; diff --git a/chapter31/docs/examples/README.md b/chapter31/docs/examples/README.md index 46965ac0..20b644cf 100644 --- a/chapter31/docs/examples/README.md +++ b/chapter31/docs/examples/README.md @@ -16,6 +16,30 @@ Run `make run-clock CTAGS=`; click the button or press Space to switch faces, and Q/Escape to exit. Both faces show system-local time. `make clock-example CTAGS=` 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 CTAGS=` or build only with `make breakout CTAGS=`. +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 diff --git a/chapter31/docs/examples/TicTacToe.smp b/chapter31/docs/examples/TicTacToe.smp index 1e0f3ca0..ee4e3182 100644 --- a/chapter31/docs/examples/TicTacToe.smp +++ b/chapter31/docs/examples/TicTacToe.smp @@ -21,7 +21,7 @@ val main = { u8[~][] args -> // Compute CPU move int reply = _cpu(board); // Set CPU choice; print board - board[reply]='O'; + board[reply] = 'O'; sys.io.p("CPU plays %(reply+1).\n"); _draw(board); // A winner? @@ -61,37 +61,37 @@ val _validMove = { u8[~] board -> // Return the winning mark, or zero. val _winner = { u8[~] board -> - for( int i=0; i<3; i++ ) { + for( int i = 0; i < 3; i++ ) { int row = i*3; - if( board[row]!=' ' && board[row]==board[row+1] && board[row]==board[row+2] ) + 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] ) + 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]; + 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; + 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 + 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; } } @@ -103,30 +103,30 @@ val _threat = { u8[] board, u8 mark -> val _cpu = { u8[] board -> // If O can win, do so int win = _threat(board,'O'); - if( win>=0 ) return win; + if( win >= 0 ) return win; // If X will win next move, block int block = _threat(board,'X'); - if( block>=0 ) return block; + if( block >= 0 ) return block; // If center is open, take it - if( board[4]==' ' ) return 4; + 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; + 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; + 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++ ) { + 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('|'); + if( col < 2 ) out.add('|'); } out.add('\n'); - if( row<2 ) out.addAry("---+---+---\n"); + if( row < 2 ) out.addAry("---+---+---\n"); } out.write(sys.libc.STDOUT); }; diff --git a/chapter31/docs/examples/TicTacToeGraphical.smp b/chapter31/docs/examples/TicTacToeGraphical.smp index da77e8f6..d3d575a7 100644 --- a/chapter31/docs/examples/TicTacToeGraphical.smp +++ b/chapter31/docs/examples/TicTacToeGraphical.smp @@ -13,28 +13,28 @@ val main = { u8[~][] args -> bool mouseHeld = false, keyHeld = false, replayHeld = false; int hover = -1, frames = 0; - while( result==sys.gfx.OK ) { + while( result == sys.gfx.OK ) { result = sys.gfx.wait(17); - if( result!=sys.gfx.OK ) break; + 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(' '); int square = _square(sys.gfx.mouseX(),sys.gfx.mouseY()); - bool dirty = square!=hover; + bool dirty = square != hover; hover = square; - if( replay && !replayHeld ) { sys.audio.stop(); _reset(board); dirty=true; } + 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++ ) { + for( int i = 0; i < 9; i++ ) { int key = '1'+i; if( sys.gfx.key(key) ) { digit = true; - if( !keyHeld ) choice=i; + if( !keyHeld ) choice = i; } } if( !(replay && !replayHeld) && _move(board,choice) ) { sys.audio.play(_sound(board)); - dirty=true; + dirty = true; } mouseHeld = down; keyHeld = digit; @@ -43,68 +43,68 @@ val main = { u8[~][] args -> _draw(screen,board,hover); result = sys.gfx.present(screen.pixels); } - if( args#>1 && ++frames==5 ) break; + if( args# > 1 && ++frames == 5 ) break; } sys.audio.close(); sys.gfx.close(); - return result==sys.gfx.ERROR ? 1 : 0; + 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; + 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]=' '; + 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; + 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; + 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'; + 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; + 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++ ) { + 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[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; + 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]; + 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]==' ' ) { + for( int i = 0; i < 9; i++ ) + if( board[i] == ' ' ) { board[i] = mark; - bool wins = _winner(board)==mark; + bool wins = _winner(board) == mark; board[i] = ' '; // Restore board if( wins ) return i; } @@ -115,16 +115,16 @@ val _threat = { u8[] board, u8 mark -> val _cpu = { u8[] board -> // If O can win, do so int win = _threat(board,'O'); - if( win>=0 ) return win; + if( win >= 0 ) return win; // If X will win next move, block int block = _threat(board,'X'); - if( block>=0 ) return block; + if( block >= 0 ) return block; // If center is open, take it - if( board[4]==' ' ) return 4; + 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; + 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; + for( int i = 0; i < 9; i++ ) if( board[i] == ' ' ) return i; return -1; }; @@ -136,30 +136,30 @@ val _draw = { !sys.draw.Canvas screen, u8[~] board, int hover -> 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.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]==' ' ) + if( !finished && hover >= 0 && hover < 9 && board[hover] == ' ' ) screen.fillRect(48+(hover-hover/3*3)*168,168+hover/3*168,168,168,0xd9e8de); - for( int i=1; i<3; i++ ) { + 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++ ) { + for( int i = 0; i < 9; i++ ) { int cx = 132+(i-i/3*3)*168, cy = 252+i/3*168; - if( board[i]=='X' ) + 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); + 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; + 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-first/3*3)*168,252+first/3*168,132+(last-last/3*3)*168,252+last/3*168,5,0xeab64e); } screen.text(48,704,"CLICK A SQUARE OR PRESS 1-9",3,paper); diff --git a/chapter31/docs/intrinsics.md b/chapter31/docs/intrinsics.md new file mode 100644 index 00000000..3aae39bd --- /dev/null +++ b/chapter31/docs/intrinsics.md @@ -0,0 +1,53 @@ +# Fixed-semantics C intrinsics + +An intrinsic is an ordinary C binding with a reserved external symbol and a +fixed signature and meaning. The compiler may replace a known call with ideal +IR nodes; it does not match the spelling of the caller's local variable or a +Simple function with the same name. No new expression syntax is involved. + +The first intrinsics preserve IEEE binary64 representations: + +| External C symbol | Signature | Public alias | +| --- | --- | --- | +| `simple_f64_bits` | `{ f64 -> i64 }` | `sys.math.f64Bits` | +| `simple_f64_from_bits` | `{ i64 -> f64 }` | `sys.math.f64FromBits` | + +```simple +i64 bits = sys.math.f64Bits(1.0); // 0x3ff0000000000000 +f64 value = sys.math.f64FromBits(bits); // 1.0 +int numeric = value; // Numeric conversion, still 1. +``` + +Both operations preserve signed zero, infinities, subnormals, and NaN signs and +payloads, including the signaling bit. They perform no arithmetic and have no +memory effects. An `i64` holds the bit pattern; its sign is irrelevant to the +conversion. Applying either operation followed by the other is an identity. +Floating-point arithmetic between conversions retains its usual semantics and +may change a NaN representation. + +`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. +Aliases and imported bindings use the existing external-function identity map. + +Unknown indirect targets keep ordinary calls. `simple_crt.c` supplies real C +definitions, using `memcpy` to preserve representations without aliasing tricks. +These symbols have fixed semantics: a replacement implementation 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 and expand to nodes with appropriate 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 CTAGS=` checks folding, representation preservation, +type errors, side effects, indirect C fallback, binary imports, and instruction +selection on all three backends, plus ARM/RISC-V emulation and native x86 execution. diff --git a/chapter31/graphics.mk b/chapter31/graphics.mk index 5b0bce09..2b557eea 100644 --- a/chapter31/graphics.mk +++ b/chapter31/graphics.mk @@ -24,6 +24,14 @@ MINIFB_SOURCES = $(addprefix $(MINIFB_SRC)/src/,$(addsuffix .c,$(MINIFB_COMMON) 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) diff --git a/chapter31/src/main/c/simple_crt.c b/chapter31/src/main/c/simple_crt.c index 438ae5f9..39708629 100644 --- a/chapter31/src/main/c/simple_crt.c +++ b/chapter31/src/main/c/simple_crt.c @@ -6,6 +6,19 @@ #include <termios.h> #include <unistd.h> +// 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; +} + // 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/chapter31/src/main/java/com/seaofnodes/simple/codegen/CodeGen.java b/chapter31/src/main/java/com/seaofnodes/simple/codegen/CodeGen.java index b4c93e1e..8618b47b 100644 --- a/chapter31/src/main/java/com/seaofnodes/simple/codegen/CodeGen.java +++ b/chapter31/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/chapter31/src/main/java/com/seaofnodes/simple/codegen/ElfWriter.java b/chapter31/src/main/java/com/seaofnodes/simple/codegen/ElfWriter.java index fcf5c287..c5b25be0 100644 --- a/chapter31/src/main/java/com/seaofnodes/simple/codegen/ElfWriter.java +++ b/chapter31/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/chapter31/src/main/java/com/seaofnodes/simple/codegen/IterPeeps.java b/chapter31/src/main/java/com/seaofnodes/simple/codegen/IterPeeps.java index 985cd4d2..f4acb729 100644 --- a/chapter31/src/main/java/com/seaofnodes/simple/codegen/IterPeeps.java +++ b/chapter31/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<Node> 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/chapter31/src/main/java/com/seaofnodes/simple/codegen/RegAlloc.java b/chapter31/src/main/java/com/seaofnodes/simple/codegen/RegAlloc.java index 3991cd48..1b335c50 100644 --- a/chapter31/src/main/java/com/seaofnodes/simple/codegen/RegAlloc.java +++ b/chapter31/src/main/java/com/seaofnodes/simple/codegen/RegAlloc.java @@ -215,7 +215,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 ? "<root>" : fun.label())); diff --git a/chapter31/src/main/java/com/seaofnodes/simple/codegen/Serialize.java b/chapter31/src/main/java/com/seaofnodes/simple/codegen/Serialize.java index 79bebe1f..b168c4af 100644 --- a/chapter31/src/main/java/com/seaofnodes/simple/codegen/Serialize.java +++ b/chapter31/src/main/java/com/seaofnodes/simple/codegen/Serialize.java @@ -448,7 +448,11 @@ public class Serialize { // TYPES names the mutable array declaration. Read-only arrays in // imported signatures keep their own types, but must not replace that // declaration: closeOver looks up its mutable variant by name. - if( ts.isAry() ) ts = ts.replace(ts.field("[]").makeFrom(false)); + if( ts.isConAry() ) { + TypeConAry ary=(TypeConAry)ts.field("[]")._t; + ts=TypeStruct.makeAry(ts._name,TypeInteger.U32,ts.field("#")._alias, + ary.storageType(),ts.field("[]")._alias,false); + } else if( ts.isAry() ) ts = ts.replace(ts.field("[]").makeFrom(false)); Parser.TYPES.put(ts._name,ts); } diff --git a/chapter31/src/main/java/com/seaofnodes/simple/codegen/StaticData.java b/chapter31/src/main/java/com/seaofnodes/simple/codegen/StaticData.java index 5d1a519b..3d3a40dd 100644 --- a/chapter31/src/main/java/com/seaofnodes/simple/codegen/StaticData.java +++ b/chapter31/src/main/java/com/seaofnodes/simple/codegen/StaticData.java @@ -14,7 +14,10 @@ public final class StaticData { public final String symbol; public final boolean readOnly, external; public final int alignment, size; + // Source names are aliases, not part of the object's pooling identity. + final TreeSet<String> 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/chapter31/src/main/java/com/seaofnodes/simple/node/ArrayInitNode.java b/chapter31/src/main/java/com/seaofnodes/simple/node/ArrayInitNode.java index 30f86ac6..c6ae90ea 100644 --- a/chapter31/src/main/java/com/seaofnodes/simple/node/ArrayInitNode.java +++ b/chapter31/src/main/java/com/seaofnodes/simple/node/ArrayInitNode.java @@ -22,7 +22,33 @@ public final class ArrayInitNode extends Node { } @Override public String label() { return "ArrayInit"; } @Override protected ExprPrinter<Node> _print1(ExprPrinter<Node> p) { return p.p("arrayInit(").n(in(2)).p(")"); } - @Override public Type compute() { return in(0)._type==Type.CONTROL ? in(2)._type : Type.TOP; } + @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; diff --git a/chapter31/src/main/java/com/seaofnodes/simple/node/BulkMemPhiNode.java b/chapter31/src/main/java/com/seaofnodes/simple/node/BulkMemPhiNode.java index 130b631c..b49163e7 100644 --- a/chapter31/src/main/java/com/seaofnodes/simple/node/BulkMemPhiNode.java +++ b/chapter31/src/main/java/com/seaofnodes/simple/node/BulkMemPhiNode.java @@ -261,15 +261,35 @@ public class BulkMemPhiNode extends PhiNode { mphi = new MemPhiNode(ScopeNode.memName(alias),alias); mphi.addDef(region()); // Due to cycles, must set before calling peephole - // Splitting preserves the bulk Phi's established escape bound. Starting - // at BOT would temporarily invent escapes when the new slice is merged. + // An escaped slice must preserve the bulk Phi's established bound. + // An unescaped slice was excluded from that summary: include the + // facts hidden in predecessor slices before wiring any cyclic Phis. TypeMem old = (TypeMem)_type; + if( !XInt.bit(old._escAs,alias) ) + old = (TypeMem)old.meet(sliceBound(this,alias,new BitSet())); mphi.setType(TypeMem.make(alias,old._t,old._one,old._clz,false,old._escFs,old._escAs)); for( int i=1; i<nIns(); i++ ) mphi.addDef(CodeGen.CODE.add(preciseInput(in(i),alias))); return CodeGen.CODE.add(mphi); } + // A bulk summary ignores unescaped slots in MemMerge inputs. Follow the + // same slots that splitting will expose, including across loop backedges. + // A visited cycle contributes TOP; its incoming definitions supply the bound. + private static TypeMem sliceBound(Node mem, int alias, BitSet visit) { + if( visit.get(mem._nid) ) return TypeMem.TOP; + visit.set(mem._nid); + if( mem instanceof MemMergeNode merge ) + return sliceBound(merge.alias(alias),alias,visit); + if( mem instanceof BulkMemPhiNode bulk ) { + TypeMem bound = TypeMem.TOP; + for( int i = 1; i < bulk.nIns(); i++ ) + bound = (TypeMem)bound.meet(sliceBound(bulk.in(i),alias,visit)); + return bound; + } + return mem._type instanceof TypeMem bound ? bound : TypeMem.BOT; + } + MemPhiNode _findPhi(int alias) { for( Node use : region().outs() ) if( use instanceof MemPhiNode mphi && mphi._alias==alias ) diff --git a/chapter31/src/main/java/com/seaofnodes/simple/node/CallEndNode.java b/chapter31/src/main/java/com/seaofnodes/simple/node/CallEndNode.java index b5156c2d..108dd024 100644 --- a/chapter31/src/main/java/com/seaofnodes/simple/node/CallEndNode.java +++ b/chapter31/src/main/java/com/seaofnodes/simple/node/CallEndNode.java @@ -85,6 +85,8 @@ public class CallEndNode extends CFGNode implements MultiNode { return ftype.isHigh() ? TypeTuple.STATE.dual() : TypeTuple.STATE; // Mid-fold, just take the inlined callee's return. if( _folding ) return in(1)._type; + TypeTuple intrinsic=Intrinsic.compute(call,this); + if( intrinsic!=null ) return intrinsic; // The outside continuation reads Start directly: Call can remain // CONTROL while its possible returned identities change. @@ -135,6 +137,8 @@ public class CallEndNode extends CFGNode implements MultiNode { } public byte maybeInline() { + byte intrinsic=Intrinsic.tryInline(this); + if( intrinsic>0 ) return intrinsic; byte inline = inlineCandidate(false); if( CodeGen.CODE._midAssert ) return inline; diff --git a/chapter31/src/main/java/com/seaofnodes/simple/node/CallNode.java b/chapter31/src/main/java/com/seaofnodes/simple/node/CallNode.java index ac5e4eee..690acfb9 100644 --- a/chapter31/src/main/java/com/seaofnodes/simple/node/CallNode.java +++ b/chapter31/src/main/java/com/seaofnodes/simple/node/CallNode.java @@ -97,6 +97,7 @@ public class CallNode extends CFGNode { if( _type!=Type.CONTROL ) return TypeMem.BOT; if( !(fptr()._type instanceof TypeFunPtr) ) return fptr()._type.isHigh() ? TypeMem.START : TypeMem.BOT; + if( Intrinsic.pure(this) ) return TypeMem.START; if( !external() ) return TypeMem.START; Type input = dep.addDepForwards(mem())._type; TypeMem escaped = input instanceof TypeMem m ? m : input.isHigh() ? TypeMem.TOP : TypeMem.BOT; @@ -241,6 +242,8 @@ public class CallNode extends CFGNode { return Parser.error("Expected a function, but found " + fptr()._type, _loc); if( !tfp.notNull() ) return Parser.error( "Might be null calling "+tfp, _loc); + Parser.ParseException intrinsic=Intrinsic.err(this); + if( intrinsic!=null ) return intrinsic; if( nargs() != tfp.nargs() ) return Parser.error( "Expecting "+(tfp.nargs()-1)+" arguments, but found "+(nargs()-1), _loc); diff --git a/chapter31/src/main/java/com/seaofnodes/simple/node/EscapeNode.java b/chapter31/src/main/java/com/seaofnodes/simple/node/EscapeNode.java index 57340609..a8a6151c 100644 --- a/chapter31/src/main/java/com/seaofnodes/simple/node/EscapeNode.java +++ b/chapter31/src/main/java/com/seaofnodes/simple/node/EscapeNode.java @@ -64,6 +64,10 @@ public class EscapeNode extends TypeNode { @Override public Type compute() { + // A static constant array has no private heap writes to publish. + // This depends on its type, regardless of which node produced it. + if( self()!=null && self()._type instanceof TypeMemPtr ptr && + ptr.isConstant() && ptr._obj.isConAry() ) return pub()._type; if( priv()._type.isHigh() ) return TypeMem.TOP; if( pub ()._type.isHigh() ) return TypeMem.TOP; TypeMem mpriv = (TypeMem)priv()._type; @@ -100,6 +104,8 @@ public class EscapeNode extends TypeNode { } @Override public Node idealize() { + if( self()._type instanceof TypeMemPtr ptr && ptr.isConstant() && ptr._obj.isConAry() ) + return pub(); // Sharpen private memory input if( priv() instanceof MemMergeNode mmm ) { setDef(2,mmm.alias(fld()._alias)); diff --git a/chapter31/src/main/java/com/seaofnodes/simple/node/Intrinsic.java b/chapter31/src/main/java/com/seaofnodes/simple/node/Intrinsic.java new file mode 100644 index 00000000..82626507 --- /dev/null +++ b/chapter31/src/main/java/com/seaofnodes/simple/node/Intrinsic.java @@ -0,0 +1,119 @@ +package com.seaofnodes.simple.node; + +import com.seaofnodes.simple.codegen.CodeGen; +import com.seaofnodes.simple.parser.Parser; +import com.seaofnodes.simple.type.*; + +// Fixed-semantics C functions. Recognition, effects and expansion live here; +// Call/CallEnd only delegate. These symbols also have ordinary C definitions +// for calls whose target is not known at compile time. +public final class Intrinsic { + private Intrinsic() {} + + private enum Op { + F64_BITS("simple_f64_bits",TypeFloat.F64,TypeInteger.BOT,true), + F64_FROM_BITS("simple_f64_from_bits",TypeInteger.BOT,TypeFloat.F64,true); + + final String symbol; + final Type arg, ret; + final boolean pure; + Op(String symbol, Type arg, Type ret, boolean pure) { + this.symbol=symbol; this.arg=arg; this.ret=ret; this.pure=pure; + } + boolean signature(TypeFunPtr fp) { + // Slot zero is the implicit receiver, omitted by the C ABI. + return fp.nargs()==2 && fp.arg(1)==arg && fp.ret()==ret; + } + Expansion expand(CallNode call) { + Node value=switch(this) { + case F64_BITS -> new F64BitsNode(call.arg(3)).peephole(); + case F64_FROM_BITS -> new F64FromBitsNode(call.arg(3)).peephole(); + }; + return new Expansion(call.ctrl(),call.mem(),value); + } + } + + private static Op lookup(CallNode call) { + if( !(call.fptr()._type instanceof TypeFunPtr fp) || !fp.notNull() || !fp.isConstant() ) return null; + String symbol=CodeGen.CODE.externFunc(fp.fidx()); + if( symbol==null ) return null; // A Simple function with this name is ordinary code. + for( Op op : Op.values() ) if( op.symbol.equals(symbol) ) return op; + return null; + } + + public static Parser.ParseException err(CallNode call) { + Op op=lookup(call); + return op==null || op.signature(call.tfp()) ? null : Parser.error( + "Intrinsic '"+op.symbol+"' requires { "+op.arg.str()+" -> "+op.ret.str()+" }",call._loc); + } + + // Both initial operations are pure and expose no references. Future atomic + // operations need their own memory/escape semantics, not this passthrough. + public static boolean pure(CallNode call) { + Op op=lookup(call); + return op!=null && op.pure && op.signature(call.tfp()); + } + + public static TypeTuple compute(CallNode call, Node dep) { + if( !pure(call) ) return null; + return TypeTuple.make(Type.CONTROL,dep.addDep(call.mem())._type,call.tfp().ret()); + } + + // An expansion replaces the complete call state, even for a pure value op. + private record Expansion(Node control, Node memory, Node value) { + void replace(CallEndNode end) { + Node[] state={control,memory,value}; + for( Node n : state ) n.keep(); + end.keep(); + for( Node use : end._outputs.asAry() ) { + if( use==null ) continue; // Our temporary keep. + assert use instanceof Proj; + use.subsume(state[((Proj)use).idx()]); + } + end.unkill(); + for( Node n : state ) n.unkill(); + CodeGen.CODE.invalidateIDepthCaches(); + } + } + + // Same cheap-inlining worklist as ordinary functions, but no body/Return, + // cloning, size heuristic, or import loading is needed. + public static byte tryInline(CallEndNode end) { + if( end.folding() || !(end.in(0) instanceof CallNode call) ) return 0; + Op op=lookup(call); + if( op==null || !op.signature(call.tfp()) || call.nargs()!=call.tfp().nargs() || + !end.goodArgs(call,call.tfp()) ) return 0; + if( !CodeGen.CODE._midAssert ) op.expand(call).replace(end); + return 1; + } + + public abstract static class BitCastNode extends Node { + BitCastNode(Node value) { super(null,value); } + public abstract boolean toBits(); + @Override public Type compute() { + Type input=in(1)._type; + Type result=toBits() ? TypeInteger.BOT : TypeFloat.F64; + if( input.isHigh() ) return result.dual(); + if( toBits() && input instanceof TypeFloat f && f.isConstant() ) + return TypeInteger.constant(Double.doubleToRawLongBits(f.value())); + if( !toBits() && input instanceof TypeInteger i && i.isConstant() ) + return TypeFloat.constant(Double.longBitsToDouble(i.value())); + return result; + } + @Override public Node idealize() { + return in(1) instanceof BitCastNode cast && cast.toBits()!=toBits() ? cast.in(1) : null; + } + } + public static final class F64BitsNode extends BitCastNode { + public F64BitsNode(Node value) { super(value); } + @Override public boolean toBits() { return true; } + @Override public Tag serialTag() { return Tag.F64Bits; } + @Override protected String format() { return "f64Bits(%1)"; } + } + public static final class F64FromBitsNode extends BitCastNode { + public F64FromBitsNode(Node value) { super(value); } + @Override public boolean toBits() { return false; } + @Override public Tag serialTag() { return Tag.F64FromBits; } + @Override protected String format() { return "f64FromBits(%1)"; } + } +} diff --git a/chapter31/src/main/java/com/seaofnodes/simple/node/MemOpNode.java b/chapter31/src/main/java/com/seaofnodes/simple/node/MemOpNode.java index 35183380..bce11b50 100644 --- a/chapter31/src/main/java/com/seaofnodes/simple/node/MemOpNode.java +++ b/chapter31/src/main/java/com/seaofnodes/simple/node/MemOpNode.java @@ -94,7 +94,8 @@ public abstract class MemOpNode extends TypeNode { if( !(ptr()._type instanceof TypeMemPtr tmp) ) return Type.BOTTOM; Field fld = tmp._obj.field(_name); - return fld == null || fld._t == null ? Type.BOTTOM : fld._t; + return fld == null || fld._t == null ? Type.BOTTOM : + fld._t instanceof TypeConAry ary ? ary.storageType() : fld._t; } @Override protected ExprPrinter<Node> _print1(ExprPrinter<Node> p) { return _printMach(p); } diff --git a/chapter31/src/main/java/com/seaofnodes/simple/node/Node.java b/chapter31/src/main/java/com/seaofnodes/simple/node/Node.java index 2815dfba..d4c0794c 100644 --- a/chapter31/src/main/java/com/seaofnodes/simple/node/Node.java +++ b/chapter31/src/main/java/com/seaofnodes/simple/node/Node.java @@ -77,7 +77,7 @@ public abstract class Node extends BaseNode<Node> implements Cloneable { New,Never,Not,Or,Parm,Phi,Proj,PtrToInt, ReadOnly,Return,Region,RoundF32, Sar,Shl,Shr,Start,StartCU,StopCU,Stop,Store,Sub, - ToInteger,ToFloat,XCtrl,Xor; + ToInteger,ToFloat,XCtrl,Xor,F64Bits,F64FromBits; public static final Tag[] VALS = values(); public Node make( BAOS bais, String[] strs, Type[] types, GlobalBits fileAliases, GlobalBits aliases ) { return switch(this) { @@ -103,6 +103,8 @@ public abstract class Node extends BaseNode<Node> implements Cloneable { case Sub -> new SubNode(null,null,(byte)bais.packed1()); case ToFloat-> new ToFloatNode(null); case ToInteger-> new ToIntegerNode(null); + case F64Bits-> new Intrinsic.F64BitsNode(null); + case F64FromBits-> new Intrinsic.F64FromBitsNode(null); case XCtrl -> new XCtrlNode(); case Xor -> { int mode=bais.packed1(); assert mode==1; yield new XorNode(null,null,null); } diff --git a/chapter31/src/main/java/com/seaofnodes/simple/node/cpus/arm/BitCastARM.java b/chapter31/src/main/java/com/seaofnodes/simple/node/cpus/arm/BitCastARM.java new file mode 100644 index 00000000..ec57b3f8 --- /dev/null +++ b/chapter31/src/main/java/com/seaofnodes/simple/node/cpus/arm/BitCastARM.java @@ -0,0 +1,23 @@ +package com.seaofnodes.simple.node.cpus.arm; + +import com.seaofnodes.isa.Arm64; +import com.seaofnodes.simple.codegen.*; +import com.seaofnodes.simple.node.*; +import com.seaofnodes.simple.util.SB; + +// A representation move, with no arithmetic, rounding, or flag changes. +public class BitCastARM extends MachConcreteNode implements MachNode { + private final boolean _toBits; + BitCastARM(Intrinsic.BitCastNode cast) { super(cast); _toBits=cast.toBits(); } + @Override public String op() { return _toBits ? "f64bits" : "f64frombits"; } + @Override public RegMask regmap(int i) { assert i==1; return _toBits ? arm.DMASK : arm.RMASK; } + @Override public RegMask outregmap() { return _toBits ? arm.WMASK : arm.DMASK; } + @Override public void encoding(Encoding enc) { + enc.add4(Arm64.f_mov_general(Arm64.OP_FMOV,0b01,0,_toBits ? 0b110 : 0b111, + enc.reg(in(1))-(_toBits ? arm.D_OFFSET : 0), + enc.reg(this)-(_toBits ? 0 : arm.D_OFFSET))); + } + @Override public void asm(CodeGen code, SB sb) { + sb.p(code.reg(this)).p(" = bits ").p(code.reg(in(1))); + } +} diff --git a/chapter31/src/main/java/com/seaofnodes/simple/node/cpus/arm/arm.java b/chapter31/src/main/java/com/seaofnodes/simple/node/cpus/arm/arm.java index ee7b0fc3..2d47edf5 100644 --- a/chapter31/src/main/java/com/seaofnodes/simple/node/cpus/arm/arm.java +++ b/chapter31/src/main/java/com/seaofnodes/simple/node/cpus/arm/arm.java @@ -350,6 +350,7 @@ public class arm extends Machine { case StoreNode st -> st(st); case SubNode sub -> sub.mode()==2 ? new SubFARM(sub) : sub(sub); case ToFloatNode tfn -> new I2F8ARM(tfn); + case Intrinsic.BitCastNode cast -> new BitCastARM(cast); case ToIntegerNode cvt -> new F8ToIARM(cvt); case XorNode xor -> xor(xor); diff --git a/chapter31/src/main/java/com/seaofnodes/simple/node/cpus/riscv/BitCastRISC.java b/chapter31/src/main/java/com/seaofnodes/simple/node/cpus/riscv/BitCastRISC.java new file mode 100644 index 00000000..141ff7d5 --- /dev/null +++ b/chapter31/src/main/java/com/seaofnodes/simple/node/cpus/riscv/BitCastRISC.java @@ -0,0 +1,23 @@ +package com.seaofnodes.simple.node.cpus.riscv; + +import com.seaofnodes.isa.RiscV; +import com.seaofnodes.simple.codegen.*; +import com.seaofnodes.simple.node.*; +import com.seaofnodes.simple.util.SB; + +// A representation move, with no arithmetic, rounding, or flag changes. +public class BitCastRISC extends MachConcreteNode implements MachNode { + private final boolean _toBits; + BitCastRISC(Intrinsic.BitCastNode cast) { super(cast); _toBits=cast.toBits(); } + @Override public String op() { return _toBits ? "f64bits" : "f64frombits"; } + @Override public RegMask regmap(int i) { assert i==1; return _toBits ? riscv.FMASK : riscv.RMASK; } + @Override public RegMask outregmap() { return _toBits ? riscv.WMASK : riscv.FMASK; } + @Override public void encoding(Encoding enc) { + enc.add4(RiscV.r_type(RiscV.OP_FP, + enc.reg(this)-(_toBits ? 0 : riscv.F_OFFSET),0, + enc.reg(in(1))-(_toBits ? riscv.F_OFFSET : 0),0,_toBits ? 0b1110001 : 0b1111001)); + } + @Override public void asm(CodeGen code, SB sb) { + sb.p(code.reg(this)).p(" = bits ").p(code.reg(in(1))); + } +} diff --git a/chapter31/src/main/java/com/seaofnodes/simple/node/cpus/riscv/SplitRISC.java b/chapter31/src/main/java/com/seaofnodes/simple/node/cpus/riscv/SplitRISC.java index d455337b..de754393 100644 --- a/chapter31/src/main/java/com/seaofnodes/simple/node/cpus/riscv/SplitRISC.java +++ b/chapter31/src/main/java/com/seaofnodes/simple/node/cpus/riscv/SplitRISC.java @@ -47,7 +47,7 @@ public class SplitRISC extends SplitNode { // FPR->FPR src -= riscv.F_OFFSET; dst -= riscv.F_OFFSET; - enc.add4(RiscV.r_type(RiscV.OP_FP, dst, 0b000, src, src, 0b0010101)); // dst = FMIN(src,src) + enc.add4(RiscV.r_type(RiscV.OP_FP, dst, 0b000, src, src, 0b0010001)); // FSGNJ.D preserves NaN bits. } else if(!srcX && dstX) { //GPR->FPR // fmv.d.x diff --git a/chapter31/src/main/java/com/seaofnodes/simple/node/cpus/riscv/riscv.java b/chapter31/src/main/java/com/seaofnodes/simple/node/cpus/riscv/riscv.java index 378955a5..976d1a52 100644 --- a/chapter31/src/main/java/com/seaofnodes/simple/node/cpus/riscv/riscv.java +++ b/chapter31/src/main/java/com/seaofnodes/simple/node/cpus/riscv/riscv.java @@ -254,6 +254,7 @@ public class riscv extends Machine { case StoreNode st -> st(st); case SubNode sub -> sub.mode()==2 ? new SubFRISC(sub) : sub(sub); case ToFloatNode tfn -> i2f8(tfn); + case Intrinsic.BitCastNode cast -> new BitCastRISC(cast); case ToIntegerNode cvt -> new F8ToIRISC(cvt); case XorNode xor -> xor(xor); diff --git a/chapter31/src/main/java/com/seaofnodes/simple/node/cpus/x86_64_v2/BitCastX86.java b/chapter31/src/main/java/com/seaofnodes/simple/node/cpus/x86_64_v2/BitCastX86.java new file mode 100644 index 00000000..bf550032 --- /dev/null +++ b/chapter31/src/main/java/com/seaofnodes/simple/node/cpus/x86_64_v2/BitCastX86.java @@ -0,0 +1,23 @@ +package com.seaofnodes.simple.node.cpus.x86_64_v2; + +import com.seaofnodes.isa.X86; +import com.seaofnodes.simple.codegen.*; +import com.seaofnodes.simple.node.*; +import com.seaofnodes.simple.util.SB; + +// A representation move, with no arithmetic, rounding, or flag changes. +public class BitCastX86 extends MachConcreteNode implements MachNode { + private final boolean _toBits; + BitCastX86(Intrinsic.BitCastNode cast) { super(cast); _toBits=cast.toBits(); } + @Override public String op() { return _toBits ? "f64bits" : "f64frombits"; } + @Override public RegMask regmap(int i) { assert i==1; return _toBits ? x86_64_v2.XMASK : x86_64_v2.RMASK; } + @Override public RegMask outregmap() { return _toBits ? x86_64_v2.WMASK : x86_64_v2.XMASK; } + @Override public void encoding(Encoding enc) { + X86.move(enc,!_toBits,_toBits, + enc.reg(this)-(_toBits ? 0 : x86_64_v2.XMM_OFFSET), + enc.reg(in(1))-(_toBits ? x86_64_v2.XMM_OFFSET : 0)); + } + @Override public void asm(CodeGen code, SB sb) { + sb.p(code.reg(this)).p(" = bits ").p(code.reg(in(1))); + } +} diff --git a/chapter31/src/main/java/com/seaofnodes/simple/node/cpus/x86_64_v2/NegFX86.java b/chapter31/src/main/java/com/seaofnodes/simple/node/cpus/x86_64_v2/NegFX86.java new file mode 100644 index 00000000..61662fd2 --- /dev/null +++ b/chapter31/src/main/java/com/seaofnodes/simple/node/cpus/x86_64_v2/NegFX86.java @@ -0,0 +1,25 @@ +package com.seaofnodes.simple.node.cpus.x86_64_v2; + +import com.seaofnodes.isa.X86; +import com.seaofnodes.simple.codegen.*; +import com.seaofnodes.simple.node.*; +import com.seaofnodes.simple.type.TypeFloat; +import com.seaofnodes.simple.util.SB; + +// Flip the sign bit, preserving signed zero, infinities, and NaN payloads. +public class NegFX86 extends MachConcreteNode implements MachNode { + NegFX86(MinusNode neg) { + super(neg); + addDef(new FltX86(new ConstantNode(TypeFloat.constant(-0.0)),null)); + } + @Override public String op() { return "negf"; } + @Override public RegMask regmap(int i) { assert i==1 || i==2; return x86_64_v2.XMASK; } + @Override public RegMask outregmap() { return x86_64_v2.XMASK; } + @Override public int twoAddress() { return 1; } + @Override public void encoding(Encoding enc) { + X86.sse(enc,0x66,0x0F57,false,enc.reg(this)-x86_64_v2.XMM_OFFSET,enc.reg(in(2))-x86_64_v2.XMM_OFFSET); + } + @Override public void asm(CodeGen code, SB sb) { + sb.p(code.reg(this)).p(" ^= ").p(code.reg(in(2))).p(" // sign bit"); + } +} diff --git a/chapter31/src/main/java/com/seaofnodes/simple/node/cpus/x86_64_v2/x86_64_v2.java b/chapter31/src/main/java/com/seaofnodes/simple/node/cpus/x86_64_v2/x86_64_v2.java index aed8ee4c..dc15b185 100644 --- a/chapter31/src/main/java/com/seaofnodes/simple/node/cpus/x86_64_v2/x86_64_v2.java +++ b/chapter31/src/main/java/com/seaofnodes/simple/node/cpus/x86_64_v2/x86_64_v2.java @@ -294,6 +294,7 @@ public class x86_64_v2 extends Machine { public Node instSelect(Node n) { return switch (n) { case AddNode add -> add(add); + case Intrinsic.BitCastNode cast -> new BitCastX86(cast); case AndNode and -> and(and); case BoolNode bool -> cmp(bool); case CLInitNode init -> new CLInitNode(init); @@ -310,10 +311,7 @@ public class x86_64_v2 extends Machine { case IfNode iff -> jmp(iff); case LoadNode ld -> ld(ld); case MemMergeNode mem -> new MemMergeNode(mem); - case MinusNode neg -> { - if( neg.mode()==2 ) throw Utils.TODO(); - yield new NegX86(neg); - } + case MinusNode neg -> neg.mode()==2 ? new NegFX86(neg) : new NegX86(neg); case MulNode mul -> mul.mode()==2 ? new MulFX86(mul) : mul(mul); case NewNode nnn -> new NewX86(nnn); case NotNode not -> new NotX86(not); diff --git a/chapter31/src/main/java/com/seaofnodes/simple/parser/Allocations.java b/chapter31/src/main/java/com/seaofnodes/simple/parser/Allocations.java index 5c6b5765..64234045 100644 --- a/chapter31/src/main/java/com/seaofnodes/simple/parser/Allocations.java +++ b/chapter31/src/main/java/com/seaofnodes/simple/parser/Allocations.java @@ -124,7 +124,7 @@ final class Allocations { TypeStruct ts = P.types.typeAry(TypeInteger.U8,true); int lenAlias = ts.field("#" )._alias; int elemAlias = ts.field("[]")._alias; - TypeConAryB body = TypeConAryB.make(s); + TypeConAry body = TypeConAry.make(s); TypeInteger slen = TypeInteger.constant(s.length); // Make a TMP, not-null (byte)2, singleton (true) (requires text // strings are hash-interned), with a TypeStruct having a constant diff --git a/chapter31/src/main/java/com/seaofnodes/simple/parser/ArrayInitializers.java b/chapter31/src/main/java/com/seaofnodes/simple/parser/ArrayInitializers.java index 70eeae1f..079853cd 100644 --- a/chapter31/src/main/java/com/seaofnodes/simple/parser/ArrayInitializers.java +++ b/chapter31/src/main/java/com/seaofnodes/simple/parser/ArrayInitializers.java @@ -66,13 +66,15 @@ final class ArrayInitializers { } } + Node result=new ArrayInitNode(P.ctrl(),mem,self,len, + generator ? -1 : values.size(),site,values).peephole().keep(); Node prior=P.mem(); - P.mem(P.mergeAlias(prior,length._alias,new EscapeNode(length,self,slen.unkeep(),prior).peephole())); + P.mem(P.mergeAlias(prior,length._alias,new EscapeNode(length,result,slen.unkeep(),prior).peephole())); prior=P.mem(); - P.mem(P.mergeAlias(prior,body._alias,new EscapeNode(body,self,mem,prior).peephole())); - Node result=new ArrayInitNode(P.ctrl(),mem.unkeep(),self.unkeep(),len.unkeep(), - generator ? -1 : values.size(),site,values).peephole(); + P.mem(P.mergeAlias(prior,body._alias,new EscapeNode(body,result,mem,prior).peephole())); + mem.unkeep(); self.unkeep(); len.unkeep(); for( Node value : values ) value.unkeep(); + result.unkeep(); return readonly ? new ReadOnlyNode(result).peephole() : result; } diff --git a/chapter31/src/main/java/com/seaofnodes/simple/parser/Conversions.java b/chapter31/src/main/java/com/seaofnodes/simple/parser/Conversions.java index fa11311d..72247ca6 100644 --- a/chapter31/src/main/java/com/seaofnodes/simple/parser/Conversions.java +++ b/chapter31/src/main/java/com/seaofnodes/simple/parser/Conversions.java @@ -37,7 +37,7 @@ final class Conversions { case TypeFloat tf -> TypeFloat.F64; case TypeMemPtr tmp -> tmp.makeVar(); case TypeFunPtr tfp -> tfp; - case TypeConAry<?> a -> a; + case TypeConAry a -> a; case TypePtr ptr -> TypePtr.PTR; case TypeScalar ts -> TypeScalar.BOT; default -> t; diff --git a/chapter31/src/main/java/com/seaofnodes/simple/print/ASMPrinter.java b/chapter31/src/main/java/com/seaofnodes/simple/print/ASMPrinter.java index bdd887e6..e4d1659d 100644 --- a/chapter31/src/main/java/com/seaofnodes/simple/print/ASMPrinter.java +++ b/chapter31/src/main/java/com/seaofnodes/simple/print/ASMPrinter.java @@ -16,13 +16,16 @@ import java.util.Map; public final class ASMPrinter extends AssemblyAdapter<Node> { private final CodeGen _code; private final Encoding _enc; - private ASMPrinter(CodeGen code) { + private ASMPrinter(CodeGen code, Encoding enc) { super(new IRPrinter()); _code=code; - _enc=code._encoding; + _enc=enc; } public static SB print(SB sb, CodeGen code) { - return sb.p(new com.seaofnodes.print.ASMPrinter<>(new ASMPrinter(code)).print()); + return print(sb,code,code._encoding); + } + public static SB print(SB sb, CodeGen code, Encoding enc) { + return sb.p(new com.seaofnodes.print.ASMPrinter<>(new ASMPrinter(code,enc)).print()); } @Override public ArrayList<Node> blocks() { var blocks=new ArrayList<Node>(); @@ -89,7 +92,7 @@ public final class ASMPrinter extends AssemblyAdapter<Node> { var data=new ArrayList<Data>(); for( var obj : _enc._data.entries() ) if( !obj.external && obj.readOnly==ro ) - data.add(new Data(obj,obj.symbol+": "+obj.type.str(),obj.alignment,obj.size)); + data.add(new Data(obj,obj.label()+": "+obj.type.str(),obj.alignment,obj.size)); return data; } // Retain this diagnostic entry point for checking that pool printing never lays out types. diff --git a/chapter31/src/main/java/com/seaofnodes/simple/type/Type.java b/chapter31/src/main/java/com/seaofnodes/simple/type/Type.java index 0f655f49..2e228494 100644 --- a/chapter31/src/main/java/com/seaofnodes/simple/type/Type.java +++ b/chapter31/src/main/java/com/seaofnodes/simple/type/Type.java @@ -531,7 +531,7 @@ public class Type /*implements Cloneable*/ { // tag-space except for the first tag-space which uses 1 tag for // multiple Types instead of 1 Type having multiple tags. Has to // be ordered to match _type enum. - for( Type t : new Type[]{Type.XNIL,TypeScalar.BOT,TypePtr.PTR,TypeInteger.BOT,TypeFloat.F64,TypeConAryB.ABC,TypeRPC.BOT,TypeMemPtr.BOT,TypeFunPtr.BOT,TypeMem.BOT,Field.BOT,TypeStruct.BOT,TypeTuple.BOT} ) + for( Type t : new Type[]{Type.XNIL,TypeScalar.BOT,TypePtr.PTR,TypeInteger.BOT,TypeFloat.F64,TypeConAry.ABC,TypeRPC.BOT,TypeMemPtr.BOT,TypeFunPtr.BOT,TypeMem.BOT,Field.BOT,TypeStruct.BOT,TypeTuple.BOT} ) TAGOFFS[t._type+1] = TAGOFFS[t._type] + t.TAGOFF(); assert TAGOFFS[TMAX] <= 255; return TAGOFFS; diff --git a/chapter31/src/main/java/com/seaofnodes/simple/type/TypeConAry.java b/chapter31/src/main/java/com/seaofnodes/simple/type/TypeConAry.java index 9cb23e09..c10f09aa 100644 --- a/chapter31/src/main/java/com/seaofnodes/simple/type/TypeConAry.java +++ b/chapter31/src/main/java/com/seaofnodes/simple/type/TypeConAry.java @@ -1,33 +1,48 @@ package com.seaofnodes.simple.type; import com.seaofnodes.simple.util.BAOS; -import com.seaofnodes.simple.util.Utils; import java.util.ArrayList; +import java.util.Arrays; import java.util.HashMap; /** - * Represents a constant array of primitives + * Constant integer contents with an explicit storage width and signedness. */ -public abstract class TypeConAry<A> extends TypeScalar { +public final class TypeConAry extends TypeScalar { boolean _any; byte _widen; - // One of byte or int array - public final A _ary; + private final TypeInteger _storage; + private final long[] _ary; - TypeConAry( boolean any, byte widen, A ary ) { super(TCONARY); _any = any; _widen = widen; _ary = ary; } + private TypeConAry(boolean any, byte widen, TypeInteger storage, long[] ary) { + super(TCONARY); + _any=any; _widen=widen; _storage=storage; _ary=ary; + } + static final TypeConAry ABC=make("abc"); + static final TypeConAry ABCD=make("abcd"); public static void gather(ArrayList<Type> ts) { - ts.add(TypeConAryB.make("")); - ts.add(TypeConAryB.ABC); - ts.add(TypeConAryB.ABCD); - ts.add(TypeConAryI.I123); + ts.add(make("")); + ts.add(ABC); + ts.add(ABCD); + ts.add(make(TypeInteger.I32,new long[]{1,2,3})); + ts.add(make(TypeInteger.U16,new long[]{0,65535})); + ts.add(make(TypeInteger.BOT,new long[]{Long.MIN_VALUE,Long.MAX_VALUE})); + for( TypeInteger storage : STORAGE ) { + ts.add(make(storage,new long[0])); + ts.add(make(storage,new long[]{0,1})); + } } // Fresh, uninterned type sharing this array; xdual must not intern. - abstract TypeConAry<A> _make(boolean any, byte widen); + private TypeConAry _make(boolean any, byte widen) { + return new TypeConAry(any,widen,_storage,_ary); + } - @Override TypeConAry<A> xdual() { return _make( !_any, (byte)(3-_widen) ); } + @Override TypeConAry xdual() { return _make( !_any, (byte)(3-_widen) ); } @Override Type xmeet(Type t) { TypeConAry ary = (TypeConAry)t; // Invariant + if( len()==0 ) return emptyMeet(ary); + if( ary.len()==0 ) return ary.emptyMeet(this); // Same base array but different? if( _equals(ary) ) // Return array with larger widen @@ -37,15 +52,7 @@ public abstract class TypeConAry<A> extends TypeScalar { } Type ymeet( TypeInteger ti ) { - // Empty arrays have no observed elements: use the storage bounds. - // Check both endpoints just as the loop checks a nonempty body; - // retaining high integer inputs here preserves lattice duality. - if( len()==0 ) { - TypeInteger bound=emptyElem(); - if( !ti.isa(TypeInteger.make(bound._min,bound._min,ti._widen)) || - !ti.isa(TypeInteger.make(bound._max,bound._max,ti._widen)) ) - return ti.meet(bound); - } + if( len()==0 ) return emptyMeet(ti); // if i can isa *each* element, then maybe can keep. // no good to i.isa(elem()) because fails the dual for( int j=0; j<len(); j++ ) @@ -56,12 +63,21 @@ public abstract class TypeConAry<A> extends TypeScalar { } private boolean _equals(TypeConAry ary) { - int len = len(); - if( len != ary.len() ) return false; - for( int i=0; i<len; i++ ) - if( at8(i) != ary.at8(i) ) - return false; - return true; + return _storage==ary._storage && (len()!=0 || _any==ary._any) && Arrays.equals(_ary,ary._ary); + } + @Override boolean eq(Type t) { return t instanceof TypeConAry ary && _widen==ary._widen && _equals(ary); } + @Override int hash() { return Arrays.hashCode(_ary)^_storage.hashCode()^(len()==0 && _any ? 1231 : 0); } + @Override public String str() { + boolean text=_storage==TypeInteger.U8; + for( long value : _ary ) + if( value<32 || value>126 ) { text=false; break; } + if( !text ) { + String range=elem().str(); + return range.startsWith("[") ? range : "["+range+"]"; + } + byte[] bytes = new byte[len()]; + for( int i=0; i<bytes.length; i++ ) bytes[i]=(byte)_ary[i]; + return "[\""+new String(bytes)+"\"]"; } @Override public boolean isHigh() { return this==TOP; } @@ -70,8 +86,6 @@ public abstract class TypeConAry<A> extends TypeScalar { // Meet-over-elements type public Type elem() { - if( _ary==null ) - return _any ? Type.TOP : BOTTOM; int len = len(); long min = Long.MAX_VALUE; if( len==0 ) return emptyElem(); @@ -83,23 +97,80 @@ public abstract class TypeConAry<A> extends TypeScalar { return TypeInteger.make(min,max,_widen); } private TypeInteger emptyElem() { - return log_size()==0 ? TypeInteger.make(0,255,_widen) - : TypeInteger.make(Integer.MIN_VALUE,Integer.MAX_VALUE,_widen); + TypeInteger storage=storageType(); + return _any ? TypeInteger.make(storage._min,storage._max,_widen) + : TypeInteger.make(storage._max,storage._min,_widen); + } + // Keep the empty payload distinct from its element bound. It sits just + // above the storage dual; its own dual sits just below the storage bound. + // This makes it a subtype of every constant array within those bounds, + // while preserving meet/join symmetry with ordinary integer ranges. + private Type emptyMeet(Type t) { + Type bound=emptyElem(); + if( t.isa(bound) && (_any || t!=bound) ) return this; + return bound.meet(t); } - public abstract long at8(int idx); - public abstract int len(); - @Override public abstract int log_size(); - public void write( BAOS baos ) { throw Utils.TODO("Should not reach here: abstract constant array cannot be written"); } + public TypeInteger storageType() { return _storage; } + public long at8(int idx) { return _ary[idx]; } + public int len() { return _ary.length; } + @Override public int log_size() { return _storage.log_size(); } + public void write( BAOS baos ) { + for( int i=0; i<len(); i++ ) { + long value=at8(i); + for( int b=0; b<(1<<log_size()); b++ ) baos.write((byte)(value >>> (8*b))); + } + } + + /** Canonical contents, independent of the node which discovered them. */ + public static TypeConAry make(TypeInteger storage, long[] values) { + long[] copy=values.clone(); + int shift=64-(8<<storage.log_size()); + for( int i=0; i<copy.length; i++ ) + copy[i]=storage._min<0 ? (copy[i]<<shift)>>shift : copy[i]&storage._max; + return new TypeConAry(false,(byte)0,storage,copy).intern(); + } + public static TypeConAry make(byte[] bytes) { + long[] values=new long[bytes.length]; + for( int i=0; i<bytes.length; i++ ) values[i]=bytes[i]&255; + return new TypeConAry(false,(byte)0,TypeInteger.U8,values).intern(); + } + public static TypeConAry make(String s) { return make(s.getBytes()); } + + // Keep the existing byte-array tag and encoding. An impossible Java array + // length escapes to a typed payload, without renumbering later type tags. + private static final int TYPED = -1; + private static final TypeInteger[] STORAGE={TypeInteger.BOOL,TypeInteger.I8,TypeInteger.U8, + TypeInteger.I16,TypeInteger.U16,TypeInteger.I32,TypeInteger.U32,TypeInteger.BOT}; // Reserve tags for u8 array @Override int TAGOFF() { return 1; } @Override public void packed( BAOS baos, HashMap<String,Integer> strs ) { - assert log_size()==0 && !_any; baos.write(TAGOFFS[TCONARY]+0); + if( storageType()!=TypeInteger.U8 || _any || _widen!=0 ) { + baos.packed4(TYPED); + int kind=0; + while( kind<STORAGE.length && STORAGE[kind]!=storageType() ) kind++; + assert kind<STORAGE.length; + baos.packed1(kind); + baos.packed1((_any ? 4 : 0)|_widen); + } baos.packed4(len()); - baos.write((byte[])_ary); + write(baos); } static TypeConAry packed( int tag, BAOS bais ) { - return TypeConAryB.make(bais.read(new byte[bais.packed4()])); + int len=bais.packed4(); + if( len!=TYPED ) return make(bais.read(new byte[len])); + TypeInteger storage=STORAGE[bais.packed1()]; + int flags=bais.packed1(); + long[] values=new long[bais.packed4()]; + int size=1<<storage.log_size(); + for( int i=0; i<values.length; i++ ) { + long value=0; + for( int b=0; b<size; b++ ) value|=(long)bais.read() << (8*b); + if( storage._min<0 && size<8 ) value=(value << (64-size*8)) >> (64-size*8); + values[i]=value; + } + TypeConAry ary=make(storage,values); + return flags==0 ? ary : ary._make((flags&4)!=0,(byte)(flags&3)).intern(); } } diff --git a/chapter31/src/main/java/com/seaofnodes/simple/type/TypeConAryB.java b/chapter31/src/main/java/com/seaofnodes/simple/type/TypeConAryB.java deleted file mode 100644 index 84be5fb2..00000000 --- a/chapter31/src/main/java/com/seaofnodes/simple/type/TypeConAryB.java +++ /dev/null @@ -1,20 +0,0 @@ -package com.seaofnodes.simple.type; - -import com.seaofnodes.simple.util.BAOS; -import java.util.Arrays; - -public class TypeConAryB extends TypeConAry<byte[]> { - private TypeConAryB(boolean any, byte widen, byte[] bs) { super(any,widen,bs); } - @Override TypeConAryB _make( boolean any, byte widen ) { return new TypeConAryB(any,widen,_ary); } - public static TypeConAryB make( byte[] bs ) { return new TypeConAryB(false,(byte)0,bs).intern(); } - public static TypeConAryB make( String s ) { return make(s.getBytes()); } - static final TypeConAryB ABC = make("abc"); - static final TypeConAryB ABCD = make("abcd"); - @Override public long at8(int idx) { return _ary[idx]&255; } - @Override public int len() { return _ary.length; } - @Override public int log_size() { return 0; } - @Override public String str() { return "[\""+new String(_ary)+"\"]"; } - @Override boolean eq(Type t) { return t instanceof TypeConAryB ary && _widen==ary._widen && Arrays.equals(_ary,ary._ary); } - @Override int hash() { return Arrays.hashCode(_ary); } - @Override public void write( BAOS baos ) { baos.write(_ary); } -} diff --git a/chapter31/src/main/java/com/seaofnodes/simple/type/TypeConAryI.java b/chapter31/src/main/java/com/seaofnodes/simple/type/TypeConAryI.java deleted file mode 100644 index b1b061de..00000000 --- a/chapter31/src/main/java/com/seaofnodes/simple/type/TypeConAryI.java +++ /dev/null @@ -1,16 +0,0 @@ -package com.seaofnodes.simple.type; - -import java.util.Arrays; - -public class TypeConAryI extends TypeConAry<int[]> { - private TypeConAryI(boolean any, byte widen, int[] bs) { super(any,widen,bs); } - public static TypeConAryI make( int[] bs ) { return new TypeConAryI(false,(byte)0,bs).intern(); } - @Override TypeConAryI _make( boolean any, byte widen ) { return new TypeConAryI(any,widen,_ary); } - static final TypeConAryI I123 = make(new int[]{1,2,3}); - @Override public long at8(int idx) { return _ary[idx]; } - @Override public int len() { return _ary.length; } - @Override public int log_size() { return 2; } - @Override public String str() { return "[i32]"; } - @Override boolean eq(Type t) { return t instanceof TypeConAryI ary && _widen==ary._widen && Arrays.equals(_ary,ary._ary); } - @Override int hash() { return Arrays.hashCode(_ary); } -} diff --git a/chapter31/src/main/java/com/seaofnodes/simple/type/TypeFloat.java b/chapter31/src/main/java/com/seaofnodes/simple/type/TypeFloat.java index d410e9cf..8d04fcbf 100644 --- a/chapter31/src/main/java/com/seaofnodes/simple/type/TypeFloat.java +++ b/chapter31/src/main/java/com/seaofnodes/simple/type/TypeFloat.java @@ -107,7 +107,7 @@ public class TypeFloat extends TypeScalar { else { assert isConstant(); baos.write(TAGOFFS[_type] + 2); - baos.packed8(Double.doubleToLongBits(_con)); + baos.packed8(Double.doubleToRawLongBits(_con)); } } @@ -121,12 +121,12 @@ public class TypeFloat extends TypeScalar { } @Override - int hash() { return (int)(Double.hashCode(_con) ^ _sz ^ (1<<17)); } + int hash() { return Long.hashCode(Double.doubleToRawLongBits(_con)) ^ _sz ^ (1<<17); } @Override public boolean eq( Type t ) { TypeFloat i = (TypeFloat)t; // Contract - // Allow NaN to check for equality - return _sz==i._sz && Double.doubleToLongBits(_con)==Double.doubleToLongBits(i._con); + // Representation conversions observe NaN signs/payloads and signed zero. + return _sz==i._sz && Double.doubleToRawLongBits(_con)==Double.doubleToRawLongBits(i._con); } } diff --git a/chapter31/src/main/java/com/seaofnodes/simple/type/TypeStruct.java b/chapter31/src/main/java/com/seaofnodes/simple/type/TypeStruct.java index 7c9758bd..11ba3cc4 100644 --- a/chapter31/src/main/java/com/seaofnodes/simple/type/TypeStruct.java +++ b/chapter31/src/main/java/com/seaofnodes/simple/type/TypeStruct.java @@ -146,8 +146,7 @@ public class TypeStruct extends Type { Type len = TypeInteger.constant(con.len()); return make(name,false, Field.make("#" ,len , lenAlias,true), - Field.make("[]" ,con.elem(),bodyAlias,true), - Field.make("[con]",con ,bodyAlias,true)); + Field.make("[]" ,con ,bodyAlias,true)); } public TypeStruct makeInit() { @@ -190,6 +189,9 @@ public class TypeStruct extends Type { } @Override TypeStruct _close( String name, HashMap<String, Type> TYPES ) { assert (name==null) != (TYPES==null); // One or the other + // Primitive constant contents are already closed. Looking up their + // shared array name would discard the length and payload on import. + if( isConAry() ) return this; String namePlusFinal = isAry() ? (_name+(_fields[1]._final ? "~" : "!")).intern() : _name; TypeStruct ts = (TypeStruct)VISIT.get(namePlusFinal); if( ts!=null ) return ts; @@ -251,7 +253,7 @@ public class TypeStruct extends Type { public static final TypeStruct TEST= make("test",false,Field.TEST); private static final TypeStruct ARY = makeAry("[]i64",TypeInteger.U32,-1,TypeInteger.BOT,-2,false); private static final TypeStruct STR = makeAry("[]u8" ,TypeInteger.U32,-1,TypeInteger.U8 ,-4,false); - private static final TypeStruct ABC = makeAry("[]u8",-1,-4,TypeConAryB.ABC); + private static final TypeStruct ABC = makeAry("[]u8",-1,-4,TypeConAry.ABC); // Representative unresolved forms for the exhaustive lattice tests: // bare forward ref, forward ref constrained by a field use, and definition. private static final TypeStruct FREF0 = forward("%FREF"); @@ -462,6 +464,7 @@ public class TypeStruct extends Type { @Override public int log_size() { throw Utils.TODO("Should not reach here: structs have no scalar log size"); } @Override public int size() { return offset(_fields.length); } @Override public int alignment() { + if( isAry() ) return Math.max(2,aryScale()); // The length is always u32. int align = 0; for( Field f : _fields ) if( !f._extern ) align = Math.max(align, f._t.alignment()); @@ -607,7 +610,7 @@ public class TypeStruct extends Type { int align = _fields[1]._t.alignment(); _offs[1] = (4 + ((1<<align)-1)) & -(1<<align); if( _fields[1]._t instanceof TypeConAry ary ) // Array length is well-defined for constants, not defined for runtime arrays - _offs[2] = _offs[1]+ary.len(); + _offs[2] = _offs[1]+(ary.len()<<ary.log_size()); } else { int[] cnts = new int[5]; // Count of fields at log field size diff --git a/chapter31/src/main/smp/sys.smp b/chapter31/src/main/smp/sys.smp index f7889c05..3fb8d94b 100644 --- a/chapter31/src/main/smp/sys.smp +++ b/chapter31/src/main/smp/sys.smp @@ -8,6 +8,7 @@ val aryi64 = aryi64; // Variable sized array of i64 val aryu8 = aryu8; // Variable sized array of u8 val char = char; // Character utilities val integer = integer; // Integer bounds +val math = math; // Floating-point representation primitives val io = io; // IO library val gfx = gfx; // Optional pixel window (MiniFB) val draw = draw; // Software raster drawing in Simple diff --git a/chapter31/src/main/smp/sys/adt/bitset.smp b/chapter31/src/main/smp/sys/adt/bitset.smp index d02cd2fe..a51a63e1 100644 --- a/chapter31/src/main/smp/sys/adt/bitset.smp +++ b/chapter31/src/main/smp/sys/adt/bitset.smp @@ -20,7 +20,7 @@ struct bitset { if( x < len ) return self; while( x >= len ) len *= 2; var bits = new i64[len]; - for( int i=0; i<_bits#; i++ ) + for( int i = 0; i < _bits#; i++ ) bits[i] = _bits[i]; _bits = bits; return self; @@ -51,7 +51,7 @@ struct bitset { }; val clear = { -> - for( int i=0; i<_bits#; i++ ) _bits[i] = 0; + for( int i = 0; i < _bits#; i++ ) _bits[i] = 0; return self; }; }; diff --git a/chapter31/src/main/smp/sys/ary.smp b/chapter31/src/main/smp/sys/ary.smp index 11ddb7a0..b94ffa8f 100644 --- a/chapter31/src/main/smp/sys/ary.smp +++ b/chapter31/src/main/smp/sys/ary.smp @@ -19,7 +19,7 @@ val copy = { u8[] dst, u32 doff, u8[~] src, u32 soff, u32 len -> if( doff > dst# || soff > src# ) return dst; if( len > dst# - doff ) len = dst# - doff; if( len > src# - soff ) len = src# - soff; - for( u32 i=0; i<len; i++ ) + for( u32 i = 0; i < len; i++ ) dst[i+doff] = src[i+soff]; return dst; }; @@ -33,7 +33,7 @@ val cmp = { u8[~] src1, u32 off1, u8[~] src2, u32 off2, u32 len -> u32 len1 = len > left1 ? left1 : len; u32 len2 = len > left2 ? left2 : len; u32 max = len1 > len2 ? len2 : len1; - for( u32 i=0; i<max; i++ ) + for( u32 i = 0; i < max; i++ ) if( src1[off1+i] != src2[off2+i] ) return src1[off1+i] - src2[off2+i]; // Bytes determine compare return len1 - len2; // Length determines compare diff --git a/chapter31/src/main/smp/sys/aryi64.smp b/chapter31/src/main/smp/sys/aryi64.smp index b9f1fbed..aba1b459 100644 --- a/chapter31/src/main/smp/sys/aryi64.smp +++ b/chapter31/src/main/smp/sys/aryi64.smp @@ -14,7 +14,7 @@ struct aryi64 { u32 newlen = ary.capacity(buf#,len+len2); if( !newlen ) libc._exit(1); // Length exceeds the array representation. i64[] !buf2 = new i64[newlen]; - for( u32 i=0; i<len; i++ ) + for( u32 i = 0; i < len; i++ ) buf2[i] = buf[i]; buf = buf2; self; @@ -32,7 +32,7 @@ struct aryi64 { val str = { -> // TODO: clunky default constructor syntax var str = new aryu8().add('['); - for( u32 i=0; i<len; i++ ) + for( u32 i = 0; i < len; i++ ) str.num(buf[i]).add(',').add(' '); if( len ) str.undo(2); return str.add(']'); @@ -79,7 +79,7 @@ val copy = { i64[] dst, u32 doff, i64[~] src, u32 soff, u32 len -> if( doff > dst# || soff > src# ) return dst; if( len > dst# - doff ) len = dst# - doff; if( len > src# - soff ) len = src# - soff; - for( u32 i=0; i<len; i++ ) + for( u32 i = 0; i < len; i++ ) dst[i+doff] = src[i+soff]; return dst; }; diff --git a/chapter31/src/main/smp/sys/aryu8.smp b/chapter31/src/main/smp/sys/aryu8.smp index 76d47ec5..3f462898 100644 --- a/chapter31/src/main/smp/sys/aryu8.smp +++ b/chapter31/src/main/smp/sys/aryu8.smp @@ -27,7 +27,7 @@ struct aryu8 { // Add all of a plain array to the aryu8 val addAry = { u8[~] xs -> - u32 n=xs#; + u32 n = xs#; _grow(n); ary.copy(buf,len,xs,0,n); len += n; @@ -60,7 +60,7 @@ val atoi = { u8[~] str -> while( x < str# && str[x] <= ' ' ) x++; if( x == str# ) return 0; bool neg = false; - if( str[x]=='-' ) { neg=true; x++; } + if( str[x] == '-' ) { neg = true; x++; } i64 n = 0; while( x < str# && '0' <= str[x] <= '9' ) n = n*10 + str[x++]-'0'; @@ -71,5 +71,5 @@ val atoi = { u8[~] str -> { u8[~] -> u8[] } str0 = { u8[~] str -> if( str# == sys.integer.MAX_U32 ) libc._exit(1); // Copy, terminate and return - return new u8[str#+1]{i64 i -> i<str# ? str[i] : '\0'; }; -};
\ No newline at end of file + return new u8[str#+1]{i64 i -> i < str# ? str[i] : '\0'; }; +}; diff --git a/chapter31/src/main/smp/sys/draw.smp b/chapter31/src/main/smp/sys/draw.smp index 61b250d3..2a8b6117 100644 --- a/chapter31/src/main/smp/sys/draw.smp +++ b/chapter31/src/main/smp/sys/draw.smp @@ -7,9 +7,9 @@ u32 BLUE = 0x0000ff; // Components are clamped to bytes rather than wrapping. val rgb = { int r, int g, int b -> - r = r<0 ? 0 : r>255 ? 255 : r; - g = g<0 ? 0 : g>255 ? 255 : g; - b = b<0 ? 0 : b>255 ? 255 : b; + r = r < 0 ? 0 : r > 255 ? 255 : r; + g = g < 0 ? 0 : g > 255 ? 255 : g; + b = b < 0 ? 0 : b > 255 ? 255 : b; u32 color = (r<<16) | (g<<8) | b; return color; }; diff --git a/chapter31/src/main/smp/sys/draw/Button.smp b/chapter31/src/main/smp/sys/draw/Button.smp index edf01119..c90ed2d3 100644 --- a/chapter31/src/main/smp/sys/draw/Button.smp +++ b/chapter31/src/main/smp/sys/draw/Button.smp @@ -3,36 +3,36 @@ struct Button { int x, y, width, height; u8[~] !label; - bool !enabled=true, !hovered=false, !pressed=false; - bool !_held=false, !_armed=false; + bool !enabled = true, !hovered = false, !pressed = false; + bool !_held = false, !_armed = false; new Button = { int px, int py, int w, int h, u8[~] text -> - x=px; y=py; width=w; height=h; label=text; + x = px; y = py; width = w; height = h; label = text; }; val contains = { i64 px, i64 py -> - if( width<=0 || height<=0 ) return false; - i64 right=x, bottom=y; right+=width; bottom+=height; - if( px<x || py<y || px>=right || py>=bottom ) return false; + if( width <= 0 || height <= 0 ) return false; + i64 right = x, bottom = y; right += width; bottom += height; + if( px < x || py < y || px >= right || py >= bottom ) return false; return true; }; val update = { i64 px, i64 py, bool down -> - hovered=false; - if( enabled ) hovered=contains(px,py); - if( !enabled ) _armed=false; - if( down && !_held ) _armed=hovered; - var clicked=false; - if( !down ) if( _held ) if( _armed ) if( hovered ) clicked=true; - if( !down ) _armed=false; - _held=down; - pressed=false; - if( down ) if( _armed ) if( hovered ) pressed=true; + hovered = false; + if( enabled ) hovered = contains(px,py); + if( !enabled ) _armed = false; + if( down && !_held ) _armed = hovered; + var clicked = false; + if( !down ) if( _held ) if( _armed ) if( hovered ) clicked = true; + if( !down ) _armed = false; + _held = down; + pressed = false; + if( down ) if( _armed ) if( hovered ) pressed = true; return clicked; }; val draw = { !sys.draw.Canvas screen, int scale, u32 foreground, u32 background, u32 active -> screen.fillRect(x,y,width,height,enabled && (hovered || pressed) ? active : background); screen.rect(x,y,width,height,2,enabled ? foreground : active); - if( scale>0 ) { - i64 textWidth=label#; textWidth=(textWidth*4-1)*scale; - if( textWidth<=width-8 && 5*scale<=height-8 ) + if( scale > 0 ) { + i64 textWidth = label#; textWidth = (textWidth*4-1)*scale; + if( textWidth <= width-8 && 5*scale <= height-8 ) screen.text(x+(width-textWidth)/2,y+(height-5*scale)/2+(pressed ? 1 : 0), label,scale,enabled ? foreground : active); } diff --git a/chapter31/src/main/smp/sys/draw/Canvas.smp b/chapter31/src/main/smp/sys/draw/Canvas.smp index 5bd7d68e..2fbcf6ea 100644 --- a/chapter31/src/main/smp/sys/draw/Canvas.smp +++ b/chapter31/src/main/smp/sys/draw/Canvas.smp @@ -6,39 +6,39 @@ struct Canvas { new Canvas = { int w, int h -> i64 count = w; count *= h; - if( w<=0 || h<=0 || count>sys.integer.MAX_I32 ) libc._exit(1); + if( w <= 0 || h <= 0 || count > sys.integer.MAX_I32 ) libc._exit(1); width = w; height = h; pixels = new u32[count]; }; val clear = { u32 color -> - for( int i=0; i<pixels#; i++ ) pixels[i] = color; + for( int i = 0; i < pixels#; i++ ) pixels[i] = color; return self; }; val pixel = { i64 x, i64 y, u32 color -> - if( 0<=x<width && 0<=y<height ) pixels[y*width+x] = color; + if( 0 <= x < width && 0 <= y < height ) pixels[y*width+x] = color; return self; }; // Integer coordinates, top-left origin. Rectangle extents are half-open. val fillRect = { i64 x, i64 y, i64 w, i64 h, u32 color -> - if( w<=0 || h<=0 ) return self; + if( w <= 0 || h <= 0 ) return self; i64 right = x; right += w; i64 bottom = y; bottom += h; - if( right<=0 || bottom<=0 || x>=width || y>=height ) return self; - int x0 = x<0 ? 0 : x, y0 = y<0 ? 0 : y; - int x1 = right>width ? width : right, y1 = bottom>height ? height : bottom; - for( int py=y0; py<y1; py++ ) - for( int px=x0; px<x1; px++ ) pixels[py*width+px] = color; + if( right <= 0 || bottom <= 0 || x >= width || y >= height ) return self; + int x0 = x < 0 ? 0 : x, y0 = y < 0 ? 0 : y; + int x1 = right > width ? width : right, y1 = bottom > height ? height : bottom; + for( int py = y0; py < y1; py++ ) + for( int px = x0; px < x1; px++ ) pixels[py*width+px] = color; return self; }; // Outline stays inside the rectangle. Wide borders become a filled rect. val rect = { i64 x, i64 y, i64 w, i64 h, i64 thickness, u32 color -> - if( w<=0 || h<=0 || thickness<=0 ) return self; - if( thickness>=w || thickness>=h || thickness>=w-thickness || thickness>=h-thickness ) + if( w <= 0 || h <= 0 || thickness <= 0 ) return self; + if( thickness >= w || thickness >= h || thickness >= w-thickness || thickness >= h-thickness ) return fillRect(x,y,w,h,color); fillRect(x,y,w,thickness,color); fillRect(x,y+h-thickness,w,thickness,color); @@ -54,23 +54,23 @@ struct Canvas { return _circle(cx,cy,radius,thickness,false,color); }; val _circle = { i64 cx, i64 cy, int radius, int thickness, bool filled, u32 color -> - if( radius<0 || (!filled && thickness<=0) ) return self; + if( radius < 0 || (!filled && thickness <= 0) ) return self; i64 left = cx; left -= radius; i64 top = cy; top -= radius; i64 right = cx; right += radius; i64 bottom = cy; bottom += radius; - if( right<0 || bottom<0 || left>=width || top>=height ) return self; - int x0 = left<0 ? 0 : left, y0 = top<0 ? 0 : top; - int x1 = right>=width ? width-1 : right, y1 = bottom>=height ? height-1 : bottom; + if( right < 0 || bottom < 0 || left >= width || top >= height ) return self; + int x0 = left < 0 ? 0 : left, y0 = top < 0 ? 0 : top; + int x1 = right >= width ? width-1 : right, y1 = bottom >= height ? height-1 : bottom; i64 outer2 = radius; outer2 *= radius; i64 inner = filled ? -1 : radius-thickness; - for( int py=y0; py<=y1; py++ ) - for( int px=x0; px<=x1; px++ ) { + for( int py = y0; py <= y1; py++ ) + for( int px = x0; px <= x1; px++ ) { i64 dx = px; dx -= cx; i64 dy = py; dy -= cy; i64 d2 = dx*dx+dy*dy; - if( d2<=outer2 && (inner<=0 || d2>inner*inner) ) pixels[py*width+px] = color; + if( d2 <= outer2 && (inner <= 0 || d2 > inner*inner) ) pixels[py*width+px] = color; } return self; }; @@ -78,17 +78,17 @@ struct Canvas { // Round caps; a zero-length segment is a dot. Only the clipped bounding // box is scanned. Floating distances avoid overflowing coordinate squares. val line = { i64 x0, i64 y0, i64 x1, i64 y1, i64 thickness, u32 color -> - if( thickness<=0 ) return self; + if( thickness <= 0 ) return self; i64 pad = thickness/2+1; - i64 left = x0<x1 ? x0 : x1; left -= pad; - i64 top = y0<y1 ? y0 : y1; top -= pad; - i64 right = x0>x1 ? x0 : x1; right += pad; - i64 bottom = y0>y1 ? y0 : y1; bottom += pad; - if( right<0 || bottom<0 || left>=width || top>=height ) return self; - int bx0 = left<0 ? 0 : left, by0 = top<0 ? 0 : top; - int bx1 = right>=width ? width-1 : right, by1 = bottom>=height ? height-1 : bottom; - for( int py=by0; py<=by1; py++ ) - for( int px=bx0; px<=bx1; px++ ) + i64 left = x0 < x1 ? x0 : x1; left -= pad; + i64 top = y0 < y1 ? y0 : y1; top -= pad; + i64 right = x0 > x1 ? x0 : x1; right += pad; + i64 bottom = y0 > y1 ? y0 : y1; bottom += pad; + if( right < 0 || bottom < 0 || left >= width || top >= height ) return self; + int bx0 = left < 0 ? 0 : left, by0 = top < 0 ? 0 : top; + int bx1 = right >= width ? width-1 : right, by1 = bottom >= height ? height-1 : bottom; + for( int py = by0; py <= by1; py++ ) + for( int px = bx0; px <= bx1; px++ ) if( _onLine(px,py,x0,y0,x1,y1,thickness) ) pixels[py*width+px] = color; return self; }; @@ -96,14 +96,14 @@ struct Canvas { // Small 3x5 bitmap font for game labels. Lowercase maps to uppercase. // Newline returns to x; unsupported characters draw a question mark. val text = { i64 x, i64 y, u8[~] str, int scale, u32 color -> - if( scale<=0 ) return self; + if( scale <= 0 ) return self; i64 px = x, py = y; - for( int i=0; i<str#; i++ ) { + for( int i = 0; i < str#; i++ ) { u8 c = str[i]; - if( c=='\n' ) { px=x; py+=6*scale; continue; } + if( c == '\n' ) { px = x; py += 6*scale; continue; } int bits = _glyph(c); - for( int row=0; row<5; row++ ) - for( int col=0; col<3; col++ ) + for( int row = 0; row < 5; row++ ) + for( int col = 0; col < 3; col++ ) if( (bits >> (14-row*3-col)) & 1 ) fillRect(px+col*scale,py+row*scale,scale,scale,color); px += 4*scale; @@ -130,7 +130,7 @@ val _glyphs = new u16[~96]{ }; val _glyph = { u8 c -> - return 32<=c<128 ? _glyphs[c-32] : 061202; + return 32 <= c < 128 ? _glyphs[c-32] : 061202; }; // Pixel coverage for a round-ended segment, separate from traversal. @@ -140,10 +140,10 @@ val _onLine = { i64 px, i64 py, i64 x0, i64 y0, i64 x1, i64 y1, i64 thickness -> f64 vx = px; vx -= x0; f64 vy = py; vy -= y0; f64 length2 = dx*dx+dy*dy; - bool point = x0==x1 && y0==y1; + bool point = x0 == x1 && y0 == y1; f64 t = point ? 0.0 : (vx*dx+vy*dy)/length2; - t = t<0 ? 0.0 : t>1 ? 1.0 : t; + t = t < 0 ? 0.0 : t > 1 ? 1.0 : t; f64 ex = vx-t*dx, ey = vy-t*dy; f64 half = thickness/2.0; - return ex*ex+ey*ey<=half*half; + return ex*ex+ey*ey <= half*half; }; diff --git a/chapter31/src/main/smp/sys/libc.smp b/chapter31/src/main/smp/sys/libc.smp index 7122bbd8..8e417461 100644 --- a/chapter31/src/main/smp/sys/libc.smp +++ b/chapter31/src/main/smp/sys/libc.smp @@ -53,9 +53,9 @@ i32 EOVERFLOW = "C"; // addr len prot flags fd off -> void* { i64 i64 i32 i32 i32 i32 -> i64 } mmap = "C"; // mmap flags -i32 PROT_EXEC = 4; -i32 PROT_READ = 1; -i32 PROT_WRITE= 2; -i32 PROT_NONE = 0; +i32 PROT_EXEC = 4; +i32 PROT_READ = 1; +i32 PROT_WRITE = 2; +i32 PROT_NONE = 0; i32 MAP_PRIVATE = 2; i32 MAP_ANON = 32; diff --git a/chapter31/src/main/smp/sys/math.smp b/chapter31/src/main/smp/sys/math.smp new file mode 100644 index 00000000..a5e1887c --- /dev/null +++ b/chapter31/src/main/smp/sys/math.smp @@ -0,0 +1,15 @@ +// Mathematical constants, rounded to the nearest f64 value. +val PI = 3.141592653589793; +val E = 2.718281828459045; + +// Fixed-semantics C bindings recognized by the compiler's intrinsic inliner. +// These preserve all 64 bits, including signed zero and NaN payloads. +// They are NOT numeric conversions (ordinary typed assignments still are). +{ f64 -> i64 } simple_f64_bits = "C"; +{ i64 -> f64 } simple_f64_from_bits = "C"; +val f64Bits = simple_f64_bits; +val f64FromBits = simple_f64_from_bits; + + +val max = { f64 x, f64 y -> return x > y ? x : y; }; +val min = { f64 x, f64 y -> return x < y ? x : y; }; diff --git a/chapter31/src/main/smp/sys/rt/simple_args.smp b/chapter31/src/main/smp/sys/rt/simple_args.smp index f2890c1c..8bfcc1a7 100644 --- a/chapter31/src/main/smp/sys/rt/simple_args.smp +++ b/chapter31/src/main/smp/sys/rt/simple_args.smp @@ -11,7 +11,7 @@ val simple_args = { i64 argc, i64 argv -> // Zero-filled reference arrays require nullable elements. Every slot is // filled before returning; the native entry bridge publishes u8[~][]. val args = new u8[~]?[argc]; - for( i64 i=0; i<argc; i++ ) { + for( i64 i = 0; i < argc; i++ ) { i64 src = simple_argv(argv,i); i64 len = strlen(src); if( len < 0 || len > _MAX_U32 ) return null; diff --git a/chapter31/src/main/smp/sys/text.smp b/chapter31/src/main/smp/sys/text.smp index 2c4b44ff..43698f22 100644 --- a/chapter31/src/main/smp/sys/text.smp +++ b/chapter31/src/main/smp/sys/text.smp @@ -9,71 +9,71 @@ val end = { aryu8 b -> }; val _pad = { !aryu8 b, i64 n, u8 c -> - for( i64 i=0; i<n; i++ ) b.add(c); + for( i64 i = 0; i < n; i++ ) b.add(c); b; }; val string = { !aryu8 b, u8[~] s, i64 spec, i64 width, i64 precision -> - i64 len=s#; - if( precision>=0 && precision<len ) len=precision; - i64 pad=width-len; + i64 len = s#; + if( precision >= 0 && precision < len ) len = precision; + i64 pad = width-len; if( !(spec&256) ) _pad(b,pad,' '); - for( i64 i=0; i<len; i++ ) b.add(s[i]); + for( i64 i = 0; i < len; i++ ) b.add(s[i]); if( spec&256 ) _pad(b,pad,' '); b; }; val integer = { !aryu8 b, i64 value, i64 spec, i64 width, i64 precision -> - i64 kind=spec&255; - if( kind=='b' ) return string(b,value ? "true" : "false",spec,width,-1); - if( kind=='c' ) { + i64 kind = spec&255; + if( kind == 'b' ) return string(b,value ? "true" : "false",spec,width,-1); + if( kind == 'c' ) { if( !(spec&256) ) _pad(b,width-1,' '); - u8 c=value; + u8 c = value; b.add(c); if( spec&256 ) _pad(b,width-1,' '); return b; } - bool signed=kind==0 || kind=='d' || kind=='i'; - i64 base=kind=='o' ? 8 : (kind=='x' || kind=='X' ? 16 : 10); - u8[~] alphabet=kind=='X' ? "0123456789ABCDEF" : "0123456789abcdef"; - val digits=new u8[22]; // Maximum: 22 octal digits for a 64-bit integer. - i64 count=0, n=value; + bool signed = kind == 0 || kind == 'd' || kind == 'i'; + i64 base = kind == 'o' ? 8 : (kind == 'x' || kind == 'X' ? 16 : 10); + u8[~] alphabet = kind == 'X' ? "0123456789ABCDEF" : "0123456789abcdef"; + val digits = new u8[22]; // Maximum: 22 octal digits for a 64-bit integer. + i64 count = 0, n = value; // Signed decimal stays nonpositive, including the minimum i64. - if( signed && n>0 ) n=-n; - if( n==0 && precision!=0 ) digits[count++]='0'; - while( n!=0 ) { - i64 q=0, r=0; - if( signed ) { q=n/base; r=q*base-n; } + if( signed && n > 0 ) n = -n; + if( n == 0 && precision != 0 ) digits[count++] = '0'; + while( n != 0 ) { + i64 q = 0, r = 0; + if( signed ) { q = n/base; r = q*base-n; } else { // Unsigned division without a u64 type. Halving first makes // the dividend nonnegative; the remainder needs at most one fix. - q=((n>>>1)/base)*2; - r=n-q*base; - if( r>=base ) { q++; r-=base; } + q = ((n>>>1)/base)*2; + r = n-q*base; + if( r >= base ) { q++; r -= base; } } - digits[count++]=alphabet[r]; - n=q; + digits[count++] = alphabet[r]; + n = q; } - u8[~] !prefix=""; + u8[~] !prefix = ""; if( signed ) { - if( value<0 ) prefix="-"; - else if( spec&512 ) prefix="+"; - else if( spec&1024 ) prefix=" "; - } else if( (spec&2048) && value!=0 ) { - if( kind=='x' ) prefix="0x"; - if( kind=='X' ) prefix="0X"; + if( value < 0 ) prefix = "-"; + else if( spec&512 ) prefix = "+"; + else if( spec&1024 ) prefix = " "; + } else if( (spec&2048) && value != 0 ) { + if( kind == 'x' ) prefix = "0x"; + if( kind == 'X' ) prefix = "0X"; } - i64 zeros=precision>count ? precision-count : 0; + i64 zeros = precision > count ? precision-count : 0; // Alternate octal always begins with a zero, including precision-zero 0. - if( kind=='o' && (spec&2048) && zeros==0 && (count==0 || digits[count-1]!='0') ) zeros=1; - i64 pad=width-prefix#-zeros-count; - bool left=(spec&256)!=0; - bool zero=(spec&4096)!=0 && precision<0 && !left; + if( kind == 'o' && (spec&2048) && zeros == 0 && (count == 0 || digits[count-1] != '0') ) zeros = 1; + i64 pad = width-prefix#-zeros-count; + bool left = (spec&256) != 0; + bool zero = (spec&4096) != 0 && precision < 0 && !left; if( !left && !zero ) _pad(b,pad,' '); b.addAry(prefix); if( zero ) _pad(b,pad,'0'); _pad(b,zeros,'0'); - while( count>0 ) b.add(digits[--count]); + while( count > 0 ) b.add(digits[--count]); if( left ) _pad(b,pad,' '); b; }; diff --git a/chapter31/src/main/smp/sys/time.smp b/chapter31/src/main/smp/sys/time.smp index 1706990e..a3e9b3a2 100644 --- a/chapter31/src/main/smp/sys/time.smp +++ b/chapter31/src/main/smp/sys/time.smp @@ -24,7 +24,7 @@ i64 MIN = -_DAYS_BEFORE_EPOCH*DAY; // 0001-01-01T00:00:00.000Z i64 MAX = (_DAYS_BEFORE_YEAR_10000-_DAYS_BEFORE_EPOCH)*DAY-1; // 9999-12-31T23:59:59.999Z // Access to the underlying LIBC functions -int ISO=0, CLOCK12=1, CLOCK24=2, ELAPSED=3, DATE=4, CLOCK24_SECONDS=5; +int ISO = 0, CLOCK12 = 1, CLOCK24 = 2, ELAPSED = 3, DATE = 4, CLOCK24_SECONDS = 5; { i64 } simple_time_now = "C"; { i64 } simple_time_mono = "C"; { i64 } simple_time_nano = "C"; @@ -40,7 +40,7 @@ val sleepUntil = { i64 deadline_ms -> simple_time_sleep(deadline_ms,1); }; // Signed duration conversions. Overflow returns -1; reverse conversions truncate // toward zero. An exact duration day is 24 hours, independent of DST. val _scale = { i64 n, i64 unit -> - if( n>sys.integer.MAX_I64/unit || n<sys.integer.MIN_I64/unit ) return -1; + if( n > sys.integer.MAX_I64/unit || n < sys.integer.MIN_I64/unit ) return -1; return n*unit; }; val seconds = { i64 n -> _scale(n,SECOND); }; @@ -56,31 +56,31 @@ val toNanos = { i64 ms -> _scale(ms,NANOS_PER_MS); }; // Clamp to zero once due, and saturate for widely separated i64 readings. val remaining = { i64 deadline_ms, i64 current_ms -> - if( deadline_ms<=current_ms ) return 0; - if( current_ms<0 && deadline_ms>sys.integer.MAX_I64+current_ms ) return sys.integer.MAX_I64; + if( deadline_ms <= current_ms ) return 0; + if( current_ms < 0 && deadline_ms > sys.integer.MAX_I64+current_ms ) return sys.integer.MAX_I64; return deadline_ms-current_ms; }; val _mod = { i64 n, i64 unit -> n-n/unit*unit; }; -val leap = { int year -> _mod(year,4)==0 && (_mod(year,100)!=0 || _mod(year,400)==0); }; +val leap = { int year -> _mod(year,4) == 0 && (_mod(year,100) != 0 || _mod(year,400) == 0); }; val monthDays = { int year, int month -> - if( month<1 || month>12 ) return 0; - return month==2 ? (leap(year) ? 29 : 28) : - month==4 || month==6 || month==9 || month==11 ? 30 : 31; + if( month < 1 || month > 12 ) return 0; + return month == 2 ? (leap(year) ? 29 : 28) : + month == 4 || month == 6 || month == 9 || month == 11 ? 30 : 31; }; // Gregorian civil dates, expressed using 400-year eras; no per-year loops. val _days = { i64 year, i64 month, i64 day -> - year -= month<=2 ? 1 : 0; - i64 era=year/400, y=year-era*400; - i64 mp=month+(month>2 ? -3 : 9); + year -= month <= 2 ? 1 : 0; + i64 era = year/400, y = year-era*400; + i64 mp = month+(month > 2 ? -3 : 9); return era*_DAYS_PER_ERA+y*365+y/4-y/100+(153*mp+2)/5+day-1-_MARCH_EPOCH_DAYS; }; val valid = { int year, int month, int day, int hour, int minute, int second, int millisecond -> - return year>=1 && year<=9999 && month>=1 && month<=12 && day>=1 && day<=monthDays(year,month) && - hour>=0 && hour<=23 && minute>=0 && minute<=59 && second>=0 && second<=59 && - millisecond>=0 && millisecond<=999; + return year >= 1 && year <= 9999 && month >= 1 && month <= 12 && day >= 1 && day <= monthDays(year,month) && + hour >= 0 && hour <= 23 && minute >= 0 && minute <= 59 && second >= 0 && second <= 59 && + millisecond >= 0 && millisecond <= 999; }; val makeUTC = { int year, int month, int day, int hour, int minute, int second, int millisecond -> @@ -89,41 +89,41 @@ val makeUTC = { int year, int month, int day, int hour, int minute, int second, }; val utc = { i64 instant -> - val d=DateTime.empty(); - if( instant<MIN || instant>MAX ) return d; - i64 day=instant/DAY, rest=_mod(instant,DAY); - if( rest<0 ) { rest+=DAY; day--; } - i64 z=day+_MARCH_EPOCH_DAYS, era=z/_DAYS_PER_ERA, doe=z-era*_DAYS_PER_ERA; - i64 y=(doe-doe/(_DAYS_PER_4_YEARS-1)+doe/_DAYS_PER_CENTURY-doe/(_DAYS_PER_ERA-1))/365; - i64 doy=doe-(365*y+y/4-y/100), mp=(5*doy+2)/153; - d.day=doy-(153*mp+2)/5+1; - d.month=mp+(mp<10 ? 3 : -9); - d.year=y+era*400+(d.month<=2 ? 1 : 0); - d.hour=rest/HOUR; d.minute=_mod(rest/MINUTE,60); - d.second=_mod(rest/SECOND,60); d.millisecond=_mod(rest,SECOND); - d.weekday=_mod(day+4,7); - if( d.weekday<0 ) d.weekday+=7; + val d = DateTime.empty(); + if( instant < MIN || instant > MAX ) return d; + i64 day = instant/DAY, rest = _mod(instant,DAY); + if( rest < 0 ) { rest += DAY; day--; } + i64 z = day+_MARCH_EPOCH_DAYS, era = z/_DAYS_PER_ERA, doe = z-era*_DAYS_PER_ERA; + i64 y = (doe-doe/(_DAYS_PER_4_YEARS-1)+doe/_DAYS_PER_CENTURY-doe/(_DAYS_PER_ERA-1))/365; + i64 doy = doe-(365*y+y/4-y/100), mp = (5*doy+2)/153; + d.day = doy-(153*mp+2)/5+1; + d.month = mp+(mp < 10 ? 3 : -9); + d.year = y+era*400+(d.month <= 2 ? 1 : 0); + d.hour = rest/HOUR; d.minute = _mod(rest/MINUTE,60); + d.second = _mod(rest/SECOND,60); d.millisecond = _mod(rest,SECOND); + d.weekday = _mod(day+4,7); + if( d.weekday < 0 ) d.weekday += 7; return d; }; val local = { i64 instant -> - val d=DateTime.empty(); - val f=new i64[10]; - i64 ptr=f; - if( simple_time_local(instant,ptr)!=0 ) return d; - d.year=f[0]; d.month=f[1]; d.day=f[2]; - d.hour=f[3]; d.minute=f[4]; d.second=f[5]; d.millisecond=f[6]; - d.weekday=f[7]; d.offsetSeconds=f[8]; d.daylight=f[9]!=0; + val d = DateTime.empty(); + val f = new i64[10]; + i64 ptr = f; + if( simple_time_local(instant,ptr) != 0 ) return d; + d.year = f[0]; d.month = f[1]; d.day = f[2]; + d.hour = f[3]; d.minute = f[4]; d.second = f[5]; d.millisecond = f[6]; + d.weekday = f[7]; d.offsetSeconds = f[8]; d.daylight = f[9] != 0; return d; }; val zoneName = { i64 instant -> - val bytes=new u8[128]; - i64 ptr=bytes; - int n=simple_time_zone(instant,ptr,bytes#); - if( n<0 ) return ""; - val b=new aryu8(); - for( int i=0; i<n; i++ ) b.add(bytes[i]); + val bytes = new u8[128]; + i64 ptr = bytes; + int n = simple_time_zone(instant,ptr,bytes#); + if( n < 0 ) return ""; + val b = new aryu8(); + for( int i = 0; i < n; i++ ) b.add(bytes[i]); return text.end(b); }; @@ -133,28 +133,28 @@ val _digits = { !aryu8 b, i64 n, int width -> val _format = { i64 instant, int style, bool localZone -> val d = localZone ? local(instant) : utc(instant); - if( d.year==0 || style<0 || style>5 || style==3 ) return "<invalid time>"; + if( d.year == 0 || style < 0 || style > 5 || style == 3 ) return "<invalid time>"; val b = new aryu8(); - if( style==4 ) { + if( style == 4 ) { _digits(b,d.day,2).add('/'); _digits(b,d.month,2).add('/'); _digits(b,_mod(d.year,100),2); } else { - if( style==0 ) { + if( style == 0 ) { _digits(b,d.year,4).add('-'); _digits(b,d.month,2).add('-'); _digits(b,d.day,2).add('T'); } - int hour=d.hour; - if( style==1 ) { hour=_mod(hour,12); if( hour==0 ) hour=12; } - _digits(b,hour,style==1 ? 1 : 2).add(':'); _digits(b,d.minute,2); - if( style==0 || style==5 ) { b.add(':'); _digits(b,d.second,2); } - if( style==1 ) b.addAry(d.hour<12 ? "am" : "pm"); - if( style==0 ) { + int hour = d.hour; + if( style == 1 ) { hour = _mod(hour,12); if( hour == 0 ) hour = 12; } + _digits(b,hour,style == 1 ? 1 : 2).add(':'); _digits(b,d.minute,2); + if( style == 0 || style == 5 ) { b.add(':'); _digits(b,d.second,2); } + if( style == 1 ) b.addAry(d.hour < 12 ? "am" : "pm"); + if( style == 0 ) { b.add('.'); _digits(b,d.millisecond,3); - if( d.offsetSeconds==0 ) b.add('Z'); + if( d.offsetSeconds == 0 ) b.add('Z'); else { - i64 offset=d.offsetSeconds; - b.add(offset<0 ? '-' : '+'); - if( offset<0 ) offset=-offset; + i64 offset = d.offsetSeconds; + b.add(offset < 0 ? '-' : '+'); + if( offset < 0 ) offset = -offset; _digits(b,offset/3600,2).add(':'); _digits(b,_mod(offset/60,60),2); - if( _mod(offset,60)!=0 ) { b.add(':'); _digits(b,_mod(offset,60),2); } + if( _mod(offset,60) != 0 ) { b.add(':'); _digits(b,_mod(offset,60),2); } } } } @@ -162,58 +162,58 @@ val _format = { i64 instant, int style, bool localZone -> }; val elapsed = { i64 ms -> - val b=new aryu8(); + val b = new aryu8(); // Nonpositive arithmetic handles the minimum i64 without negating it. - if( ms<0 ) b.add('-'); else ms=-ms; + if( ms < 0 ) b.add('-'); else ms = -ms; _digits(b,-(ms/MINUTE),2).add(':'); _digits(b,-_mod(ms/SECOND,60),2).add('.'); _digits(b,-_mod(ms,SECOND),3); return text.end(b); }; val format = { i64 instant, int style -> - if( style==ELAPSED ) return elapsed(instant); + if( style == ELAPSED ) return elapsed(instant); return _format(instant,style,false); }; val formatLocal = { i64 instant, int style -> - if( style==ELAPSED ) return elapsed(instant); + if( style == ELAPSED ) return elapsed(instant); return _format(instant,style,true); }; val _number = { u8[~] s, i64 at, int count -> - if( at<0 || count<1 || at+count>s# ) return -1; - int n=0; - for( int i=0; i<count; i++ ) { - int c=s[at+i]; - if( c<'0' || c>'9' ) return -1; - n=n*10+c-'0'; + if( at < 0 || count < 1 || at+count > s# ) return -1; + int n = 0; + for( int i = 0; i < count; i++ ) { + int c = s[at+i]; + if( c < '0' || c > '9' ) return -1; + n = n*10+c-'0'; } return n; }; // Keep suffix validation separate from calendar construction. val _parseZone = { u8[~] s, int at, i64 instant -> - if( at<0 || at>=s# ) return -1; - i64 offset=0; - if( s[at]=='Z' ) { if( at+1!=s# ) return -1; } + if( at < 0 || at >= s# ) return -1; + i64 offset = 0; + if( s[at] == 'Z' ) { if( at+1 != s# ) return -1; } else { - int sign=s[at]=='+' ? 1 : s[at]=='-' ? -1 : 0; - if( !sign || (s#!=at+6 && s#!=at+9) || s[at+3]!=':' ) return -1; - int oh=_number(s,at+1,2), om=_number(s,at+4,2), os=0; - if( s#==at+9 ) { if( s[at+6]!=':' ) return -1; os=_number(s,at+7,2); } - if( oh<0 || oh>23 || om<0 || om>59 || os<0 || os>59 ) return -1; - offset=sign*(oh*HOUR+om*MINUTE+os*SECOND); + int sign = s[at] == '+' ? 1 : s[at] == '-' ? -1 : 0; + if( !sign || (s# != at+6 && s# != at+9) || s[at+3] != ':' ) return -1; + int oh = _number(s,at+1,2), om = _number(s,at+4,2), os = 0; + if( s# == at+9 ) { if( s[at+6] != ':' ) return -1; os = _number(s,at+7,2); } + if( oh < 0 || oh > 23 || om < 0 || om > 59 || os < 0 || os > 59 ) return -1; + offset = sign*(oh*HOUR+om*MINUTE+os*SECOND); } - instant-=offset; - return instant<MIN || instant>MAX ? -1 : instant; + instant -= offset; + return instant < MIN || instant > MAX ? -1 : instant; }; // Strict ISO absolute instants only. -1 is reserved for failure (and therefore // cannot distinguish the valid instant one millisecond before Unix epoch). val parse = { u8[~] s -> - if( s#<20 || s[4]!='-' || s[7]!='-' || s[10]!='T' || s[13]!=':' || s[16]!=':' ) return -1; - int y=_number(s, 0,4), m =_number(s, 5,2), d =_number(s, 8,2); - int h=_number(s,11,2), min=_number(s,14,2), sec=_number(s,17,2); - bool fraction=s[19]=='.'; - int ms=fraction ? _number(s,20,3) : 0; + if( s# < 20 || s[4] != '-' || s[7] != '-' || s[10] != 'T' || s[13] != ':' || s[16] != ':' ) return -1; + int y = _number(s, 0,4), m = _number(s, 5,2), d = _number(s, 8,2); + int h = _number(s,11,2), min = _number(s,14,2), sec = _number(s,17,2); + bool fraction = s[19] == '.'; + int ms = fraction ? _number(s,20,3) : 0; if( !valid(y,m,d,h,min,sec,ms) ) return -1; return _parseZone(s,fraction ? 23 : 19,makeUTC(y,m,d,h,min,sec,ms)); }; diff --git a/chapter31/src/main/smp/sys/time/Timers.smp b/chapter31/src/main/smp/sys/time/Timers.smp index eca32d15..7cca2e9c 100644 --- a/chapter31/src/main/smp/sys/time/Timers.smp +++ b/chapter31/src/main/smp/sys/time/Timers.smp @@ -14,37 +14,37 @@ struct Timers { // Add a new timer { i64 i64 i64 -> u32 } _add = { i64 current_ms, i64 delay_ms, i64 period_ms -> - if( current_ms<0 || delay_ms<0 || current_ms>sys.integer.MAX_I64-delay_ms || _next==0 ) return 0; + if( current_ms < 0 || delay_ms < 0 || current_ms > sys.integer.MAX_I64-delay_ms || _next == 0 ) return 0; // Ugly linear scan for an available slot - int slot=0; - while( slot<_ids# && _ids[slot]!=0 ) slot++; + int slot = 0; + while( slot < _ids# && _ids[slot] != 0 ) slot++; // Double size for lots of timers - if( slot==_ids# ) { - if( _ids#>sys.integer.MAX_I32/2 ) return 0; + if( slot == _ids# ) { + if( _ids# > sys.integer.MAX_I32/2 ) return 0; val ids = new u32[_ids#*2]; val due_ms = new i64[_ids#*2], periods_ms = new i64[_ids#*2]; - for( int i=0; i<_ids#; i++ ) { ids[i]=_ids[i]; due_ms[i]=_due_ms[i]; periods_ms[i]=_period_ms[i]; } - _ids=ids; _due_ms=due_ms; _period_ms=periods_ms; + for( int i = 0; i < _ids#; i++ ) { ids[i] = _ids[i]; due_ms[i] = _due_ms[i]; periods_ms[i] = _period_ms[i]; } + _ids = ids; _due_ms = due_ms; _period_ms = periods_ms; // Retry against the newly published arrays after growing. return _add(current_ms,delay_ms,period_ms); } // Next available timer id u32 id = _next; - _next = id==sys.integer.MAX_U32 ? 0 : id+1; - _ids[slot]=id; _due_ms[slot]=current_ms+delay_ms; _period_ms[slot]=period_ms; + _next = id == sys.integer.MAX_U32 ? 0 : id+1; + _ids[slot] = id; _due_ms[slot] = current_ms+delay_ms; _period_ms[slot] = period_ms; return id; }; // Explicit-clock versions make game logic and tests deterministic. { i64 i64 -> u32 } afterAt = { i64 current_ms, i64 delay_ms -> _add(current_ms,delay_ms,0); }; - { i64 i64 -> u32 } everyAt = { i64 current_ms, i64 period_ms -> period_ms<=0 ? 0 : _add(current_ms,period_ms,period_ms); }; + { i64 i64 -> u32 } everyAt = { i64 current_ms, i64 period_ms -> period_ms <= 0 ? 0 : _add(current_ms,period_ms,period_ms); }; { i64 -> u32 } after = { i64 delay_ms -> afterAt(time.monotonic(),delay_ms ); }; { i64 -> u32 } every = { i64 period_ms -> everyAt(time.monotonic(),period_ms); }; // Remove a timer val cancel = { u32 id -> - if( id==0 ) return false; - for( int i=0; i<_ids#; i++ ) if( _ids[i]==id ) { _ids[i]=0; return true; } + if( id == 0 ) return false; + for( int i = 0; i < _ids#; i++ ) if( _ids[i] == id ) { _ids[i] = 0; return true; } return false; }; @@ -52,8 +52,8 @@ struct Timers { val nextDeadline = { -> i64 next_ms = -1; // Ugly linear scan again, but short - for( int i=0; i<_ids#; i++ ) - if( _ids[i]!=0 && (next_ms<0 || _due_ms[i] < next_ms) ) next_ms = _due_ms[i]; + for( int i = 0; i < _ids#; i++ ) + if( _ids[i] != 0 && (next_ms < 0 || _due_ms[i] < next_ms) ) next_ms = _due_ms[i]; return next_ms; }; @@ -63,16 +63,16 @@ struct Timers { // Repeats skip missed ticks and retain their phase, avoiding bursts/drift. { i64 -> u32 } poll = { i64 current_ms -> int slot = -1; - for( int i=0; i<_ids#; i++ ) - if( _ids[i]!=0 && _due_ms[i]<=current_ms && (slot<0 || _due_ms[i]<_due_ms[slot] || - (_due_ms[i]==_due_ms[slot] && _ids[i]<_ids[slot])) ) slot=i; - if( slot<0 ) return 0; + for( int i = 0; i < _ids#; i++ ) + if( _ids[i] != 0 && _due_ms[i] <= current_ms && (slot < 0 || _due_ms[i] < _due_ms[slot] || + (_due_ms[i] == _due_ms[slot] && _ids[i] < _ids[slot])) ) slot = i; + if( slot < 0 ) return 0; u32 id = _ids[slot]; i64 period_ms = _period_ms[slot]; - if( period_ms==0 ) _ids[slot]=0; + if( period_ms == 0 ) _ids[slot] = 0; else { i64 steps = (current_ms-_due_ms[slot])/period_ms; - if( steps>=(sys.integer.MAX_I64-_due_ms[slot])/period_ms ) _ids[slot]=0; + if( steps >= (sys.integer.MAX_I64-_due_ms[slot])/period_ms ) _ids[slot] = 0; else _due_ms[slot] += (steps+1)*period_ms; } return id; diff --git a/chapter31/src/test/java/com/seaofnodes/simple/ArithNodeTest.java b/chapter31/src/test/java/com/seaofnodes/simple/ArithNodeTest.java index 1e6c6fc0..b29c9706 100644 --- a/chapter31/src/test/java/com/seaofnodes/simple/ArithNodeTest.java +++ b/chapter31/src/test/java/com/seaofnodes/simple/ArithNodeTest.java @@ -65,7 +65,7 @@ public class ArithNodeTest { TypePtr.gather(inputs); TypeMemPtr.gather(inputs); TypeFunPtr.gather(inputs); - inputs.add(TypeConAryB.make(new byte[]{1,2,3})); + inputs.add(TypeConAry.make(new byte[]{1,2,3})); for( long value : new long[]{Long.MIN_VALUE,Long.MIN_VALUE+1,-1,1,Long.MAX_VALUE} ) inputs.add(TypeInteger.constant(value)); for( double value : new double[]{-0.0,0.0,-1.0,1.0,16777216.0,16777217.0,Double.NaN,Double.NEGATIVE_INFINITY,Double.POSITIVE_INFINITY} ) diff --git a/chapter31/src/test/java/com/seaofnodes/simple/ArrayInitTest.java b/chapter31/src/test/java/com/seaofnodes/simple/ArrayInitTest.java index 6cba5ee3..d298828e 100644 --- a/chapter31/src/test/java/com/seaofnodes/simple/ArrayInitTest.java +++ b/chapter31/src/test/java/com/seaofnodes/simple/ArrayInitTest.java @@ -1,10 +1,46 @@ package com.seaofnodes.simple; import com.seaofnodes.simple.codegen.CodeGen; +import com.seaofnodes.simple.node.ArrayInitNode; +import com.seaofnodes.simple.node.ConstantNode; +import com.seaofnodes.simple.node.Node; +import com.seaofnodes.simple.type.*; +import com.seaofnodes.simple.util.Ary; +import java.util.ArrayList; import org.junit.Test; import static org.junit.Assert.*; public class ArrayInitTest { + @Test public void constantListComputeIsMonotone() { + CodeGen code = new CodeGen("return 0;").parse(); + TypeStruct layout = TypeStruct.makeAry("[]i32",TypeInteger.U32,2,TypeInteger.I32,3,true); + Type array = TypeMemPtr.make(layout); + Node ctrl = ConstantNode.seed(Type.CONTROL); + Node ptr = ConstantNode.seed(Type.TOP); + Node len = ConstantNode.seed(Type.TOP); + Node x = ConstantNode.seed(Type.TOP), y = ConstantNode.seed(Type.TOP); + ArrayInitNode init = new ArrayInitNode(ctrl,code.ZERO,ptr,len,2,null,new Ary<>(new Node[]{x,y})); + Type[][] inputs = { + {Type.TOP,TypeMemPtr.TOP,array}, + {Type.TOP,TypeInteger.TOP,TypeInteger.TWO,TypeInteger.U32}, + {Type.TOP,TypeInteger.TOP,TypeInteger.constant(5),TypeInteger.BOT}, + {Type.TOP,TypeInteger.TOP,TypeInteger.constant(6),TypeInteger.BOT} + }; + var states = new ArrayList<Type[]>(); + for( Type p : inputs[0] ) + for( Type l : inputs[1] ) + for( Type a : inputs[2] ) + for( Type b : inputs[3] ) { + ptr._type = p; len._type = l; x._type = a; y._type = b; + states.add(new Type[]{p,l,a,b,init.compute()}); + } + for( Type[] before : states ) + for( Type[] after : states ) + if( before[0].isa(after[0]) && before[1].isa(after[1]) && + before[2].isa(after[2]) && before[3].isa(after[3]) ) + assertTrue("Array initializer rose from "+before[4]+" to "+after[4],before[4].isa(after[4])); + } + private static void value(String src, long expected) { CodeGen code=new CodeGen(src).driver(CodeGen.Phase.TypeCheck); assertEquals(Long.toString(expected),Eval2.eval(code,0,100000)); diff --git a/chapter31/src/test/java/com/seaofnodes/simple/AssemblyDumpTest.java b/chapter31/src/test/java/com/seaofnodes/simple/AssemblyDumpTest.java new file mode 100644 index 00000000..0e4c230a --- /dev/null +++ b/chapter31/src/test/java/com/seaofnodes/simple/AssemblyDumpTest.java @@ -0,0 +1,61 @@ +package com.seaofnodes.simple; + +import com.seaofnodes.simple.codegen.CodeGen; +import com.seaofnodes.simple.type.*; +import com.seaofnodes.simple.util.BAOS; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.HexFormat; +import org.junit.Test; +import static org.junit.Assert.*; + +public class AssemblyDumpTest { + @Test public void libraryUnitsAndGlyphs() throws Exception { + Path root=Path.of("build/objs/assembly-dump"); + Files.createDirectories(root); + Path build=Files.createTempDirectory(root,"sys-"); + CodeGen code=new CodeGen("src/main/smp",build.toString(),null,"sys",null,123,true,TypeInteger.BOT) + .driver(CodeGen.Phase.Serialize,TestC.CPU_PORT,TestC.CALL_CONVENTION) + .driver(CodeGen.Phase.Encoding,TestC.CPU_PORT,TestC.CALL_CONVENTION); + var entry=code._encoding; + String before=code.asm(); + assertSame("Dumping another unit must not change the active encoding",entry,code._encoding); + for( var unit : code._compunits.values() ) + if( unit._src!=null ) { + String heading="=== Compilation unit: "+unit._cname+" ==="; + assertEquals("Exactly one heading for "+unit._cname,2,before.split(heading,-1).length); + } + int start=before.indexOf("=== Compilation unit: sys.draw.Canvas ==="); + assertTrue(start>=0); + int end=before.indexOf("=== Compilation unit:",start+1); + String canvas=before.substring(start,end<0 ? before.length() : end); + assertTrue(canvas.contains("Constant Pool")); + assertTrue(canvas.contains("sys.draw.Canvas._glyphs: []u16")); + TypeMemPtr ptr=(TypeMemPtr)code._compunits.get("sys/draw/Canvas")._clz.field("_glyphs")._t; + TypeConAry glyphs=(TypeConAry)ptr._obj.field("[]")._t; + assertEquals(96,glyphs.len()); + BAOS bytes=new BAOS(); + glyphs.write(bytes); + assertTrue("The complete font follows its u32 length header", + canvas.contains("60000000"+HexFormat.of().formatHex(bytes.toByteArray()))); + code.exportELF(false,false); + com.seaofnodes.simple.codegen.PrintRegTestSupport.checkDataAliases( + build.resolve("sys/draw/Canvas.o"),196,"sys.draw.Canvas._glyphs"); + assertSame(entry,code._encoding); + assertEquals("Export must not truncate the dump to its entry unit",before,code.asm()); + Files.writeString(build.resolve("sys.asm"),before); + } + + @Test public void combinedEncodingAndEarlierPhase() { + for( String cpu : new String[]{"x86_64_v2","arm","riscv"} ) { + CodeGen code=new CodeGen("val a=new u16[~]{5,6,7}; return a[arg&1];") + .driver(CodeGen.Phase.RegAlloc,cpu,"SystemV"); + assertFalse(code.asm().contains("Constant Pool")); + code.driver(cpu,"SystemV",true,false); + String dump=code.asm(); + assertFalse(dump.contains("=== Compilation unit:")); + assertTrue(dump.contains("Constant Pool")); + assertTrue(dump.contains("03000000050006000700")); + } + } +} diff --git a/chapter31/src/test/java/com/seaofnodes/simple/BreakoutTest.java b/chapter31/src/test/java/com/seaofnodes/simple/BreakoutTest.java new file mode 100644 index 00000000..efdb1dd7 --- /dev/null +++ b/chapter31/src/test/java/com/seaofnodes/simple/BreakoutTest.java @@ -0,0 +1,163 @@ +package com.seaofnodes.simple; + +import java.awt.image.BufferedImage; +import java.nio.ByteBuffer; +import java.nio.ByteOrder; +import java.nio.file.Files; +import java.nio.file.Path; +import javax.imageio.ImageIO; +import org.junit.Test; +import static org.junit.Assert.*; + +// Exercise the actual Simple game and rasterizer in native code, without a window. +public class BreakoutTest { + private static String game() throws Exception { + String source = Files.readString(Path.of("docs/examples/Breakout.smp")); + // Physics/rendering tests supply their own entry point. Input and + // sound are exercised by GraphicsTest with the complete program. + int end = source.indexOf("// Short, fading triangle waves"); + assertTrue("Breakout physics/rendering section",end >= 0); + String physics = source.substring(0,end); + // The shared square-root helper now follows the input code. + int sqrt = source.indexOf("val _sqrt ="); + if( sqrt >= end ) { + int close = source.indexOf("\n};",sqrt); + assertTrue("Square-root helper end",close >= 0); + physics += source.substring(sqrt,close+4); + } + return physics; + } + + @Test public void paddleLivesAndPause() throws Exception { + TestC.runSYS(game()+""" + val main={ -> + val g=new Game; + if( g.remaining!=192 || g.score!=0 || g.lives!=3 || g.phase!=READY ) return 1; + _tick(g,1); + if( g.paddle<510.39 || g.paddle>510.41 || g.x!=g.paddle ) return 2; + g._paddle(-100.0); if( g.paddle != 80.0 ) return 3; + g._paddle(2000.0); if( g.paddle != 928.0 ) return 4; + _reset(g); + g.x=g.paddle-50.0; _rebound(g); + if( g.dx > -0.78 || g.dy>=0.0 ) return 5; + g.x=g.paddle+50.0; _rebound(g); + if( g.dx < 0.78 || g.dy>=0.0 ) return 6; + g.x=g.paddle; _rebound(g); + if( g.dy > -0.99 || g.dx*g.dx+g.dy*g.dy<0.999999 ) return 7; + _serve(g); g.paused=true; + f64 x=g.x, y=g.y, paddle=g.paddle; + _tick(g,1); + if( g.x!=x || g.y!=y || g.paddle!=paddle ) return 8; + g.paused=false; + for( int i=0; i<3; i++ ) { + _serve(g); g.x=40.0; g.y=723.0; g.dx=0.0; g.dy=1.0; + _tick(g,0); + if( g.lives!=2-i || g.backWall || g.sound!=5 ) return 9; + } + if( g.phase!=LOST ) return 10; + _serve(g); if( g.phase!=LOST ) return 11; + _reset(g); + if( g.phase!=READY || g.lives!=3 || g.boosted || g.paused || g.speed!=320.0 ) return 12; + return 0; + }; + ""","breakoutControls","",-1); + } + + @Test public void collisionsAndBoost() throws Exception { + TestC.runSYS(game()+""" + val main={ -> + val g=new Game; + _serve(g); + g.x=29.1; g.y=400.0; g.dx=-1.0; g.dy=0.0; + _tick(g,0); + if( g.dx<=0.0 || g.x<29.0 || g.sound!=1 ) return 1; + g.x=978.9; g.dx=1.0; _tick(g,0); + if( g.dx>=0.0 || g.x>979.0 ) return 2; + // Front of the bottom row: one point, no acceleration or boost. + g.x=44.0; g.y=330.0; g.dx=0.0; g.dy=-1.0; + _tick(g,0); + if( g.bricks[168]!=0 || g.score!=1 || g.dy<=0.0 || g.boosted || g.soundDepth!=1 ) return 3; + // Top of a brick alone does not arm the back-wall bonus. + g.x=44.0; g.y=146.0; g.dy=1.0; + _tick(g,0); + if( g.bricks[0]!=0 || g.score!=9 || g.speed!=565.0 || g.boosted || g.soundDepth!=8 ) return 4; + // Back wall arms it; hitting a side still must not trigger it. + g.x=84.0; g.y=89.1; g.dy=-1.0; + _tick(g,0); + if( !g.backWall || g.dy<=0.0 || g.boosted ) return 5; + g.x=60.0; g.y=160.0; g.dx=1.0; g.dy=0.0; + _tick(g,0); + if( g.bricks[1]!=0 || g.dx>=0.0 || g.boosted ) return 6; + g.x=124.0; g.y=146.0; g.dx=0.0; g.dy=1.0; + _tick(g,0); + if( !g.boosted || g.speed<932.24 || g.speed>932.26 || g.dy>=0.0 || g.sound!=4 ) return 7; + // Another back hit cannot multiply the speed a second time. + g.x=164.0; g.y=146.0; g.dy=1.0; + _tick(g,0); + if( g.speed>932.26 || g.bricks[3]!=0 ) return 8; + // A boosted front hit cannot tunnel through the brick either. + g.x=84.0; g.y=331.0; g.dy=-1.0; + _tick(g,0); + if( g.bricks[169]!=0 || g.dy<=0.0 || g.speed<932.24 ) return 9; + // Actual paddle contact disarms the trip and chooses its angle. + g.x=g.paddle+50.0; g.y=668.0; g.dy=1.0; g.dx=0.0; + _tick(g,0); + if( g.dy>=0.0 || g.dx<0.78 || g.backWall || !g.boosted ) return 10; + // A lost ball clears both kinds of acceleration, preserving the wall/score. + int score=g.score, remaining=g.remaining; + g.x=40.0; g.y=723.0; g.dx=0.0; g.dy=1.0; + _tick(g,0); + if( g.phase!=READY || g.lives!=2 || g.speed!=320.0 || g.depth!=1 || g.boosted ) return 11; + if( g.score!=score || g.remaining!=remaining ) return 12; + _serve(g); + if( g.speed!=320.0 ) return 13; + // The new ball can earn its own boost. + g.sound=0; g.backWall=true; + g.x=204.0; g.y=146.0; g.dx=0.0; g.dy=1.0; + _tick(g,0); + if( !g.boosted || g.speed<932.24 || g.sound!=4 ) return 14; + return 0; + }; + ""","breakoutCollisions","",-1); + } + + @Test public void clearEveryBrickAndRender() throws Exception { + TestC.runSYS(game()+""" + val main={ -> + val g=new Game; + val c=new sys.draw.Canvas(WIDTH,HEIGHT); + _draw(c,g); + for( int row=0; row<ROWS; row++ ) + if( c.pixels[(BRICK_TOP+row*BRICK_DY+4)*WIDTH+28]!=COLORS[row] ) return 1; + if( c.pixels[675*WIDTH+504]!=CYAN || c.pixels[663*WIDTH+504]!=WHITE ) return 2; + // Save a native-rendered preview for manual visual review. + int fd=sys.io.create("build/objs/breakout-preview.bgra"); + i64 pixels=c.pixels; + if( fd<0 || sys.libc.write(fd,pixels,c.pixels#*4)!=c.pixels#*4 ) return 3; + sys.io.close(fd); + _serve(g); + // Drive through every brick's front, bottom row first. + for( int i=COLS*ROWS-1; i>=0; i-- ) { + g.x=LEFT+20.0+(i-i/COLS*COLS)*BRICK_DX; + g.y=BRICK_TOP+1.0+(i/COLS)*BRICK_DY+BRICK_H+RADIUS; + g.dx=0.0; g.dy=-1.0; + _tick(g,0); + if( g.bricks[i]!=0 ) return 4; + } + if( g.phase!=WON || g.remaining!=0 || g.score!=864 || g.sound!=6 ) return 5; + f64 y=g.y; _tick(g,0); + if( g.y!=y ) return 6; + _reset(g); + for( int i=0; i<g.bricks#; i++ ) if( g.bricks[i]!=1 ) return 7; + if( g.score!=0 || g.remaining!=192 ) return 8; + return 0; + }; + ""","breakoutClear","",-1); + byte[] pixels=Files.readAllBytes(Path.of("build/objs/breakout-preview.bgra")); + assertEquals(1008*760*4,pixels.length); + var image=new BufferedImage(1008,760,BufferedImage.TYPE_INT_RGB); + var bytes=ByteBuffer.wrap(pixels).order(ByteOrder.LITTLE_ENDIAN); + for(int y=0;y<760;y++) for(int x=0;x<1008;x++) image.setRGB(x,y,bytes.getInt()); + ImageIO.write(image,"png",Path.of("build/objs/breakout-preview.png").toFile()); + } +} diff --git a/chapter31/src/test/java/com/seaofnodes/simple/BulkMemPhiTest.java b/chapter31/src/test/java/com/seaofnodes/simple/BulkMemPhiTest.java index 31c0302b..fd816c68 100644 --- a/chapter31/src/test/java/com/seaofnodes/simple/BulkMemPhiTest.java +++ b/chapter31/src/test/java/com/seaofnodes/simple/BulkMemPhiTest.java @@ -4,10 +4,35 @@ import com.seaofnodes.simple.codegen.CodeGen; import com.seaofnodes.simple.node.*; import com.seaofnodes.simple.type.TypeInteger; import com.seaofnodes.simple.type.TypeMem; +import com.seaofnodes.simple.type.Type; +import com.seaofnodes.simple.type.XInt; import org.junit.Test; import static org.junit.Assert.*; public class BulkMemPhiTest { + @Test public void testUnescapedSliceKeepsItsOwnEscapes() { + CodeGen code = new CodeGen(""); + code._phase = CodeGen.Phase.Lower; + Node defaults = code.con(TypeMem.START); + Node method = code.con(TypeMem.make(55,Type.BOTTOM,false,false,false,XInt.make(4),XInt.EMPTY)); + MemMergeNode fields = new MemMergeNode(null,defaults); + fields.alias(55,method); + fields.init(); + assertSame("The bulk excludes this unescaped field",TypeMem.START,fields._type); + Node ctrl = new CProjNode(code._start,0,"Ctrl").init(); + Node iff = new IfNode(ctrl,code.con(TypeInteger.BOOL)).init(); + RegionNode region = new RegionNode(null,null, + new CProjNode(iff,0,"True").init(), + new CProjNode(iff,1,"False").init()).init(); + BulkMemPhiNode bulk = new BulkMemPhiNode("$mem",region,fields,defaults).init(); + MemMergeNode split = (MemMergeNode)bulk.idealize(); + Node precise = split.alias(55); + assertTrue("A new slice must not inherit an escape bound that excludes its method", + precise.compute().isa(precise._type)); + precise.peephole(); + assertTrue(XInt.bit(((TypeMem)precise._type)._escFs,4)); + } + // Reduced from Capitalize's Lower-phase failure. A precise MemMerge slot // may still be supplied by bulk memory which covers the requested alias. @Test public void testBulkInPreciseSlot() { diff --git a/chapter31/src/test/java/com/seaofnodes/simple/Chapter25Test.java b/chapter31/src/test/java/com/seaofnodes/simple/Chapter25Test.java index 055ef518..85f273a1 100644 --- a/chapter31/src/test/java/com/seaofnodes/simple/Chapter25Test.java +++ b/chapter31/src/test/java/com/seaofnodes/simple/Chapter25Test.java @@ -477,7 +477,7 @@ public class Chapter25Test { // Software drawing and the optional native graphics interface. assertArrayEquals(new String[]{"sys/adt", "sys/ary", - "sys/aryi64", "sys/aryu8", "sys/audio", "sys/char", "sys/draw", "sys/gfx", "sys/integer", "sys/io", "sys/libc", "sys/rt", "sys/scan", "sys/text", "sys/time"},sys_elf._deps); + "sys/aryi64", "sys/aryu8", "sys/audio", "sys/char", "sys/draw", "sys/gfx", "sys/integer", "sys/io", "sys/libc", "sys/math", "sys/rt", "sys/scan", "sys/text", "sys/time"},sys_elf._deps); assertArrayEquals(new String[]{"sys"},sys_elf._units); assertSame("class:sys" ,sys_elf._clz._name); } diff --git a/chapter31/src/test/java/com/seaofnodes/simple/ConstantArrayTest.java b/chapter31/src/test/java/com/seaofnodes/simple/ConstantArrayTest.java new file mode 100644 index 00000000..c641487b --- /dev/null +++ b/chapter31/src/test/java/com/seaofnodes/simple/ConstantArrayTest.java @@ -0,0 +1,123 @@ +package com.seaofnodes.simple; + +import com.seaofnodes.simple.codegen.CodeGen; +import com.seaofnodes.simple.codegen.StaticData; +import com.seaofnodes.simple.node.*; +import com.seaofnodes.simple.parser.Parser; +import com.seaofnodes.simple.type.*; +import com.seaofnodes.simple.util.Ary; +import java.nio.file.Files; +import java.nio.file.Path; +import org.junit.Test; +import static org.junit.Assert.*; + +public class ConstantArrayTest { + private static StaticData.ObjectData array(CodeGen code, TypeInteger storage, int len) { + var arrays=code._encoding._data.entries().stream().filter(o -> + o.type instanceof TypeStruct ts && ts.isConAry() && + ts.field("[]")._t instanceof TypeConAry c && c.storageType()==storage && c.len()==len).toList(); + assertEquals(1,arrays.size()); + assertTrue(arrays.getFirst().readOnly); + return arrays.getFirst(); + } + + @Test public void typedDataAndSharing() throws Exception { + String source=""" + val a=new u16[~]{025755,65535,65538}; + val b=new u16[~]{025755,65535,65538}; + val fresh={ -> new u16[~]{025755,65535,65538}; }; + val main={ -> + if(a!=b || a!=fresh() || a#!=3 || a[0]!=025755 || a[1]!=65535 || a[2]!=2) return 1; + val bytes=new u8[~]{65,66,67}; + if(bytes!="ABC") return 2; + val signed=new i16[~]{-32768,-1,32767}; + if(signed[0]!=-32768 || signed[1]!=-1 || signed[2]!=32767) return 3; + val ints=new i32[~]{-2147483648,2147483647}; + if(ints[0]!=-2147483648 || ints[1]!=2147483647) return 4; + val uints=new u32[~]{0,4294967295}; + if(uints[1]!=4294967295) return 5; + val longs=new i64[~]{1<<63,0x7fffffffffffffff}; + if(longs[0]!=(1<<63) || longs[1]!=0x7fffffffffffffff) return 6; + val empty=new u16[~]{}; + if(empty#!=0) return 7; + return 0; + }; + """; + TestC.runSF(source,"constantArrayWidths","",-1); + CodeGen code=new CodeGen(source).driver(CodeGen.Phase.Encoding,TestC.CPU_PORT,TestC.CALL_CONVENTION); + StaticData.ObjectData obj=array(code,TypeInteger.U16,3); + assertEquals("Test.a, Test.b",obj.label()); + assertEquals(12,obj.size); // Four-byte length, six data bytes, alignment padding. + byte[] bytes=code._encoding._cpool.buf(); + assertEquals(3,bytes[obj.offset]); + assertEquals(025755&255,bytes[obj.offset+4]&255); + assertEquals(025755>>>8,bytes[obj.offset+5]&255); + assertEquals(255,bytes[obj.offset+6]&255); + assertEquals(255,bytes[obj.offset+7]&255); + assertNull(code._stop.walk(n -> n instanceof NewNode ? n : null)); + com.seaofnodes.simple.codegen.PrintRegTestSupport.checkDataAliases( + Path.of("build/objs/constantArrayWidths.o"),12,"constantArrayWidths.a","constantArrayWidths.b"); + } + + @Test public void arbitraryProducerUsesStaticData() { + for(String cpu:new String[]{"x86_64_v2","arm","riscv"}) { + CodeGen code=new CodeGen("u16[~]? unused=null; return 0;").parse(); + TypeStruct layout=(TypeStruct)Parser.TYPES.get("[]u16"); + TypeConAry contents=TypeConAry.make(TypeInteger.U16,new long[]{1,65535}); + TypeStruct array=TypeStruct.makeAry(layout._name,layout.field("#")._alias,layout.field("[]")._alias,contents); + Type ptr=TypeMemPtr.make((byte)2,array,true).makeRO(); + // No initializer or allocation node: only compute() supplies the type. + Node producer=new ReadOnlyNode(code.ZERO) { + @Override public String label() { return "constant-array producer"; } + @Override public Type compute() { return ptr; } + }; + ReturnNode ret=code._stop.walk(n -> n instanceof ReturnNode r && r.fun().isClz() ? r : null); + assertNotNull(ret); + ret.setDef(2,producer.peephole()); + code.add(ret); + code.driver(CodeGen.Phase.Encoding,cpu,"SystemV"); + StaticData.ObjectData obj=array(code,TypeInteger.U16,2); + assertEquals(8,obj.size); + } + } + + @Test public void sideEffectsAndMutableArrays() throws Exception { + CodeGen eval=new CodeGen(""" + val same_noInline={u16[~] a -> a==new u16[~]{1,2};}; + return same_noInline(new u16[~]{1,2}); + """).driver(CodeGen.Phase.TypeCheck); + assertEquals("1",Eval2.eval(eval,0)); + TestC.runSF(""" + val next={int[] counter -> counter[0]++; return 7;}; + val main={ -> + val count=new int[1]; + val a=new int[~]{next(count),next(count)}; + if(count[0]!=2 || a[0]!=7 || a[1]!=7) return 1; + val b=new int[]{7,7}, c=new int[]{7,7}; + if(b==c) return 2; + int[~] view=b; + b[0]=9; + if(view[0]!=9 || c[0]!=7) return 3; + return 0; + }; + ""","constantArrayEffects","",-1); + } + + @Test public void importedTypedConstants() throws Exception { + Path root=Path.of("build/objs/separate"); + Files.createDirectories(root); + Path lib=Files.createTempDirectory(root,"constant-arrays-"); + new CodeGen(null,lib.toString(),null,"Table",""" + val small=new u16[~]{1,65535}; + val wide=new i64[~]{1<<63,0x7fffffffffffffff}; + val uints=new u32[~]{4294967295}; + val signed=new i32[~]{-2147483648}; + """,126,true,TypeInteger.BOT).driver(TestC.CPU_PORT,TestC.CALL_CONVENTION,false,false); + var paths=new Ary<>(new String[]{lib.toString()}); + CodeGen code=new CodeGen(null,"build/objs",paths,"TableClient",""" + return Table.small[1]==65535 && Table.wide[0]==(1<<63) && + Table.wide[1]==0x7fffffffffffffff && Table.uints[0]==4294967295 && Table.signed[0]==-2147483648; + """,126,true,TypeInteger.BOT).driver(CodeGen.Phase.TypeCheck); + assertEquals("1",Eval2.eval(code,0)); + } +} diff --git a/chapter31/src/test/java/com/seaofnodes/simple/ConvertNodeTest.java b/chapter31/src/test/java/com/seaofnodes/simple/ConvertNodeTest.java index 96d73f26..bdda3171 100644 --- a/chapter31/src/test/java/com/seaofnodes/simple/ConvertNodeTest.java +++ b/chapter31/src/test/java/com/seaofnodes/simple/ConvertNodeTest.java @@ -28,7 +28,7 @@ public class ConvertNodeTest { for( boolean arrayRO : new boolean[]{false,true} ) inputs.add(TypeMemPtr.make(TypeStruct.makeAry("[]test",len,-1, TypeMemPtr.TEST.withAccess(elementRO),-2,false)).withAccess(arrayRO)); - inputs.add(TypeConAryB.make(new byte[]{1,2,3})); + inputs.add(TypeConAry.make(new byte[]{1,2,3})); for( long value : new long[]{Long.MIN_VALUE,-129,-128,-1,0,1,127,128,255,256,Long.MAX_VALUE} ) inputs.add(TypeInteger.constant(value)); for( double value : new double[]{-0.0,0.0,1.0,16777217.0,Double.NaN,Double.NEGATIVE_INFINITY,Double.POSITIVE_INFINITY} ) diff --git a/chapter31/src/test/java/com/seaofnodes/simple/Eval2.java b/chapter31/src/test/java/com/seaofnodes/simple/Eval2.java index b6228666..eef05f93 100644 --- a/chapter31/src/test/java/com/seaofnodes/simple/Eval2.java +++ b/chapter31/src/test/java/com/seaofnodes/simple/Eval2.java @@ -110,6 +110,7 @@ public abstract class Eval2 { // Class pointers and initializer self parameters share one object per run. private static final HashMap<String,Object[]> CLASSES = new HashMap<>(); + private static final IdentityHashMap<TypeStruct,Object[]> ARRAYS = new IdentityHashMap<>(); public static String eval( CodeGen code, long arg ) { return eval(code,arg,1000); } public static String eval( CodeGen code, long arg, int timeout ) { @@ -122,6 +123,7 @@ public abstract class Eval2 { // selection. Objects loaded later are scheduled independently. code.driver(CodeGen.Phase.LocalSched); CLASSES.clear(); + ARRAYS.clear(); // Timer for when we run too long. Ticks once per backedge or function call int loopCnt = 0; @@ -334,6 +336,8 @@ public abstract class Eval2 { case RoundF32Node rnd -> (double)(float)d(rnd.in(1)); case ToIntegerNode cvt -> (long)d(cvt.in(1)); case ToFloatNode toflt-> (double)x(toflt.in(1)); + case Intrinsic.F64BitsNode cast -> Double.doubleToRawLongBits(d(cast.in(1))); + case Intrinsic.F64FromBitsNode cast -> Double.longBitsToDouble(x(cast.in(1))); case XorNode xor -> x(xor.in(1)) ^ x(xor.in(2)); default -> throw Utils.TODO(); }; @@ -361,9 +365,12 @@ public abstract class Eval2 { if( tmp._obj.isAry() ) { // Constant array ptr Type elem = tmp._obj.field("[]")._t; if( elem instanceof TypeConAry con ) { + Object[] old=ARRAYS.get(tmp._obj); + if( old!=null ) yield old; Object[] xs = new Object[con.len()]; for( int i=0; i<con.len(); i++ ) xs[i] = con.at8(i); + ARRAYS.put(tmp._obj,xs); yield xs; } else { // Generic constant array, used as a default input to a diff --git a/chapter31/src/test/java/com/seaofnodes/simple/FloatNegationNativeTest.java b/chapter31/src/test/java/com/seaofnodes/simple/FloatNegationNativeTest.java new file mode 100644 index 00000000..dbbe353a --- /dev/null +++ b/chapter31/src/test/java/com/seaofnodes/simple/FloatNegationNativeTest.java @@ -0,0 +1,21 @@ +package com.seaofnodes.simple; + +import org.junit.Test; + +public class FloatNegationNativeTest extends TestC { + @Test public void negateRuntimeValues() throws Exception { + // Keep negation out of constant folding, including both signs of zero. + runSYS(""" + val neg_noInline={f64 x -> -x;}; + val main={ -> + if( neg_noInline(2.5)!=-2.5 || neg_noInline(-3.75)!=3.75 ) return 1; + if( 1.0/neg_noInline(0.0)!=-1e300*1e300 ) return 2; + if( 1.0/neg_noInline(-0.0)!=1e300*1e300 ) return 3; + if( neg_noInline(1e300*1e300)!=-1e300*1e300 ) return 4; + f64 nan=neg_noInline(1e300*1e300-1e300*1e300); + if( nan==nan ) return 5; + return 0; + }; + ""","floatNegation","",-1); + } +} diff --git a/chapter31/src/test/java/com/seaofnodes/simple/GraphicsTest.java b/chapter31/src/test/java/com/seaofnodes/simple/GraphicsTest.java index 66ced278..110a6a38 100644 --- a/chapter31/src/test/java/com/seaofnodes/simple/GraphicsTest.java +++ b/chapter31/src/test/java/com/seaofnodes/simple/GraphicsTest.java @@ -10,7 +10,7 @@ import static org.junit.Assert.*; // These tests never open a window and do not need MiniFB installed. public class GraphicsTest { - private static String graphics, text, game, clock; + private static String graphics, text, game, clock, breakout; @BeforeClass public static void compilePrograms() throws Exception { var paths = new Ary<>(new String[]{TestC.RELEASE_SYS_DIR}); @@ -22,6 +22,8 @@ public class GraphicsTest { "graphics_game",paths,TestC.CALL_CONVENTION,null,null,-1); clock = TestC.compile(Files.readString(Path.of("docs/examples/Clock.smp")), "graphics_clock",paths,TestC.CALL_CONVENTION,null,null,-1); + breakout = TestC.compile(Files.readString(Path.of("docs/examples/Breakout.smp")), + "graphics_breakout",paths,TestC.CALL_CONVENTION,null,null,-1); } private static String run(String exe, String backend, int exit) throws Exception { @@ -101,6 +103,71 @@ public class GraphicsTest { assertTrue(run(clock,"off",1).contains("disabled")); } + @Test public void breakoutWithoutBackend() throws Exception { + assertTrue(run(breakout,"off",1).contains("disabled")); + } + + @Test public void breakoutInputAndFrames() throws Exception { + Path source=Path.of("build/objs/breakout_input.c"); + Path library=Path.of("build/objs/breakout_input"+(TestC.OS.startsWith("Windows") ? ".dll" : ".so")); + Files.writeString(source,""" + #include "simple_graphics.h" + #include <stdio.h> + #include <unistd.h> + static int frames, previous_ball, previous_paddle; + static int32_t open_window(const char *s,uint32_t w,uint32_t h) { + return w==1008 && h==760 ? 0 : -1; + } + static int32_t present(const uint32_t *p,uint32_t n) { + if(n!=1008*760) return -1; + int paddle=-1,ball=-1; + for(int x=24;x<984;x++) if(p[675*1008+x]==0x4ce0ef) { paddle=x; break; } + for(int y=560;y<674 && ball<0;y++) + for(int x=24;x<984;x++) if(p[y*1008+x]==0xeef7ff) { ball=y; break; } + int ok=paddle>=0 && ball>=0; + if(frames==0) ok=ok && paddle==448 && ball==658; + if(frames==1 || frames==6 || frames==9) ok=ok && ball<previous_ball; + if(frames==2 || frames==3) ok=ok && paddle>previous_paddle; + if(frames==4 || frames==5) ok=ok && paddle==previous_paddle && ball==previous_ball; + if(frames==7) ok=ok && paddle==584; + if(frames==8) ok=ok && paddle==448 && ball==658; + if(!ok) { + printf("bad frame %d: paddle %d (was %d), ball %d (was %d)\\n", + frames,paddle,previous_paddle,ball,previous_ball); + return -1; + } + previous_ball=ball; previous_paddle=paddle; + if(++frames==10) puts("breakout input smoke passed"); + return 0; + } + static int32_t poll_events(int32_t n) { return 0; } + static int32_t mouse_x(void) { return frames>=7 ? 640 : 504; } + static int32_t mouse_y(void) { return 680; } + static int32_t key(int32_t k) { + return (k==' ' && (frames==1 || frames==9)) || + (k==262 && (frames==2 || frames==3)) || + (k=='P' && (frames==4 || frames==6)) || + (k=='R' && (frames==8 || frames==9)); + } + static int32_t wait_events(int64_t ms) { usleep(ms*1000); return 0; } + static void close_window(void) {} + static const struct simple_graphics_api api={SIMPLE_GRAPHICS_VERSION, + open_window,present,poll_events,mouse_x,mouse_y,poll_events,key,close_window,wait_events}; + const struct simple_graphics_api *simple_minifb_api(void) { return &api; } + """); + TestC.exec(30,"gcc","-shared","-fPIC","-Isrc/main/c",source.toString(),"-o",library.toString()); + var pb=new ProcessBuilder(Path.of(breakout).toAbsolutePath().toString(),"smoke").redirectErrorStream(true); + pb.environment().put("SIMPLE_MINIFB",library.toAbsolutePath().toString()); + pb.environment().put("SIMPLE_MINIAUDIO","off"); + Process child=pb.start(); + try { + assertTrue("Breakout timed out",child.waitFor(10,TimeUnit.SECONDS)); + String output=new String(child.getInputStream().readAllBytes(),java.nio.charset.StandardCharsets.UTF_8); + assertEquals(output,0,child.exitValue()); + assertEquals("breakout input smoke passed\n",output); + } finally { if(child.isAlive()) child.destroyForcibly(); } + } + @Test public void missingLibrary() throws Exception { String missing = Path.of("build","no-such-minifb-backend").toAbsolutePath().toString(); String output = run(graphics,missing,1); diff --git a/chapter31/src/test/java/com/seaofnodes/simple/IntrinsicTest.java b/chapter31/src/test/java/com/seaofnodes/simple/IntrinsicTest.java new file mode 100644 index 00000000..e3b30efb --- /dev/null +++ b/chapter31/src/test/java/com/seaofnodes/simple/IntrinsicTest.java @@ -0,0 +1,188 @@ +package com.seaofnodes.simple; + +import com.seaofnodes.simple.codegen.CodeGen; +import com.seaofnodes.simple.node.*; +import com.seaofnodes.simple.type.*; +import com.seaofnodes.simple.util.Ary; +import com.seaofnodes.simple.codegen.RegAllocTestSupport.CheckedCodeGen; +import java.nio.file.Files; +import java.nio.file.Path; +import org.junit.Test; +import static org.junit.Assert.*; + +public class IntrinsicTest { + private static final String DECL=""" + { f64 -> i64 } simple_f64_bits="C"; + { i64 -> f64 } simple_f64_from_bits="C"; + """; + + @Test public void constantsAndRawNaNs() { + long[] patterns={0,Long.MIN_VALUE,1,0x0010000000000000L,0x3ff0000000000000L, + 0x7fefffffffffffffL,0x7ff0000000000000L,0xfff0000000000000L, + 0x7ff8000000000001L,0x7ff8000000000002L,0xfff800000000002aL,0x7ff0000000000001L}; + for(long bits:patterns) { + String literal=bits==Long.MIN_VALUE ? "(-9223372036854775807-1)" : Long.toString(bits); + CodeGen code=new CodeGen(DECL+"return simple_f64_bits(simple_f64_from_bits("+literal+"));") + .driver(CodeGen.Phase.TypeCheck); + assertNull(code._stop.walk(n -> n instanceof CallNode ? n : null)); + assertEquals(Long.toString(bits),Eval2.eval(code,0)); + } + assertNotSame(TypeFloat.constant(Double.longBitsToDouble(patterns[8])), + TypeFloat.constant(Double.longBitsToDouble(patterns[9]))); + } + + @Test public void runtimeNodesAndMemory() { + CodeGen code=new CodeGen(DECL+""" + val bits=simple_f64_bits; + val a=new f64[1]; + a[0]=simple_f64_from_bits(arg); + if( arg==0 ) a[0]=-0.0; + return bits(a[0]); + """).driver(CodeGen.Phase.TypeCheck); + assertNotNull(code._stop.walk(n -> n instanceof Intrinsic.BitCastNode ? n : null)); + assertNull(code._stop.walk(n -> n instanceof CallNode ? n : null)); + assertEquals(Long.toString(Long.MIN_VALUE),Eval2.eval(code,0)); + assertEquals("9221120237041090602",Eval2.eval(code,0x7ff800000000002aL)); + } + + @Test public void ordinaryFunctionWithSameName() { + CodeGen code=new CodeGen(""" + val simple_f64_bits={ f64 x -> 42; }; + return simple_f64_bits(1.0); + """); + assertEquals("42",Eval2.eval(code,0)); + } + + @Test public void wrongSignature() { + try { + new CodeGen("{ i64 -> i64 } simple_f64_bits=\"C\"; return simple_f64_bits(arg);") + .driver(CodeGen.Phase.TypeCheck); + fail("The reserved C symbol has fixed semantics and a fixed signature"); + } catch(RuntimeException e) { + assertTrue(e.getMessage(),e.getMessage().contains("Intrinsic 'simple_f64_bits' requires")); + } + } + + @Test public void nativeRepresentations() throws Exception { + TestC.runSYS(""" + val bits_noInline={ f64 x -> sys.math.f64Bits(x); }; + val float_noInline={ i64 x -> sys.math.f64FromBits(x); }; + val main={ -> + val patterns=new i64[~]{0,sys.integer.MIN_I64,1,0x0010000000000000, + 0x3ff0000000000000,0x7fefffffffffffff,0x7ff0000000000000, + 0x7ff8000000000001,0x7ff8000000000002,-2251799813685206,0x7ff0000000000001}; + for( int i=0; i<patterns#; i++ ) + if( bits_noInline(float_noInline(patterns[i]))!=patterns[i] ) return 1; + if( bits_noInline(-0.0)!=sys.integer.MIN_I64 ) return 2; + if( float_noInline(0x4008000000000000)!=3.0 ) return 3; + int numeric=3.75; + if( numeric!=3 ) return 4; + return 0; + }; + ""","intrinsicNative","",-1); + } + + @Test public void indirectCallsUseCFallback() throws Exception { + String source=DECL+""" + { f64 -> i64 } llround="C"; + val apply_noInline={ { f64 -> i64 } f, f64 x -> f(x); }; + val main={ -> + if( apply_noInline(simple_f64_bits,-0.0)!=(-9223372036854775807-1) ) return 1; + if( apply_noInline(llround,3.75)!=4 ) return 2; + if( apply_noInline(simple_f64_bits,1.0)!=0x3ff0000000000000 ) return 3; + if( apply_noInline(simple_f64_bits,simple_f64_from_bits(0x7ff800000000002a))!=0x7ff800000000002a ) return 4; + return 0; + }; + """; + CodeGen code=new CodeGen(source).driver(CodeGen.Phase.TypeCheck); + assertNotNull("The indirect C call must survive",code._stop.walk(n -> + n instanceof CallNode c && c.external() && !c.tfp().isConstant() ? n : null)); + TestC.runSYS(source,"intrinsicFallback","",-1); + } + + @Test public void importedNodesAndNaNConstants() throws Exception { + Path dir=Files.createTempDirectory(Path.of("build/objs"),"intrinsic-import-"); + String library=DECL+""" + val bits_noInline={ f64 x -> simple_f64_bits(x); }; + val float_noInline={ i64 x -> simple_f64_from_bits(x); }; + val nan=simple_f64_from_bits(0x7ff8000000000001); + val otherNaN=simple_f64_from_bits(0x7ff8000000000002); + """; + new CodeGen(null,dir.toString(),null,"Bits",library,126,true,TypeInteger.BOT) + .driver(TestC.CPU_PORT,TestC.CALL_CONVENTION,false,false); + var paths=new Ary<>(new String[]{dir.toString()}); + String[] clients={ + "return Bits.bits_noInline(Bits.float_noInline(arg));", + "return Bits.bits_noInline(Bits.nan);", + "return Bits.bits_noInline(Bits.otherNaN);" + }; + long[] expected={0x7ff800000000002aL,0x7ff8000000000001L,0x7ff8000000000002L}; + for(int i=0;i<clients.length;i++) { + CodeGen client=new CodeGen(null,dir.toString(),paths,"Client",clients[i],126,true,TypeInteger.BOT); + assertEquals(Long.toString(expected[i]),Eval2.eval(client,expected[0])); + } + } + + @Test public void allBackendsSelectRepresentationMoves() { + // The array store/load and branch keep both directions alive, rather + // than allowing the inverse-cast peephole to erase the whole test. + String source=DECL+""" + val a=new f64[1]; + a[0]=simple_f64_from_bits(arg); + if( arg==0 ) a[0]=-0.0; + return simple_f64_bits(a[0]); + """; + for(String cpu:new String[]{"x86_64_v2","arm","riscv"}) { + CodeGen code=new CheckedCodeGen(source).driver(CodeGen.Phase.Encoding,cpu,"SystemV"); + assertNotNull(code._stop.walk(n -> n instanceof MachConcreteNode m && m.op().equals("f64bits") ? n : null)); + assertNotNull(code._stop.walk(n -> n instanceof MachConcreteNode m && m.op().equals("f64frombits") ? n : null)); + } + } + + @Test public void invalidArgumentIsNotInlinedAway() { + try { + new CodeGen(DECL+"return simple_f64_bits(1);").driver(CodeGen.Phase.TypeCheck); + fail("Intrinsic inlining must not hide the call's type error"); + } catch(RuntimeException e) { + assertTrue(e.getMessage(),e.getMessage().contains("Argument #1 isa")); + } + } + + @Test public void discardedValueKeepsArgumentEffects() throws Exception { + TestC.runSYS(DECL+""" + val next={ i64[] a -> a[0]++; return 1.0; }; + val main={ -> + val a=new i64[1]; + simple_f64_bits(next(a)); + return a[0]!=1; + }; + ""","intrinsicEffects","",-1); + } + + @Test public void emulatedRepresentationMoves() throws Exception { + long[] patterns={0,Long.MIN_VALUE,1,0x3ff0000000000000L,0x7ff0000000000000L, + 0xfff0000000000000L,0x7ff800000000002aL,0x7ff0000000000001L}; + for(boolean toBits:new boolean[]{true,false}) { + String source=toBits + ? "val cast={ f64 x -> { f64 -> i64 } simple_f64_bits=\"C\"; return simple_f64_bits(x); };" + : "val cast={ i64 x -> { i64 -> f64 } simple_f64_from_bits=\"C\"; return simple_f64_from_bits(x); };"; + var arm=TestArm64.build("cast",source,0,-1,false); + var risc=TestRisc5.build(source,"cast",0,-1,false); + int armStart=arm._pc, riscStart=risc._pc; + for(long bits:patterns) { + arm._pc=armStart; risc._pc=riscStart; + if(toBits) { + arm.fregs[0]=Double.longBitsToDouble(bits); + risc.fregs[10]=Double.longBitsToDouble(bits); + } else { + arm.regs[0]=bits; + risc.regs[10]=bits; + } + assertEquals(0,arm.step(1000)); + assertEquals(0,risc.step(1000)); + assertEquals(bits,toBits ? arm.regs[0] : Double.doubleToRawLongBits(arm.fregs[0])); + assertEquals(bits,toBits ? risc.regs[10] : Double.doubleToRawLongBits(risc.fregs[10])); + } + } + } +} diff --git a/chapter31/src/test/java/com/seaofnodes/simple/TypeTest.java b/chapter31/src/test/java/com/seaofnodes/simple/TypeTest.java index 16b75fdc..52e857e9 100644 --- a/chapter31/src/test/java/com/seaofnodes/simple/TypeTest.java +++ b/chapter31/src/test/java/com/seaofnodes/simple/TypeTest.java @@ -7,6 +7,26 @@ import static org.junit.Assert.assertSame; public class TypeTest { + @Test public void testConstantArrayElements() { + TypeConAry range=TypeConAry.make(TypeInteger.U16,new long[]{5,6,7}); + Assert.assertEquals("[5-7]",range.toString()); + Assert.assertEquals("[5-7]",TypeConAry.make(TypeInteger.U8,new long[]{5,6,7}).toString()); + Assert.assertEquals("[\"abc\"]",TypeConAry.make("abc").toString()); + for( TypeInteger storage : new TypeInteger[]{TypeInteger.BOOL,TypeInteger.I8,TypeInteger.U8, + TypeInteger.I16,TypeInteger.U16,TypeInteger.I32,TypeInteger.U32,TypeInteger.BOT} ) { + TypeConAry empty=TypeConAry.make(storage,new long[0]); + assertSame(storage.dual(),empty.elem()); + assertSame(storage,((TypeConAry)empty.dual()).elem()); + for( long[] values : new long[][]{{0},{1},{0,1},{storage._min,storage._max}} ) { + TypeConAry array=TypeConAry.make(storage,values); + Assert.assertTrue(empty.isa(array)); + assertSame(array,empty.meet(array)); + assertSame(empty,array.join(empty)); + check_symmetric(empty,array); + } + } + } + @Test public void testOpaqueExternalEscapes() { TypeMem defaults = TypeMem.START.makeFrom(XInt.make(2),XInt.make(3)); TypeMem prior = TypeMem.START.makeFrom(XInt.make(5),XInt.make(7)); diff --git a/chapter31/src/test/java/com/seaofnodes/simple/codegen/PrintRegTestSupport.java b/chapter31/src/test/java/com/seaofnodes/simple/codegen/PrintRegTestSupport.java index b0f0f225..190cf17c 100644 --- a/chapter31/src/test/java/com/seaofnodes/simple/codegen/PrintRegTestSupport.java +++ b/chapter31/src/test/java/com/seaofnodes/simple/codegen/PrintRegTestSupport.java @@ -3,6 +3,30 @@ import com.seaofnodes.simple.node.*; import com.seaofnodes.simple.type.TypeInteger; import static org.junit.Assert.*; public class PrintRegTestSupport { + public static void checkDataAliases(java.nio.file.Path file, int size, String... names) { + ElfReader elf=ElfReader.load(file.toFile(),null); + assertNotNull(elf); + ElfReader.Section symbols=java.util.Arrays.stream(elf._sections) + .filter(s -> ".symtab".equals(s._name)).findFirst().orElseThrow(); + ElfReader.Section strings=elf._sections[symbols._link]; + var bytes=java.nio.ByteBuffer.wrap(elf._buf).order(java.nio.ByteOrder.LITTLE_ENDIAN); + var wanted=new java.util.HashSet<>(java.util.Arrays.asList(names)); + Long address=null; + for( int i=0; i<symbols._size/symbols._esize; i++ ) { + int off=(int)symbols._offset+i*symbols._esize; + String name=strings.str(bytes.getInt(off)); + if( !wanted.remove(name) ) continue; + assertTrue("Debug aliases precede global symbols",i<symbols._info); + assertEquals("Local object symbol",1,bytes.get(off+4)&255); + assertEquals(".rodata",elf._sections[bytes.getShort(off+6)&65535]._name); + assertEquals(size,bytes.getLong(off+16)); + long value=bytes.getLong(off+8); + if( address!=null ) assertEquals("Aliases share storage",address.longValue(),value); + address=value; + } + assertTrue("Missing debug symbols: "+wanted,wanted.isEmpty()); + } + public static void check() throws Exception { var code = new CodeGen("return 0;").parse(); var alloc = new RegAlloc(code); diff --git a/docs/roadmap.md b/docs/roadmap.md index 98f319db..f1922a4a 100644 --- a/docs/roadmap.md +++ b/docs/roadmap.md @@ -366,21 +366,6 @@ as design references. Decide ownership, borrowing, sharing, cycles, and native retention together with the existing object and array model. This is a language design candidate, independent of compact pointer storage. -### A small graphical game - -Chapter 31 follows ASCII tic-tac-toe with a graphical version, using -[software drawing in Simple](../chapter31/docs/drawing.md) and an optional -MiniFB window/input backend. The initial library supplies colors, rectangles, -circles, thick lines, and bitmap labels. Mouse/keyboard turns and replay -exercise that boundary without requiring an animated game engine. - -Optional [background audio](../chapter31/docs/audio.md) uses miniaudio for -soft move sounds and ascending/descending win/loss cues. Further games remain -future work; MiniFB supplies only the window and input boundary. - -Chapter 31 also implements [time and single-threaded animation](../chapter31/docs/time.md), -including cooperative timers and responsive input waits. - ### Structs with trailing arrays Allow named fields followed by an array length and inline element storage: diff --git a/isa/src/test-support/java/com/seaofnodes/isa/eval/EvalArm64.java b/isa/src/test-support/java/com/seaofnodes/isa/eval/EvalArm64.java index d4a54719..98658bb3 100644 --- a/isa/src/test-support/java/com/seaofnodes/isa/eval/EvalArm64.java +++ b/isa/src/test-support/java/com/seaofnodes/isa/eval/EvalArm64.java @@ -418,6 +418,11 @@ public class EvalArm64 { int rs1 = (ir >> 5) & 0x1F; if( (ir & 0xFFFFFC00)==0x9E780000 ) { // FCVTZS Xd,Dn rval = (long)fregs[rs1]; + } else if( (ir & 0xFFFFFC00)==0x9E660000 ) { // FMOV Xd,Dn + rval = Double.doubleToRawLongBits(fregs[rs1]); + } else if( (ir & 0xFFFFFC00)==0x9E670000 ) { // FMOV Dd,Xn + is_f = true; + frval = Double.longBitsToDouble(regs[rs1]); } else { // SCVTF is_f = true; frval = (double)regs[rs1]; diff --git a/isa/src/test-support/java/com/seaofnodes/isa/eval/EvalRisc5.java b/isa/src/test-support/java/com/seaofnodes/isa/eval/EvalRisc5.java index 6c3659ef..cca08226 100644 --- a/isa/src/test-support/java/com/seaofnodes/isa/eval/EvalRisc5.java +++ b/isa/src/test-support/java/com/seaofnodes/isa/eval/EvalRisc5.java @@ -335,7 +335,19 @@ public class EvalRisc5 { case 1: frval = lhs - rhs; break; // fsub.d case 2: frval = lhs * rhs; break; // fmul.d case 3: frval = lhs / rhs; break; // fdiv.d - case 5: frval = Math.min(lhs,rhs); break; // fmin.d, also used for move + case 4: { // FSGNJ.D / FSGNJN.D / FSGNJX.D (FMV.D uses FSGNJ.D) + long left = Double.doubleToRawLongBits(lhs); + long right = Double.doubleToRawLongBits(rhs); + long sign = switch((ir >> 12)&7) { + case 0 -> right; + case 1 -> ~right; + case 2 -> left ^ right; + default -> throw new UnsupportedOperationException(); + }; + frval = Double.longBitsToDouble((left & Long.MAX_VALUE) | (sign & Long.MIN_VALUE)); + break; + } + case 5: frval = Math.min(lhs,rhs); break; // FMIN.D case 20: is_f = false; // Output into a GPR rval = switch( (ir >> 12) & 7 ) { @@ -351,10 +363,15 @@ public class EvalRisc5 { rval = Double.isNaN(lhs) ? Long.MAX_VALUE : (long)lhs; break; case 26: frval = (double)regs[rs1]; break; // fcvt.d.l - case 28: { // FCLASS.D - if( rs2!=0 || ((ir>>12)&7)!=1 ) throw new UnsupportedOperationException(); + case 28: { // FMV.X.D / FCLASS.D + if( rs2!=0 ) throw new UnsupportedOperationException(); is_f = false; long bits = Double.doubleToRawLongBits(lhs); + if( ((ir>>12)&7)==0 ) { + rval = bits; + break; + } + if( ((ir>>12)&7)!=1 ) throw new UnsupportedOperationException(); boolean neg = bits<0; int kind = Double.isNaN(lhs) ? ((bits&(1L<<51))==0 ? 8 : 9) : Double.isInfinite(lhs) ? (neg ? 0 : 7) @@ -364,6 +381,10 @@ public class EvalRisc5 { rval = 1L<<kind; break; } + case 30: // FMV.D.X + if( rs2!=0 || ((ir>>12)&7)!=0 ) throw new UnsupportedOperationException(); + frval = Double.longBitsToDouble(regs[rs1]); + break; default: trap = (2+1); // Fault: Invalid opcode. throw new UnsupportedOperationException(); |
