<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0"><channel><title><![CDATA[Creating the EK9 programming language]]></title><description><![CDATA[Programming language creation blog]]></description><link>https://blog.ek9.io</link><generator>RSS for Node</generator><lastBuildDate>Mon, 16 Nov 2026 09:41:16 GMT</lastBuildDate><atom:link href="https://blog.ek9.io/rss.xml" rel="self" type="application/rss+xml"/><language><![CDATA[en]]></language><ttl>60</ttl><item><title><![CDATA[Well Another Year (how did we do)]]></title><description><![CDATA[Head down for another year, but development has now been very rapid. Claude Code and AI really does make a difference. Last year we had just one single ek9…]]></description><link>https://blog.ek9.io/well-another-year-how-did-we-do</link><guid isPermaLink="true">https://blog.ek9.io/well-another-year-how-did-we-do</guid><dc:creator><![CDATA[Steve]]></dc:creator><pubDate>Fri, 06 Nov 2026 17:58:44 GMT</pubDate><content:encoded><![CDATA[<p>Head down for another year, but development has now been very rapid. Claude Code and AI really does make a difference. Last year we had just one single ek9 program (hello world). Now we have tens of thousands of small programs. Plus ports of books written for other languages (like Python).</p>
<p>Last yer we also only had the bytecode JVM solution. Now, we almost have parity of native code via llvm. Theres still more work to do to round this out and ensure correct memory management.</p>
<p>We've added an Integrated Development Environment (<a href="https://ek9.io/ide/index.html">https://ek9.io/ide/index.html</a>) and also a full AI mcp connector with lots of built in functionality to enable and AI to code ek9 source easily and query the compiler from its symbol table (<a href="https://ek9.io/mcp/index.html">https://ek9.io/mcp/index.html</a>).</p>
<p>Also this year we've built a fuzzer (and found lots of defects and corrected them).</p>
<p>So, what's next? More documentation, packaging for MacOS, Linux and Windows to enable the first BETA release in 2027. Then we have to use the tooling to start building real applications and tease out any other issue not yet discovered.</p>
<p>So 2027 a BETA release available and then the hard work of using that to build real applications and ensure it is fit for use. During this time we will look at optimising the code generated (this should be very interesting).</p>
<p>Again this is getting closer and closer to being usable (Oh and I almost forgot, we also added a debugger in the IDE for the jvm runtime).</p>
<p>So, next year you'll be able to try this out and see what you think.</p>
<p>Steve</p>
]]></content:encoded></item><item><title><![CDATA[Hello World Again!]]></title><description><![CDATA[Well, not too long ago I managed to get the first ‘Hello World’ ek9 application working on the Java JVM. I was very pleased. This work on generating the…]]></description><link>https://blog.ek9.io/hello-world-again</link><guid isPermaLink="true">https://blog.ek9.io/hello-world-again</guid><category><![CDATA[native apps]]></category><category><![CDATA[LLVM ]]></category><category><![CDATA[LLVM CodeGen]]></category><category><![CDATA[EK9]]></category><dc:creator><![CDATA[Steve]]></dc:creator><pubDate>Wed, 17 Dec 2025 15:05:29 GMT</pubDate><content:encoded><![CDATA[<p>Well, not too long ago I managed to get the first ‘Hello World’ ek9 application working on the Java JVM. I was very pleased. This work on generating the Intermediate Representation (IR) and the JVM bytecode has progresssed much further. It now included conditions (if/else/switch), and iteration (for, while, do/while) and exceptions (try, catch, finally). All progressing very nicely and also being ‘fuzzed’ by Claude Code so we now have many mutations and changes. This ‘fuzzing; has really paid off finding weird edge cases and some just pure ‘dumb bugs’.</p>
<p>So, why ‘Hello World Again!’, well the EK9 language has a common front-end, ‘middle-end’ (IR), but importantly it has a dual back-end. By this I mean there is the JVM implementation that is well underway as outlined above. But now the LLVM native back end is also well under way.</p>
<p>The llvm-native back end has been progressing in terms of design and development of a standard api that mirrors the standard api that has been completed in Java for the JVM run-time. By this I mean types like String, Float, Integer, List etc. In Java these are daily easy to implement because they compile down to JVM bytecode and so can just be used via the byte code the ek9 compiler generates for user developed ek9 source.</p>
<p>However, for native execution, there is much more to consider. How do you represent ‘objects’ for example, how does the memory management work? Not to mention the rich API’s and structures modern Java offers that can just be reused in the JVM implementation, but mist be coded in the native back end.</p>
<p>As a back graound taks I;ve been working on a separate branch structuring the native llvm back-end using pure C with mangled named functions, structs (as vtables) and specific memory management routines. The EK9 IR already produces memory management instructions using ‘ARC’ basically reference counting to manage the memory allocation and release.</p>
<p>While maybe not as sophisticated as the Rust ‘borrow checker’, it is probablu much easier for developers to use as it is more akin to ‘garbage collection’. But it frees memory on last reference removal - so not really a mark and sweep. Although there has to be an element of mark and sweep for ‘islands’ of linked data structures. By this i mean object that reference each other but are now ‘detatched’ from the main application logic. These too need to be identified and ‘freed’.</p>
<p>Anyway, today after another 6 months of background work, we finally had ‘Hello World’ but via ek9 → IR → llvm IR → native binary executable.</p>
]]></content:encoded></item><item><title><![CDATA[Hello, World!]]></title><description><![CDATA[Having spent quite a bit of time defining the EK9 language, I started writing the compiler in around 2020. Now today on the 2nd of Ocober 2025, I have…]]></description><link>https://blog.ek9.io/hello-world</link><guid isPermaLink="true">https://blog.ek9.io/hello-world</guid><category><![CDATA[AI]]></category><category><![CDATA[#ai-tools]]></category><category><![CDATA[EK9]]></category><category><![CDATA[programming languages]]></category><category><![CDATA[Programming Blogs]]></category><dc:creator><![CDATA[Steve]]></dc:creator><pubDate>Thu, 02 Oct 2025 21:25:45 GMT</pubDate><content:encoded><![CDATA[<h1 id="heading-five-years-later">Five Years Later</h1>
<p>Having spent quite a bit of time defining the EK9 language, I started writing the compiler in around 2020. Now today on the 2nd of Ocober 2025, I have ‘hello world’ done from end to end. At the moment just running on a Java VM, but in time it will also be native.</p>
<h2 id="heading-why-so-long">Why so long?</h2>
<p>Well I went down quite a few rabbit holes in the ‘front-end’ of the compiler to be honest. I was that interested in detecting developer issues and reporting errors, I just carried on. Strage this is there are still more to pick up, like detecting missing dependency injection variables with ‘Applications’. I want to work out cohesion and coupling and emit errors if the values are to low/high, I’ve done this with complexity and I think it will stop AI producing poor quality code.</p>
<p>In fact it is in the latter area of using AI that I’m most interested in to be honest, because I’ve already used Claude Code to write some EK9 source examples and with a few adjustements in the compiler I managed to change its behaviour to produce more accurate code. I have the feeling I’m only skimming the surface of this. It’s really quite addictive and interesting to be able to automatically get and AI to alter its approach to code writing via compiler error messages. I see great potential here.</p>
<h2 id="heading-the-intermediate-representation">The Intermediate Representation</h2>
<p>To be frank, it took me about three goes to get the right sort of level of IR. I started off far too low, then I pulled back to much so it was too close to EK9. Then I found I have issues in being able to target both the JVM (which is stack based), versus LLVM (which is Static Single Assignment based). Plus I had to work out how I could do memeory management via LLVM (as the JVM is garbage collection based). So a single Medium Level Intermediate Representation was my final approach. There’s still 90% of it still to do! But enough for hello world.</p>
<h2 id="heading-jvm-back-end">JVM Back End</h2>
<p>Now I have at least some IR ready and was able to focus on checking that the IR was good enough to produce some sort of machine code. Turns out I had to keep fixing defects and omissions in the IR. I suspect there will be more as I do more of the IR. This sort of validates my approach of working on the ‘middle end’ and ‘back-end’ concurrently. But I also need to start work on the LLVM back-end to ensure that is viable.</p>
<p>I decided to use the ‘ASM’ Java package to help create the JVM byte code. Once I had a ‘stack based’ approach (which again took me a couple of attempts), I could move forward.</p>
<p>Basically now the back-end uses the generate IR (MLIR actually) and the details from the Symbols (populated by the ‘front-end’) to generate byte code.</p>
<p>There’s lots of tidying up to do and refactoring - because I was unsure which wy to go - so there’s messy dead end code I need to prune out - plus Claude is a ‘copy-paste master’.</p>
<h2 id="heading-integrating-it-all">Integrating it all</h2>
<p>While the phases of the compiler all defined and coordinated and work well together, I had to decide on how to call the compiled code for a ‘program’ from some sort of ‘main’.</p>
<p>As an EK9 project can contain multiple ‘programs’ I needed to detect them all and then look at what arguments those programs needed. Unlike most languages, EK9 can marshall a range of types and promote them to the correct type for the ‘program’. It does this my looking at the type signature of the program, then uses the ‘String’ values that are provides on the command line and attempts to marshal them into the type. If the number of arguments is incorrect on the command line or the types cannot be marshalled then an error is emitted and the program not run.</p>
<p>So, the compiler can detect all the programs and create and appropriate MLIR structure for the back-end to generate code for. But then I also need the ‘main’ for the initial entry point. This was again done by using ASM to dynamically create an ek9/Main class and deal with creating the new program (as selected by the user running the command).</p>
<h2 id="heading-almost-there">Almost there</h2>
<p>The EK9 design is such that it is intended to ‘feel scripty’, but actually be a compiled language. So, the main reason for the ‘shebang’ of ‘#!ek9’ in all EK9 source files is so that an EK9 source file can be set as ‘executable’ and an ‘ek9’ executable will be run to execute the code.</p>
<p>As the initial compiler and runtime is Java based, I did not want any EK9 developers (well just me at the moment) to have to deal with all the Java ‘-jar’, ‘-cp’ some.jar various commandlines bits. So it’s back to my roots and ‘C’.</p>
<p>So the ‘C’ wrapper ‘ek9.c’ was created, this (when compiled using clang) can be put on the users PATH, it will then use environment variable ‘EK9_HOME’ to find the ‘jar’ that has the compiler in it. It also checks that a suitable version of Java is available (25 - yes we’re on the bleading edge). It can then use ‘fork’ to call java with all the right arguments to trigger the compilation. If the command was a ‘run’ command the EK9 compiler will do all the necessary checks to see if any code need compiling and then compile the ek9 sources to Java class files and also extract the ‘stdlib’ from within the compiler classes file and create a ‘fat jar’.</p>
<p>So, now with a simple native binary we get the ‘shebang’, easy command line use for the user. a migration path off Java in time (not sure when!), but without any user code or use changes. The command runs our compiler and if the compilation is successful and ‘run’ was requested, the command to execute is provided back to the ek9.c binary and it can then execute that.</p>
<h2 id="heading-hello-world">Hello, World!</h2>
<pre><code class="lang-python"><span class="hljs-comment">#!ek9</span>
defines module introduction

  defines program

    HelloWorld()
      stdout &lt;- Stdout()
      stdout.println(<span class="hljs-string">"Hello, World!"</span>)

//EOF
</code></pre>
<p>Then when I run it (hardly a surprise):</p>
<pre><code class="lang-bash"> % ./helloWorld.ek9 
<span class="hljs-string">"Hello, World!"</span>
</code></pre>
<h3 id="heading-summary">Summary</h3>
<p>It’s been a bit of a long haul, with lots of interesting distractions. I’ll spend a bit of time updating the error handling and then look at implementing the llvm native parts for ‘hello world’.</p>
]]></content:encoded></item><item><title><![CDATA[Can Claude Help?]]></title><description><![CDATA[How to Use AI]]></description><link>https://blog.ek9.io/can-claude-help</link><guid isPermaLink="true">https://blog.ek9.io/can-claude-help</guid><category><![CDATA[AI]]></category><category><![CDATA[#ai-tools]]></category><category><![CDATA[claude.ai]]></category><category><![CDATA[claude]]></category><category><![CDATA[EK9]]></category><category><![CDATA[Java]]></category><dc:creator><![CDATA[Steve]]></dc:creator><pubDate>Tue, 22 Jul 2025 14:51:05 GMT</pubDate><content:encoded><![CDATA[<h1 id="heading-creating-ek9-standard-lib-api">Creating EK9 Standard Lib API</h1>
<p>From my other blog posts, you’ll be able to see I’ve been focussed on the ‘front-end’ of the compiler for several years.</p>
<p>I’m now looking to start work on the Intermediate Representation and also the ‘back-end’. With this in mind I deduced that for the ‘back-end’ I’m going to need some API’s to call.</p>
<p>I have already defined a ‘standard library’ for EK9 in terms of its interface. This covers most of the standard classes such as String and Float for example; but also some collections like List and Dict.</p>
<p>So I now have the daunting task of actually providing an implementation for all of these interfaces definitions in Java (as running via the JVM will be the first implementation).</p>
<p>You might be thinking, why are you jumping to the end to implement the API when you’ve not even completed the IR yet? Well I’m a start at both ends and meet in the middle sort of guy. This is borne of experience. You need to spread the pain parts, by this I mean it is very easy to start in one place and make your life very easy only to find by the time you get to the end those parts are no all but impossible.</p>
<p>So I start at both ends and then try and meet in the middle, then if I have to I spread the pain bits in the most appropriate direction so that I can join the two halves. The IR layer is going to have to suck up some or most of any of the mismatches between the ‘front-end’ and ‘back-end’. Plus I need to make it possible to produce an LLVM version of the back-end (one day in the next decade or so).</p>
<h2 id="heading-well-how-hard-can-it-be-to-implement-the-interface">Well how hard can it be to implement the interface?</h2>
<p>We’ll not that hard - the mapping from EK9 semantics methods/operators to Java API calls is pretty straightforward. But there are a very large amount of constructs to do (about 80 in total). Oh yes and the unit tests to make sure they all work. If I then look at the total number of methods/operators - I’ll have to implement around about a thousand (yes 1000 methods to implement and <strong>test</strong>).</p>
<p>Quick example (a little snippet of the EK9 interface for String (but truncated):</p>
<pre><code class="lang-python">...
          String <span class="hljs-keyword">as</span> open

            String() <span class="hljs-keyword">as</span> pure

            String() <span class="hljs-keyword">as</span> pure
              -&gt; arg0 <span class="hljs-keyword">as</span> String

            trim() <span class="hljs-keyword">as</span> pure
              &lt;- rtn <span class="hljs-keyword">as</span> String?
...
</code></pre>
<p>Now what I need is this implementation in Java. But I really need to be able to ‘introspect’ these implementations and dynamically pull out the EK9 interface.</p>
<p>So, I created a couple of Java annotations and a processor, so now I can just write:</p>
<pre><code class="lang-java">...
<span class="hljs-meta">@Ek9Class("""
    String as open""")</span>
<span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">String</span> <span class="hljs-keyword">extends</span> <span class="hljs-title">BuiltinType</span> <span class="hljs-keyword">implements</span> <span class="hljs-title">Any</span> </span>{
  java.lang.String state = <span class="hljs-string">""</span>;

  <span class="hljs-meta">@Ek9Constructor("""
      String() as pure""")</span>
  <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-title">String</span><span class="hljs-params">()</span> </span>{
    <span class="hljs-keyword">super</span>.unSet();
  }

  <span class="hljs-meta">@Ek9Constructor("""
      String() as pure
        -&gt; arg0 as String""")</span>
  <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-title">String</span><span class="hljs-params">(String arg0)</span> </span>{
    unSet();
    assign(arg0);
  }

  <span class="hljs-meta">@Ek9Method("""
      trim() as pure
        &lt;- rtn as String?""")</span>
  <span class="hljs-function"><span class="hljs-keyword">public</span> String <span class="hljs-title">trim</span><span class="hljs-params">()</span> </span>{
    <span class="hljs-keyword">if</span> (isSet) {
      <span class="hljs-keyword">return</span> String._of(<span class="hljs-keyword">this</span>.state.trim());
    }
    <span class="hljs-keyword">return</span> _new();
  }

...
</code></pre>
<p>Now I’ll do a bit of handwaving relating to the BuiltinType and Any types. But basically what this means is the I (or anyone) can define a Java class (using these Annotations) and the EK9 compiler can ‘extract’ the EK9 interface parts from it and use that to compile EK9 code against. It’s a bit like a ‘C’ header file - but all bound into the java class.</p>
<h2 id="heading-ok-so-lets-do-80-classes-and-over-a-thousand-methods-then">Ok so lets do 80 classes and over a thousand methods then</h2>
<p>Well, while I’m a glutton for punishment - why else try and develop a new language and compiler - even I get bored.</p>
<p><strong>Help</strong>, as an open source project that is still many years away from being useful, I’ve not had much help from anyone (no complaints - it’s just not useful to anyone yet - or I’m bad at promotion - probably both).</p>
<p>But now I have a new friend - it’s the friend I’ve always wanted - a workaholic, uncomplaining, fast typing, happy and polite developer. Ok they have their moments and are a bit ‘on the spectrum’.</p>
<p>Meet <strong>ClaudeCode</strong>, probably the biggest shake up in IT for several decades.</p>
<h3 id="heading-my-history">My history</h3>
<p>I’ve been a developer for many years 40 or so. I’ve used a range of lanaguages. I can focus and ‘crack out’ large amounts of reasonable code. Over time you realise some of what you create is truely bad, some outststand and most just about acceptable. But it varies day to day and week to week.</p>
<p>I’ve also been an analyst, team lead, technical lead, IT solution Architect, Product Owner and done two ‘start-ups’, both with some success.</p>
<p>So, I know how to articulate business requirements, break those down into technical tasks and then get on and develop them. Basically from the 80’s-90’s-early 2000’s ‘progammers’ were expected to do all of this.</p>
<p>But, I have been very, very sceptical of AI. Tried a few things here and there. Then I saw a blog post by Kent Beck. I thought well maybe I should have another look and use this tool called <strong>Claude Code.</strong></p>
<p>Well I’m really gald I did (thanks Kent). After a bit of tinkering around and ‘us’ getting to know one another, if you have a big bulky load of boiler plate code that follows a specific set of design patterns - the world is as deep as your pockets can go (Claude costs money).</p>
<p>But, as I finished a contract at the end of June (to do some personal stuff), I thought there’s no way I’ll get through all this code (as I can’t really spend all my time on it). But with Claude Code I can.</p>
<h2 id="heading-lets-cut-to-the-chase-then">Let’s cut to the chase then</h2>
<p>From 1st July until today 22nd of July; 46 thousand lines of code created. About 78 constructs created, lists of unit test cases. and 100% method code coverage, with about 95% total line coverage.</p>
<p>Pretty much the whole of EK9 standard library developed. I have a few more constructs to do and then revisit some of the existing ones to add in new methods.</p>
<p>That’s an average of 2,000 lines of code per day. <strong>But remember - this is boiler plate tedious work.</strong> I’ve done all the thinking, defined the EK9 interfaces, written thousands of line of example EK9 code (for the front-end of the compiler). Plus I know how to express what I want, and having work with lots of junior develops - I know when to say stop - you’re going in the wrong direction.</p>
<h2 id="heading-why-not-get-claude-to-write-this-blog-post">Why not get Claude to write this blog post</h2>
<p>Well I did, it was very technical, very interesting (some of it was wrong!). But it really is like asking a junior developer to write a business case for management - it would be just too technical and miss the benefits.</p>
<p>In short, Claude code wrote about 65% of the code for me - one I had given two or three examples of how I wanted it developed, kept correcting it and asked it to document this new knowledge. Plus I had the wealth of effort I had previously applied to creating ek9.io and lots of EK9 code for the front-end.</p>
<p>So, I’ll carry on using it for the rest of the easy API code generation, then I’ll try it with the Intermediate Representation.</p>
<h1 id="heading-summary">Summary</h1>
<p><strong>Yes</strong> Claude Code can help, it really can help. It’s a game changer. If you want to see the code - look in <a target="_blank" href="https://github.com/stephenjohnlimb/ek9">GitHub</a> and <a target="_blank" href="https://ek9.io">ek9</a>.</p>
<p>But, and here’s the kicker. I see the world moving back to a time when we did much more up front analysis and programmers need to become technical analysts/technical business analysts. Just knowing languages and coding will not be enough. You still need to be a savvy programmer, Claude and all these AI’s can churn out piles of stuff. You have to know how to cut it back. It will try and alter the implementation to pass the tests! Sometimes (once in a blue moon) its right. The test is correct but the implementation is defective.</p>
<p>So, we all still have jobs, but you’re going to have to move away from expecting detailed specs, and actually move up to working with the business to define detailed specs to get Claude (or some other AI) to code it. But you still need to be able to wade in correct the code and point that out. It’s like training a new developer in many ways.</p>
<p>Writing code and tests is no longer the bottleneck. Knowing what you want and knowing how to control the AI is the real need (Oh and yes having deep pockets, as you will be spending $$$ with the AI company).</p>
<p>Perhaps this screenshot from Github will make the productivity gain more obvious.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1753194598247/accbdc7e-8b33-4975-9531-8ca9c80ca84b.png" alt class="image--center mx-auto" /></p>
]]></content:encoded></item><item><title><![CDATA[Phases and Rules]]></title><description><![CDATA[Syntax and Semantics Rules]]></description><link>https://blog.ek9.io/phases-and-rules</link><guid isPermaLink="true">https://blog.ek9.io/phases-and-rules</guid><category><![CDATA[parsing]]></category><category><![CDATA[codegeneration]]></category><category><![CDATA[syntax analysis]]></category><category><![CDATA[semantics]]></category><dc:creator><![CDATA[Steve]]></dc:creator><pubDate>Tue, 04 Feb 2025 21:17:22 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/stock/unsplash/lUaaKCUANVI/upload/6b7b42959cfdd7d34c4e6b0bc6b1e19b.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>Now the EK9 grammar has stabilised, it's time to ensure that the EK9 code written by the developer actually makes sense. All of these phases use ANTLR Listeners/Visitors but all delegate processing, rules and checks to <em>functions</em>.</p>
<p>These functions tend to be composed with even more <em>functions</em>. Each one is designed to be focused on one task (or a limited number of related tasks). This is in contrast to the first prototype that used a more Object-Oriented solution. This quickly became very complex. The <em>function</em> based approach is much simpler and enables much more reuse through composition.</p>
<h3 id="heading-phasespasses">Phases/Passes</h3>
<p>With the EK9 grammar and language structure it is not possible to validate it all in a single 'pass'. This is because EK9 supports:</p>
<ul>
<li><p>Forward use (i.e. reference before declaration)</p>
</li>
<li><p>Type inference</p>
</li>
<li><p>It does not include the concept of <em>header files</em></p>
</li>
<li><p>Some rules can be checked very early and so:</p>
<ul>
<li><p>Can emit errors very quickly, speeding up the development cycles</p>
</li>
<li><p>Other rules need more details and so checks can only occur in later phases</p>
</li>
</ul>
</li>
</ul>
<p>This means that EK9 source code can reference other <strong>functions</strong>, <strong>classes</strong>, etc. from other EK9 source files or even the same source file when they are declared after their use. Moreover, EK9 has a form of type inference within code blocks meaning that the compiler can work out the <strong>type</strong> of variable being used in many cases.</p>
<p>To accomplish this, the EK9 compiler <em>visits</em> the AST a number of times (in phases). Importantly some of these phases can process code structures concurrently on a per file basis. The EK9 compiler has been designed to use multi-core CPU's from the outset.</p>
<h3 id="heading-phase-zero">Phase Zero</h3>
<p>Accepts source files that are to be compiled and parses them concurrently. The parsing of source files is quite an <em>expensive</em> operation. This phase leverages Java <strong>ANTLR</strong> to parse and validate the overall syntactic structure of the EK9 source code. The errors at this level are <strong>ANTLR</strong> generated. This is only focussed on <strong>syntax</strong> and not <strong>semantics</strong> (i.e. the meaning of the code).</p>
<p>The main issues in parsing are:</p>
<ul>
<li><p>Reading data from slow storage (yes SSD's are slow)</p>
</li>
<li><p>Breaking that source data text into Lexemes</p>
</li>
<li><p>Building an Abstract Syntax Tree (AST) via the grammar</p>
</li>
</ul>
<p>Given that most applications consist of hundreds if not thousands of source files (and that EK9 always works from source), it is essential that the above process is carried out quickly.</p>
<p>With the advent of widespread availability of multi-core CPU's, increasing cpu-core count and memory - concurrent file processing is viable.</p>
<p>However, this also means that the EK9 compiler will use a significant amount of memory. It is designed from the outset to only use memory, no file paging is employed at all. Big programs will require big memory and lots of CPU’s. But really modern development should at least try not be build huge monolithic applications where possible. They should be designed to be modular.</p>
<p>It is during this phase that an appropriate <a target="_blank" href="https://repo.ek9lang.org/apidocs/0.0.1-SNAPSHOT/org/ek9lang/compiler/common/ErrorListener.html">error listener</a> is configured and associated with each source file. Subsequent phases will emit errors in compilation using this <a target="_blank" href="https://repo.ek9lang.org/apidocs/0.0.1-SNAPSHOT/org/ek9lang/compiler/common/ErrorListener.html">error listener</a> object.</p>
<p><a target="_blank" href="https://repo.ek9lang.org/apidocs/0.0.1-SNAPSHOT/org/ek9lang/compiler/phase0/package-summary.html">See code documentation</a> for details of phase zero.</p>
<p>Phases 1-5 include layered and progressive <strong>semantic</strong> checks over and above enriching the internal <strong>Symbol</strong> definition and processing.</p>
<h3 id="heading-phase-one">Phase One</h3>
<p>Once each EK9 source file has been loaded and parsed it can be 'visited'. This means the AST can be traversed and <strong>Symbols</strong> defined by the EK9 developer can be identified and recorded. This all from data now held in memory.</p>
<p>This is in effect the first real 'pass' through the EK9 code, it is run in a concurrent manner. However, this is where things start to get complex.</p>
<p>Where multiple EK9 source files form part of the same <strong>module</strong> the <strong>Symbols</strong> must all be recorded in that same <strong>module</strong>. Moreover they must not <em>clash</em> with each other.</p>
<p>To accomplish this, the EK9 compiler protects <strong>modules</strong> with concurrency locks. This is designed to prevent multiple processing threads altering the internal state at the same time.</p>
<p>There is actually multiple forms of <strong>Symbol</strong> recording:</p>
<ul>
<li><p>Against an AST <em>tree node</em></p>
</li>
<li><p>Within a <em>module</em></p>
</li>
<li><p>Within some form of <em>aggregate/function</em> in a <em>module</em></p>
</li>
</ul>
<p>It is also during phase one that <strong>types</strong> are identified (where possible) on variables and properties. Typically these are just when <strong>literals</strong> are used, in general this is the approach the EK9 compiler takes. It builds up a more detailed picture of the <strong>types</strong> as each of the phases is processed.</p>
<p>See <a target="_blank" href="https://repo.ek9lang.org/apidocs/0.0.1-SNAPSHOT/org/ek9lang/compiler/phase1/package-summary.html">phase one details</a> for some of the many functions that get called during this phase. These are all just basic checks over and above the ANTLR grammar.</p>
<p>In general the ANTLR grammar has been made more flexible and simpler, this has enabled more rules and better error messages to be built into the EK9 compiler. It also simplifies the grammar to some extent.</p>
<h3 id="heading-phase-two">Phase Two</h3>
<p>During Phase One all of the main <em>aggregates</em> and <em>functions</em> will have been defined in a very basic skeleton form, this phase starts to add more detail around those constructs mainly focusing on <strong>type</strong> information.</p>
<p>The main purpose of this phase is to identify and resolve:</p>
<ul>
<li><p>Explicit <strong>type</strong> use</p>
</li>
<li><p>Explicit <strong>generic type</strong> use</p>
</li>
<li><p>Simple ‘constructor based’ inferred <strong>type use</strong> including construction of parameterised genetic types</p>
</li>
</ul>
<p>The processing in this phase also does a number of additional basic checks (<strong>semantic checks</strong>) now that <strong>Symbols</strong> and their relationships have at least been outlined.</p>
<p>This will include ensuring that <strong>types</strong> are open for extension and are of the same 'Genus'. This means it is not logical or allowed for a 'Class' to extend a 'Record' for example.</p>
<p>It is also during this phase that <em>functions</em> are examined to see if they fall into one of the following categories:</p>
<ul>
<li><p>Consumer</p>
</li>
<li><p>BiConsumer</p>
</li>
<li><p>Acceptor</p>
</li>
<li><p>BiAcceptor</p>
</li>
<li><p>Supplier</p>
</li>
<li><p>Provider</p>
</li>
<li><p>Function</p>
</li>
<li><p>BiFunction</p>
</li>
<li><p>UnaryOperator</p>
</li>
<li><p>Predicate</p>
</li>
<li><p>BiPredicate</p>
</li>
<li><p>Assessor</p>
</li>
<li><p>BiAssessor</p>
</li>
</ul>
<p>As EK9 treats <em>functions</em> in a polymorphic manner it automatically makes those <em>functions</em> 'super types' of the above common patterns - where their arguments, return values and 'pure' nature match. The generic functions above are really just common patterns of function signatures.</p>
<p>If a function does ‘match’ the signature of one of the above generic functions, then its ‘super function’ (a bit like a ‘super class’ for aggregates) is set. It should also be noted that each of the <em>generic functions</em> list above have a ‘super function’ of <strong>Any</strong>.</p>
<p>While it may seem strange to give ‘functions’ a sort of hierarchy - it enables ‘functions’ as well as ‘aggregates’ to be treated in a polymorphic manner (sub-typing).</p>
<p>See <a target="_blank" href="https://repo.ek9lang.org/apidocs/0.0.1-SNAPSHOT/org/ek9lang/compiler/phase2/package-summary.html">phase two details</a> for all the range of operations that are carried out in this phase.</p>
<h3 id="heading-phase-three">Phase Three</h3>
<p>This is a key phase as it checks for <strong>resolution</strong> of all <strong>symbols</strong>. It also deals with processing and deducing <strong>inferred types</strong> as part of code block expressions.</p>
<p>There are many rules, checks (more <strong>semantic</strong> assertions) and processes in this phase, indeed when this phase is triggered and the AST is 'visited' each tree node is processed on both <em>entry</em> and <em>exit</em>.</p>
<p>The <a target="_blank" href="https://repo.ek9lang.org/apidocs/0.0.1-SNAPSHOT/org/ek9lang/compiler/phase3/ResolveDefineInferredTypeListener.html">Listener</a> is the hook in from the ANTLR infrastructure, but really does very little other than calling one or more of the <em>functions</em> that perform the key processing of the specific EK9 language construct.</p>
<p>This approach has been taken to ensure there is a clear separation of concerns and a single responsibility for each of the aspects of processing.</p>
<p>Any <a target="_blank" href="https://repo.ek9lang.org/apidocs/0.0.1-SNAPSHOT/org/ek9lang/compiler/common/package-summary.html">common</a> or <a target="_blank" href="https://repo.ek9lang.org/apidocs/0.0.1-SNAPSHOT/org/ek9lang/compiler/support/package-summary.html">support</a> <em>functions</em> are pulled out and made reusable in different phases.</p>
<p>During <a target="_blank" href="https://repo.ek9lang.org/apidocs/0.0.1-SNAPSHOT/org/ek9lang/compiler/phase3/package-summary.html">phase three</a> many functions are called and most either populate/augments the <strong>Symbols</strong> identified or they process rules and emit compilation errors.</p>
<h3 id="heading-phase-four">Phase Four</h3>
<p>This phase checks that where a real type (or indeed a conceptual type in the case of generics using generics) has been employed. When parameterising a generic type with one or more types those types must support all the operators needed (used within the generic type). This is in the situation where generic/template types have been defined and operators have been ‘assumed’.</p>
<p>This approach enables generic types to be created with the assumption that when parameterised those type will have the right operators. Clearly the EK9 developer may attempt to use the generic type that does not have an essential operator - in this case a compiler error will be emitted. The EK9 developer can then add the operator to their type.</p>
<h3 id="heading-phase-five">Phase Five</h3>
<p>Now all symbols have been identified and all references resolved. This phase is the PRE_IR_CHECKS phase. It is designed to be the last set of <strong>semantic</strong> checks that can be made with just the ANTLR AST and the symbols identified.</p>
<p>This is done because the generation of the ‘Intermediate Representation’ is quite costly (in time and memory), so any obvious issues that can be identified now can cause the compilation to fail as early as possible.</p>
<p>The typical checks in this phase are:</p>
<ul>
<li><p>Variables being used before initialised</p>
</li>
<li><p>Return values not always being initialised</p>
</li>
<li><p>Safe access on Optional/Result methods such as get(), ok() and error()</p>
</li>
<li><p>Guard expressions and uninitialised return values (if/for/try/while/switch, etc)</p>
</li>
</ul>
<p>These checks make the EK9 language quite opinionated in terms of what ‘good code’ and ‘bad code’ is. From experience I’ve found that many of the longer term bugs and defects have been caused by issues relating to these checks. Hence, I’ve added these checks in to stop <strong>me</strong> writing code that could cause errors.</p>
<h3 id="heading-phase-six">Phase Six</h3>
<p>Resolving external libraries and built-in code for EK9 code that is marked as <strong>extern</strong>.</p>
<p>Resolution/linking of the built-in types that come as part of EK9 or in the future when there are other platform specific libraries/modules.</p>
<p>The EK9 compiler comes with lots of predefined and built in types and functions. But in reality they are only defined in terms of being and external interface - in other words they have no concrete implementation.</p>
<p>While this may seem strange, EK9 is designed to be able to have multiple ‘back-ends’ to produce different type of executable code (see later phases). For example it could be that the EK9 compiler (while written initially in Java) could produce outputs of:</p>
<ul>
<li><p>Java byte code for the EK9 applications developed</p>
</li>
<li><p>LLVM code and then several final binary outputs</p>
</li>
<li><p>Direct platform specific binary outputs (or even cross platform support)</p>
</li>
</ul>
<h3 id="heading-phase-seven">Phase Seven</h3>
<p>Focusses on the creation of an ‘Intermediate Representation’, this layer is the full abstraction away from the EK9 language and is much more general in nature. It does away with specific checks (as earlier compiler phases have ensured that the structures and semantics are coherent.</p>
<p>The ‘Intermediate Representation’ design is really important, it has to remove most (if not all) of the EK9 language specifics and move towards something much more general. It must also avoid becoming too ‘target architecture’ focussed as well. It must however reify specific information from the EK9 program (such as <strong>type</strong> information). This will be quite a balancing act to get right.</p>
<p>There is little difference at the IR level between a Component, Class, Trait, Text or Record - they are all just really an <strong>aggregate</strong>. Strangely you can also consider a Function or a Dynamic Function to be just an <strong>aggregate</strong> with one method. This works very well for the dynamic functions as they can actually <strong>capture</strong> data as properties (much like an aggregate with no accessor methods for those properties).</p>
<p>Even operators now just become methods on those <strong>aggregates</strong>. This whole approach enables the IR phase to just create various ‘flavours’ of aggregate- it will annotate/reify them with sufficient detail that they can be identified during code generation and runtime in a very specific way.</p>
<p>But this approach is an essential one to enable the ‘dispatcher’ and ‘function delegate’ approach to work as now everything is just an aggregate (i.e. it is an EK9 ‘Any’). So even instances of functions become ‘objects’ and can be passed around. But the dispatcher code will need to be able to access the ‘Any’ and find out its real type so that appropriate dispatcher methods can be called.</p>
<p>For example; within a module there will be <strong>constants</strong>, these will just be ‘instances’ of an ‘aggregate’ of a specific type (i.e. Float, Date, etc.). But so will named functions, they too will just be ‘instances’ of a ‘function’. A named function can therefore be considered just a <strong>constant</strong> but of a specific ‘function’.</p>
<h3 id="heading-phase-eight">Phase Eight</h3>
<p>All of the EK9 developer created generic/template types and their concrete (parametrised forms) can now be included in the ‘Intermediate Representation’. This may take several forms (unsure which approach to take at present). But it is quite possible that some form of simple aggregate (without the implementation is created and a real concrete implementation is delegated to (but in a very general and untype safe way), with casting to and from real concrete types.</p>
<p>The alternative would be to create real implementations from the generic type/template in a ‘cookie cutter’ fashion. This is likely to create a significant amount more code. This approach probably won’t be taken.</p>
<h3 id="heading-phase-nine">Phase Nine</h3>
<p>This phases is designed to be a place-holder for Intermediate Representation Analysis and Optimisation. Initially this will not be implemented. It can be quite complex and time consuming to implement and really I’d like to move ahead with code generation (so I can finally see something coded in EK9 actually run).</p>
<h3 id="heading-phase-ten">Phase Ten</h3>
<p>Code (Byte code, LLVM, binary) will be generated using the ‘Intermediate Representation’ and associated <strong>Symbol</strong> data.</p>
<p>At this point - my view on how this will be efficiently implemented is quite sketchy (TBH), how much caching can be done to avoid regeneration of code sections that are unchanged is not clear.</p>
<h3 id="heading-phase-eleven">Phase Eleven</h3>
<p>This is just a placeholder for optimisation of generated code, for some architectures this will be essential, but for others (like JVM based architectures) most of the optimisation will be done at runtime.</p>
<h3 id="heading-phase-twelve">Phase Twelve</h3>
<p>Finally, the last phase, this is just packaging. This could be into an executable either for the platform this compilation is running on or maybe for another platform if ‘cross-compilation’ is required. For Java byte code generation this phase would probably produce a ‘jar’ file.</p>
<h2 id="heading-summary">Summary</h2>
<p>While the first few phases above are quite detailed, you can see that the latter few are much more general. This is because most of the first phases (up to phase 5) have been implemented (I’m sure there will be bits missing that come to light as the later phases are developed).</p>
<p>The description of phases 6-8 are quite detailed (as they are now become more obvious to me as to what will be needed). I’m still unsure how to implement the <strong>resolution/linking</strong> of types that have been defined via ‘extern’ interfaces. Clearly this does depend on the ‘target architecture’. So for Java for example I may just load the ‘EK9-Lang.jar’ (that I’ll need to code up). Then using introspection check that a method on say <strong>org.ek9.lang.String</strong> as defined in the compiler does have all the correct methods and signatures as implemented in the Java target architecture and packaged in ‘EK9-Lang.jar’.</p>
<p>This would then able the compiler to generate the correct ASM (java byte code) to make a call from a developer EK9 code using the <strong>org.ek9.lang.String</strong> to the Java implementation.</p>
<p>For LLVM solutions, there would need to be some similar mechanism. Clearly this has been done for linking Python code to binary shared libraries. One mechanism to enable early resolution of symbols (before runtime), is to ensure that a binary shared library has a ‘known’ entry point.</p>
<p>By enabling the EK9 compiler to call this ‘known’ entry point in the shared library would enable the shared library to respond with some form of data structure that states what functions, constants, types etc exist with in it. So for the ‘EK9-Lang.so’ lets say compiled for Linux it might respond back with just a plain (but long) <strong>String</strong> that has basically the same <strong>types</strong> and structures as the built-in EK9 language interface as defined by the compiler. Indeed, maybe the current built-in types hard coded in the compiler would be removed and just the ‘EK9-Lang.jar’ used via the well known call. It would provide the ‘interface’.</p>
<p>In the same way that the compiler can check and resolve methods against the built-in ‘extern’ interface definition. It can be used at resolution/linking time to resolve the same types and calls on the interface supplied by the ‘EK9-Lang.so’. This does of course depend on the ‘EK9-Lang.jar’ or ‘EK9-Lang.so’ actually correctly reporting what it has (if this is incorrect then errors will occur either at linking time (for binaries) or runtime for Java ‘jar’ combinations.</p>
<p>This latter approach, does seem more scalable and would require less code in the compiler:</p>
<ul>
<li><p>Locate library depending on target architecture</p>
</li>
<li><p>Make a call (using that target architecture) from the compiler to the ‘known’ entry point.</p>
</li>
<li><p>Use the ‘String’ response (containing the EK9 <strong>extern</strong> interface definition) in the compiler and parse it.</p>
</li>
<li><p>In effect this <strong>extern</strong> interface definition is that the EK9 developers code must use</p>
</li>
<li><p>Assuming that the developer of the EK9-*.jar or EK9-*.so (or whatever was provided did a good job and all the constructs outlined in the ‘EK9 <strong>extern</strong> interface definition’ were correctly implemented in the EK9-*.jar or EK9-*.so then at linking/runtime the calls would be resolved and work.</p>
</li>
</ul>
<p>The above approach, would enable 3rd parties or EK9 developers that wanted to wrap and use existing binary or other code in this sort of interface and make it available to be used in EK9 code.</p>
]]></content:encoded></item><item><title><![CDATA[New core 'Types' added]]></title><description><![CDATA[Essential Types]]></description><link>https://blog.ek9.io/new-core-types-added</link><guid isPermaLink="true">https://blog.ek9.io/new-core-types-added</guid><category><![CDATA[EK9]]></category><category><![CDATA[Types]]></category><category><![CDATA[polymorphism]]></category><category><![CDATA[rust lang]]></category><dc:creator><![CDATA[Steve]]></dc:creator><pubDate>Sun, 26 Jan 2025 13:40:45 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/stock/unsplash/2JIvboGLeho/upload/18190854f670669b962754e7991796c1.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>Well it’s been ages since I last wrote any blog articles, but I’ve been pretty busy on EK9 development and it has moved on in leaps and bounds.</p>
<p>So here’s a quick update on what’s been added and why.</p>
<p>I have also adjusted the type inference mechanism to be able to deal with simple expressions for the types on function returns, method returns and properties. This can now deal with simple Constructors and enables a sightly simpler syntax. See the ‘SteveSupplier’ and ‘StephenSupplier’ functions for examples of this.</p>
<h2 id="heading-any-type">Any Type</h2>
<p>At first when I designed EK9 I made the point that variables should be strongly typed.</p>
<p>But, I also highlighted how important ‘polymorphism’ was. While I was creating some tests in the EK9 language I found that it would be useful to mix a range of instances of typed values in ‘Lists’ and then via the use of a ‘dispatcher’ process each of those values (using their correct type).</p>
<p>However, with the current design of the language this was not possible, so I added the ‘Any’ type. Obviously I then had to make every construct type ‘extend’ the ‘Any’ type (this includes functions).</p>
<p>It took a reasonable amount of effort, but now it is possible to do this:</p>
<pre><code class="lang-python"><span class="hljs-comment">#!ek9</span>
defines module example.dispatch.any
  defines text <span class="hljs-keyword">for</span> <span class="hljs-string">"en"</span>
    Text
      welcome()
        <span class="hljs-string">"Welcome"</span>

  defines type
    CardSuit
      Hearts
      Diamonds
      Clubs
      Spades

    EmailAddress <span class="hljs-keyword">as</span> String constrain <span class="hljs-keyword">as</span>
      matches /^[a-zA-Z0<span class="hljs-number">-9</span>_.+-]+@[a-zA-Z0<span class="hljs-number">-9</span>-]+\.[a-zA-Z0<span class="hljs-number">-9</span>-.]+$/

  defines record
    R1
      property &lt;- <span class="hljs-string">"Steve"</span>
      default operator ?

  defines function
    SteveSupplier()
      &lt;- rtn &lt;- <span class="hljs-string">"Steve"</span>

    StephenSupplier()
      &lt;- rtn &lt;- <span class="hljs-string">"Stephen"</span>

  defines <span class="hljs-class"><span class="hljs-keyword">class</span>
    <span class="hljs-title">DispatcherExample</span>

      <span class="hljs-title">process</span>() <span class="hljs-title">as</span> <span class="hljs-title">dispatcher</span>
        -&gt; value as Any
        &lt;- rtn as String:</span> <span class="hljs-string">"Unknown type"</span>

      private process()
        -&gt; value <span class="hljs-keyword">as</span> Integer
        &lt;- rtn <span class="hljs-keyword">as</span> String: `Integer value of ${value}`

      private process()
        -&gt; value <span class="hljs-keyword">as</span> Float
        &lt;- rtn <span class="hljs-keyword">as</span> String: `Floating point value of ${value}`

      private process()
        -&gt; value <span class="hljs-keyword">as</span> Text
        &lt;- rtn <span class="hljs-keyword">as</span> String: `Text value of ${value.welcome()}`

      private process()
        -&gt; value <span class="hljs-keyword">as</span> CardSuit
        &lt;- rtn <span class="hljs-keyword">as</span> String: `CardSuit value of ${value}`

      private process()
        -&gt; value <span class="hljs-keyword">as</span> EmailAddress
        &lt;- rtn <span class="hljs-keyword">as</span> String: `EmailAddress value of ${value}`

      private process()
        -&gt; value <span class="hljs-keyword">as</span> R1
        &lt;- rtn <span class="hljs-keyword">as</span> String: `R1 property value of ${value.property}`

      private process()
        -&gt; value <span class="hljs-keyword">as</span> Supplier of String
        &lt;- rtn <span class="hljs-keyword">as</span> String: `Function value of ${value()}`

  defines function
    showExampleOfAnyAndDispatcher()
      //The compiler works out the <span class="hljs-string">'Any'</span> <span class="hljs-keyword">is</span> the best <span class="hljs-string">'type'</span>
      list &lt;- [
        <span class="hljs-number">1</span>,
        <span class="hljs-number">3.142</span>,
        Text(<span class="hljs-string">"en"</span>),
        CardSuit.Hearts,
        EmailAddress(<span class="hljs-string">"stephenjohnlimb@gmail.com"</span>),
        R1(),
        SteveSupplier,
        StephenSupplier
      ]

      //Now use a dispatcher.
      processor &lt;- DispatcherExample()
      <span class="hljs-keyword">for</span> listItem <span class="hljs-keyword">in</span> list
        value &lt;- processor.process(listItem)
        <span class="hljs-keyword">assert</span> value?

//EOF
</code></pre>
<p>This use of ‘Any’ in conjunction with the ‘dispatcher’ approach removes the need for any type casting, type checking or assumptions. Clearly if you were just dealing with ‘classes’ or ‘traits’ then a common method name/signature across all the varied types might remove the need for the dispatcher.</p>
<p>Also, note that functions that have specific ‘signatures’ are automatically given the appropriate ‘super function’. Here you can see that function ‘SteveSupplier’ and ‘StephenSupplier’ have been given a ‘super function’ of ‘Supplier of String’ (that has a ‘super function’ of ‘Any’).</p>
<h2 id="heading-optional-type">Optional Type</h2>
<p>While the Optional type was already defined in EK9, I decided to take a more ‘RUST’ approach to the access of the value (optionally held). So, I added some compiler checks specifically for the EK9 Optional type. The short example below highlights this:</p>
<pre><code class="lang-python"><span class="hljs-comment">#!ek9</span>
defines module error.on.optional.access

  defines function
    testSimpleValidIfCheck1()
      o &lt;- Optional(<span class="hljs-string">"Steve"</span>)

      <span class="hljs-keyword">if</span> o?
        value &lt;- o.get()
        <span class="hljs-keyword">assert</span> value?

    testUsingTernary() <span class="hljs-keyword">as</span> pure
      o &lt;- Optional(<span class="hljs-string">"Steve"</span>)

      value &lt;- o? &lt;- o.get() <span class="hljs-keyword">else</span> String()
      <span class="hljs-keyword">assert</span> value?

    &lt;?-
      Demonstrates how direct access to <span class="hljs-string">'get()'</span> will be detected
      <span class="hljs-keyword">if</span> a call to <span class="hljs-string">'o?'</span> <span class="hljs-keyword">is</span> <span class="hljs-keyword">not</span> made first.
    -?&gt;
    testInvalidGetAccess1()
      o &lt;- Optional(<span class="hljs-string">"Steve"</span>)

      //You will get a compiler error here, because no check has been done
      value &lt;- o.get()
      <span class="hljs-keyword">assert</span> value?

      //Safer access without the need <span class="hljs-keyword">for</span> o? call first.
      assuredValue &lt;- o.getOrDefault(<span class="hljs-string">"Stephen"</span>)
      <span class="hljs-keyword">assert</span> assuredValue?

//EOF
</code></pre>
<p>The function ‘testInvalidGetAccess1’ highlights that the compiler will emit an error if no check has been made before getting the optional value held. The safer way is to use one of the many other methods on the Optional type (including ‘getOrDefault’).</p>
<h2 id="heading-result-type">Result Type</h2>
<p>While I was reworking the ‘Optional’ type I decided to introduce the ‘Result’ type (as I could see that when used in RUST it had some merit). However, to be honest I did not like the way RUST employed the ‘Result’ type. So I’ve had a go at trying to make something slightly easier to use (well easier for me anyway).</p>
<p>The ‘Result’ type is a generic class much like ‘Optional’ but it has two type parameters; the ‘Ok’ type and the ‘Error’ type. These two types cannot be the same, they must be different (in EK9).</p>
<p>The key methods on the ‘Result’ are ‘?’ (is-set), ‘isOk()’, ‘isError()’ then ‘ok()’ and ‘error()’ to access the appropriate values.</p>
<p>Just like ‘Optional’ there are checks built into the compiler for ‘Result’ that check access is safe as shown below.</p>
<pre><code class="lang-python"><span class="hljs-comment">#!ek9</span>
defines module result.access

  defines function
    testEmptyResult()
      r &lt;- Result() of (String, Integer)
      <span class="hljs-keyword">assert</span> <span class="hljs-keyword">not</span> r.isOk() <span class="hljs-keyword">and</span> <span class="hljs-keyword">not</span> r.isError()

    testOkOnlyResult()
      r &lt;- (Result() of (String, Integer)).asOk(<span class="hljs-string">"Steve"</span>)
      <span class="hljs-keyword">assert</span> r.isOk() <span class="hljs-keyword">and</span> <span class="hljs-keyword">not</span> r.isError()

    testErrorOnlyResult()
      r &lt;- (Result() of (String, Integer)).asError(<span class="hljs-number">-1</span>)
      <span class="hljs-keyword">assert</span> <span class="hljs-keyword">not</span> r.isOk() <span class="hljs-keyword">and</span> r.isError()

    testSimpleResultUse()
      r &lt;- Result(<span class="hljs-string">"Steve"</span>, Integer())
      <span class="hljs-keyword">assert</span> r.isOk() <span class="hljs-keyword">and</span> r.isError()

      okValue &lt;- r.isOk() &lt;- r.ok() <span class="hljs-keyword">else</span> String()
      <span class="hljs-keyword">assert</span> okValue?

      //You can also do this
      errorValue &lt;- r.isError() &lt;- r.error() <span class="hljs-keyword">else</span> Integer()
      <span class="hljs-keyword">assert</span> <span class="hljs-keyword">not</span> errorValue?

      assuredValue1 &lt;- r.okOrDefault(<span class="hljs-string">"Stephen"</span>)
      <span class="hljs-keyword">assert</span> assuredValue1?

      assuredValue2 &lt;- r.getOrDefault(<span class="hljs-string">"Stephen"</span>)
      <span class="hljs-keyword">assert</span> assuredValue2?

    testCompilerErrorWhenAccessBeforeCheckingOk()
      r &lt;- Result(String(), Integer())

      //Compiler will emit error here, because no check has been made
      okValue &lt;- r.ok()
      <span class="hljs-keyword">assert</span> okValue?

      //Compiler will emit error here, because no check has been made
      asLower &lt;- r.ok().lowerCase()
      <span class="hljs-keyword">assert</span> asLower?

      //Compiler will emit error here, because no check has been made
      errorValue &lt;- r.error()
      <span class="hljs-keyword">assert</span> errorValue?
//EOF
</code></pre>
<p>The short example above shows some of the more simple methods on the ‘Result’ type, there are lots of other methods available for a more ‘functional’ approach; such as ‘whenOk()’ and ‘whenError()’.</p>
<h2 id="heading-summary">Summary</h2>
<p>All in all, I’m quite happy with the range of built-in types defined in EK9 now. In the next post I’ll cover each of the phases of the EK9 compiler and how far I’ve come and how much further there is to go (a long way!).</p>
]]></content:encoded></item><item><title><![CDATA[The Symbol Table]]></title><description><![CDATA[Well, it's been just over a year since my last blog post, I've been working on the Symbol Table (also changing jobs - so a bit distracted). I've had the…]]></description><link>https://blog.ek9.io/the-symbol-table</link><guid isPermaLink="true">https://blog.ek9.io/the-symbol-table</guid><category><![CDATA[programming languages]]></category><dc:creator><![CDATA[Steve]]></dc:creator><pubDate>Mon, 31 Oct 2022 17:37:39 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/unsplash/W8Qqn1PmQH0/upload/v1667216631854/iyKDHjeCGn.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<h1 id="heading-progress">Progress</h1>
<p>Well, it's been just over a year since my last blog post, I've been working on the Symbol Table (also changing jobs - so a bit distracted).</p>
<h2 id="heading-review-of-grammar">Review of Grammar</h2>
<p>I've had the standard ANTLR grammar reviewed and all looks good. So I progressed with the main symbol table work. All this code is all up in <a target="_blank" href="https://github.com/stephenjohnlimb/ek9">GitHub</a>.</p>
<h2 id="heading-what-is-a-symbol-table">What is a Symbol Table?</h2>
<p>What do I intend to use the <code>Symbols</code> and <code>SymbolTable</code> for exactly? Well, as source code is broken up in to <code>Tokens</code>, those <code>Tokens</code> are used by the <code>Parser</code> to match up against the grammar. In effect ANTL4 will build a 'abstract syntax tree' (AST) for me.</p>
<p>The ANTLR4 API then allows me to plug in 'visitors' and/or 'listeners'.</p>
<p>So when the AST is created by something from EK9 code like:</p>
<pre><code>...
  someIntegerValue &lt;- <span class="hljs-number">42</span>
...
</code></pre><p>Here is what the AST looks like:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1667236313108/2vzUVEFJ9.png" alt="AST2.png" /></p>
<p>This is where it starts to get interesting for me. There are 'built-in' concepts such as <code>String</code> and <code>Integer</code> for example; that the EK9 language just must 'know about'. But how does it know about them? Also, how does the compiler 'know' <strong>42</strong> is an <code>Integer</code>?</p>
<p>If you look at the AST above, you can see that the great work done in ANTR4 by <a target="_blank" href="https://en.wikipedia.org/wiki/Terence_Parr">Terence Parr</a> together with the EK9 grammar enables me to 'see' that <strong>42</strong> is an 'integerLit'. i.e. a literal of type <code>Integer</code>.</p>
<p>More importantly when a developer creates a new 'class' or 'function' then the compiler must then know about those new <em>types</em> as well.</p>
<p>This is where a symbol table comes in. Those <code>Symbols</code> are actually <em>types</em> and so need to be recoded somewhere as <em>types</em>, this is so that when we declare a variable of a particular <em>type</em>; we can <strong>resolve it</strong>.</p>
<p>So for the compiler to be able to deal with a statement as simple as <code>someIntegerValue &lt;- 42</code> I need to have defined:</p>
<ul>
<li>The grammar</li>
<li>The Lexer</li>
<li>The Parser</li>
<li>The ANTLR4 Visitor</li>
<li>A Symbol for <em>type</em> <code>Integer</code></li>
<li>A SymbolTable for EK9 where that <code>Integer</code> <em>type</em> can be recorded</li>
<li>Also a SymbolTable where the <em>variable</em> 'someIntegerValue' can be recorded and linked to its <em>type</em></li>
</ul>
<p>But as soon as I want to do something with the variable <strong> someIntegerValue</strong>, like add another integer value to it, I'll need some <em>operators</em> on the <code>Integer</code> <em>type</em>. For that I'll need the <em>type</em> <code>Integer</code> to be an <code>Aggregate</code> (with methods/operators).</p>
<h3 id="heading-boot-strapping-the-symboltable">Boot strapping the SymbolTable</h3>
<p>There is more than one <code>SymbolTable</code>, in fact there will be thousands. But there is only one main global <code>SymbolTable</code> that is part of the EK9 language. So the first job I have to do is define the concept of the <code>SymbolTable</code> and the idea of a <code>Symbol</code>.</p>
<p>The <code>SymbolTable</code> has a <code>Scope</code> this is sort of like a 'prefix' in programming terms like a 'namespace'. So it has a 'name', these names have to be unique. Like a module name for example.</p>
<p>It is within this <code>Scope</code> we need to <strong>define</strong> a <code>Symbol</code>. Now we can just keep a list of these <code>Symbols</code>. The idea that some <code>Symbols</code> may clash may depend on the type of <code>Symbol</code> being defined.</p>
<p>So for example, I've described <code>String</code> and <code>Integer</code>, clearly as types, these must be unique. But let's consider <code>Methods</code> on a <code>Class</code>; where we allow <strong>method overloading</strong>.
In that case; we would have several <code>Methods</code> (which will also be <code>Symbols</code>) with the same name, but with different parameters in the same <code>SymbolTable</code>.</p>
<p>So that's the job I'm working on at the moment, boot strapping the main EK9 <code>Symbol Table</code> with all the standard built-in <em>types</em> and then some of the main built-in <code>Functions</code> and <code>Classes</code>.</p>
<p>In my prototype compilers; I actually used Java and reflection to do this, but now I'm moving to the first reference compiler - I'll define the <code>Symbols</code> in terms of <code>Aggregates</code> in a more abstract way. Only if the final compiled output targets Java will the appropriate Java class be employed. This will allow me to target different runtimes, initially it will be Java, but I want to be able to target LLVM as well (at least).</p>
<h3 id="heading-resolving-symbols">Resolving <code>Symbols</code></h3>
<p>Once you have <code>SymbolTables</code> then next thing you need to be able to do after <strong>defining</strong> a <code>Symbol</code> is <strong>resolving</strong> a <code>Symbol</code>. But you have to bear in mind that programs tend to have nested structures. For example:</p>
<ul>
<li>Global (built-in EK9)</li>
<li>module (the developers application)</li>
<li>class</li>
<li>method</li>
<li>block</li>
</ul>
<p>So when you want to <em>resolve</em> a symbol from within the block above, it is necessary to <em>resolve</em> <code>Symbols</code> back up that nested structure; right up to the Global (building-in EK9 <em>types</em>).</p>
<h2 id="heading-summary">Summary</h2>
<p>So that's where I am at the moment, writing lots of <code>Symbols</code>, <code>Scopes</code> and many tests. I hope to get the bulk of the <code>SymbolTable</code> done this year, but it'll depend on how draining my new job is!</p>
]]></content:encoded></item><item><title><![CDATA[Syntax - the thorny issue of syntax]]></title><description><![CDATA[Why are tabs, spaces, braces and semi-colons so divisive?]]></description><link>https://blog.ek9.io/syntax-the-thorny-issue-of-syntax</link><guid isPermaLink="true">https://blog.ek9.io/syntax-the-thorny-issue-of-syntax</guid><category><![CDATA[programing]]></category><category><![CDATA[Open Source]]></category><dc:creator><![CDATA[Steve]]></dc:creator><pubDate>Sat, 23 Oct 2021 11:48:47 GMT</pubDate><content:encoded><![CDATA[<h1 id="syntax">Syntax</h1>
<h2 id="background">Background</h2>
<p>In my <a target="_blank" href="https://blog.ek9.io/constructs-do-we-need-more">previous post</a>, I made the argument for a lot more <em>constructs</em>. But this post is how all those <em>constructs</em>, <em>immutability</em> and <em>flow control</em> will be expressed in EK9.</p>
<p>It might seem strange that I've left the aspect of <em>syntax</em> until this point in this series of posts. While the <em>syntax</em> is really the first thing most developers <strong>see</strong> when they start to use a new language; underneath the <strong>DNA</strong> of the language exists in its own right.</p>
<h3 id="who-is-the-code-for">Who is the code for?</h3>
<p>The code is for the <em>developer</em> to provide functionality in the form of software for a <em>customer</em>. But there are a couple of other <em>interested parties</em> besides the <em>developer</em> and the <em>end customer</em>:</p>
<ul>
<li>The compiler -- this transforms the code in to some form of executable</li>
<li>Other developers -- unless your code is small/trivial; it will be read by other developers</li>
<li>Your future self -- you will spend quite a bit of time in the future reading code</li>
</ul>
<p>You may think the idea of <em>your future self</em> is a contrivance. But when you develop code, you get <em>deep into it</em> and lots of <em>context</em>, <em>pre-conditions</em> and <em>logic</em> seem obvious. But with the passage of time all of that fades and you are only left with the <strong>code</strong>. So that <strong>code</strong> needs to be clear.</p>
<h3 id="so-whats-needed">So what's needed?</h3>
<p>The <em>end customer</em> just wants the functionality, but they also want the developer to be able to add new features in a timely manner. They absolutely want it to <em>work</em> and <strong>don't want defects</strong>.</p>
<p>The <em>compiler</em> needs clear unambiguous code. This needs to be <em>parsed</em> so it can inform the developer if there are potential issues and to produce the final executable for the <em>end customer</em>. So we need to ensure that we provide the minimal readable syntax that enables to <em>compiler</em> to process the code.</p>
<p>The <em>developers</em> (including yourself) need:</p>
<ul>
<li>To be able to organise the code in a logical manner to aid navigation</li>
<li>To be able to quickly <strong>read</strong> and comprehend the code</li>
<li>Some degree of symmetry and consistency in the syntax</li>
<li>To type the minimal amount of text (<strong>but it must still be clear</strong>)</li>
<li>To be able to make changes without introducing defects</li>
<li>To be able to express themselves using <em>design patterns</em></li>
<li>To be able avoid obvious pitfalls and mistakes</li>
</ul>
<p>Note the above list is just for the syntax, the developers also need the <em>constructs</em> to enable them to express themselves and create <em>abstract concepts</em>. This has been covered in a <a target="_blank" href="https://blog.ek9.io/constructs-do-we-need-more">previous post</a>. <a target="_blank" href="https://blog.ek9.io/strong-typing-in-programming-languages">Strong typing</a> has also been covered and is a key part of EK9.</p>
<h2 id="developer-needs">Developer needs</h2>
<p>Focusing on the needs of the <em>developer</em> from the section above; means that we need to understand how <em>developers</em> and in a more general sense how humans comprehend written text. Only then can we get an idea of what a syntactic layout might look like. The aim is to enable the developer to write <em>idiomatic EK9</em>.</p>
<h3 id="directory-structures">Directory Structures</h3>
<p><em>Developers</em> will come up with and evolve file system directory structures when organising code; these enable software to be broken down in to related concepts or sub systems. Indeed the <em>tree</em> like structure (or <strong>directed graph</strong>) is quite a natural organisational mechanism. So EK9 will facilitate the full and free use of directory structures for files that contain EK9 code.</p>
<h3 id="file-names">File Names</h3>
<p>For source code files and files in general most developers and users of software expect a file name to end in a <strong>suffix</strong>. This <strong>suffix</strong> enables them to <em>know</em> what the content is likely to be; for example <strong>.txt, .png, .xls</strong>. So EK9 source code files will have a suffix of <strong>.ek9</strong>.</p>
<h3 id="source-file-layout">Source File Layout</h3>
<p>Most people are used to reading books with some form of internal structure; such as:</p>
<ul>
<li>Forward</li>
<li>Introduction</li>
<li>Chapters (N)</li>
<li>Conclusion</li>
</ul>
<p>Languages like C, C++, Java, C#, etc have a minimal layout; but this is mainly due to their limited range of <em>constructs</em>. This has one major disadvantage; it means that you see the words <strong>fun/function</strong> and <strong>class/interface</strong> repeated frequently.</p>
<p><a target="_blank" href="https://www.tutorialspoint.com/pascal/pascal_program_structure.htm">Pascal</a> and some other languages have a sectional layout. This approach means that if you define a <strong>functions</strong> block or a <strong>procedures</strong> block; everything in those blocks is naturally a function or a procedure. </p>
<p>As EK9 has quite a few <a target="_blank" href="https://www.ek9.io/structure.html">constructs</a> it will follow the Pascal model.
This reduces the amount of repetitive text that a developer needs to type, it provides a logic and rational structure within the EK9 source code file.</p>
<p>Here is the broad idea of that layout:</p>
<pre><code>#!ek9
defines module introduction
  references
    <span class="hljs-comment">//Multiple references to constructs</span>
  defines constant
    <span class="hljs-comment">//Multiple constants</span>
  defines type
    <span class="hljs-comment">//Multiple types</span>
  defines function
    <span class="hljs-comment">//Multiple functions</span>
  defines <span class="hljs-class"><span class="hljs-keyword">trait</span></span>
    <span class="hljs-comment">//Multiple traits</span>
  defines <span class="hljs-class"><span class="hljs-keyword">class</span></span>
    <span class="hljs-comment">//Multiple classes</span>
  defines record
    <span class="hljs-comment">//Multiple records</span>
  defines text
    <span class="hljs-comment">//Multiple text for languages</span>
  defines component
    <span class="hljs-comment">//Multiple components</span>
  defines application
    <span class="hljs-comment">//Multiple applications</span>
  defines service
    <span class="hljs-comment">//Multiple services</span>
  defines program
    <span class="hljs-comment">//Multiple programs</span>
  defines <span class="hljs-keyword">package</span>
    <span class="hljs-comment">//A package definition</span>
</code></pre><p>So the reasons for this approach are driven by the logical nature of what most humans are used to reading (<strong>books</strong>) and the desire to reduce typing (where possible, but retaining clarity). The only real downside of this approach is the fact the developer needs to <em>know the context</em>; this is not too bad with a small number of <em>construct definitions</em>. But as EK9 enables multiple files to be part of the same module it means files can be numerous and short/related.</p>
<p>This gives the developer flexibility on how to group files in directory structures and how best to group specific <em>constructs</em> within the sections in those files. So for example; the developer could elect to put all the <em>functions</em> in one file and all the <em>classes</em> in another; or they could mix and combine <em>constructs</em>.</p>
<h3 id="block-layout">Block Layout</h3>
<p>Vertical layouts can be read with ease:</p>
<ul>
<li>Column based layouts (like newspapers) -- but only to a finite degree</li>
<li>Tree/Graph layouts -- but again only to a finite degree</li>
<li>Indented code block layouts -- but only to a finite depth</li>
</ul>
<p>The key point in the bullets above is <strong>restraint</strong>. Deeply indented, excessive columns or dense tree structures <strong>will not work</strong>; moderation is essential. EK9 accomplishes this in a variety of different ways; not through hard compiler driven rules, but by creating <strong>pain</strong> and therefore encouraging <em>decomposition</em>. This further aids reuse and testing. This is <strong>pain creation is deliberate</strong>, it sounds perverse to design something that limits and frustrates; but we developers need to be encouraged in the right direction.</p>
<p>A concrete example of this is the omission of <em>direct inline lambda functions</em>. EK9 offers <a target="_blank" href="https://www.ek9.io/dynamicFunctions.html">Dynamic Functions</a> instead. These separate the definition of small dynamic functions from their use. This is a <strong>deliberate pain point</strong> aimed at encouraging structure and facilitating reuse and testing.</p>
<h4 id="visual-flow">Visual Flow</h4>
<p>We can also understand horizontal flow, such as:</p>
<ul>
<li>-&gt; -- flow into something</li>
<li>&lt;- -- flow out of something</li>
</ul>
<p>These ideas will drive the layout and syntax of EK9. This layout is quite different to many other programming languages (though there are some similarities to Python in places).</p>
<h3 id="punctuation">Punctuation</h3>
<p>OK, now it's time to bite the bullet.</p>
<p>I don't like too much punctuation in source code, I always ask myself the following questions:</p>
<ul>
<li>Why does another developer need a colon <strong>':'</strong> or a  semi-colon <strong>';'</strong>?</li>
<li>If I've indented this block of code -- why do I need the <strong>'{' '}'</strong>?</li>
<li>How can I encourage more or less use of capabilities in the appropriate context</li>
</ul>
<p>Clearly we've had a good example of this with Python/YAML. But it's not all plain sailing with white space  and the amount/type of indentations. It is possible to introduce defects that are not easy to spot.</p>
<p>But the same can be said of languages that employ semi-colons. Here's an example:</p>
<pre><code><span class="hljs-selector-tag">for</span>(int i=<span class="hljs-number">0</span>; i&lt;<span class="hljs-number">10</span>; i++);
  <span class="hljs-selector-tag">printf</span>(<span class="hljs-string">"Hello"</span>);
</code></pre><p>The use of <strong>'&lt;' '&gt;'</strong> with generics/templates in C++ and Java for example is another area that can lead to excessive punctuation.
Why not just use:</p>
<pre><code><span class="hljs-comment">//List example</span>
<span class="hljs-keyword">List</span> of <span class="hljs-keyword">String</span>
<span class="hljs-comment">//Dictionary example</span>
Dict of (<span class="hljs-keyword">Integer</span>, <span class="hljs-keyword">String</span>)
</code></pre><p>There is a place for punctuation characters as shown here for lists.</p>
<pre><code><span class="hljs-string">...</span>      
  <span class="hljs-string">aList</span> <span class="hljs-string">&lt;-</span> [ <span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>, <span class="hljs-number">4</span>, <span class="hljs-number">5</span>, <span class="hljs-number">6</span>, <span class="hljs-number">7</span>, <span class="hljs-string">Integer()</span> ]
<span class="hljs-string">...</span>
</code></pre><p>and here for dictionaries/maps:</p>
<pre><code><span class="hljs-meta">...</span>
  aDictionary &lt;- { 1: "Gomez", 2: "Morticia" }
<span class="hljs-meta">...</span>
</code></pre><p>This <a target="_blank" href="https://www.ek9.io/collectionTypes.html#list">list example</a> and <a target="_blank" href="https://www.ek9.io/collectionTypes.html#dict">dictionary example</a> give more details; the use of punctuation in definitions feels more natural. When this punctuation is used in combination with <em>type inference</em> as shown above; a very terse, simple and concise statement is created that is clear to read and requires minimal typing.</p>
<p>But the <a target="_blank" href="https://www.ek9.io/streamsAndPipelines.html">streaming pipeline</a> and <a target="_blank" href="https://www.ek9.io/operators.html">operators</a> use punctuation extensively.
Part of the Streaming Pipeline example is shown below (some functions omitted for brevity):</p>
<pre><code>...
  defines function

    filterBooksToOutput()
      -&gt;
        books <span class="hljs-keyword">as</span> List <span class="hljs-keyword">of</span> Book
        filterSelection <span class="hljs-keyword">as</span> BookFilterSelection
        output <span class="hljs-keyword">as</span> StringOutput

      authorId &lt;- getAuthorChange()  
      theBookFilter &lt;- suitableBookFilter(filterSelection)

      cat books
        | sort <span class="hljs-keyword">by</span> compareAuthor
        | split <span class="hljs-keyword">by</span> authorId
        | select <span class="hljs-keyword">with</span> sufficientBooks
        | map <span class="hljs-keyword">by</span> orderOnPublishedDate
        | map <span class="hljs-keyword">with</span> theBookFilter
        | flatten
        &gt; output
...
</code></pre><p>This should give you some idea of the look and feel of EK9 source code.</p>
<p>Indeed there are <a target="_blank" href="https://www.ek9.io/operators.html#ternary">additional operators</a> in EK9 that don't appear in most languages. EK9 has all the normal <a target="_blank" href="https://www.ek9.io/operators.html#comparison">comparison</a> operators. It also provides fuzzy comparison, null coalescing, Elvis operator and some short cuts that combine null coalescing and comparison operators.</p>
<p>Here are some examples:</p>
<pre><code>bird1 <span class="hljs-keyword">as</span> String
bird2 ← "Duck"
birdA ← bird1 ?? bird2
birdA := bird1 &lt;? bird2
birdA := bird1 &lt;=? bird2
birdA := bird1 &gt;? bird2
birdA := bird1 &gt;=? bird2
//<span class="hljs-keyword">In</span> <span class="hljs-keyword">all</span> above examples birdA would have the <span class="hljs-keyword">value</span> <span class="hljs-keyword">of</span> "Duck"
//because <span class="hljs-string">'bird1'</span> <span class="hljs-keyword">is</span> <span class="hljs-keyword">not</span> <span class="hljs-keyword">set</span> 
birdB ← bird1 ?: bird2
//birdB would <span class="hljs-keyword">also</span> have the <span class="hljs-keyword">value</span> <span class="hljs-keyword">of</span> "Duck"
//because <span class="hljs-string">'bird1'</span> <span class="hljs-keyword">is</span> <span class="hljs-keyword">not</span> <span class="hljs-keyword">set</span>

bird1 := String()
birdA := bird1 ?? bird2
//birdA would now be un <span class="hljs-keyword">set</span> <span class="hljs-keyword">and</span> <span class="hljs-keyword">not</span> have a meaningful <span class="hljs-keyword">value</span>
//because it has taken same <span class="hljs-keyword">value</span> <span class="hljs-keyword">as</span> <span class="hljs-string">'bird1'</span>
</code></pre><p>But the main point is that in EK9; the punctuation characters are used for assignments, lists, dictionaries and operators in general and not for <strong>code block</strong> definitions.</p>
<p>The range of new forms of operator, ternary expressions, type inference will probably take any developer a while to get used to. The aim of these operators is to reduce the amount of typing required and to make the code terse but readable when revisiting.</p>
<p>I've used <strong>'&lt;' and '&gt;'</strong> punctuation in combinations with other characters to facilitate the use of <em>block comments</em>. Again is is by design to encourage some forms of commenting -- but not an excessive amount.</p>
<h3 id="comments">Comments</h3>
<p>Commenting code is always a point of contention for developers. Some say <em>comment everything</em>; others say <em>comment the why not the how</em>. There is no simple answer that will keep everyone happy.</p>
<p>I'd suggest <em>comment the why</em>; but also <em>comment the how</em>, if the how does not look obvious.</p>
<p>EK9 offers several different type of comments.</p>
<pre><code>//A Simple single line <span class="hljs-keyword">comment</span>
<span class="hljs-keyword">name</span> &lt;- <span class="hljs-string">"Steve"</span> //Can <span class="hljs-keyword">comment</span> <span class="hljs-keyword">end</span> <span class="hljs-keyword">of</span> line <span class="hljs-keyword">as</span> well
&lt;!-
<span class="hljs-keyword">Or</span> a <span class="hljs-keyword">block</span> <span class="hljs-keyword">comment</span>
<span class="hljs-keyword">Over</span> multiple <span class="hljs-keyword">lines</span>
-!&gt;

defines <span class="hljs-keyword">function</span>
  &lt;?-
  This <span class="hljs-keyword">is</span> an explicit documentation comment.
  -?&gt;
  function1()
    -&gt; n <span class="hljs-built_in">Integer</span>
    &lt;- <span class="hljs-keyword">sum</span> <span class="hljs-built_in">Integer</span>: <span class="hljs-number">0</span>
    ...
</code></pre><p>EK9 does <strong>not</strong> offer <code>/* type block comments */</code> nor Java style <code>/** Doc comments */</code>.</p>
<h2 id="parameter-declarations">Parameter declarations</h2>
<p>Declaring <em>functions</em> and <em>methods</em> that accept incoming parameters is significant in terms of design. The developer is defining an <strong>interface</strong> that will be used. By combining the ideas from the block layout above; EK9 provides quite a unique and clear way to declare incoming and returning parameters.</p>
<pre><code><span class="hljs-comment">#!ek9</span>
<span class="hljs-string">defines</span> <span class="hljs-string">module</span> <span class="hljs-string">introduction</span>
  <span class="hljs-string">defines</span> <span class="hljs-string">function</span>

    <span class="hljs-string">function1()</span>
      <span class="hljs-string">-&gt;</span> <span class="hljs-string">n</span> <span class="hljs-string">Integer</span>
      <span class="hljs-string">&lt;-</span> <span class="hljs-attr">sum Integer:</span> <span class="hljs-number">0</span>      
      <span class="hljs-string">...</span>

    <span class="hljs-string">function2()</span>
      <span class="hljs-string">-&gt;</span>
        <span class="hljs-string">n1</span> <span class="hljs-string">Integer</span>
        <span class="hljs-string">n2</span> <span class="hljs-string">Integer</span>
      <span class="hljs-string">&lt;-</span>
        <span class="hljs-attr">sum Integer:</span> <span class="hljs-number">0</span>
      <span class="hljs-string">...</span>
<span class="hljs-string">//EOF</span>
</code></pre><p>So data being passed into the function is demarked by using <strong>-&gt;</strong> and data being returned is demarked by using <strong>&lt;-</strong>. For multiple parameters there is also an indentation block.</p>
<p>This mechanism creates <em>tree/graph</em>, <em>column</em> structures but also indicates <em>flow</em>. It encourages single parameters; in general fewer parameters is a <strong>cleaner design</strong>.</p>
<p>Source code text is not <em>densely packed</em> and <a target="_blank" href="https://medium.com/successivetech/importance-of-whitespace-in-good-design-de03ea0ab4db">white space</a> is created.
UI designers and web developers spend a significant amount of time designing white space, they do this with good reason. EK9 uses this same approach but in software source code.</p>
<p>This does make the source code files longer and much less dense. This is by design, this encourages the developer to break source files up.</p>
<p>It is easy to <strong>glance</strong> at a block of code and just <strong>see</strong> the flow in and out with parameter names/types. It also limits the length of each line, ideally source code line length should be 80-120 characters. This is <strong>not</strong> driven by terminal width, font size nor any other technology capability; it is purely to do with how humans comprehend text.</p>
<p>It is not a hard and fast rule, but the EK9 syntax structure encourages a general move to shorter lines in a more column based format. Here is a short example (streaming pipelines):</p>
<pre><code><span class="hljs-meta">...</span>
cat books
  | sort by compareAuthor
  | split by authorId
  | select with sufficientBooks
  | map by orderOnPublishedDate
  | flatten
  &gt; stdout
<span class="hljs-meta">...</span>
</code></pre><p>This could have all been done on a single line, but it just much easier to see at a <strong>glance</strong> when in a column format as above.</p>
<h3 id="end-of-line">End of Line</h3>
<p>EK9 does not use the <a target="_blank" href="https://www.ek9.io/basics.html#line_termination">semi-colon</a> <strong>';'</strong> at all. It is not even used as an end of line marker.</p>
<h3 id="variable-declarations-and-assignments">Variable Declarations and Assignments</h3>
<p><a target="_blank" href="https://www.ek9.io/basics.html#declarations">Variable declarations</a> and <a target="_blank" href="https://www.ek9.io/operators.html#assignment">variable assignments</a> have a number forms. These are designed to provide the developer with a number of natural and simple <strong>syntactic</strong> symbols that are familiar from other languages. But importantly they provide a mechanism in EK9 for <em>type inference</em> and also provide a very terse way to work with variables.</p>
<p>Here are some examples:</p>
<pre><code>age <span class="hljs-keyword">as</span> <span class="hljs-type">Integer</span>: <span class="hljs-type">Integer</span>()
age <span class="hljs-keyword">as</span> <span class="hljs-type">Integer</span> = <span class="hljs-type">Integer</span>()
age <span class="hljs-keyword">as</span> <span class="hljs-type">Integer</span> := <span class="hljs-type">Integer</span>()
age <span class="hljs-keyword">as</span> <span class="hljs-type">Integer</span> := <span class="hljs-number">21</span>
age &lt;- <span class="hljs-number">21</span>
</code></pre><p>The first few lines declare a variable as an Integer but of an unknown value. The final example shows the most terse mechanism (this uses <em>type inference</em>). This <em>type inference</em> can be used with any <em>type</em> including your own <em>type definitions, classes, traits, components</em> and <em>functions</em>. For more details see <a target="_blank" href="https://www.ek9.io/basics.html#type_inference">type inference</a>.</p>
<p>Initially I didn't like this <em>type inference</em> syntax, but over time it grew on me more and more (when I say time I'm talking years here). Now I look at it and it seems so concise, terse and elegant; it's really about the shortest amount of code you could write.</p>
<p>It has an interesting side effect (which was not planned); it encourages the declaration of new variables in preference to re(mis)-using existing variables. When designing <a target="_blank" href="https://www.ek9.io/basics.html#pure">pure</a> code that is <a target="_blank" href="https://blog.ek9.io/immutability-why-is-it-hard">immutable</a>, this; in conjunction with <a target="_blank" href="https://www.ek9.io/operators.html#ternary">ternary</a> operators enables very succinct code to be written. </p>
<h3 id="flow-control">Flow Control</h3>
<p>The <a target="_blank" href="https://www.ek9.io/flowControl.html#if_elseif_else">if/else</a> and <a target="_blank" href="https://www.ek9.io/flowControl.html#switch">switch</a> syntax is pretty much what you'd expect; nothing too radical. Though there are alternate syntaxes available, guarded assignments and <em>switches</em> can return values. So there are some innovations, but several other languages already have these.</p>
<p>Here is a show example of an <strong>if</strong> statement:</p>
<pre><code>...
  defines program
    simpleIf()
      stdout &lt;- Stdout()
      valueToTest &lt;- <span class="hljs-number">9</span>

      <span class="hljs-keyword">if</span> valueToTest &lt; <span class="hljs-number">10</span>
        stdout.<span class="hljs-built_in">println</span>(<span class="hljs-string">`Value ${valueToTest} is less than 10`</span>)

      <span class="hljs-comment">//Rather than use the keyword 'if' you can use 'when'</span>
      <span class="hljs-comment">//Also you could just use string concatenation</span>
      when valueToTest &lt; <span class="hljs-number">10</span>
        stdout.<span class="hljs-built_in">println</span>(<span class="hljs-string">"Value "</span> + $valueToTest + <span class="hljs-string">" is less than 10"</span>)
...
</code></pre><p>The <a target="_blank" href="https://www.ek9.io/flowControl.html#for_loop">for loop</a> takes a few ideas from other languages; but is less like C, C++, C#, Java, Javascript. It is more like Pascal and ADA.</p>
<p>Importantly the <strong>loop variable</strong>s <em>type</em> is inferred and the value of the <strong>loop variable</strong> is in effect <em>immutable</em> as far as the developer is concerned. This means the developer cannot alter the <strong>loop variable</strong>.</p>
<p>Here is an example (it uses time of day and durations in the loop):</p>
<pre><code><span class="hljs-attribute">timeForLoop</span>()
  <span class="hljs-attribute">stdout</span> &lt;- Stdout()
  <span class="hljs-attribute">startOfWorkDay</span> &lt;- Time().startOfDay() + PT<span class="hljs-number">9</span>H
  <span class="hljs-attribute">endOfWorkDay</span> &lt;- Time().endOfDay() - PT<span class="hljs-number">6</span>H<span class="hljs-number">30</span>M
  <span class="hljs-attribute">thirtyMinutes</span> &lt;- PT<span class="hljs-number">30</span>M

  <span class="hljs-attribute">for</span> theTime in startOfWorkDay ... endOfWorkDay by thirtyMinutes
    <span class="hljs-attribute">stdout</span>.println(`Value <span class="hljs-variable">${theTime}</span>`)
</code></pre><p>It can also take this form with collections and iterators:</p>
<pre><code><span class="hljs-selector-tag">for</span> <span class="hljs-selector-tag">item</span> <span class="hljs-selector-tag">in</span> <span class="hljs-selector-attr">[<span class="hljs-string">"Alpha"</span>, <span class="hljs-string">"Beta"</span>, <span class="hljs-string">"Charlie"</span>]</span>
  <span class="hljs-selector-tag">stdout</span><span class="hljs-selector-class">.println</span>(<span class="hljs-selector-tag">item</span>)
</code></pre><p>And this form with Stream pipelines:</p>
<pre><code>defines <span class="hljs-function"><span class="hljs-keyword">function</span>
  <span class="hljs-title">workHours</span>(<span class="hljs-params"></span>)
    -&gt; <span class="hljs-title">time</span> <span class="hljs-title">as</span> <span class="hljs-title">Time</span>
    &lt;- <span class="hljs-title">workTime</span> <span class="hljs-title">as</span> <span class="hljs-title">Boolean</span>: <span class="hljs-title">time</span> &lt; 12:00 <span class="hljs-title">or</span> <span class="hljs-title">time</span> &gt; 14:00

  <span class="hljs-title">timePipeLine</span>(<span class="hljs-params"></span>)
    <span class="hljs-title">stdout</span> &lt;- <span class="hljs-title">Stdout</span>(<span class="hljs-params"></span>)

    <span class="hljs-title">start</span> &lt;- <span class="hljs-title">Time</span>(<span class="hljs-params"></span>).<span class="hljs-title">startOfDay</span>(<span class="hljs-params"></span>) + <span class="hljs-title">PT9H</span>
    <span class="hljs-title">end</span> &lt;- <span class="hljs-title">Time</span>(<span class="hljs-params"></span>).<span class="hljs-title">endOfDay</span>(<span class="hljs-params"></span>) - <span class="hljs-title">PT6H30M</span>

    <span class="hljs-title">for</span> <span class="hljs-title">i</span> <span class="hljs-title">in</span> <span class="hljs-title">start</span> ... <span class="hljs-title">end</span> <span class="hljs-title">by</span> <span class="hljs-title">PT30M</span> | <span class="hljs-title">filter</span> <span class="hljs-title">by</span> <span class="hljs-title">workHours</span> &gt; <span class="hljs-title">stdout</span></span>
</code></pre><p>Hopefully you can now start to see how the EK9 syntax has been formed and how readable/expressive it can be. With the introduction of  <a target="_blank" href="https://www.ek9.io/streamsAndPipelines.html">streaming pipelines</a>, EK9 promotes a more functional approach. This further encourages <em>steps</em> in processing that can be expressed in a <strong>column</strong> layout when the steps are numerous; this aids readability.</p>
<h2 id="summary">Summary</h2>
<p>Superficially EK9 looks a little like Python. Whilst the <em>block</em> notation does use indentation; there are few other similarities.</p>
<p>I challenged the need for every character whilst developing the EK9 syntax. I followed the layout design from Pascal to reduce <strong>fun/function, class</strong> text by using a <em>sectional</em> structure.</p>
<p>The introduction of a range of new null safe (<strong>is set</strong>) operators that act more like <a target="_blank" href="https://www.ek9.io/operators.html#ternary">ternary operators</a> enable a reduction of <strong>if/else</strong> statements.</p>
<p>EK9 is <strong>strongly typed</strong> and <em>compiled</em>. The EK9 syntax has been created and developed with:</p>
<ul>
<li>Vertical structures -- like paragraphs and sections</li>
<li>Tree structures -- like directories</li>
<li>Horizontal structures -- like newspaper columns</li>
<li>Horizontal flow -- across the page</li>
<li>Minimal text -- that still permits easy comprehension</li>
<li>Concepts and ideas from a range of other languages</li>
<li>Limited punctuation for <strong>code block</strong> structures</li>
<li>Additional operators to reduce code further</li>
</ul>
<p>The final syntax is not one I was expecting; as my background is in C, C++ and Java. In some ways the EK9 syntax even feels <strong>alien</strong> to me!</p>
<p>The definition of the <a target="_blank" href="https://github.com/stephenjohnlimb/ek9/tree/main/src/main/antlr4/org/ek9lang/antlr">EK9 language</a>  is in the form of an ANTLR4 grammar.</p>
<h3 id="braces-and-indentation">Braces and Indentation</h3>
<p>I've not really answered the question: <em>'Why are tabs, spaces, braces and semi-colons so divisive?'</em>. I don't really have an answer I'm afraid. Having used a range of languages including C and Python I'm surprised the <strong>strong</strong> reaction people have to a few characters. Though I have to confess to an aversion to punctuation in block structures myself.</p>
<p>I've been driven by how I best understand code and its layout. I've tried to find some patterns to see if I could come up with a direction; and to tried to be consistent.</p>
<h3 id="next-steps">Next Steps</h3>
<p>The next series of posts will cover the building of the <strong>compiler</strong>. Importantly this <strong>compiler</strong> will be driven through the development of a <em>Language Server</em> for VSCode. The VSCode extension has already been developed and is available on <a target="_blank" href="https://github.com/stephenjohnlimb/vscode-ek9-ls">github</a>.</p>
<p>As the grammar for EK9 has been defined in ANTL4, much of the lexing/parsing hard work has been done for me (I'm not going to cover lexing and parsing as there is plenty of material available on that already).</p>
<p>Special thanks to <a target="_blank" href="https://parrt.cs.usfca.edu">Terrence Parr</a> for providing ANTLR it has made a big difference when experimenting with grammars and structures.</p>
<p>So much of the next post will cover the development of the <em>Symbol Table</em>.</p>
]]></content:encoded></item><item><title><![CDATA[Constructs - do we need more?]]></title><description><![CDATA[Functions and Classes just aren't enough]]></description><link>https://blog.ek9.io/constructs-do-we-need-more</link><guid isPermaLink="true">https://blog.ek9.io/constructs-do-we-need-more</guid><category><![CDATA[programing]]></category><category><![CDATA[Open Source]]></category><category><![CDATA[programming languages]]></category><dc:creator><![CDATA[Steve]]></dc:creator><pubDate>Tue, 12 Oct 2021 22:07:16 GMT</pubDate><content:encoded><![CDATA[<h2 id="background">Background</h2>
<p>In my <a target="_blank" href="https://blog.ek9.io/immutability-why-is-it-hard">previous post</a> I covered immutability and touched on the first <em>construct</em>; the <a target="_blank" href="https://www.ek9.io/constants.html">constant</a>.</p>
<p>EK9 also has <a target="_blank" href="https://www.ek9.io/functions.html">functions</a>, <a target="_blank" href="https://www.ek9.io/dynamicFunctions.html">dynamic functions</a>, <a target="_blank" href="https://www.ek9.io/classes.html">classes</a>,
<a target="_blank" href="https://www.ek9.io/dynamicClasses.html">dynamic classes</a> and <a target="_blank" href="https://www.ek9.io/traits.html">interfaces/traits</a>. These are all unsurprising as they are presented in most languages. But in EK9 <strong>functions</strong> and <strong>classes</strong> are equal <em>constructs</em> much like they are in <strong>C++</strong>.</p>
<p>But are <strong>constants, functions</strong> and <strong>classes</strong> enough?</p>
<h2 id="apis-frameworks-pre-processors">APIs - Frameworks - Pre-processors</h2>
<p>Let's take a quick look at what developers actually use more widely beyond just the programming language of choice.</p>
<p>It's pretty obvious what an <em>API</em> or <em>library</em> is. It is some form of prebuilt functionality that you as the developer decide to call. The developer is in the driving seat -- so to speak.</p>
<p>The <em>framework</em> is also fairly easy to understand. In this case the developer creates some piece of functionality and <em>registers</em> it via some existing software through an <em>API</em>, <em>library</em> or configuration file. But here is the twist, the <em>framework</em> does the actual calling of the developers code. So the <em>framework</em> is in the driving seat of making the call (yes the developer did configure when to make the call - but the framework does the calling).</p>
<p>So what about <em>pre-processors</em> like those for <em>sass</em>, <em>svelte</em>, etc. Indeed what about <em>post-processors</em> for slimming down the final sets of artefacts, packaging etc.</p>
<p>Now these <em>processors</em> take code to output in one format and transform it, in some cases they are a quite <em>simple</em> but in others they are more like a <em>compiler</em>.</p>
<p>But in general they all push the final use/checks/assembly to <em>runtime</em>.</p>
<h3 id="front-end">Front-end</h3>
<p>While most (but not all) back-end development has long had <em>compile and packaging</em> technology in various forms (<em>dll, so, lib, jar</em> etc), the front-end has generally made the most of its agility. By this I mean just straight forward text files that a browser engine uses (HTML, Javascript and CSS). Simple, clean (without too much complexity in the tool chain). For many years this was the way to deliver an application via the internet to clients/customers (for some; it still is).</p>
<p>But now the front-end has almost moved into being <em>compiled</em>. Initially through the use of <em>pre-processors</em>, but now more frameworks are adding in specifics that require <em>pre-processing</em>. More importantly the resulting artefacts require (<em>post-processing</em> and <em>packaging</em>).</p>
<p><strong>Why?</strong></p>
<p>Evolution; the fact that the delivery mechanism of <em>HTML, Javascript and CSS</em> is being treated more like assembly code. Web App developers are looking for more of a <em>component model</em> rather than a <em>page layout model</em>. Developers want to make reusable components they can compose on to a page.
But importantly they want to componentise not just the dynamic visual content, but the behaviour and the presentation. They want <em>Object Orientation</em>; but more than just pulling/merging/copying a number of separate files together.</p>
<p>Web Applications are becoming more like <strong>thick clients</strong> of old, it is just that the browser is the deployment mechanism. Newer Web Applications are tending to <em>thin out</em> the back-end and put more and more logic in the front-end.</p>
<p>Will this trend end? There was a reason the <strong>N-tier</strong> architecture evolved. Thicker client solutions come with a range of benefits but also a range of drawbacks.</p>
<p>With more of a component model; <strong>CSS</strong> becomes an issue, because it was designed to work with a <em>page layout model</em> not really a <em>component model</em>. This is designed right into <strong>CSS</strong> it has a very strong mechanism to be able to address elements via the structure of a page. It also has the <strong>.class</strong> mechanism to short cut all that.</p>
<p>This then causes alternate <strong>CSS</strong> approaches to be adopted (like <em>tailwind</em> for example). When you think about it; it is the whole <em>page</em> the user sees. So there are some aspects of styling that could be at a component level; but there is a significant amount that should be at the whole page/site level.</p>
<p>It's quite obvious that moving from just pure <strong>HTML</strong> with <a target="_blank" href="https://en.wikipedia.org/wiki/Unobtrusive_JavaScript">unobtrusive Javascript</a> and <strong>CSS</strong> with a page layout focus; to a <em>component model</em>, that is primarily driven through Javascript frameworks; is a very big shift in approach!</p>
<p>Why have I discussed these different approaches? The main reason is to highlight evolution and the constant struggle to find a viable solution to specific problems.</p>
<p>Will the Javascript framework pull more and more into the browser; is this desirable? What are the implications/benefits/drawbacks?</p>
<p>The most interesting thing here for me is the adoption of an <em>Object Oriented Approach</em> to UI delivery to the browser. But several of these new frameworks have lost the <em>separation of concerns</em> when it comes to mixing object structure, markup and <em>CSS</em> presentation.</p>
<p>So while gaining some <em>componentisation</em> functionality, the separation between the <em>HTML</em> markup and code and the further separation of <strong>look</strong> via <strong>CSS</strong> has been sacrificed to some extent. </p>
<p>It is interesting to note that <a target="_blank" href="https://wicket.apache.org/start/quickstart.html">Apache Wicket</a> (which dates back to 2005) has a sort of <em>OO</em> approach with a separation between <em>HTML</em> and <em>Java</em> but is server side rendering (with Ajax hooks).</p>
<h3 id="back-end">Back-end</h3>
<p>Evolution is not restricted to the front-end; the back-end has also undergone some change. If we focus on <em>Java</em> and <em>Spring</em> for a moment; it becomes quite clear that a sort of 'meta-language' of <strong>Component, Service, Config, etc</strong> has; in effect, created another language. This is in stark contradiction to what <em>Spring</em> set out to do. Originally its aim was to be unobtrusive and <em>wire</em> together Objects through configuration files.</p>
<p>But I digress, the main point of <em>Spring</em> and any IOC/DI framework is to add capability that is missing from the programming language itself.
You can make the argument <strong>that's what Annotations are for</strong>, but you are building a framework and additional syntax/semantics that are not really compile time safe. It is only at runtime you actually find out if your <em>wiring</em> was right or not. Those <strong>Annotations</strong> are also very specific to the API/Framework.</p>
<p>You see this same sort of <strong>Annotation</strong> driven approach in frameworks like <em>Spring WebServices</em>.</p>
<h2 id="different-roles">Different Roles</h2>
<p>What appears to have happened since the 1960's that different sorts of <em>patterns/constructs</em> have just naturally evolved out of different programming languages when they have been applied to specific problems. During the late 1980's the new construct of the <em>class</em> emerged. Further innovations occur in the 1990's with <em>markup</em> (specifically HTML). This is followed quite quickly by the pattern of <em>separation of concerns</em> with respect to <em>markup</em> and how/where that <em>marked up content</em> is presented (<strong>CSS</strong>). We also see a move to <em>virtual machines</em> with Java (though the <a target="_blank" href="https://en.wikipedia.org/wiki/UCSD_Pascal">USDC p-system</a> and others pre-dates this). Innovation continues with <em>markup</em> in the form of <em>JSON</em> and the <em>Semantic Web</em>.</p>
<p>In general we can see languages like <strong>Smalltalk</strong>, <strong>Haskell</strong>, <strong>Erlang</strong>, <strong>Lisp</strong> for example have some following in certain domains; but remain somewhat niche. But concepts and ideas from those languages <em>leak out</em> and get incorporated into <em>design patterns</em> or other languages over time.</p>
<h3 id="summary">Summary</h3>
<p>You may think that the above <em>history</em> and summaries of front-end and back-end are just ramblings. But there is a common theme in all of them; the choice of programming language has not allowed a developer to solve a problem without significant additional APIs, Frameworks and Processors.</p>
<p>In some cases the <em>constructs</em> are constraints of simple types but in others they are <em>Aggregates</em> used in conjunction with a <em>design pattern</em> or <em>role</em>.</p>
<p>Additionally; certain technologies such as Browsers, Java and C# have provided mechanisms that enable developers to mitigate omissions of <em>constructs</em> in programming languages.</p>
<p>I'll give some examples to try and make this a little clearer.</p>
<h3 id="enumerations">Enumerations</h3>
<p>An <a target="_blank" href="https://en.wikipedia.org/wiki/Enumerated_type">enumerated</a> type is normally based on some simple primitive type (an Integer for example). But this construct was not always <strong>baked in</strong>. The original K&amp;R <strong>C</strong> language did not have enumerations. They sort of evolved out over time, most languages (but not all) now support <strong>Enumerations</strong>.</p>
<p>But why are they needed? What purpose to they perform? Won't just a finite set of <em>ints</em> just do the job just as well?</p>
<p>No, not really; if you want <strong>strong typing</strong>. This is really what an enumeration is giving you; <strong>strong typing</strong>. It's noticeable that languages like Javascript and Python are a little late to the <em>enumeration game</em> -- these languages don't tend to be associated with <strong>strong typing</strong>.</p>
<p><a target="_blank" href="https://www.ek9.io/enumerations.html">EK9 has enumerations</a>.</p>
<h3 id="simple-constraints">Simple Constraints</h3>
<p>So really an enumeration boils down to some sort of <em>constraint</em> on a primitive type when it comes to delivering <strong>Enumerations</strong>.</p>
<p><a target="_blank" href="https://www.adaic.org/resources/add_content/docs/craft/html/ch05.htm">ADA</a> has the idea of subtypes/derived types. This again is a form of <strong>strong typing</strong>.</p>
<p>Why would these be useful in a program? They could be used to represent minimum and maximum values for a person age for example. Defining a <em>constraint</em> on Integer to be greater than 16 and less than 91 for some business reason.</p>
<p>The main benefit of this is type safety, but also it is possible to have an <strong>operator</strong> of <strong>++</strong> on a variable and accidentally transition over a boundary. When this boundary is transited an exception could be thrown or the value could just become undefined. </p>
<p>EK9 has <a target="_blank" href="https://www.ek9.io/components.html">constrained types</a>; specifically look at <strong> EmployeeId</strong> and <strong>Name</strong> in the example code. These provide <strong>strong typing</strong>. The <em>Tag Cloud</em> shown on the link above also highlights the value of strong typing. It helps to quickly convey meaning.</p>
<h3 id="classes">Classes</h3>
<p>Classes sort of evolved out of <em>structs</em> with <em>function pointers</em> attached to them, then became a solution for <em>reuse</em> through inheritance.</p>
<h3 id="interfacestraits">Interfaces/traits</h3>
<p>These programming concepts evolved out of <em>abstract classes</em> and enabled developers to create different polymorphic views of the same object but in a type safe way.</p>
<h3 id="dtos">DTO's</h3>
<p>In general quite a few programs are written using <em>data transfer objects</em>, in <strong>C/C++/C#</strong> these would be called <em>structs</em>. Other languages call them <strong>records</strong>.
EK9 uses the term <a target="_blank" href="https://www.ek9.io/records.html">record</a>.
In EK9 these have constructors, public fields and optional <strong>operators</strong>. Their main purpose is to be a <em>data transfer object</em>.</p>
<p>The Java programming language has now also evolved to include <em>records</em>. So this is another concrete example of how languages move and evolve different <em>constructs</em> over time.</p>
<p>But this is also quite significant and many Object Oriented theorists would decry these <em>records</em> as <strong>anaemic classes</strong>. Again this is an example of how patterns/trends and accepted ways of working change over time (I'll skip the <strong>Singleton</strong> debacle).</p>
<h3 id="internationalisation">Internationalisation</h3>
<p>Most languages provide APIs for internationalisation and managing of localisation of messages for the end user. But EK9 takes this important area one step further by providing a <a target="_blank" href="https://www.ek9.io/textProperties.html">text</a> <em>construct</em> explicitly designed to deal with internationalisation and localisation. It does also provide API calls in the form of a <a target="_blank" href="https://www.ek9.io/builtInTypes.html#locale">Locale</a>.</p>
<p>But the <a target="_blank" href="https://www.ek9.io/textProperties.html">text</a> <em>construct</em> has been designed to:</p>
<ul>
<li>Deal with small or large amounts of text</li>
<li>Be component driven</li>
<li>Be parametrisable with strong typing</li>
<li>Provide compiler support for missing messages</li>
<li>Be flexible in the number and size of files that contain application text</li>
</ul>
<p>You may consider this a little excessive, but if you have ever developed a large component based application for multiple spoken languages you'll immediately see the value and need for this <em>construct</em>.</p>
<h3 id="ioc-and-di">IOC and DI</h3>
<p>Inversion of Control and Dependency Injection are two mechanism used widely in development. But in general they are provided through some form of <em>meta language</em> or <em>external configuration</em> mechanism. <a target="_blank" href="https://docs.spring.io/spring-framework/docs/3.2.x/spring-framework-reference/html/overview.html">Spring</a> is an example of this.
EK9 is no where near as comprehensive as <em>Spring</em> it has been designed <strong>not to be</strong>. It bakes IOC and DI right into the language; through the use of <a target="_blank" href="https://www.ek9.io/components.html">Applications/Components</a> and <a target="_blank" href="https://www.ek9.io/dependencyInjection.html">Dependency Injection</a>.</p>
<p>Both IOC and DI can be very useful, but can also lead to massive complexity. EK9 looks to cut through the excesses and provide a minimal but valuable <em>construct</em> to support this design technique.</p>
<p>But what should we apply IOC/DI and Aspect to? In EK9 you can <strong>only</strong> apply them to <a target="_blank" href="https://www.ek9.io/components.html">components</a>.</p>
<p><strong>Why</strong></p>
<p>Because that is the most appropriate <em>level</em> to apply them. If you can apply them to <em>Classes</em> then IOC/DI is abused and the code base becomes too interlinked through excessive injection. In short it's just too easy.</p>
<p>By ensuring only <em>components</em> can be injected, it is possible to ensure a more appropriate layering of code.</p>
<h3 id="aspects">Aspects</h3>
<p>Through the use of IOC and DI EK9 also includes a minimal <em>aspect oriented mechanism</em> for cross cutting concerns. Many theorists now avoid <em>aspect oriented programming</em> stating that it is <strong>brittle</strong>, buggy or limits refactoring.</p>
<p>EK9 has deliberately <em>limited</em> the excesses of <em>AOP</em>, in EK9 there is no matching methods by name or anything like that. It's an all or nothing thing on a <em>component</em>.  </p>
<h3 id="streaming">Streaming</h3>
<p>While not strictly a <em>construct</em> in the traditional sense; EK9 pulls away from the object oriented approach of streaming and pipelining through <em>fluent interfaces</em> or <em>method chaining</em>. It firmly moves in the direction of <em>functional programming</em> and provides <a target="_blank" href="https://www.ek9.io/streamsAndPipelines.html">Pipelines</a>.</p>
<p>If you are familiar with Unix pipes and pipeline processing then this is for you; but in a programming language.</p>
<p>You may ask; why create more syntax and <em>constructs</em> for something that can be delivered via <strong>Classes/Objects</strong>? The main reasons are simple syntax, semantics and consistency. The concept of streaming <em>objects/data/functions</em> through a processing pipeline is significant and compelling. The only reason languages such as Java/C# employ objects and a fluent interface is because that's all they have available.</p>
<p><a target="_blank" href="https://www.ek9.io/streamsAndPipelines.html">EK9 Pipelines</a> provide and very clear, concise and elegant natural <em>construct</em> for developers.</p>
<h3 id="web-services">Web Services</h3>
<p>As mentioned previously <em>Spring WebServices</em> employs <strong>Annotations</strong> for implementation of web services. Many other languages have frameworks that support web services. But <a target="_blank" href="https://www.ek9.io/webServices.html">EK9 Web services</a> bake this essential <em>construct</em> right into the language. This <strong>service</strong> <em>construct</em> dovetails with the <strong>text</strong> <em>construct</em>.</p>
<p>Like <strong>TCP</strong>; the <strong>HTTP</strong> protocol is here to stay. It is now very unlikely it will be replaced by anything else. It may evolve and change but unlike some technologies (<em>RMI</em> and <em>CORBA</em> for example), <strong>HTTP</strong> is here to stay in the mainstream.</p>
<p>As such EK9 builds it right into the language as a powerful <em>construct</em>.</p>
<h3 id="packaging">Packaging</h3>
<p>The last <em>construct</em> EK9 introduces is <a target="_blank" href="https://www.ek9.io/packaging.html">packaging</a>. You may think that final packaging, versioning and releasing of software should be external to the language. After all most languages don't include packaging but depend on tools like <strong>npm, ant, ivy, maven, cradle, make, imake, cmake, pip</strong> etc, etc).</p>
<p>Here lies the problem if we're honest. Why so many package managers and why does each language tend to add at least one new one?</p>
<p>In general it's because each language has features/limits/constraints that require a different approach. Unfortunately all these package managers then invent their own specific package syntax and file format!</p>
<p>So let's just accept that as a new language EK9 will probably need some type of package manager mechanism and rather than use an external format - just build it into the language itself.</p>
<p>Tools like <em>make</em> start off simple, but building software is now so much more than simple steps from taking source -&gt; object -&gt; binaries.
Dependency management, packaging, publishing and version management are now critical aspects in software development.</p>
<p>The <a target="_blank" href="https://www.ek9.io/commandline.html">EK9 command line tool</a> has a very wide range of options and lots of functionality to be able to support:</p>
<ul>
<li>Dependency Resolution</li>
<li>Package Management</li>
<li>Compilation</li>
<li>Versioning</li>
<li>Packaging</li>
<li>Publishing</li>
<li>Execution</li>
</ul>
<h2 id="summary">Summary</h2>
<p>EK9 has gone from a couple of simple <em>constructs</em> and included a wide range of additional ideas. You may consider this is going too far; take a look at the <a target="_blank" href="https://www.ek9.io/index.html#examples">example</a>, you might see the ideas fit quite well together.</p>
<p>These conclusions I'm drawing here may well be <strong>wrong</strong>. But I have to wonder why we have some many different <em>frameworks</em>, <em>APIs</em> and <em>build tools</em> if our programming languages are complete.</p>
<p>When I look at most new <em>programming languages</em> such as <strong>Golang, Rust, Dart, Kotlin, Swift, etc</strong>; I see improvements here and there; but no real radical shift or innovation. I don't intend this to be a criticism, they each address the target issues they are attempting to resolve.</p>
<p>I'm attempting to resolve the target issue I think exist (maybe only I think these are real issues to be addressed).</p>
<p>Importantly, when getting started with EK9 you only really need to use a handful of these different <em>constructs</em>, but you can employ more of them as you progress.</p>
<p>There are quite a few <a target="_blank" href="https://www.ek9.io/index.html#examples">examples</a> for you to look at to get a feel of the language. These range from very simple to complete applications.</p>
<h3 id="a-different-approach">A different approach</h3>
<p>In the next post I'll cover the syntax of EK9 and why it was adopted.</p>
<p>Superficially EK9 syntax looks very similar to Python rather than C, C++, C#, Java, Dart, Kotlin, Go, Rust or Swift. This is not due to my Python background (my background is C, C++ and Java). But my aversion to <em>punctuation</em> and slight dyslexia make it much easier for me to read a sort of Python syntax.</p>
<p>Why not just use Python then?  There are some flaws in its approach and its lack of <strong>strong typing</strong> means I find it useful for small utilities, but not for full large scale application development.</p>
<p>So I have attempted to merge aspects of many languages into one I like. You may consider this egocentric. I can understand you might think that.</p>
<p>When creating something you like yourself; it maybe that <strong>only</strong> you like it; that's fine by me. But I'm hoping a few other people will see value and utility in this new language.</p>
<p>So next post is all about syntax. It will probably look quite strange to you at first. But I've looked at quite a few theoretical papers on how humans comprehend text via layout. I have attempted to fold some of those ideas into the layout and structure.</p>
]]></content:encoded></item><item><title><![CDATA[Immutability - why is it hard?]]></title><description><![CDATA[Immutability; const doesn't cut it]]></description><link>https://blog.ek9.io/immutability-why-is-it-hard</link><guid isPermaLink="true">https://blog.ek9.io/immutability-why-is-it-hard</guid><category><![CDATA[Computer Science]]></category><category><![CDATA[Functional Programming]]></category><category><![CDATA[General Programming]]></category><dc:creator><![CDATA[Steve]]></dc:creator><pubDate>Sat, 02 Oct 2021 08:16:30 GMT</pubDate><content:encoded><![CDATA[<h2 id="background">Background</h2>
<p>In my <a target="_blank" href="https://blog.ek9.io/flow-control-why-no-early-returns">previous post</a> I dealt with flow control and mentioned immutability.</p>
<p>But why is immutability desirable at all? Why, as developers would we not want to alter/mutate/change variables? After all we need to be able to calculate results and modify data all the time; why restrict ourselves?</p>
<p>Developers restrict themselves all the time. With <strong>public, protected</strong> and <strong>private</strong> modifiers; <strong>abstract</strong>, <strong>interfaces/traits</strong> and polymorphic mechanisms. Information hiding and other abstractions are also a form of self imposed constraint.</p>
<h3 id="constraints-and-restrictions">Constraints and Restrictions</h3>
<p>We  know in the longer term it is safer to use these mechanisms above. The idea of many <strong>functions</strong> having unrestricted access to some <strong>global data</strong> and modifying it in a free and easy manner has been shown to create errors.</p>
<p>Being assured that some item of data/object cannot undergo any sort of mutation/change enables us to design a solution with that in mind.</p>
<h2 id="immutability-in-languages">Immutability in languages</h2>
<p>Many programming languages have a relatively simple view of immutability in the form of <strong>const, final</strong> and <strong>let</strong> etc. But they are really just referring to the ability to change a <em>primitive</em> value or a <em>reference</em> to an Object. These mechanisms don't really apply to complex data structures, lists, maps or object graphs.</p>
<h3 id="considerations">Considerations</h3>
<p>If we consider a <em>List</em> with one or more values in it and declare it to be <strong>immutable</strong> by some mechanism. Are we declaring that the reference to that <em>List</em> is immutable or that the contents of the <em>List</em> are immutable or that the actual items in the list are immutable? What would we mean if we mixed variable and constant values in that <em>list</em>? How far should/does that <strong>immutability</strong> extend?</p>
<p>Some languages have <strong>immutable</strong> versions of more complex data structures. This now means that all the <em>type signatures</em> need to be specific about whether or not they accept <strong>mutable</strong> or <strong>immutable</strong> types. The alternative is to move the <strong>immutable</strong> checks to runtime. Then there is less compiler support for <strong>immutability</strong>. So with a <em>List</em> holding a mix of variable and constant values we may now get runtime errors in some circumstances and not others.</p>
<h2 id="functional-approach-with-pure">Functional approach with <strong>pure</strong></h2>
<p>The world of Functional Programming has a very different and somewhat rigorous approach to controlling change; in the form of a <a target="_blank" href="https://en.wikipedia.org/wiki/Pure_function">pure function</a>.</p>
<h3 id="pure">Pure</h3>
<p>The <strong>pure</strong> idea is very appealing in many ways. In short; what the developer is saying is <em>I won't alter any externally visible data or parameters used when this function is called</em>.</p>
<p>What this gives you in a single concept, is the assurance that data will not be altered. It therefore removes the need for <strong>const, final</strong> and <strong>let</strong> etc and all the immutable versions of mutable data structures.</p>
<p>But the price is somewhat expensive in some ways. It limits your ability to log, write files or even how you implement some algorithms in the way you'd like.</p>
<p>So true <strong>pure functions</strong> really do stop all side effects, but they actually <strong>don't</strong> stop you reassigning local variables inside a <strong>pure function</strong>. So they do not provide <strong>const, final</strong> and <strong>let</strong> semantics for local variables; this is because they are not externally visible. But reassignment of variables can also lead to issues and in EK9 we'd like to address those issues as well if possible.</p>
<h2 id="ek9-use-of-constants-and-pure">EK9 use of <em>constants</em> and <em>pure</em></h2>
<p>The idea in EK9 is to try and meld <a target="_blank" href="https://www.ek9.io/constants.html">constants</a>, <strong>const, final, let</strong> and a
<a target="_blank" href="https://www.ek9.io/basics.html#pure">pure-ish</a> idea applied to <em>functions/methods</em> into a reliable way of delivering immutability and limit variable mutation/reassignment.</p>
<p><a target="_blank" href="https://www.ek9.io">EK9</a> does not have global variables; it provides <a target="_blank" href="https://www.ek9.io/dependencyInjection.html">Dependency Injection</a>. It also has <a target="_blank" href="https://www.ek9.io/constants.html">constants</a> for use with its <a target="_blank" href="https://www.ek9.io/builtInTypes.html">built-in types</a>. This means that some of the issues surrounding <strong>immutability</strong> have been solved (as constants are by definition immutable).</p>
<p>But by adding <strong>pure</strong> as a key word on <em>functions</em> and <em>methods</em>; EK9 provides a mechanism to guarantee that any data passed in (irrespective of the complexity of the data structures) won't be mutated (modified). This is quite a <em>misuse</em> of the word <strong>pure</strong> as seen from a Functional Programming point of view, but it has a certain ring to it. So I'm going to <em>misuse it</em>.</p>
<h3 id="pure-functions-objects-and-constructors">Pure Functions, Objects and Constructors</h3>
<p>In EK9 when a <em>function</em> or a <em>method</em> is marked as being 'pure' it means variables cannot be mutated and only other 'pure' functions and methods can be called.</p>
<p>This means that no matter what is passed in as parameters can never be mutated. But also it means local variables/field properties can never be mutated (or reassigned).</p>
<p>Significantly is means that a 'pure' Object constructor <strong>must</strong> be an exception to this rule. It <strong>must</strong> be able to mutate its own fields/properties at construction. In essence it has to be possible to mutate those fields/properties during object construction.</p>
<p>Clearly it must also be possible to assign/reassign/mutate any return parameter.</p>
<h3 id="side-effects">Side effects</h3>
<p>EK9 is not so rigorous as true <em>Pure Functions</em> in the sense of forbidding all side effects. For example EK9 does not consider writing files or sending information out as being <strong>impure</strong>.</p>
<p>In EK9 it is only the mutation of data (with the exception of Object construction/return parameters) that EK9 limits with <strong>pure</strong>.</p>
<h2 id="implications">Implications</h2>
<p>There are a number of implications of taking this approach. These are outlined below.</p>
<h3 id="constants">Constants</h3>
<p><strong>Constants</strong> can be passed into <em>functions/methods</em>; if those <em>functions/methods</em> are pure then it's quite clear that those <strong>constants</strong> cannot be <strong>mutated</strong>. If on the other hand the <em>functions/methods</em> are not marked as <strong>pure</strong> then those <strong>constants</strong> have to be converted to a <em>variable</em>. While it is possible to 'trace the const-ness' of a value, it leads to complexity and a push into runtime checks.</p>
<p>Imagine for a moment a <strong>constant</strong> being inserted into a <strong>List</strong> or some part of an object graph; The check now has to be a runtime check if <em>functions/methods</em> are not marked as <strong>pure</strong>. This limits the compilers ability to detect issues at development time. EK9 avoids this but that the price of making the developer knowingly convert a <strong>constant</strong> to a variable (when used in that context).</p>
<p>We only allow a <strong>constant</strong> to be passed into a <strong>pure</strong> <em>function/method</em>. EK9 enforces the conversion of a <strong>constant</strong> to a <em>variable</em> if it is to be used in a data structure or passed in to a <strong>non-pure</strong> <em>function/method</em>. All <strong>constant</strong> values must be converted to a variable if being returned from any <em>function/method</em>.</p>
<h3 id="inheritance-and-delegation">Inheritance and Delegation</h3>
<p>The creation of <em>abstract</em> <strong>pure</strong> <em>functions</em> and <em>methods</em> has a couple of additional implications. Specifically it means that overriding those <em>functions</em> and <em>methods</em> must also be <strong>pure</strong>. This is because the <em>super</em> has defined the contract that is to be used. When other <em>functions/methods</em> make the calls via abstract mechanisms that are marked <strong>pure</strong> then the contract is set and therefore the implementations must also be pure to maintain the contract.</p>
<p>The converse is not true however, if a <em>super</em> <em>function/method</em> is <strong>not pure</strong> the implementation can either be <strong>pure</strong> or <strong>not pure</strong>.</p>
<h2 id="summary">Summary</h2>
<p>The approach to immutability in EK9 is a bit of a 'cutting the gordian knot' approach. It removes an entire set of existing concepts in most modern imperative languages. The <strong>const, final, let</strong> syntax, all the compiler rules around those. The profusion and need to create immutable data structures to parallel the mutable versions (and compiler checks on those). But most importantly of all it pulls any immutability check back out of runtime into compile/design time.</p>
<p>The idea of <strong>pure</strong> in EK9 has some similarities to <a target="_blank" href="https://en.wikipedia.org/wiki/Pure_function">pure functions</a>, but has a number of significant differences.
Maybe the use of the word <strong>pure</strong> will lead to confusion or 'heated debate'. But it's a nice short word and has sort of 'clean simplicity' to it. I could not find another word that conveyed this meaning.</p>
<p>The next blog post will discuss the <strong>constructs</strong> that EK9 will provide, by this I mean the concept of things like a <em>class</em> or a <em>function</em>. EK9 provides many more than just those two.</p>
]]></content:encoded></item><item><title><![CDATA[Flow Control - why no early returns]]></title><description><![CDATA[Are early returns really more trouble than they are worth?]]></description><link>https://blog.ek9.io/flow-control-why-no-early-returns</link><guid isPermaLink="true">https://blog.ek9.io/flow-control-why-no-early-returns</guid><category><![CDATA[programming languages]]></category><category><![CDATA[Developer]]></category><category><![CDATA[languages]]></category><dc:creator><![CDATA[Steve]]></dc:creator><pubDate>Mon, 20 Sep 2021 21:22:24 GMT</pubDate><content:encoded><![CDATA[<h2 id="background">Background</h2>
<p>In my <a target="_blank" href="https://blog.ek9.io/programming-language-modern-types">previous post</a> I outlined the need for a range of new modern <strong>types</strong> in
<a target="_blank" href="https://www.ek9.io">EK9</a>.</p>
<p>In this article I'll discuss the different forms of flow control. I will also introduce a couple of contentious ideas relating to unnecessary complexity in most languages; those being <strong>break</strong>, <strong>label</strong>, <strong>continue</strong> and <strong>return</strong>.</p>
<h2 id="forms-of-flow-control">Forms of flow control</h2>
<p>There are broadly two categories of flow control in <a target="_blank" href="https://www.ek9.io">EK9</a>.</p>
<ul>
<li>Decision flow control</li>
<li>Iteration flow control</li>
</ul>
<h3 id="decision-flow-control">Decision flow control</h3>
<p>This is the simple <strong>if/else</strong> and the <strong>switch</strong> construct.
These are described in <a target="_blank" href="https://www.ek9.io/flowControl.html#if_elseif_else">if/else</a> and
<a target="_blank" href="https://www.ek9.io/flowControl.html#switch">switch</a> on the EK9 site. Both of these are fairly similar to most languages. The <strong>switch</strong> has no <strong>break</strong> syntax and significantly you can use <strong>switch</strong> to return a value.</p>
<h3 id="iteration-flow-control">Iteration flow control</h3>
<p>Similar to most languages in the form of <a target="_blank" href="https://www.ek9.io/flowControl.html#for_loop"><strong>for loops</strong></a>, <a target="_blank" href="https://www.ek9.io/flowControl.html#while_loop"><strong>while loops</strong></a> and <a target="_blank" href="https://www.ek9.io/flowControl.html#do_while_loop"><strong>do while loops</strong></a>.</p>
<p>But again the most significant change is the lack of any <strong>break</strong> syntax to exit a loop early. The developer has to use a condition expression in the <strong>while do/while</strong> loop and must iterate through to the end in a 'for loop' (<strong>WHAT!</strong> you may think, but read on).</p>
<h2 id="give-me-a-break">Give me a <strong>break</strong></h2>
<p>In short, no I won't; at least not in the forms most languages use. The main reason why  <strong>return</strong>, <strong>break</strong>, <strong>label</strong>, <strong>continue</strong> or <strong>goto</strong> are <strong>not</strong> available is to reduce the possible processing paths a developer has to understand when looking at code.</p>
<p>Just think about it for a moment. If a function/method has multiple exit points you have to build a mental model of each of the processing paths. Many would say - hey I only do preconditions at the start and they are simple. Hmm -- take a look at a few code bases, that's not what people do. If they are all simple preconditions -- hey put them in a simple single if statement.</p>
<p>The original idea of <a target="_blank" href="https://en.wikipedia.org/wiki/Structured_programming">structured programming</a> was really innovative at the time. There will be many <em>commentators</em> that think reverting to single entry, single exit is a retrograde step. I'd agree if all <a target="_blank" href="https://www.ek9.io">EK9</a> was offering was this same old reheated soup from other languages.</p>
<p><strong>But it's not</strong>, is going to try and attempt to ween developers away from just standard procedural/imperative code and more in the direction of a functional approach.</p>
<p>Now bear with me, don't huff and puff just yet. Given this a quick read first.</p>
<h2 id="pipelines-or-fluent-interfaces">Pipelines or 'fluent interfaces'</h2>
<p><a target="_blank" href="https://java-design-patterns.com/patterns/fluentinterface/">Fluent Interfaces</a> are a sort of Object Oriented attempt at functional programming (a bit harsh maybe).</p>
<p>Why is this at all relevant to <strong>for loops</strong>, <strong>break</strong> and lack of <strong>early returns</strong>?</p>
<p>It's relevant because with <a target="_blank" href="https://www.ek9.io/streamsAndPipelines.html">EK9 pipelines</a> you have all the <strong>early returns</strong>, <strong>breaks</strong> and <strong>continues</strong> you need; but in the form of new syntax (unless you have a Unix background then it's familiar).</p>
<h3 id="filter">Filter</h3>
<p>This is your <strong>if</strong> statement that either does or does not let data flow through the pipeline.</p>
<h3 id="head-tail-skip">Head, Tail, Skip</h3>
<p>This is your <strong>break</strong>.</p>
<h3 id="pipeline-summary">Pipeline summary</h3>
<p>The pipeline manages your state variables as they <em>stream</em> through the pipeline.
When you adopt <a target="_blank" href="https://www.ek9.io/streamsAndPipelines.html">EK9 pipelines</a>; you'll see that:</p>
<pre><code>cat someList | <span class="hljs-keyword">filter</span> <span class="hljs-keyword">by</span> someCriteria | head <span class="hljs-number">1</span> &gt; stdout
</code></pre><p>Means you don't write <strong>for</strong> or <strong>if</strong> or <strong>break</strong>. You don't need any loop state variables, multiple nested loops and no <strong>labels</strong> to <strong>continue</strong> to.</p>
<p>This single construct from Functional programming is probably as significant as <strong>Polymorphism</strong> from Object Oriented programming.</p>
<p>There are lots of other <strong>commands</strong> in <a target="_blank" href="https://www.ek9.io/streamsAndPipelines.html">EK9 Pipelines</a> for grouping, sorting, uniqueness, joining, mapping and collecting/reducing. Also even <strong>teeing</strong> off data from parts of the pipeline as it flows through (big Unix/Linux influence here).</p>
<h2 id="exceptions">Exceptions</h2>
<p>The <em>unspoken</em> flow control is the <a target="_blank" href="https://www.ek9.io/exceptions.html"><strong>Exception</strong></a>. <a target="_blank" href="https://www.ek9.io">EK9</a> uses these in a very limited way and they are 'unchecked' meaning you do not declare them on function or method signatures.</p>
<h3 id="implementation-details-leaking-out">Implementation details leaking out</h3>
<p>If <a target="_blank" href="https://www.ek9.io/exceptions.html">Exceptions</a> had to be declared (like some languages) then implementation details start to leak out (FileNotFoundException). It looks like you are accessing files in your implementation then. But what if you altered this implementation to read and write data from a remote system (what about those of Exceptions and then new networking Exceptions).</p>
<p>That's why EK9 only has unchecked Exceptions. In general it's only worth catching Exceptions if you can do something about the processing. A remote call to a web server could be retried a couple of times (that's reasonable). But not being able to write a file is pretty much it - what are you going to do to solve that?</p>
<p>By the way, Exceptions destroy the entire Pipeline processing if not caught!</p>
<h3 id="the-unset-nature-of-data">The Unset nature of data</h3>
<p>EK9 prefers to return <strong>unset</strong> data, this is much easier to deal with. In pipeline processes it just gets omitted from the flow; in a sort of <a target="_blank" href="https://wiki.haskell.org/All_About_Monads">Haskell MONAD</a> type manner.</p>
<h2 id="summary">Summary</h2>
<p>EK9 has traditional flow control, but it has been deliberately limited to enforce a more <em>structured</em> approach originally created by Böhm, Jacopini and  Dijkstra.</p>
<p>You may see this as a limitation, but I've found it forces more decomposition in to smaller functions and methods and the overall processing is much easier to understand at first glance.</p>
<p>The functional approach to collection processing again encourages smaller well rounded <em>pure</em> functions and a more declarative syntax. Basically you don't get bogged down in the detail.</p>
<p>The next blog post will discuss the thorny issue of <strong>immutability</strong> and take another key innovation from the Functional programming camp (<strong>pure</strong>). In EK9 it won't be
totally pure. I'm a pragmatic person and also like to bend the rules, so it will be <strong>pure-ish</strong>.</p>
]]></content:encoded></item><item><title><![CDATA[Programming Language - Modern Types]]></title><description><![CDATA[Integer, Float, String types aren't enough]]></description><link>https://blog.ek9.io/programming-language-modern-types</link><guid isPermaLink="true">https://blog.ek9.io/programming-language-modern-types</guid><category><![CDATA[programming languages]]></category><category><![CDATA[development]]></category><dc:creator><![CDATA[Steve]]></dc:creator><pubDate>Sun, 05 Sep 2021 18:09:03 GMT</pubDate><content:encoded><![CDATA[<h2 id="background">Background</h2>
<p>In my <a target="_blank" href="https://blog.ek9.io/an-object-oriented-or-a-functional-language">previous post</a> I concluded that both Object Oriented and Function programming should be adopted in
<a target="_blank" href="https://www.ek9.io">EK9</a>.</p>
<p>In fact all instances of <em>types</em> in EK9 will be <strong>Objects</strong>, there will be no <strong>primitive</strong> <em>types</em> at all. This solves the 'Autoboxing' issues and requirements of mapping <strong>primitive</strong> values to <strong>Objects</strong> and vice versa. But means the compiler will have to work harder to produce efficient machine code.</p>
<p>This decision to use only <strong>Objects</strong> does have one profound effect however, unlike a primitive variable (that always has to have a value); EK9 will allow variables to be <strong>unset</strong>. This means that the <strong>Object</strong> is of a specific <em>type</em> but can have no meaningful value. This removes the need for <strong>NaN</strong> with floating points, it also means it possible to avoid the concept of <strong>null</strong> to some extent (but not quite 100%). It means that a <strong>Boolean</strong> can be <strong>true</strong>, <strong>false</strong> and <strong>unset</strong>/<strong>unknown</strong>.</p>
<h2 id="the-types">The Types</h2>
<p>The question now is what <em>types</em> to provide as part of the language and why?</p>
<h3 id="simple-types">Simple Types</h3>
<p>Obviously it will be necessary to provide:</p>
<ul>
<li>Boolean</li>
<li>Character</li>
<li>String</li>
<li>Integer</li>
<li>Float</li>
</ul>
<p>More complex types will also be required for any sort of meaningful processing, such as:</p>
<ul>
<li>Date</li>
<li>Time</li>
<li>DateTime</li>
</ul>
<p>But when you think about dates and times there is also the obvious type of <em>Duration</em> that should also be provided. After all if EK9 is to provide <strong>operators</strong> developers will want to do 'operations' on dates and times with <em>Durations</em>.</p>
<p>So EK9 will include:</p>
<ul>
<li>Duration</li>
</ul>
<h3 id="more-sophisticated-types">More Sophisticated Types</h3>
<p>If EK9 is to include the <strong>String</strong> <em>type</em> then it is almost essential to support <em>regular expressions</em>. While these can be complex, they are familiar to many developers and are really a modern essential component.</p>
<p>So EK9 will include:</p>
<ul>
<li>RegEx</li>
</ul>
<p>While dates and times are reasonably modern concepts, <strong>Money</strong> is also widely used! It has a number of very specific and intricate processing issues associated with it. These mainly focus around varying decimals places, precision and rounding.</p>
<p>It should not be possible to add $100 to £100 for example. While both variables are of a <strong>Money</strong> <em>type</em>; they are not actually compatible without conversion to the same currency.</p>
<p>As EK9 is <em>strongly typed</em> then it must enforce this on:</p>
<ul>
<li>Money</li>
</ul>
<p>The same sort of logic can be applied to <strong>Colour (Color)</strong> and <strong>Dimension</strong>. In particular <strong>Dimensions</strong> in different units are not compatible without conversion (you would not want to <a target="_blank" href="https://www.simscale.com/blog/2017/12/nasa-mars-climate-orbiter-metric/">crash a space ship</a> by accidentally mixing imperial and metric units would you?).</p>
<p>EK9 will include both:</p>
<ul>
<li>Colour</li>
<li>Dimension</li>
</ul>
<p>EK9 should include the concept of a <strong>Locale</strong> so that numbers, financial amounts, dates, times and money can all be formatted correctly based on a selected locale.</p>
<p>The <a target="_blank" href="https://www.ek9.io/builtInTypes.html">EK9 built in types</a> go beyond what most languages supply as <strong>built-in</strong>. But really most modern development needs some or all of these <em>types</em>.</p>
<h3 id="collection-typeshttpswwwek9iocollectiontypeshtml"><a target="_blank" href="https://www.ek9.io/collectionTypes.html">Collection Types</a></h3>
<p>Most programming languages need to provide specific types that can act as collections or containers for zero or more instances of a particular <em>type</em>.</p>
<p>EK9 will provide:</p>
<ul>
<li>Optional</li>
<li>List</li>
<li>Dict (Dictionary/Map)</li>
<li>PriorityQueue</li>
</ul>
<p>These will be <em>Generic</em> <em>types</em> that can be parameterised with another <em>type</em> or <em>types</em>. A <strong>List of Money</strong> or <strong>Optional of Dimension</strong> for example. But importantly as EK9 is strongly typed; a <strong>List of Integer</strong> is a fully different <em>type</em> to a <strong>List of Float</strong> (unlike Java there is no type erasure). But note it will not provide <strong>arrays</strong>.</p>
<h2 id="standard-api-typeshttpswwwek9iostandardtypeshtml"><a target="_blank" href="https://www.ek9.io/standardTypes.html">Standard API Types</a></h2>
<p>These built in <em>types</em> are really utility <em>types</em>, many of which provide some type of interface into the underlying operating system.</p>
<p>EK9 will include:</p>
<ul>
<li>Stdin, Stdout, Stderr</li>
<li>FileSystem, TextFile</li>
<li>EnvVars (environment variables)</li>
<li>OS (Operating System)</li>
<li>Signals</li>
</ul>
<h2 id="networking-apishttpswwwek9ionetworktypeshtml"><a target="_blank" href="https://www.ek9.io/networkTypes.html">Networking APIs</a></h2>
<p>Networking is a key capability for many programming language and EK9 will provide:</p>
<ul>
<li>UDP</li>
<li>TCP</li>
<li>HTTP</li>
</ul>
<h2 id="conclusion">Conclusion</h2>
<p>These are a minimal set of types a modern language could provide. Note these are not low level <em>types</em>. <strong>Byte</strong> and arrays are missing from EK9, only time will tell if low level <strong>Byte</strong> <em>types</em> should be included.</p>
<p>It could be argued that some of these types could/should have been provided via API's. But in terms of a basic starting point; these <em>types</em> should provide enough to get the language going.</p>
<p><strong>Integer</strong> and <strong>Float</strong> will be 64bit values, there will be no other short, unsigned, long, 'long long' <em>types</em>.</p>
<p>The next blog will discuss flow control and exception/error conditions.</p>
]]></content:encoded></item><item><title><![CDATA[An Object Oriented or a Functional Language]]></title><description><![CDATA[Object Oriented and Functional programming can be used together]]></description><link>https://blog.ek9.io/an-object-oriented-or-a-functional-language</link><guid isPermaLink="true">https://blog.ek9.io/an-object-oriented-or-a-functional-language</guid><category><![CDATA[programming languages]]></category><category><![CDATA[components]]></category><category><![CDATA[Developer]]></category><dc:creator><![CDATA[Steve]]></dc:creator><pubDate>Thu, 02 Sep 2021 08:32:28 GMT</pubDate><content:encoded><![CDATA[<h2 id="background">Background</h2>
<p>In my <a target="_blank" href="https://blog.ek9.io/strong-typing-in-programming-languages">previous post</a> I came to the conclusion that <strong>strong typing</strong> should be adopted in <a target="_blank" href="https://www.ek9.io">EK9</a>.</p>
<p>The next question (before deciding on the <strong>types</strong>) is to consider the pros-and-cons of Object Oriented programming and Functional programming.</p>
<h2 id="name-spaces-scopes-and-polymorphism">Name Spaces, Scopes and Polymorphism</h2>
<p>It is necessary to decide 'where' to locate code when defining an aggregate (structured data) or a function/subroutine. This can assist <em>Polymorphism</em> and has an impact on <em>Coupling</em>/<em>Cohesion</em>.</p>
<p>Some programming languages only have a single global name space in which to define artefacts. This can cause a number of issues, mainly to do with name collisions but also encapsulation of data and function accessibility.</p>
<h3 id="name-spaces">Name Spaces</h3>
<p>Languages such as C++, Java and C# have the concept of a 'namespace' or a 'package' from which artefacts can be <em>addressed</em>. This means that it is possible to reduce the collisions of naming. In <a target="_blank" href="https://www.ek9.io">EK9</a> this will be called a
<a target="_blank" href="https://www.ek9.io/structure.html#module"><strong>module</strong></a>.
This will allow naming as follows:</p>
<pre><code><span class="hljs-selector-tag">postalAddress</span> &lt;<span class="hljs-selector-tag">-</span> <span class="hljs-selector-tag">general</span><span class="hljs-selector-class">.postal</span><span class="hljs-selector-pseudo">::Address()</span>
<span class="hljs-selector-tag">networkAddress</span> &lt;<span class="hljs-selector-tag">-</span> <span class="hljs-selector-tag">org</span><span class="hljs-selector-class">.network</span><span class="hljs-selector-pseudo">::Address()</span>
</code></pre><p>This allows the name <em>Address</em> to be reused, but when this clashes with <em>Address</em> from another <a target="_blank" href="https://www.ek9.io/structure.html#module"><strong>module</strong></a> it can be 'fully qualified' to make resolution clear.</p>
<h3 id="scopes">Scopes</h3>
<p>It is normal in most programming languages to create <strong>block scope</strong> in <em>functions</em> or
<em>member functions</em> (<a target="_blank" href="https://www.ek9.io/methods.html"><em>methods</em></a> on
<a target="_blank" href="https://www.ek9.io/classes.html"><em>classes</em></a>).
This enables variables to be declared within that block, these variables are typically destroyed/lost when the block scope is complete. There are times when it is desirable to let such variables 'live on' such an idea leads to a <em>closure</em>.</p>
<p>Some languages allow all variables in a scope to be 'closed over'. In <a target="_blank" href="https://www.ek9.io">EK9</a> the use of variables in a <em>closure</em> will be explicit.</p>
<p>Both <a target="_blank" href="https://www.ek9.io/classes.html"><em>classes</em></a> and <a target="_blank" href="https://www.ek9.io/functions.html"><em>functions</em></a> also have their own <em>scopes</em>. For <em>functions</em> this <em>scope</em> acts much like a <strong>block scope</strong>.</p>
<p>For <a target="_blank" href="https://www.ek9.io/classes.html"><em>classes</em></a> the scope contains the member variables and member functions (<a target="_blank" href="https://www.ek9.io/methods.html"><em>methods</em></a>). As discussed  in the <a target="_blank" href="https://blog.ek9.io/strong-typing-in-programming-languages">previous post</a>; polymorphism is highly desirable. While it can be implemented in a number of different ways; use of <em>classes</em> is one of the most natural.</p>
<p>But <a target="_blank" href="https://www.ek9.io/classes.html"><em>classes</em></a> are just one aspect of polymorphism that need to be considered; the concept of a set of <em>method</em> signatures acting as some type of <em>interface</em> or <a target="_blank" href="https://www.ek9.io/traits.html"><em>trait</em></a> can also facilitate polymorphism. These are the main reasons why C morphed from just <em>structs</em> and <em>functions</em> into C++ an Object Oriented language.</p>
<h3 id="operatorshttpswwwek9iooperatorshtml"><a target="_blank" href="https://www.ek9.io/operators.html">Operators</a></h3>
<p>If we were not to provide <a target="_blank" href="https://www.ek9.io/classes.html"><em>classes</em></a>/<a target="_blank" href="https://www.ek9.io/traits.html"><em>traits</em></a> then we'd have to face the issue of whether or not to include <a target="_blank" href="https://www.ek9.io/operators.html"><em>operators</em></a> and <em>operator overloading</em> with developer defined aggregates (data structures).</p>
<p>Are <a target="_blank" href="https://www.ek9.io/operators.html"><em>operators</em></a> desirable? Many languages do include this capability such as C++ and C#; others like Java do not. There are significant benefits in providing this capability; the main one being <strong>semantics</strong>.</p>
<p>A defined set of <a target="_blank" href="https://www.ek9.io/operators.html"><em>operators</em></a> can also enable the compiler to make a number of assumptions when parsing code (especially when defining 'Generics').</p>
<p>So <a target="_blank" href="https://www.ek9.io/operators.html"><em>operators</em></a> will be included in <a target="_blank" href="https://www.ek9.io">EK9</a> and they will be defined in the <em>scope</em> and context of aggregates (such as <a target="_blank" href="https://www.ek9.io/classes.html"><em>classes</em></a> and <a target="_blank" href="https://www.ek9.io/traits.html"><em>traits</em></a>).</p>
<h3 id="reuse-inheritancehttpswwwek9ioinheritancehtml-and-delegation">Reuse, <a target="_blank" href="https://www.ek9.io/inheritance.html">Inheritance</a> and Delegation</h3>
<p>With both <em>classes</em> and <em>traits</em> we can use the traditional <a target="_blank" href="https://www.ek9.io/inheritance.html"><em>inheritance</em></a> mechanism provided in most Object Oriented languages. In general this feature is overused. In
<a target="_blank" href="https://www.ek9.io">EK9</a> we will facilitate a mechanism to make <a target="_blank" href="https://www.ek9.io/composition.html"><em>delegation</em></a> just as easy as <a target="_blank" href="https://www.ek9.io/inheritance.html"><em>inheritance</em></a>. This will be accomplished through the use of member variables and <a target="_blank" href="https://www.ek9.io/traits.html"><em>traits</em></a>.</p>
<p><em>Delegation</em>/Composition encapsulates data better, facilitates reuse, enables cohesion and makes coupling more flexible. It is currently under used because few programming languages have built in syntax to make <a target="_blank" href="https://www.ek9.io/composition.html"><em>delegation</em>/composition</a> as easy as <a target="_blank" href="https://www.ek9.io/inheritance.html"><em>inheritance</em></a>.</p>
<h2 id="why-bother-with-functions">Why bother with functions?</h2>
<p>Are <a target="_blank" href="https://www.ek9.io/functions.html"><em>functions</em></a>  necessary then? <em>Functions</em> provide a small, stateless and succinct artefact for processing steps. Moreover they are easily reusable and can be made <a target="_blank" href="https://www.ek9.io/basics.html#pure">'pure'</a> (i.e. having no side effects).</p>
<p>In conjunction with the <a target="_blank" href="https://www.ek9.io/composition.html"><em>delegation</em></a> model outlined for <a target="_blank" href="https://www.ek9.io/classes.html"><em>classes</em></a> and <a target="_blank" href="https://www.ek9.io/traits.html"><em>traits</em></a>; <a target="_blank" href="https://www.ek9.io/functions.html"><em>functions</em></a> can also be reused via delegation. </p>
<p>But most importantly there are elements of functionality that do not have a natural 'home' as part of a  <a target="_blank" href="https://www.ek9.io/classes.html"><em>classes</em></a>; they stand in there own right within the context of a <a target="_blank" href="https://www.ek9.io/structure.html#module"><strong>module</strong></a>.</p>
<p>This is particularly important when the subject of 'streaming pipelines' is addressed. Many languages use/reuse <em>methods</em> on <em>classes</em> to implement what is called a 'fluent' programming interface.</p>
<p>But <a target="_blank" href="https://www.ek9.io">EK9</a> will follow the Unix philosophy and use distinct syntax with the pipe <strong>|</strong> symbol for <a target="_blank" href="https://www.ek9.io/streamsAndPipelines.html">stream pipelines</a>.</p>
<p> <a target="_blank" href="https://www.ek9.io">EK9</a> will also introduce the concept of an <a target="_blank" href="https://www.ek9.io/dynamicFunctions.html"><em>abstract function</em></a> in a similar manner to the <strong>C typedef</strong> in the previous article.</p>
<h2 id="conclusion">Conclusion</h2>
<p><em>Functions</em>, <em>Classes</em> and <em>Traits</em> are all required in EK9. They each bring capability and reuse but in different but complementary ways and can be used in combination.</p>
<p>So <a target="_blank" href="https://www.ek9.io">EK9</a> will provide syntax and semantics for both Object Oriented Programming and Functional Programming.</p>
<p>The next blog post will cover the basic <strong>types</strong> that will be provided by <a target="_blank" href="https://www.ek9.io">EK9</a> and how higher levels of abstraction for modern concepts should be built into the language from the outset.</p>
]]></content:encoded></item><item><title><![CDATA[Strong typing in programming languages]]></title><description><![CDATA[Strong typing can reduce defects and make code more readable]]></description><link>https://blog.ek9.io/strong-typing-in-programming-languages</link><guid isPermaLink="true">https://blog.ek9.io/strong-typing-in-programming-languages</guid><category><![CDATA[programming languages]]></category><category><![CDATA[C]]></category><category><![CDATA[JavaScript]]></category><dc:creator><![CDATA[Steve]]></dc:creator><pubDate>Sat, 28 Aug 2021 08:11:57 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/stock/unsplash/0gkw_9fy0eQ/upload/92be76417143234073fedb01436b0999.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<h2 id="heading-background">Background</h2>
<p>In the <a target="_blank" href="https://blog.ek9.io/whats-involved-in-creating-a-programming-language">previous post</a> I removed all syntax and language content to focus on just:</p>
<ul>
<li><p>Structure, in the form of an aggregate</p>
</li>
<li><p>Sequence, in the form of an ordered number of steps</p>
</li>
<li><p>Classification, in the form of a <em>type</em></p>
</li>
</ul>
<p>Most programming languages have the attributes above (they are pretty much essential). But it is the last attribute, that of <em>type</em>; where languages vary in their use.</p>
<p>In this post I'll articulate why I think strong typing is important. Strong typing is the combination of <strong>Structure</strong> and <strong>Classification</strong>. For example an <strong>Address</strong> <em>type</em> could be defined as:</p>
<ul>
<li><p>House Number</p>
</li>
<li><p>Street Name</p>
</li>
<li><p>City</p>
</li>
<li><p>Region</p>
</li>
<li><p>Postcode (Zipcode)</p>
</li>
</ul>
<p>The above defines an aggregate called <strong>Address</strong>. Most people would not expect that <em>type</em> to fundamentally change in structure once declared. The values might not be set; but most people would not expect 'City' to no longer exist in some contexts and reappear in others. Some programming languages do allow this.</p>
<p>We are used to the idea that once something is <em>classified</em> it will; in general remain of that classification unless some significant event occurs to transform it. Following that event it is normally reclassified in some way.</p>
<p>So in line with creating a programming language that most people will be able to adopt and understand; I think it is quite important to base the language on that principle. Moreover we look to create order and classification almost by nature and without detailed thought. Humans are almost always looking to group and classify things they observe, it is in our nature.</p>
<h2 id="heading-why-types">Why Types</h2>
<p>Even languages that are dynamic in nature like Javascript, do have <a target="_blank" href="https://www.oreilly.com/library/view/you-dont-know/9781491905159/ch01.html">types</a>. It's just that those languages tend to be a little 'free-and-easy' with <em>type</em> conversions.</p>
<p>That is to say Javascript will allow (snip from <a target="_blank" href="https://twitter.com/codingyuri/status/1427839582037442564">@codingyuri original post</a>)</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">let</span> num1 = <span class="hljs-number">5</span>;
<span class="hljs-keyword">let</span> num2 = <span class="hljs-number">7</span>;
num1 = num1.toString();
<span class="hljs-keyword">let</span> total = <span class="hljs-built_in">Number</span>(num1 + num2)
</code></pre>
<p>So you may ask, why is this strange? While not explicit <strong>num1</strong> and <strong>num2</strong> have been classified as <strong>Number</strong>. When I say classified I mean most people now create a mental mapping that something called 'num1' (a variable) is of <em>type</em> <strong>Number</strong>. The Javascript runtime has also classified them and a <strong>Number</strong> (typeof shows this).</p>
<p>But when the 'toString()' operation is used it returns back a value of <strong>String*</strong>type*. This is assigned to 'num1'. This is the equivalent of writing:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">let</span> num1 = <span class="hljs-string">"5"</span>;
</code></pre>
<h3 id="heading-implicit-type-changing">Implicit <em>type</em> changing</h3>
<p>So the <em>type</em> of 'num1' has now been altered from a <strong>Number</strong> to <strong>String</strong>. You could argue calling 'toString()' was the significant event that allows this. But other than the name 'toString()' there was nothing to inform the developer that the <em>type</em> would be would be changed.</p>
<h3 id="heading-variable-reassignment">Variable reassignment</h3>
<p>There are various schools of thought around limiting variable reassignment, some say it leads to defects or code that is hard to read and understand.</p>
<p>But you will probably find that when you return to review code like the above; it takes time to 'grok'. Not only are variables being reused through the processing steps but they are also changing <em>type</em>. That's a lot of change going on and quite a bit of that change is implicit. This means you have to comprehend those implicit changes and mentally apply them through to processing steps.</p>
<h3 id="heading-operators-and-implicit-type-coercion-promotion">Operators and implicit type coercion (promotion)</h3>
<p>The part of the example above that deals with creating the 'total' shows implicit <em>type</em> coercion.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">let</span> num2 = <span class="hljs-number">7</span>;
<span class="hljs-keyword">let</span> total = <span class="hljs-built_in">Number</span>(num1 + num2)
</code></pre>
<p>The <strong>+</strong> operator is being used with 'num1' which has been <em>type</em> altered from a <strong>Number</strong> to a <strong>String</strong> and so now has the meaning of 'append'; rather than mathematic 'addition'. Enabling polymorphic use with operators is normal and natural; again it fits with our natural human traits of looking for symmetry and consistency.</p>
<p>But 'num2' is still of <em>type</em> <strong>Number</strong> and so will be silently coerced to <strong>String</strong> <em>type</em>. The result will be "57" and passed into the <strong>Number</strong> constructor which will create the <strong>Number</strong> 57.</p>
<h3 id="heading-an-aside">An aside</h3>
<p>If we were to alter the <strong>+</strong> operator to ***** then we would get mathematical multiplication; which requires 'num1' is silently coerced back to a <strong>Number</strong>. The variable 'total' will now have the value 35. For such a small change - changing what was a simple operator; the effect has been to transform the expression in a non-obvious manner.</p>
<h3 id="heading-refactoring">Refactoring</h3>
<p>If the code were now refactored as show below:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">let</span> num1 = <span class="hljs-number">5</span>;
<span class="hljs-keyword">let</span> num2 = <span class="hljs-number">7</span>;
<span class="hljs-keyword">let</span> total = <span class="hljs-built_in">Number</span>(num1 + num2)
num1 = num1.toString();
</code></pre>
<p>The value of 'total' would be 12 rather than 57. The change to the processing is significant for such a simple change.</p>
<h2 id="heading-why-is-this-behaviour-not-desirable">Why is this behaviour not desirable?</h2>
<p>It is not desirable because it forces the developer to keep an unwritten mental model of what <em>type</em> each variable actually is (as it may change). By allowing the reassignment and changing of <em>type</em> of a variable the reader has to keep track of where these changes take place. Moreover the implicit type conversions that take place alter their semantic meaning depending on both the <em>types</em> involved and the <em>operator</em> in question.</p>
<p>In short you can't just look at the code and it be simple and self documenting.</p>
<p>The intention here is not to denigrate other languages, but to attempt to highlight the reasoning why strong typing is more natural for Humans. It is what we do naturally and without conscious thought most of the time.</p>
<h2 id="heading-what-is-the-alternative">What is the alternative</h2>
<p>The simple alternative is to ensure that once a variable has an established <em>type</em>; it cannot be changed. This is much easier to understand; as once you know what the <em>type</em> of a variable is -- that's it.</p>
<p>So reusing 'num1' which is a <strong>Number</strong> to hold a <strong>String</strong> would not be allowed.</p>
<pre><code class="lang-javascript">num1 = num1.toString();
</code></pre>
<p>Would result in an error, the developer would be informed 'num1' is of <em>type</em> <strong>Number</strong> and therefore the result of 'toString()' (which is a <strong>String</strong>) cannot be assigned to it.</p>
<p>The coercion of a <strong>Number</strong> to a <strong>String</strong> as shown below should not be implicit.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">let</span> total = <span class="hljs-built_in">Number</span>(num1 + num2)
</code></pre>
<p>This too should result in an error being issued, i.e. It is not possible to add a <strong>Number</strong> value to a <strong>String</strong> value. If you wished to do this then your conversion should be explicit (maybe through the use of 'toString' or an operator such as '$').</p>
<h2 id="heading-too-verbose">Too Verbose</h2>
<p>The argument is not to introduce too much 'verbosity' when creating <em>structures</em>/<em>types</em> or <em>sequences of instructions</em>. But to make statements much more explicit in nature. For example, there is little wrong with this:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">let</span> num1 = <span class="hljs-number">5</span>;
</code></pre>
<p>It is obvious 'num1' is a <strong>Number</strong> <em>type</em> and by using 'let' it is clear that it is being declared. It just 'num1' must now always be a <strong>Number</strong> while in scope. Alternatives might be:</p>
<pre><code class="lang-javascript"><span class="hljs-built_in">Number</span> num1 = <span class="hljs-number">5</span>;
num1: <span class="hljs-built_in">Number</span> = <span class="hljs-number">5</span>;
num1 <span class="hljs-keyword">as</span> <span class="hljs-built_in">Number</span> = <span class="hljs-number">5</span>;
num1 &lt;- <span class="hljs-number">5</span>
</code></pre>
<p>All of which declare a variable called 'num1' as a <strong>Number</strong> <em>type</em> and initialise that variable to have the value of 5.</p>
<p>So the argument is not to make declarations or syntax more verbose or 'bulky' but to ensure <em>types</em> don't change. When <em>types</em> can be safely inferred they can and should be. But there are times when it is necessary/desirable to be explicit as to what <em>type</em> are variable should be. Typically this is necessary when working with polymorphic <em>types</em>.</p>
<h2 id="heading-polymorphism">Polymorphism</h2>
<p>There has been much discussion around polymorphism in various intellectual materials and blogs. It is seen by many as the real value of Object Oriented programming (irrespective of language). But it can be argued that the real value is:</p>
<ul>
<li><p>The ability to call functions without depending on access to the source code of that function</p>
</li>
<li><p>The ability to have or present multiple different perspectives of some software entity</p>
</li>
</ul>
<p>What do those statements mean in practical terms and why are <em>types</em> important?</p>
<h3 id="heading-expression-of-relationships">Expression of relationships</h3>
<p><em>Types</em> give us a mechanism to express polymorphic relationships. This can take the form of <em>inheritance</em> or even exhibiting the same or similar <em>traits</em>. Some languages, such as Python use 'Duck typing' which is really implicit <em>typing</em> based on matching signatures. This does not really enable the expression of relationships in an explicit manner.</p>
<h3 id="heading-an-example-in-c">An example in C</h3>
<p>While C is not an Object Oriented language it still has the capability to provide:</p>
<ul>
<li><p>Structure, in the form of a 'struct'</p>
</li>
<li><p>Sequence, in the form of a 'function'</p>
</li>
<li><p>Classification, in the form of both 'struct' and 'typedef'</p>
</li>
</ul>
<p>Moreover when used in a thoughtful and progressive manner it can provide various forms of polymorphism. Importantly this is done without C being an Object Oriented programming language.</p>
<pre><code class="lang-c"><span class="hljs-meta">#<span class="hljs-meta-keyword">include</span> <span class="hljs-meta-string">&lt;stdio.h&gt;</span></span>
<span class="hljs-function"><span class="hljs-keyword">typedef</span> <span class="hljs-title">void</span> <span class="hljs-params">(*operation)</span><span class="hljs-params">(<span class="hljs-keyword">int</span>)</span></span>;
<span class="hljs-function"><span class="hljs-keyword">void</span> <span class="hljs-title">fun1</span><span class="hljs-params">(<span class="hljs-keyword">int</span> a)</span> </span>{
    <span class="hljs-built_in">printf</span>(<span class="hljs-string">"Value of a is %d\n"</span>, a);
}
<span class="hljs-function"><span class="hljs-keyword">void</span> <span class="hljs-title">fun2</span><span class="hljs-params">(<span class="hljs-keyword">int</span> a)</span> </span>{
    <span class="hljs-built_in">printf</span>(<span class="hljs-string">"a has the value of %d\n"</span>, a);
}

<span class="hljs-function">operation <span class="hljs-title">getFunction</span><span class="hljs-params">()</span> </span>{
    <span class="hljs-keyword">return</span> &amp;fun2;
}

<span class="hljs-function"><span class="hljs-keyword">int</span> <span class="hljs-title">main</span><span class="hljs-params">()</span> </span>{
    getFunction()(<span class="hljs-number">10</span>);
}
</code></pre>
<p>As can be seen in the example above <strong>strong typing</strong> aids safe use of pointers to functions in C. The 'main' function can call 'getFunction' and be assured that the result will be compatible with 'operation' a function that accepts a single int as a parameter.</p>
<p>Through the use of <em>typedef</em> the code above has created an <em>abstraction</em> for a function signature. In may ways this can be viewed as polymorphism. The 'main' function through 'getFunction' has become decoupled from which actual function it will be calling. It is now possible to use 'operation' as a <em>type</em> and pass variables around that are <strong>of that <em>type</em></strong>.</p>
<pre><code class="lang-c">operation op = getFunction();
</code></pre>
<p>In the above example the variable 'op' has the <em>type</em> <strong>operation</strong>. I am not advocating using C as an Object Oriented programming language. There is a reason C++, C#, Java and other OO languages were created after all.</p>
<h3 id="heading-the-same-example-in-javascript">The same example in Javascript</h3>
<pre><code class="lang-javascript">getFunction()(<span class="hljs-number">10</span>)

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">fun1</span>(<span class="hljs-params">a</span>) </span>{
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'The value of a is '</span> + a);
}

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">fun2</span>(<span class="hljs-params">a</span>) </span>{
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'a has the value of '</span> + a);
}

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">getFunction</span>(<span class="hljs-params"></span>) </span>{
    <span class="hljs-keyword">return</span> fun2;
}
</code></pre>
<h3 id="heading-discussion">Discussion</h3>
<p>The Javascript language has much going for it and the removal of the need for <em>types</em> everywhere means that coding can be much simpler and more dynamic. But it comes at a cost; safety. Refactoring code needs much more care and attention, altering the number of parameters of 'fun1' for example may cause errors at runtime.</p>
<p>In the C example the C compiler checks this at compilation time. If we were to alter the code above as follows:</p>
<pre><code class="lang-c"><span class="hljs-function">function <span class="hljs-title">fun1</span><span class="hljs-params">()</span> </span>{
    console.<span class="hljs-built_in">log</span>(<span class="hljs-string">'The value of a is '</span> + a);
}
</code></pre>
<p>Then run the example, all would still be fine because 'fun1' has not been called. Should we then alter our code again.</p>
<pre><code class="lang-c"><span class="hljs-function">function <span class="hljs-title">getFunction</span><span class="hljs-params">()</span> </span>{
    <span class="hljs-keyword">return</span> fun1;
}
</code></pre>
<p>Only now would we get the error (at runtime).</p>
<h2 id="heading-conclusion">Conclusion</h2>
<p>There are significant disadvantages in having to use strong <em>types</em> everywhere, they require definition, variable declarations can be more verbose and generic (parametric programming) is much more verbose and complex.</p>
<p>But they can provide compile time safety and facilitate the expression of relationships. They are much more natural for humans as we tend to classify and categorise most things.</p>
<p>So putting additional definition requirements, slightly more verbose code issues to one side; the natural and logical effect strong <em>types</em> bring together with increased safety is worth the price.</p>
<h3 id="heading-needs-already-catered-for">Needs already catered for</h3>
<p>This conclusion won't suit everyone and there are languages such as Python and Javascript that are much freer with respect to <em>types</em>.</p>
<p>But then there are numerous languages that have strong <em>types</em> already, such as C, C++, C#, Java, Scala, Kotlin, Dart, etc. So why create another language that is 'just like those'?</p>
<p>The next few blog posts will make this clearer. But do far I've not really added anything new other than to fall into the 'compiled', 'strong <em>typing</em>' camp of languages.</p>
]]></content:encoded></item><item><title><![CDATA[What's involved in creating a programming language]]></title><description><![CDATA[The main driving forces for a programming language]]></description><link>https://blog.ek9.io/whats-involved-in-creating-a-programming-language</link><guid isPermaLink="true">https://blog.ek9.io/whats-involved-in-creating-a-programming-language</guid><category><![CDATA[Programming Blogs]]></category><category><![CDATA[Productivity]]></category><category><![CDATA[languages]]></category><category><![CDATA[Developer]]></category><dc:creator><![CDATA[Steve]]></dc:creator><pubDate>Mon, 23 Aug 2021 16:05:31 GMT</pubDate><content:encoded><![CDATA[<h2 id="introduction">Introduction</h2>
<p>Having used various programming languages over the last 30 or so years; I found there were features in some languages that really helped productivity. But I also found there were inconsistencies and syntax that caused defects in programs that were not always obvious.</p>
<h2 id="application-of-programming-languages">Application of Programming Languages</h2>
<p>There was a time when getting a computer to complete any task was a major achievement. In such times, when resources such as CPU power, disk/memory were very constrained; it was necessary to create <em>code</em> that would enable easy translation into machine instructions.
However, it is now possible to create small applications with relative ease that can deliver significant functionality. So the move from:</p>
<p><code>printf("Hello, World")</code></p>
<p>to dynamic web pages has encouraged more people to get involved in computer programming. But many programmers struggle with the historic <strong>baggage</strong> that the genus of those early programming languages still carry forward.</p>
<h2 id="concepts-and-syntax">Concepts and Syntax</h2>
<p>Some of the concepts in languages have proven useful or even essential over time. There is commonality irrespective of programming language. Other parts of a language are just different ways of expressing the same or similar concepts.</p>
<p>Most new entrants to computer programming are really thrust straight into a specific language syntax (be it C, C++, Java, C#, Javascript, Python, Lisp or Prolog, etc). Before long most developers just accept the shortcomings or <em>foibles</em> of their selected language.</p>
<p>So really the first task in creating a new  <a target="_blank" href="https://www.ek9.io">programming language</a>  is to remove some or all of the existing <strong>baggage</strong>; until it is possible to distil the bare minimum number of concepts and syntax to be able to create machine instructions.</p>
<h2 id="the-building-blocks">The Building Blocks</h2>
<p>The following are the two main ingredients of a programming language:</p>
<ul>
<li>Data Structures (or <strong>types</strong>)</li>
<li>Processing Instructions (computation/flow control)</li>
</ul>
<p>The question is then how to express and arrange these building blocks in a coherent and logical way. It is also important to accommodate how people comprehend information in concept, syntax and general instructions outside of computer programming.</p>
<p>While the original computer programmers were mainly mathematicians and scientists; today individuals entering into 'IT' are from various backgrounds and are much younger with fewer academic qualifications.</p>
<p>Building on what many have already been taught in general terms and also what comes most naturally, leads to the conclusion that most people understand:</p>
<ul>
<li>Structure, of the form of a postal address for example</li>
<li>Sequence, of the form of a recipe or directions to an address</li>
<li>Classification, of the form of plant/animal or cat/dog</li>
</ul>
<p>It is these aspects that have lead to the adoption of <strong>imperative</strong> languages being <em>more</em> dominant over <strong>declarative</strong> languages (such as Lisp and Prolog). Those imperative ideas are just easier to understand for most people.</p>
<h3 id="data-structures">Data Structures</h3>
<p>A data structure could be as simple as a <strong>whole number</strong> or a <strong>postal address</strong> (an aggregate of data items). It could also be a collection of data items, like a <strong>List of Address</strong> for example.
Almost all programming languages contain such concepts and this basic building block is something most people can readily accept and comprehend. </p>
<h3 id="processing-instructions">Processing Instructions</h3>
<p>It is the area of <strong>processing instructions</strong> that can cause confusion. For example:</p>
<p><code>x = 2</code></p>
<p><code>y = x + 4</code></p>
<p>In which both <strong>statements</strong> seem simple enough, but this is where the first major discord takes place. For a <strong>declarative</strong> programmer the next statement makes no sense:</p>
<p><code>x = 3</code></p>
<p>How can 'x' now be set to something different? Does this now mean 'y' should be reevaluated to be '7'?</p>
<p>The <strong>imperative</strong> programmer accepts the above as just an ordered sequence of statements, once 'y' was calculated with the value of 'x' was 2 that's all done and dusted. Now let 'x' be set to 3 and do something else with it.</p>
<p>Most people can and do accept 'x' can be set to something different. After all they have been used to completing sets of mathematical questions during their schooling. Albeit in a new and separate question!</p>
<h3 id="arrangement">Arrangement</h3>
<p>The final part of this first post relates to how the data structures and processing instructions should be used and arranged in relation to each other.</p>
<p>There are really two schools of thought on this.</p>
<ol>
<li>Data structures are separate from processing (<strong>functional</strong> programming)</li>
<li>Data and processing should be related (<strong>Object Oriented</strong> programming)</li>
</ol>
<p>When you look in detail as most modern languages; you can see there is now an acceptance that both <strong>paradigms</strong> have pros and cons. Even Java has gone someway to accept <strong>functional</strong> programming (though not in that graceful a manner).</p>
<p>There are times it is appropriate to link state and behaviour (object-oriented); there are also times when it is more appropriate to have multiple functions operate on a data structure.</p>
<h2 id="conclusion">Conclusion</h2>
<p>The first part of <strong>What's involved in creating a programming language</strong> has now been discussed and the conclusion is:</p>
<ul>
<li>Imperative programming language</li>
<li>Strongly <em>typed</em></li>
<li>Both Object-oriented and functional programming model</li>
</ul>
<p>That conclusion can be drawn because a new programming language has to target the very widest range of people.</p>
<p>So it sound's like it is possible to use Python, C++, Typescript or Scala without developing a new language then? Well there are other aspects to a language that are still to be addressed in terms of:</p>
<ul>
<li>Syntax (symbols, punctuation, layout)</li>
<li>Ease of getting started but facilitating more advanced concepts</li>
<li>Flow control constraints, error handling (known gotchas)</li>
<li>Type safety and type inferrence (casting, type checking)</li>
<li>Internal state (global variables, coupling and cohesion)</li>
<li>Simplicity (nil/null NaN or <strong>is set</strong>)</li>
<li>Reuse (packaging, modules, dependencies)</li>
</ul>
]]></content:encoded></item></channel></rss>