Questions and answers
Each answer holds a program that compiles, and the target code below it is the output of the compiler for that program.
How do I fill an array?
Section titled “How do I fill an array?”When the items are known, write an array literal. The literal has two forms.
([] a b c) takes the element type from the items. ([] _:T (a b c)) states
the type, and the marker _:T must be followed by a group in parentheses.
class Main { sfn main:void () { ; One statement, and the compiler knows the size. def numbers:[int] ([] 1 2 3 4 5)
; A literal with an explicit element type needs a parenthesised group. def names:[string] ([] _:string ("Ada" "Alan" "Grace"))
print ("numbers " + (array_length numbers)) print ("first name " + (itemAt names 0)) }}const numbers = [1, 2, 3, 4, 5];const names = ["Ada", "Alan", "Grace"];console.log("numbers " + numbers.length);console.log("first name " + names[0]);The complete file
class Main { constructor() { }}/* static JavaSript main routine at the end of the JS file */function __js_main() { const numbers = [1, 2, 3, 4, 5]; const names = ["Ada", "Alan", "Grace"]; console.log("numbers " + numbers.length); console.log("first name " + names[0]);}__js_main();const numbers : Array<number> = [1, 2, 3, 4, 5];const names : Array<string> = ["Ada", "Alan", "Grace"];console.log("numbers " + numbers.length);console.log("first name " + names[0]);The complete file
export class Main { constructor() { }}/* static JavaSript main routine at the end of the JS file */function __js_main() { const numbers : Array<number> = [1, 2, 3, 4, 5]; const names : Array<string> = ["Ada", "Alan", "Grace"]; console.log("numbers " + numbers.length); console.log("first name " + names[0]);}__js_main();var numbers []int64= []int64 {int64(1), int64(2), int64(3), int64(4), int64(5)};var names []string= []string {"Ada", "Alan", "Grace"};fmt.Println( strings.Join([]string{ "numbers ",strconv.FormatInt(int64(len(numbers)), 10) }, "") )fmt.Println( "first name " + names[int64(0)] )The complete file
package mainimport ( "strings" "strconv" "fmt")type Main struct {}
func CreateNew_Main() *Main { me := new(Main) return me;}func main() { var numbers []int64= []int64 {int64(1), int64(2), int64(3), int64(4), int64(5)}; var names []string= []string {"Ada", "Alan", "Grace"}; fmt.Println( strings.Join([]string{ "numbers ",strconv.FormatInt(int64(len(numbers)), 10) }, "") ) fmt.Println( "first name " + names[int64(0)] )}let __rg_main_thread = std::thread::Builder::new().stack_size(512 * 1024 * 1024) .spawn(__rg_main_body).expect("could not start the main thread");__rg_main_thread.join().expect("main thread panicked");The complete file
#![allow(dead_code)]#![allow(unused_mut)]
#[derive(Clone)]struct Main {}impl Main { pub fn new() -> Self { Self { } }}fn main() { let __rg_main_thread = std::thread::Builder::new().stack_size(512 * 1024 * 1024) .spawn(__rg_main_body).expect("could not start the main thread"); __rg_main_thread.join().expect("main thread panicked");}fn __rg_main_body() { let mut numbers: Vec<i64> = vec![1, 2, 3, 4, 5]; let mut names: Vec<String> = vec!["Ada".to_string(), "Alan".to_string(), "Grace".to_string()]; println!("numbers {}", numbers.len() as i64); println!("first name {}", names[0].clone());}numbers = [1, 2, 3, 4, 5]names = ["Ada", "Alan", "Grace"]print("numbers " + str(len(numbers)))print("first name " + names[0])The complete file
# -*- coding: utf-8 -*-from __future__ import annotationsfrom typing import Optional
class Main: def __init__(self) -> None: pass# Main entry pointdef main(): numbers = [1, 2, 3, 4, 5] names = ["Ada", "Alan", "Grace"] print("numbers " + str(len(numbers))) print("first name " + names[0])if __name__ == "__main__": main()RgArgs.args = args;final ArrayList<Integer> numbers = new ArrayList<Integer>(Arrays.asList( new Integer[] {1, 2, 3, 4, 5}));final ArrayList<String> names = new ArrayList<String>(Arrays.asList( new String[] {"Ada", "Alan", "Grace"}));System.out.println(String.valueOf( "numbers " + numbers.size() ) );System.out.println(String.valueOf( "first name " + names.get(0) ) );The complete file
import java.util.*;import java.io.*;
public class Main {
public static void main(String [] args ) { RgArgs.args = args; final ArrayList<Integer> numbers = new ArrayList<Integer>(Arrays.asList( new Integer[] {1, 2, 3, 4, 5})); final ArrayList<String> names = new ArrayList<String>(Arrays.asList( new String[] {"Ada", "Alan", "Grace"})); System.out.println(String.valueOf( "numbers " + numbers.size() ) ); System.out.println(String.valueOf( "first name " + names.get(0) ) ); }}
public class RgArgs { public static String[] args = new String[0];}__g_args = argsval numbers : MutableList<Int> = arrayListOf<Int>(1, 2, 3, 4, 5);val names : MutableList<String> = arrayListOf<String>("Ada", "Alan", "Grace");println( "numbers " + (numbers.size).toString() )println( "first name " + names[0] )The complete file
class Main {
}
var __g_args : Array<String> = arrayOf()
fun main(args : Array<String>) { __g_args = args val numbers : MutableList<Int> = arrayListOf<Int>(1, 2, 3, 4, 5); val names : MutableList<String> = arrayListOf<String>("Ada", "Alan", "Grace"); println( "numbers " + (numbers.size).toString() ) println( "first name " + names[0] )}__g_args = args;List<int> numbers = [1, 2, 3, 4, 5];List<String> names = ["Ada", "Alan", "Grace"];print( "numbers " + (numbers.length).toString() );print( "first name " + names[0] );The complete file
class Main {}
List<String> __g_args = <String>[];
void main(List<String> args) { __g_args = args; List<int> numbers = [1, 2, 3, 4, 5]; List<String> names = ["Ada", "Alan", "Grace"]; print( "numbers " + (numbers.length).toString() ); print( "first name " + names[0] );}let numbers : [Int] = [1, 2, 3, 4, 5]let names : [String] = ["Ada", "Alan", "Grace"]print("numbers " + String(numbers.count))print("first name " + names[0])The complete file
func ==(l: Main, r: Main) -> Bool { return l === r}final class Main : Hashable { func hash(into hasher: inout Hasher) { hasher.combine(ObjectIdentifier(self)) }}// Main entry pointfunc __main__swift() { let numbers : [Int] = [1, 2, 3, 4, 5] let names : [String] = ["Ada", "Alan", "Grace"] print("numbers " + String(numbers.count)) print("first name " + names[0])}__main__swift()List<int> numbers = new List<int> {1, 2, 3, 4, 5};List<String> names = new List<String> {"Ada", "Alan", "Grace"};Console.WriteLine("numbers " + numbers.Count);Console.WriteLine("first name " + names[0]);The complete file
using System;using System.Collections;using System.Collections.Generic;class Main { static void Main( string [] args ) { List<int> numbers = new List<int> {1, 2, 3, 4, 5}; List<String> names = new List<String> {"Ada", "Alan", "Grace"}; Console.WriteLine("numbers " + numbers.Count); Console.WriteLine("first name " + names[0]); }}std::vector<int> numbers = std::vector<int>{1, 2, 3, 4, 5};std::vector<std::string> names = std::vector<std::string>{std::string("Ada"), std::string("Alan"), std::string("Grace")};std::cout << std::string("numbers ") + std::to_string((int)(numbers.size())) << std::endl;std::cout << std::string("first name ") + names.at(0) << std::endl;return 0;The complete file
#include <memory>#include <vector>#include <iostream>#include <string>
// define classes here to avoid compiler errorsclass Main;
// header definitionsclass Main { public : /* class constructor */ Main( ); /* static methods */ static void main();};
int __g_argc;char **__g_argv;Main::Main( ) {}int main(int argc, char* argv[]) { __g_argc = argc; __g_argv = argv; std::vector<int> numbers = std::vector<int>{1, 2, 3, 4, 5}; std::vector<std::string> names = std::vector<std::string>{std::string("Ada"), std::string("Alan"), std::string("Grace")}; std::cout << std::string("numbers ") + std::to_string((int)(numbers.size())) << std::endl; std::cout << std::string("first name ") + names.at(0) << std::endl; return 0;}$numbers = array(1, 2, 3, 4, 5);$names = array("Ada", "Alan", "Grace");echo( "numbers " . count($numbers) . "\n");echo( "first name " . $names[0] . "\n");The complete file
<?php
class Main { function __construct( ) { }}/* static PHP main routine */$numbers = array(1, 2, 3, 4, 5);$names = array("Ada", "Alan", "Grace");echo( "numbers " . count($numbers) . "\n");echo( "first name " . $names[0] . "\n");val numbers : collection.mutable.ArrayBuffer[Int] = collection.mutable.ArrayBuffer(1, 2, 3, 4, 5)val names : collection.mutable.ArrayBuffer[String] = collection.mutable.ArrayBuffer("Ada", "Alan", "Grace")println( "numbers " + numbers.length )println( "first name " + names(0) )The complete file
import scala.collection.mutablecase class ScalaReturnValue(value:Any) extends Exception
// application main function for Mainobject AppMain extends App { val numbers : collection.mutable.ArrayBuffer[Int] = collection.mutable.ArrayBuffer(1, 2, 3, 4, 5) val names : collection.mutable.ArrayBuffer[String] = collection.mutable.ArrayBuffer("Ada", "Alan", "Grace") println( "numbers " + numbers.length ) println( "first name " + names(0) )}The compiler knows the number of items, so the target code holds one
statement: [1, 2, 3, 4, 5] in JavaScript, []int64 {…} in Go and vec![…]
in Rust.
How do I build an array while the program runs?
Section titled “How do I build an array while the program runs?”When the items come from a loop, from a file or from a calculation, the number of them is not known in advance. Use the operators that change the array.
| Operator | Function |
|---|---|
push |
Add an item to the end. |
set_at |
Replace the item at an index. |
remove_index |
Remove the item at an index. |
removeLast |
Remove the last item. |
clear |
Remove every item. |
insert |
Add an item at an index. |
class Main { sfn main:void () { ; The items are not known in advance, so the program adds them one at ; a time. def numbers:[int] def i 1 while (i < 4) { push numbers (i * 10) i = i + 1 } print ("after push " + (array_length numbers))
set_at numbers 0 99 print ("first " + (itemAt numbers 0))
removeLast numbers remove_index numbers 0 print ("left " + (array_length numbers))
clear numbers print ("after clear " + (array_length numbers)) }}let numbers = [];let i = 1;while (i < 4) { numbers.push(i * 10); i = i + 1;};console.log("after push " + numbers.length);numbers[0] = 99;console.log("first " + numbers[0]);numbers.pop();numbers.splice(0, 1).pop();console.log("left " + numbers.length);numbers.length = 0;console.log("after clear " + numbers.length);The complete file
class Main { constructor() { }}/* static JavaSript main routine at the end of the JS file */function __js_main() { let numbers = []; let i = 1; while (i < 4) { numbers.push(i * 10); i = i + 1; }; console.log("after push " + numbers.length); numbers[0] = 99; console.log("first " + numbers[0]); numbers.pop(); numbers.splice(0, 1).pop(); console.log("left " + numbers.length); numbers.length = 0; console.log("after clear " + numbers.length);}__js_main();let numbers : Array<number> | undefined = [];let i : number = 1;while (i < 4) { numbers.push(i * 10); i = i + 1;};console.log("after push " + numbers.length);numbers[0] = 99;console.log("first " + numbers[0]);numbers.pop();numbers.splice(0, 1).pop();console.log("left " + numbers.length);numbers.length = 0;console.log("after clear " + numbers.length);The complete file
export class Main { constructor() { }}/* static JavaSript main routine at the end of the JS file */function __js_main() { let numbers : Array<number> | undefined = []; let i : number = 1; while (i < 4) { numbers.push(i * 10); i = i + 1; }; console.log("after push " + numbers.length); numbers[0] = 99; console.log("first " + numbers[0]); numbers.pop(); numbers.splice(0, 1).pop(); console.log("left " + numbers.length); numbers.length = 0; console.log("after clear " + numbers.length);}__js_main();var numbers []int64 = make([]int64, 0);var i int64= int64(1);for i < int64(4) { numbers = append(numbers,i * int64(10)); i = i + int64(1);}fmt.Println( strings.Join([]string{ "after push ",strconv.FormatInt(int64(len(numbers)), 10) }, "") )numbers[int64(0)] = int64(99)fmt.Println( strings.Join([]string{ "first ",strconv.FormatInt(numbers[int64(0)], 10) }, "") )numbers = numbers[:len(numbers)-1];numbers = append(numbers[:int64(0)], numbers[int64(0)+1:]...)fmt.Println( strings.Join([]string{ "left ",strconv.FormatInt(int64(len(numbers)), 10) }, "") )numbers = numbers[:0]fmt.Println( strings.Join([]string{ "after clear ",strconv.FormatInt(int64(len(numbers)), 10) }, "") )The complete file
package mainimport ( "strings" "strconv" "fmt")
type GoNullable struct { value interface{} has_value bool}
type Main struct {}
func CreateNew_Main() *Main { me := new(Main) return me;}func main() { var numbers []int64 = make([]int64, 0); var i int64= int64(1); for i < int64(4) { numbers = append(numbers,i * int64(10)); i = i + int64(1); } fmt.Println( strings.Join([]string{ "after push ",strconv.FormatInt(int64(len(numbers)), 10) }, "") ) numbers[int64(0)] = int64(99) fmt.Println( strings.Join([]string{ "first ",strconv.FormatInt(numbers[int64(0)], 10) }, "") ) numbers = numbers[:len(numbers)-1]; numbers = append(numbers[:int64(0)], numbers[int64(0)+1:]...) fmt.Println( strings.Join([]string{ "left ",strconv.FormatInt(int64(len(numbers)), 10) }, "") ) numbers = numbers[:0] fmt.Println( strings.Join([]string{ "after clear ",strconv.FormatInt(int64(len(numbers)), 10) }, "") )}let __rg_main_thread = std::thread::Builder::new().stack_size(512 * 1024 * 1024) .spawn(__rg_main_body).expect("could not start the main thread");__rg_main_thread.join().expect("main thread panicked");The complete file
#![allow(dead_code)]
#[derive(Clone)]struct Main {}impl Main { pub fn new() -> Self { Self { } }}fn main() { let __rg_main_thread = std::thread::Builder::new().stack_size(512 * 1024 * 1024) .spawn(__rg_main_body).expect("could not start the main thread"); __rg_main_thread.join().expect("main thread panicked");}fn __rg_main_body() { let mut numbers: Vec<i64> = Vec::new(); let mut i: i64 = 1; while i < 4 { numbers.push(i * 10); i += 1; }; println!("after push {}", numbers.len() as i64); numbers[0] = 99; println!("first {}", numbers[0]); numbers.pop(); numbers.remove((0) as usize); println!("left {}", numbers.len() as i64); numbers.clear(); println!("after clear {}", numbers.len() as i64);}numbers = []i = 1while i < 4: numbers.append(i * 10) i = i + 1;print("after push " + str(len(numbers)))numbers[0] = 99print("first " + str(numbers[0]))numbers.pop()numbers.pop(0)print("left " + str(len(numbers)))numbers.clear()print("after clear " + str(len(numbers)))The complete file
# -*- coding: utf-8 -*-from __future__ import annotationsfrom typing import Optional
class Main: def __init__(self) -> None: pass# Main entry pointdef main(): numbers = [] i = 1 while i < 4: numbers.append(i * 10) i = i + 1; print("after push " + str(len(numbers))) numbers[0] = 99 print("first " + str(numbers[0])) numbers.pop() numbers.pop(0) print("left " + str(len(numbers))) numbers.clear() print("after clear " + str(len(numbers)))if __name__ == "__main__": main()RgArgs.args = args;ArrayList<Integer> numbers = new ArrayList<Integer>();Integer i = 1;while (i < 4) { numbers.add(i * 10); i = i + 1;}System.out.println(String.valueOf( "after push " + numbers.size() ) );numbers.set(0, 99);System.out.println(String.valueOf( "first " + numbers.get(0) ) );numbers.remove(numbers.size() - 1);numbers.remove((int)(0));System.out.println(String.valueOf( "left " + numbers.size() ) );numbers.clear();System.out.println(String.valueOf( "after clear " + numbers.size() ) );The complete file
import java.util.*;import java.io.*;
public class Main {
public static void main(String [] args ) { RgArgs.args = args; ArrayList<Integer> numbers = new ArrayList<Integer>(); Integer i = 1; while (i < 4) { numbers.add(i * 10); i = i + 1; } System.out.println(String.valueOf( "after push " + numbers.size() ) ); numbers.set(0, 99); System.out.println(String.valueOf( "first " + numbers.get(0) ) ); numbers.remove(numbers.size() - 1); numbers.remove((int)(0)); System.out.println(String.valueOf( "left " + numbers.size() ) ); numbers.clear(); System.out.println(String.valueOf( "after clear " + numbers.size() ) ); }}
public class RgArgs { public static String[] args = new String[0];}__g_args = argsvar numbers : MutableList<Int> = arrayListOf();var i : Int = 1;while (i < 4) { numbers.add(i * 10); i = i + 1;}println( "after push " + (numbers.size).toString() )numbers[0] = 99println( "first " + (numbers[0]).toString() )numbers.removeAt(numbers.size - 1)numbers.removeAt(0)println( "left " + (numbers.size).toString() )numbers.clear()println( "after clear " + (numbers.size).toString() )The complete file
class Main {
}
var __g_args : Array<String> = arrayOf()
fun main(args : Array<String>) { __g_args = args var numbers : MutableList<Int> = arrayListOf(); var i : Int = 1; while (i < 4) { numbers.add(i * 10); i = i + 1; } println( "after push " + (numbers.size).toString() ) numbers[0] = 99 println( "first " + (numbers[0]).toString() ) numbers.removeAt(numbers.size - 1) numbers.removeAt(0) println( "left " + (numbers.size).toString() ) numbers.clear() println( "after clear " + (numbers.size).toString() )}__g_args = args;List<int> numbers = [];int i = 1;while (i < 4) { numbers.add(i * 10); i = i + 1;}print( "after push " + (numbers.length).toString() );numbers[0] = 99;print( "first " + (numbers[0]).toString() );numbers.removeLast();numbers.removeAt(0);print( "left " + (numbers.length).toString() );numbers.clear();print( "after clear " + (numbers.length).toString() );The complete file
class Main {}
List<String> __g_args = <String>[];
void main(List<String> args) { __g_args = args; List<int> numbers = []; int i = 1; while (i < 4) { numbers.add(i * 10); i = i + 1; } print( "after push " + (numbers.length).toString() ); numbers[0] = 99; print( "first " + (numbers[0]).toString() ); numbers.removeLast(); numbers.removeAt(0); print( "left " + (numbers.length).toString() ); numbers.clear(); print( "after clear " + (numbers.length).toString() );}var numbers : [Int] = [Int]()var i : Int = 1while (i < 4) { numbers.append(i * 10) i = i + 1;}print("after push " + String(numbers.count))numbers[0] = 99print("first " + String(numbers[0]))numbers.removeLast()numbers.remove(at:0)print("left " + String(numbers.count))numbers.removeAll()print("after clear " + String(numbers.count))The complete file
func ==(l: Main, r: Main) -> Bool { return l === r}final class Main : Hashable { func hash(into hasher: inout Hasher) { hasher.combine(ObjectIdentifier(self)) }}// Main entry pointfunc __main__swift() { var numbers : [Int] = [Int]() var i : Int = 1 while (i < 4) { numbers.append(i * 10) i = i + 1; } print("after push " + String(numbers.count)) numbers[0] = 99 print("first " + String(numbers[0])) numbers.removeLast() numbers.remove(at:0) print("left " + String(numbers.count)) numbers.removeAll() print("after clear " + String(numbers.count))}__main__swift()List<int> numbers = new List<int>();int i = 1;while (i < 4) { numbers.Add(i * 10); i = i + 1;}Console.WriteLine("after push " + numbers.Count);numbers[0] = 99;Console.WriteLine("first " + numbers[0]);numbers.RemoveAt(numbers.Count - 1);numbers.RemoveAt((int)(0));Console.WriteLine("left " + numbers.Count);numbers.Clear();Console.WriteLine("after clear " + numbers.Count);The complete file
using System;using System.Collections;using System.Collections.Generic;class Main { static void Main( string [] args ) { List<int> numbers = new List<int>(); int i = 1; while (i < 4) { numbers.Add(i * 10); i = i + 1; } Console.WriteLine("after push " + numbers.Count); numbers[0] = 99; Console.WriteLine("first " + numbers[0]); numbers.RemoveAt(numbers.Count - 1); numbers.RemoveAt((int)(0)); Console.WriteLine("left " + numbers.Count); numbers.Clear(); Console.WriteLine("after clear " + numbers.Count); }}std::vector<int> numbers;int i = 1;while (i < 4) { numbers.push_back( i * 10 ); i = i + 1;};std::cout << std::string("after push ") + std::to_string((int)(numbers.size())) << std::endl;numbers[0] = 99;std::cout << std::string("first ") + std::to_string(numbers.at(0)) << std::endl;numbers.pop_back();numbers.erase( numbers.begin() + 0 );std::cout << std::string("left ") + std::to_string((int)(numbers.size())) << std::endl;numbers.clear();std::cout << std::string("after clear ") + std::to_string((int)(numbers.size())) << std::endl;return 0;The complete file
#include <memory>#include <vector>#include <iostream>#include <string>
// define classes here to avoid compiler errorsclass Main;
// header definitionsclass Main { public : /* class constructor */ Main( ); /* static methods */ static void main();};
int __g_argc;char **__g_argv;Main::Main( ) {}int main(int argc, char* argv[]) { __g_argc = argc; __g_argv = argv; std::vector<int> numbers; int i = 1; while (i < 4) { numbers.push_back( i * 10 ); i = i + 1; }; std::cout << std::string("after push ") + std::to_string((int)(numbers.size())) << std::endl; numbers[0] = 99; std::cout << std::string("first ") + std::to_string(numbers.at(0)) << std::endl; numbers.pop_back(); numbers.erase( numbers.begin() + 0 ); std::cout << std::string("left ") + std::to_string((int)(numbers.size())) << std::endl; numbers.clear(); std::cout << std::string("after clear ") + std::to_string((int)(numbers.size())) << std::endl; return 0;}$numbers = array();$i = 1;while ($i < 4) { array_push($numbers, $i * 10); $i = $i + 1;}echo( "after push " . count($numbers) . "\n");$numbers[0] = 99;echo( "first " . $numbers[0] . "\n");array_pop($numbers );array_splice($numbers, 0, 1);echo( "left " . count($numbers) . "\n");$numbers = array();echo( "after clear " . count($numbers) . "\n");The complete file
<?php
class Main { function __construct( ) { }}/* static PHP main routine */$numbers = array();$i = 1;while ($i < 4) { array_push($numbers, $i * 10); $i = $i + 1;}echo( "after push " . count($numbers) . "\n");$numbers[0] = 99;echo( "first " . $numbers[0] . "\n");array_pop($numbers );array_splice($numbers, 0, 1);echo( "left " . count($numbers) . "\n");$numbers = array();echo( "after clear " . count($numbers) . "\n");var numbers : collection.mutable.ArrayBuffer[Int] = new collection.mutable.ArrayBuffer()var i : Int = 1try { val __break__ = new Breaks; __break__.breakable { while (i < 4) { val __continue__ = new Breaks; __continue__.breakable { numbers.append(i * 10) i = i + 1 } } }}println( "after push " + numbers.length )numbers(0) = 99println( "first " + numbers(0) )numbers.remove(numbers.length - 1)numbers.remove((0).toInt)println( "left " + numbers.length )numbers.clear()println( "after clear " + numbers.length )The complete file
import scala.collection.mutableimport scala.util.control._case class ScalaReturnValue(value:Any) extends Exception
// application main function for Mainobject AppMain extends App { var numbers : collection.mutable.ArrayBuffer[Int] = new collection.mutable.ArrayBuffer() var i : Int = 1 try { val __break__ = new Breaks; __break__.breakable { while (i < 4) { val __continue__ = new Breaks; __continue__.breakable { numbers.append(i * 10) i = i + 1 } } } } println( "after push " + numbers.length ) numbers(0) = 99 println( "first " + numbers(0) ) numbers.remove(numbers.length - 1) numbers.remove((0).toInt) println( "left " + numbers.length ) numbers.clear() println( "after clear " + numbers.length )}The array operators page holds the
complete set, and each entry states which targets it writes code for. insert
and remove both write code for the command-line targets.
How do I write “not”?
Section titled “How do I write “not”?”The operator is !, and it is in prefix form like every other operator:
(! value). The argument is a boolean.
class Main { sfn main:void () { def ready false if (! ready) { print "the program is not ready" } def empty:[int] if (! ((array_length empty) > 0)) { print "the array holds no item" } }}const ready = false;if ( false == ready ) { console.log("the program is not ready");}let empty = [];if ( false == (empty.length > 0) ) { console.log("the array holds no item");}The complete file
class Main { constructor() { }}/* static JavaSript main routine at the end of the JS file */function __js_main() { const ready = false; if ( false == ready ) { console.log("the program is not ready"); } let empty = []; if ( false == (empty.length > 0) ) { console.log("the array holds no item"); }}__js_main();const ready : boolean = false;if ( false == ready ) { console.log("the program is not ready");}let empty : Array<number> | undefined = [];if ( false == (empty.length > 0) ) { console.log("the array holds no item");}The complete file
export class Main { constructor() { }}/* static JavaSript main routine at the end of the JS file */function __js_main() { const ready : boolean = false; if ( false == ready ) { console.log("the program is not ready"); } let empty : Array<number> | undefined = []; if ( false == (empty.length > 0) ) { console.log("the array holds no item"); }}__js_main();var ready bool= false;if false == ready { fmt.Println( "the program is not ready" )}var empty []int64 = make([]int64, 0);if false == (int64(len(empty)) > int64(0)) { fmt.Println( "the array holds no item" )}The complete file
package mainimport ( "fmt")
type GoNullable struct { value interface{} has_value bool}
type Main struct {}
func CreateNew_Main() *Main { me := new(Main) return me;}func main() { var ready bool= false; if false == ready { fmt.Println( "the program is not ready" ) } var empty []int64 = make([]int64, 0); if false == (int64(len(empty)) > int64(0)) { fmt.Println( "the array holds no item" ) }}let __rg_main_thread = std::thread::Builder::new().stack_size(512 * 1024 * 1024) .spawn(__rg_main_body).expect("could not start the main thread");__rg_main_thread.join().expect("main thread panicked");The complete file
#![allow(dead_code)]#![allow(unused_mut)]
#[derive(Clone)]struct Main {}impl Main { pub fn new() -> Self { Self { } }}fn main() { let __rg_main_thread = std::thread::Builder::new().stack_size(512 * 1024 * 1024) .spawn(__rg_main_body).expect("could not start the main thread"); __rg_main_thread.join().expect("main thread panicked");}fn __rg_main_body() { let ready: bool = false; if false == ready { println!("the program is not ready"); } let mut empty: Vec<i64> = Vec::new(); if false == ((empty.len() as i64) > 0) { println!("the array holds no item"); }}ready = Falseif False == ready: print("the program is not ready")empty = []if False == (len(empty) > 0): print("the array holds no item")The complete file
# -*- coding: utf-8 -*-from __future__ import annotationsfrom typing import Optional
class Main: def __init__(self) -> None: pass# Main entry pointdef main(): ready = False if False == ready: print("the program is not ready") empty = [] if False == (len(empty) > 0): print("the array holds no item")if __name__ == "__main__": main()RgArgs.args = args;final Boolean ready = false;if ( false == ready ) { System.out.println(String.valueOf( "the program is not ready" ) );}final ArrayList<Integer> empty = new ArrayList<Integer>();if ( false == (empty.size() > 0) ) { System.out.println(String.valueOf( "the array holds no item" ) );}The complete file
import java.io.*;import java.util.*;
public class Main {
public static void main(String [] args ) { RgArgs.args = args; final Boolean ready = false; if ( false == ready ) { System.out.println(String.valueOf( "the program is not ready" ) ); } final ArrayList<Integer> empty = new ArrayList<Integer>(); if ( false == (empty.size() > 0) ) { System.out.println(String.valueOf( "the array holds no item" ) ); } }}
public class RgArgs { public static String[] args = new String[0];}__g_args = argsval ready : Boolean = false;if ( false == ready ) { println( "the program is not ready" )}val empty : MutableList<Int> = arrayListOf();if ( false == (empty.size > 0) ) { println( "the array holds no item" )}The complete file
class Main {
}
var __g_args : Array<String> = arrayOf()
fun main(args : Array<String>) { __g_args = args val ready : Boolean = false; if ( false == ready ) { println( "the program is not ready" ) } val empty : MutableList<Int> = arrayListOf(); if ( false == (empty.size > 0) ) { println( "the array holds no item" ) }}__g_args = args;bool ready = false;if ( false == ready ) { print( "the program is not ready" );}List<int> empty = [];if ( false == (empty.length > 0) ) { print( "the array holds no item" );}The complete file
class Main {}
List<String> __g_args = <String>[];
void main(List<String> args) { __g_args = args; bool ready = false; if ( false == ready ) { print( "the program is not ready" ); } List<int> empty = []; if ( false == (empty.length > 0) ) { print( "the array holds no item" ); }}let ready : Bool = falseif ( false == ready ) { print("the program is not ready")}let empty : [Int] = [Int]()if ( false == (empty.count > 0) ) { print("the array holds no item")}The complete file
func ==(l: Main, r: Main) -> Bool { return l === r}final class Main : Hashable { func hash(into hasher: inout Hasher) { hasher.combine(ObjectIdentifier(self)) }}// Main entry pointfunc __main__swift() { let ready : Bool = false if ( false == ready ) { print("the program is not ready") } let empty : [Int] = [Int]() if ( false == (empty.count > 0) ) { print("the array holds no item") }}__main__swift()bool ready = false;if ( false == ready ) { Console.WriteLine("the program is not ready");}List<int> empty = new List<int>();if ( false == (empty.Count > 0) ) { Console.WriteLine("the array holds no item");}The complete file
using System;using System.Collections;using System.Collections.Generic;class Main { static void Main( string [] args ) { bool ready = false; if ( false == ready ) { Console.WriteLine("the program is not ready"); } List<int> empty = new List<int>(); if ( false == (empty.Count > 0) ) { Console.WriteLine("the array holds no item"); } }}bool ready = false;if ( false == ready ) { std::cout << std::string("the program is not ready") << std::endl;}std::vector<int> empty;if ( false == (((int)(empty.size())) > 0) ) { std::cout << std::string("the array holds no item") << std::endl;}return 0;The complete file
#include <memory>#include <iostream>#include <string>#include <vector>
// define classes here to avoid compiler errorsclass Main;
// header definitionsclass Main { public : /* class constructor */ Main( ); /* static methods */ static void main();};
int __g_argc;char **__g_argv;Main::Main( ) {}int main(int argc, char* argv[]) { __g_argc = argc; __g_argv = argv; bool ready = false; if ( false == ready ) { std::cout << std::string("the program is not ready") << std::endl; } std::vector<int> empty; if ( false == (((int)(empty.size())) > 0) ) { std::cout << std::string("the array holds no item") << std::endl; } return 0;}$ready = false;if ( false == $ready ) { echo( "the program is not ready" . "\n");}$empty = array();if ( false == (count($empty) > 0) ) { echo( "the array holds no item" . "\n");}The complete file
<?php
class Main { function __construct( ) { }}/* static PHP main routine */$ready = false;if ( false == $ready ) { echo( "the program is not ready" . "\n");}$empty = array();if ( false == (count($empty) > 0) ) { echo( "the array holds no item" . "\n");}val ready : Boolean = falseif ( false == ready ) { println( "the program is not ready" )}val empty : collection.mutable.ArrayBuffer[Int] = new collection.mutable.ArrayBuffer()if ( false == (empty.length > 0) ) { println( "the array holds no item" )}The complete file
import scala.collection.mutablecase class ScalaReturnValue(value:Any) extends Exception
// application main function for Mainobject AppMain extends App { val ready : Boolean = false if ( false == ready ) { println( "the program is not ready" ) } val empty : collection.mutable.ArrayBuffer[Int] = new collection.mutable.ArrayBuffer() if ( false == (empty.length > 0) ) { println( "the array holds no item" ) }}How do I create a singleton class?
Section titled “How do I create a singleton class?”A singleton class has one instance, and each part of the program uses that
instance. Add the annotation @singleton(true) to the class. The compiler then
writes a static function __singleton(), and each call gives the same
instance.
class CounterStore @singleton(true) { def total:int 0
fn add:void (n:int) { total = total + n }}
class Main { sfn main:void () { def a (CounterStore.__singleton()) def b (CounterStore.__singleton()) a.add(3) b.add(7) print ("total " + b.total) }}const a = CounterStore.__singleton();const b = CounterStore.__singleton();a.add(3);b.add(7);console.log("total " + b.total);The complete file
class CounterStore { constructor() { if (CounterStore.__singleton_instance != null) { return CounterStore.__singleton_instance; } this.total = 0; CounterStore.__singleton_instance = this; } add (n) { this.total = this.total + n; };}CounterStore.__singleton_instance = null;CounterStore.__singleton = function() { if (CounterStore.__singleton_instance == null) { CounterStore.__singleton_instance = new CounterStore(); } return CounterStore.__singleton_instance;};class Main { constructor() { }}/* static JavaSript main routine at the end of the JS file */function __js_main() { const a = CounterStore.__singleton(); const b = CounterStore.__singleton(); a.add(3); b.add(7); console.log("total " + b.total);}__js_main();const a : CounterStore = CounterStore.__singleton();const b : CounterStore = CounterStore.__singleton();a.add(3);b.add(7);console.log("total " + b.total);The complete file
export class CounterStore { total!: number; constructor() { if (CounterStore.__singleton_instance != null) { return CounterStore.__singleton_instance; } this.total = 0; CounterStore.__singleton_instance = this; } add (n : number) : void { this.total = this.total + n; }; static __singleton_instance : CounterStore | null = null; static __singleton() : CounterStore { if (this.__singleton_instance == null) { this.__singleton_instance = new CounterStore(); } return this.__singleton_instance; };}export class Main { constructor() { }}/* static JavaSript main routine at the end of the JS file */function __js_main() { const a : CounterStore = CounterStore.__singleton(); const b : CounterStore = CounterStore.__singleton(); a.add(3); b.add(7); console.log("total " + b.total);}__js_main();var a *CounterStore= CounterStore_static___singleton(); _ = avar b *CounterStore= CounterStore_static___singleton(); _ = ba.add(int64(3));b.add(int64(7));fmt.Println( strings.Join([]string{ "total ",strconv.FormatInt(b.total, 10) }, "") )The complete file
package mainimport ( "strings" "strconv" "fmt")type CounterStore struct { total int64 `json:"total"`}
func CreateNew_CounterStore() *CounterStore { me := new(CounterStore) me.total = int64(0) return me;}var CounterStore__singleton_instance *CounterStore = nilfunc CounterStore_static___singleton() *CounterStore { if CounterStore__singleton_instance == nil { CounterStore__singleton_instance = CreateNew_CounterStore() } return CounterStore__singleton_instance}func (this *CounterStore) add (n int64) () { this.total = this.total + n;}type Main struct {}
func CreateNew_Main() *Main { me := new(Main) return me;}func main() { var a *CounterStore= CounterStore_static___singleton(); _ = a var b *CounterStore= CounterStore_static___singleton(); _ = b a.add(int64(3)); b.add(int64(7)); fmt.Println( strings.Join([]string{ "total ",strconv.FormatInt(b.total, 10) }, "") )}let __rg_main_thread = std::thread::Builder::new().stack_size(512 * 1024 * 1024) .spawn(__rg_main_body).expect("could not start the main thread");__rg_main_thread.join().expect("main thread panicked");The complete file
#![allow(dead_code)]#![allow(unused_mut)]
use std::rc::Rc;use std::cell::RefCell;
pub trait RgAnyRef { fn rg_as_any(&self) -> &dyn std::any::Any; }fn rg_downcast<T: 'static, D: ?Sized + RgAnyRef>(v: &Rc<RefCell<D>>) -> Rc<RefCell<T>> { assert!(v.borrow().rg_as_any().is::<T>(), "invalid downcast"); let p = Rc::into_raw(v.clone()) as *const () as *const RefCell<T>; unsafe { Rc::from_raw(p) }}pub trait RgIdentical { fn rg_identical(&self, other: &Self) -> bool; }impl<T: ?Sized> RgIdentical for Rc<RefCell<T>> { fn rg_identical(&self, other: &Self) -> bool { Rc::ptr_eq(self, other) }}
#[derive(Clone)]struct CounterStore { total: i64,}impl CounterStore { pub fn new() -> Self { Self { total: 0, } } pub fn __singleton() -> Rc<RefCell<CounterStore>> { thread_local!(static __SINGLETON: RefCell<Option<Rc<RefCell<CounterStore>>>> = RefCell::new(None)); __SINGLETON.with(|s| { let mut slot = s.borrow_mut(); if slot.is_none() { *slot = Some(Rc::new(RefCell::new(CounterStore::new()))); } slot.as_ref().unwrap().clone() }) } fn add(__self_rc: &Rc<RefCell<CounterStore>>, n: i64) { __self_rc.borrow_mut().total += n; }}#[derive(Clone)]struct Main {}impl Main { pub fn new() -> Self { Self { } }}fn main() { let __rg_main_thread = std::thread::Builder::new().stack_size(512 * 1024 * 1024) .spawn(__rg_main_body).expect("could not start the main thread"); __rg_main_thread.join().expect("main thread panicked");}fn __rg_main_body() { let mut a: Rc<RefCell<CounterStore>> = CounterStore::__singleton(); let mut b: Rc<RefCell<CounterStore>> = CounterStore::__singleton(); CounterStore::add(&a, 3); CounterStore::add(&b, 7); println!("total {}", b.borrow().total);}a = CounterStore.rg_singleton()b = CounterStore.rg_singleton()a.add(3)b.add(7)print("total " + str(b.total))The complete file
# -*- coding: utf-8 -*-from __future__ import annotationsfrom typing import Optional
class CounterStore: _rg_singleton_instance = None def __init__(self) -> None: self.total = 0 @staticmethod def rg_singleton(): if CounterStore._rg_singleton_instance is None: CounterStore._rg_singleton_instance = CounterStore() return CounterStore._rg_singleton_instance def add(self, n: int) -> None: self.total = self.total + n;class Main: def __init__(self) -> None: pass# Main entry pointdef main(): a = CounterStore.rg_singleton() b = CounterStore.rg_singleton() a.add(3) b.add(7) print("total " + str(b.total))if __name__ == "__main__": main()RgArgs.args = args;final CounterStore a = CounterStore.__singleton();final CounterStore b = CounterStore.__singleton();a.add(3);b.add(7);System.out.println(String.valueOf( "total " + b.total ) );The complete file
public class CounterStore { public Integer total = 0; static CounterStore __singleton_instance = null; public static CounterStore __singleton() { if (__singleton_instance == null) { __singleton_instance = new CounterStore(); } return __singleton_instance; }
public void add( final Integer n ) { total = total + n; }}
import java.io.*;
public class Main {
public static void main(String [] args ) { RgArgs.args = args; final CounterStore a = CounterStore.__singleton(); final CounterStore b = CounterStore.__singleton(); a.add(3); b.add(7); System.out.println(String.valueOf( "total " + b.total ) ); }}
public class RgArgs { public static String[] args = new String[0];}__g_args = argsval a : CounterStore = CounterStore.__singleton();val b : CounterStore = CounterStore.__singleton();a.add(3);b.add(7);println( "total " + (b.total).toString() )The complete file
class CounterStore { @JvmField var total : Int = 0; companion object { private var __singleton_instance : CounterStore? = null fun __singleton() : CounterStore { if (__singleton_instance == null) { __singleton_instance = CounterStore() } return __singleton_instance!! } }
fun add( n : Int) : Unit { total = total + n; }}
class Main {
}
var __g_args : Array<String> = arrayOf()
fun main(args : Array<String>) { __g_args = args val a : CounterStore = CounterStore.__singleton(); val b : CounterStore = CounterStore.__singleton(); a.add(3); b.add(7); println( "total " + (b.total).toString() )}__g_args = args;CounterStore a = CounterStore.__singleton();CounterStore b = CounterStore.__singleton();a.add(3);b.add(7);print( "total " + (b.total).toString() );The complete file
class CounterStore { int total = 0; static CounterStore? __singleton_instance;
static CounterStore __singleton() { if (__singleton_instance == null) { __singleton_instance = CounterStore(); } return __singleton_instance!; }
void add(int n) { total = total + n; }}
class Main {}
List<String> __g_args = <String>[];
void main(List<String> args) { __g_args = args; CounterStore a = CounterStore.__singleton(); CounterStore b = CounterStore.__singleton(); a.add(3); b.add(7); print( "total " + (b.total).toString() );}let a : CounterStore = CounterStore.__singleton()let b : CounterStore = CounterStore.__singleton()a.add(n : 3)b.add(n : 7)print("total " + String(b.total))The complete file
func ==(l: CounterStore, r: CounterStore) -> Bool { return l === r}final class CounterStore : Hashable { func hash(into hasher: inout Hasher) { hasher.combine(ObjectIdentifier(self)) } var total : Int = 0 private static var __singleton_instance : CounterStore? = nil class func __singleton() -> CounterStore { if (CounterStore.__singleton_instance == nil) { CounterStore.__singleton_instance = CounterStore() } return CounterStore.__singleton_instance! } func add(n : Int) -> Void { self.total = self.total + n; }}func ==(l: Main, r: Main) -> Bool { return l === r}final class Main : Hashable { func hash(into hasher: inout Hasher) { hasher.combine(ObjectIdentifier(self)) }}// Main entry pointfunc __main__swift() { let a : CounterStore = CounterStore.__singleton() let b : CounterStore = CounterStore.__singleton() a.add(n : 3) b.add(n : 7) print("total " + String(b.total))}__main__swift()CounterStore a = CounterStore.__singleton();CounterStore b = CounterStore.__singleton();a.add(3);b.add(7);Console.WriteLine("total " + b.total);The complete file
using System;class CounterStore { public int total = 0; static CounterStore __singleton_instance = null; public static CounterStore __singleton() { if (__singleton_instance == null) { __singleton_instance = new CounterStore(); } return __singleton_instance; } public void add( int n ) { total = total + n; }}class Main { static void Main( string [] args ) { CounterStore a = CounterStore.__singleton(); CounterStore b = CounterStore.__singleton(); a.add(3); b.add(7); Console.WriteLine("total " + b.total); }}std::shared_ptr<CounterStore> a = CounterStore::__singleton();std::shared_ptr<CounterStore> b = CounterStore::__singleton();a->add(3);b->add(7);std::cout << std::string("total ") + std::to_string(b->total) << std::endl;return 0;The complete file
#include <memory>#include <iostream>#include <string>
// define classes here to avoid compiler errorsclass CounterStore;class Main;
// header definitionsclass CounterStore { public : int total; /* class constructor */ CounterStore( ); static std::shared_ptr<CounterStore> __singleton_instance; static const std::shared_ptr<CounterStore>& __singleton(); /* instance methods */ void add( int n );};class Main { public : /* class constructor */ Main( ); /* static methods */ static void main();};
int __g_argc;char **__g_argv;CounterStore::CounterStore( ) { this->total = 0;}std::shared_ptr<CounterStore> CounterStore::__singleton_instance = nullptr;const std::shared_ptr<CounterStore>& CounterStore::__singleton() { if (CounterStore::__singleton_instance == nullptr) { CounterStore::__singleton_instance = std::make_shared<CounterStore>(); } return CounterStore::__singleton_instance;}void CounterStore::add( int n ) { total = total + n;}Main::Main( ) {}int main(int argc, char* argv[]) { __g_argc = argc; __g_argv = argv; std::shared_ptr<CounterStore> a = CounterStore::__singleton(); std::shared_ptr<CounterStore> b = CounterStore::__singleton(); a->add(3); b->add(7); std::cout << std::string("total ") + std::to_string(b->total) << std::endl; return 0;}$a = CounterStore::__singleton();$b = CounterStore::__singleton();$a->add(3);$b->add(7);echo( "total " . $b->total . "\n");The complete file
<?php
class CounterStore { public int $total = 0; function __construct( ) { $this->total = 0; } function add( $n ) { $this->total = $this->total + $n; }}class Main { function __construct( ) { }}/* static PHP main routine */$a = CounterStore::__singleton();$b = CounterStore::__singleton();$a->add(3);$b->add(7);echo( "total " . $b->total . "\n");val a : CounterStore = CounterStore.__singleton()val b : CounterStore = CounterStore.__singleton()a.add(3);b.add(7);println( "total " + b.total )The complete file
case class ScalaReturnValue(value:Any) extends Exceptionclass CounterStore { var total : Int = 0 def add( n : Int) : Unit = total = (total + n)}
// application main function for Mainobject AppMain extends App { val a : CounterStore = CounterStore.__singleton() val b : CounterStore = CounterStore.__singleton() a.add(3); b.add(7); println( "total " + b.total )}The instance is per target process. The compiler writes the registry that the target language needs, so the program does not hold a global variable.
How do I write one class that holds several types?
Section titled “How do I write one class that holds several types?”Declare the class with @params(...) and give the arguments with @(...).
; A type parameter is declared with @params and given with @(...). Nothing is; asked of the argument type, so each of these is a separate concrete class; after the compiler expands it.class History @params(Op) { def ops:[Op]
fn record:void (op:Op) { push ops op } fn count:int () { return (array_length ops) } fn newest:Op () { def v:Op (last ops) return v }}
class Main { sfn main:void () { def numbers:History@(int) (new History@(int) ()) numbers.record(3) numbers.record(9) def n (numbers.count()) def top (numbers.newest()) print (("numbers " + n) + " newest " + top)
def words:History@(string) (new History@(string) ()) words.record("first") words.record("second") def wn (words.count()) def wtop (words.newest()) print (("words " + wn) + " newest " + wtop) }}const numbers = new History_int();numbers.record(3);numbers.record(9);const n = numbers.count();const top = numbers.newest();console.log((("numbers " + n) + " newest ") + top);const words = new History_string();words.record("first");words.record("second");const wn = words.count();const wtop = words.newest();console.log((("words " + wn) + " newest ") + wtop);The complete file
class Main { constructor() { }}class History_int { constructor() { this.ops = []; } record (op) { this.ops.push(op); }; count () { return this.ops.length; }; newest () { const v = this.ops[(this.ops.length - 1)]; return v; };}class History_string { constructor() { this.ops = []; } record (op) { this.ops.push(op); }; count () { return this.ops.length; }; newest () { const v = this.ops[(this.ops.length - 1)]; return v; };}/* static JavaSript main routine at the end of the JS file */function __js_main() { const numbers = new History_int(); numbers.record(3); numbers.record(9); const n = numbers.count(); const top = numbers.newest(); console.log((("numbers " + n) + " newest ") + top); const words = new History_string(); words.record("first"); words.record("second"); const wn = words.count(); const wtop = words.newest(); console.log((("words " + wn) + " newest ") + wtop);}__js_main();const numbers : History_int = new History_int();numbers.record(3);numbers.record(9);const n : number = numbers.count();const top : number = numbers.newest();console.log((("numbers " + n) + " newest ") + top);const words : History_string = new History_string();words.record("first");words.record("second");const wn : number = words.count();const wtop : string = words.newest();console.log((("words " + wn) + " newest ") + wtop);The complete file
export class Main { constructor() { }}export class History_int { ops!: Array<number>; constructor() { this.ops = []; } record (op : number) : void { this.ops.push(op); }; count () : number { return this.ops.length; }; newest () : number { const v : number = this.ops[(this.ops.length - 1)]; return v; };}export class History_string { ops!: Array<string>; constructor() { this.ops = []; } record (op : string) : void { this.ops.push(op); }; count () : number { return this.ops.length; }; newest () : string { const v : string = this.ops[(this.ops.length - 1)]; return v; };}/* static JavaSript main routine at the end of the JS file */function __js_main() { const numbers : History_int = new History_int(); numbers.record(3); numbers.record(9); const n : number = numbers.count(); const top : number = numbers.newest(); console.log((("numbers " + n) + " newest ") + top); const words : History_string = new History_string(); words.record("first"); words.record("second"); const wn : number = words.count(); const wtop : string = words.newest(); console.log((("words " + wn) + " newest ") + wtop);}__js_main();var numbers *History_int= CreateNew_History_int();numbers.record(int64(3));numbers.record(int64(9));var n int64= numbers.count();var top int64= numbers.newest();fmt.Println( strings.Join([]string{ (strings.Join([]string{ "numbers ",strconv.FormatInt(n, 10) }, "") + " newest "),strconv.FormatInt(top, 10) }, "") )var words *History_string= CreateNew_History_string();words.record("first");words.record("second");var wn int64= words.count();var wtop string= words.newest();fmt.Println( (strings.Join([]string{ "words ",strconv.FormatInt(wn, 10) }, "") + " newest ") + wtop )The complete file
package mainimport ( "strings" "strconv" "fmt")
type GoNullable struct { value interface{} has_value bool}
type Main struct {}
func CreateNew_Main() *Main { me := new(Main) return me;}func main() { var numbers *History_int= CreateNew_History_int(); numbers.record(int64(3)); numbers.record(int64(9)); var n int64= numbers.count(); var top int64= numbers.newest(); fmt.Println( strings.Join([]string{ (strings.Join([]string{ "numbers ",strconv.FormatInt(n, 10) }, "") + " newest "),strconv.FormatInt(top, 10) }, "") ) var words *History_string= CreateNew_History_string(); words.record("first"); words.record("second"); var wn int64= words.count(); var wtop string= words.newest(); fmt.Println( (strings.Join([]string{ "words ",strconv.FormatInt(wn, 10) }, "") + " newest ") + wtop )}type History_int struct { ops []int64 `json:"ops"`}
func CreateNew_History_int() *History_int { me := new(History_int) me.ops = make([]int64,0) return me;}func (this *History_int) record (op int64) () { this.ops = append(this.ops,op);}func (this *History_int) count () int64 { return int64(len(this.ops))}func (this *History_int) newest () int64 { var v int64= this.ops[(int64(len(this.ops)) - int64(1))]; return v}type History_string struct { ops []string `json:"ops"`}
func CreateNew_History_string() *History_string { me := new(History_string) me.ops = make([]string,0) return me;}func (this *History_string) record (op string) () { this.ops = append(this.ops,op);}func (this *History_string) count () int64 { return int64(len(this.ops))}func (this *History_string) newest () string { var v string= this.ops[(int64(len(this.ops)) - int64(1))]; return v}let __rg_main_thread = std::thread::Builder::new().stack_size(512 * 1024 * 1024) .spawn(__rg_main_body).expect("could not start the main thread");__rg_main_thread.join().expect("main thread panicked");The complete file
#![allow(dead_code)]
#[derive(Clone)]struct Main {}impl Main { pub fn new() -> Self { Self { } }}fn main() { let __rg_main_thread = std::thread::Builder::new().stack_size(512 * 1024 * 1024) .spawn(__rg_main_body).expect("could not start the main thread"); __rg_main_thread.join().expect("main thread panicked");}fn __rg_main_body() { let mut numbers: History_int = History_int::new(); numbers.record(3); numbers.record(9); let n: i64 = numbers.count(); let top: i64 = numbers.newest(); println!("numbers {} newest {}", n, top); let mut words: History_string = History_string::new(); words.record("first"); words.record("second"); let wn: i64 = words.count(); let wtop: String = words.newest(); println!("words {} newest {}", wn, wtop);}#[derive(Clone)]struct History_int { ops: Vec<i64>,}impl History_int { pub fn new() -> Self { Self { ops: Vec::new(), } } fn record(&mut self, op: i64) { self.ops.push(op); } fn count(&self) -> i64 { self.ops.len() as i64 } fn newest(&self) -> i64 { let v: i64 = self.ops[((self.ops.len() as i64) - 1) as usize]; v }}#[derive(Clone)]struct History_string { ops: Vec<String>,}impl History_string { pub fn new() -> Self { Self { ops: Vec::new(), } } fn record(&mut self, op: &str) { self.ops.push(op.to_string()); } fn count(&self) -> i64 { self.ops.len() as i64 } fn newest(&self) -> String { let v: String = self.ops[((self.ops.len() as i64) - 1) as usize].clone(); v.clone() }}numbers = History_int()numbers.record(3)numbers.record(9)n = numbers.count()top = numbers.newest()print((("numbers " + str(n)) + " newest ") + str(top))words = History_string()words.record("first")words.record("second")wn = words.count()wtop = words.newest()print((("words " + str(wn)) + " newest ") + wtop)The complete file
# -*- coding: utf-8 -*-from __future__ import annotationsfrom typing import Optional
class Main: def __init__(self) -> None: pass# Main entry pointdef main(): numbers = History_int() numbers.record(3) numbers.record(9) n = numbers.count() top = numbers.newest() print((("numbers " + str(n)) + " newest ") + str(top)) words = History_string() words.record("first") words.record("second") wn = words.count() wtop = words.newest() print((("words " + str(wn)) + " newest ") + wtop)class History_int: def __init__(self) -> None: self.ops = [] def record(self, op: int) -> None: self.ops.append(op) def count(self) -> int: return len(self.ops); def newest(self) -> int: v = self.ops[(len(self.ops) - 1)] return v;class History_string: def __init__(self) -> None: self.ops = [] def record(self, op: str) -> None: self.ops.append(op) def count(self) -> int: return len(self.ops); def newest(self) -> str: v = self.ops[(len(self.ops) - 1)] return v;if __name__ == "__main__": main()RgArgs.args = args;final History_int numbers = new History_int();numbers.record(3);numbers.record(9);final Integer n = numbers.count();final Integer top = numbers.newest();System.out.println(String.valueOf( (("numbers " + n) + " newest ") + top ) );final History_string words = new History_string();words.record("first");words.record("second");final Integer wn = words.count();final String wtop = words.newest();System.out.println(String.valueOf( (("words " + wn) + " newest ") + wtop ) );The complete file
import java.io.*;
public class Main {
public static void main(String [] args ) { RgArgs.args = args; final History_int numbers = new History_int(); numbers.record(3); numbers.record(9); final Integer n = numbers.count(); final Integer top = numbers.newest(); System.out.println(String.valueOf( (("numbers " + n) + " newest ") + top ) ); final History_string words = new History_string(); words.record("first"); words.record("second"); final Integer wn = words.count(); final String wtop = words.newest(); System.out.println(String.valueOf( (("words " + wn) + " newest ") + wtop ) ); }}
public class RgArgs { public static String[] args = new String[0];}
import java.util.*;
public class History_int { public ArrayList<Integer> ops = new ArrayList<Integer>();
public void record( final Integer op ) { ops.add(op); }
public Integer count() { return ops.size(); }
public Integer newest() { final Integer v = ops.get(ops.size() - 1); return v; }}
import java.util.*;
public class History_string { public ArrayList<String> ops = new ArrayList<String>();
public void record( final String op ) { ops.add(op); }
public Integer count() { return ops.size(); }
public String newest() { final String v = ops.get(ops.size() - 1); return v; }}__g_args = argsval numbers : History_int = History_int();numbers.record(3);numbers.record(9);val n : Int = numbers.count();val top : Int = numbers.newest();println( (("numbers " + (n).toString()) + " newest ") + (top).toString() )val words : History_string = History_string();words.record("first");words.record("second");val wn : Int = words.count();val wtop : String = words.newest();println( (("words " + (wn).toString()) + " newest ") + wtop )The complete file
class Main {
}
var __g_args : Array<String> = arrayOf()
fun main(args : Array<String>) { __g_args = args val numbers : History_int = History_int(); numbers.record(3); numbers.record(9); val n : Int = numbers.count(); val top : Int = numbers.newest(); println( (("numbers " + (n).toString()) + " newest ") + (top).toString() ) val words : History_string = History_string(); words.record("first"); words.record("second"); val wn : Int = words.count(); val wtop : String = words.newest(); println( (("words " + (wn).toString()) + " newest ") + wtop )}
class History_int { @JvmField var ops : MutableList<Int> = arrayListOf();
fun record( op : Int) : Unit { ops.add(op); }
fun count() : Int { return ops.size; }
fun newest() : Int { val v : Int = ops[(ops.size - 1)]; return v; }}
class History_string { @JvmField var ops : MutableList<String> = arrayListOf();
fun record( op : String) : Unit { ops.add(op); }
fun count() : Int { return ops.size; }
fun newest() : String { val v : String = ops[(ops.size - 1)]; return v; }}__g_args = args;History_int numbers = History_int();numbers.record(3);numbers.record(9);int n = numbers.count();int top = numbers.newest();print( (("numbers " + (n).toString()) + " newest ") + (top).toString() );History_string words = History_string();words.record("first");words.record("second");int wn = words.count();String wtop = words.newest();print( (("words " + (wn).toString()) + " newest ") + wtop );The complete file
class Main {}
List<String> __g_args = <String>[];
void main(List<String> args) { __g_args = args; History_int numbers = History_int(); numbers.record(3); numbers.record(9); int n = numbers.count(); int top = numbers.newest(); print( (("numbers " + (n).toString()) + " newest ") + (top).toString() ); History_string words = History_string(); words.record("first"); words.record("second"); int wn = words.count(); String wtop = words.newest(); print( (("words " + (wn).toString()) + " newest ") + wtop );}
class History_int { List<int> ops = [];
void record(int op) { ops.add(op); }
int count() { return ops.length; }
int newest() { int v = ops[(ops.length - 1)]; return v; }}
class History_string { List<String> ops = [];
void record(String op) { ops.add(op); }
int count() { return ops.length; }
String newest() { String v = ops[(ops.length - 1)]; return v; }}let numbers : History_int = History_int()numbers.record(op : 3)numbers.record(op : 9)let n : Int = numbers.count()let top : Int = numbers.newest()print((("numbers " + String(n)) + " newest ") + String(top))let words : History_string = History_string()words.record(op : "first")words.record(op : "second")let wn : Int = words.count()let wtop : String = words.newest()print((("words " + String(wn)) + " newest ") + wtop)The complete file
func ==(l: Main, r: Main) -> Bool { return l === r}final class Main : Hashable { func hash(into hasher: inout Hasher) { hasher.combine(ObjectIdentifier(self)) }}func ==(l: History_int, r: History_int) -> Bool { return l === r}final class History_int : Hashable { func hash(into hasher: inout Hasher) { hasher.combine(ObjectIdentifier(self)) } var ops : [Int] = [Int]() func record(op : Int) -> Void { self.ops.append(op) } func count() -> Int { return self.ops.count } func newest() -> Int { let v : Int = self.ops[(self.ops.count - 1)] return v }}func ==(l: History_string, r: History_string) -> Bool { return l === r}final class History_string : Hashable { func hash(into hasher: inout Hasher) { hasher.combine(ObjectIdentifier(self)) } var ops : [String] = [String]() func record(op : String) -> Void { self.ops.append(op) } func count() -> Int { return self.ops.count } func newest() -> String { let v : String = self.ops[(self.ops.count - 1)] return v }}// Main entry pointfunc __main__swift() { let numbers : History_int = History_int() numbers.record(op : 3) numbers.record(op : 9) let n : Int = numbers.count() let top : Int = numbers.newest() print((("numbers " + String(n)) + " newest ") + String(top)) let words : History_string = History_string() words.record(op : "first") words.record(op : "second") let wn : Int = words.count() let wtop : String = words.newest() print((("words " + String(wn)) + " newest ") + wtop)}__main__swift()History_int numbers = new History_int();numbers.record(3);numbers.record(9);int n = numbers.count();int top = numbers.newest();Console.WriteLine((("numbers " + n) + " newest ") + top);History_string words = new History_string();words.record("first");words.record("second");int wn = words.count();String wtop = words.newest();Console.WriteLine((("words " + wn) + " newest ") + wtop);The complete file
using System;using System.Collections;using System.Collections.Generic;class Main { static void Main( string [] args ) { History_int numbers = new History_int(); numbers.record(3); numbers.record(9); int n = numbers.count(); int top = numbers.newest(); Console.WriteLine((("numbers " + n) + " newest ") + top); History_string words = new History_string(); words.record("first"); words.record("second"); int wn = words.count(); String wtop = words.newest(); Console.WriteLine((("words " + wn) + " newest ") + wtop); }}class History_int { public List<int> ops = new List<int>(); public void record( int op ) { ops.Add(op); } public int count() { return ops.Count; } public int newest() { int v = ops[(ops.Count - 1)]; return v; }}class History_string { public List<String> ops = new List<String>(); public void record( String op ) { ops.Add(op); } public int count() { return ops.Count; } public String newest() { String v = ops[(ops.Count - 1)]; return v; }}std::shared_ptr<History_int> numbers = std::make_shared<History_int>();numbers->record(3);numbers->record(9);int n = numbers->count();int top = numbers->newest();std::cout << ((std::string("numbers ") + std::to_string(n)) + std::string(" newest ")) + std::to_string(top) << std::endl;std::shared_ptr<History_string> words = std::make_shared<History_string>();words->record(std::string("first"));words->record(std::string("second"));int wn = words->count();std::string wtop = words->newest();std::cout << ((std::string("words ") + std::to_string(wn)) + std::string(" newest ")) + wtop << std::endl;return 0;The complete file
#include <memory>#include <iostream>#include <string>#include <vector>
// define classes here to avoid compiler errorsclass Main;class History_int;class History_string;
// header definitionsclass Main { public : /* class constructor */ Main( ); /* static methods */ static void main();};class History_int { public : std::vector<int> ops; /* class constructor */ History_int( ); /* instance methods */ void record( int op ); int count(); int newest();};class History_string { public : std::vector<std::string> ops; /* class constructor */ History_string( ); /* instance methods */ void record( const std::string& op ); int count(); std::string newest();};
int __g_argc;char **__g_argv;Main::Main( ) {}int main(int argc, char* argv[]) { __g_argc = argc; __g_argv = argv; std::shared_ptr<History_int> numbers = std::make_shared<History_int>(); numbers->record(3); numbers->record(9); int n = numbers->count(); int top = numbers->newest(); std::cout << ((std::string("numbers ") + std::to_string(n)) + std::string(" newest ")) + std::to_string(top) << std::endl; std::shared_ptr<History_string> words = std::make_shared<History_string>(); words->record(std::string("first")); words->record(std::string("second")); int wn = words->count(); std::string wtop = words->newest(); std::cout << ((std::string("words ") + std::to_string(wn)) + std::string(" newest ")) + wtop << std::endl; return 0;}History_int::History_int( ) {}void History_int::record( int op ) { ops.push_back( op );}int History_int::count() { return (int)(ops.size());}int History_int::newest() { int v = ops.at(((int)(ops.size())) - 1); return v;}History_string::History_string( ) {}void History_string::record( const std::string& op ) { ops.push_back( op );}int History_string::count() { return (int)(ops.size());}std::string History_string::newest() { std::string v = ops.at(((int)(ops.size())) - 1); return v;}$numbers = new History_int();$numbers->record(3);$numbers->record(9);$n = ($numbers)->count();$top = $numbers->newest();echo( (("numbers " . $n) . " newest ") . $top . "\n");$words = new History_string();$words->record("first");$words->record("second");$wn = ($words)->count();$wtop = $words->newest();echo( (("words " . $wn) . " newest ") . $wtop . "\n");class History_int { public array $ops = []; function __construct( ) { $this->ops = array(); } function record( $op ) { array_push($this->ops, $op); } function count() { return count($this->ops); } function newest() { $v = $this->ops[(count($this->ops) - 1)]; return $v; }}class History_string { public array $ops = []; function __construct( ) { $this->ops = array(); } function record( $op ) { array_push($this->ops, $op); } function count() { return count($this->ops); } function newest() { $v = $this->ops[(count($this->ops) - 1)]; return $v; }}The complete file
<?php
class Main { function __construct( ) { }}/* static PHP main routine */$numbers = new History_int();$numbers->record(3);$numbers->record(9);$n = ($numbers)->count();$top = $numbers->newest();echo( (("numbers " . $n) . " newest ") . $top . "\n");$words = new History_string();$words->record("first");$words->record("second");$wn = ($words)->count();$wtop = $words->newest();echo( (("words " . $wn) . " newest ") . $wtop . "\n");class History_int { public array $ops = []; function __construct( ) { $this->ops = array(); } function record( $op ) { array_push($this->ops, $op); } function count() { return count($this->ops); } function newest() { $v = $this->ops[(count($this->ops) - 1)]; return $v; }}class History_string { public array $ops = []; function __construct( ) { $this->ops = array(); } function record( $op ) { array_push($this->ops, $op); } function count() { return count($this->ops); } function newest() { $v = $this->ops[(count($this->ops) - 1)]; return $v; }}val numbers : History_int = new History_int()numbers.record(3);numbers.record(9);val n : Int = numbers.count()val top : Int = numbers.newest()println( (("numbers " + n) + " newest ") + top )val words : History_string = new History_string()words.record("first");words.record("second");val wn : Int = words.count()val wtop : String = words.newest()println( (("words " + wn) + " newest ") + wtop )The complete file
import scala.collection.mutablecase class ScalaReturnValue(value:Any) extends Exceptionclass History_int { var ops : collection.mutable.ArrayBuffer[Int] = new collection.mutable.ArrayBuffer() def record( op : Int) : Unit = ops.append(op) def count() : Int = ops.length def newest() : Int = { val v : Int = ops(ops.length - 1) v }}class History_string { var ops : collection.mutable.ArrayBuffer[String] = new collection.mutable.ArrayBuffer() def record( op : String) : Unit = ops.append(op) def count() : Int = ops.length def newest() : String = { val v : String = ops(ops.length - 1) v }}
// application main function for Mainobject AppMain extends App { val numbers : History_int = new History_int() numbers.record(3); numbers.record(9); val n : Int = numbers.count() val top : Int = numbers.newest() println( (("numbers " + n) + " newest ") + top ) val words : History_string = new History_string() words.record("first"); words.record("second"); val wn : Int = words.count() val wtop : String = words.newest() println( (("words " + wn) + " newest ") + wtop )}The target code holds History_int and History_string, two separate
classes. The compiler makes one class for each set of arguments before it
writes the target, so a target language does not need generics of its own and
no target writes the type parameter. Neither class can see the fields of the
other.
A type parameter is usable as an array element, as a map value, as a parameter
type and as a return type. The argument can be a primitive, a class, a record,
a shape, an array (History@([string])) or a map (Store@([string:int])).
There are no bounds and no constraints, so when the class must compare two
values, give it the comparison function at construction.
A generic class has no static side. Only the instantiations exist, so a sfn
in a generic class is not reachable. Put the static functions in a plain class
beside it.
How do I write an object to JSON and read it back?
Section titled “How do I write an object to JSON and read it back?”Add the annotation @serialize(true) to the class. The compiler then writes
toDictionary() and the static fromDictionary().
class Point @serialize(true) { def x:int 0 def y:int 0}
class Main { sfn main:void () { def p:Point (new Point()) p.x = 3 p.y = 4
def data:JSONDataObject (p.toDictionary()) def back:Point (Point.fromDictionary(data)) print ("x " + back.x + " y " + back.y) }}const p = new Point();p.x = 3;p.y = 4;const data = p.toDictionary();const back = Point.fromDictionary(data);console.log((("x " + back.x) + " y ") + back.y);The complete file
class Point { constructor() { this.x = 0; this.y = 0; } toDictionary () { let res = {}; try { res["x"] = this.x; res["y"] = this.y; } catch(e) { } return res; };}Point.fromDictionary = function(dict) { const obj = new Point(); try { const v = isNaN( parseInt(dict ["x"]) ) ? undefined : parseInt(dict ["x"]) ; if ( (typeof(v) !== "undefined" && v != null ) ) { obj.x = v; } const v_1 = isNaN( parseInt(dict ["y"]) ) ? undefined : parseInt(dict ["y"]) ; if ( (typeof(v_1) !== "undefined" && v_1 != null ) ) { obj.y = v_1; } } catch(e) { } return obj;};class Main { constructor() { }}/* static JavaSript main routine at the end of the JS file */function __js_main() { const p = new Point(); p.x = 3; p.y = 4; const data = p.toDictionary(); const back = Point.fromDictionary(data); console.log((("x " + back.x) + " y ") + back.y);}__js_main();const p : Point = new Point();p.x = 3;p.y = 4;const data : Record<string, any> = p.toDictionary();const back : Point = Point.fromDictionary(data);console.log((("x " + back.x) + " y ") + back.y);The complete file
export class Point { x!: number; y!: number; constructor() { this.x = 0; this.y = 0; } toDictionary () : Record<string, any> { let res : Record<string, any> = {}; try { res["x"] = this.x; res["y"] = this.y; } catch(e) { } return res; }; static fromDictionary (dict : Record<string, any>) : Point { const obj : Point = new Point(); try { const v : number | undefined = isNaN( parseInt(dict ["x"]) ) ? undefined : parseInt(dict ["x"]) ; if ( (typeof(v) !== "undefined" && v != null ) ) { obj.x = v; } const v_1 : number | undefined = isNaN( parseInt(dict ["y"]) ) ? undefined : parseInt(dict ["y"]) ; if ( (typeof(v_1) !== "undefined" && v_1 != null ) ) { obj.y = v_1; } } catch(e) { } return obj; };}export class Main { constructor() { }}/* static JavaSript main routine at the end of the JS file */function __js_main() { const p : Point = new Point(); p.x = 3; p.y = 4; const data : Record<string, any> = p.toDictionary(); const back : Point = Point.fromDictionary(data); console.log((("x " + back.x) + " y ") + back.y);}__js_main();var p *Point= CreateNew_Point(); _ = pp.x = int64(3);p.y = int64(4);var data map[string]interface{}= p.toDictionary();var back *Point= Point_static_fromDictionary(data); _ = backfmt.Println( strings.Join([]string{ (strings.Join([]string{ "x ",strconv.FormatInt(back.x, 10) }, "") + " y "),strconv.FormatInt(back.y, 10) }, "") )The complete file
package mainimport ( "strings" "strconv" "fmt")
type GoNullable struct { value interface{} has_value bool}
func r_get_opt_json_int( data map[string]interface{}, key string ) *GoNullable { res := new(GoNullable) v, ok := data[key] if ok { // encoding/json decodes EVERY number as float64, so the int assertion // alone never matched anything that came back from from_string: getInt // answered "absent" for a key that plainly held 3. A JSON number is // int or double and the two are distinct types here, so this accepts // both and converts, the way the Dart, Python, Rust and C# entries do. switch n := v.(type) { case int: res.has_value = true res.value = int64(n) return res case int64: res.has_value = true res.value = n return res case float64: res.has_value = true res.value = int64(n) return res } } res.has_value = false return res}
type Point struct { x int64 `json:"x"` y int64 `json:"y"`}
func CreateNew_Point() *Point { me := new(Point) me.x = int64(0) me.y = int64(0) return me;}func Point_static_fromDictionary(dict map[string]interface{}) *Point { var obj *Point= CreateNew_Point(); did_return, ex_result := (func () ( __ex_returned bool, __exReturn interface{}) { defer func() { if r:= recover(); r != nil { } }() var v *GoNullable = new(GoNullable); var v__src *GoNullable = r_get_opt_json_int(dict, "x"); v.value = v__src.value; v.has_value = v__src.has_value; if v.has_value { obj.x = v.value.(int64); } var v_1 *GoNullable = new(GoNullable); var v_1__src *GoNullable = r_get_opt_json_int(dict, "y"); v_1.value = v_1__src.value; v_1.has_value = v_1__src.has_value; if v_1.has_value { obj.y = v_1.value.(int64); } return __ex_returned, __exReturn })() if did_return { return ex_result.(*Point) } return obj}func (this *Point) toDictionary () map[string]interface{} { var res map[string]interface{}= make(map[string]interface{}); did_return, ex_result := (func () ( __ex_returned bool, __exReturn interface{}) { defer func() { if r:= recover(); r != nil { } }() res["x"] = this.x res["y"] = this.y return __ex_returned, __exReturn })() if did_return { return ex_result.(map[string]interface{}) } return res}type Main struct {}
func CreateNew_Main() *Main { me := new(Main) return me;}func main() { var p *Point= CreateNew_Point(); _ = p p.x = int64(3); p.y = int64(4); var data map[string]interface{}= p.toDictionary(); var back *Point= Point_static_fromDictionary(data); _ = back fmt.Println( strings.Join([]string{ (strings.Join([]string{ "x ",strconv.FormatInt(back.x, 10) }, "") + " y "),strconv.FormatInt(back.y, 10) }, "") )}let __rg_main_thread = std::thread::Builder::new().stack_size(512 * 1024 * 1024) .spawn(__rg_main_body).expect("could not start the main thread");__rg_main_thread.join().expect("main thread panicked");The complete file
#![allow(dead_code)]
#[derive(Clone)]struct Point { x: i64, y: i64,}impl Point { pub fn new() -> Self { Self { x: 0, y: 0, } } pub fn from_dictionary(dict: std::collections::HashMap<String, RJson>) -> Point { let mut obj: Point = Point::new(); /* try: Rust has no exceptions, so the catch block is not written */ let v: Option<i64> = r_json_get_int(&dict, &"x".to_string()); if v.is_some() { obj.x = v.unwrap(); } let v_1: Option<i64> = r_json_get_int(&dict, &"y".to_string()); if v_1.is_some() { obj.y = v_1.unwrap(); } obj.clone() } fn to_dictionary(&self) -> std::collections::HashMap<String, RJson> { let mut res: std::collections::HashMap<String, RJson> = std::collections::HashMap::<String, RJson>::new(); /* try: Rust has no exceptions, so the catch block is not written */ res.insert(("x".to_string()).to_string(), RJson::Int(self.x)); res.insert(("y".to_string()).to_string(), RJson::Int(self.y)); res.clone() }}#[derive(Clone)]struct Main {}impl Main { pub fn new() -> Self { Self { } }}fn main() { let __rg_main_thread = std::thread::Builder::new().stack_size(512 * 1024 * 1024) .spawn(__rg_main_body).expect("could not start the main thread"); __rg_main_thread.join().expect("main thread panicked");}fn __rg_main_body() { let mut p: Point = Point { x: 3, y: 4, }; let data: std::collections::HashMap<String, RJson> = p.to_dictionary(); let back: Point = Point::from_dictionary(data.clone()); println!("x {} y {}", back.x, back.y);}
#[derive(Clone, Debug, PartialEq)]enum RJson { Null, Bool(bool), Int(i64), Double(f64), Str(String), Arr(Vec<RJson>), Obj(std::collections::HashMap<String, RJson>) }
fn r_json_get_int(o: &std::collections::HashMap<String, RJson>, k: &str) -> Option<i64> { match o.get(k) { Some(RJson::Int(v)) => Some(*v), Some(RJson::Double(v)) => Some(*v as i64), _ => None }}p = Point()p.x = 3;p.y = 4;data = p.toDictionary()back = Point.fromDictionary(data)print((("x " + str(back.x)) + " y ") + str(back.y))The complete file
# -*- coding: utf-8 -*-from __future__ import annotationsfrom typing import Optional
class Point: def __init__(self) -> None: self.x = 0 self.y = 0 @staticmethod def fromDictionary(_dict: dict) -> Point: obj = Point() try: pass v = (lambda v: v if isinstance(v, int) and not isinstance(v, bool) else None)(_dict.get("x")) if (v is not None): obj.x = v; v_1 = (lambda v: v if isinstance(v, int) and not isinstance(v, bool) else None)(_dict.get("y")) if (v_1 is not None): obj.y = v_1; except Exception as e: pass pass return obj; def toDictionary(self) -> dict: res = {} try: pass res["x"] = self.x res["y"] = self.y except Exception as e: pass pass return res;class Main: def __init__(self) -> None: pass# Main entry pointdef main(): p = Point() p.x = 3; p.y = 4; data = p.toDictionary() back = Point.fromDictionary(data) print((("x " + str(back.x)) + " y ") + str(back.y))if __name__ == "__main__": main()RgArgs.args = args;final Point p = new Point();p.x = 3;p.y = 4;final JSONObject data = p.toDictionary();final Point back = Point.fromDictionary(data);System.out.println(String.valueOf( (("x " + back.x) + " y ") + back.y ) );The complete file
import java.io.IOException;
public class Point { public Integer x = 0; public Integer y = 0;
public static Point fromDictionary( final JSONObject dict ) { final Point obj = new Point(); try { final Integer v = dict.isNull( "x" ) ? null : dict.optInt("x") ; if ( v != null ) { obj.x = v; } final Integer v_1 = dict.isNull( "y" ) ? null : dict.optInt("y") ; if ( v_1 != null ) { obj.y = v_1; } } catch( Exception e) { } return obj; }
public JSONObject toDictionary() { JSONObject res = new JSONObject(); try { res.put("x" , Point.this.x); res.put("y" , Point.this.y); } catch( Exception e) { } return res; }}
public class JSONException extends RuntimeException { public JSONException(String message) { super(message); }}
import java.util.*;
public class JSONArray { public ArrayList<Object> values = new ArrayList<Object>(); public JSONArray() { } public int length() { return values.size(); } public Object get(int index) { if (index < 0 || index >= values.size()) { return null; } return values.get(index); } public JSONArray put(Object value) { values.add(value); return this; } // the templates reach an ARRAY element the same way they reach an object // member: isNull first, then get. org.json has both overloads and so does // this. public boolean isNull(int index) { return index < 0 || index >= values.size() || values.get(index) == null; } public String toString() { return RgJson.write(this); }}
import java.util.*;
public class JSONObject { public LinkedHashMap<String, Object> values = new LinkedHashMap<String, Object>(); public JSONObject() { } // used to take the text and throw it away, which is how the Kotlin twin of // this class started out: from_string answered an empty object and every // getter after it read absent public JSONObject(String source) { Object parsed = RgJson.readText(source); if (parsed instanceof JSONObject) { values.putAll(((JSONObject)parsed).values); } } public boolean isNull(String key) { return !values.containsKey(key) || values.get(key) == null; } public JSONArray names() { JSONArray a = new JSONArray(); for (String k : values.keySet()) { a.put(k); } return a; } public String optString(String key) { Object v = values.get(key); if (v instanceof String) { return (String)v; } return null; } // A JSON number reads back as Integer or Double and the two are distinct // types, so each getter accepts both and converts. public Integer optInt(String key) { Object v = values.get(key); if (v instanceof Integer) { return (Integer)v; } if (v instanceof Double) { return Integer.valueOf(((Double)v).intValue()); } if (v instanceof Long) { return Integer.valueOf(((Long)v).intValue()); } return null; } public Double optDouble(String key) { Object v = values.get(key); if (v instanceof Double) { return (Double)v; } if (v instanceof Integer) { return Double.valueOf(((Integer)v).doubleValue()); } if (v instanceof Long) { return Double.valueOf(((Long)v).doubleValue()); } return null; } public Boolean optBoolean(String key) { Object v = values.get(key); if (v instanceof Boolean) { return (Boolean)v; } return null; } public JSONObject getJSONObject(String key) { Object v = values.get(key); if (v instanceof JSONObject) { return (JSONObject)v; } return null; } public JSONArray getJSONArray(String key) { Object v = values.get(key); if (v instanceof JSONArray) { return (JSONArray)v; } return null; } public JSONObject put(String key, Object value) { values.put(key, value); return this; } public String toString() { return RgJson.write(this); }}
import java.util.*;
// Java has no JSON in the standard library, and the generated files have to// build with a plain javac line and no dependency, so the object, the array,// the reader and the writer all live here. org.json is deliberately NOT// imported on top of these -- nothing puts that package on the classpath.// Kotlin carries the same set for the same reason; see lib/JSON.rgr.public class RgJson { static void writeStr(String s, StringBuilder o) { o.append((char)34); for (int i = 0; i < s.length(); i++) { char c = s.charAt(i); if (c == (char)34 || c == (char)92) { o.append((char)92); o.append(c); } else if (c == (char)10) { o.append((char)92); o.append('n'); } else if (c == (char)13) { o.append((char)92); o.append('r'); } else if (c == (char)9) { o.append((char)92); o.append('t'); } else if (c < 32) { o.append((char)92); o.append('u'); o.append(String.format("%04x", (int)c)); } else { o.append(c); } } o.append((char)34); } static void writeVal(Object v, StringBuilder o) { if (v == null) { o.append("null"); return; } if (v instanceof String) { writeStr((String)v, o); return; } if (v instanceof Boolean) { o.append(((Boolean)v).booleanValue() ? "true" : "false"); return; } if (v instanceof Integer) { o.append(v.toString()); return; } if (v instanceof Long) { o.append(v.toString()); return; } if (v instanceof Double) { String t = v.toString(); if (t.indexOf('.') < 0 && t.indexOf('e') < 0 && t.indexOf('E') < 0) { t = t + ".0"; } o.append(t); return; } if (v instanceof JSONObject) { o.append('{'); boolean first = true; for (Map.Entry<String, Object> e : ((JSONObject)v).values.entrySet()) { if (!first) { o.append(','); } first = false; writeStr(e.getKey(), o); o.append(':'); writeVal(e.getValue(), o); } o.append('}'); return; } if (v instanceof JSONArray) { o.append('['); ArrayList<Object> items = ((JSONArray)v).values; for (int i = 0; i < items.size(); i++) { if (i > 0) { o.append(','); } writeVal(items.get(i), o); } o.append(']'); return; } o.append("null"); } public static String write(Object v) { StringBuilder o = new StringBuilder(); writeVal(v, o); return o.toString(); } static class Pos { int i; Pos(int start) { i = start; } } static void skipWs(String s, Pos p) { while (p.i < s.length()) { char c = s.charAt(p.i); if (c == ' ' || c == (char)9 || c == (char)10 || c == (char)13) { p.i++; } else { break; } } } static String readStr(String s, Pos p) { StringBuilder o = new StringBuilder(); if (p.i < s.length() && s.charAt(p.i) == (char)34) { p.i++; } while (p.i < s.length() && s.charAt(p.i) != (char)34) { char c = s.charAt(p.i); if (c == (char)92 && (p.i + 1) < s.length()) { p.i++; char e = s.charAt(p.i); if (e == 'n') { o.append((char)10); } else if (e == 'r') { o.append((char)13); } else if (e == 't') { o.append((char)9); } else if (e == 'b') { o.append((char)8); } else if (e == 'f') { o.append((char)12); } else if (e == 'u') { if ((p.i + 4) < s.length()) { o.append((char)Integer.parseInt(s.substring(p.i + 1, p.i + 5), 16)); p.i += 4; } } else { o.append(e); } p.i++; continue; } o.append(c); p.i++; } if (p.i < s.length()) { p.i++; } return o.toString(); } static Object readVal(String s, Pos p) { skipWs(s, p); if (p.i >= s.length()) { return null; } char c = s.charAt(p.i); if (c == '{') { p.i++; JSONObject o = new JSONObject(); while (true) { skipWs(s, p); if (p.i >= s.length()) { break; } if (s.charAt(p.i) == '}') { p.i++; break; } if (s.charAt(p.i) == ',') { p.i++; continue; } String k = readStr(s, p); skipWs(s, p); if (p.i < s.length() && s.charAt(p.i) == ':') { p.i++; } o.put(k, readVal(s, p)); } return o; } if (c == '[') { p.i++; JSONArray a = new JSONArray(); while (true) { skipWs(s, p); if (p.i >= s.length()) { break; } if (s.charAt(p.i) == ']') { p.i++; break; } if (s.charAt(p.i) == ',') { p.i++; continue; } a.put(readVal(s, p)); } return a; } if (c == (char)34) { return readStr(s, p); } if (c == 't') { p.i += 4; return Boolean.TRUE; } if (c == 'f') { p.i += 5; return Boolean.FALSE; } if (c == 'n') { p.i += 4; return null; } int start = p.i; boolean isDouble = false; while (p.i < s.length()) { char d = s.charAt(p.i); if (d == '.' || d == 'e' || d == 'E') { isDouble = true; } else if (!(d == '-' || d == '+' || (d >= '0' && d <= '9'))) { break; } p.i++; } String text = s.substring(start, p.i); if (text.length() == 0) { p.i++; return null; } try { if (isDouble) { return Double.valueOf(text); } return Integer.valueOf(text); } catch (Exception e) { return isDouble ? (Object)Double.valueOf(0.0) : (Object)Integer.valueOf(0); } } public static Object readText(String s) { return readVal(s, new Pos(0)); }}
import java.io.*;
public class Main {
public static void main(String [] args ) { RgArgs.args = args; final Point p = new Point(); p.x = 3; p.y = 4; final JSONObject data = p.toDictionary(); final Point back = Point.fromDictionary(data); System.out.println(String.valueOf( (("x " + back.x) + " y ") + back.y ) ); }}
public class RgArgs { public static String[] args = new String[0];}__g_args = argsval p : Point = Point();p.x = 3;p.y = 4;val _data : JSONObject = p.toDictionary();val back : Point = Point.fromDictionary(_data);println( (("x " + (back.x).toString()) + " y ") + (back.y).toString() )The complete file
class Point { @JvmField var x : Int = 0; @JvmField var y : Int = 0; companion object {
fun fromDictionary( dict : JSONObject) : Point { val obj : Point = Point(); try { val v : Int? = (if (dict.isNull("x")) null else dict.optInt("x")); if ( v != null ) { obj.x = v!!; } val v_1 : Int? = (if (dict.isNull("y")) null else dict.optInt("y")); if ( v_1 != null ) { obj.y = v_1!!; } } catch( e : Exception ) { } return obj; } }
fun toDictionary() : JSONObject { var res : JSONObject = JSONObject(); try { res.put("x" , this.x); res.put("y" , this.y); } catch( e : Exception ) { } return res; }}
class Main {
}
var __g_args : Array<String> = arrayOf()
fun main(args : Array<String>) { __g_args = args val p : Point = Point(); p.x = 3; p.y = 4; val _data : JSONObject = p.toDictionary(); val back : Point = Point.fromDictionary(_data); println( (("x " + (back.x).toString()) + " y ") + (back.y).toString() )}__g_args = args;Point p = Point();p.x = 3;p.y = 4;Map<String, dynamic> data = p.toDictionary();Point back = Point.fromDictionary(data);print( (("x " + (back.x).toString()) + " y ") + (back.y).toString() );The complete file
class Point { int x = 0; int y = 0;
static Point fromDictionary(Map<String, dynamic> dict) { Point obj = Point(); try { int? v = rg_json_get_int(dict, "x"); if ( v != null ) { obj.x = v!; } int? v_1 = rg_json_get_int(dict, "y"); if ( v_1 != null ) { obj.y = v_1!; } } catch(e) { } return obj; }
Map<String, dynamic> toDictionary() { Map<String, dynamic> res = <String, dynamic>{}; try { res["x"] = this.x; res["y"] = this.y; } catch(e) { } return res; }}
class Main {}
List<String> __g_args = <String>[];
void main(List<String> args) { __g_args = args; Point p = Point(); p.x = 3; p.y = 4; Map<String, dynamic> data = p.toDictionary(); Point back = Point.fromDictionary(data); print( (("x " + (back.x).toString()) + " y ") + (back.y).toString() );}
Map<String, dynamic>? rg_json_get_obj(Map<String, dynamic> o, String k) { final v = o[k]; return v is Map<String, dynamic> ? v : null;}List<dynamic>? rg_json_get_arr(Map<String, dynamic> o, String k) { final v = o[k]; return v is List<dynamic> ? v : null;}String? rg_json_get_str(Map<String, dynamic> o, String k) { final v = o[k]; return v is String ? v : null;}bool? rg_json_get_bool(Map<String, dynamic> o, String k) { final v = o[k]; return v is bool ? v : null;}// A JSON number is int or double and the two are distinct types in Dart, so// each getter accepts both and converts, the way the Python and Rust entries do.int? rg_json_get_int(Map<String, dynamic> o, String k) { final v = o[k]; if (v is int) { return v; } if (v is double) { return v.toInt(); } return null;}double? rg_json_get_double(Map<String, dynamic> o, String k) { final v = o[k]; if (v is double) { return v; } if (v is int) { return v.toDouble(); } return null;}List<dynamic>? rg_json_as_arr(dynamic v) { return v is List<dynamic> ? v : null;}let p : Point = Point()p.x = 3;p.y = 4;let data : [String:Any] = p.toDictionary()let back : Point = Point.fromDictionary(dict : data)print((("x " + String(back.x)) + " y ") + String(back.y))The complete file
func ==(l: Point, r: Point) -> Bool { return l === r}final class Point : Hashable { func hash(into hasher: inout Hasher) { hasher.combine(ObjectIdentifier(self)) } var x : Int = 0 var y : Int = 0 class func fromDictionary(dict : [String:Any]) -> Point { let obj : Point = Point() let v : Int? = dict["x"] as? Int if ( v != nil ) { obj.x = v!; } let v_2 : Int? = dict["y"] as? Int if ( v_2 != nil ) { obj.y = v_2!; } return obj } func toDictionary() -> [String:Any] { var res : [String:Any] = [String:Any]() _ = res res["x"] = self.x res["y"] = self.y return res }}func ==(l: Main, r: Main) -> Bool { return l === r}final class Main : Hashable { func hash(into hasher: inout Hasher) { hasher.combine(ObjectIdentifier(self)) }}// Main entry pointfunc __main__swift() { let p : Point = Point() p.x = 3; p.y = 4; let data : [String:Any] = p.toDictionary() let back : Point = Point.fromDictionary(dict : data) print((("x " + String(back.x)) + " y ") + String(back.y))}__main__swift()Point p = new Point();p.x = 3;p.y = 4;System.Collections.Generic.Dictionary<string, object> data = p.toDictionary();Point back = Point.fromDictionary(data);Console.WriteLine((("x " + back.x) + " y ") + back.y);The complete file
using System;
// The JSON value on the C# target: an object is a Dictionary, an array is a// List and a value is the boxed object inside them, which is what `case v// x:JSONDataObject` type-tests against.static class RgJson { public static object Get(System.Collections.Generic.Dictionary<string, object> o, string k) { object v; if (o != null && o.TryGetValue(k, out v)) { return v; } return null; } public static string GetStr(System.Collections.Generic.Dictionary<string, object> o, string k) { return Get(o, k) as string; } public static System.Collections.Generic.Dictionary<string, object> GetObj(System.Collections.Generic.Dictionary<string, object> o, string k) { return Get(o, k) as System.Collections.Generic.Dictionary<string, object>; } public static System.Collections.Generic.List<object> GetArr(System.Collections.Generic.Dictionary<string, object> o, string k) { return Get(o, k) as System.Collections.Generic.List<object>; } public static bool? GetBool(System.Collections.Generic.Dictionary<string, object> o, string k) { object v = Get(o, k); if (v is bool) { return (bool)v; } return null; } // A JSON number reads back as int or double and the two are distinct types, // so each getter accepts both and converts, the way the Dart, Python and Rust // entries do. public static int? GetInt(System.Collections.Generic.Dictionary<string, object> o, string k) { object v = Get(o, k); if (v is int) { return (int)v; } if (v is double) { return (int)(double)v; } return null; } public static double? GetDouble(System.Collections.Generic.Dictionary<string, object> o, string k) { object v = Get(o, k); if (v is double) { return (double)v; } if (v is int) { return (double)(int)v; } return null; } public static System.Collections.Generic.List<object> AsArr(object v) { return v as System.Collections.Generic.List<object>; } public static object At(System.Collections.Generic.List<object> a, int i) { if (a != null && i >= 0 && i < a.Count) { return a[i]; } return null; } static readonly char[] Hexd = new char[] { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' }; static void WriteStr(string s, System.Text.StringBuilder o) { o.Append((char)34); for (int i = 0; i < s.Length; i++) { char c = s[i]; if (c == (char)34 || c == (char)92) { o.Append((char)92); o.Append(c); } else if (c == (char)10) { o.Append((char)92); o.Append('n'); } else if (c == (char)13) { o.Append((char)92); o.Append('r'); } else if (c == (char)9) { o.Append((char)92); o.Append('t'); } else if (c < (char)32) { o.Append((char)92); o.Append('u'); o.Append('0'); o.Append('0'); o.Append(Hexd[((int)c >> 4) & 15]); o.Append(Hexd[(int)c & 15]); } else { o.Append(c); } } o.Append((char)34); } static void Write(object v, System.Text.StringBuilder o) { if (v == null) { o.Append("null"); return; } if (v is string) { WriteStr((string)v, o); return; } if (v is bool) { o.Append(((bool)v) ? "true" : "false"); return; } if (v is int) { o.Append(((int)v).ToString(System.Globalization.CultureInfo.InvariantCulture)); return; } if (v is long) { o.Append(((long)v).ToString(System.Globalization.CultureInfo.InvariantCulture)); return; } if (v is double) { string t = ((double)v).ToString("R", System.Globalization.CultureInfo.InvariantCulture); if (t.IndexOf('.') < 0 && t.IndexOf('e') < 0 && t.IndexOf('E') < 0) { t = t + ".0"; } o.Append(t); return; } if (v is System.Collections.Generic.Dictionary<string, object>) { System.Collections.Generic.Dictionary<string, object> m = (System.Collections.Generic.Dictionary<string, object>)v; o.Append('{'); bool first = true; foreach (System.Collections.Generic.KeyValuePair<string, object> kv in m) { if (!first) { o.Append(','); } first = false; WriteStr(kv.Key, o); o.Append(':'); Write(kv.Value, o); } o.Append('}'); return; } if (v is System.Collections.Generic.List<object>) { System.Collections.Generic.List<object> a = (System.Collections.Generic.List<object>)v; o.Append('['); for (int i = 0; i < a.Count; i++) { if (i > 0) { o.Append(','); } Write(a[i], o); } o.Append(']'); return; } o.Append("null"); } public static string Str(object v) { System.Text.StringBuilder o = new System.Text.StringBuilder(); Write(v, o); return o.ToString(); } static void SkipWs(string s, ref int i) { while (i < s.Length && (s[i] == ' ' || s[i] == (char)9 || s[i] == (char)10 || s[i] == (char)13)) { i++; } } static string ReadStr(string s, ref int i) { System.Text.StringBuilder o = new System.Text.StringBuilder(); if (i < s.Length && s[i] == (char)34) { i++; } while (i < s.Length && s[i] != (char)34) { char c = s[i]; if (c == (char)92 && (i + 1) < s.Length) { i++; char e = s[i]; if (e == 'n') { o.Append((char)10); } else if (e == 'r') { o.Append((char)13); } else if (e == 't') { o.Append((char)9); } else if (e == 'b') { o.Append((char)8); } else if (e == 'f') { o.Append((char)12); } else if (e == 'u' && (i + 4) < s.Length) { o.Append((char)System.Convert.ToInt32(s.Substring(i + 1, 4), 16)); i = i + 4; } else { o.Append(e); } i++; continue; } o.Append(c); i++; } if (i < s.Length) { i++; } return o.ToString(); } static object Read(string s, ref int i) { SkipWs(s, ref i); if (i >= s.Length) { return null; } char c = s[i]; if (c == '{') { i++; System.Collections.Generic.Dictionary<string, object> o = new System.Collections.Generic.Dictionary<string, object>(); while (true) { SkipWs(s, ref i); if (i >= s.Length) { break; } if (s[i] == '}') { i++; break; } if (s[i] == ',') { i++; continue; } string k = ReadStr(s, ref i); SkipWs(s, ref i); if (i < s.Length && s[i] == ':') { i++; } o[k] = Read(s, ref i); } return o; } if (c == '[') { i++; System.Collections.Generic.List<object> a = new System.Collections.Generic.List<object>(); while (true) { SkipWs(s, ref i); if (i >= s.Length) { break; } if (s[i] == ']') { i++; break; } if (s[i] == ',') { i++; continue; } a.Add(Read(s, ref i)); } return a; } if (c == (char)34) { return ReadStr(s, ref i); } if (c == 't') { i = i + 4; return true; } if (c == 'f') { i = i + 5; return false; } if (c == 'n') { i = i + 4; return null; } int start = i; bool isDouble = false; while (i < s.Length) { char d = s[i]; if (d == '.' || d == 'e' || d == 'E') { isDouble = true; } else if (!(d == '-' || d == '+' || (d >= '0' && d <= '9'))) { break; } i++; } string text = s.Substring(start, i - start); if (text.Length == 0) { i++; return null; } if (isDouble) { return double.Parse(text, System.Globalization.CultureInfo.InvariantCulture); } return int.Parse(text, System.Globalization.CultureInfo.InvariantCulture); } public static System.Collections.Generic.Dictionary<string, object> Parse(string s) { int i = 0; object v = Read(s, ref i); if (v is System.Collections.Generic.Dictionary<string, object>) { return (System.Collections.Generic.Dictionary<string, object>)v; } throw new System.Exception("Invalid JSON"); }}
class Point { public int x = 0; public int y = 0; public static Point fromDictionary( System.Collections.Generic.Dictionary<string, object> dict ) { Point obj = new Point(); try { int? v = RgJson.GetInt(dict, "x"); if ( v != null ) { obj.x = (v).Value; } int? v_1 = RgJson.GetInt(dict, "y"); if ( v_1 != null ) { obj.y = (v_1).Value; } } catch( Exception e ) { } return obj; } public System.Collections.Generic.Dictionary<string, object> toDictionary() { System.Collections.Generic.Dictionary<string, object> res = new System.Collections.Generic.Dictionary<string, object>(); try { res["x"] = this.x; res["y"] = this.y; } catch( Exception e ) { } return res; }}class Main { static void Main( string [] args ) { Point p = new Point(); p.x = 3; p.y = 4; System.Collections.Generic.Dictionary<string, object> data = p.toDictionary(); Point back = Point.fromDictionary(data); Console.WriteLine((("x " + back.x) + " y ") + back.y); }}std::shared_ptr<Point> p = std::make_shared<Point>();p->x = 3;p->y = 4;rg_json_obj data = p->toDictionary();std::shared_ptr<Point> back = Point::fromDictionary(data);std::cout << ((std::string("x ") + std::to_string(back->x)) + std::string(" y ")) + std::to_string(back->y) << std::endl;return 0;The complete file
#include <memory>#include <stdexcept>#include <string>#include <iostream>
// define classes here to avoid compiler errorsclass Point;class Main;
template <class T>class r_optional_primitive { public: // has_value has to start false: cpp_str_to_int and its siblings leave the // field untouched when the conversion throws, and an indeterminate bool // made a failed str2int read back as a value on the C++ target. bool has_value = false; T value = T(); r_optional_primitive() {} // a plain value placed into an optional slot: returning a bare string // from a function declared @(optional):string arrives here. Declaring // any constructor takes the implicit default one away, hence the pair. r_optional_primitive(const T & a_value) : has_value(true), value(a_value) {} r_optional_primitive<T> & operator=(const r_optional_primitive<T> & rhs) { has_value = rhs.has_value; value = rhs.value; return *this; } r_optional_primitive<T> & operator=(const T a_value) { has_value = true; value = a_value; return *this; }};
#include <memory>#include <string>#include <vector>#include <variant>#include <utility>#include <stdexcept>#include <cstdlib>// A JSON value on the C++ target. The object and the array are handles, so// pushing an object into an array and then filling it keeps working the way it// does on JavaScript; the value is a variant, so `case v x:JSONDataObject`// lowers to the same std::holds_alternative that every other union uses.struct rg_json_obj_t;struct rg_json_arr_t;typedef std::shared_ptr<rg_json_obj_t> rg_json_obj;typedef std::shared_ptr<rg_json_arr_t> rg_json_arr;typedef std::variant<std::nullptr_t, bool, int, double, std::string, rg_json_arr, rg_json_obj> rg_json_val;struct rg_json_obj_t { std::vector<std::pair<std::string, rg_json_val> > items; };struct rg_json_arr_t { std::vector<rg_json_val> items; };inline rg_json_obj rg_json_new_obj() { return std::make_shared<rg_json_obj_t>(); }inline rg_json_arr rg_json_new_arr() { return std::make_shared<rg_json_arr_t>(); }inline int rg_json_len(const rg_json_arr& a) { return a ? (int)a->items.size() : 0; }inline std::vector<std::string> rg_json_keys(const rg_json_obj& o) { std::vector<std::string> r; if (o) { for (size_t i = 0; i < o->items.size(); i++) { r.push_back(o->items[i].first); } } return r;}inline rg_json_val rg_json_at(const rg_json_arr& a, int i) { if (!a || i < 0 || i >= (int)a->items.size()) { return rg_json_val(nullptr); } return a->items[(size_t)i];}inline rg_json_arr rg_json_as_arr(const rg_json_val& v) { if (std::holds_alternative<rg_json_arr>(v)) { return std::get<rg_json_arr>(v); } return rg_json_arr();}
inline const rg_json_val* rg_json_find(const rg_json_obj& o, const std::string& k) { if (!o) { return nullptr; } for (size_t i = 0; i < o->items.size(); i++) { if (o->items[i].first == k) { return &(o->items[i].second); } } return nullptr;}// getStr is declared optional, and every other target answers null for a key// that is absent or not a string. Returning a bare std::string made that the// empty string, which is a value.inline r_optional_primitive<std::string> rg_json_get_str(const rg_json_obj& o, const std::string& k) { r_optional_primitive<std::string> res; const rg_json_val* v = rg_json_find(o, k); if (v && std::holds_alternative<std::string>(*v)) { res = std::get<std::string>(*v); } return res;}inline bool rg_json_get_bool(const rg_json_obj& o, const std::string& k) { const rg_json_val* v = rg_json_find(o, k); if (v && std::holds_alternative<bool>(*v)) { return std::get<bool>(*v); } return false;}inline rg_json_obj rg_json_get_obj(const rg_json_obj& o, const std::string& k) { const rg_json_val* v = rg_json_find(o, k); if (v && std::holds_alternative<rg_json_obj>(*v)) { return std::get<rg_json_obj>(*v); } return rg_json_obj();}inline rg_json_arr rg_json_get_arr(const rg_json_obj& o, const std::string& k) { const rg_json_val* v = rg_json_find(o, k); if (v && std::holds_alternative<rg_json_arr>(*v)) { return std::get<rg_json_arr>(*v); } return rg_json_arr();}
inline r_optional_primitive<int> rg_json_get_int(const rg_json_obj& o, const std::string& k) { r_optional_primitive<int> res; const rg_json_val* v = rg_json_find(o, k); if (v) { if (std::holds_alternative<int>(*v)) { res.has_value = true; res.value = std::get<int>(*v); } else if (std::holds_alternative<double>(*v)) { res.has_value = true; res.value = (int)std::get<double>(*v); } } return res;}inline r_optional_primitive<double> rg_json_get_double(const rg_json_obj& o, const std::string& k) { r_optional_primitive<double> res; const rg_json_val* v = rg_json_find(o, k); if (v) { if (std::holds_alternative<double>(*v)) { res.has_value = true; res.value = std::get<double>(*v); } else if (std::holds_alternative<int>(*v)) { res.has_value = true; res.value = (double)std::get<int>(*v); } } return res;}
// Every member of the JSON unions reaches the variant through one of these, so// `set obj key 1` and `set obj key "one"` share one writer.inline rg_json_val rg_json_v(const rg_json_val& v) { return v; }inline rg_json_val rg_json_v(const rg_json_obj& v) { return rg_json_val(v); }inline rg_json_val rg_json_v(const rg_json_arr& v) { return rg_json_val(v); }inline rg_json_val rg_json_v(const std::string& v) { return rg_json_val(v); }inline rg_json_val rg_json_v(const char* v) { return rg_json_val(std::string(v)); }inline rg_json_val rg_json_v(bool v) { return rg_json_val(v); }inline rg_json_val rg_json_v(int v) { return rg_json_val(v); }inline rg_json_val rg_json_v(long v) { return rg_json_val((int)v); }inline rg_json_val rg_json_v(long long v) { return rg_json_val((int)v); }inline rg_json_val rg_json_v(double v) { return rg_json_val(v); }template <class T> void rg_json_set(const rg_json_obj& o, const std::string& k, const T& value) { if (!o) { return; } for (size_t i = 0; i < o->items.size(); i++) { if (o->items[i].first == k) { o->items[i].second = rg_json_v(value); return; } } o->items.push_back(std::make_pair(k, rg_json_v(value)));}template <class T> void rg_json_push(const rg_json_arr& a, const T& value) { if (!a) { return; } a->items.push_back(rg_json_v(value));}
// header definitionsclass Point { public : int x; int y; /* class constructor */ Point( ); /* static methods */ static std::shared_ptr<Point> fromDictionary( rg_json_obj dict ); /* instance methods */ rg_json_obj toDictionary();};class Main { public : /* class constructor */ Main( ); /* static methods */ static void main();};
int __g_argc;char **__g_argv;Point::Point( ) { this->x = 0; this->y = 0;}std::shared_ptr<Point> Point::fromDictionary( rg_json_obj dict ) { std::shared_ptr<Point> obj = std::make_shared<Point>(); try { r_optional_primitive<int> v = rg_json_get_int(dict, std::string("x")); if ( v.has_value ) { obj->x = /*unwrap int*/v.value; } r_optional_primitive<int> v_1 = rg_json_get_int(dict, std::string("y")); if ( v_1.has_value ) { obj->y = /*unwrap int*/v_1.value; } } catch( ... ) { std::string __rg_err_msg = "unspecified error"; try { throw; } catch( const std::exception& __rg_e ) { __rg_err_msg = __rg_e.what(); } catch( ... ) {} (void)__rg_err_msg; } return obj;}rg_json_obj Point::toDictionary() { rg_json_obj res = rg_json_new_obj(); try { rg_json_set(res, std::string("x"), this->x); rg_json_set(res, std::string("y"), this->y); } catch( ... ) { std::string __rg_err_msg = "unspecified error"; try { throw; } catch( const std::exception& __rg_e ) { __rg_err_msg = __rg_e.what(); } catch( ... ) {} (void)__rg_err_msg; } return res;}Main::Main( ) {}int main(int argc, char* argv[]) { __g_argc = argc; __g_argv = argv; std::shared_ptr<Point> p = std::make_shared<Point>(); p->x = 3; p->y = 4; rg_json_obj data = p->toDictionary(); std::shared_ptr<Point> back = Point::fromDictionary(data); std::cout << ((std::string("x ") + std::to_string(back->x)) + std::string(" y ")) + std::to_string(back->y) << std::endl; return 0;}$p = new Point();$p->x = 3;$p->y = 4;$data = $p->toDictionary();$back = Point::fromDictionary($data);echo( (("x " . $back->x) . " y ") . $back->y . "\n");The complete file
<?php
class Point { public int $x = 0; public int $y = 0; function __construct( ) { $this->x = 0; $this->y = 0; } public static function fromDictionary( $dict ) { $obj = new Point(); try { $v = isset($dict["x"]) ? $dict["x"] : null; if ( (isset($v)) ) { $obj->x = $v; } $v_1 = isset($dict["y"]) ? $dict["y"] : null; if ( (isset($v_1)) ) { $obj->y = $v_1; } } catch( Exception $e) { } return $obj; } function toDictionary() { $res = array(); try { $res["x"] = $this->x; $res["y"] = $this->y; } catch( Exception $e) { } return $res; }}class Main { function __construct( ) { }}/* static PHP main routine */$p = new Point();$p->x = 3;$p->y = 4;$data = $p->toDictionary();$back = Point::fromDictionary($data);echo( (("x " . $back->x) . " y ") . $back->y . "\n");The compiler does not write Scala code for this example. The message is:
18: Could not match argument types for json_object18: Variable was assigned an incompatible type. Types were JSONDataObject vs <no type>21: Could not match argument types for set23: Could not match argument types for set5: Could not match argument types for getInt5: Unknown type: type ID : 06: !null? applies only to optional values; 'v' is non-optional ()7: Could not match argument types for unwrap7: Could not match argument types for =6: Could not match argument types for if9: Could not match argument types for getInt9: Unknown type: type ID : 010: !null? applies only to optional values; 'v' is non-optional ()11: Could not match argument types for unwrap11: Could not match argument types for =10: Could not match argument types for ifTwo rules apply:
- Every class that the serialized class refers to must also be
@serialize(true), or it must holdtoDictionaryandfromDictionaryby hand. The compiler stops with the name of the class that is not serializable. - The generated code uses the JSON operators. The tabs above show which targets have them.
Which annotations change the code for C++, Rust and Swift?
Section titled “Which annotations change the code for C++, Rust and Swift?”Most targets collect the memory that a program does not use. C++, Rust and
Swift count references instead, and two objects that hold each other keep each
other alive. Ranger has four annotations for this: weak, strong, lives
and temp.
The program below is the case that matters: a parent holds a child, and the
child holds the parent back. The back reference carries @(weak).
class Node { def name:string "" def child@(optional):Node ; The parent must not keep the child alive: the two would then hold each ; other, and a target that counts references would free neither. def parent@(weak optional):Node}
class Main { sfn main:void () { def root:Node (new Node()) root.name = "root" def leaf:Node (new Node()) leaf.name = "leaf"
root.child = leaf leaf.parent = root
def kid:Node (!! root.child) print ("child of root " + kid.name) }}const root = new Node();root.name = "root";const leaf = new Node();leaf.name = "leaf";root.child = leaf;leaf.parent = root;const kid = root.child;console.log("child of root " + kid.name);The complete file
class Node { constructor() { this.name = ""; this.child = undefined; this.parent = undefined; }}class Main { constructor() { }}/* static JavaSript main routine at the end of the JS file */function __js_main() { const root = new Node(); root.name = "root"; const leaf = new Node(); leaf.name = "leaf"; root.child = leaf; leaf.parent = root; const kid = root.child; console.log("child of root " + kid.name);}__js_main();const root : Node = new Node();root.name = "root";const leaf : Node = new Node();leaf.name = "leaf";root.child = leaf;leaf.parent = root;const kid : Node = root.child;console.log("child of root " + kid.name);The complete file
export class Node { name!: string; child?: Node; parent?: Node; constructor() { this.name = ""; }}export class Main { constructor() { }}/* static JavaSript main routine at the end of the JS file */function __js_main() { const root : Node = new Node(); root.name = "root"; const leaf : Node = new Node(); leaf.name = "leaf"; root.child = leaf; leaf.parent = root; const kid : Node = root.child; console.log("child of root " + kid.name);}__js_main();var root *Node= CreateNew_Node();root.name = "root";var leaf *Node= CreateNew_Node();leaf.name = "leaf";root.child.value = leaf;root.child.has_value = true; /* detected as non-optional */leaf.parent.value = root;leaf.parent.has_value = true; /* detected as non-optional */var kid *Node= root.child.value.(*Node); _ = kidfmt.Println( "child of root " + kid.name )The complete file
package mainimport ( "fmt")
type GoNullable struct { value interface{} has_value bool}
type Node struct { name string `json:"name"` child *GoNullable `json:"child"` parent *GoNullable `json:"parent"`}
func CreateNew_Node() *Node { me := new(Node) me.name = "" me.child = new(GoNullable); me.parent = new(GoNullable); return me;}type Main struct {}
func CreateNew_Main() *Main { me := new(Main) return me;}func main() { var root *Node= CreateNew_Node(); root.name = "root"; var leaf *Node= CreateNew_Node(); leaf.name = "leaf"; root.child.value = leaf; root.child.has_value = true; /* detected as non-optional */ leaf.parent.value = root; leaf.parent.has_value = true; /* detected as non-optional */ var kid *Node= root.child.value.(*Node); _ = kid fmt.Println( "child of root " + kid.name )}let __rg_main_thread = std::thread::Builder::new().stack_size(512 * 1024 * 1024) .spawn(__rg_main_body).expect("could not start the main thread");__rg_main_thread.join().expect("main thread panicked");The complete file
#![allow(dead_code)]#![allow(unused_mut)]
use std::rc::Rc;use std::rc::Weak;use std::cell::RefCell;
pub trait RgAnyRef { fn rg_as_any(&self) -> &dyn std::any::Any; }fn rg_downcast<T: 'static, D: ?Sized + RgAnyRef>(v: &Rc<RefCell<D>>) -> Rc<RefCell<T>> { assert!(v.borrow().rg_as_any().is::<T>(), "invalid downcast"); let p = Rc::into_raw(v.clone()) as *const () as *const RefCell<T>; unsafe { Rc::from_raw(p) }}pub trait RgIdentical { fn rg_identical(&self, other: &Self) -> bool; }impl<T: ?Sized> RgIdentical for Rc<RefCell<T>> { fn rg_identical(&self, other: &Self) -> bool { Rc::ptr_eq(self, other) }}
#[derive(Clone)]struct Node { name: &'static str, child: Option<Rc<RefCell<Node>>>, parent: Option<Weak<RefCell<Node>>>,}impl Node { pub fn new() -> Self { Self { name: "", child: None, parent: None, } }}#[derive(Clone)]struct Main {}impl Main { pub fn new() -> Self { Self { } }}fn main() { let __rg_main_thread = std::thread::Builder::new().stack_size(512 * 1024 * 1024) .spawn(__rg_main_body).expect("could not start the main thread"); __rg_main_thread.join().expect("main thread panicked");}fn __rg_main_body() { let mut root: Rc<RefCell<Node>> = Rc::new(RefCell::new(Node::new())); root.borrow_mut().name = "root"; let mut leaf: Rc<RefCell<Node>> = Rc::new(RefCell::new(Node::new())); leaf.borrow_mut().name = "leaf"; root.borrow_mut().child = Some(leaf.clone()); leaf.borrow_mut().parent = Some(Rc::downgrade(&root)); let mut kid: Rc<RefCell<Node>> = root.borrow().child.unwrap(); println!("child of root {}", kid.borrow().name);}root = Node()root.name = "root";leaf = Node()leaf.name = "leaf";root.child = leaf;leaf.parent = root;kid = root.childprint("child of root " + kid.name)The complete file
# -*- coding: utf-8 -*-from __future__ import annotationsfrom typing import Optional
class Node: def __init__(self) -> None: self.name = "" self.child = None self.parent = Noneclass Main: def __init__(self) -> None: pass# Main entry pointdef main(): root = Node() root.name = "root"; leaf = Node() leaf.name = "leaf"; root.child = leaf; leaf.parent = root; kid = root.child print("child of root " + kid.name)if __name__ == "__main__": main()RgArgs.args = args;final Node root = new Node();root.name = "root";final Node leaf = new Node();leaf.name = "leaf";root.child = leaf;leaf.parent = root;final Node kid = root.child;System.out.println(String.valueOf( "child of root " + kid.name ) );The complete file
public class Node { public String name = ""; public Node child = null; public Node parent = null;}
import java.io.*;
public class Main {
public static void main(String [] args ) { RgArgs.args = args; final Node root = new Node(); root.name = "root"; final Node leaf = new Node(); leaf.name = "leaf"; root.child = leaf; leaf.parent = root; final Node kid = root.child; System.out.println(String.valueOf( "child of root " + kid.name ) ); }}
public class RgArgs { public static String[] args = new String[0];}__g_args = argsval root : Node = Node();root.name = "root";val leaf : Node = Node();leaf.name = "leaf";root.child = leaf;leaf.parent = root;val kid : Node = root.child!!;println( "child of root " + kid.name )The complete file
class Node { @JvmField var name : String = ""; @JvmField var child : Node? = null; @JvmField var parent : Node? = null;}
class Main {
}
var __g_args : Array<String> = arrayOf()
fun main(args : Array<String>) { __g_args = args val root : Node = Node(); root.name = "root"; val leaf : Node = Node(); leaf.name = "leaf"; root.child = leaf; leaf.parent = root; val kid : Node = root.child!!; println( "child of root " + kid.name )}__g_args = args;Node root = Node();root.name = "root";Node leaf = Node();leaf.name = "leaf";root.child = leaf;leaf.parent = root;Node kid = root.child!;print( "child of root " + kid.name );The complete file
class Node { String name = ""; Node? child = null; Node? parent = null;}
class Main {}
List<String> __g_args = <String>[];
void main(List<String> args) { __g_args = args; Node root = Node(); root.name = "root"; Node leaf = Node(); leaf.name = "leaf"; root.child = leaf; leaf.parent = root; Node kid = root.child!; print( "child of root " + kid.name );}let root : Node = Node()root.name = "root";let leaf : Node = Node()leaf.name = "leaf";root.child = leaf;leaf.parent = root;let kid : Node = root.child!print("child of root " + kid.name)The complete file
func ==(l: Node, r: Node) -> Bool { return l === r}final class Node : Hashable { func hash(into hasher: inout Hasher) { hasher.combine(ObjectIdentifier(self)) } var name : String = "" var child : Node? = nil weak var parent : Node? = nil}func ==(l: Main, r: Main) -> Bool { return l === r}final class Main : Hashable { func hash(into hasher: inout Hasher) { hasher.combine(ObjectIdentifier(self)) }}// Main entry pointfunc __main__swift() { let root : Node = Node() root.name = "root"; let leaf : Node = Node() leaf.name = "leaf"; root.child = leaf; leaf.parent = root; let kid : Node = root.child! print("child of root " + kid.name)}__main__swift()Node root = new Node();root.name = "root";Node leaf = new Node();leaf.name = "leaf";root.child = leaf;leaf.parent = root;Node kid = root.child;Console.WriteLine("child of root " + kid.name);The complete file
using System;class Node { public String name = ""; public Node child; public Node parent;}class Main { static void Main( string [] args ) { Node root = new Node(); root.name = "root"; Node leaf = new Node(); leaf.name = "leaf"; root.child = leaf; leaf.parent = root; Node kid = root.child; Console.WriteLine("child of root " + kid.name); }}std::shared_ptr<Node> root = std::make_shared<Node>();root->name = std::string("root");std::shared_ptr<Node> leaf = std::make_shared<Node>();leaf->name = std::string("leaf");root->child = leaf;leaf->parent = root;std::shared_ptr<Node> kid = root->child;std::cout << std::string("child of root ") + kid->name << std::endl;return 0;The complete file
#include <memory>#include <string>#include <iostream>
// define classes here to avoid compiler errorsclass Node;class Main;
// a `weak` field: it holds no reference count, and it reads like a std::shared_ptrtemplate <class T> class r_weak { public : std::weak_ptr<T> w; r_weak() { } r_weak(std::nullptr_t) { } r_weak(const std::shared_ptr<T>& s) : w(s) { } r_weak<T>& operator=(const std::shared_ptr<T>& s) { w = s; return *this; } r_weak<T>& operator=(std::nullptr_t) { w.reset(); return *this; } operator std::shared_ptr<T>() const { return w.lock(); } std::shared_ptr<T> lock() const { return w.lock(); } T* operator->() const { return w.lock().get(); } explicit operator bool() const { return !w.expired(); } bool operator==(std::nullptr_t) const { return w.expired(); } bool operator!=(std::nullptr_t) const { return !w.expired(); }};
// header definitionsclass Node { public : std::string name; std::shared_ptr<Node> child; r_weak<Node> parent; /* class constructor */ Node( );};class Main { public : /* class constructor */ Main( ); /* static methods */ static void main();};
int __g_argc;char **__g_argv;Node::Node( ) {}Main::Main( ) {}int main(int argc, char* argv[]) { __g_argc = argc; __g_argv = argv; std::shared_ptr<Node> root = std::make_shared<Node>(); root->name = std::string("root"); std::shared_ptr<Node> leaf = std::make_shared<Node>(); leaf->name = std::string("leaf"); root->child = leaf; leaf->parent = root; std::shared_ptr<Node> kid = root->child; std::cout << std::string("child of root ") + kid->name << std::endl; return 0;}$root = new Node();$root->name = "root";$leaf = new Node();$leaf->name = "leaf";$root->child = $leaf;$leaf->parent = $root;$kid = $root->child;echo( "child of root " . $kid->name . "\n");The complete file
<?php
class Node { public string $name = ''; public ?Node $child = null; public ?Node $parent = null; function __construct( ) { $this->name = ""; $this->child; $this->parent; }}class Main { function __construct( ) { }}/* static PHP main routine */$root = new Node();$root->name = "root";$leaf = new Node();$leaf->name = "leaf";$root->child = $leaf;$leaf->parent = $root;$kid = $root->child;echo( "child of root " . $kid->name . "\n");val root : Node = new Node()root.name = "root"val leaf : Node = new Node()leaf.name = "leaf"root.child = Some(leaf)leaf.parent = Some(root)val kid : Node = root.child.getprintln( "child of root " + kid.name )The complete file
case class ScalaReturnValue(value:Any) extends Exceptionclass Node { var name : String = "" var child : Option[Node] = Option.empty[Node] var parent : Option[Node] = Option.empty[Node]}
// application main function for Mainobject AppMain extends App { val root : Node = new Node() root.name = "root" val leaf : Node = new Node() leaf.name = "leaf" root.child = Some(leaf) leaf.parent = Some(root) val kid : Node = root.child.get println( "child of root " + kid.name )}This is what the three targets do with that annotation. The statements come from the output above and from the writers of the compiler. A tab holds the main function, and the class with the two fields is in the complete file behind the link under the code.
std::shared_ptr<Node> child;r_weak<Node> parent;r_weak<T> is a small wrapper that the compiler writes above the classes. It
holds a std::weak_ptr<T> and gives the shared pointer back at the read, so a
field access, a null test and an assignment stay as they were.
The measurement is a leak check. A parent and a child that hold each other with
strong references, built with g++ -fsanitize=address, reports
168 byte(s) leaked in 3 allocation(s). With @(weak) on the back reference
the same program leaks nothing.
var child : Node?weak var parent : Node?ARC then frees the pair. Swift needs two things: the storage must be a var,
and the type must be optional. Swift sets a weak reference to nil when the
object goes away. Write @(weak optional), as the example does. A field that
states weak without optional keeps the strong form, because
weak var parent : Node is not Swift that compiles.
child : Option<Box<Node>>,parent : Option<Weak<RefCell<Node>>>,The Rust writer reads weak, and the assignment becomes Rc::downgrade(…).
The Rust output of that assignment does not compile. rustc rejects the
read of the field, and the Rc that Rc::downgrade takes is a temporary, so
the weak reference would be empty even if it compiled. The cause is under the
annotation: a Rust class is a plain struct, so no Rc holds the parent. Do
not use @(weak) in a program that must compile for Rust.
The other three annotations
Section titled “The other three annotations”| Annotation | Measured effect |
|---|---|
strong |
The target code does not change. |
lives |
The target code does not change. The compiler uses the annotation for its own lifetime bookkeeping. |
temp |
The target code does not change, for the same reason. |
On a target that collects memory — JavaScript, TypeScript, Java, Kotlin, Dart, C#, Go, Python, PHP and Scala — none of the four changes the output. The collector handles a cycle.
Ownership and lifetime states the model behind these annotations, and the memory page states what each target writes.
Why does my call not compile?
Section titled “Why does my call not compile?”Ranger is an s-expression language. A call is (function argument argument).
A call on a dotted receiver may also be written the way the C family writes
it, with nothing between the name and the (. The parser folds the two into one
call node, so both spellings below are the same program:
| Both of these work | |
|---|---|
return this.helper() |
return (this.helper()) |
return this.helper() + 10 |
def v:int (this.helper()) then return (v + 10) |
def v:int (this.helper() + 1) |
def v:int (this.helper()) then def w:int (v + 1) |
this.other(this.helper()) |
this.other((this.helper())) |
return a.b().c() |
return (a.b().c()) |
What still needs the parentheses, or a local:
| Write | Do not write | Why |
|---|---|---|
return (fn1(3)) |
return fn1(3) |
The fold reaches a dotted receiver only. An undotted name in front of a ( is also how new Type(...) and a method declaration are spelled. |
def recv:T (expr) then recv.method() |
(expr).method() |
A statement must not start with a receiver in parentheses. |
def n:T (h.nodeOf()) then f(n.plain) |
f((h.nodeOf()).plain) |
A parenthesised receiver followed by a field does not resolve in argument position. |
| One statement per line | { def c:int 5 return c } |
Two statements on one line is a parse error. |
A property read on a parenthesised receiver compiles in an infix operator:
((unwrap x).v == 1) and (1 + (f()).v). A method call on that receiver
inside an infix expression still needs a local. A statement must not start
with a parenthesised receiver.
class Helper { fn value:int () { return 42 }}
class Main { sfn main:void () { def helper:Helper (new Helper())
; A call gives a value. On a dotted receiver the parentheses around it ; are optional, so `(helper.value())` and `helper.value()` are the same ; call, and arithmetic may use one directly. def n (helper.value()) def total (helper.value() + 1) print ("total " + total) }}const helper = new Helper();const n = helper.value();const total = helper.value() + 1;console.log("total " + total);The complete file
class Helper { constructor() { } value () { return 42; };}class Main { constructor() { }}/* static JavaSript main routine at the end of the JS file */function __js_main() { const helper = new Helper(); const n = helper.value(); const total = helper.value() + 1; console.log("total " + total);}__js_main();const helper : Helper = new Helper();const n : number = helper.value();const total : number = helper.value() + 1;console.log("total " + total);The complete file
export class Helper { constructor() { } value () : number { return 42; };}export class Main { constructor() { }}/* static JavaSript main routine at the end of the JS file */function __js_main() { const helper : Helper = new Helper(); const n : number = helper.value(); const total : number = helper.value() + 1; console.log("total " + total);}__js_main();var helper *Helper= CreateNew_Helper(); _ = helper _ = helper.value()var total int64= helper.value() + int64(1);fmt.Println( strings.Join([]string{ "total ",strconv.FormatInt(total, 10) }, "") )The complete file
package mainimport ( "strings" "strconv" "fmt")type Helper struct {}
func CreateNew_Helper() *Helper { me := new(Helper) return me;}func (this *Helper) value () int64 { return int64(42)}type Main struct {}
func CreateNew_Main() *Main { me := new(Main) return me;}func main() { var helper *Helper= CreateNew_Helper(); _ = helper _ = helper.value() var total int64= helper.value() + int64(1); fmt.Println( strings.Join([]string{ "total ",strconv.FormatInt(total, 10) }, "") )}let __rg_main_thread = std::thread::Builder::new().stack_size(512 * 1024 * 1024) .spawn(__rg_main_body).expect("could not start the main thread");__rg_main_thread.join().expect("main thread panicked");The complete file
#![allow(dead_code)]
#[derive(Clone)]struct Helper {}impl Helper { pub fn new() -> Self { Self { } } fn value() -> i64 { 42 }}#[derive(Clone)]struct Main {}impl Main { pub fn new() -> Self { Self { } }}fn main() { let __rg_main_thread = std::thread::Builder::new().stack_size(512 * 1024 * 1024) .spawn(__rg_main_body).expect("could not start the main thread"); __rg_main_thread.join().expect("main thread panicked");}fn __rg_main_body() { let helper: Helper = Helper::new(); let _n: i64 = Helper::value(); let total: i64 = Helper::value() + 1; println!("total {}", total);}helper = Helper()_n = helper.value()total = helper.value() + 1print("total " + str(total))The complete file
# -*- coding: utf-8 -*-from __future__ import annotationsfrom typing import Optional
class Helper: def __init__(self) -> None: pass def value(self) -> int: return 42;class Main: def __init__(self) -> None: pass# Main entry pointdef main(): helper = Helper() _n = helper.value() total = helper.value() + 1 print("total " + str(total))if __name__ == "__main__": main()RgArgs.args = args;final Helper helper = new Helper();/* unused: final Integer n = helper.value() **/ ;final Integer total = helper.value() + 1;System.out.println(String.valueOf( "total " + total ) );The complete file
public class Helper {
public Integer value() { return 42; }}
import java.io.*;
public class Main {
public static void main(String [] args ) { RgArgs.args = args; final Helper helper = new Helper(); /* unused: final Integer n = helper.value() **/ ; final Integer total = helper.value() + 1; System.out.println(String.valueOf( "total " + total ) ); }}
public class RgArgs { public static String[] args = new String[0];}__g_args = argsval helper : Helper = Helper();helper.value();val total : Int = helper.value() + 1;println( "total " + (total).toString() )The complete file
class Helper {
fun value() : Int { return 42; }}
class Main {
}
var __g_args : Array<String> = arrayOf()
fun main(args : Array<String>) { __g_args = args val helper : Helper = Helper(); helper.value(); val total : Int = helper.value() + 1; println( "total " + (total).toString() )}__g_args = args;Helper helper = Helper();helper.value();int total = helper.value() + 1;print( "total " + (total).toString() );The complete file
class Helper {
int value() { return 42; }}
class Main {}
List<String> __g_args = <String>[];
void main(List<String> args) { __g_args = args; Helper helper = Helper(); helper.value(); int total = helper.value() + 1; print( "total " + (total).toString() );}let helper : Helper = Helper()_ = helper.value();let total : Int = helper.value() + 1print("total " + String(total))The complete file
func ==(l: Helper, r: Helper) -> Bool { return l === r}final class Helper : Hashable { func hash(into hasher: inout Hasher) { hasher.combine(ObjectIdentifier(self)) } func value() -> Int { return 42 }}func ==(l: Main, r: Main) -> Bool { return l === r}final class Main : Hashable { func hash(into hasher: inout Hasher) { hasher.combine(ObjectIdentifier(self)) }}// Main entry pointfunc __main__swift() { let helper : Helper = Helper() _ = helper.value(); let total : Int = helper.value() + 1 print("total " + String(total))}__main__swift()Helper helper = new Helper();int _n = helper.value();int total = helper.value() + 1;Console.WriteLine("total " + total);The complete file
using System;class Helper { public int value() { return 42; }}class Main { static void Main( string [] args ) { Helper helper = new Helper(); int _n = helper.value(); int total = helper.value() + 1; Console.WriteLine("total " + total); }}std::shared_ptr<Helper> helper = std::make_shared<Helper>();int n = helper->value();int total = helper->value() + 1;std::cout << std::string("total ") + std::to_string(total) << std::endl;return 0;The complete file
#include <memory>#include <iostream>#include <string>
// define classes here to avoid compiler errorsclass Helper;class Main;
// header definitionsclass Helper { public : /* class constructor */ Helper( ); /* instance methods */ int value();};class Main { public : /* class constructor */ Main( ); /* static methods */ static void main();};
int __g_argc;char **__g_argv;Helper::Helper( ) {}int Helper::value() { return 42;}Main::Main( ) {}int main(int argc, char* argv[]) { __g_argc = argc; __g_argv = argv; std::shared_ptr<Helper> helper = std::make_shared<Helper>(); int n = helper->value(); int total = helper->value() + 1; std::cout << std::string("total ") + std::to_string(total) << std::endl; return 0;}$helper = new Helper();/* unused: $n = $helper->value() **/ ;$total = $helper->value() + 1;echo( "total " . $total . "\n");The complete file
<?php
class Helper { function __construct( ) { } function value() { return 42; }}class Main { function __construct( ) { }}/* static PHP main routine */$helper = new Helper();/* unused: $n = $helper->value() **/ ;$total = $helper->value() + 1;echo( "total " . $total . "\n");val helper : Helper = new Helper()/** unused val n : Int = helper.value()**/val total : Int = helper.value() + 1println( "total " + total )The complete file
case class ScalaReturnValue(value:Any) extends Exceptionclass Helper { def value() : Int = 42}
// application main function for Mainobject AppMain extends App { val helper : Helper = new Helper() /** unused val n : Int = helper.value()**/ val total : Int = helper.value() + 1 println( "total " + total )}What does “Could not find suitable match for the operator node” mean?
Section titled “What does “Could not find suitable match for the operator node” mean?”The call is to a defn macro, and no macro of that name fits the arguments.
A macro declares no types. The compiler selects one by trial. It expands the body of each macro with that name into the call site and compiles the result. The first candidate that makes no error wins. The message says that every candidate made an error.
The errors above the message come from the candidate with the fewest errors.
That candidate is not always the macro that you had in mind. Read the message
together with the bodies on the
macros page, and start from the types of your
arguments. ForEach is an example: one macro reads an array, and another one
reads a hash map, and only the body states the difference.
Which operators can I use?
Section titled “Which operators can I use?”compiler/Lang.rgr is the language definition. Ranger has no separate
standard library. You can declare more library operators for the compiler in
Lang.rgr and in imported files. A custom operator needs a new compiler.
- The operator reference lists
Lang.rgr. Every program can use those operators. stdlib.rgris an imported file. It addsmap,filter,reduce,any,allandslice.JSON.rgrand the other imported files work the same way.
How do I divide two integers?
Section titled “How do I divide two integers?”The operator / on two integers gives a double. The operator idiv gives
an integer and truncates toward zero.
class Main { sfn main:void () { def a 10 def b 3 print ("real " + (a / b)) print ("integer " + (idiv a b)) }}const a = 10;const b = 3;console.log("real " + a / b);console.log("integer " + ((a / b) | 0));The complete file
class Main { constructor() { }}/* static JavaSript main routine at the end of the JS file */function __js_main() { const a = 10; const b = 3; console.log("real " + a / b); console.log("integer " + ((a / b) | 0));}__js_main();const a : number = 10;const b : number = 3;console.log("real " + a / b);console.log("integer " + ((a / b) | 0));The complete file
export class Main { constructor() { }}/* static JavaSript main routine at the end of the JS file */function __js_main() { const a : number = 10; const b : number = 3; console.log("real " + a / b); console.log("integer " + ((a / b) | 0));}__js_main();var a int64= int64(10);var b int64= int64(3);fmt.Println( strings.Join([]string{ "real ",strconv.FormatFloat(r_div_f64(float64(a), float64(b)),'f', -1, 64) }, "") )fmt.Println( strings.Join([]string{ "integer ",strconv.FormatInt(a / b, 10) }, "") )The complete file
package mainimport ( "strings" "strconv" "fmt")
func r_div_f64(a float64, b float64) float64 { return a / b}
type Main struct {}
func CreateNew_Main() *Main { me := new(Main) return me;}func main() { var a int64= int64(10); var b int64= int64(3); fmt.Println( strings.Join([]string{ "real ",strconv.FormatFloat(r_div_f64(float64(a), float64(b)),'f', -1, 64) }, "") ) fmt.Println( strings.Join([]string{ "integer ",strconv.FormatInt(a / b, 10) }, "") )}let __rg_main_thread = std::thread::Builder::new().stack_size(512 * 1024 * 1024) .spawn(__rg_main_body).expect("could not start the main thread");__rg_main_thread.join().expect("main thread panicked");The complete file
#![allow(dead_code)]
#[derive(Clone)]struct Main {}impl Main { pub fn new() -> Self { Self { } }}fn main() { let __rg_main_thread = std::thread::Builder::new().stack_size(512 * 1024 * 1024) .spawn(__rg_main_body).expect("could not start the main thread"); __rg_main_thread.join().expect("main thread panicked");}fn __rg_main_body() { let a: i64 = 10; let b: i64 = 3; println!("real {}", a as f64 / b as f64); println!("integer {}", a / b);}a = 10b = 3print("real " + str(r_div_f64(float(a), float(b))))print("integer " + str(((a) // (b))))The complete file
# -*- coding: utf-8 -*-from __future__ import annotationsfrom typing import Optional
import math
def r_div_f64(a, b): if b == 0.0: if a == 0.0 or a != a: return float('nan') return math.copysign(float('inf'), a) * math.copysign(1.0, b) return a / b
class Main: def __init__(self) -> None: pass# Main entry pointdef main(): a = 10 b = 3 print("real " + str(r_div_f64(float(a), float(b)))) print("integer " + str(((a) // (b))))if __name__ == "__main__": main()RgArgs.args = args;final Integer a = 10;final Integer b = 3;System.out.println(String.valueOf( "real " + ((double)(a) / (double)(b)) ) );System.out.println(String.valueOf( "integer " + ((a) / (b)) ) );The complete file
import java.io.*;
public class Main {
public static void main(String [] args ) { RgArgs.args = args; final Integer a = 10; final Integer b = 3; System.out.println(String.valueOf( "real " + ((double)(a) / (double)(b)) ) ); System.out.println(String.valueOf( "integer " + ((a) / (b)) ) ); }}
public class RgArgs { public static String[] args = new String[0];}__g_args = argsval a : Int = 10;val b : Int = 3;println( "real " + (a.toDouble() / b.toDouble()).toString() )println( "integer " + (a / b).toString() )The complete file
class Main {
}
var __g_args : Array<String> = arrayOf()
fun main(args : Array<String>) { __g_args = args val a : Int = 10; val b : Int = 3; println( "real " + (a.toDouble() / b.toDouble()).toString() ) println( "integer " + (a / b).toString() )}__g_args = args;int a = 10;int b = 3;print( "real " + (a / b).toString() );print( "integer " + (((a) ~/ (b))).toString() );The complete file
class Main {}
List<String> __g_args = <String>[];
void main(List<String> args) { __g_args = args; int a = 10; int b = 3; print( "real " + (a / b).toString() ); print( "integer " + (((a) ~/ (b))).toString() );}let a : Int = 10let b : Int = 3print("real " + String((Double(a) / Double(b))))print("integer " + String(a / b))The complete file
func ==(l: Main, r: Main) -> Bool { return l === r}final class Main : Hashable { func hash(into hasher: inout Hasher) { hasher.combine(ObjectIdentifier(self)) }}// Main entry pointfunc __main__swift() { let a : Int = 10 let b : Int = 3 print("real " + String((Double(a) / Double(b)))) print("integer " + String(a / b))}__main__swift()int a = 10;int b = 3;Console.WriteLine("real " + ((double)(a) / (double)(b)));Console.WriteLine("integer " + (a / b));The complete file
using System;class Main { static void Main( string [] args ) { int a = 10; int b = 3; Console.WriteLine("real " + ((double)(a) / (double)(b))); Console.WriteLine("integer " + (a / b)); }}int a = 10;int b = 3;std::cout << std::string("real ") + r_double_to_string(((double)(a) / (double)(b))) << std::endl;std::cout << std::string("integer ") + std::to_string(((a) / (b))) << std::endl;return 0;The complete file
#include <memory>#include <sstream>#include <iomanip>#include <string>#include <cstdlib>#include <iostream>
// define classes here to avoid compiler errorsclass Main;
inline std::string r_double_to_string(double v) { for (int p = 1; p < 18; p++) { std::ostringstream s; s << std::setprecision(p) << v; /* strtod, not stod: stod THROWS out_of_range when a low-precision candidate like "2e+308" overflows; strtod answers HUGE_VAL, which simply fails the round-trip test. */ const std::string cand = s.str(); if (std::strtod(cand.c_str(), nullptr) == v) { return cand; } } std::ostringstream s; s << std::setprecision(17) << v; return s.str();}
// header definitionsclass Main { public : /* class constructor */ Main( ); /* static methods */ static void main();};
int __g_argc;char **__g_argv;Main::Main( ) {}int main(int argc, char* argv[]) { __g_argc = argc; __g_argv = argv; int a = 10; int b = 3; std::cout << std::string("real ") + r_double_to_string(((double)(a) / (double)(b))) << std::endl; std::cout << std::string("integer ") + std::to_string(((a) / (b))) << std::endl; return 0;}$a = 10;$b = 3;echo( "real " . ($a / $b) . "\n");echo( "integer " . intdiv($a, $b) . "\n");The complete file
<?php
class Main { function __construct( ) { }}/* static PHP main routine */$a = 10;$b = 3;echo( "real " . ($a / $b) . "\n");echo( "integer " . intdiv($a, $b) . "\n");val a : Int = 10val b : Int = 3println( "real " + (a.toDouble / b.toDouble) )println( "integer " + (a / b) )The complete file
case class ScalaReturnValue(value:Any) extends Exception
// application main function for Mainobject AppMain extends App { val a : Int = 10 val b : Int = 3 println( "real " + (a.toDouble / b.toDouble) ) println( "integer " + (a / b) )}Why does the compiler say that a class does not have a method that I wrote?
Section titled “Why does the compiler say that a class does not have a method that I wrote?”The compiler resolves some method names in another place. A class can define
one of these names, and the class compiles. Each call to that method then
fails with Class X does not have method ….
| Do not use as a method name | A name that works |
|---|---|
contains |
hasSub |
startsWith |
beginsWith |
endsWith |
finishesWith |
trim |
trimWs |
first |
lowest |
last |
highest |
remove |
removeNode |
insert |
insertNode |
write |
toText |
read |
fromText |
normalize |
collapse |
toString |
asString |
has |
mentions |
sqrt |
squareRoot |
The list is the names that programs have hit. It is not a complete list of reserved names.
What license does Ranger use?
Section titled “What license does Ranger use?”Ranger-authored compiler sources use the MIT license, unless a file
states a different license. Ranger-authored files in gallery/ use the
GNU Affero General Public License, version 3 or a later version, unless
a file states a different license. The license of compiled output
follows the source. A compiled gallery program stays under the AGPL.
The Licenses page states the rule.
Which target language does the compiler write?
Section titled “Which target language does the compiler write?”Thirteen languages from the command line: JavaScript, TypeScript, Go, Rust, Python, Java, Kotlin, Dart, Swift, C#, C++, PHP and Scala. The target page states what each one supports, and each operator page states the support per operator.
Ranger 3.5.1 · commit f323fd4 · development build