Hubbry Logo
Cobra (programming language)Cobra (programming language)Main
Open search
Cobra (programming language)
Community hub
Cobra (programming language)
logo
7 pages, 0 posts
0 subscribers
Be the first to start a discussion here.
Be the first to start a discussion here.
Cobra (programming language)
Cobra (programming language)
from Wikipedia
Cobra
ParadigmMulti-paradigm: object-oriented
Designed byCharles Esterbrook
DeveloperCobra Language LLC
First appeared2006; 19 years ago (2006)
Final release
0.9.6 / December 23, 2013; 11 years ago (2013-12-23)
Typing disciplinestrong, static, dynamic, inferred
OSMicrosoft .NET, Mono
LicenseMIT
Filename extensions.cobra
Websitecobra-language.com
Influenced by
Python, Eiffel, C#, Objective-C

Cobra is a discontinued general-purpose, object-oriented programming language.[1] Cobra is designed by Charles Esterbrook, and runs on the Microsoft .NET and Mono platforms.[2] It is strongly influenced by Python, C#, Eiffel, Objective-C, and other programming languages.[3] It supports both static and dynamic typing.[4][5] It has support for unit tests and contracts.[4] It has lambda expressions, closures, list comprehensions, and generators.[6]

Cobra is an open-source project; it was released under the MIT License on February 29, 2008.[7][8]

Features

[edit]
Object-oriented
Quality control
Expressiveness
  • Static and dynamic binding
  • List, dictionary, and set literals
  • in and implies operator
  • for expressions
  • Slicing
  • Interpolated strings
  • Compile-time type inference
  • Lambdas and closures
General productivity
Scripting conveniences
  • Clean syntax
  • Dynamic binding
  • One-step run
  • Shebang line (#!)
Miscellaneous

Examples

[edit]

The following examples can be run from a file using cobra <filename>.

class Hello
    def main
        print 'HELLO WORLD'

A simple class

[edit]
class Person

    var _name as String
    var _age as int

    cue init(name as String, age as int)
        _name, _age = name, age

    def toString as String is override
        return 'My name is [_name] and I am [_age] years old.'

References

[edit]
[edit]
Revisions and contributorsEdit on WikipediaRead on Wikipedia
from Grokipedia
Cobra is an imperative, high-level, object-oriented programming language designed by Charles Esterbrook, featuring clean syntax with influences from Python, C#, and Eiffel, and providing built-in support for contracts, unit tests, and compile-time nil tracking to enhance code quality and reliability. Development of Cobra began in 2006 as an effort to synthesize expressive scripting conveniences with compiled performance and static typing, targeting the .NET platform for Windows and Mono for systems including and macOS. It was released as under the in 2008, allowing both commercial and non-commercial use. Key features include static and dynamic binding for flexibility, lambdas and closures for elements, mixins and extensions for , generics for type-safe collections, and with garbage collection for robust application development. The language supports namespaces, interfaces, properties, indexers, and , while its indented block structure and literals for lists, dictionaries, and sets promote readable, Python-like code. Cobra compiles to executable code, offering scripting conveniences alongside high performance, and includes tools for rapid compilation via command-line interfaces like cobra file.cobra. A port to the was in progress during its active development phase, alongside integration with IDEs such as . The latest stable release, version 0.9.6, was made available on December 23, 2013, after which active development appears to have ceased, though the project remains accessible as open-source with and binaries for supported platforms. Community forums and resources persist for legacy use and potential revival efforts.

History

Origins and development

Cobra was designed and developed solely by Charles Esterbrook, a software consultant and language enthusiast, who began work on the project around 2006 as a personal endeavor under Cobra Language LLC. The initial motivations stemmed from Esterbrook's desire to create a that synthesized the best attributes of existing ones, prioritizing Python's readability and simplicity for rapid development, C#'s performance on .NET platforms, and Eiffel's design-by-contract features for enhanced safety and reliability. This approach aimed to address common trade-offs in programming languages, such as balancing expressiveness with execution speed and built-in quality assurances, without introducing experimental concepts. Development proceeded as a self-funded effort, with Esterbrook supporting the full-time work through winnings from poker tournaments, allowing him to focus on early prototypes without external backing. These prototypes evolved through iterative testing, incorporating feedback from an emerging via discussion forums, which influenced refinements and ultimately led to the decision to open-source the project in 2008 under the . Key early milestones included the language's first public demonstration at the Lang.NET Symposium in early , following internal beta stages that had been underway for about two years, marking the transition from private development to broader accessibility.

Release history and current status

Cobra first appeared in 2006 as a project initiated by Charles Esterbrook. It was released as under the on , . The language progressed through a series of beta releases, beginning with version 0.7.0 on January 27, , followed by version 0.8.0 in April , and further iterations in the 0.9.x series, including 0.9.2 in November 2012 and 0.9.4 in May 2013. These updates incorporated incremental enhancements, such as refinements to contracts and built-in support. The final release, version 0.9.6, arrived on December 23, 2013, marking the end of official development. After this point, activity ceased, with the last recorded commit to the primary repository occurring in March 2014. As of 2025, Cobra remains discontinued, with no active development or community-driven maintenance. The source code is preserved in archived repositories, such as the official GitHub mirror. Binary downloads for all major releases, from 0.7.0 through 0.9.6, are available via the archived official website at cobra-language.com, supporting legacy installations on .NET 4.0+ and Mono 2.10+ platforms.

Design

Philosophy and influences

Cobra's philosophy revolves around synthesizing proven features from established programming languages into a cohesive, practical that prioritizes developer productivity, code readability, and safety without introducing experimental or overly complex elements. By blending the ease of scripting languages with the performance of compiled ones, it aims to enable quick, expressive coding while ensuring fast execution through compilation to the .NET and Mono platforms. Central tenets include a strong emphasis on quality-driven development, achieved via language-level support for contracts, unit tests, and compile-time error checking such as nil tracking, which reduces runtime bugs and promotes robust applications. Cobra balances flexibility and discipline by supporting both static typing for performance-critical code and dynamic typing for , allowing developers to choose approaches that suit their needs. It also defaults to accurate decimal mathematics to avoid common floating-point pitfalls, further enhancing reliability. The language draws significant influences from Python, adopting its indentation-based syntax for clean, symbol-light code structure and simplicity in everyday programming tasks. C# shapes Cobra's object-oriented features, generics, and seamless integration with the .NET ecosystem, while Eiffel's design-by-contract approach informs its built-in preconditions, postconditions, and invariants for verifiable software correctness. contributes concepts around messaging and , and adds to the focus on expressiveness; other minor influences include for certain declarative elements and Smalltalk for object-oriented purity. Key design goals encompass minimizing boilerplate through concise syntax for common operations like properties and collections, elevating testing and contracts to first-class language constructs for inherent , and incorporating lightweight via mixins and extensions without the overhead of more intricate systems. This philosophy positions Cobra as a bridge between scripting convenience and enterprise-grade development, fostering productivity across diverse applications from prototypes to high-performance software.

Syntax overview

Cobra source files use the .cobra extension. The language employs indentation to structure code blocks, following a Python-like approach where each level of indentation consists of either one tab character or four spaces, but mixing tabs and spaces within the same line triggers a compiler error. Core keywords include class for declaring classes, def for defining methods, init for constructors (declared as def init), var for variable declarations (which support dynamic typing when no type is specified), and control flow elements such as if, else, and for for loops. Statements end at newlines, rendering semicolons optional and rarely used. Single-line comments begin with #; multi-line comments and documentation strings use triple quotes """. Strings are enclosed in single or double quotes and support via embedded expressions in square brackets, such as 'Hello, [_name]'. programs require a main method within a class, typically declared as class Program def main is shared, to serve as the , with all executable code contained within classes and methods rather than at the top level. The language supports shebang lines (e.g., #!/usr/bin/env cobra) for scripting, enabling direct execution of .cobra files as standalone scripts. Relative to its influences, Cobra's syntax demands more verbosity than Python for explicit type declarations (e.g., var x as String) but achieves greater conciseness than C# by relying on indentation over mandatory braces and semicolons.

Language features

Typing system

Cobra features a hybrid typing system that defaults to static typing for enhanced performance, compile-time error checking, and , while offering dynamic typing through the dynamic keyword to enable flexibility in scenarios requiring late binding or polymorphic behavior. This approach allows developers to leverage the benefits of both paradigms without fully committing to one, as static types facilitate optimization and early detection of incompatibilities, whereas dynamic types support and integration with varying data sources. Type inference plays a central role in the static typing model, automatically deducing variable types from initialization expressions to minimize explicit annotations and improve code readability. For instance, a local variable assigned an integer literal, such as n = 10, is inferred as the int type and remains fixed thereafter, preventing reassignment to incompatible types like strings at compile time. This inference applies to local variables within methods, reducing boilerplate while maintaining static guarantees, though explicit type declarations like n as int = 10 are available for clarity or when initialization is deferred using the var keyword, as in var n as int. The language enforces strong typing, prohibiting implicit conversions between incompatible types to uphold safety and prevent subtle runtime bugs. Numeric operations, for example, require matching types or explicit casts, and attempts to mix strings with numbers without coercion result in compile-time errors under static contexts. Supported primitive types include bool for logical values, string for text, char for single characters, and numeric variants such as decimal for exact fractional arithmetic, float32 and float64 for approximate floating-point, and number as a built-in type that defaults to decimal. Object types encompass classes, interfaces, and enums, while built-in collections like lists, sets, and dictionaries are supported through generic types (e.g., List<of string>) and literal syntax for concise initialization. Binding in Cobra is static by default for explicitly declared or inferred types, resolving method calls and accesses at for efficiency. However, dynamic binding occurs for variables or parameters marked with dynamic, such as in def process(x as dynamic), where operations like x.someMethod() are resolved at runtime, enabling for unknown or heterogeneous inputs. Late-bound calls, including those on dynamic entities, defer resolution to execution, which can invoke .NET reflection under the hood for . Error handling aligns with the typing mode: static contexts perform rigorous compile-time checks for type mismatches, , and invalid assignments, often reporting multiple issues simultaneously to accelerate development. In contrast, dynamic contexts shift type-related errors to runtime, where exceptions arise from failed method resolutions or invalid operations, such as invoking a nonexistent on a dynamic object; this trades early detection for adaptability but may increase overhead. This duality integrates with Cobra's design-by-contract features to enhance overall without overlapping into precondition enforcement.

Design by contract

Cobra's design by contract system draws directly from the Eiffel programming language, incorporating preconditions to ensure conditions hold before method execution, postconditions to verify outcomes afterward, and invariants to maintain class-wide state consistency throughout an object's lifecycle. This approach promotes reliable software by embedding behavioral specifications directly into the code, allowing developers to define expectations that the compiler and runtime can enforce. In Cobra, preconditions are specified using the require keyword followed by one or more boolean expressions, such as require serialNum > 0, which must evaluate to true prior to method invocation; failure triggers a RequireException. Postconditions employ the ensure keyword, often referencing the method's return value with result (e.g., ensure result > 0) or pre-execution state via the old prefix (e.g., .actionCount == old .actionCount + 1), ensuring post-execution validity and raising an EnsureException if violated. Class invariants, declared with invariant (e.g., .serialNum >= 1000), apply to the entire object and are checked at method entry and exit, with violations throwing an InvariantException. These contracts attach to methods or classes and are verified at runtime by default, though they can be disabled via the compiler flag cobra -contracts:none to avoid overhead in production environments. The system supports by allowing subclasses to extend contracts with or require for preconditions or and ensure for postconditions, ensuring derived classes uphold or strengthen the base specifications. Benefits include early detection during development and testing, clear of method interfaces, and facilitated through explicit behavioral guarantees. However, runtime checks introduce overhead, which can be mitigated by omitting them in release builds.

Built-in unit testing

Cobra's built-in framework allows developers to embed tests directly within class definitions, promoting close proximity between code and its validations. Tests are declared using the test keyword, followed by a block containing one or more assert statements that verify expected behaviors. For instance, within a class, a block might examine method outputs or , such as expecting a NullArgumentException for invalid inputs. This syntax integrates seamlessly with Cobra's object-oriented structure, treating tests as first-class elements akin to methods or properties. The framework supports automatic discovery of all test blocks within a class or during execution. Assertions provide detailed failure reporting, including the evaluated subexpressions, source file, line number, and relevant object state, which aids in rapid . Additionally, the expect keyword extends testing to anticipated exceptions, robust error handling validation. Tests can leverage Cobra's contracts—such as require and ensure clauses—for combined runtime and explicit checks, though unit tests focus on discrete validations rather than ongoing enforcement. This integration fosters a layered approach to without requiring separate tooling. To execute tests, developers use the built-in Cobra compiler with the -test option, such as cobra -test MyClass.cobra, which compiles the code, runs the tests, and provides pass/fail summaries. For broader project testing, the command scans and runs all discovered tests across files, reporting results in a concise format. This runner is included in the standard Cobra tools, eliminating the need for external frameworks like or . In production builds, tests can be excluded via the -turbo flag to optimize deployment. The philosophy behind Cobra's testing emphasizes ubiquity and simplicity, encouraging tests as executable documentation that evolves with the . By embedding tests inline, developers reduce context-switching and dependency on disparate tools, aligning with Cobra's goal of quality-driven development. A typical workflow involves writing test blocks alongside new methods during , then invoking the runner as part of the compilation process to validate changes iteratively. This approach not only catches regressions early but also serves as living examples for team members, enhancing in medium- to large-scale projects.

Advanced constructs

Cobra provides several advanced language constructs that enable expressive and efficient programming, drawing from functional and object-oriented paradigms to support concise code generation and reuse. Lambdas in Cobra are anonymous functions defined using the do keyword, allowing for inline function definitions that can capture variables from their enclosing scope, thus forming closures. This feature facilitates functional-style programming, such as passing small functions to higher-order methods for tasks like sorting or filtering collections. For example, a lambda might be used as sort list using do (a, b) a > b, where the closure captures external variables if needed. List comprehensions, known as "for expressions" in Cobra, offer a declarative way to transform iterables, similar to those in Python. The syntax is for var in sequence [where condition] get expression, producing a new collection. An example is lengths = for s in strings get s.length, which creates a of string lengths from an input of s. These expressions support optional filtering with where clauses, such as outstanding = for cust in customers where cust.balance > 0 get cust, enhancing readability for data transformations. Generators enable of sequences through the yield keyword, allowing functions to produce a series of values on demand without storing the entire result in memory. This is particularly useful for iterating over large or infinite datasets, such as recursive structures. Cobra's includes examples of using yield to traverse recursive data, integrating seamlessly with for loops and other iteration constructs. Mixins in Cobra provide a mechanism for composing behavior across classes, functioning as trait-like additions that support without resolving the diamond problem at runtime—all handled via compile-time composition. A class can incorporate a mixin using the mixins keyword in its declaration, inheriting methods and properties to promote and . For instance, a Logger mixin might add methods to any class that includes it, reducing duplication while maintaining single for the primary . Exception handling in Cobra follows a structured approach with try-catch blocks, allowing developers to anticipate and manage runtime errors gracefully. The syntax includes try for protected code, catch clauses for specific exception types (e.g., catch ex as IOException), and an optional finally for cleanup. This integrates with Cobra's compile-time nil tracking to minimize unexpected exceptions, as demonstrated in examples handling database or file operations. Modules in Cobra are supported through multi-file compilation, where related source files (e.g., .cobra files) are built together into a single assembly, enabling modular organization without explicit statements for local modules. Access to external .NET libraries occurs via declarations, such as use System.IO, facilitating integration with the broader ecosystem. This approach simplifies dependency management while leveraging the to resolve references across files.

Implementation

Compiler and tools

The Cobra compiler is a command-line tool named cobra that processes source files with the .cobra extension and generates Intermediate Language (IL) bytecode as .NET assemblies, such as executables (.exe) or libraries (.dll). This output is compatible with the .NET runtime and can be consumed by other .NET languages like C# or VB.NET. The tool supports direct execution of source files for scripting-like workflows, where cobra filename.cobra compiles and runs the program in one step, leaving behind the compiled assembly for reuse. The compilation process begins with the source code, followed by semantic analysis including static for declared types and contract verification. Cobra's hybrid system allows dynamic resolution at runtime for undeclared types, but the enforces checks for obvious mismatches, such as assigning a string to an integer variable, issuing errors before code generation. Contracts and built-in unit tests are evaluated where possible during this phase to catch violations early. The final step emits optimized IL bytecode. To compile without immediate execution, developers use flags like -c or -compile, producing standalone assemblies runnable directly on Windows or via Mono on systems. The -turbo flag activates full optimizations and removes debug symbols for production builds. Error reporting emphasizes compile-time diagnostics, providing clear messages for issues like inconsistent indentation (e.g., mixing tabs and spaces) or failures. These diagnostics include line numbers, expected versus actual types, and suggestions for resolution, aiding rapid . Runtime errors for dynamic aspects are handled via .NET exceptions, but the compiler's proactive checks reduce their occurrence. For IDE support, legacy plugins like VisualCobra provided syntax highlighting and project integration in 2010, though full compiler invocation required command-line fallback. Cobra's build system is straightforward and makefile-like, relying on the cobra tool for single-file or multi-file without a dedicated . Developers typically use simple scripts or .NET build tools like NAnt for larger projects, compiling modules into assemblies that reference each other via standard .NET mechanisms. This approach prioritizes simplicity over complex dependency resolution. The targets .NET and Mono platforms for broad compatibility, as detailed in the supported platforms section.

Supported platforms

Cobra runs primarily on the Microsoft .NET Framework for Windows environments and on Mono for cross-platform support, enabling execution on and macOS. This reliance on the (CLR) ensures compatibility with .NET 4.0 or later on Windows and Mono 2.10 or equivalent on systems. The language offers full integration with the .NET ecosystem, permitting Cobra code to directly invoke C# libraries and other .NET assemblies without additional bridging mechanisms. However, Cobra does not support native compilation; instead, its compiler generates intermediate language (IL) code that is executed via the CLR's just-in-time () compilation process. This approach introduces runtime overhead from dynamic typing and other features, though it leverages the CLR's optimized execution environment for overall performance. Key limitations include its tight coupling to the CLR, which precludes support for mobile platforms or targets. As of 2025, Cobra remains a legacy language with no official ports to modern .NET versions such as .NET Core or .NET 5 and later; it functions on .NET Framework 4.x installations but requires maintenance for contemporary environments.

Examples

The simplest program in Cobra, often referred to as "Hello World," demonstrates the language's basic syntax for outputting text to the console. This can be written as a top-level script without requiring a class definition, leveraging Cobra's scripting conveniences for quick execution. Here is the basic example saved in a file named hello.cobra:

cobra

print 'Hello, world.'

print 'Hello, world.'

This code uses the print statement to output the string literal 'Hello, world.' to the standard console. String literals in Cobra are enclosed in single or double quotes, and the print function handles the display without additional formatting. Top-level execution allows statements like this to run directly when the file is processed by the Cobra compiler, providing a Python-like simplicity for introductory scripts. Indentation is not required for this single statement, though it denotes structure in more complex code. To compile and run the program, use the Cobra compiler from the command line: cobra hello.cobra. This single command compiles the source to an (typically hello.exe on .NET platforms) and runs it immediately, producing the output "Hello, world." On Windows with .NET, the executable runs natively; on systems with Mono, it may require mono hello.exe if not run via the compiler. For a variation enabling direct scripting, add a shebang line at the top of the file:

cobra

#!/usr/bin/env cobra print 'Hello, world.'

#!/usr/bin/env cobra print 'Hello, world.'

Make the file executable with chmod +x hello.cobra and run it directly as ./hello.cobra, allowing seamless integration as a script on systems.

Simple class definition

In Cobra, classes are declared using the class keyword followed by the class name, establishing a blueprint for objects that encapsulate data and behavior. All members, such as variables and methods, are public by default unless specified otherwise. A simple class definition might look like the following example for a Person class, which stores a name and provides a string representation:

cobra

class Person var _name as String cue init(name as String) _name = name def toString as String return 'Name: ' + _name

class Person var _name as String cue init(name as String) _name = name def toString as String return 'Name: ' + _name

Here, the class declares a private instance variable _name of type String using var, which underscores Cobra's static typing system where parameter and variable types must be explicitly specified. The constructor, named init and introduced with the cue keyword, initializes the object with a required name parameter; it assigns the value directly to the instance variable. The toString method, defined with def, returns a formatted string using concatenation (+ operator) and explicitly declares its return type as String. To use this class, an instance is created and methods invoked as shown:

cobra

p = [Person](/page/Person)('Alice') print p

p = [Person](/page/Person)('Alice') print p

This instantiates a Person object with the name "Alice" and outputs "Name: Alice" by implicitly calling toString during printing. Such definitions highlight Cobra's object-oriented foundations, blending concise syntax with compile-time .

References

Add your contribution
Related Hubs
User Avatar
No comments yet.