1350 files changed
+197
-941995
No files matched your search
@@ -8,7 +8,7 @@ import path from 'node:path';
|
||||
import { fileURLToPath } from 'node:url';
|
||||
import { studyOf, runPseudo } from '../dist/services/pseudo.js';
|
||||
|
||||
const dir = path.join(path.dirname(fileURLToPath(import.meta.url)), 'corpus');
|
||||
const dir = path.join(path.dirname(fileURLToPath(import.meta.url)), '..', 'library', 'pseudo', 'programs');
|
||||
const files = fs.readdirSync(dir).filter((f) => f.endsWith('.pseudo')).sort();
|
||||
|
||||
for (const f of files) {
|
||||
|
||||
@@ -1,26 +0,0 @@
|
||||
// Numbers: every arithmetic operator, both numeric types, and the conversions between them.
|
||||
// EXPECT: 3.5
|
||||
// EXPECT: 3
|
||||
// EXPECT: 1
|
||||
// EXPECT: -4
|
||||
// EXPECT: 512
|
||||
// EXPECT: 2.0
|
||||
// EXPECT: 27
|
||||
// EXPECT: 28
|
||||
// EXPECT: 5
|
||||
// EXPECT: 7 -7 -7
|
||||
DECLARE A, B : INTEGER
|
||||
DECLARE X : FLOAT
|
||||
A <- 7
|
||||
B <- 2
|
||||
OUTPUT A / B
|
||||
OUTPUT A DIV B
|
||||
OUTPUT A MOD B
|
||||
OUTPUT -2 ^ 2
|
||||
OUTPUT 2 ^ 3 ^ 2
|
||||
OUTPUT 4 / 2
|
||||
X <- 27.54
|
||||
OUTPUT INT(X)
|
||||
OUTPUT ROUND(X)
|
||||
OUTPUT ABS(-5)
|
||||
OUTPUT 7 DIV 1, " ", -7 DIV 1, " ", (-7) DIV 1
|
||||
@@ -1,11 +0,0 @@
|
||||
// A FLOAT formula with a FUNCTION; classic first program in any language.
|
||||
// EXPECT: 212.0
|
||||
// EXPECT: 37.0
|
||||
FUNCTION TO_FAHRENHEIT(C : FLOAT) RETURNS FLOAT
|
||||
RETURN C * 9 / 5 + 32
|
||||
ENDFUNCTION
|
||||
FUNCTION TO_CELSIUS(F : FLOAT) RETURNS FLOAT
|
||||
RETURN (F - 32) * 5 / 9
|
||||
ENDFUNCTION
|
||||
OUTPUT TO_FAHRENHEIT(100.0)
|
||||
OUTPUT TO_CELSIUS(98.6)
|
||||
@@ -1,11 +0,0 @@
|
||||
// Finance flavor: a loop that updates a FLOAT, with ROUND for reporting.
|
||||
// EXPECT: 1628.89
|
||||
FUNCTION BALANCE_AFTER(Principal : FLOAT, Rate : FLOAT, Years : INTEGER) RETURNS FLOAT
|
||||
DECLARE B : FLOAT
|
||||
B <- Principal
|
||||
FOR Y <- 0 TO Years
|
||||
B <- B * (1 + Rate)
|
||||
NEXT Y
|
||||
RETURN B
|
||||
ENDFUNCTION
|
||||
OUTPUT ROUND(BALANCE_AFTER(1000.0, 0.05, 10) * 100) / 100
|
||||
@@ -1,13 +0,0 @@
|
||||
// Recursion with a DECREASES measure and a REQUIRE.
|
||||
// EXPECT: 6
|
||||
// EXPECT: 1
|
||||
FUNCTION GCD(A : INTEGER, B : INTEGER) RETURNS INTEGER
|
||||
REQUIRE A >= 0 AND B >= 0
|
||||
DECREASES B
|
||||
IF B == 0 THEN
|
||||
RETURN A
|
||||
ENDIF
|
||||
RETURN GCD(B, A MOD B)
|
||||
ENDFUNCTION
|
||||
OUTPUT GCD(48, 18)
|
||||
OUTPUT GCD(17, 5)
|
||||
@@ -1,19 +0,0 @@
|
||||
// An ARRAY of BOOL, nested loops with STEP, and a LIST answer.
|
||||
// EXPECT: [2, 3, 5, 7, 11, 13, 17, 19, 23, 29]
|
||||
FUNCTION PRIMES_UP_TO(N : INTEGER) RETURNS LIST OF INTEGER
|
||||
DECLARE IsPrime : ARRAY[N + 1] OF BOOL
|
||||
DECLARE Found : LIST OF INTEGER
|
||||
FOR I <- 0 TO N + 1
|
||||
IsPrime[I] <- I >= 2
|
||||
NEXT I
|
||||
FOR I <- 2 TO N + 1
|
||||
IF IsPrime[I] THEN
|
||||
APPEND(Found, I)
|
||||
FOR J <- I * I TO N + 1 STEP I
|
||||
IsPrime[J] <- FALSE
|
||||
NEXT J
|
||||
ENDIF
|
||||
NEXT I
|
||||
RETURN Found
|
||||
ENDFUNCTION
|
||||
OUTPUT PRIMES_UP_TO(30)
|
||||
@@ -1,25 +0,0 @@
|
||||
// Memoised recursion. A FUNCTION cannot take BYREF, so the memo table has to travel through a PROCEDURE
|
||||
// with the answer coming back BYREF too. Finding: this is the idiom; it reads heavier than in most languages.
|
||||
// EXPECT: 6765
|
||||
// EXPECT: 12586269025
|
||||
PROCEDURE FIB(N : INTEGER, BYREF Memo : HASHMAP OF INTEGER : INTEGER, BYREF Result : INTEGER)
|
||||
IF N < 2 THEN
|
||||
Result <- N
|
||||
RETURN
|
||||
ENDIF
|
||||
IF N IN Memo THEN
|
||||
Result <- Memo[N]
|
||||
RETURN
|
||||
ENDIF
|
||||
DECLARE A, B : INTEGER
|
||||
CALL FIB(N - 1, Memo, A)
|
||||
CALL FIB(N - 2, Memo, B)
|
||||
Memo[N] <- A + B
|
||||
Result <- A + B
|
||||
ENDPROCEDURE
|
||||
DECLARE M : HASHMAP OF INTEGER : INTEGER
|
||||
DECLARE R : INTEGER
|
||||
CALL FIB(20, M, R)
|
||||
OUTPUT R
|
||||
CALL FIB(50, M, R)
|
||||
OUTPUT R
|
||||
@@ -1,34 +0,0 @@
|
||||
// Text flavor: splitting a sentence into words by hand, since the notation has no SPLIT, then tallying.
|
||||
// EXPECT: {"a": 2, "is": 2, "rose": 3}
|
||||
// A HASHMAP prints its keys smallest first, whatever order they were added in.
|
||||
FUNCTION WORDS(S : STRING) RETURNS LIST OF STRING
|
||||
DECLARE Out : LIST OF STRING
|
||||
DECLARE W : STRING
|
||||
W <- ""
|
||||
FOR EACH C IN S
|
||||
IF C == ' ' THEN
|
||||
IF LENGTH(W) > 0 THEN
|
||||
APPEND(Out, W)
|
||||
ENDIF
|
||||
W <- ""
|
||||
ELSE
|
||||
W <- W & C
|
||||
ENDIF
|
||||
NEXT C
|
||||
IF LENGTH(W) > 0 THEN
|
||||
APPEND(Out, W)
|
||||
ENDIF
|
||||
RETURN Out
|
||||
ENDFUNCTION
|
||||
FUNCTION TALLY(Ws : LIST OF STRING) RETURNS HASHMAP OF STRING : INTEGER
|
||||
DECLARE T : HASHMAP OF STRING : INTEGER
|
||||
FOR EACH W IN Ws
|
||||
IF W IN T THEN
|
||||
T[W] <- T[W] + 1
|
||||
ELSE
|
||||
T[W] <- 1
|
||||
ENDIF
|
||||
NEXT W
|
||||
RETURN T
|
||||
ENDFUNCTION
|
||||
OUTPUT TALLY(WORDS("a rose is a rose is rose"))
|
||||
@@ -1,17 +0,0 @@
|
||||
// Cryptography flavor: CHAR arithmetic with ORD and CHR, MOD to wrap.
|
||||
// EXPECT: KHOOR, ZRUOG!
|
||||
// EXPECT: HELLO, WORLD!
|
||||
FUNCTION SHIFT(S : STRING, K : INTEGER) RETURNS STRING
|
||||
DECLARE Out : STRING
|
||||
Out <- ""
|
||||
FOR EACH C IN S
|
||||
IF C >= 'A' AND C <= 'Z' THEN
|
||||
Out <- Out & CHR((ORD(C) - ORD('A') + K) MOD 26 + ORD('A'))
|
||||
ELSE
|
||||
Out <- Out & C
|
||||
ENDIF
|
||||
NEXT C
|
||||
RETURN Out
|
||||
ENDFUNCTION
|
||||
OUTPUT SHIFT("HELLO, WORLD!", 3)
|
||||
OUTPUT SHIFT(SHIFT("HELLO, WORLD!", 3), 23)
|
||||
@@ -1,17 +0,0 @@
|
||||
// Two positions moving toward each other; a WHILE with a compound guard.
|
||||
// EXPECT: TRUE
|
||||
// EXPECT: FALSE
|
||||
// EXPECT: TRUE
|
||||
FUNCTION IS_PALINDROME(S : STRING) RETURNS BOOL
|
||||
DECLARE Lo, Hi : INTEGER
|
||||
Lo <- 0
|
||||
Hi <- LENGTH(S) - 1
|
||||
WHILE Lo < Hi AND S[Lo] == S[Hi]
|
||||
Lo <- Lo + 1
|
||||
Hi <- Hi - 1
|
||||
ENDWHILE
|
||||
RETURN Lo >= Hi
|
||||
ENDFUNCTION
|
||||
OUTPUT IS_PALINDROME("racecar")
|
||||
OUTPUT IS_PALINDROME("rose")
|
||||
OUTPUT IS_PALINDROME("")
|
||||
@@ -1,19 +0,0 @@
|
||||
// An in-place sort with a PROCEDURE and BYREF, plus a loop invariant.
|
||||
// EXPECT: [1, 2, 3, 5, 8, 9]
|
||||
PROCEDURE INSERTION_SORT(BYREF L : LIST OF INTEGER)
|
||||
FOR I <- 1 TO LENGTH(L)
|
||||
INVARIANT FORALL K IN [1, I) : L[K - 1] <= L[K]
|
||||
DECLARE Key, J : INTEGER
|
||||
Key <- L[I]
|
||||
J <- I - 1
|
||||
WHILE J >= 0 AND L[J] > Key
|
||||
L[J + 1] <- L[J]
|
||||
J <- J - 1
|
||||
ENDWHILE
|
||||
L[J + 1] <- Key
|
||||
NEXT I
|
||||
ENDPROCEDURE
|
||||
DECLARE Xs : LIST OF INTEGER
|
||||
Xs <- [5, 2, 9, 1, 8, 3]
|
||||
CALL INSERTION_SORT(Xs)
|
||||
OUTPUT Xs
|
||||
@@ -1,27 +0,0 @@
|
||||
// Two-dimensional ARRAYs, triple nested loops, ROWS and COLUMNS.
|
||||
// EXPECT: 19 22
|
||||
// EXPECT: 43 50
|
||||
FUNCTION MATMUL(A : ARRAY[2, 2] OF INTEGER, B : ARRAY[2, 2] OF INTEGER) RETURNS ARRAY[2, 2] OF INTEGER
|
||||
DECLARE C : ARRAY[ROWS(A), COLUMNS(B)] OF INTEGER
|
||||
FOR I <- 0 TO ROWS(A)
|
||||
FOR J <- 0 TO COLUMNS(B)
|
||||
C[I, J] <- 0
|
||||
FOR K <- 0 TO COLUMNS(A)
|
||||
C[I, J] <- C[I, J] + A[I, K] * B[K, J]
|
||||
NEXT K
|
||||
NEXT J
|
||||
NEXT I
|
||||
RETURN C
|
||||
ENDFUNCTION
|
||||
DECLARE A, B, C : ARRAY[2, 2] OF INTEGER
|
||||
A[0, 0] <- 1
|
||||
A[0, 1] <- 2
|
||||
A[1, 0] <- 3
|
||||
A[1, 1] <- 4
|
||||
B[0, 0] <- 5
|
||||
B[0, 1] <- 6
|
||||
B[1, 0] <- 7
|
||||
B[1, 1] <- 8
|
||||
C <- MATMUL(A, B)
|
||||
OUTPUT C[0, 0], " ", C[0, 1]
|
||||
OUTPUT C[1, 0], " ", C[1, 1]
|
||||
@@ -1,37 +0,0 @@
|
||||
// Records in a LIST, a FUNCTION over them, and "find the best".
|
||||
// EXPECT: Bob
|
||||
// EXPECT: 86.5
|
||||
TYPE Student
|
||||
DECLARE Name : STRING
|
||||
DECLARE Marks : LIST OF INTEGER
|
||||
ENDTYPE
|
||||
FUNCTION MEAN(Xs : LIST OF INTEGER) RETURNS FLOAT
|
||||
REQUIRE LENGTH(Xs) >= 1
|
||||
DECLARE Total : INTEGER
|
||||
Total <- 0
|
||||
FOR EACH X IN Xs
|
||||
Total <- Total + X
|
||||
NEXT X
|
||||
RETURN Total / LENGTH(Xs)
|
||||
ENDFUNCTION
|
||||
FUNCTION TOP(Ss : LIST OF Student) RETURNS Student
|
||||
REQUIRE LENGTH(Ss) >= 1
|
||||
DECLARE Best : Student
|
||||
Best <- Ss[0]
|
||||
FOR EACH S IN Ss
|
||||
IF MEAN(S.Marks) > MEAN(Best.Marks) THEN
|
||||
Best <- S
|
||||
ENDIF
|
||||
NEXT S
|
||||
RETURN Best
|
||||
ENDFUNCTION
|
||||
DECLARE A, B : Student
|
||||
DECLARE Class : LIST OF Student
|
||||
A.Name <- "Ann"
|
||||
A.Marks <- [70, 80, 90]
|
||||
B.Name <- "Bob"
|
||||
B.Marks <- [88, 85]
|
||||
APPEND(Class, A)
|
||||
APPEND(Class, B)
|
||||
OUTPUT TOP(Class).Name
|
||||
OUTPUT MEAN(TOP(Class).Marks)
|
||||
@@ -1,25 +0,0 @@
|
||||
// A LIST used as a stack: APPEND to push, REMOVE the last to pop. Balanced brackets.
|
||||
// EXPECT: TRUE
|
||||
// EXPECT: FALSE
|
||||
// EXPECT: FALSE
|
||||
FUNCTION BALANCED(S : STRING) RETURNS BOOL
|
||||
DECLARE Stack : LIST OF CHAR
|
||||
DECLARE Pairs : HASHMAP OF CHAR : CHAR
|
||||
Pairs[')'] <- '('
|
||||
Pairs[']'] <- '['
|
||||
Pairs['}'] <- '{'
|
||||
FOR EACH C IN S
|
||||
IF C == '(' OR C == '[' OR C == '{' THEN
|
||||
APPEND(Stack, C)
|
||||
ELSEIF C IN Pairs THEN
|
||||
IF LENGTH(Stack) == 0 OR Stack[LENGTH(Stack) - 1] != Pairs[C] THEN
|
||||
RETURN FALSE
|
||||
ENDIF
|
||||
REMOVE(Stack, LENGTH(Stack) - 1)
|
||||
ENDIF
|
||||
NEXT C
|
||||
RETURN LENGTH(Stack) == 0
|
||||
ENDFUNCTION
|
||||
OUTPUT BALANCED("{[()()]}")
|
||||
OUTPUT BALANCED("([)]")
|
||||
OUTPUT BALANCED("((")
|
||||
@@ -1,30 +0,0 @@
|
||||
// Graph flavor: breadth-first search with a LIST as a queue (REMOVE at 0) and a SET of seen nodes.
|
||||
// Finding: a neighbour cannot be called Next, because names ignore case and NEXT is a keyword.
|
||||
// EXPECT: [0, 1, 2, 3, 4]
|
||||
FUNCTION BFS(Adj : HASHMAP OF INTEGER : LIST OF INTEGER, Start : INTEGER) RETURNS LIST OF INTEGER
|
||||
DECLARE Queue, Order : LIST OF INTEGER
|
||||
DECLARE Seen : SET OF INTEGER
|
||||
APPEND(Queue, Start)
|
||||
ADD(Seen, Start)
|
||||
WHILE LENGTH(Queue) > 0
|
||||
DECLARE Node : INTEGER
|
||||
Node <- Queue[0]
|
||||
REMOVE(Queue, 0)
|
||||
APPEND(Order, Node)
|
||||
IF Node IN Adj THEN
|
||||
FOR EACH Nb IN Adj[Node]
|
||||
IF NOT (Nb IN Seen) THEN
|
||||
ADD(Seen, Nb)
|
||||
APPEND(Queue, Nb)
|
||||
ENDIF
|
||||
NEXT Nb
|
||||
ENDIF
|
||||
ENDWHILE
|
||||
RETURN Order
|
||||
ENDFUNCTION
|
||||
DECLARE G : HASHMAP OF INTEGER : LIST OF INTEGER
|
||||
G[0] <- [1, 2]
|
||||
G[1] <- [3]
|
||||
G[2] <- [3, 4]
|
||||
G[3] <- [4]
|
||||
OUTPUT BFS(G, 0)
|
||||
@@ -1,49 +0,0 @@
|
||||
// Simulation flavor: one step of Conway's Life on a small two-dimensional ARRAY; a blinker turns.
|
||||
// Finding: the function cannot be called STEP, nor the new grid Next: both are keywords, whatever their case.
|
||||
// EXPECT: 0 1 0
|
||||
// EXPECT: 0 1 0
|
||||
// EXPECT: 0 1 0
|
||||
FUNCTION NEIGHBOURS(G : ARRAY[3, 3] OF INTEGER, R : INTEGER, C : INTEGER) RETURNS INTEGER
|
||||
DECLARE N : INTEGER
|
||||
N <- 0
|
||||
FOR DR <- -1 TO 2
|
||||
FOR DC <- -1 TO 2
|
||||
IF NOT (DR == 0 AND DC == 0) THEN
|
||||
IF R + DR >= 0 AND R + DR < ROWS(G) AND C + DC >= 0 AND C + DC < COLUMNS(G) THEN
|
||||
N <- N + G[R + DR, C + DC]
|
||||
ENDIF
|
||||
ENDIF
|
||||
NEXT DC
|
||||
NEXT DR
|
||||
RETURN N
|
||||
ENDFUNCTION
|
||||
FUNCTION LIFE_STEP(G : ARRAY[3, 3] OF INTEGER) RETURNS ARRAY[3, 3] OF INTEGER
|
||||
DECLARE After : ARRAY[3, 3] OF INTEGER
|
||||
FOR R <- 0 TO 3
|
||||
FOR C <- 0 TO 3
|
||||
DECLARE N : INTEGER
|
||||
N <- NEIGHBOURS(G, R, C)
|
||||
IF G[R, C] == 1 AND (N == 2 OR N == 3) THEN
|
||||
After[R, C] <- 1
|
||||
ELSEIF G[R, C] == 0 AND N == 3 THEN
|
||||
After[R, C] <- 1
|
||||
ELSE
|
||||
After[R, C] <- 0
|
||||
ENDIF
|
||||
NEXT C
|
||||
NEXT R
|
||||
RETURN After
|
||||
ENDFUNCTION
|
||||
DECLARE G : ARRAY[3, 3] OF INTEGER
|
||||
FOR R <- 0 TO 3
|
||||
FOR C <- 0 TO 3
|
||||
G[R, C] <- 0
|
||||
NEXT C
|
||||
NEXT R
|
||||
G[1, 0] <- 1
|
||||
G[1, 1] <- 1
|
||||
G[1, 2] <- 1
|
||||
G <- LIFE_STEP(G)
|
||||
FOR R <- 0 TO 3
|
||||
OUTPUT G[R, 0], " ", G[R, 1], " ", G[R, 2]
|
||||
NEXT R
|
||||
@@ -1,29 +0,0 @@
|
||||
// Statistics flavor: mean and variance in one pass (Welford), returning two values through a record.
|
||||
// EXPECT: 5.0
|
||||
// EXPECT: 4.0
|
||||
TYPE Stats
|
||||
DECLARE Mean : FLOAT
|
||||
DECLARE Variance : FLOAT
|
||||
ENDTYPE
|
||||
FUNCTION RUNNING(Xs : LIST OF FLOAT) RETURNS Stats
|
||||
REQUIRE LENGTH(Xs) >= 2
|
||||
DECLARE N : INTEGER
|
||||
DECLARE Mean, M2, Delta : FLOAT
|
||||
DECLARE Out : Stats
|
||||
N <- 0
|
||||
Mean <- 0.0
|
||||
M2 <- 0.0
|
||||
FOR EACH X IN Xs
|
||||
N <- N + 1
|
||||
Delta <- X - Mean
|
||||
Mean <- Mean + Delta / N
|
||||
M2 <- M2 + Delta * (X - Mean)
|
||||
NEXT X
|
||||
Out.Mean <- Mean
|
||||
Out.Variance <- M2 / N
|
||||
RETURN Out
|
||||
ENDFUNCTION
|
||||
DECLARE S : Stats
|
||||
S <- RUNNING([2.0, 4.0, 4.0, 4.0, 5.0, 5.0, 7.0, 9.0])
|
||||
OUTPUT S.Mean
|
||||
OUTPUT S.Variance
|
||||
@@ -1,17 +0,0 @@
|
||||
// CASE with half-open ranges on a FLOAT, and OTHERWISE.
|
||||
// EXPECT: A
|
||||
// EXPECT: B
|
||||
// EXPECT: F
|
||||
FUNCTION GRADE(Score : FLOAT) RETURNS STRING
|
||||
DECLARE G : STRING
|
||||
CASE OF Score
|
||||
90 TO 101 : G <- "A"
|
||||
80 TO 90 : G <- "B"
|
||||
70 TO 80 : G <- "C"
|
||||
OTHERWISE : G <- "F"
|
||||
ENDCASE
|
||||
RETURN G
|
||||
ENDFUNCTION
|
||||
OUTPUT GRADE(95.5)
|
||||
OUTPUT GRADE(80.0)
|
||||
OUTPUT GRADE(12.0)
|
||||
@@ -1,10 +0,0 @@
|
||||
// REPEAT ... UNTIL with INPUT, validating until a legal value arrives.
|
||||
// INPUT: 55
|
||||
// INPUT: -3
|
||||
// INPUT: 20
|
||||
// EXPECT: 20
|
||||
DECLARE Threshold : INTEGER
|
||||
REPEAT
|
||||
INPUT Threshold
|
||||
UNTIL Threshold >= 0 AND Threshold <= 40
|
||||
OUTPUT Threshold
|
||||
@@ -1,16 +0,0 @@
|
||||
// Kadane: find the best, with an early return for the empty case.
|
||||
// EXPECT: 6
|
||||
// EXPECT: -1
|
||||
FUNCTION MAX_SUBARRAY(Xs : LIST OF INTEGER) RETURNS INTEGER
|
||||
REQUIRE LENGTH(Xs) >= 1
|
||||
DECLARE Best, Here : INTEGER
|
||||
Best <- Xs[0]
|
||||
Here <- Xs[0]
|
||||
FOR I <- 1 TO LENGTH(Xs)
|
||||
Here <- MAX(Xs[I], Here + Xs[I])
|
||||
Best <- MAX(Best, Here)
|
||||
NEXT I
|
||||
RETURN Best
|
||||
ENDFUNCTION
|
||||
OUTPUT MAX_SUBARRAY([-2, 1, -3, 4, -1, 2, 1, -5, 4])
|
||||
OUTPUT MAX_SUBARRAY([-1])
|
||||
@@ -1,18 +0,0 @@
|
||||
// A HASHMAP from value to position: the lookup pattern every interview asks for.
|
||||
// EXPECT: [0, 2]
|
||||
// EXPECT: []
|
||||
FUNCTION TWO_SUM(Xs : LIST OF INTEGER, Target : INTEGER) RETURNS LIST OF INTEGER
|
||||
DECLARE Seen : HASHMAP OF INTEGER : INTEGER
|
||||
DECLARE Answer : LIST OF INTEGER
|
||||
FOR I <- 0 TO LENGTH(Xs)
|
||||
IF Target - Xs[I] IN Seen THEN
|
||||
APPEND(Answer, Seen[Target - Xs[I]])
|
||||
APPEND(Answer, I)
|
||||
RETURN Answer
|
||||
ENDIF
|
||||
Seen[Xs[I]] <- I
|
||||
NEXT I
|
||||
RETURN Answer
|
||||
ENDFUNCTION
|
||||
OUTPUT TWO_SUM([3, 5, 7, 9], 10)
|
||||
OUTPUT TWO_SUM([1, 2], 10)
|
||||
@@ -1,17 +0,0 @@
|
||||
// SETs: fixed with DEFINE, growing with ADD, membership, LENGTH, SORTED.
|
||||
// EXPECT: TRUE
|
||||
// EXPECT: FALSE
|
||||
// EXPECT: 4
|
||||
// EXPECT: ["ACG", "CGT", "GTA", "TAC"]
|
||||
TYPE BaseSet = SET OF CHAR
|
||||
DEFINE Purines ('A', 'G') : BaseSet
|
||||
OUTPUT 'A' IN Purines
|
||||
OUTPUT 'C' IN Purines
|
||||
DECLARE Seen : SET OF STRING
|
||||
DECLARE T : STRING
|
||||
T <- "ACGTACG"
|
||||
FOR I <- 0 TO LENGTH(T) - 3 + 1
|
||||
ADD(Seen, SLICE(T, I, I + 3))
|
||||
NEXT I
|
||||
OUTPUT LENGTH(Seen)
|
||||
OUTPUT SORTED(Seen)
|
||||
@@ -1,25 +0,0 @@
|
||||
// Number bases: a STRING of digits read left to right, and the reverse with DIV and MOD.
|
||||
// EXPECT: 13
|
||||
// EXPECT: 1101
|
||||
FUNCTION FROM_BINARY(S : STRING) RETURNS INTEGER
|
||||
DECLARE V : INTEGER
|
||||
V <- 0
|
||||
FOR EACH C IN S
|
||||
V <- V * 2 + TO_INTEGER(C)
|
||||
NEXT C
|
||||
RETURN V
|
||||
ENDFUNCTION
|
||||
FUNCTION TO_BINARY(N : INTEGER) RETURNS STRING
|
||||
REQUIRE N >= 1
|
||||
DECLARE S : STRING
|
||||
DECLARE M : INTEGER
|
||||
S <- ""
|
||||
M <- N
|
||||
WHILE M > 0
|
||||
S <- TO_STRING(M MOD 2) & S
|
||||
M <- M DIV 2
|
||||
ENDWHILE
|
||||
RETURN S
|
||||
ENDFUNCTION
|
||||
OUTPUT FROM_BINARY("1101")
|
||||
OUTPUT TO_BINARY(13)
|
||||
@@ -1,17 +0,0 @@
|
||||
// Randomness: RANDINT in a loop and a tally; the lab seeds its random numbers so a run repeats.
|
||||
// EXPECT: 100
|
||||
DECLARE Tally : ARRAY[7] OF INTEGER
|
||||
DECLARE Total : INTEGER
|
||||
FOR F <- 0 TO 7
|
||||
Tally[F] <- 0
|
||||
NEXT F
|
||||
FOR Roll <- 0 TO 100
|
||||
DECLARE Face : INTEGER
|
||||
Face <- RANDINT(1, 7)
|
||||
Tally[Face] <- Tally[Face] + 1
|
||||
NEXT Roll
|
||||
Total <- 0
|
||||
FOR F <- 1 TO 7
|
||||
Total <- Total + Tally[F]
|
||||
NEXT F
|
||||
OUTPUT Total
|
||||
@@ -1,17 +0,0 @@
|
||||
// What the notation offers for text: SLICE, &, UPPER, LOWER, ORD, CHR, TO_STRING, TO_INTEGER.
|
||||
// EXPECT: ATT
|
||||
// EXPECT: GATTACA!
|
||||
// EXPECT: hello
|
||||
// EXPECT: DNA
|
||||
// EXPECT: 65
|
||||
// EXPECT: B
|
||||
// EXPECT: 42 apples
|
||||
// EXPECT: 43
|
||||
OUTPUT SLICE("GATTACA", 1, 4)
|
||||
OUTPUT "GATTACA" & "!"
|
||||
OUTPUT LOWER("HeLLo")
|
||||
OUTPUT UPPER("dna")
|
||||
OUTPUT ORD('A')
|
||||
OUTPUT CHR(66)
|
||||
OUTPUT TO_STRING(42) & " apples"
|
||||
OUTPUT TO_INTEGER("42") + 1
|
||||
@@ -1,20 +0,0 @@
|
||||
// A HASHMAP of LISTs built up, then printed in sorted key order with KEYS.
|
||||
// Finding: the list cannot be called Keys, because built-in names are reserved whatever their case.
|
||||
// EXPECT: a: [1, 3]
|
||||
// EXPECT: b: [2]
|
||||
DECLARE Groups : HASHMAP OF STRING : LIST OF INTEGER
|
||||
DECLARE Ks : LIST OF STRING
|
||||
DECLARE Names : LIST OF STRING
|
||||
DECLARE Values : LIST OF INTEGER
|
||||
Names <- ["a", "b", "a"]
|
||||
Values <- [1, 2, 3]
|
||||
FOR I <- 0 TO LENGTH(Names)
|
||||
IF NOT (Names[I] IN Groups) THEN
|
||||
Groups[Names[I]] <- []
|
||||
ENDIF
|
||||
APPEND(Groups[Names[I]], Values[I])
|
||||
NEXT I
|
||||
Ks <- KEYS(Groups)
|
||||
FOR EACH K IN Ks
|
||||
OUTPUT K & ": " & TO_STRING(Groups[K])
|
||||
NEXT K
|
||||
@@ -1,22 +0,0 @@
|
||||
// BYREF versus by value, side by side.
|
||||
// EXPECT: 2 1
|
||||
// EXPECT: 2 1
|
||||
PROCEDURE SWAP(BYREF X : INTEGER, BYREF Y : INTEGER)
|
||||
DECLARE Temp : INTEGER
|
||||
Temp <- X
|
||||
X <- Y
|
||||
Y <- Temp
|
||||
ENDPROCEDURE
|
||||
PROCEDURE TRY_SWAP(X : INTEGER, Y : INTEGER)
|
||||
DECLARE Temp : INTEGER
|
||||
Temp <- X
|
||||
X <- Y
|
||||
Y <- Temp
|
||||
ENDPROCEDURE
|
||||
DECLARE A, B : INTEGER
|
||||
A <- 1
|
||||
B <- 2
|
||||
CALL SWAP(A, B)
|
||||
OUTPUT A, " ", B
|
||||
CALL TRY_SWAP(A, B)
|
||||
OUTPUT A, " ", B
|
||||
@@ -1,11 +0,0 @@
|
||||
// The reasoning sublanguage used as values: FORALL, EXISTS, SUM, and a set written by rule.
|
||||
// EXPECT: TRUE
|
||||
// EXPECT: FALSE
|
||||
// EXPECT: 15
|
||||
// EXPECT: 3
|
||||
DECLARE L : LIST OF INTEGER
|
||||
L <- [1, 2, 3, 4, 5]
|
||||
OUTPUT FORALL K IN [0, LENGTH(L)) : L[K] > 0
|
||||
OUTPUT EXISTS K IN [0, LENGTH(L)) : L[K] > 10
|
||||
OUTPUT SUM K IN [0, LENGTH(L)) : L[K]
|
||||
OUTPUT LENGTH({ K IN [0, LENGTH(L)) : L[K] MOD 2 == 1 })
|
||||
@@ -1,7 +0,0 @@
|
||||
// What FLOAT does and does not promise.
|
||||
// EXPECT: FALSE
|
||||
// EXPECT: TRUE
|
||||
// EXPECT: 0.30000000000000004
|
||||
OUTPUT 0.1 + 0.2 == 0.3
|
||||
OUTPUT ABS((0.1 + 0.2) - 0.3) < 0.000001
|
||||
OUTPUT 0.1 + 0.2
|
||||
@@ -1,38 +0,0 @@
|
||||
// Linear search three ways: with a flag, with BREAK, with RETURN; all three agree.
|
||||
// EXPECT: 2 2 2
|
||||
// EXPECT: -1 -1 -1
|
||||
FUNCTION FIND_FLAG(Xs : LIST OF INTEGER, X : INTEGER) RETURNS INTEGER
|
||||
DECLARE Found, I : INTEGER
|
||||
Found <- -1
|
||||
I <- 0
|
||||
WHILE I < LENGTH(Xs) AND Found == -1
|
||||
IF Xs[I] == X THEN
|
||||
Found <- I
|
||||
ENDIF
|
||||
I <- I + 1
|
||||
ENDWHILE
|
||||
RETURN Found
|
||||
ENDFUNCTION
|
||||
FUNCTION FIND_BREAK(Xs : LIST OF INTEGER, X : INTEGER) RETURNS INTEGER
|
||||
DECLARE Found : INTEGER
|
||||
Found <- -1
|
||||
FOR I <- 0 TO LENGTH(Xs)
|
||||
IF Xs[I] == X THEN
|
||||
Found <- I
|
||||
BREAK
|
||||
ENDIF
|
||||
NEXT I
|
||||
RETURN Found
|
||||
ENDFUNCTION
|
||||
FUNCTION FIND_RETURN(Xs : LIST OF INTEGER, X : INTEGER) RETURNS INTEGER
|
||||
FOR I <- 0 TO LENGTH(Xs)
|
||||
IF Xs[I] == X THEN
|
||||
RETURN I
|
||||
ENDIF
|
||||
NEXT I
|
||||
RETURN -1
|
||||
ENDFUNCTION
|
||||
DECLARE L : LIST OF INTEGER
|
||||
L <- [4, 8, 15, 16]
|
||||
OUTPUT FIND_FLAG(L, 15), " ", FIND_BREAK(L, 15), " ", FIND_RETURN(L, 15)
|
||||
OUTPUT FIND_FLAG(L, 7), " ", FIND_BREAK(L, 7), " ", FIND_RETURN(L, 7)
|
||||
@@ -1,37 +0,0 @@
|
||||
// A state machine over a STRING: does a token look like a decimal number? CASE on a STRING state.
|
||||
// EXPECT: TRUE
|
||||
// EXPECT: TRUE
|
||||
// EXPECT: FALSE
|
||||
// EXPECT: FALSE
|
||||
FUNCTION IS_NUMBER(S : STRING) RETURNS BOOL
|
||||
DECLARE State : STRING
|
||||
State <- "start"
|
||||
FOR EACH C IN S
|
||||
CASE OF State
|
||||
"start" : IF C >= '0' AND C <= '9' THEN
|
||||
State <- "int"
|
||||
ELSE
|
||||
State <- "bad"
|
||||
ENDIF
|
||||
"int" : IF C == '.' THEN
|
||||
State <- "dot"
|
||||
ELSEIF NOT (C >= '0' AND C <= '9') THEN
|
||||
State <- "bad"
|
||||
ENDIF
|
||||
"dot" : IF C >= '0' AND C <= '9' THEN
|
||||
State <- "frac"
|
||||
ELSE
|
||||
State <- "bad"
|
||||
ENDIF
|
||||
"frac" : IF NOT (C >= '0' AND C <= '9') THEN
|
||||
State <- "bad"
|
||||
ENDIF
|
||||
OTHERWISE : State <- "bad"
|
||||
ENDCASE
|
||||
NEXT C
|
||||
RETURN State == "int" OR State == "frac"
|
||||
ENDFUNCTION
|
||||
OUTPUT IS_NUMBER("42")
|
||||
OUTPUT IS_NUMBER("3.14")
|
||||
OUTPUT IS_NUMBER("3.")
|
||||
OUTPUT IS_NUMBER("x1")
|
||||
@@ -1,20 +0,0 @@
|
||||
// Edge semantics every reader should know: chained comparisons, string order, MIN of a list, SORT of text, nested lists.
|
||||
// EXPECT: TRUE
|
||||
// EXPECT: TRUE
|
||||
// EXPECT: 1
|
||||
// EXPECT: ["apple", "fig", "pear"]
|
||||
// EXPECT: 6
|
||||
// EXPECT: FALSE
|
||||
DECLARE I : INTEGER
|
||||
I <- 3
|
||||
OUTPUT 0 <= I < 5
|
||||
OUTPUT "apple" < "banana"
|
||||
OUTPUT MIN([4, 1, 9])
|
||||
DECLARE Fruit : LIST OF STRING
|
||||
Fruit <- ["pear", "apple", "fig"]
|
||||
SORT(Fruit)
|
||||
OUTPUT Fruit
|
||||
DECLARE Grid : LIST OF LIST OF INTEGER
|
||||
Grid <- [[1, 2, 3], [4, 5, 6]]
|
||||
OUTPUT Grid[1][2]
|
||||
OUTPUT "" IN Fruit
|
||||
@@ -1,7 +0,0 @@
|
||||
// A run that stops: reading one past the end. The lab names the position and the length.
|
||||
// STOPS: index
|
||||
DECLARE T : STRING
|
||||
T <- "GATTACA"
|
||||
FOR I <- 0 TO LENGTH(T) + 1
|
||||
OUTPUT T[I]
|
||||
NEXT I
|
||||
@@ -1,11 +0,0 @@
|
||||
// A run that stops: dividing by zero inside a function; the lab blames the line and shows the values.
|
||||
// STOPS: divide
|
||||
FUNCTION MEAN(Xs : LIST OF INTEGER) RETURNS FLOAT
|
||||
DECLARE Total : INTEGER
|
||||
Total <- 0
|
||||
FOR EACH X IN Xs
|
||||
Total <- Total + X
|
||||
NEXT X
|
||||
RETURN Total / LENGTH(Xs)
|
||||
ENDFUNCTION
|
||||
OUTPUT MEAN([])
|
||||
@@ -1,6 +0,0 @@
|
||||
// A run that stops: recursion with no base case.
|
||||
// STOPS: depth
|
||||
FUNCTION DOWN(N : INTEGER) RETURNS INTEGER
|
||||
RETURN DOWN(N - 1)
|
||||
ENDFUNCTION
|
||||
OUTPUT DOWN(10)
|
||||
@@ -1,4 +0,0 @@
|
||||
// A run that stops: a declared name read before anything is stored in it.
|
||||
// STOPS: unset
|
||||
DECLARE Total : INTEGER
|
||||
OUTPUT Total + 1
|
||||
@@ -1,6 +0,0 @@
|
||||
// A run that stops: a FOR counter read after its loop.
|
||||
// STOPS: unset
|
||||
DECLARE I : INTEGER
|
||||
FOR I <- 0 TO 3
|
||||
NEXT I
|
||||
OUTPUT I
|
||||
@@ -1,14 +0,0 @@
|
||||
// What the checker refuses before anything runs. Each line below is one mistake the guide names.
|
||||
// ERRORS: 5
|
||||
DECLARE T : STRING
|
||||
DECLARE N : INTEGER
|
||||
T <- "GATTACA"
|
||||
N <- 7 / 2
|
||||
T[0] <- 'C'
|
||||
IF T[0] == "G" THEN
|
||||
OUTPUT "g"
|
||||
ENDIF
|
||||
FOR I <- 0 TO 3
|
||||
I <- I + 1
|
||||
NEXT I
|
||||
N = 5
|
||||
@@ -1,11 +0,0 @@
|
||||
// CONTINUE skips a pass; here, unknown bases are not evidence.
|
||||
// EXPECT: 6
|
||||
DECLARE Total : INTEGER
|
||||
Total <- 0
|
||||
FOR EACH B IN "GATNACA"
|
||||
IF B == 'N' THEN
|
||||
CONTINUE
|
||||
ENDIF
|
||||
Total <- Total + 1
|
||||
NEXT B
|
||||
OUTPUT Total
|
||||
@@ -1,29 +0,0 @@
|
||||
// CONSTANT names a number once; STEP walks codon starts; a HASHMAP codon table; a SET of stops.
|
||||
// EXPECT: MAK
|
||||
CONSTANT BasesPerCodon = 3
|
||||
FUNCTION TRANSLATE(T : STRING) RETURNS STRING
|
||||
DECLARE Table : HASHMAP OF STRING : CHAR
|
||||
DECLARE Stops : SET OF STRING
|
||||
DECLARE Out : STRING
|
||||
Table["ATG"] <- 'M'
|
||||
Table["GCC"] <- 'A'
|
||||
Table["AAA"] <- 'K'
|
||||
ADD(Stops, "TAG")
|
||||
ADD(Stops, "TAA")
|
||||
ADD(Stops, "TGA")
|
||||
Out <- ""
|
||||
FOR I <- 0 TO LENGTH(T) - BasesPerCodon + 1 STEP BasesPerCodon
|
||||
DECLARE Codon : STRING
|
||||
Codon <- SLICE(T, I, I + BasesPerCodon)
|
||||
IF Codon IN Stops THEN
|
||||
BREAK
|
||||
ENDIF
|
||||
IF Codon IN Table THEN
|
||||
Out <- Out & Table[Codon]
|
||||
ELSE
|
||||
Out <- Out & '?'
|
||||
ENDIF
|
||||
NEXT I
|
||||
RETURN Out
|
||||
ENDFUNCTION
|
||||
OUTPUT TRANSLATE("ATGGCCAAATAGTTT")
|
||||
@@ -1,24 +0,0 @@
|
||||
// The four text built-ins added after the stress test: SPLIT, JOIN, INDEX_OF, REPLACE.
|
||||
// EXPECT: ["the", "quick", "", "brown", "fox"]
|
||||
// EXPECT: the quick brown fox
|
||||
// EXPECT: 3 -1 2
|
||||
// EXPECT: GAUUACA
|
||||
// EXPECT: read_1:GAT
|
||||
FUNCTION WORDS(S : STRING) RETURNS LIST OF STRING
|
||||
DECLARE Out : LIST OF STRING
|
||||
FOR EACH W IN SPLIT(S, " ")
|
||||
IF LENGTH(W) > 0 THEN
|
||||
APPEND(Out, W)
|
||||
ENDIF
|
||||
NEXT W
|
||||
RETURN Out
|
||||
ENDFUNCTION
|
||||
DECLARE S : STRING
|
||||
S <- "the quick brown fox"
|
||||
OUTPUT SPLIT(S, " ")
|
||||
OUTPUT JOIN(WORDS(S), " ")
|
||||
OUTPUT INDEX_OF("GATTACA", "TAC"), " ", INDEX_OF("GATTACA", 'N'), " ", INDEX_OF([4, 8, 15], 15)
|
||||
OUTPUT REPLACE("GATTACA", "T", "U")
|
||||
DECLARE Fields : LIST OF STRING
|
||||
Fields <- SPLIT("read_1\tGAT\t30", "\t")
|
||||
OUTPUT Fields[0], ":", Fields[1]
|
||||
@@ -1,7 +0,0 @@
|
||||
// A keyword used as a name is one error per name, not a cascade: the rest of the program still parses.
|
||||
// ERRORS: 2
|
||||
DECLARE Step : INTEGER
|
||||
Step <- 1
|
||||
FOR EACH Next IN [1, 2]
|
||||
OUTPUT Next + Step
|
||||
NEXT Next
|
||||
@@ -1,17 +0,0 @@
|
||||
// The numeric built-ins added for mathematics, physics, chemistry and statistics.
|
||||
// EXPECT: 2 3 -3
|
||||
// EXPECT: 1.0 1.0
|
||||
// EXPECT: 10 120
|
||||
// EXPECT: 6 2.5 2.0 2.5
|
||||
// EXPECT: 4.571428571428571 2.138089935299395
|
||||
// EXPECT: 32 5.0
|
||||
// EXPECT: [0.0, 0.0, 0.0] 4
|
||||
// EXPECT: 3.0 3.142
|
||||
OUTPUT FLOOR(2.7), " ", CEIL(2.1), " ", FLOOR(-2.3)
|
||||
OUTPUT ROUND(SIN(PI() / 2) * 1000) / 1000, " ", ROUND(COS(0.0) * 1000) / 1000
|
||||
OUTPUT CHOOSE(5, 2), " ", CHOOSE(10, 3)
|
||||
OUTPUT SUM_OF([1, 2, 3]), " ", MEAN_OF([1, 2, 3, 4]), " ", MEDIAN_OF([3, 1, 2]), " ", MEDIAN_OF([4, 1, 3, 2])
|
||||
OUTPUT VARIANCE_OF([2, 4, 4, 4, 5, 5, 7, 9]), " ", STDEV_OF([2, 4, 4, 4, 5, 5, 7, 9])
|
||||
OUTPUT DOT([1, 2, 3], [4, 5, 6]), " ", NORM_OF([3.0, 4.0])
|
||||
OUTPUT FILL(3, 0.0), " ", LENGTH(FILL(4, 'A'))
|
||||
OUTPUT LOG10(1000.0), " ", ROUND(ATAN2(1.0, 1.0) * 4 * 1000) / 1000
|
||||
@@ -1,30 +0,0 @@
|
||||
// GPU thinking: a PARALLEL FOR whose passes each own one slot (a map), then a sequential reduce.
|
||||
// EXPECT: [1.0, 4.0, 9.0, 16.0]
|
||||
// EXPECT: 30.0
|
||||
// EXPECT: [5, 7, 9]
|
||||
FUNCTION SQUARES(Xs : LIST OF FLOAT) RETURNS LIST OF FLOAT
|
||||
DECLARE Out : LIST OF FLOAT
|
||||
Out <- FILL(LENGTH(Xs), 0.0)
|
||||
PARALLEL FOR I <- 0 TO LENGTH(Xs)
|
||||
DECLARE X : FLOAT
|
||||
X <- Xs[I]
|
||||
Out[I] <- X * X
|
||||
NEXT I
|
||||
RETURN Out
|
||||
ENDFUNCTION
|
||||
|
||||
FUNCTION ADD_VECTORS(A : LIST OF INTEGER, B : LIST OF INTEGER) RETURNS LIST OF INTEGER
|
||||
REQUIRE LENGTH(A) == LENGTH(B)
|
||||
DECLARE C : LIST OF INTEGER
|
||||
C <- FILL(LENGTH(A), 0)
|
||||
PARALLEL FOR I <- 0 TO LENGTH(A)
|
||||
C[I] <- A[I] + B[I]
|
||||
NEXT I
|
||||
RETURN C
|
||||
ENDFUNCTION
|
||||
|
||||
DECLARE Sq : LIST OF FLOAT
|
||||
Sq <- SQUARES([1.0, 2.0, 3.0, 4.0])
|
||||
OUTPUT Sq
|
||||
OUTPUT SUM_OF(Sq)
|
||||
OUTPUT ADD_VECTORS([1, 2, 3], [4, 5, 6])
|
||||
@@ -1,10 +0,0 @@
|
||||
// A shared running total inside a PARALLEL FOR is a data race, and the lab says so.
|
||||
// STOPS: race
|
||||
DECLARE Xs : LIST OF FLOAT
|
||||
DECLARE Acc : FLOAT
|
||||
Xs <- [1.0, 2.0, 3.0]
|
||||
Acc <- 0.0
|
||||
PARALLEL FOR I <- 0 TO LENGTH(Xs)
|
||||
Acc <- Acc + Xs[I]
|
||||
NEXT I
|
||||
OUTPUT Acc
|
||||
@@ -1,8 +0,0 @@
|
||||
// Reading a neighbour that another pass writes is also a race, even with no shared scalar.
|
||||
// STOPS: race
|
||||
DECLARE A : LIST OF INTEGER
|
||||
A <- [5, 6, 7, 8]
|
||||
PARALLEL FOR I <- 0 TO 3
|
||||
A[I] <- A[I + 1]
|
||||
NEXT I
|
||||
OUTPUT A
|
||||
@@ -1,25 +0,0 @@
|
||||
// Physics: where a projectile lands, by stepping Newton's laws, against the closed form.
|
||||
// EXPECT: 10.2 10.2
|
||||
FUNCTION RANGE_BY_STEPS(Speed : FLOAT, Angle : FLOAT, Dt : FLOAT) RETURNS FLOAT
|
||||
DECLARE X, Y, Vx, Vy, G : FLOAT
|
||||
G <- 9.81
|
||||
X <- 0.0
|
||||
Y <- 0.0
|
||||
Vx <- Speed * COS(Angle)
|
||||
Vy <- Speed * SIN(Angle)
|
||||
REPEAT
|
||||
X <- X + Vx * Dt
|
||||
Y <- Y + Vy * Dt
|
||||
Vy <- Vy - G * Dt
|
||||
UNTIL Y <= 0.0
|
||||
RETURN X
|
||||
ENDFUNCTION
|
||||
|
||||
FUNCTION RANGE_EXACT(Speed : FLOAT, Angle : FLOAT) RETURNS FLOAT
|
||||
RETURN Speed * Speed * SIN(2.0 * Angle) / 9.81
|
||||
ENDFUNCTION
|
||||
|
||||
DECLARE Angle : FLOAT
|
||||
Angle <- PI() / 4
|
||||
// Stepping forward overshoots a little, so compare to one decimal place.
|
||||
OUTPUT ROUND(RANGE_BY_STEPS(10.0, Angle, 0.0001) * 10) / 10, " ", ROUND(RANGE_EXACT(10.0, Angle) * 10) / 10
|
||||
@@ -1,22 +0,0 @@
|
||||
// Probability and chemistry: a binomial probability from CHOOSE, and pH from LOG10.
|
||||
// EXPECT: 0.2461
|
||||
// EXPECT: 1.0
|
||||
// EXPECT: 3.0 7.0
|
||||
FUNCTION BINOMIAL(N : INTEGER, K : INTEGER, P : FLOAT) RETURNS FLOAT
|
||||
REQUIRE 0 <= K AND K <= N
|
||||
RETURN CHOOSE(N, K) * P ^ K * (1.0 - P) ^ (N - K)
|
||||
ENDFUNCTION
|
||||
|
||||
FUNCTION PH(Concentration : FLOAT) RETURNS FLOAT
|
||||
REQUIRE Concentration > 0.0
|
||||
RETURN -LOG10(Concentration)
|
||||
ENDFUNCTION
|
||||
|
||||
DECLARE Sum : FLOAT
|
||||
Sum <- 0.0
|
||||
FOR K <- 0 TO 11
|
||||
Sum <- Sum + BINOMIAL(10, K, 0.5)
|
||||
NEXT K
|
||||
OUTPUT ROUND(BINOMIAL(10, 5, 0.5) * 10000) / 10000
|
||||
OUTPUT ROUND(Sum * 1000) / 1000
|
||||
OUTPUT PH(0.001), " ", PH(0.0000001)
|
||||
@@ -1,32 +0,0 @@
|
||||
// Declaring with a starting value on one line, beside the two-line form, at the top, in a routine, and in a loop.
|
||||
// EXPECT: 3
|
||||
// EXPECT: 7 3
|
||||
// EXPECT: a <- b
|
||||
// EXPECT: 6
|
||||
// EXPECT: 2
|
||||
FUNCTION COUNT_BASE(B : CHAR, T : STRING) RETURNS INTEGER
|
||||
DECLARE N : INTEGER <- LENGTH(T)
|
||||
DECLARE Total : INTEGER <- 0 // the running total
|
||||
FOR I <- 0 TO N
|
||||
IF T[I] == B THEN
|
||||
Total <- Total + 1
|
||||
ENDIF
|
||||
NEXT I
|
||||
RETURN Total
|
||||
ENDFUNCTION
|
||||
DECLARE Seq : STRING <- "GATTACA"
|
||||
DECLARE Count : INTEGER
|
||||
Count <- COUNT_BASE('A', Seq)
|
||||
OUTPUT Count
|
||||
DECLARE Len : INTEGER <- LENGTH(Seq)
|
||||
OUTPUT Len, " ", Count
|
||||
DECLARE Arrow : STRING <- "a <- b"
|
||||
OUTPUT Arrow
|
||||
DECLARE Sum : INTEGER <- 0
|
||||
FOR K <- 0 TO 3
|
||||
DECLARE Twice : INTEGER <- 2 * K
|
||||
Sum <- Sum + Twice
|
||||
NEXT K
|
||||
OUTPUT Sum
|
||||
DECLARE Xs : LIST OF INTEGER <- [4, 9]
|
||||
OUTPUT LENGTH(Xs)
|
||||
@@ -1,14 +0,0 @@
|
||||
// Sized whole numbers: arithmetic that stays inside its type, wrapping only when asked, and conversions that check.
|
||||
// EXPECT: 255 0 255
|
||||
// EXPECT: 1500000000 -2 256
|
||||
// EXPECT: 8 14 6 255 1024 -4
|
||||
// EXPECT: 12 12 -128 2147483647
|
||||
DECLARE Count : UINT8 <- 250
|
||||
Count <- Count + 5
|
||||
OUTPUT Count, " ", WRAP(Count + 1, UINT8), " ", MAX_VALUE(UINT8)
|
||||
DECLARE Big : INT64 <- 3_000_000_000
|
||||
DECLARE Small : INT32
|
||||
Small <- INT32(Big DIV 2)
|
||||
OUTPUT Small, " ", INT16(-2.9), " ", 0xFF + 0b1
|
||||
OUTPUT BIT_AND(0b1100, 0b1010), " ", BIT_OR(12, 10), " ", BIT_XOR(12, 10), " ", BIT_NOT(UINT8(0)), " ", SHIFT_LEFT(1, 10), " ", SHIFT_RIGHT(-8, 1)
|
||||
OUTPUT GCD(84, 36), " ", LCM(4, 6), " ", MIN_VALUE(INT8), " ", MAX_VALUE(INT32)
|
||||
@@ -1,20 +0,0 @@
|
||||
// Single precision: every FLOAT32 result is rounded to 24 bits, and a literal next to a FLOAT32 is a FLOAT32.
|
||||
// EXPECT: 1.0000001 0.9999999999999999
|
||||
// EXPECT: TRUE FALSE
|
||||
// EXPECT: 0.100000001490116119384765625
|
||||
// EXPECT: 16777216.0 1.1920929e-7 1.1920929e-7
|
||||
// EXPECT: 5.551115123125783e-17 0.0
|
||||
// EXPECT: TRUE TRUE
|
||||
DECLARE X : FLOAT32 <- 0.1
|
||||
DECLARE Total32 : FLOAT32 <- 0.0
|
||||
DECLARE Total64 : FLOAT <- 0.0
|
||||
FOR I <- 0 TO 10
|
||||
Total32 <- Total32 + X
|
||||
Total64 <- Total64 + 0.1
|
||||
NEXT I
|
||||
OUTPUT Total32, " ", Total64
|
||||
OUTPUT X == 0.1, " ", FLOAT64(X) == 0.1
|
||||
OUTPUT EXACT(X)
|
||||
OUTPUT FLOAT32(16777217), " ", ULP(FLOAT32(1.0)), " ", EPSILON(FLOAT32)
|
||||
OUTPUT FMA(0.1, 10.0, -1.0), " ", 0.1 * 10.0 - 1.0
|
||||
OUTPUT IS_CLOSE(Total32, 1.0, 1e-6, 0.0), " ", IS_CLOSE(Total64, 1.0, 1e-15, 0.0)
|
||||
@@ -1,12 +0,0 @@
|
||||
// USE IEEE: NaN and the infinities flow through a calculation as IEEE 754 says, instead of stopping the run.
|
||||
// EXPECT: infinity -infinity not a number
|
||||
// EXPECT: TRUE TRUE FALSE TRUE
|
||||
// EXPECT: not a number -infinity FALSE
|
||||
USE IEEE
|
||||
DECLARE Zero : FLOAT <- 0.0
|
||||
DECLARE Inf : FLOAT
|
||||
Inf <- 1.0 / Zero
|
||||
DECLARE NotANumber : FLOAT <- Inf - Inf
|
||||
OUTPUT Inf, " ", -Inf, " ", NotANumber
|
||||
OUTPUT IS_INF(Inf), " ", IS_NAN(NotANumber), " ", NotANumber == NotANumber, " ", NotANumber != NotANumber
|
||||
OUTPUT SQRT(-1.0), " ", LOG(0.0), " ", IS_FINITE(MAX_VALUE(FLOAT64) * 2.0)
|
||||
@@ -1,11 +0,0 @@
|
||||
// Elementary functions for numerical work, and the accurate forms near 0.
|
||||
// EXPECT: 5.0 TRUE -3.0 1024.0
|
||||
// EXPECT: 1.00000000005e-10 1.000000082740371e-10 9.999999999500001e-11
|
||||
// EXPECT: -2.0 -1 -2.0 10 0.0
|
||||
// EXPECT: 3.142 3.142 0.0 0.0 2.718
|
||||
// EXPECT: TRUE 2.220446049250313e-16
|
||||
OUTPUT HYPOT(3.0, 4.0), " ", HYPOT(1e200, 1e200) > 1e200, " ", CBRT(-27.0), " ", POW(2.0, 10.0)
|
||||
OUTPUT EXPM1(1e-10), " ", EXP(1e-10) - 1.0, " ", LOG1P(1e-10)
|
||||
OUTPUT TRUNC(-2.7), " ", SIGN(-3), " ", COPYSIGN(2.0, -0.0), " ", CLAMP(15, 0, 10), " ", CLAMP(-0.5, 0.0, 1.0)
|
||||
OUTPUT ROUND(ASIN(1.0) * 2 * 1000) / 1000, " ", ROUND(ACOS(-1.0) * 1000) / 1000, " ", ATAN(0.0), " ", TANH(0.0), " ", ROUND(E() * 1000) / 1000
|
||||
OUTPUT NEXT_AFTER(1.0, 2.0) - 1.0 == EPSILON(FLOAT64), " ", ULP(1.0)
|
||||
@@ -1,12 +0,0 @@
|
||||
// Routines from the library, called like the program's own: a run steps over each one, and the
|
||||
// prover uses each one's REQUIRE and ENSURE at the call.
|
||||
// EXPECT: 5.0 4.571428571428571
|
||||
// EXPECT: 0.0 -0.0615234375
|
||||
// EXPECT: 0
|
||||
USE stats
|
||||
USE md.LennardJones
|
||||
USE align.NeedlemanWunschScore
|
||||
DECLARE Samples : LIST OF FLOAT <- [2.0, 4.0, 4.0, 4.0, 5.0, 5.0, 7.0, 9.0]
|
||||
OUTPUT Mean(Samples), " ", Variance(Samples)
|
||||
OUTPUT LennardJones(1.0, 1.0, 1.0), " ", LennardJones(2.0, 1.0, 1.0)
|
||||
OUTPUT NeedlemanWunschScore("GATTACA", "GCATGCU", 1, -1, -1)
|
||||
@@ -1,4 +1,4 @@
|
||||
// The programs the sync translators are held to: every exercise with pseudo, every program in tests/corpus/,
|
||||
// The programs the sync translators are held to: every exercise with pseudo, every program in library/pseudo/programs/,
|
||||
// and small fixtures that each exercise one construct. Shared by the translator tests and the coverage report.
|
||||
import fs from 'node:fs';
|
||||
import path from 'node:path';
|
||||
@@ -6,7 +6,7 @@ import { fileURLToPath } from 'node:url';
|
||||
import { EXERCISES } from '../../dist/exercises/index.js';
|
||||
|
||||
const here = path.dirname(fileURLToPath(import.meta.url));
|
||||
export const corpusDir = path.join(here, '..', 'corpus');
|
||||
export const corpusDir = path.join(here, '..', '..', 'library', 'pseudo', 'programs');
|
||||
|
||||
/** One construct each, with the call that runs it. */
|
||||
export const FIXTURES = {
|
||||
|
||||
@@ -8,7 +8,7 @@ import { listingFunctions } from '../dist/services/godbolt.js';
|
||||
import { parseAsm } from '../dist/services/asm.js';
|
||||
|
||||
const ROOT = new URL('..', import.meta.url).pathname;
|
||||
const GOLDEN = ROOT + 'mojo/golden';
|
||||
const GOLDEN = ROOT + 'library/mojo/golden';
|
||||
const mods = { forSimulator, simulatorSetup, listingFunctions };
|
||||
|
||||
test('stripHeader drops what emit_ts.py drops, and says how many lines went', () => {
|
||||
@@ -28,7 +28,7 @@ test('readHeader reads the keys verify.py knows and ignores other comments', ()
|
||||
});
|
||||
|
||||
test('a golden is used only for the exact source, mode and arguments it answered', () => {
|
||||
const probe = fs.readFileSync(ROOT + 'mojo/probes/godbolt-line-tables-O0.mojo', 'utf8');
|
||||
const probe = fs.readFileSync(ROOT + 'library/mojo/probes/godbolt-line-tables-O0.mojo', 'utf8');
|
||||
const h = readHeader(probe);
|
||||
assert.ok(findGolden(GOLDEN, probe, h.mode, h.args ?? ''), 'the committed answer for this probe is found');
|
||||
assert.equal(findGolden(GOLDEN, probe + ' ', h.mode, h.args ?? ''), null, 'one extra character and the answer no longer applies');
|
||||
@@ -37,8 +37,8 @@ test('a golden is used only for the exact source, mode and arguments it answered
|
||||
|
||||
test('real godbolt answers become x86-64 panes the assembler accepts, with lines that point into the shown source', () => {
|
||||
let made = 0;
|
||||
for (const f of fs.readdirSync(ROOT + 'mojo/probes').filter((x) => x.endsWith('.mojo'))) {
|
||||
const text = fs.readFileSync(ROOT + 'mojo/probes/' + f, 'utf8');
|
||||
for (const f of fs.readdirSync(ROOT + 'library/mojo/probes').filter((x) => x.endsWith('.mojo'))) {
|
||||
const text = fs.readFileSync(ROOT + 'library/mojo/probes/' + f, 'utf8');
|
||||
if (!/^# mode: (asm|both)/m.test(text)) continue;
|
||||
const r = buildListing(text, GOLDEN, mods);
|
||||
if (r.why) continue; // e.g. built without -O0, so the optimizer inlined every function
|
||||
@@ -64,12 +64,12 @@ test('render keeps the header and interface, and writes programs in name order',
|
||||
assert.ok(out.endsWith('};\n'));
|
||||
});
|
||||
|
||||
test('every exercise that names a Mojo program has that program in mojo/local/', () => {
|
||||
test('every exercise that names a Mojo program has that program in library/mojo/local/', () => {
|
||||
const dir = ROOT + 'src/exercises/';
|
||||
const missing = [];
|
||||
for (const f of fs.readdirSync(dir).filter((x) => x.endsWith('.ts') && !x.startsWith('_'))) {
|
||||
const m = /mojoProgram:\s*['"]([^'"]+)['"]/.exec(fs.readFileSync(dir + f, 'utf8'));
|
||||
if (m && !fs.existsSync(ROOT + `mojo/local/${m[1]}.mojo`)) missing.push(`${f} -> mojo/local/${m[1]}.mojo`);
|
||||
if (m && !fs.existsSync(ROOT + `library/mojo/local/${m[1]}.mojo`)) missing.push(`${f} -> library/mojo/local/${m[1]}.mojo`);
|
||||
}
|
||||
assert.deepEqual(missing, [], 'create the file, or remove `mojoProgram` from the exercise; until then `pixi run play` will not regenerate programs.ts, because the catalog would throw');
|
||||
});
|
||||
+17
-17
@@ -1,4 +1,4 @@
|
||||
// Programming+'s Mojo checker, scored against the real compiler (godbolt's answers in mojo/golden,
|
||||
// Programming+'s Mojo checker, scored against the real compiler (godbolt's answers in library/mojo/golden,
|
||||
// and the compiler's own diagnostic tests). Two rules never bend, and two numbers only go up:
|
||||
// - no error on a program the compiler accepts (a false accusation teaches the wrong lesson)
|
||||
// - no error on a rejected program that the compiler did not make there, in those words
|
||||
@@ -12,8 +12,8 @@ import { compilerDiagnostics } from '../dist/services/godbolt.js';
|
||||
|
||||
const R = new URL('..', import.meta.url).pathname;
|
||||
const read = (p) => JSON.parse(fs.readFileSync(R + p, 'utf8'));
|
||||
const golden = (key) => key && fs.existsSync(`${R}mojo/golden/${key}.json`) ? read(`mojo/golden/${key}.json`) : null;
|
||||
const verdicts = new Map(read('mojo/golden/status.json').items.map((r) => [r.id, r]));
|
||||
const golden = (key) => key && fs.existsSync(`${R}library/mojo/golden/${key}.json`) ? read(`library/mojo/golden/${key}.json`) : null;
|
||||
const verdicts = new Map(read('library/mojo/golden/status.json').items.map((r) => [r.id, r]));
|
||||
const errorsOf = (src) => checkMojo(src).diagnostics.filter((d) => d.severity === 'error');
|
||||
|
||||
/** What the compiler said, as (line, message): its <source> errors, and the one it gives no line. */
|
||||
@@ -28,18 +28,18 @@ const MATCHED_AT_LEAST = 43; // raise when a stage makes more starters
|
||||
const ANNOTATIONS_AT_LEAST = 21; // 2a: 14, 2b: 18, 2c: 19, 4c: 21
|
||||
|
||||
test('no false accusations: every program the compiler accepts gets no error', () => {
|
||||
const items = [...read('mojo/corpus/quest/manifest.json').items.map((i) => ['quest', i]), ...read('mojo/corpus/manual/manifest.json').items.map((i) => ['manual', i])];
|
||||
const items = [...read('library/mojo/corpus/quest/manifest.json').items.map((i) => ['quest', i]), ...read('library/mojo/corpus/manual/manifest.json').items.map((i) => ['manual', i])];
|
||||
const accused = []; let checked = 0;
|
||||
for (const [dir, it] of items) {
|
||||
const g = golden(verdicts.get(it.id)?.key);
|
||||
if (!g?.result.compiled) continue;
|
||||
checked++;
|
||||
for (const d of errorsOf(fs.readFileSync(`${R}mojo/corpus/${dir}/${it.file}`, 'utf8'))) accused.push(`${it.id}: line ${d.line}: ${d.message}`);
|
||||
for (const d of errorsOf(fs.readFileSync(`${R}library/mojo/corpus/${dir}/${it.file}`, 'utf8'))) accused.push(`${it.id}: line ${d.line}: ${d.message}`);
|
||||
}
|
||||
for (const f of fs.readdirSync(`${R}mojo/local`).filter((f) => f.endsWith('.mojo'))) for (const d of errorsOf(fs.readFileSync(`${R}mojo/local/${f}`, 'utf8'))) accused.push(`local/${f}: line ${d.line}: ${d.message}`);
|
||||
for (const f of fs.readdirSync(`${R}library/mojo/local`).filter((f) => f.endsWith('.mojo'))) for (const d of errorsOf(fs.readFileSync(`${R}library/mojo/local/${f}`, 'utf8'))) accused.push(`local/${f}: line ${d.line}: ${d.message}`);
|
||||
// the stress programs: every one is meant to compile, so none may be accused, verified or not
|
||||
for (const f of fs.readdirSync(`${R}mojo/stress`).filter((f) => f.endsWith('.mojo'))) {
|
||||
const src = fs.readFileSync(`${R}mojo/stress/${f}`, 'utf8');
|
||||
for (const f of fs.readdirSync(`${R}library/mojo/stress`).filter((f) => f.endsWith('.mojo'))) {
|
||||
const src = fs.readFileSync(`${R}library/mojo/stress/${f}`, 'utf8');
|
||||
if (/^# expect: compile-error$/m.test(src)) continue; // kept as checker tests: meant to fail
|
||||
for (const d of errorsOf(src)) accused.push(`stress/${f}: line ${d.line}: ${d.message}`);
|
||||
}
|
||||
@@ -49,10 +49,10 @@ test('no false accusations: every program the compiler accepts gets no error', (
|
||||
|
||||
test('rejected starters: what Programming+ says is what the compiler said', () => {
|
||||
const wrong = [], matched = [];
|
||||
for (const it of read('mojo/corpus/quest/manifest.json').items.filter((i) => i.id.endsWith('/starter'))) {
|
||||
for (const it of read('library/mojo/corpus/quest/manifest.json').items.filter((i) => i.id.endsWith('/starter'))) {
|
||||
const g = golden(verdicts.get(it.id)?.key);
|
||||
if (!g || g.result.compiled) continue;
|
||||
const ours = errorsOf(fs.readFileSync(`${R}mojo/corpus/quest/${it.file}`, 'utf8'));
|
||||
const ours = errorsOf(fs.readFileSync(`${R}library/mojo/corpus/quest/${it.file}`, 'utf8'));
|
||||
if (!ours.length) continue;
|
||||
const theirs = compilerSaid(g);
|
||||
const bad = ours.filter((d) => !theirs.some((t) => t.line === d.line && t.message === d.message));
|
||||
@@ -67,12 +67,12 @@ test('rejected starters: what Programming+ says is what the compiler said', () =
|
||||
test('the compiler\'s own diagnostic tests: every error Programming+ reports there is one they expect', () => {
|
||||
const toRe = (a) => new RegExp(a.message.split(/(\{\{.*?\}\})/).map((p) => p.startsWith('{{') ? p.slice(2, -2) : p.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')).join(''));
|
||||
const wrong = []; let matched = 0;
|
||||
for (const it of read('mojo/corpus/diagnostics/manifest.json').items) {
|
||||
for (const it of read('library/mojo/corpus/diagnostics/manifest.json').items) {
|
||||
// run with the isolated stdlib or other local files: they know other names, and that mode
|
||||
// does not check for code at file scope; and as tests, none of them has a main
|
||||
const special = it.run.some((r) => /isolated|%S\/|-I\s/.test(r));
|
||||
const skip = new Set(['no-main', ...(special ? ['unknown-name', 'implicit-declaration', 'file-scope'] : [])]);
|
||||
for (const d of errorsOf(fs.readFileSync(`${R}mojo/corpus/diagnostics/${it.file}`, 'utf8')).filter((d) => !skip.has(d.id))) {
|
||||
for (const d of errorsOf(fs.readFileSync(`${R}library/mojo/corpus/diagnostics/${it.file}`, 'utf8')).filter((d) => !skip.has(d.id))) {
|
||||
if (it.annotations.some((a) => a.kind === 'error' && a.line === d.line && (a.regex ? toRe(a).test(d.message) : d.message.includes(a.message)))) matched++;
|
||||
else wrong.push(`${it.id}: line ${d.line}: ${d.message}`);
|
||||
}
|
||||
@@ -158,9 +158,9 @@ test('Stage 2c: types, in the compiler\'s words, and silence where a type is not
|
||||
|
||||
test('lifetime warnings: each is the compiler\'s, at its line and column', () => {
|
||||
const programs = [];
|
||||
for (const [dir, mf] of [['quest', 'quest'], ['manual', 'manual']]) for (const it of read(`mojo/corpus/${mf}/manifest.json`).items) programs.push([it.id, `mojo/corpus/${dir}/${it.file}`]);
|
||||
for (const f of fs.readdirSync(`${R}mojo/probes`)) programs.push([`probes/${f.replace('.mojo', '')}`, `mojo/probes/${f}`]);
|
||||
for (const f of fs.readdirSync(`${R}mojo/stress`)) programs.push([`stress/${f.replace('.mojo', '')}`, `mojo/stress/${f}`]);
|
||||
for (const [dir, mf] of [['quest', 'quest'], ['manual', 'manual']]) for (const it of read(`library/mojo/corpus/${mf}/manifest.json`).items) programs.push([it.id, `library/mojo/corpus/${dir}/${it.file}`]);
|
||||
for (const f of fs.readdirSync(`${R}library/mojo/probes`)) programs.push([`probes/${f.replace('.mojo', '')}`, `library/mojo/probes/${f}`]);
|
||||
for (const f of fs.readdirSync(`${R}library/mojo/stress`)) programs.push([`stress/${f.replace('.mojo', '')}`, `library/mojo/stress/${f}`]);
|
||||
const wrong = []; let matched = 0;
|
||||
for (const [id, file] of programs) {
|
||||
const g = golden(verdicts.get(id)?.key);
|
||||
@@ -190,8 +190,8 @@ test('Stage 4c: a value read where it may be uninitialized, on any path, in the
|
||||
|
||||
test('rejected stress programs: whatever Programming+ reports there is what the compiler said', () => {
|
||||
const wrong = []; let matched = 0, current = 0;
|
||||
for (const f of fs.readdirSync(`${R}mojo/stress`).filter((f) => f.endsWith('.mojo'))) {
|
||||
const src = fs.readFileSync(`${R}mojo/stress/${f}`, 'utf8');
|
||||
for (const f of fs.readdirSync(`${R}library/mojo/stress`).filter((f) => f.endsWith('.mojo'))) {
|
||||
const src = fs.readFileSync(`${R}library/mojo/stress/${f}`, 'utf8');
|
||||
const g = golden(verdicts.get(`stress/${f.replace('.mojo', '')}`)?.key);
|
||||
// a golden answers the exact source godbolt saw: an edited file waits for the next verify
|
||||
if (!g || g.result.compiled || g.sourceSha256 !== crypto.createHash('sha256').update(src).digest('hex')) continue;
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
// Programming+'s Mojo interpreter, judged against the real compiler: for every program godbolt
|
||||
// compiled and ran (mojo/golden), the interpreter either declines ("cannot run this yet") or
|
||||
// compiled and ran (library/mojo/golden), the interpreter either declines ("cannot run this yet") or
|
||||
// prints exactly what godbolt's run printed and ends the same way. It never disagrees.
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
@@ -10,17 +10,17 @@ import { runMojo } from '../dist/mojo/interp.js';
|
||||
|
||||
const R = new URL('..', import.meta.url).pathname;
|
||||
const read = (p) => JSON.parse(fs.readFileSync(R + p, 'utf8'));
|
||||
const verdicts = new Map(read('mojo/golden/status.json').items.map((r) => [r.id, r]));
|
||||
const golden = (key) => key && fs.existsSync(`${R}mojo/golden/${key}.json`) ? read(`mojo/golden/${key}.json`) : null;
|
||||
const verdicts = new Map(read('library/mojo/golden/status.json').items.map((r) => [r.id, r]));
|
||||
const golden = (key) => key && fs.existsSync(`${R}library/mojo/golden/${key}.json`) ? read(`library/mojo/golden/${key}.json`) : null;
|
||||
const run = (src, input = []) => runMojo(parseModule(src), src, { input, maxSteps: 200000 });
|
||||
const AGREE_AT_LEAST = 203; // raise as the interpreter learns more (3a: 171, 4a: 180, 4b: 182, 4c: 191, 7a: 201, 7b: 203)
|
||||
|
||||
test('the interpreter never disagrees with godbolt, and agrees on at least the ratchet', () => {
|
||||
const programs = [];
|
||||
for (const [dir, mf] of [['quest', 'quest'], ['manual', 'manual']]) for (const it of read(`mojo/corpus/${mf}/manifest.json`).items) programs.push([it.id, `mojo/corpus/${dir}/${it.file}`]);
|
||||
for (const f of fs.readdirSync(R + 'mojo/probes')) programs.push([`probes/${f.replace('.mojo', '')}`, `mojo/probes/${f}`]);
|
||||
for (const f of fs.readdirSync(R + 'mojo/local')) programs.push([`local/${f.replace('.mojo', '')}`, `mojo/local/${f}`]);
|
||||
for (const f of fs.readdirSync(R + 'mojo/stress')) programs.push([`stress/${f.replace('.mojo', '')}`, `mojo/stress/${f}`]);
|
||||
for (const [dir, mf] of [['quest', 'quest'], ['manual', 'manual']]) for (const it of read(`library/mojo/corpus/${mf}/manifest.json`).items) programs.push([it.id, `library/mojo/corpus/${dir}/${it.file}`]);
|
||||
for (const f of fs.readdirSync(R + 'library/mojo/probes')) programs.push([`probes/${f.replace('.mojo', '')}`, `library/mojo/probes/${f}`]);
|
||||
for (const f of fs.readdirSync(R + 'library/mojo/local')) programs.push([`local/${f.replace('.mojo', '')}`, `library/mojo/local/${f}`]);
|
||||
for (const f of fs.readdirSync(R + 'library/mojo/stress')) programs.push([`stress/${f.replace('.mojo', '')}`, `library/mojo/stress/${f}`]);
|
||||
const disagree = []; let agree = 0;
|
||||
for (const [id, file] of programs) {
|
||||
const g = golden(verdicts.get(id)?.key);
|
||||
|
||||
+9
-9
@@ -1,4 +1,4 @@
|
||||
// The Mojo corpus as the app sees it: the generated modules agree with mojo/pin.json
|
||||
// The Mojo corpus as the app sees it: the generated modules agree with library/mojo/pin.json
|
||||
// and the harvested corpus, and the Python pipeline's own tests pass.
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
@@ -9,9 +9,9 @@ import { MOJO_KEYWORDS, MOJO_SOFT_KEYWORDS, MOJO_REMOVED_WORDS, MOJO_DECORATORS,
|
||||
import { Workspace } from '../dist/common/workspace.js';
|
||||
import { PROBLEMS, problemById, workForProblem } from '../dist/common/problems.js';
|
||||
|
||||
const pin = JSON.parse(fs.readFileSync(new URL('../mojo/pin.json', import.meta.url), 'utf8'));
|
||||
const pin = JSON.parse(fs.readFileSync(new URL('../library/mojo/pin.json', import.meta.url), 'utf8'));
|
||||
|
||||
test('the generated pin is mojo/pin.json', () => {
|
||||
test('the generated pin is library/mojo/pin.json', () => {
|
||||
assert.equal(MOJO_VERSION, pin.mojo.version);
|
||||
assert.equal(GODBOLT_BASE, pin.godbolt.base);
|
||||
assert.equal(GODBOLT_COMPILER, pin.godbolt.compiler);
|
||||
@@ -37,7 +37,7 @@ test('the corpus pipeline tests pass (python3)', { skip: py.status !== 0 ? 'pyth
|
||||
|
||||
/* ---------------------------------------------------------------------------
|
||||
* Stage 1: the Mojo pane. Wherever possible these use godbolt's real answers
|
||||
* (mojo/golden), so they test against what the compiler said, not what we assume.
|
||||
* (library/mojo/golden), so they test against what the compiler said, not what we assume.
|
||||
* ------------------------------------------------------------------------- */
|
||||
import { tokenizeMojo } from '../dist/mojo/tokenize.js';
|
||||
import { removedSyntax } from '../dist/mojo/check.js';
|
||||
@@ -50,8 +50,8 @@ import { parseModule } from '../dist/mojo/parse.js';
|
||||
import { MOJO_PROGRAMS } from '../dist/mojo/generated/programs.js';
|
||||
|
||||
const ROOT = new URL('..', import.meta.url).pathname;
|
||||
const goldens = fs.readdirSync(new URL('../mojo/golden/', import.meta.url)).filter((f) => /^[0-9a-f]{64}\.json$/.test(f))
|
||||
.map((f) => JSON.parse(fs.readFileSync(new URL(`../mojo/golden/${f}`, import.meta.url), 'utf8')));
|
||||
const goldens = fs.readdirSync(new URL('../library/mojo/golden/', import.meta.url)).filter((f) => /^[0-9a-f]{64}\.json$/.test(f))
|
||||
.map((f) => JSON.parse(fs.readFileSync(new URL(`../library/mojo/golden/${f}`, import.meta.url), 'utf8')));
|
||||
/** godbolt's answer for one corpus item, rebuilt as the raw JSON the browser receives. */
|
||||
function answerFor(item) {
|
||||
const g = goldens.find((x) => x.firstItem === item);
|
||||
@@ -59,7 +59,7 @@ function answerFor(item) {
|
||||
const source = (a) => a.line ? { line: a.line, ...('file' in a ? { file: a.file } : {}), ...('main' in a ? { mainsource: a.main } : {}) } : null;
|
||||
return { golden: g, raw: { ...g.raw, asm: (g.result.asm || []).map((a) => ({ text: a.text, source: source(a) })) } };
|
||||
}
|
||||
const sourceOf = (item) => fs.readFileSync(new URL(`../mojo/${item.replace('probes/', 'probes/')}.mojo`, import.meta.url), 'utf8');
|
||||
const sourceOf = (item) => fs.readFileSync(new URL(`../library/mojo/${item.replace('probes/', 'probes/')}.mojo`, import.meta.url), 'utf8');
|
||||
function applyFix(src, f) {
|
||||
const lines = src.split('\n'); const l = lines[f.line - 1];
|
||||
lines[f.line - 1] = l.slice(0, f.col - 1) + f.text + l.slice(f.endCol == null ? l.length : f.endCol - 1);
|
||||
@@ -68,7 +68,7 @@ function applyFix(src, f) {
|
||||
const kinds = (line) => tokenizeMojo(line)[0].filter((t) => t.cls).map((t) => `${t.cls.replace('tok-', '')}:${t.text}`);
|
||||
|
||||
test('highlighting agrees with the Mojo grammar\'s own tests', () => {
|
||||
const { cases } = JSON.parse(fs.readFileSync(new URL('../mojo/corpus/syntax/cases.json', import.meta.url), 'utf8'));
|
||||
const { cases } = JSON.parse(fs.readFileSync(new URL('../library/mojo/corpus/syntax/cases.json', import.meta.url), 'utf8'));
|
||||
assert.ok(cases.length >= 20);
|
||||
for (const c of cases) {
|
||||
const toks = tokenizeMojo(c.text)[0];
|
||||
@@ -216,7 +216,7 @@ test('each exercise\'s Mojo prints, in the interpreter, what the exercise expect
|
||||
});
|
||||
|
||||
test('the Compile button builds with exactly the flags a passing probe verified', () => {
|
||||
const text = fs.readFileSync(new URL('../mojo/probes/godbolt-compile-button.mojo', import.meta.url), 'utf8');
|
||||
const text = fs.readFileSync(new URL('../library/mojo/probes/godbolt-compile-button.mojo', import.meta.url), 'utf8');
|
||||
const args = /^# args: (.*)$/m.exec(text)[1].trim();
|
||||
assert.equal(BUILD_ARGS.O0, args, 'change the probe and re-verify before changing the button');
|
||||
const g = goldens.find((x) => x.firstItem === 'probes/godbolt-compile-button');
|
||||
|
||||
@@ -45,7 +45,7 @@ test('each rule\'s example: both programs read, run, and print the same; the rul
|
||||
});
|
||||
|
||||
test('grounding: every standard-library method a rewrite names is in the harvested index', () => {
|
||||
const index = JSON.parse(fs.readFileSync(path.join(root, 'mojo', 'corpus', 'stdtypes', 'stdtypes.json'), 'utf8')).structs;
|
||||
const index = JSON.parse(fs.readFileSync(path.join(root, 'library', 'mojo', 'corpus', 'stdtypes', 'stdtypes.json'), 'utf8')).structs;
|
||||
let n = 0;
|
||||
for (const r of RULES) for (const [type, method] of r.apis) { n++; assert.ok(index[type]?.methods.includes(method), `${r.id}: ${type}.${method}`); }
|
||||
assert.ok(n >= 4);
|
||||
@@ -63,8 +63,8 @@ function mojoFiles(dir, out = []) {
|
||||
// (a variable declared apart from its value to show how `var` works, `imm` written out to name the convention). Each
|
||||
// number is a reviewed count; a rule that starts firing more than this on code that is already good is too noisy.
|
||||
const ALLOWED = { 'declare-then-assign': 10, 'augmented-assign': 6, 'argument-convention': 4, 'unneeded-raises': 3, 'comptime-constant': 3, 'codepoint-loop': 0, 'reserve': 2, 'transfer-last-use': 2, 'explicit-copy': 0 };
|
||||
test('false-positive gate: over mojo/corpus/manual/ the rules fire no more than the reviewed allowlist', () => {
|
||||
const files = mojoFiles(path.join(root, 'mojo', 'corpus', 'manual'));
|
||||
test('false-positive gate: over library/mojo/corpus/manual/ the rules fire no more than the reviewed allowlist', () => {
|
||||
const files = mojoFiles(path.join(root, 'library', 'mojo', 'corpus', 'manual'));
|
||||
assert.ok(files.length >= 100, `${files.length} programs`);
|
||||
const counts = {};
|
||||
for (const f of files) for (const x of findPractices(fs.readFileSync(f, 'utf8'))) counts[x.rule] = (counts[x.rule] ?? 0) + 1;
|
||||
@@ -112,8 +112,8 @@ test('idiomatic version: for every exercise the safe rewrites keep the program c
|
||||
assert.ok(changed >= 5 && compared >= 5, `${changed} changed, ${compared} compared`);
|
||||
});
|
||||
|
||||
test('Developer area: applying every fix to each mojo/local program keeps it checking and printing the same', () => {
|
||||
const dir = path.join(root, 'mojo', 'local');
|
||||
test('Developer area: applying every fix to each library/mojo/local program keeps it checking and printing the same', () => {
|
||||
const dir = path.join(root, 'library', 'mojo', 'local');
|
||||
let fired = 0;
|
||||
for (const f of fs.readdirSync(dir).filter((x) => x.endsWith('.mojo'))) {
|
||||
const src = fs.readFileSync(path.join(dir, f), 'utf8');
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
// The prover's "proved" must be a proof. Two gates hold it to that:
|
||||
//
|
||||
// 1. The regression programs in tests/prover/ each name, in a `// MUST-NOT-PROVE: <kind>@<line>`
|
||||
// 1. The regression programs in library/pseudo/prover/ each name, in a `// MUST-NOT-PROVE: <kind>@<line>`
|
||||
// header, an obligation that a run of the program breaks. Each one was proved by an unsound
|
||||
// rule once; the rule is fixed, and the obligation may never be proved again. A program whose
|
||||
// fix was to the language instead (a run that now stops where it used to go on outside what a
|
||||
@@ -10,7 +10,7 @@
|
||||
// line and column) or by running the program as written (matched by kind and line).
|
||||
//
|
||||
// A failure here is a soundness bug in src/engines/pseudo/vcgen.js or solver.js: fix the rule,
|
||||
// never the test. Add the program that found it to tests/prover/.
|
||||
// never the test. Add the program that found it to library/pseudo/prover/.
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import fs from 'node:fs';
|
||||
@@ -21,8 +21,8 @@ import { checkProperties } from '../dist/engines/pseudo/testing.js';
|
||||
import { PROBLEMS } from '../dist/common/problems.js';
|
||||
import { LESSONS, solutionOf } from '../dist/curriculum/index.js';
|
||||
|
||||
const PROVER_DIR = 'tests/prover';
|
||||
const CORPUS_DIR = 'tests/corpus';
|
||||
const PROVER_DIR = 'library/pseudo/prover';
|
||||
const CORPUS_DIR = 'library/pseudo/programs';
|
||||
|
||||
/** The verifier's obligation kinds against the runtime error kinds a run or the fuzzer reports. */
|
||||
const RUNTIME_KIND = {
|
||||
@@ -127,7 +127,7 @@ test('nothing the prover proves is broken by a run or by generated inputs', () =
|
||||
test('canary: after a program that runs to its end, ASSERT 1 == 2 is never proved', () => {
|
||||
// A false claim proved at a point every run reaches means the checker holds a contradiction
|
||||
// there: some rule assumed a fact a run can break. This finds such a rule even when no
|
||||
// program happens to assert something false after it (tests/prover/foreach-empty.pseudo).
|
||||
// program happens to assert something false after it (library/pseudo/prover/foreach-empty.pseudo).
|
||||
const problems = [];
|
||||
let canaries = 0;
|
||||
for (const p of programs()) {
|
||||
|
||||
@@ -1,9 +0,0 @@
|
||||
// FILL stops the program on a negative count, so the call is an
|
||||
// obligation, not a fact the checker may assume.
|
||||
// MUST-NOT-PROVE: argument@6
|
||||
FUNCTION F(N : INTEGER) RETURNS INTEGER
|
||||
DECLARE Xs : LIST OF INTEGER
|
||||
Xs <- FILL(N, 0)
|
||||
RETURN LENGTH(Xs)
|
||||
ENDFUNCTION
|
||||
OUTPUT F(-1)
|
||||
@@ -1,10 +0,0 @@
|
||||
// The prover treats a FLOAT as a number: Y == Y, and X < X + 1.0 or not.
|
||||
// Infinity and NaN are not numbers in that sense. A run that let 1.0E308 *
|
||||
// 10.0 become infinity, and X - X become NaN, broke both claims while the
|
||||
// checker proved them. Such a run now stops at the overflow instead.
|
||||
// RUN-STOPS: overflow@7
|
||||
DECLARE X, Y : FLOAT
|
||||
X <- 1.0E308 * 10.0
|
||||
Y <- X - X
|
||||
ASSERT Y == Y
|
||||
OUTPUT Y
|
||||
@@ -1,8 +0,0 @@
|
||||
// A whole number stored in a FLOAT32 is rounded to the nearest single:
|
||||
// 16777217 becomes 16777216. A rule that kept the INTEGER's value for the
|
||||
// FLOAT32 would prove this ASSERT, and the run breaks it.
|
||||
// MUST-NOT-PROVE: assert@8
|
||||
DECLARE N : INTEGER <- 16777217
|
||||
DECLARE X : FLOAT32
|
||||
X <- N
|
||||
ASSERT X == N
|
||||
@@ -1,13 +0,0 @@
|
||||
// The way out of a FOR EACH loop includes the case of no pass at all. A
|
||||
// checker that kept "X is in Xs" on the way out held FALSE after looping over
|
||||
// an empty list, and proved anything, even 1 == 2.
|
||||
// MUST-NOT-PROVE: assert@12
|
||||
DECLARE Xs : LIST OF INTEGER
|
||||
DECLARE S : INTEGER
|
||||
Xs <- []
|
||||
S <- 0
|
||||
FOR EACH X IN Xs
|
||||
S <- S + X
|
||||
NEXT X
|
||||
ASSERT 1 == 2
|
||||
OUTPUT S
|
||||
@@ -1,23 +0,0 @@
|
||||
// The checker's own invariant guesses must be checked to a fixed point.
|
||||
// Each pass shifts a value one variable further down a chain, so "F <= 0"
|
||||
// survives the first four rounds of guessing and fails on the fifth. A
|
||||
// checker that stopped guessing after four rounds assumed it, and proved
|
||||
// the false ASSERT below.
|
||||
// MUST-NOT-PROVE: assert@22
|
||||
DECLARE A, B, C, D, E, F : INTEGER
|
||||
A <- 0
|
||||
B <- 0
|
||||
C <- 0
|
||||
D <- 0
|
||||
E <- 0
|
||||
F <- 0
|
||||
FOR I <- 0 TO 10
|
||||
F <- E
|
||||
E <- D
|
||||
D <- C
|
||||
C <- B
|
||||
B <- A
|
||||
A <- A + 1
|
||||
NEXT I
|
||||
ASSERT F <= 0
|
||||
OUTPUT F
|
||||
@@ -1,7 +0,0 @@
|
||||
// With USE IEEE a FLOAT can be NaN, and NaN == NaN is FALSE. The prover's
|
||||
// rule that every number equals itself does not hold for NaN, so nothing in
|
||||
// a program that says USE IEEE may be marked proved.
|
||||
// MUST-NOT-PROVE: assert@7
|
||||
USE IEEE
|
||||
DECLARE X : FLOAT <- NAN()
|
||||
ASSERT X == X
|
||||
@@ -1,7 +0,0 @@
|
||||
// INT8 holds -128 to 127. X + 1 for X = 127 is 128, which does not fit, so
|
||||
// the run stops there. A rule that treated the sum as an exact whole number
|
||||
// with no range would prove it fits without a REQUIRE to guarantee it.
|
||||
// MUST-NOT-PROVE: overflow@6
|
||||
FUNCTION Inc(X : INT8) RETURNS INT8
|
||||
RETURN X + 1
|
||||
ENDFUNCTION
|
||||
@@ -1,6 +0,0 @@
|
||||
// RAND(X) for a negative X gives a value in (X, 0], not [0, X).
|
||||
// MUST-NOT-PROVE: assert@5
|
||||
DECLARE R : FLOAT
|
||||
R <- RAND(-1.0)
|
||||
ASSERT R >= 0.0
|
||||
OUTPUT R
|
||||
@@ -1,7 +0,0 @@
|
||||
// RAND(0.0) gives 0.0. A checker that assumed 0 <= R < 0.0 held a
|
||||
// contradiction from here on, and proved anything, even 1 == 2.
|
||||
// MUST-NOT-PROVE: assert@6
|
||||
DECLARE R : FLOAT
|
||||
R <- RAND(0.0)
|
||||
ASSERT 1 == 2
|
||||
OUTPUT R
|
||||
@@ -1,8 +0,0 @@
|
||||
// RANDINT(A, B) stops the program when [A, B) is empty.
|
||||
// MUST-NOT-PROVE: argument@5
|
||||
FUNCTION G(A : INTEGER) RETURNS INTEGER
|
||||
DECLARE R : INTEGER
|
||||
R <- RANDINT(A, 3)
|
||||
RETURN R
|
||||
ENDFUNCTION
|
||||
OUTPUT G(5)
|
||||
@@ -67,7 +67,7 @@ function report(x) {
|
||||
const out = [];
|
||||
out.push('# Translation coverage', '',
|
||||
'<!-- Written by tests/sync-coverage.test.mjs. Do not edit; rerun `npm test` to refresh. -->', '',
|
||||
`Each translator in \`src/sync/\` is run over every exercise with pseudo (${ex}), every program in \`tests/corpus/\` (${all.length - ex - fx}), and ${fx} one-construct fixtures (\`tests/helpers/sync-programs.mjs\`). ${all.length - ok.length} of the ${all.length} have pseudo that does not read, by design (they teach the notation's error messages), and are left out below. That leaves **${ok.length} programs**.`, '',
|
||||
`Each translator in \`src/sync/\` is run over every exercise with pseudo (${ex}), every program in \`library/pseudo/programs/\` (${all.length - ex - fx}), and ${fx} one-construct fixtures (\`tests/helpers/sync-programs.mjs\`). ${all.length - ok.length} of the ${all.length} have pseudo that does not read, by design (they teach the notation's error messages), and are left out below. That leaves **${ok.length} programs**.`, '',
|
||||
'| From pseudo to | Says it completely | Says it with a gap or a checker error | Cannot say it |', '| --- | ---: | ---: | ---: |',
|
||||
`| Mojo | ${rows.mojo.full} | ${new Set(rows.mojo.gaps.map((g) => g[0])).size + rows.mojo.checker} | ${rows.mojo.no.length} |`,
|
||||
`| lingo | ${rows.lingo.full} | 0 | ${ok.length - rows.lingo.full} |`,
|
||||
|
||||
@@ -18,7 +18,7 @@ import { MOJO_STD_STRUCTS } from '../dist/mojo/generated/types.js';
|
||||
globalThis.localStorage = { getItem() { return null; }, setItem() { }, removeItem() { } };
|
||||
|
||||
const here = path.dirname(fileURLToPath(import.meta.url));
|
||||
const corpusDir = path.join(here, 'corpus');
|
||||
const corpusDir = path.join(here, '..', 'library', 'pseudo', 'programs');
|
||||
const snapDir = path.join(here, 'snapshots', 'sync-mojo');
|
||||
|
||||
/**
|
||||
|
||||
Reference in new issue
Block a user