summaryrefslogtreecommitdiff
path: root/chapter25/docs
diff options
context:
space:
mode:
Diffstat (limited to 'chapter25/docs')
-rw-r--r--chapter25/docs/24-grammar.ja.md (renamed from chapter25/docs/25-grammar.ja.md)21
-rw-r--r--chapter25/docs/24-grammar.md (renamed from chapter25/docs/25-grammar.md)21
-rw-r--r--chapter25/docs/examples/A_helloWorld.smp3
-rw-r--r--chapter25/docs/examples/BubbleSort.smp39
-rw-r--r--chapter25/docs/examples/Capitalize.smp22
-rw-r--r--chapter25/docs/examples/Dijkstra.smp72
-rw-r--r--chapter25/docs/examples/FileIO.smp50
7 files changed, 36 insertions, 192 deletions
diff --git a/chapter25/docs/25-grammar.ja.md b/chapter25/docs/24-grammar.ja.md
index 9e9fb820..fd3fa232 100644
--- a/chapter25/docs/25-grammar.ja.md
+++ b/chapter25/docs/24-grammar.ja.md
@@ -1,14 +1,12 @@
-# 第25章の文法
+# 第24章の文法
-[English](25-grammar.md) | 日本語
+[English](24-grammar.md) | 日本語
```antlrv4
grammar SimpleLanguage;
// Name lookup, assignable operands, type compatibility, and access permissions
// are checked by the compiler in addition to these syntax rules.
-// A file is a compilation unit; its path supplies its namespace.
-// Qualified names resolve nested types and other units without an import keyword.
program : statement* EOF ;
block : '{' statement* '}' ;
@@ -38,14 +36,11 @@ forStatement
;
structDeclaration : 'struct' IDENTIFIER '{' structMember* '}' ';' ;
-structMember : constructorDeclaration | methodDeclaration | statement ;
-
-// The constructor name must match the enclosing struct's name.
-constructorDeclaration : 'new' IDENTIFIER '=' functionExpression ';' ;
+structMember : methodDeclaration | statement ;
// A method is an ordinary fixed function binding in a struct definition.
// The compiler supplies self; it is not written in parameterList.
-// Function types and expressions both receive their implicit receiver here.
+// The general declaration rule also admits explicitly typed function fields.
methodDeclaration : 'val' bindingModifier? IDENTIFIER '=' functionExpression ';' ;
declaration : declarationType binding (',' binding)* ;
@@ -53,8 +48,7 @@ declarationType : type | 'var' | 'val' ;
binding : bindingModifier? IDENTIFIER ('=' initializer)? ;
bindingModifier : '!' | '~' ;
// A declaration initializer consisting of the string "C" declares an extern
-// symbol: a function, or explicit numeric native storage. Ordinary strings
-// elsewhere are array-valued expressions.
+// symbol. Ordinary strings elsewhere are array-valued expressions.
initializer : assignment ;
// The prefix qualifies the named struct reference, not an enclosing array.
@@ -157,9 +151,8 @@ functionType
callSuffix : '(' argumentList? ')' ;
argumentList : assignment (',' assignment)* ','? ;
-// Allocation invokes the declared constructor; inline initializer blocks from
-// earlier chapters are replaced by constructor arguments.
-newExpression : 'new' type ('[' assignment ']' | callSuffix)? ;
+// Struct initialization uses a block; array allocation supplies a length.
+newExpression : 'new' type ('[' assignment ']' | block)? ;
INTEGER_LITERAL : '0' | [1-9] DIGIT* ;
FLOAT_LITERAL : DIGIT+ ('.' DIGIT* ('e' DIGIT+)? | 'e' '-'? DIGIT+) ;
diff --git a/chapter25/docs/25-grammar.md b/chapter25/docs/24-grammar.md
index 065cf051..22867355 100644
--- a/chapter25/docs/25-grammar.md
+++ b/chapter25/docs/24-grammar.md
@@ -1,14 +1,12 @@
-# Grammar for Chapter 25
+# Grammar for Chapter 24
-English | [日本語](25-grammar.ja.md)
+English | [日本語](24-grammar.ja.md)
```antlrv4
grammar SimpleLanguage;
// Name lookup, assignable operands, type compatibility, and access permissions
// are checked by the compiler in addition to these syntax rules.
-// A file is a compilation unit; its path supplies its namespace.
-// Qualified names resolve nested types and other units without an import keyword.
program : statement* EOF ;
block : '{' statement* '}' ;
@@ -38,14 +36,11 @@ forStatement
;
structDeclaration : 'struct' IDENTIFIER '{' structMember* '}' ';' ;
-structMember : constructorDeclaration | methodDeclaration | statement ;
-
-// The constructor name must match the enclosing struct's name.
-constructorDeclaration : 'new' IDENTIFIER '=' functionExpression ';' ;
+structMember : methodDeclaration | statement ;
// A method is an ordinary fixed function binding in a struct definition.
// The compiler supplies self; it is not written in parameterList.
-// Function types and expressions both receive their implicit receiver here.
+// The general declaration rule also admits explicitly typed function fields.
methodDeclaration : 'val' bindingModifier? IDENTIFIER '=' functionExpression ';' ;
declaration : declarationType binding (',' binding)* ;
@@ -53,8 +48,7 @@ declarationType : type | 'var' | 'val' ;
binding : bindingModifier? IDENTIFIER ('=' initializer)? ;
bindingModifier : '!' | '~' ;
// A declaration initializer consisting of the string "C" declares an extern
-// symbol: a function, or explicit numeric native storage. Ordinary strings
-// elsewhere are array-valued expressions.
+// symbol. Ordinary strings elsewhere are array-valued expressions.
initializer : assignment ;
// The prefix qualifies the named struct reference, not an enclosing array.
@@ -157,9 +151,8 @@ functionType
callSuffix : '(' argumentList? ')' ;
argumentList : assignment (',' assignment)* ','? ;
-// Allocation invokes the declared constructor; inline initializer blocks from
-// earlier chapters are replaced by constructor arguments.
-newExpression : 'new' type ('[' assignment ']' | callSuffix)? ;
+// Struct initialization uses a block; array allocation supplies a length.
+newExpression : 'new' type ('[' assignment ']' | block)? ;
INTEGER_LITERAL : '0' | [1-9] DIGIT* ;
FLOAT_LITERAL : DIGIT+ ('.' DIGIT* ('e' DIGIT+)? | 'e' '-'? DIGIT+) ;
diff --git a/chapter25/docs/examples/A_helloWorld.smp b/chapter25/docs/examples/A_helloWorld.smp
index 4ed6abdf..07ff935f 100644
--- a/chapter25/docs/examples/A_helloWorld.smp
+++ b/chapter25/docs/examples/A_helloWorld.smp
@@ -1,2 +1,3 @@
-sys.io.p("Hello, World!\n");
+// -*- mode: java; -*-
+sys.io.p("Hello, World!");
return 0;
diff --git a/chapter25/docs/examples/BubbleSort.smp b/chapter25/docs/examples/BubbleSort.smp
index ca6906b5..938e3181 100644
--- a/chapter25/docs/examples/BubbleSort.smp
+++ b/chapter25/docs/examples/BubbleSort.smp
@@ -1,3 +1,4 @@
+// -*- mode: java; -*-
// An implementation of
// https://sampleprograms.io/projects/bubble-sort/
@@ -5,32 +6,32 @@
// Bubble sort, with reading (parsing) and writing (formatting) the data.
val sort = { !sys.aryi64 nums ->
- sys.aryi64?! more = nums;
- while( more ) {
- more = null;
+ var done = false;
+ while( !done ) {
+ done = true;
for( var i = 0; i < nums.len-1; i++ )
- if( nums.buf[i] > nums.buf[i+1] )
- more = nums.swap(i,i+1);
+ if( nums.buf[i] > nums.buf[i+1] ) {
+ int tmp = nums.buf[i];
+ nums.buf[i] = nums.buf[i+1];
+ nums.buf[i+1] = tmp; // Swap
+ done = false;
+ }
}
};
-// Read one process argument of the form "[ 4, 3, 2, 1]" and print it sorted.
-// args[0] is the executable name, as with native C argc/argv.
-val main = { u8[~][] args ->
- val usage = { ->
- sys.io.p("Usage: please provide a list of at least two integers to sort in the format \"[1, 2, 3, 4, 5]\"\n");
- return 0;
- };
- if( args# != 2 ) return usage();
-
- var nums = sys.aryi64.parseAryI64(args[1]);
- if( !nums ) return usage();
- if( nums.len < 2 ) return usage();
+// Read from stdin a line of the form "[ 4, 3, 2, 1]" and print it sorted.
+val main = { ->
+ // Parse array of numbers from stdin
+ var nums = sys.parseAryI64( sys.io.stdin() );
+ if( !nums ) {
+ sys.io.p("stdin must look like [4, 3, 2, 1]");
+ return 1;
+ }
// Bubble sort array of integers
sort(nums);
- // Print the same bracketed array-list format accepted as input.
- nums.str().add('\n').write(1);
+ // Print a list of numbers to stdout
+ nums.str().write(1);
return 0;
};
diff --git a/chapter25/docs/examples/Capitalize.smp b/chapter25/docs/examples/Capitalize.smp
deleted file mode 100644
index 8e31c18f..00000000
--- a/chapter25/docs/examples/Capitalize.smp
+++ /dev/null
@@ -1,22 +0,0 @@
-
-// An implementation of
-// https://sampleprograms.io/projects/capitalize/
-
-val main = { u8[~][] args ->
- if( args# > 2 ) {
- sys.io.p("Use quotes around multiple strings.\n");
- return 0;
- }
- if( args# != 2 || args[1]# == 0 ) {
- sys.io.p("Usage: please provide a string\n");
- return 0;
- }
-
- u8[~] input = args[1];
- var output = new u8[input# + 1];
- sys.ary.copy(output,0,input,0,input#);
- output[0] = sys.char.toupper(input[0]);
- output[input#] = '\n';
- sys.io.p(output);
- return 0;
-};
diff --git a/chapter25/docs/examples/Dijkstra.smp b/chapter25/docs/examples/Dijkstra.smp
deleted file mode 100644
index fd595eb5..00000000
--- a/chapter25/docs/examples/Dijkstra.smp
+++ /dev/null
@@ -1,72 +0,0 @@
-
-// An implementation of
-// https://sampleprograms.io/projects/dijkstra/
-
-val shortestPath = { !sys.aryi64 matrix, int nodes, int src, int dst ->
- i64 infinity = (1 << 63)-1;
- var dist = new i64[nodes];
- var visited = new sys.adt.bitset();
- // All nodes are infinitely far from each other
- for( int i=0; i<nodes; i++ ) dist[i] = infinity;
- // Starting point is zero far from starting point
- dist[src] = 0;
-
- i64 result = -1;
- int count = 0;
- while( count < nodes && result < 0 ) {
- int nearest = -1;
- i64 best = infinity;
- for( int node=0; node<nodes; node++ )
- if( !visited.get(node) && dist[node] < best ) {
- nearest = node;
- best = dist[node];
- }
- if( nearest < 0 ) count = nodes;
- else {
- if( nearest == dst ) return best;
- visited.set(nearest);
- for( int node=0; node<nodes; node++ ) {
- i64 weight = matrix.get(nearest*nodes + node);
- if( weight > 0 && !visited.get(node) && best+weight < dist[node] )
- dist[node] = best+weight;
- }
- }
- count++;
- }
- return result;
-};
-
-val usage = { ->
- sys.io.p("Usage: please provide three inputs: a serialized matrix, a source node and a destination node\n");
- return 0;
-};
-
-val main = { u8[~][] args ->
- // Exactly 3 args
- if( args# != 4 ) return usage();
- // First is a serialized square matrix of positive numbers
- var matrix = sys.aryi64.parseAryI64(args[1]);
- if( !matrix ) return usage();
- if( !matrix.len ) return usage();
- // All numbers are positive
- for( int i=0; i<matrix.len; i++ )
- if( matrix.get(i) < 0 ) return usage();
- // Matrix is square
- int nodes = 0;
- while( nodes*nodes < matrix.len ) nodes++;
- if( nodes*nodes != matrix.len )
- return usage(); // Not a square matrix
-
- // src,dst are values within the matrix
- i64 src = sys.aryu8.atoi(args[2]);
- i64 dst = sys.aryu8.atoi(args[3]);
- if( src < 0 || src >= nodes || dst < 0 || dst >= nodes )
- return usage(); // Source and destination land within the graph
-
- i64 cost = shortestPath(matrix,nodes,src,dst);
- if( cost >= 0 ) {
- new sys.aryu8().num(cost).add('\n').write(1);
- return 0;
- }
- return usage();
-};
diff --git a/chapter25/docs/examples/FileIO.smp b/chapter25/docs/examples/FileIO.smp
deleted file mode 100644
index e48d435b..00000000
--- a/chapter25/docs/examples/FileIO.smp
+++ /dev/null
@@ -1,50 +0,0 @@
-
-// An implementation of
-// https://sampleprograms.io/projects/file-input-output/
-
-val FILE = "output.txt";
-
-val main = { u8[~][] args ->
- var str = new sys.aryu8();
- str.addAry("Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.\n");
- str.addAry("Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.\n");
- str.addAry("Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur.\n");
- str.addAry("Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.\n");
-
- // Create
- i32 fd = sys.io.create(FILE);
- if( fd == -1 ) return _error();
- // Write
- int wrote = sys.io.writeOff(fd,str.buf,0,str.len);
- if( wrote == -1 ) return _error();
- if( wrote != str.len ) return _error2(-2);
- // Close
- if( sys.io.close(fd) != 0 ) return _error();
-
- // Open
- i32 fd2 = sys.io.open(FILE);
- if( fd2 == -1 ) return _error();
- // Read
- var got = sys.io.read(fd2);
- if( got# != str.len ) return _error2(-3);
- // Close
- if( sys.io.close(fd2) != 0 ) return _error();
-
- // Check contents are equal
- if( sys.ary.cmp(got,0,str.buf,0,str.len) )
- return _error2(-4);
-
- // Remove
- if( sys.io.remove(FILE) != 0 ) return _error();
-
- sys.io.p("File I/O succeeded\n");
- return 0;
-};
-
-val _error2 = { i32 errno ->
- sys.io.remove(FILE);
- new sys.aryu8().addAry("Failed with error code ").num(errno).add('\n').write(sys.libc.STDERR);
- sys.libc._exit(errno);
-};
-
-val _error = { -> _error2(sys.libc.errno()); };