XHarbour

Last updated

xHarbour is a free multi-platform extended Clipper compiler, offering multiple graphic terminals (GTs), including console drivers, GUIs, and hybrid console/GUIs. xHarbour is backward-compatible with Clipper and supports many language syntax extensions, greatly extended run-time libraries, and extensive third party support.

Contents

Like most dynamic languages, xHarbour is also available as a scripting language (standalone application, linkable library, MS ActiveScript engine [Windows Script Host, HTML, ASP]) utilizing an interpreter written in the xHarbour language.

The xHarbour Usenet newsgroup comp.lang.xharbour is an active community for discussing xHarbour related questions.

Built-in data types

xHarbour has 6 scalar types: Nil, String, Date, Logical, Number, Pointer, and 4 complex types: Array, Object, CodeBlock, and Hash. A scalar holds a single value, such as a string, number, or reference to any other type. Arrays are ordered lists of scalars or complex types, indexed by number, starting at 1. Hashes, or associative arrays, are unordered collections of any type values indexed by their associated key, which may be of any scalar or complex type.

Literal (static) representation of scalar types:

Complex Types may also be represent as literal values:

Hashes may use any type including other Hashes as the Key for any element. Hashes and Arrays may contain any type as the Value of any member, including nesting arrays, and Hashes.

Codeblocks may have references to Variables of the Procedure/Function>method in which it was defined. Such Codeblocks may be returned as a value, or by means of an argument passed BY REFERENCE, in such case the Codeblock will "outlive" the routine in which it was defined, and any variables it references, will be a DETACHED variable.

Detached variables will maintain their value for as long as a Codeblock referencing them still exists. Such values will be shared with any other Codeblock which may have access to those same variables. If the Codeblock did not outlive its containing routine, and will be evaluated within the lifetime of the routine in which it is defined, changes to its Detached Variables(s) by means of its evaluation, will be reflected back at its parent routine.

Codeblocks can be evaluated any number of times, by means of the Eval( BlockExp ) function.

Variables

All types can be assigned to named variables. Named variable identifiers are 1 to 63 characters long, start with [A-Z|_] and further consist of the characters [A-Z|0-9|_] up to a maximum of 63 characters. Named variables are not case sensitive.

Variables have one of the following scopes:

LOCAL, STATIC, and GLOBAL are resolved at compile time, and thus are much faster than PRIVATE and PUBLIC variables which are dynamic entities accessed by means of a runtime Symbol table. For this same reason, LOCAL, STATIC and GLOBAL variables are not exposed to the Macro compiler, and any macro code which attempts to reference them will generate a runtime error.

Due to the dynamic nature of PRIVATE and PUBLIC variables, they can be created and destroyed at runtime, can be accessed and modified by means of runtime macros, and can be accessed and modified by Codeblocks created on the fly.

Control structures

The basic control structures include all of the standard dBase, and Clipper control structures as well as additional ones inspired by the C or Java programming languages:

Loops

[DO] WHILE ConditionExp...    [LOOP]    [EXIT] END[DO]
FOR Var := InitExp TO EndExp [STEP StepExp]    ...    [LOOP]    [EXIT] NEXT
FOR EACH Var IN CollectionExp...    [HB_EnumIndex()]    [LOOP]    [EXIT] NEXT

In the FOR statement, the assignment expression is evaluated prior to the first loop iteration. The TO expression is evaluated and compared against the value of the control variable, prior to each iteration, and the loop is terminated if it evaluates to a numeric value greater than the numeric value of the control variable. The optional STEP expression is evaluated after each iteration, prior to deciding whether to perform the next iteration.

In FOR EACH, the Var variable will have the value (scalar, or complex) of the respective element in the collection value. The collection expression, may be an Array (of any type or combinations of types), an Hash Table, or an Object type.

IF statements

IF CondExp... [ELSEIF] CondExp... [ELSE]    ... END[IF]

... represents 0 or more statement(s).

The condition expression(s) has to evaluate to a LOGICAL value.

DO CASE statements

DO CASE    CASE CondExp...    [CASE CondExp]       ...    [OTHERWISE]       ... END[CASE ]

Above construct is logically equivalent to:

IF CondExp... ELSEIF CondExp... [ELSEIF CondExp]    ... [ELSE]    ... END[IF]

SWITCH statements

xHarbour supports a SWITCH construct inspired by the C implementation of switch().

SWITCH SwitchExp    CASE LiteralExp...       [EXIT]
   [CASE LiteralExp]       ...       [EXIT]     [DEFAULT]       ... END

BEGIN SEQUENCE statements

BEGIN SEQUENCE    ...    [BREAK]    [Break([Exp])] RECOVER [USING Var]    ... END[SEQUENCE]

or:

BEGIN SEQUENCE    ...    [BREAK]    [Break()] END[SEQUENCE]

The BEGIN SEQUENCE structure allows for a well behaved abortion of any sequence, even when crossing nested procedures/functions. This means that a called procedure/function, may issue a BREAK statement, or a Break() expression, to force unfolding of any nested procedure/functions, all the way back to the first outer BEGIN SEQUENCE structure, either after its respective END statement, or a RECOVER clause if present. The Break statement may optionally pass any type of expression, which may be accepted by the RECOVER statement to allow further recovery handing.

Additionally the xHarbour Error Object supports canDefault, canRetry and canSubstitute properties, which allows error handlers to perform some preparations, and then request a Retry Operation, a Resume, or return a Value to replace the expression triggering the error condition.

TRY [CATCH] [FINALLY] statements

TRY    ...    [BREAK]    [Break([Exp])]    [Throw([Exp])] CATCH [Var]    ... END
TRY    ...    [BREAK]    [Break([Exp])]    [Throw([Exp])] CATCH [Var]    ... FINALLY    ... END

or:

TRY    ...    [BREAK]    [Break([Exp])]    [Throw([Exp])] FINALLY    ... END

The TRY construct is very similar to the BEGIN SEQUENCE construct, except it automatically integrates error handling, so that any error will be intercepted, and recovered by means of the CATCH statement or forwarded to an outer CATCH handler otherwise. The FINALLY section is guaranteed to be executed before the TRY or CATCH sections forward flow control by means of RETURN, BREAK, or THROW.

Procedures/functions

[STATIC] PROCEDURE SomeProcedureName [STATIC] PROCEDURE SomeProcedureName() [STATIC] PROCEDURE SomeProcedureName( Param1' [, ParamsN] )
INIT PROCEDURE SomeProcedureName EXIT PROCEDURE SomeProcedureName
[STATIC] FUNCTION SomeProcedureName [STATIC] FUNCTION SomeProcedureName() [STATIC] FUNCTION SomeProcedureName( Param1' [, ParamsN] )

Procedures/functions in xHarbour can be specified with the keywords PROCEDURE, or FUNCTION. Naming rules are same as those for Variables (up to 63 characters non case sensitive). Both Procedures and Functions may be qualified by the scope qualifier STATIC to restrict their usage to the scope of the module where defined.

The INIT or EXIT optional qualifiers, will flag the procedure to be automatically invoked just before calling the application startup procedure, or just after quitting the application, respectively. Parameters passed to a procedure/function appear in the subroutine as local variables, and may accept any type, including references.

Changes to argument variables are not reflected in respective variables passed by the calling procedure/function/method unless explicitly passed BY REFERENCE using the @ prefix.

PROCEDURE have no return value, and if used in an Expression context will produce a NIL value.

FUNCTION may return any type by means of the RETURN statement, anywhere in the body of its definition.

An example procedure definition and a function call follows:

x := Cube( 2 )  FUNCTION Cube( n ) RETURN n ** 3 

Database support

xHarbour extends the Clipper Replaceable Database Drivers (RDD) approach. It offers multiple RDDs such as DBF, DBFNTX, DBFCDX, DBFDBT, and DBFFPT. In xHarbour multiple RDDs can be used in a single application, and new logical RDDs can be defined from combination of other RDD. The RDD architecture allows for inheritance, so that a given RDD may extend the functionality of other existing RDD(s). 3rd party RDDs, like RDDSQL, RDDSIX, RMDBFCDX, Advantage Database Server, and Mediator exemplify some of the RDD architecture features.

xHarbour also offers ODBC support by means of an OOP syntax, and ADO support by means of OLE.

Macro operator (runtime compiler)

One of the most powerful features of the xBase languages is the MACRO Operator '&'. xHarbour’s implementation of the Macro Operator allows for runtime compilation of any valid xHarbour expression. Such compiled expression may be used as a VALUE, i.e. the right side of an Assignment, but such compiled expression may be used to resolve the LEFT side of an assignment, i.e. PRIVATE, or PUBLIC variables, or Database FIELD.

Additionally the Macro Operator may compile and execute function calls, complete assignments, or even list of arguments, and the result of the macro may be used to resolve any of the above contexts in the compiled application. IOW, any xHarbour application may be extended, and/or modified in runtime, to compile and execute additional code on demand.

The xHarbour implementation of this feature is so complete that the xHarbour interpreter, xbScript, uses it heavily, to compile xHarbour scripts.

Syntax:

 &( ... )

The text value of the expression '...' will be compiled, and the value resulting from the execution of the compiled code is the result.

 &SomeId

is the short form for &( SomeId ).

 &SomeId.postfix

is the short form of &( SomeId + "postfix" ).

Example code

Hello, world!

The typical "hello world" program would be:

 ? "Hello, world!"

Or:

 QOut( "Hello, world!" )

Or:

 Alert( "Hello, world!" )

Or, enclosed in an explicit procedure:

PROCEDURE Main()    ? "Hello, world!"RETURN

OOP

 #include "hbclass.ch"   PROCEDURE Main()      LOCAl oPerson := Person( "Dave" )      oPerson:Eyes := "Invalid"      oPerson:Eyes := "Blue"      Alert( oPerson:Describe() )  RETURN 
 CLASS Person     DATA Name INIT ""      METHOD New() CONSTRUCTOR      ACCESS Eyes INLINE ::pvtEyes     ASSIGN Eyes( x ) INLINE IIF( ValType( x ) == 'C' .AND. x IN "Blue,Brown,Green", ::pvtEyes := x, Alert( "Invalid value" ) )      // Sample of IN-LINE Method definition     INLINE METHOD Describe()        LOCAL cDescription         IF Empty( ::Name )           cDescription := "I have no name yet."        ELSE           cDescription := "My name is: " + ::Name + ";"        ENDIF         IF ! Empty( ::Eyes )           cDescription += "my eyes' color is: " + ::Eyes        ENDIF     ENDMETHOD      PRIVATE:        DATA pvtEyes  ENDCLASS   // Sample of normal Method definition.  METHOD New( cName ) CLASS Person     ::Name := cName   RETURN Self 

Scripting

xHarbour is also available as an interpreted language in few flavors of scripting engines.

Related Research Articles

<span class="mw-page-title-main">Common Lisp</span> Programming language standard

Common Lisp (CL) is a dialect of the Lisp programming language, published in American National Standards Institute (ANSI) standard document ANSI INCITS 226-1994 (S2018). The Common Lisp HyperSpec, a hyperlinked HTML version, has been derived from the ANSI Common Lisp standard.

Eiffel is an object-oriented programming language designed by Bertrand Meyer and Eiffel Software. Meyer conceived the language in 1985 with the goal of increasing the reliability of commercial software development; the first version becoming available in 1986. In 2005, Eiffel became an ISO-standardized language.

<span class="mw-page-title-main">Scheme (programming language)</span> Dialect of Lisp

Scheme is a dialect of the Lisp family of programming languages. Scheme was created during the 1970s at the MIT Computer Science and Artificial Intelligence Laboratory and released by its developers, Guy L. Steele and Gerald Jay Sussman, via a series of memos now known as the Lambda Papers. It was the first dialect of Lisp to choose lexical scope and the first to require implementations to perform tail-call optimization, giving stronger support for functional programming and associated techniques such as recursive algorithms. It was also one of the first programming languages to support first-class continuations. It had a significant influence on the effort that led to the development of Common Lisp.

In computer science, control flow is the order in which individual statements, instructions or function calls of an imperative program are executed or evaluated. The emphasis on explicit control flow distinguishes an imperative programming language from a declarative programming language.

In computer programming, the scope of a name binding is the part of a program where the name binding is valid; that is, where the name can be used to refer to the entity. In other parts of the program, the name may refer to a different entity, or to nothing at all. Scope helps prevent name collisions by allowing the same name to refer to different objects – as long as the names have separate scopes. The scope of a name binding is also known as the visibility of an entity, particularly in older or more technical literature—this is in relation to the referenced entity, not the referencing name.

In computer programming, a parameter or a formal argument is a special kind of variable used in a subroutine to refer to one of the pieces of data provided as input to the subroutine. These pieces of data are the values of the arguments with which the subroutine is going to be called/invoked. An ordered list of parameters is usually included in the definition of a subroutine, so that, each time the subroutine is called, its arguments for that call are evaluated, and the resulting values can be assigned to the corresponding parameters.

<span class="mw-page-title-main">C syntax</span> Set of rules defining correctly structured programs

The syntax of the C programming language is the set of rules governing writing of software in C. It is designed to allow for programs that are extremely terse, have a close relationship with the resulting object code, and yet provide relatively high-level data abstraction. C was the first widely successful high-level language for portable operating-system development.

<span class="mw-page-title-main">For loop</span> Control flow statement for repeated execution

In computer science a for-loop or for loop is a control flow statement for specifying iteration. Specifically, a for loop functions by running a section of code repeatedly until a certain condition has been satisfied.

<span class="mw-page-title-main">Foreach loop</span> Control flow statement for traversing items in a collection

In computer programming, foreach loop is a control flow statement for traversing items in a collection. foreach is usually used in place of a standard for loop statement. Unlike other for loop constructs, however, foreach loops usually maintain no explicit counter: they essentially say "do this to everything in this set", rather than "do this x times". This avoids potential off-by-one errors and makes code simpler to read. In object-oriented languages, an iterator, even if implicit, is often used as the means of traversal.

In computer programming, a return statement causes execution to leave the current subroutine and resume at the point in the code immediately after the instruction which called the subroutine, known as its return address. The return address is saved by the calling routine, today usually on the process's call stack or in a register. Return statements in many programming languages allow a function to specify a return value to be passed back to the code that called the function.

Harbour is a computer programming language, primarily used to create database/business programs. It is a modernised, open source and cross-platform version of the older Clipper system, which in turn developed from the dBase database market of the 1980s and 1990s.

<span class="mw-page-title-main">JavaScript syntax</span> Set of rules defining correctly structured programs

The syntax of JavaScript is the set of rules that define a correctly structured JavaScript program.

Haxe is a high-level cross-platform programming language and compiler that can produce applications and source code for many different computing platforms from one code-base. It is free and open-source software, released under an MIT License. The compiler, written in OCaml, is released under the GNU General Public License (GPL) version 2.

In programming languages, a label is a sequence of characters that identifies a location within source code. In most languages, labels take the form of an identifier, often followed by a punctuation character. In many high-level languages, the purpose of a label is to act as the destination of a GOTO statement. In assembly language, labels can be used anywhere an address can. Also in Pascal and its derived variations. Some languages, such as Fortran and BASIC, support numeric labels. Labels are also used to identify an entry point into a compiled sequence of statements.

The syntax and semantics of PHP, a programming language, form a set of rules that define how a PHP program can be written and interpreted.

<span class="mw-page-title-main">Rexx</span> Command/scripting/programming language

Rexx is a programming language that can be interpreted or compiled. It was developed at IBM by Mike Cowlishaw. It is a structured, high-level programming language designed for ease of learning and reading. Proprietary and open source Rexx interpreters exist for a wide range of computing platforms; compilers exist for IBM mainframe computers.

The structure of the Perl programming language encompasses both the syntactical rules of the language and the general ways in which programs are organized. Perl's design philosophy is expressed in the commonly cited motto "there's more than one way to do it". As a multi-paradigm, dynamically typed language, Perl allows a great degree of flexibility in program design. Perl also encourages modularization; this has been attributed to the component-based design structure of its Unix roots, and is responsible for the size of the CPAN archive, a community-maintained repository of more than 100,000 modules.

Nemerle is a general-purpose, high-level, statically typed programming language designed for platforms using the Common Language Infrastructure (.NET/Mono). It offers functional, object-oriented, aspect-oriented, reflective and imperative features. It has a simple C#-like syntax and a powerful metaprogramming system.

Racket has been under active development as a vehicle for programming language research since the mid-1990s, and has accumulated many features over the years. This article describes and demonstrates some of these features. Note that one of Racket's main design goals is to accommodate creating new programming languages, both domain-specific languages and completely new languages. Therefore, some of the following examples are in different languages, but they are all implemented in Racket. Please refer to the main article for more information.

<span class="mw-page-title-main">Nim (programming language)</span> Programming language

Nim is a general-purpose, multi-paradigm, statically typed, compiled high-level systems programming language, designed and developed by a team around Andreas Rumpf. Nim is designed to be "efficient, expressive, and elegant", supporting metaprogramming, functional, message passing, procedural, and object-oriented programming styles by providing several features such as compile time code generation, algebraic data types, a foreign function interface (FFI) with C, C++, Objective-C, and JavaScript, and supporting compiling to those same languages as intermediate representations.

References