Vala (programming language)

Vala
ParadigmMulti-paradigm: imperative, structured, object-oriented
DeveloperJürg Billeter, Raffaele Sandrini, Rico Tzschichholz
First appeared2006; 19 years ago (2006)
Stable release
0.57.0 Edit this on Wikidata / 11 April 2023; 21 months ago (11 April 2023)
Typing disciplineStatic, strong, inferred, structural
OSCross-platform all supported by GLib, but distributed as source code only.
LicenseLGPLv2.1+
Filename extensions.vala, .vapi
Websitevala.dev
Influenced by
C, C++, C#, D, Java, Boo

Vala is an object-oriented programming language with a self-hosting compiler that generates C code and uses the GObject system.

Vala is syntactically similar to C# and includes notable features such as anonymous functions, signals, properties, generics, assisted memory management, exception handling, type inference, and foreach statements.[1] Its developers, Jürg Billeter and Raffaele Sandrini, wanted to bring these features to the plain C runtime with little overhead and no special runtime support by targeting the GObject object system. Rather than compiling directly to machine code or assembly language, it compiles to a lower-level intermediate language. It source-to-source compiles to C, which is then compiled with a C compiler for a given platform, such as GCC or Clang.[2]

Using functionality from native code libraries requires writing vapi files, defining the library interfaces. Writing these interface definitions is well-documented for C libraries. Bindings are already available for a large number of libraries, including libraries that are not based on GObject such as the multimedia library SDL and OpenGL.

Description

Vala is a programming language that combines the high-level build-time performance of scripting languages with the run-time performance of low-level programming languages. It aims to bring modern programming language features to GNOME developers without imposing any additional runtime requirements and without using a different ABI, compared to applications and libraries written in C. The syntax of Vala is similar to C#, modified to better fit the GObject type system.[3]

History

Vala was conceived by Jürg Billeter and was implemented by him and Raffaele Sandrini, who wished for a higher-level alternative for developing GNOME applications instead of C. They liked the syntax and semantics of C# but did not want to use Mono, so they finished a compiler in May 2006. Initially, it was bootstrapped using C, and one year later (with release of version 0.1.0 in July 2007), the Vala compiler became self-hosted. In 2008, the Genie language was created to expose a Python-like syntax to the Vala compiler.[4] As of 2021, the current stable release branch with long-term support is 0.48, and the language is under active development with the goal of releasing a stable version 1.0.[5]

Version Release date[6] Remarks
Old version, no longer maintained: 0.0.1 2006-07-15
Old version, no longer maintained: 0.1.0 2007-07-09
Old version, no longer maintained: 0.10.0 2010-09-18
Old version, no longer maintained: 0.20.0 2013-05-27
Old version, no longer maintained: 0.30.0 2015-09-18
Old version, no longer maintained: 0.40.0 2018-05-12 Stable Long-term Support
Old version, no longer maintained: 0.42.0 2018-09-01
Old version, no longer maintained: 0.44.0 2019-05-09
Old version, no longer maintained: 0.46.0 2019-09-05
Old version, no longer maintained: 0.48.0 2020-03-03 Stable Long-term Support
Old version, no longer maintained: 0.50.0 2020-09-10
Old version, no longer maintained: 0.52.0 2021-05-17
Old version, no longer maintained: 0.54.0 2021-09-16
Latest version: 0.40.25 2021-01-11 Stable Long-term Support
Old version, no longer maintained: 0.56.0 2022-03-17 Stable Long-term Support
Latest version: 0.48.25 2022-09-16 Stable Long-term Support
Latest version: 0.56.17 2024-04-19 Stable Long-term Support
Legend:
Old version
Old version, still maintained
Latest version
Latest preview version
Future release
For old versions, only first point releases are listed

Language design

Features

Vala uses GLib and its submodules (GObject, GModule, GThread, GIO) as the core library, which is available for most operating systems and offers things like platform independent threading, input/output, file management, network sockets, plugins, regular expressions, etc. The syntax of Vala currently supports modern language features as follows:

Graphical user interfaces can be developed with the GTK GUI toolkit and the Glade GUI builder.

Memory management

For memory management, the GType or GObject system provides reference counting. In C, a programmer must manually manage adding and removing references, but in Vala, managing such reference counts is automated if a programmer uses the language's built-in reference types rather than plain pointers. The only detail one needs to worry about is to avoid generating reference cycles, because in that case this memory management system will not work correctly.[7]

Vala also allows manual memory management with pointers as an option.

Bindings

Vala is intended to provide runtime access to existing C libraries, especially GObject-based libraries, without the need for runtime bindings. To use a library with Vala, all that needed is an API file (.vapi) containing the class and method declarations in Vala syntax. However, C++ libraries are not supported. At present, vapi files for a large part of the GNU project and GNOME platform are included with each release of Vala, including GTK. There is also a library called Gee, written in Vala, that provides GObject-based interfaces and classes for commonly used data structures.[8]

It should also be easily possible to write a bindings generator for access to Vala libraries from applications written in other languages, e.g., C#, as the Vala parser is written as a library, so that all compile-time information is available when generating a binding.

Tools

Editors

Tooling for Vala development has seen significant improvement over the recent years. The following is a list of some popular IDEs and text editors with plug-ins that add support for programming in Vala:

Code intelligence

Currently, there are two actively developing language servers which offer code intelligence for Vala as follows:

  • vala-lang/vala-language-server, designed for any editor that supports LSP, including VSCode, vim, and GNOME Builder[12]
  • esodan/gvls, currently the default language server for Vala in GNOME Builder and provides support to any editor with support for LSP[13]

Build systems

Currently, there are a number of build systems supporting Vala, including Automake, CMake, Meson, and others.[14]

Debugging

Debugging for Vala programs can be done with either GDB or LLDB. For debugging in IDEs,

Examples

Hello world

simple "Hello, World!" program in Vala:

void main () {
	print ("Hello World\n");
}

As can be noted, unlike C or C++, there are no header files in Vala. The linking to libraries is done by specifying --pkg parameters during compiling. Moreover, the GLib library is always linked and its namespace can be omitted (print is in fact GLib.print).

Object-oriented programming

Below is a more complex version which defines a subclass HelloWorld inheriting from the base class GLib.Object, aka the GObject class. It shows some of Vala's object-oriented features:

class HelloWorld: Object {
	private uint year = 0;
	
	public HelloWorld () {
	}
	
	public HelloWorld.with_year (int year) {
		if (year>0)
			this.year = year;
	}

	public void greeting () {
		if (year == 0)
			print ("Hello World\n");
		else
			/* Strings prefixed with '@' are string templates. */
			print (@"Hello World, $(this.year)\n"); 
	}
}

void main (string[] args) {
	var helloworld = new HelloWorld.with_year (2021);
	helloworld.greeting ();
}

As in the case of GObject library, Vala does not support multiple inheritance, but a class in Vala can implement any number of interfaces, which may contain default implementations for their methods. Here is a piece of sample code to demonstrate a Vala interface with default implementation (sometimes referred to as a mixin)

using GLib;

interface Printable {
	public abstract string print ();

	public virtual string pretty_print () {
		return "Please " + print ();
	}
}

class NormalPrint: Object, Printable {
	string print () {
		return "don't forget about me";
	}
}

class OverridePrint: Object, Printable {
	string print () {
		return "Mind the gap";
	}

	public override string pretty_print () {
		return "Override";
	}
}

void main (string[] args) {
	var normal = new NormalPrint ();
	var overridden = new OverridePrint ();

	print (normal.pretty_print ());
	print (overridden.pretty_print ());
}

Signals and callbacks

Below is a basic example to show how to define a signal in a class that is not compact, which has a signal system built in by Vala through GLib. Then callback functions are registered to the signal of an instance of the class. The instance can emit the signal and each callback function (also referred to as handler) connected to the signal for the instance will get invoked in the order they were connected in:

class Foo {
    public signal void some_event ();   // definition of the signal

    public void method () {
        some_event ();                  // emitting the signal (callbacks get invoked)
    }
}

void callback_a () {
    stdout.printf ("Callback A\n");
}

void callback_b () {
    stdout.printf ("Callback B\n");
}

void main () {
    var foo = new Foo ();
    foo.some_event.connect (callback_a);      // connecting the callback functions
    foo.some_event.connect (callback_b);
    foo.method ();
}

Threading

A new thread in Vala is a portion of code such as a function that is requested to be executed concurrently at runtime. The creation and synchronization of new threads are done by using the Thread class in GLib, which takes the function as a parameter when creating new threads, as shown in the following (very simplified) example:

int question(){
    // Some print operations 
    for (var i = 0; i < 3; i++){
        print (".");
        Thread.usleep (800000);
        stdout.flush ();
    }

    return 42;
}

void main () {
    if (!Thread.supported ()) {
        stderr.printf ("Cannot run without thread support.\n");
        return;
    }
    print ("The Ultimate Question of Life, the Universe, and Everything");
    // Generic parameter is the type of return value
    var thread = new Thread<int> ("question", question);

    print(@" $(thread.join ())\n");
}

Graphical user interface

Below is an example using GTK to create a GUI "Hello, World!" program (see also GTK hello world) in Vala:

using Gtk;

int main (string[] args) {
	Gtk.init (ref args);

	var window = new Window ();
	window.title = "Hello, World!";
	window.border_width = 10;
	window.window_position = WindowPosition.CENTER;
	window.set_default_size (350, 70);
	window.destroy.connect (Gtk.main_quit);

	var label = new Label ("Hello, World!");

	window.add (label);
	window.show_all ();

	Gtk.main ();
	return 0;
}

The statement Gtk.main () creates and starts a main loop listening for events, which are passed along via signals to the callback functions. As this example uses the GTK package, it needs an extra --pkg parameter (which invokes pkg-config in the C backend) to compile:

valac --pkg gtk+-3.0 hellogtk.vala

See also

  • Shotwell, an image organiser written in Vala.
  • Geary, an email client written in Vala.
  • elementary OS, a Linux distribution with a desktop environment programmed mostly in Vala.
  • Budgie, a Linux desktop environment programmed mostly in Vala.

References

  1. ^ "Vala: high-level programming with less fat". Ars Technica. 2 September 2007. Retrieved 13 December 2011.
  2. ^ "A look at two new languages: Vala and Clojure".
  3. ^ "Vala· GitLab". GNOME. Retrieved 16 March 2021.
  4. ^ Jančár, M.; Chodarev, S. (2015). "A generative framework for development of CRUD-based Linux desktop applications". 2015 IEEE 13th International Scientific Conference on Informatics. Poprad, Slovakia. pp. 133–138. doi:10.1109/Informatics.2015.7377821. The Vala compiler also supports the Genie language, which is almost equal to Vala except the syntax. That is useful especially for defining models because of simple, "Python-like" syntax of Genie.
  5. ^ Michael Lauer (2019). Introducing Vala Programming. doi:10.1007/978-1-4842-5380-9. ISBN 978-1-4842-5379-3. S2CID 207911698. Retrieved 16 March 2021.
  6. ^ "Vala Releases". Vala Project. Retrieved 18 March 2021.
  7. ^ "Vala's Memory Management Explained".
  8. ^ "Libgee on Gitlab".
  9. ^ a b "Coding in Vala with Visual Studio Code". Retrieved 17 March 2021.
  10. ^ "Coding in Vala with the Vim Text Editor". Retrieved 17 March 2021.
  11. ^ "Enable Vala syntax highlighting and code browser support in GNU Emacs". Retrieved 17 March 2021.
  12. ^ "vala-lang/vala-language-server on Github". GitHub. Retrieved 17 March 2021.
  13. ^ "esodan/gvls on GitLab". Retrieved 17 March 2021.
  14. ^ "Vala Tools". Retrieved 29 March 2021.
Comparison with other languages

Read other articles:

Artikel ini bukan mengenai All rights reserved. Simbol copyleft yang sama sekali tidak memiliki makna legal daripada simbol hak cipta All rights reversed (secara kontekstual berarti hak cipta dibebaskan) adalah frasa penanda status lisensi hak cipta ataupun copyleft. Disebut-sebut sebagai permainan kata dari kalimat formalitas all rights reserved yang berasal dari Konvensi Buenos Aires 1910.[1] All Rights Reversed dibuat oleh Gregory Hill to mengizinkan pencetakan Principia Discordia ...

 

  Grand Prix Qatar 2016Detail lombaLomba ke 1 dari 18Grand Prix Sepeda Motor musim 2016Tanggal20 Maret 2016Nama resmiCommercial Bank Grand Prix of Qatar[1][2][3]LokasiLosail International CircuitSirkuitFasilitas balapan permanen5.380 km (3.340 mi)MotoGPPole positionPembalap Jorge Lorenzo YamahaCatatan waktu 1:54.543 Putaran tercepatPembalap Jorge Lorenzo YamahaCatatan waktu 1:54.927 di lap 20 PodiumPertama Jorge Lorenzo YamahaKedua Andrea Dovizioso ...

 

Entertainment NewsGenreInfotainmenPembuatGista PutriWishnutamaPresenterTemmy RahadiShafira UmmAubry BeerMaria SabtaGanindra BimoDeva MahenraCaesar GunawanNegara asalIndonesiaBahasa asliBahasa IndonesiaProduksiLokasi produksiThe East Building, Mega Kuningan, Kuningan Timur, Setiabudi, Jakarta Selatan, IndonesiaDurasi60 menitRumah produksiNET. NewsDistributorNet Visi MediaIndika GroupRilis asliJaringanNET.Format gambar16:9 HDTVFormat audioDolby Digital 5.1Rilis18 Mei 2013 (2013-05-18)...

Badruddin bin Ahmad ZainiBiografiKelahiran11 Februari 1937 Kematian22 Desember 1992 (55 tahun)Tempat pemakamanMakam Wali Lima Martapura Data pribadiAgamaIslam KegiatanPekerjaanUlama Bekerja diPondok Pesantren Darussalam Martapura (1976–1992) K.H. Badruddin bin Mufti K.H Ahmad Zaini atau lebih dikenal dengan Guru Ibad adalah salah seorang tokoh ulama sangat berpengaruh di Kota Martapura, Kabupaten Banjar, Kalimantan Selatan. Selain sebagai tokoh ulama yang dikenal karismatik dan berwibaw...

 

العلاقات الدومينيكية الليسوتوية دومينيكا ليسوتو   دومينيكا   ليسوتو تعديل مصدري - تعديل   العلاقات الدومينيكية الليسوتوية هي العلاقات الثنائية التي تجمع بين دومينيكا وليسوتو.[1][2][3][4][5] مقارنة بين البلدين هذه مقارنة عامة ومرجعية للدولتين:...

 

2005 single by EditorsMunichCover of the original single from 2005Single by Editorsfrom the album The Back Room B-side Disappear Crawl Down the Wall Colours Release Camera French Disko Find Yourself a Safe Place Released18 April 2005 (2005-04-18)Recorded2005Genre Post-punk revival indie rock Length3:46LabelKitchenwareSongwriter(s) Edward Lay Russell Leetch Tom Smith Chris Urbanowicz Producer(s)Jim AbbissEditors singles chronology Bullets (2005) Munich (2005) Blood (2005) 2006 R...

Currency of Hungary Hungarian forintMagyar forint (Hungarian) Hungarian forint banknotesISO 4217CodeHUF (numeric: 348)Subunit0.01UnitPluralforintok (nominative only)SymbolFt‎DenominationsSubunit 1⁄100fillér(defunct)Banknotes500 Ft, 1,000 Ft, 2,000 Ft, 5,000 Ft, 10,000 Ft, 20,000 FtCoins Freq. used5 Ft, 10 Ft, 20 Ft, 50 Ft, 100 Ft, 200 FtDemographicsDate of introduction1 August 1946ReplacedHunga...

 

Road in Spain You can help expand this article with text translated from the corresponding article in Spanish. (February 2024) Click [show] for important translation instructions. Machine translation, like DeepL or Google Translate, is a useful starting point for translations, but translators must revise errors as necessary and confirm that the translation is accurate, rather than simply copy-pasting machine-translated text into the English Wikipedia. Do not translate text that appears u...

 

Political party in Honduras Honduran Patriotic Alliance Alianza Patriótica HondureñaLeaderRomeo Vásquez VelásquezFounded25 March 2012HeadquartersTegucigalpaIdeologyConservatismPolitical positionCentre-rightNational Congress0 / 128Party flagWebsitehttp://alianzapatriotica.hn/Politics of HondurasPolitical partiesElections The Honduran Patriotic Alliance (Spanish: Alianza Patriótica Hondureña) is a centre-right political party in Honduras.[1] Romeo Vásquez Velásquez was ...

Artikel ini membutuhkan rujukan tambahan agar kualitasnya dapat dipastikan. Mohon bantu kami mengembangkan artikel ini dengan cara menambahkan rujukan ke sumber tepercaya. Pernyataan tak bersumber bisa saja dipertentangkan dan dihapus.Cari sumber: Ardan Radio – berita · surat kabar · buku · cendekiawan · JSTOR (Juli 2023) Ardan Radio (PM3FHI)PT Radio Ardan Swaratama (sebelumnya PT Radio Bonk-Kenks)KotaBandungWilayah siarBandung, Kabupaten Bandung, Kabu...

 

Министерство природных ресурсов и экологии Российской Федерациисокращённо: Минприроды России Общая информация Страна  Россия Юрисдикция Россия Дата создания 12 мая 2008 Предшественники Министерство природных ресурсов Российской Федерации (1996—1998)Министерство охраны...

 

Municipality in Catalonia, SpainSant Climent Sescebes San Clemente SasebasMunicipalityParish church Coat of armsSant Climent SescebesLocation in the Province of GironaShow map of Province of GironaSant Climent SescebesLocation in CataloniaShow map of CataloniaSant Climent SescebesLocation in SpainShow map of SpainCoordinates: 42°22′08″N 2°58′48″E / 42.369°N 2.980°E / 42.369; 2.980Country SpainCommunity CataloniaProvince GironaComarca Alt...

Национальное аэрокосмическое агентство Азербайджана Штаб-квартира Баку, ул. С. Ахундова, AZ 1115 Локация  Азербайджан Тип организации Космическое агентство Руководители Директор: Натиг Джавадов Первый заместитель генерального директора Тофик Сулейманов Основание Осн�...

 

Chemical compound This article needs additional citations for verification. Please help improve this article by adding citations to reliable sources. Unsourced material may be challenged and removed.Find sources: Pyriprole – news · newspapers · books · scholar · JSTOR (October 2013) (Learn how and when to remove this message) PyriproleClinical dataTrade namesPrac-ticATCvet codeQP53AX26 (WHO) Identifiers IUPAC name 1-[2,6-dichloro-4-(trifluoro...

 

International border Map of Kuwait, with Iraq to the north The Iraq–Kuwait border is 254 km (158 mi) in length and runs from the tripoint with Saudi Arabia in the west to the Persian Gulf coast in the east.[1] Description The border starts in the west at the Saudi tripoint on the Wadi al-Batin, and then follows this wadi as it flows north-eastwards. The border then turns east, following a straight line for 32 km (20 mi), before another straight line veers to the south-east...

Plant species grown for its oil-rich seed Brassica napus redirects here. For another cultivar of the same species grown for its root, see Rutabaga. Similar Brassica plants used in cooking as leafy greens, and also called rape may include rapini and choy sum. Rapeseed Scientific classification Kingdom: Plantae Clade: Tracheophytes Clade: Angiosperms Clade: Eudicots Clade: Rosids Order: Brassicales Family: Brassicaceae Genus: Brassica Species: B. napus Binomial name Brassica napusL.[no...

 

  Boldo Ilustración de 1887 de P. boldusEstado de conservaciónPreocupación menor (UICN)[1]​TaxonomíaReino: PlantaeDivisión: MagnoliophytaClase: MagnoliopsidaOrden: LauralesFamilia: MonimiaceaeGénero: PeumusEspecie: Peumus boldusMolina[2]​[editar datos en Wikidata] El boldo (Peumus boldus) es la única especie del género monotípico Peumus, de la familia de las monimiáceas. Este árbol es endémico de Chile. Sus hojas, de fuerte aroma, se utilizan con propós...

 

T

Tمعلومات عامةصنف فرعي من مِحْرَف جزء من إخطاطة لاتينيةPolish alphabet (en) أبجدية إنجليزية الرمز -TangoT تعديل - تعديل مصدري - تعديل ويكي بيانات T \ تيه \ الحرف العشرون من الأبجدية اللاتينية. وهو الحرف الساكن الأكثر شيوعًا وثاني الأحرف الأكثر شيوعًا في نصوص اللغة الإنجليزية.[1] مراجع ^...

2009 British filmShadows in the SunDirected byDavid RocksavageWritten byDavid RocksavageScreenplay byMargaret Glover David RocksavageProduced byNick O'HaganStarringJean Simmons James Wilby Ophelia Lovibond Jamie DornanMusic byRichard ChesterRelease date 5 June 2009 (2009-06-05) Running time81 minutesCountryUnited KingdomLanguageEnglish Shadows in the Sun is a 2009 British independent film directed by David Rocksavage and starring James Wilby, Jean Simmons, Jamie Dornan and Oph...

 

Italian porridge, usually of cornmeal For other uses, see Polenta (disambiguation). PolentaPolenta porridge with lentils (bottom) and cotechino sausage (top)TypePorridgePlace of originNorthern and central Italy[1]Main ingredientsYellow or white cornmeal, liquid (water, soup stock) Cookbook: Polenta  Media: Polenta Polenta (/pəˈlɛntə, poʊˈ-/, Italian: [poˈlɛnta])[2][3] is an Italian dish of boiled cornmeal that was historically made from other g...