B# (pronounced “be sharp”) is a tiny, object-oriented, andmulti-threaded programming language that is specially dedicated forsmall footprint embedded systems.
Because B# has its roots in the C family of languages, it will beimmediately familiar to C, C++, Java, and C# programmers. In additionto supporting modern object-oriented features such as namespaces,abstract and concrete classes, interfaces, and delegates, the B#language caters to the embedded systems programmer with efficientboxing/unboxing conversions, multi-threading statements, fieldproperties, device addressing registers, interrupt handlers, anddeterministic memory defragmenter.
Each of these features is directly supported by the constructs of B#and its underlying virtual machine in order to create, use, and reusemore portable and decoupled software components across differentembedded systems applications. This series of articles highlights andillustrates these key B# concepts with short programming excerpts, butleaves the details of other more common features to a more completeoverview.
Motivation and Unique Key Features
Despite the evolution of object-orientation and the development ofadvanced language features such as interfaces, delegates, andproperties, the linga franca for embedded systems programmers continuesto be the C programming language. Developed in the early 1970’s, the Clanguage has maintained its foothold over the years for four keyreasons: availability, portability, flexibility, and accessibility.
It has also served, at least syntactically, as the foundation forC++, Java, and C#, among many other experimental languages. C is nodoubt venerable, but it is also old [1, 2]. And, unfortunately , C++and Embedded C++ are often notsuitable for small-scale architectures with tight memory (<64KBytes) constraints.
Our programming language called B# (pronounced “be sharp”)introduces embeddedsystems developers to a fully-fledged, object-oriented programminglanguage that is designed explicitly for small footprint embeddedsystems [3, 4].
In addition to the traditional object-oriented features ofencapsulation, inheritance, and polymorphism, the B# language includesefficient boxing/ unboxing conversions, field properties, deviceaddressing registers, interrupthandlers, deterministic memory defragmenter, and multi-threadingcapabilities.
In order to support these features efficiently, high-level B# codeis mapped directly to a compact instruction set which is interpreted byan optimized embedded virtual machine called B#EVM. The intermediary ofa stack-based virtual machine allows the embedded systems developer towrite interrupt handlers and to access device registers in a uniformmanner, independent of the underlying target architecture(memory-mapped or port-mapped).
Several advantages accrue. First, resultant B# binary code is morecompact. The stack architecture of B#EVM precludes specifying registersand addressing modes. Hence, the opcode of B#EVM is reduced to onlyeight bits from the 16- or 32-bit opcodes of several modernmicrocontrollers. Second, the B#EVM which directly supportsobject-oriented features promotes the reusability of softwarecomponents expressed in binary format on any architecture where theB#EVM isavailable. It is worth noting that the implementation of the B#EVM,written in full ANSI C, is the only porting effort required for eachspecific architecture.
Third, not being dedicated to any specific microcontrollerarchitecture, the development of a toolkit (compiler, assembler,monitor, and so on) for a virtual machine like B#EVM is far easier totest, debug, and maintain and therefore, far more cost effective withrespect to the development of embeddedsystems applications.
Finally , B#EVM has its own multi-threading kernel and avoids theinclusion of third party kernels.
The paper is divided into two main sections. In this first part in aseries, an overview of the key and unique features of the B# languageitself are reviewed, while Part 2 outlines outlines the three majorcomponents of the embedded virtual machine B#EVM.
The B# Language
Each B# program consists of one or more source files.Eac h file iscomposedof types which, in turn, are composed of members.Classes, interfaces,and delegates are examples of different types and fields, methods,properties, interrupt handlers, and device registers are examples ofdifferent members. Classes are grouped into namespaces that may extendbeyond a single file, but unlike C#, namespaces cannot be nested.
Unified TypeSystem . B# has a unified type system. All B# types inherit froma single root object type. Thus, all types share a set of commonoperations and values of any type can be manipulated in a consistentmanner. B# is also strongly-typed and supports both value and referencetypes.
Value Types .B# has five value types: boolean (bool) ,character (char ), signedinteger (int ), unsigned integer(uint) , and floating-point (float ). For the sake of simplicityand internal stack evaluation efficiency, the five value types are allrepresented and manipulated as (maximum) 32-bit values.
Reference Types. Whereas value types contain variable data, reference types containaddresses of objects. B# provides a set of predefined reference typesfamiliar to Java or C# developers including object , array , and string . Two additional types, delegate and ioreg for device addressing, arealso included. The object type is similar to the untyped pointer (void* ) in the C programminglanguage.
EfficientBoxing/Unboxing Conversions . The type system of B# has theability to obtain type information of every variable at runtime and totreat value types as objects. These runtime capabilities are achievedby keeping minimal information on types in order to provide efficientand flexible boxing/unboxing conversions.
These conversions are an elegant mechanism inspired from C# andadapted for our needs. Consider the use of boxing/unboxing in the B#example below:
An int value is converted to object and back again to int . Boxing happens when avaluetype variable is converted to a reference type. Unlike C#, anobject box is already allocated and therefore, the value does not needto be copied into the box. Unboxing is the complementary process, butcontrary to C#. B# avoids copying a value into and out of a box byproviding a pre-allocated wrapping mechanism within the B#EVM stack.
This wrapping mechanism uses a tag that is set for each variable andidentifies its type. When a value-type variable is converted to areference type (or vice versa), the tag field is reset. In this way,the unified type systems of B# provides value types with the benefitsof reference types without introducing unnecessary overhead.
Expressions andMulti-threading Statements . The operators of B#, theirprecedence and associativity, are identical to those in C. Only thepointer operators *, & ,and -> are excluded andonly the operators, new forobject creation and is for typetesting, are also included. Expressions are formed by combining literalvalues and variables with B# operators.
B# also borrows several sequential statements from C includingstatement lists,block statements, expression statements,return, if, while, and break .In addition, the lock and start statements of B# are inspiredfrom Edison.
The lock statement, originally called when in Edison, is used formutual exclusion and synchronization. The start statement, originally called cobegin in Edison, is used toinitiate threads. The addition of multi-thread and synchronizationstatements facilitates the development of embedded systemswhere concurrent activities are often implicit.
In the following example, two threads, SerialPortThread and ParallelPortThread , are initiatedwith access to a shared buffer .
Classes andObjects. In B#, classes are the most fundamental types.A classtype defines a data structure that contains data members (fields) andfunction members (methods, properties, and others). A class provides aspecification for dynamically created instances of the class, alsoknown as objects.
Classes support inheritance and polymorphism, mechanisms wherebyderived classes can extend and specialize base classes. New classes arecreated usingclass declarations. A class declaration starts with a header thatspecifies the modifiers of the class, the name of the class, the baseclass (if any), and the interfaces implemented by the class.
Class Members. In B#, the members of a class are either static members or instancemembers. Static members belong to classes and instance members belongto objects (instances of classes). The following table provides anoverview of the kinds of members a class can contain.
|Table1. Class Members in B#|
FieldProperties. A field property is a natural extension of fieldsand is similar to properties in C#. In addition to declaring a field, afield property also specifies the read and/or write access to the fielditself using the get and set accessors, respectively.
Each accessor is defined as a block statement which is executed whenthe field value is read or written. In essence, therefore, a fieldproperty is a field declaration followed by a get and/or set accessor.
In the following example, the Device module defines a Status fieldproperty. A property is always assumed to be an implicit private field with public accessors. Unlike C#, fieldproperties in B# denote storage locations.Therefore, it is unnecessaryto declare the private field status .
The value of a field property can be read by invoking the get accessor or written by invokingthe set accessor. In a set accessor, the new value for thefield property is passed via an implicit parameter named value . Accessing a field property islike getting or setting the value itself. For example, the Status property can be read andwritten in the same way that fields can be read and written:
Device Registers. The type ioreg represents input/output device register addressing forembedded processors based on the ISO/IEC standard.It is used for bothport- and memory mapped device registers, but submerges the distinctionbetween the two kinds of registers to the level of the virtual machineB#EVM.
Therefore, the embedded systems developer is not required to specifywhether or not a device is either port- or memory-mapped: the ioreg provides a uniform way ofhandling both. The type ioreg is the base class of three other predefined classes, ioreg8, ioreg16 , and ioreg32 , which allow read/writeaccess from/to8-bit, 16-bit, and 32-bit device registers, respectively.
Access to the device registers is defined using a mechanism similarto field properties. The only difference between the two is that theaddress of a ioreg field mustbe initialized at declaration. The following example declares threedevice registers as read only, write only, and read/write:
Interrupt Handlers. An interrupt handler (also called an interrupt service routine) is aspecial method which is executed when an external hardware interrupt istriggered. Each handler is specified by adding the interrupt keyword infront of a method, making it implicitly static and internal with noreturn value.
The interrupt number is declared after the name of the handler andis mapped internally by the B#EVM.The following method is a real-timeclock handler set to the interrupt vector 8:
Later, in the second part in this series, we will discuss the innerworkings of the embedded virtual machine B#EVM.
Michel de Champlain will present a full day tutorial at theEmbedded Systems Conference (ESC-504: Java Jumpstart in Room C2)starting at 8:30 a.m. on April 7. At 4:30 p.m. after the class, he willpresent a 30 minute presentation on B#.
Michel is chief scientist of DeepObjectKnowledge Inc., anobject-oriented training/mentoring firm located in Montreal, Quebec,Canada. He is also a former associate professor in Computer Engineeringat Concordia University and a regular speaker at the Embedded SystemsConference. He can be contacted at mdec@DeepObjectKnowledge.com.
Brian is an associate professor of Computer Science/Studies at TrentUniversity located in Peterborough, Ontario, Canada. His main researchinterests are programming languages and parallel job scheduling. He canbe contacted at email@example.com.
 M.Barr, Is C Passing?, Embedded.com,May 2002.
 J.W. Grenning, Why are you still using C?, Embedded.com,April 2003.
 M.de Champlain, B# Grammar, presents the grammatical summary of theB# programming language. Its syntax is described in a concise fashionusing the EBNF notation. www.DeepObjectKnowledge.comBSharpProjector www.BSharpLanguage.org.
 M.de Champlain and B.G Patrick, B# Project: Object Design forDevelopping Small Embedded Systems Applications, will be published byNewnes/Elsevier, Fall 2006.