BasicPlus — The JC language

JC is BasicPlus written with the syntax of Java and C#. This volume describes the language: how each thing is written in JC, what it is in BP and how the two differ. Everything else is shared with BP —the standard library, the graphical interface, the databases, the IDE and the boards— and their volumes apply as they are to a program in JC (§19).

1. What JC is

1.1 The same language, different clothes

JC (from Java and C#) is BasicPlus with braces, semicolons and the type before the name. It is not another language: it is the same one with another syntax.

And that is why JC is neither Java nor C#: what BP does not have —lambdas, struct, your own generics with <T>…— JC does not have either, and some things behave as in BP even though they are written as in C#. They are gathered in §17.

1.2 BP or JC?

It is a matter of taste: the result is the same, with the same speed and the same libraries. JC, if you come from Java, C# or C; BP, if you prefer blocks that close with end and statements without ;.

2. A first program

2.1 Hello, in both

BP

module Hola
  function main(arg: string := "mundo")
    print "hola, "; arg
  end main
end Hola

JC

module Hola
{
   function void main(string arg = "mundo")
   {
      println("hola, ", arg);
   }
}

The module goes between braces, and every statement ends in ;. The type goes before the name (string arg), and a function that returns nothing is void. A parameter's default value is written with =. And println writes its pieces, one after another, and moves to a new line.

2.2 Compiling and running

The same commands as for a .bp (reference §16):

java -jar basicplus-frontend.jar Hola.jc --compile out --backend=mivm
java -jar bpgenvm.jar out/Hola.mod
bpgenvm-c out/Hola.mod "a todos"
hola, mundo
hola, a todos

The second argument to the VM is the one for main; without it, the parameter takes its default value. In the IDE, you open the .jc and run it like any other source (§18.4).

2.3 print and println

It is the first thing you notice when going from BP to JC. BP's print moves to a new line at the end, and the comma puts a space between the pieces. JC's does not:

BP

module Piezas
  function main()
    var n: integer := 3
    print "n = ";
    print n;
    print ", y sigue en la misma línea"
    print "a"; "b"; 1 + 2
    print "a", "b"
    print
    print "fin"
  end main
end Piezas

JC

module Piezas
{
   function void main()
   {
      int n = 3;
      print("n = ");
      print(n);
      println(", y sigue en la misma línea");
      println("a", "b", 1 + 2);
      println("a", " ", "b");
      println();
      println("fin");
   }
}

Both write the same:

n = 3, y sigue en la misma línea
ab3
a b

fin

3. A whole program, in BP and in JC

The same program in both languages. It is the example with which JC's syntax was decided, and it touches almost all the basics: constants, a module variable and a module property, an enum, a tuple, a parameter with a default value, an inline function, if, for, foreach, do, try and print. First in BP:

module Ejemplo
  import Collections

  public const MAX: integer := 10
  const PI := 3.5
  var cuenta: integer := 0
  public property nivel: integer := 1

  public enum Color
    Rojo
    Verde := 5
  end Color

  function par(): (integer, string)
    return (1, "uno")
  end par

  public function sumar(a: integer, b: integer := 1): integer
    return a + b
  end sumar

  public function codigo(s: string, i: integer): integer
    inline CALL_BUILTIN 48
  end codigo

  public function main()
    var n: integer
    var s: string
    var l: List := List()
    { n, s } := par()
    if n > 0 and not (s == "") then print "si"
    for i := 1 to MAX step 2 do
      cuenta += i
    next
    for x in [1, 2, 3] do print x
    do
      n -= 1
    loop n > 0
    try
      throw RuntimeError("fallo")
    catch e: RuntimeError
      print e.msg
    endtry
    print "cuenta: "; cuenta; " pi: "; PI
  end main
end Ejemplo

And in JC:

module Ejemplo
{
   import Collections;

   public const int MAX = 10;
   const float PI = 3.5f;
   int cuenta = 0;
   public int nivel { get; set; } = 1;

   public enum Color { Rojo, Verde = 5 }

   function (int, string) par()
   {
      return (1, "uno");
   }

   public function int sumar(int a, int b = 1)
   {
      return a + b;
   }

   public function int codigo(string s, int i) inline CALL_BUILTIN 48;

   public function void main()
   {
      int n;
      string s;
      List l = new List();
      (n, s) = par();
      if (n > 0 && !(s == "")) println("si");
      for (int i = 1; i <= MAX; i += 2)
      {
         cuenta += i;
      }
      foreach (var x in [1, 2, 3]) println(x);
      do
      {
         n -= 1;
      } while (n > 0);
      try
      {
         throw new RuntimeError("fallo");
      }
      catch (RuntimeError e)
      {
         println(e.msg);
      }
      println("cuenta: ", cuenta, " pi: ", PI);
   }
}

Both write the same, and give the same .mod:

si
1
2
3
fallo
cuenta: 25 pi: 3.5

What the comparison shows:

4. The basics

/* A comment
   on several lines */
int total = 0;            // and a line comment
total = total
      + 1;                  // one statement on two lines

4.1 The reserved words

What forWords
Modulesmodule library import from
Declarations const function class interface enum event var inline implements extends
Modifiers public protected private static final native sync owner
Types void int long float double bool string byte sbyte short ushort
Objectsnew this base field is super
Control if else while do for foreach in switch case default break continue return parallel
Exceptions and events try catch finally throw raise
Valuestrue false null
Outputprint println

super is reserved to tell you that in JC it is written base; and implements and extends, for the module headers inherited from BP. A few words are special only in their place and are valid as names outside it: get and set inside a property, value in its set, pack in an import and Thread in a case of parallel.

5. Modules and import

5.1 The module

A file is a module, as in BP: module Name { … }. Inside go, first, the imports, and then the definitions —constants, variables, properties, functions, classes, interfaces and enums— in any order. What is not public is private to the module.

module Medidor
{
   public const int MAXIMO = 100;
   int lecturas = 0;                     // private to the module
   public int ultima { get; set; }          // visible to those who import Medidor

   public function void apunta(int v)
   {
      lecturas++;
      ultima = v;
      if (ultima > MAXIMO) println("¡pasa de ", MAXIMO, "!");
   }

   function void main()
   {
      apunta(42);
      apunta(120);
      println(lecturas, " lecturas, la última ", ultima);
   }
}
¡pasa de 100!
2 lecturas, la última 120

A module variable cannot be public (it is an error): what is shared with other modules is a property, like ultima (manual §9.5). With library "com.ejemplo"; before module, the .mod is called com.ejemplo.Medidor.mod (manual §10.1).

5.2 main and the startup function

The program starts at function void main() of the root module, or at main(string arg) if it takes an argument (Main also works). And a void function without parameters named like the module is its startup function: it runs when the module is loaded, after those of the modules it imports and before main.

module Arranque
{
   int veces = 0;

   function void Arranque()
   {
      veces = 1;
      println("[init] cargado");
   }

   function void main(string arg = "defecto")
   {
      println("main con '", arg, "', veces = ", veces);
   }
}
[init] cargado
main con 'defecto', veces = 1

With bpgenvm-c Arranque.mod hola, the second line says main con 'hola'. Everything else about the argument —its 127-byte cap, the autorun, the IDE console— is as in BP (manual §10.2).

5.3 import

The same as BP's, with their ;, and always the first thing in the module:

JCBPWhat for
import Gpio;import Gpioa module, by its name
import com.ejemplo.Util;import com.ejemplo.Util with its library; used as Util.f()
import Helper from "plugins/helper.mod";import Helper from "plugins/helper.mod" where the compiler finds its .mod or its .bp
import Graficas from pack MisLibs;import Graficas from pack MisLibs its interface, from that pack (IDE guide §10.2)
import v1 from pack "SQLI";import v1 from pack "SQLI" a pack's native functions, for whoever writes the library

The rest, as in BP (manual §10.3): import Core is not needed, because the compiler always adds it —that is why List, RuntimeError or len can be used just like that—, and imports are not transitive: to name a type from another module, you have to import that module.

5.4 Importing your own modules

A module in JC imports BP modules like any other: if the .bp is next to it, the compiler compiles it too. To import another module in JC there is, for now, one condition: the compiler looks for the source of an import as a .bp, so an imported .jc is compiled first, and its .mod, next to the importer or in the output folder, is what gets found. In a project, they are listed in sources, the imported one first (§18.2).

module Utiles
{
   public const int VECES = 3;

   public function string repite(string s, int n = 3)
   {
      string r = "";
      for (int i = 1; i <= n; i++) r += s;
      return r;
   }
}
module Viejo
  public function doble(n: integer): integer
    return n * 2
  end doble
end Viejo
module Programa
{
   import Utiles;        // in JC: compiled first
   import Viejo;         // in BP: the compiler finds Viejo.bp

   function void main()
   {
      println(Utiles.repite("ja"));
      println(Viejo.doble(21));
   }
}
java -jar basicplus-frontend.jar Utiles.jc --compile out --backend=mivm
java -jar basicplus-frontend.jar Programa.jc --compile out --backend=mivm
java -jar bpgenvm.jar out/Programa.mod
jajaja
42

Without compiling Utiles.jc first, the compiler says so: «no se localizó .bp ni .bpi para import 'Utiles'» (no .bp or .bpi was found for the import), and then that Utiles is unknown. A default value is a literal, as in BP: int n = VECES is not valid, even though VECES is a constant.

6. Types, variables and literals

6.1 The types

C#'s, including the narrow ones. One name per type:

JCBPWhat it is
intinteger32-bit signed integer
longlong64-bit signed integer
floatfloat32-bit real
doubledouble64-bit real
boolbooleantrue or false
stringstringtext string, UTF-8 and immutable
bytebyte8-bit unsigned integer, 0..255
sbyteint88-bit signed integer, -128..127
shortint16 (or short)16-bit signed integer
ushortword16-bit unsigned integer, 0..65535
int[], Punto[]integer[], Punto[]an array (§6.4)
(int, string)(integer, string)a tuple (§6.6)
Punto, Object, Listthe samea class, by its name; from another module, Json.JsonObject

There is no char: a character in single quotes is an int (§6.3). Nor uint, ulong or decimal: BP does not have them. The narrow ones (byte, sbyte, short, ushort) are for storing —in an array or in a field they take 1 or 2 bytes— and in arithmetic they operate as int (manual §4.1).

6.2 Variables and constants

The type in front, as in Java and C#, and the value with =:

JCBP
int x = 5;var x: integer := 5
int a, b;var a, b: integer
int a = 1, b = 2;var a: integer := 1, b: integer := 2
int a, b = 3; — only b is 3var a: integer, b: integer := 3
int a = 3, b = 3;var a, b: integer := 3 — both are 3
owner Recurso r = new Recurso("db");var owner r: Recurso := Recurso("db")
const int MAX = 10;const MAX: integer := 10
module Variables
{
   const int MAX = 3;
   int total;                     // module-level, no value: 0

   function void main()
   {
      int a = 1, b = 2;
      int c;                       // no value: it must be given one before it is read
      c = a + b;
      double media = c / 2.0;
      float f = 1.5f;
      long grande = 4000000000L;
      bool listo = c > MAX;
      string nombre = "Ana";
      total += c;
      println(a, " ", b, " ", c, " ", media, " ", f, " ", grande);
      println(listo, " ", nombre, " ", total);
   }
}
1 2 3 1.5 1.5 4000000000
false Ana 3

6.3 Literals

C#'s. What changes with respect to BP are the reals and the characters:

JCWhat it isIn BP
42 · 0xFF · 0b1010 · 1_000_000 an int (a long, if it does not fit in 32 bits)the same
10La longthe same
1.5 · 1.5d · 2e3a double1.5d · 2e3d
1.5fa float1.5
'a' · 'é' · '\n' an int: the character's code (97, 233, 10)the number (BP does not have them)
"hola"a stringthe same
true · false · nullthe same
module Literales
{
   function void main()
   {
      int c = 'a';
      println(c, " ", 'A' + 1, " ", 'é', " ", 0xFF, " ", 0b1010, " ", 1_000_000);
      println("caf\u00e9 con le", 'c' == 99 ? "che" : "?");
      println("dijo \"hola\" y se fue");
      double d = 1.5;
      float f = 1.5f;
      println(d * 2, " ", f * 2);
   }
}
97 66 233 255 10 1000000
café con leche
dijo "hola" y se fue
3 3

A real with an integer value is printed without decimals: 3, not 3.0, as in BP.

6.4 Arrays

JCBP
int[] v = [1, 2, 3];var v: integer[] := [1, 2, 3]
int[] v = new int[n];var v: integer[] := integer[n]
Punto[] ps = new Punto[10];var ps: Punto[] := Punto[10]
int buf[64];var buf: integer[64]
byte m[4] = [1, 2, 250];var m: byte[4] := [1, 2, 250]
len(v)len(v)
module Arrays
{
   function int suma(int[] v)
   {
      int s = 0;
      foreach (var x in v) s += x;
      return s;
   }

   function void main()
   {
      int[] primos = [2, 3, 5, 7];
      int[] cuadrados = new int[4];
      for (int i = 0; i <= len(cuadrados) - 1; i++) cuadrados[i] = i * i;
      string[] nombres = new string[2];
      nombres[0] = "uno";
      int buf[8];                  // fixed size: in the frame, zeroed
      buf[0] = 42;
      println(suma(primos), " ", suma(cuadrados), " ", len(buf), " ", buf[0], " ", buf[1]);
      println(nombres[0], " ", nombres[1] == null);
   }
}
17 14 8 42 0
uno true

6.5 Strings and null

A JC string is BP's: UTF-8 text that does not change. What someone coming from Java or C# expects:

module Textos
{
   function void main()
   {
      string s = "hola mundo";
      println(len(s), " ", upper(s), " ", substring(s, 0, 4), " ", indexOf(s, "mu"));
      println(charAt(s, 1), " ", charCodeAt(s, 1), " ", contains(s, "mun"), " ", startsWith(s, "ho"));
      string[] partes = split("a,b,c", ",");
      println(len(partes), " ", partes[2], " ", replace(s, "mundo", "JC"));
      println(s == "hola " + "mundo", " ", "abc" < "abd", " ", parseInt("42") + 1);
      StringBuilder sb = new StringBuilder();
      sb.appendStr("uno");
      sb.appendStr("+dos");
      println(sb.toString());
   }
}
10 HOLA MUNDO hola 5
o 111 true true
3 c hola JC
true true 43
uno+dos

A string is never null, but a string variable can be, as in C#: string s = null; is a variable that references no string. The same goes for a parameter, a field or what a function returns. With it:

A string field, property or module variable without a value starts out as "", not null; a local without a value cannot be read (§6.2). And a const string cannot be null: it is a value, not a variable.

module Nulos
{
   string nombre;                  // module-level, no value: ""

   function string busca(int id)
   {
      if (id == 1) return "Ana";
      return null;
   }

   function void main()
   {
      string s = busca(2);
      println("[", s, "] [", "x" + s + "y", "]");
      println(s == null, " ", s == "", " ", len(nombre));
      try
      {
         println(upper(s));
      }
      catch (RuntimeError e)
      {
         println(e.msg);
      }
   }
}
[] [xy]
true false 0
referencia nula: upper de un string null

6.6 Tuples

A function can return several values, as in C#:

JCBP
function (int, int) divmod(int a, int b)function divmod(a: integer, b: integer): (integer, integer)
return (a / b, a % b);return (a / b, a mod b)
(q, r) = divmod(17, 5);{ q, r } := divmod(17, 5)
(int, int) t = divmod(9, 4);var t: (integer, integer) := divmod(9, 4)

The unpacking targets must already exist —variables, fields or array elements—, and _ discards a value. A tuple cannot be printed or put in a list (manual §8.2).

module Tuplas
{
   function (int, int) divmod(int a, int b)
   {
      return (a / b, a % b);
   }

   function void main()
   {
      int q, r;
      (q, r) = divmod(17, 5);
      println(q, " ", r);
      (int, int) t = divmod(9, 4);
      (q, _) = t;
      println(q);
   }
}
3 2
2

6.7 Enums

As in C#: enum Color { Rojo, Verde = 5, Azul }, with a trailing comma if you like. It is BP's enum … end. The values are numbered from 0, and an explicit one is an unsigned integer; C#'s expressions (1 << 3, -1) and the underlying type (enum Color : byte) are not there.

module Colores
{
   public enum Color { Rojo, Verde = 5, Azul }

   function void main()
   {
      Color c = Color.Azul;
      println(c, " ", (int) Color.Verde, " ", (int) c + 1);
      println(Enum.getName(c));
      if (c == Color.Azul) println("es azul");
   }
}
6 5 7
Azul
es azul

7. Expressions and operators

7.1 The operators

JCBPWhat it does
=:=assigns (it is a statement, §7.3)
+ - * /the samebetween two integers, / is integer division: 17 / 5 is 3
%modthe remainder
**^the power: 2 ** 10 is 1024
&& || !and or notlogical; && and || skip the second operand if the result is already clear
& |the samebitwise; between two bools, logical operators that evaluate both sides
^xorexclusive or
<< >>shl shrshifts
== != < <= > >=the samecompare; between strings, the text (§6.5); between objects, whether they are the same one
x is Perrox instanceof Perrois it of that class or interface? (§7.4)
c ? a : biif(c, a, b)the ternary (§7.5)
(int) x · (Perro) ainteger(x) · Perro(a)conversions (§7.4)
new Perro(…) · new int[n]Perro(…) · integer[n]creates an object or an array
obj::metodothe samea method of an object, as a value (§13, §15)

There is no ~, the bitwise not (BP does not have it either: in JC it is written x ^ -1, and in BP, x xor -1), nor ?? or ?.: each one gives an error that says so.

7.2 Precedence, as in C#

From the weakest to the strongest:

LevelOperators
1c ? a : b (right-associative)
2||
3&&
4, 5, 6|, then ^, then &
7== !=
8< <= > >= is
9<< >>
10+ -
11* / %
12the unary - and !, and the conversion (T) x
13**, stronger than the unary minus and right-associative: -2 ** 2 is -4, and 2 ** 3 ** 2 is 2 ** 9, 512

BP's is not the same for the bitwise operators: in BP, the shifts go with *, and | and xor, with +. So the same text can give a different value. In JC:

module Precedencia
{
   function void main()
   {
      int a = 1;
      println(a << 1 + 2);            // 8: the + goes before the <<
      println(2 ** 3 ** 2, " ", -2 ** 2);
      println(7 % 3, " ", 6 ^ 3, " ", 6 & 3, " ", 6 | 3, " ", 1 << 4, " ", -16 >> 2);
      bool b = a > 0 && !(a == 2) || false;
      println(b);
   }
}
8
512 -4
1 5 2 7 16 -4
true

And the same in BP, with its operators:

module PrecedenciaBp
  function main()
    var a: integer := 1
    print a shl 1 + 2               // 4: in BP, shl goes with the *
    print 2 ^ 3 ^ 2, -2 ^ 2
    print 7 mod 3, 6 xor 3, 6 & 3, 6 | 3, 1 shl 4, -16 shr 2
  end main
end PrecedenciaBp
4
512 -4
1 5 2 7 16 -4

When translating, each language puts in the parentheses its precedence requires, so a translated program computes the same as the original: BP's a shl 1 + 2 comes out in JC as (a << 1) + 2.

7.3 Assignments

JCBP
x = e;x := e
x += e; x -= e; x *= e; x /= e;the same
x %= e; x ^= e; x <<= e; x >>= e;x mod= e x xor= e x shl= e x shr= e
x &= e; x |= e;the same
x++; x--;x += 1 x -= 1
module Asignaciones
{
   function void main()
   {
      int i = 3;
      i += 2;          // 5
      i *= 4;          // 20
      i %= 6;          // 2
      i <<= 3;         // 16
      i ^= 1;          // 17
      i++;             // 18
      println(i);
      byte b = 255;
      b += 1;          // 0: a byte operates as an int and keeps its size
      long l = 1;
      l <<= 40;
      string s = "n=";
      s += 5;          // + concatenates
      println(b, " ", l, " ", s);
   }
}
18
0 1099511627776 n=5

7.4 Conversions and is

As in C#: (T) x. In BP, creating, calling and converting are written the same way —Perro(x)— and the compiler decides; in JC each one has its own form: new Perro(x) creates, (Perro) x converts and f(x) calls.

module Conversiones
{
   class Animal
   {
      public function string habla()
      {
         return "...";
      }
   }

   class Perro : Animal
   {
      public function string habla()
      {
         return "guau";
      }

      public function string trae()
      {
         return "la pelota";
      }
   }

   function void main()
   {
      double d = 3.9;
      int i = (int) d;                     // 3: truncates toward zero
      long l = (long) i * 1000000000;
      byte b = (byte) 200;
      println(i, " ", l, " ", b);
      Animal a = new Perro();
      if (a is Perro) println(((Perro) a).trae());
      Object o = a;
      Perro p = (Perro) o;                 // if it were not one: CastError
      println(p.habla());
      try
      {
         b = (byte) (i * 100);
      }
      catch (ArithmeticError e)
      {
         println("300 no cabe en un byte");
      }
   }
}
3 3000000000 200
la pelota
guau
300 no cabe en un byte

Writing one thing for another is an error that says how it goes in JC: Perro("Rex") without new gives «'Perro(…)' crea un objeto: en JC se escribe 'new Perro(…)'» (it creates an object: in JC, write new Perro(…)), and int(d), «en JC, una conversión se escribe (int) x» (in JC, a conversion is written (int) x).

7.5 The ternary

c ? a : b is a if c holds, and otherwise b. It is BP's iif(c, a, b), and it only evaluates the branch that applies, so a recursive function that uses it terminates. Its type is that of the two branches: the same one; or two numbers, and the wider one wins; or null and a reference; or a class and its child, and the parent wins. It is not a statement: to choose what to do, an if.

module Ternario
{
   function int fib(int n)
   {
      return n < 2 ? n : fib(n - 1) + fib(n - 2);
   }

   function void main()
   {
      for (int n = 1; n <= 4; n++) println(n, n % 2 == 0 ? " par" : " impar");
      println(fib(10));
   }
}
1 impar
2 par
3 impar
4 par
55

8. Control flow

8.1 if, while and do

JCBP
if (c) { … } else if (d) { … } else { … }if c then … elseif d then … else … endif
while (c) { … }while c do … endwh
do { … } while (c);do … loop c
while (true) { … }do … loop (without a condition)

As in C. With a single statement, without braces. The else goes with the nearest if, and else if is BP's elseif. The do repeats while the condition holds, and a continue inside it goes to the condition, as in C#. The endless loop is while (true): JC does not have BP's do … loop without a condition.

With a single statement, the do also goes without braces: do i++; while (i < 3);. If it has a name (§8.5), the name goes right after do and before the brace of its body: do vuelta { i++; } while (i < 3);.

module Control
{
   function string etapa(int edad)
   {
      if (edad < 18) return "menor";
      else if (edad < 65) return "adulto";
      else return "senior";
   }

   function void main()
   {
      println(etapa(10), " ", etapa(40), " ", etapa(70));
      int i = 0;
      while (i < 3) i++;
      do
      {
         i += 10;
      } while (i < 25);
      println(i);
      while (true)
      {
         i -= 7;
         if (i < 0) break;
      }
      println(i);
   }
}
menor adulto senior
33
-2

8.2 for

JC's for is BP's dressed as C: a counter. It has four forms:

JCBP
for (int i = a; i <= b; i++)for i := a to b do
for (int i = a; i <= b; i += 2)for i := a to b step 2 do
for (int i = a; i >= b; i--)for i := a to b step -1 do
for (int i = a; i >= b; i -= 2)for i := a to b step -2 do
module Contar
{
   function void main()
   {
      for (int i = 1; i <= 10; i += 3) print(i, " ");
      println("fin");
      for (int i = 3; i >= 1; i--)
      {
         print(i, "... ");
      }
      println("¡ya!");
   }
}
1 4 7 10 fin
3... 2... 1... ¡ya!

8.3 foreach

foreach (var x in collection) is BP's for x in collection do. It goes through an array or a List (also SyncList and OwnerList). The variable is always written var: it takes the type of the elements —in a plain List, Object; in a List<Sensor>, Sensor (§12)—. With a written type, foreach (int x in a), it is an error. The list is measured once, on entry: what the body adds to it is not visited.

module Recorrer
{
   function void main()
   {
      int total = 0;
      foreach (var n in [2, 3, 5, 7]) total += n;
      println(total);
      List<Object> l = new List<Object>();
      l.add("uno");
      l.add(2);
      foreach (var x in l) println(x);
   }
}
17
uno
2

8.4 switch

C#'s form with BP's meaning: case 1, 2: with several values, and the default at the end. It does not fall through from one case to the next, so break is not needed; if it is written, it leaves the switch. The subject is an integer, a bool, an enum or a string, which is compared by its text; not a real or an object.

module Ordenes
{
   function void ejecuta(string orden)
   {
      switch (orden)
      {
         case "ls", "dir":
            println("lista");
         case "cd":
            println("cambia de carpeta");
         default:
            println("no conozco ", orden);
      }
   }

   function void main()
   {
      ejecuta("dir");
      ejecuta("cd");
      ejecuta("rm");
   }
}
lista
cambia de carpeta
no conozco rm

8.5 break and continue, with a name

break leaves the nearest loop or switch, and continue goes on with the next iteration of the nearest loop. A loop can carry a name, after its keyword, to leave several at once or to continue with the outer one:

JCBP
for fila (int i = 1; i <= 3; i++) { … }for i := 1 to 3 do fila
foreach fila (var x in l) { … }for x in l do fila
while fila (c) { … }while c do fila
do fila { … } while (c);do fila … loop c
break fila; · continue fila;break fila · continue fila

They are not labels and there is no goto: the name is only visible inside its loop. On leaving, the trys in between are closed and their finallys run.

module Buscar
{
   function void main()
   {
      for fila (int i = 1; i <= 3; i++)
      {
         for (int j = 1; j <= 3; j++)
         {
            if (j > i) continue fila;
            if (i * j == 6)
            {
               println("encontrado: ", i, " x ", j);
               break fila;
            }
         }
      }
      println("fuera");
   }
}
encontrado: 3 x 2
fuera

9. Functions

9.1 Declaring and calling

JCBP
function int suma(int a, int b = 1) { … }function suma(a: integer, b: integer := 1): integer … end suma
function void avisa(string msg) { … }function avisa(msg: string) … end avisa
public function …public function …
function (int, string) par() { … }function par(): (integer, string) … end par
module Funciones
{
   public function string etiqueta(string texto, string antes = "[", string despues = "]")
   {
      return antes + texto + despues;
   }

   function string texto(int n)
   {
      return "int:" + n;
   }

   function string texto(string s)
   {
      return "str:" + s;
   }

   function void avisa(string msg)
   {
      println("aviso: ", msg);
   }

   function void main()
   {
      println(etiqueta("hola"), " ", etiqueta("hola", "<"), " ", etiqueta("hola", "<", ">"));
      println(texto(5), " ", texto("cinco"));
      avisa("fin");
   }
}
[hola] <hola] <hola>
int:5 str:cinco
aviso: fin

9.2 var parameters

A var parameter does not receive a value but a property of an object, which is passed as object::property: reading the parameter reads the property, and assigning to it writes it. It is C#'s ref, but only with properties: this VM has no references to variables.

module Contadores
{
   public class Contador
   {
      public int valor { get; set; }
   }

   function void suma(var int n, int m)
   {
      n += m;
   }

   function void main()
   {
      Contador c = new Contador();
      suma(c::valor, 5);
      suma(c::valor, 2);
      println(c.valor);
   }
}
7

In BP, function suma(var n: integer, m: integer) and the same call. It is passed object::property, of the same type and one the caller can read and write, or another var parameter by its name; not a variable or a field. No default value, and not in a constructor, an event or a native. Module properties and static ones, not yet (manual §8.1b).

9.3 native and inline

module Nativo
{
   native function int sumaCuadrados(int n)
   {
      int s = 0;
      for (int i = 1; i <= n; i++) s += i * i;
      return s;
   }

   public function int codigo(string s, int i) inline CALL_BUILTIN 48;

   function void main()
   {
      println(sumaCuadrados(10), " ", codigo("A", 0));
   }
}
385 65

10. Classes

10.1 Constructors, inheritance and base

As in C#, plus what BP has and C# does not. An animal and a dog:

module Zoo
{
   public class Animal
   {
      protected string nombre;
      private static int cuantos = 0;

      public function Animal(string nombre)
      {
         this.nombre = nombre;
         Animal.cuantos += 1;
      }

      public function string habla()
      {
         return "...";
      }

      public function string presenta()
      {
         return this.nombre + " dice " + this.habla();
      }

      public static function int total()
      {
         return Animal.cuantos;
      }
   }

   public class Perro : Animal
   {
      private int edad;

      public function Perro(string nombre, int edad) : base(nombre)
      {
         this.edad = edad;
      }

      public function Perro(string nombre) : this(nombre, 2)
      {
      }

      public function string habla()
      {
         return "guau";
      }

      public function string presenta()
      {
         return base.presenta() + " (" + this.edad + " años)";
      }
   }

   function void main()
   {
      Animal a = new Animal("Bicho");
      Perro p = new Perro("Rex", 3);
      Animal q = new Perro("Lua");
      println(a.presenta());
      println(p.presenta());
      println(q.presenta());
      println(Animal.total(), " animales");
   }
}
Bicho dice ...
Rex dice guau (3 años)
Lua dice guau (2 años)
3 animales

Translated to BP —and it gives the same .mod—:

module Zoo
  public class Animal
    var nombre: string
    private var Animal.cuantos: integer := 0

    public function Animal(nombre: string)
      this.nombre := nombre
      Animal.cuantos += 1
    end Animal

    public function habla(): string
      return "..."
    end habla

    public function presenta(): string
      return this.nombre + " dice " + this.habla()
    end presenta

    public function Animal.total(): integer
      return Animal.cuantos
    end Animal.total
  end Animal

  public class Perro extends Animal
    private var edad: integer

    public function Perro(nombre: string, edad: integer)
      super(nombre)
      this.edad := edad
    end Perro

    public function Perro(nombre: string)
      Perro(nombre, 2)
    end Perro

    public function habla(): string
      return "guau"
    end habla

    public function presenta(): string
      return super.presenta() + " (" + this.edad + " años)"
    end presenta
  end Perro

  function main()
    var a: Animal := Animal("Bicho")
    var p: Perro := Perro("Rex", 3)
    var q: Animal := Perro("Lua")
    print a.presenta()
    print p.presenta()
    print q.presenta()
    print Animal.total(); " animales"
  end main
end Zoo
JCBP
class Perro : Animal { … }class Perro extends Animal … end Perro
function Perro(string n) { … }, without a typefunction Perro(n: string) … end Perro
… : base(n) { … }super(n), the first statement
… : this(n, 2) { … }Perro(n, 2), the first statement
base.presenta()super.presenta()
staticthe class name in front: Animal.total
new Perro("Rex", 3)Perro("Rex", 3)

10.2 Visibility

JCBPWho sees it
publicpubliceveryone
protected, or nothingnothingthe class and its children, also those in another module
privateprivateonly the class (and it is not virtual)

10.3 Properties

JCBP
public int lecturas { get; set; }public property lecturas: integer
public string unidad { get; set; } = "C";public property unidad: string := "C"
double celsius { get { … } set { … } }, with valueproperty celsius: double, get … endget, set(value) … endset, endprop
set(v) { … }set(v) … endset
fieldfield
module Termometros
{
   public class Termometro
   {
      private double grados;

      public string unidad { get; set; } = "C";
      public int lecturas { get; set; }

      public double celsius
      {
         get
         {
            return this.grados;
         }
         set
         {
            if (value < -273.15) throw new RuntimeError("bajo el cero absoluto");
            this.grados = value;
            this.lecturas += 1;
         }
      }

      public double fahrenheit
      {
         get
         {
            return this.grados * 9 / 5 + 32;
         }
      }

      public long nivel
      {
         get
         {
            return field;
         }
         set(v)
         {
            field = v * 2;
         }
      }
   }

   function void main()
   {
      Termometro t = new Termometro();
      t.celsius = 25;
      t.celsius += 5;
      t.nivel = 7;
      println(t.celsius, " ", t.unidad, " = ", t.fahrenheit, " F");
      println(t.lecturas, " lecturas, nivel ", t.nivel);
      try
      {
         t.celsius = -300;
      }
      catch (RuntimeError e)
      {
         println(e.msg);
      }
   }
}
30 C = 86 F
2 lecturas, nivel 14
bajo el cero absoluto

10.4 static, const and sync

module Estaticos
{
   public sync int pedidos { get; set; }

   public class Cuenta
   {
      public const int MAXIMO = 1000;
      public static int abiertas { get; set; }
      public sync int saldo { get; set; }

      public function Cuenta(int inicial)
      {
         this.saldo = inicial;
         Cuenta.abiertas += 1;
      }

      public static function Cuenta abre(int inicial)
      {
         if (inicial > Cuenta.MAXIMO) throw new RuntimeError("demasiado");
         return new Cuenta(inicial);
      }
   }

   function void main()
   {
      Cuenta a = Cuenta.abre(100);
      Cuenta b = Cuenta.abre(50);
      a.saldo -= 30;
      pedidos += 2;
      println(a.saldo, " ", b.saldo, " ", Cuenta.abiertas, " ", Cuenta.MAXIMO, " ", pedidos);
   }
}
70 50 2 1000 2

10.5 The destructor and owner

BP destroys objects right away, without waiting for the collector, when they have an owner: that is owner. And what has to be done when they are destroyed is written once, in the class's destructor.

JCBP
public function ~Recurso() { … }public function ~Recurso() … end ~Recurso
owner Recurso r = new Recurso("db");var owner r: Recurso := Recurso("db")
protected owner Recurso contenido;var owner contenido: Recurso
try (Recurso f = new Recurso("x")) { … }try var f: Recurso := Recurso("x") … endtry
module Recursos
{
   public class Recurso
   {
      private string nombre;

      public function Recurso(string nombre)
      {
         this.nombre = nombre;
         println("abre ", nombre);
      }

      public function ~Recurso()
      {
         println("cierra ", this.nombre);
      }

      public function void usa()
      {
         println("usa ", this.nombre);
      }
   }

   public class Caja
   {
      protected owner Recurso contenido;

      public function Caja(string n)
      {
         this.contenido = new Recurso(n);
      }
   }

   function void trabaja()
   {
      owner Recurso r = new Recurso("db");
      r.usa();
   }

   function void main()
   {
      trabaja();
      try (Recurso f = new Recurso("fichero"))
      {
         f.usa();
      }
      owner Caja c = new Caja("caja");
      println("fin del main");
   }
}
abre db
usa db
cierra db
abre fichero
usa fichero
cierra fichero
abre caja
fin del main
cierra caja

11. Interfaces

A class inherits from a single class and implements as many interfaces as it wants. An interface says which methods and which properties a type has, without code, and it can inherit from several.

module Formas
{
   public interface Forma
   {
      function double area();
      function string nombre();
   }

   public interface Poligono : Forma
   {
      function int lados();
   }

   public interface Etiquetado
   {
      string etiqueta { get; set; }
   }

   public class Figura
   {
      public function string nombre()
      {
         return "figura";
      }
   }

   public class Cuadrado : Figura, Poligono, Etiquetado
   {
      private double lado;

      @implement{ Etiquetado }
      public string etiqueta { get; set; }

      public function Cuadrado(double l)
      {
         this.lado = l;
      }

      @implement{ Poligono }
      public function double area()
      {
         return this.lado * this.lado;
      }

      @implement{ Poligono }
      public function int lados()
      {
         return 4;
      }

      @implement{ Poligono }
      @override{}
      public function string nombre()
      {
         return "cuadrado";
      }
   }

   function void main()
   {
      Forma f = new Cuadrado(2.0);
      println(f.nombre(), " ", f.area());
      Poligono p = (Poligono) f;
      println(p.lados(), " ", f is Etiquetado);
      Etiquetado e = (Etiquetado) f;
      e.etiqueta = "cuadrado de 2";
      println(e.etiqueta);
   }
}
cuadrado 4
4 true
cuadrado de 2

12. Generics

List<Sensor> is the usual List with an order for the compiler: what goes in has to be a Sensor, and what comes out is a Sensor, without writing the conversion. The class does not change and the VM does not notice. The same goes for SyncList<T> and OwnerList<T>; and a Map takes two, the key (int or string) and the value.

module Almacen
{
   import Collections;

   public class Sensor
   {
      private int v;

      public function Sensor(int v)
      {
         this.v = v;
      }

      public function int valor()
      {
         return this.v;
      }
   }

   function void main()
   {
      List<Sensor> sensores = new List<Sensor>();
      sensores.add(new Sensor(4));
      sensores.add(new Sensor(7));
      println(sensores.get(0).valor(), " ", sensores[1].valor());
      int suma = 0;
      foreach (var s in sensores) suma += s.valor();
      println("suma: ", suma);
      Collections.Map<int, string> nombres = new Collections.Map<int, string>();
      nombres.put(10, "diez");
      nombres[20] = "veinte";
      println(nombres.get(10), " ", nombres[20]);
      Collections.Map<string, Sensor> porNombre = new Collections.Map<string, Sensor>();
      porNombre["patio"] = new Sensor(21);
      println(porNombre["patio"].valor());
   }
}
4 7
suma: 11
diez veinte
21

A class of yours is generic if it states its base type with the @element{type} annotation. It is written with that type in its signatures, and whoever uses it asks for one that descends from it. There is no <T> variable, nor generic methods:

module Bolsas
{
   public class Medida
   {
      protected double v;

      public function Medida(double v)
      {
         this.v = v;
      }

      public function double valor()
      {
         return this.v;
      }
   }

   public class Metro : Medida
   {
      public function Metro(double v) : base(v)
      {
      }

      public function double enCm()
      {
         return this.v * 100;
      }
   }

   @element{Medida}
   public class Bolsa
   {
      private List cosas = new List();

      public function void mete(Medida m)
      {
         this.cosas.add(m);
      }

      public function Medida saca(int i)
      {
         return (Medida) this.cosas.get(i);
      }
   }

   function void main()
   {
      Bolsa<Metro> b = new Bolsa<Metro>();
      b.mete(new Metro(2));
      println(b.saca(0).enCm());
   }
}
200

b.saca(0) comes out as a Metro, without converting. What is lost along the way —a list that goes through an Object or a plain List— and what happens between modules is in the manual §4.6: it is the same in JC.

13. Events

An event lets an object announce that something has happened, without knowing who is listening. It is the foundation of the graphical interface —a button does not know what your program does when it is pressed—, but it works in any class.

module Botones
{
   public class Boton
   {
      public int numero { get; set; }
      event onClick(Boton sender, int veces);

      public function Boton(int n)
      {
         this.numero = n;
      }

      public function void pulsa(int veces)
      {
         if (onClick != null) raise onClick(this, veces);
      }
   }

   public class Panel
   {
      private string nombre;

      public function Panel(string n)
      {
         this.nombre = n;
      }

      function event void pulsado(Boton b, int veces)
      {
         println("  boton ", b.numero, " x", veces, " en ", this.nombre);
      }
   }

   function void main()
   {
      Boton b = new Boton(7);
      Panel p = new Panel("principal");
      b.pulsa(1);
      b.onClick = p::pulsado;
      println("antes del raise");
      b.pulsa(3);
      println("despues del raise");
      sleep(30);
      println("fin");
   }
}
antes del raise
despues del raise
  boton 7 x3 en principal
fin
JCBP
event onClick(Boton sender, int veces);event onClick(sender: Boton, veces: integer)
raise onClick(this, veces);raise onClick(this, veces)
function event void pulsado(Boton b, int veces) { … }function event pulsado(b: Boton, veces: integer) … end pulsado
b.onClick = p::pulsado;b.onClick := p::pulsado
if (onClick != null) …if onClick != null then …

14. Exceptions

BP's try, with braces, and the catch by type with the type in front, as in C#:

module Errores
{
   public class SensorError : RuntimeError
   {
      public int pin { get; set; }

      public function SensorError(string msg, int pin) : base(msg)
      {
         this.pin = pin;
      }
   }

   function int lee(int pin)
   {
      if (pin < 0) throw new SensorError("pin no válido", pin);
      return 100 / pin;
   }

   function void prueba(int pin)
   {
      try
      {
         int r = lee(pin);
         println("lee ", pin, ": ", r);
      }
      catch (SensorError e)
      {
         println("sensor: ", e.msg, " (", e.pin, ")");
      }
      catch (ArithmeticError e)
      {
         println("cuenta: ", e.msg);
      }
      catch
      {
         println("otro error");
      }
      finally
      {
         println("  hecho");
      }
   }

   function void main()
   {
      prueba(4);
      prueba(-1);
      prueba(0);
   }
}
lee 4: 25
  hecho
sensor: pin no válido (-1)
  hecho
cuenta: División por cero
  hecho
JCBP
try { … } catch (RuntimeError e) { … } finally { … }try … catch e: RuntimeError … finally … endtry
catch (Exception e) { … }catch e
catch { … }, without a variable: catches everythingcatch
throw new SensorError("…", 3);throw SensorError("…", 3)
try (Recurso f = new Recurso("x")) { … }try var f: Recurso := Recurso("x") … endtry
class SensorError : RuntimeErrorclass SensorError extends RuntimeError

15. Threads and parallel

BP's threads are real threads, which the VM's scheduler alternates and which, on a dual-core board, run at the same time (manual §14). In JC they are written in three ways:

module Hilos
{
   public class Calculo
   {
      public function void suma(int n)
      {
         int s = 0;
         for (int i = 1; i <= n; i++) s += i;
         println("suma hasta ", n, " = ", s);
      }
   }

   public class Contador : Thread
   {
      private string nombre;

      public function Contador(string nombre) : base(2048)
      {
         this.nombre = nombre;
      }

      public function void run()
      {
         println(this.nombre, " corre en su hilo");
      }
   }

   function int sumaRango(int a, int b)
   {
      int s = 0;
      for (int i = a; i <= b; i++) s += i;
      return s;
   }

   function void main()
   {
      parallel
      {
         case t1 = new Thread(2048):
            println("t1 = ", sumaRango(1, 100));
         case t2 = new Thread(2048):
            println("t2 = ", sumaRango(101, 200));
      }
      println("los dos han acabado");
      Contador c = new Contador("contador");
      c.start();
      c.join();
      Calculo k = new Calculo();
      Thread h = new Thread(k::suma(10));
      h.start();
      h.join();
   }
}
t1 = 5050
t2 = 15050
los dos han acabado
contador corre en su hilo
suma hasta 10 = 55

16. Annotations

BP's, as they are: @Name{ key = value, key }, before the declaration, with the braces even if they carry nothing, and several per declaration if needed. They are not C#'s [Attributes] or Java's annotations. The ones there are: @BD, which describes the ORM's entities (databases §3); @element, the type of a generic class (§12); and @implement and @override (§11).

module Entidades
{
   @BD{ tabla = "medidas" }
   public class Medida
   {
      @BD{ pk }
      public long id { get; set; }

      @BD{ columna = "sensor_id" }
      public long sensorId { get; set; }

      @BD{}
      public double valor { get; set; }
   }

   function void main()
   {
      Medida m = new Medida();
      m.valor = 21.5;
      println(m.id, " ", m.valor);
   }
}
0 21.5

17. What JC does not have, and what clashes

17.1 What JC does not have

JC is BP: what BP does not have, JC does not have. Much of what is missing from C#, the compiler recognizes and calls by its name («JC no tiene el ?? de C#…», JC does not have C#'s ??); the rest gives a syntax error.

From Java or C#In JC
lambdas, delegates, LINQno; a method as a value is object::method, for an event (§13) or a thread (§15)
your own generics: class Caja<T>, T f<T>()no; a generic class states its base type with @element{type} (§12)
struct, nested classes, abstract, static classno
var x = 5;no: the type is always written (§6.2)
char, uint, ulong, decimala character is an int (§6.3); the others, no
@"…", $"…{x}"no; concatenate with +
??, ?., x is T t, x is nullno; x == null, x is T and (T) x
++x, y = x++, a = b = 0x++; as a statement; an assignment does not go inside an expression (§7.3)
~xx ^ -1
C's general forthe four forms of the counter; the rest, with while (§8.2)
a switch that falls through, goto case, patternsno; each case is its own block (§8.4)
goto and labelsbreak and continue with the loop's name (§8.5)
ref, out, params, named argumentsthe var parameter, with a property (§9.2)
throw;, catch … when, using (…)throw e;; no filters; try (T r = e) (§14)
namespace, using System;modules and import (§5)
operator overloading, reflection, async/awaitno; for what blocks, a thread (§15)

17.2 If you come from Java or C#

What compiles the same as in Java or C#, but does something else, or is written slightly differently:

17.3 What clashes with BP

What you need to know when translating from one language to the other (§18.3):

18. Compiling, translating and the IDE

18.1 Compiling a .jc

Like a .bp: the compiler picks the reader by the extension, and the rest is shared. The options are the usual ones (reference §16.1):

java -jar basicplus-frontend.jar Programa.jc --compile out --backend=mivm

18.2 A project

A .bpbuild (reference §16.2) with "main": "Programa" looks for src/Programa.bp and, if it is not there, src/Programa.jc. With both at once, it does not guess: it says so («el main está dos veces, Programa.bp y Programa.jc: el proyecto no sabe cuál compilar», the main is there twice: the project does not know which one to compile) and does not compile. The sources list accepts .jc files, and its files are compiled in order, so a JC module that imports another JC module goes after it:

{
  "sourceDir": "src",
  "outDir":    "out",
  "main":      "Programa",
  "sources":   ["src/Utiles.jc", "src/Programa.jc"]
}
java -jar basicplus-frontend.jar --project app.bpbuild

With the files of §5.4 in src, it compiles Utiles, then Programa and, because Programa imports it, Viejo.bp.

18.3 Translating between BP and JC

The compiler translates a source into the other language and writes it to the output. It translates the already analysed tree, so it knows where each new goes, which call is a conversion and what type a constant has when BP does not write it.

OptionWith a .bpWith a .jc
--escribir-jcits translation to JCthe same file, rewritten
--escribir-bpthe same file, rewrittenits translation to BP
--comprobar-jcthe round trip: it translates it to JC, reads it back and compares the two trees—

A BP source, with its comments:

module Saludo
  // how many times to greet
  const VECES := 2

  function main()
    for i := 1 to VECES do
      print "hola "; i     // no comma: no space
    next
  end main
end Saludo
java -jar basicplus-frontend.jar Saludo.bp --escribir-jc > Saludo.jc
java -jar basicplus-frontend.jar Saludo.bp --comprobar-jc

The second command does the round trip, and the tree that comes back is the same:

Saludo.bp: EQUIVALENTE

The first one leaves the translation in Saludo.jc, without the comments and with the type the compiler deduces for the constant:

module Saludo
{
   const int VECES = 2;

   function void main()
   {
      for (int i = 1; i <= VECES; i++)
      {
         println("hola ", i);
      }
   }
}
hola 1
hola 2

18.4 In the IDE

Just the essentials; the details are in the IDE guide.

18.5 The error messages

19. The libraries

The standard library, the graphical interface, SQLite and the packs are compiled BP modules: a program in JC imports them and uses them the same way, with the same names. Their documentation is in the BP volumes:

I want…See
the functions of Core, List, Map, files, Json, Math…Reference, §13
the pins, the buses, the network, Bluetooth, the SD card, soundReference, §14
the graphical interface: screens, widgets, events, formsGraphical interface
SQLite and the ORMDatabases
the IDE, the boards, the packs, debuggingIDE guide
the background of each construct: the GC, threads, owner, modulesLanguage manual

Their examples are in BP. They read in JC like this:

In the documentation (BP)In JC
function parseInt(s: string): integerint n = parseInt("42");
var l: List := List()List l = new List();
var txt: Gui.Label := Gui.Label(scr, "Hola")Gui.Label txt = new Gui.Label(scr, "Hola");
var m: Modelo.Medida := Modelo.Medida(l.get(i)) (converts)Modelo.Medida m = (Modelo.Medida) l.get(i);
print "valor:", vprintln("valor: ", v);
b.onClick := this::pulsadob.onClick = this::pulsado;
try var f: IO.TextFile := IO.TextFile("datos.txt", "r") … endtrytry (IO.TextFile f = new IO.TextFile("datos.txt", "r")) { … }
while not f.eof() do … endwhwhile (!f.eof()) { … }

Or, for a whole example, copy it into a .bp and translate it: --escribir-jc, or «Traducir a JC» in the IDE. A real JC program, with the Json library, is in the repository: samplesJC/JsonDemo.jc, also tested on a board.