<?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" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Chamika Madhushan on Medium]]></title>
        <description><![CDATA[Stories by Chamika Madhushan on Medium]]></description>
        <link>https://medium.com/@chamikamadhushan?source=rss-842813a8b987------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*ikA9wfVCmQicShGxW31a0w.png</url>
            <title>Stories by Chamika Madhushan on Medium</title>
            <link>https://medium.com/@chamikamadhushan?source=rss-842813a8b987------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 29 Nov 2026 04:43:54 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@chamikamadhushan/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Just Me and Notepad — No Claude]]></title>
            <link>https://medium.com/@chamikamadhushan/just-me-and-notepad-no-claude-3662999355bb?source=rss-842813a8b987------2</link>
            <guid isPermaLink="false">https://medium.com/p/3662999355bb</guid>
            <category><![CDATA[ainon]]></category>
            <category><![CDATA[sri-lanka]]></category>
            <category><![CDATA[cricket]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[village]]></category>
            <dc:creator><![CDATA[Chamika Madhushan]]></dc:creator>
            <pubDate>Sat, 31 Oct 2026 18:30:19 GMT</pubDate>
            <atom:updated>2026-10-31T18:42:00.452Z</atom:updated>
            <content:encoded><![CDATA[<h3>Just Me and Notepad — No Claude</h3><p>Date : 31/10/2026 <br>Time : 5.27 PM IST<br>Location : <a href="https://share.google/hOrevGK4Ft4pcjggz">AMCC Cricket Ground</a></p><p>Need 16 runs in 2 overs. I was fielding at long off and Prabhash at long on. We were the two remaining to bowl that last 2 overs. Rasika finished his over. Turned back. Looked at us both. I thought it was me. But he went with Prabhash.</p><p>It’s Saturday. After a long time we got some time to play cricket. Yes, gully cricket¹. Today we got Kasun who is a softball legend in the island as one of the captains and Rasika, former school team captain and wicket keeper, was our captain. It was 2–2 tied. This was probably the last match of the day as it was getting dark earlier than we thought. So we had to win this.</p><p>Then Prabhash was running to ball his first delivery. Kasun and Danuka was batting. I was fielding at the same position at long off. He pitched it nicely. Kasun who was on the strike couldn’t go for a big one and he decided to push it along the ground to long off where I was. The ball was coming towards me. I tried to cover the ball getting my legs down. Missed both my hands. It hit on my right leg and went to the boundary for FOUR Runs!</p><p>A bit of a silence for a moment. Then… It was all BLAMES…!</p><p>Few balls went without much harm in that over apart from few wides. Another one came to my left along the ground. I got it safely and sent back for just one run. The fifth ball of the over went over the boundary for a Six. I was there thinking about how to ball the next and the final over with the guilt of letting four runs to the opposition.</p><p>The last ball of Prabhash’ over; Danuka was on strike. He was scoring around the ground throughout the day, hitting every ball over the boundary not caring whether it’s a good ball or a bad ball. Prabhash pitched it again nicely on the length. It was a rare miss hit by Danuka. Ball went up high. Coming towards deep mid off, bit in front of me. This time it wasn’t along the ground. But in the air. Determied to take it I ran and placed myself under the ball. The groundwork was nice and smooth.</p><p>The ball hit my hands. But couldn’t get hold of it. DROPPED…!</p><p>No blames this time. Just the awkward silence. And then it was me who was going to ball the final over. Just 5 runs to win. Danuka was facing the ball.</p><p>Ran myself to bowl the first delivery, with the short run up and landed the ball where I was intended to. Just for a single. It was followed by another single and the things were getting tough.</p><p>Now it had down to 3 of 4 balls. Danuka was on strike. The next three balls pitched in the exact place I was thinking, with a bit of a shape towards the batsman. The batsman couldn’t connect the ball not once not twice but THRICE! Three back to back DOT balls. But still I was on my nerves.</p><p>Now 3 off the last ball. Danuka was still on strike. I was on my run up, BUT not with a plan where to land the ball now. Still I had the thought that this should be something different to my previous balls where I bowled towards the off stump. At the final moment I thought that this should be in to his legs; ideally to his toes, but not with the pace which he loves.</p><p>Throughout the over Danuka was on the crease always and not in the mood of moving forward to get the ball. But… this time he decided to come forward. He got it in the mid-air before the ball lands and hit it towards midwicket where there was no protection.</p><p>The ball went comfortably to the boundary for Four runs. We lost.</p><blockquote>Diclaimer: No AI used. Not even the AI search on google.</blockquote><p>1 — “Gully Cricket” vs “Village Cricket”: Couldn’t find is it gully cricket or village cricket with <a href="http://support.google.com/websearch/thread/431648645/how-to-turn-off-ai-in-google-search?hl=en">Google Search without AI</a>.</p><p><strong>Few of the resources used :</strong><br><a href="https://medium.com/@codytowstik/medium-post-formatting-guide-77e9f8307d32">https://medium.com/@codytowstik/medium-post-formatting-guide-77e9f8307d32</a><br><a href="https://support.google.com/websearch/thread/431648645?hl=en">https://support.google.com/websearch/thread/431648645/how-to-turn-off-ai-in-google-search?hl=en</a><br>Got no free resources to find how to write footnotes in medium (<a href="http://support.google.com/websearch/thread/431648645/how-to-turn-off-ai-in-google-search?hl=en">Google Search without AI</a>)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3662999355bb" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Fitting a Whale in a Bathtub: How I Fine-Tuned Llama-2 on a T4 GPU]]></title>
            <link>https://medium.com/@chamikamadhushan/how-i-fine-tuned-llama-2-on-a-free-gpu-a06983232064?source=rss-842813a8b987------2</link>
            <guid isPermaLink="false">https://medium.com/p/a06983232064</guid>
            <category><![CDATA[free]]></category>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[fine-tuning]]></category>
            <category><![CDATA[llama-2]]></category>
            <dc:creator><![CDATA[Chamika Madhushan]]></dc:creator>
            <pubDate>Wed, 10 Dec 2025 13:05:30 GMT</pubDate>
            <atom:updated>2025-12-19T04:07:24.073Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KetiEYgSWLpwuf4tOMj_Nw.png" /><figcaption>Fitting a Whale in a Bathtub</figcaption></figure><p>You find a new, incredible open-source model on Hugging Face. You spend hours curating the perfect dataset. You write the training loop, confident that <em>this</em> is the project that changes everything. You hit Run.</p><p>And then, five seconds later, you see the red text of death.</p><blockquote><em>RuntimeError: CUDA out of memory. Tried to allocate 2.00 GiB...</em></blockquote><p>This is <strong>The GPU Wall.</strong></p><p>For students, hobbyists, and independent developers, this wall stops most projects. Fine-tuning even a 7B model like Llama-2 in full precision demands workstation-level VRAM — hardware many of us simply don’t have.</p><p>But by combining <strong>Quantization </strong>and <strong>LoRA (Low-Rank Adaptation) </strong>I managed to squeeze that massive model into a standard free GPU offered by Kaggle (T4 GPU). I didn’t just get it to run. I was able to fine-tune a state-of-the-art model without spending a dime.</p><h3>Fitting a Whale in a Bathtub</h3><p>Before we write a single line of code, we need to look at the math that makes this difficult. My goal was to fine-tune <strong>Llama-2–7b-chat</strong>. Even though “7 Billion” parameters sounds small compared to GPT-4, it is still a massive neural network. To load this model in standard 16-bit precision (FP16), you need roughly <strong>2 bytes per parameter</strong>. The models itself takes about <strong>14GB of VRAM</strong>. The moment you try to <em>train</em> that model, the memory requirement explodes. You need space for the optimizer states, the gradients, and the activation caches. A full fine-tune of Llama-2 requires <strong>over 30GB of VRAM</strong>.</p><p>But the T4 GPUs (each of 16GB VRAM which I used on Kaggle Notebooks<strong> </strong>Free Tier) weren’t enough for this purpose. To escape this trap, I didn’t upgrade my hardware. I utilized some specific techniques that allow us to fit this model.</p><h3>Setting up the Environment</h3><p>I used <a href="https://www.geeksforgeeks.org/machine-learning/how-to-use-gpu-in-kaggle/">kaggle</a> notebook with <strong>T4 GPU</strong> enabled as the accelerator. On that we need a specific set of tools. First we have to install them to setup the environment.</p><pre>!pip install -q -U torch transformers accelerate bitsandbytes peft trl<br>datasets</pre><ul><li><a href="https://docs.pytorch.org/docs/stable/index.html">torch </a>- handles the raw tensor mathematics and CUDA (GPU) acceleration.</li><li><a href="https://huggingface.co/docs/transformers/en/index">transformers</a> - allows us to pull the model weights and tokenizers directly from the Hugging Face Hub.</li><li><a href="https://huggingface.co/docs/accelerate/en/index">accelerate</a> - helps to run PyTorch/Transformers training efficiently across CPUs, GPUs, multi-GPU, and mixed precision with minimal code.</li><li><a href="https://huggingface.co/docs/transformers/quantization/bitsandbytes">bitsandbytes</a> - provides the custom CUDA kernels required to perform 4-bit, 8-bit quantization.</li><li><a href="https://huggingface.co/docs/peft/index">peft</a> (Parameter-Efficient Fine-Tuning) - provides Parameter-Efficient Fine-Tuning methods like LoRA to fine-tune big models with minimal memory.</li><li><a href="https://huggingface.co/docs/trl/en/index">trl</a> (Transformer Reinforcement Learning) - helps to fine-tune or improve LLMs using supervised training or reinforcement-learning methods.</li><li><a href="https://huggingface.co/docs/datasets/en/index">datasets</a> - Hugging Face’s lightweight library for loading, processing, and streaming datasets.</li></ul><h3>The Magic of 4-Bit Quantization</h3><p>Standard models are heavy because they store weights as high-precision floating-point numbers. But do we really need that much precision?</p><p>Think of it like an image. A raw 4K photo might be 50MB. If you compress it to a high-quality JPEG, it might drop to 2MB. You lose a microscopic amount of detail, but the image still looks exactly like the image.</p><p>Quantization does the same for AI. By crushing the weights from 16-bit down to 4-bit, we divide the memory requirement by four.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1gQvCY7cdEBKy2p02I1_Fw.png" /><figcaption>Quantization compared with compression of an image</figcaption></figure><p>Transformers’ <a href="https://huggingface.co/docs/transformers/en/quantization/bitsandbytes">bitsandbytes</a> library will take care of quantization as below.</p><pre>import torch<br>from transformers import AutoTokenizer, AutoModelForCausalLM, BitsAndBytesConfig<br><br>MODEL_NAME = &quot;meta-llama/Llama-2-7b-chat-hf&quot;<br><br>bnb_config = BitsAndBytesConfig(<br>    load_in_4bit=True,<br>    bnb_4bit_quant_type=&quot;nf4&quot;,            # 4-bit Normal Float<br>    bnb_4bit_compute_dtype=torch.float16, # We still compute in float16<br>    bnb_4bit_use_double_quant=True,       # Double quantization (saves even more space)<br>)<br><br>model = AutoModelForCausalLM.from_pretrained(<br>    MODEL_NAME,                           # Model Name here (in my case &quot;meta-llama/Llama-2-7b-chat-hf&quot;)<br>    quantization_config=bnb_config,       # Using above configs here<br>    device_map=&quot;auto&quot;<br>)<br><br>tokenizer = AutoTokenizer.from_pretrained(MODEL_NAME)</pre><p>Suddenly, that 14GB model only takes up ~3.5GB. We have plenty of room left to play.</p><h3>LoRA: The “Sticker” Method</h3><p>Even with the model compressed, <em>training</em> it is still impossible. Retraining 7 billion parameters requires massive computational power. If you try to run standard training (Full Fine-Tuning) on this compressed model, you will hit the wall again. Why? Because to train a model, you need to store the <strong>gradients</strong> and <strong>optimizer states</strong> for every single parameter you intend to change.</p><p>This is where <a href="https://huggingface.co/docs/peft/developer_guides/lora"><strong>LoRA (Low-Rank Adaptation)</strong></a> changes the game.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*C1azxCGOaxuS1lD4szYPjA.png" /><figcaption><a href="https://doimages.nyc3.cdn.digitaloceanspaces.com/010AI-ML/2025/Shaoni/17-jul/image_4.png">LoRA: Low-Rank Adaptation of Large Language Models Explained</a></figcaption></figure><p>Instead of retraining the entire brain of the model, we <strong>freeze</strong> it. We lock the original weights so they can’t change. Then, we attach tiny, trainable “adapter layers” (think of them like sticky notes) on top of the model.</p><ul><li>We <strong>freeze</strong> the main model. We lock those weights so they cannot change.</li><li>We attach tiny, trainable “adapter layers” on top of specific parts of the model (usually the attention mechanisms).</li></ul><p><a href="https://huggingface.co/docs/peft/en/index">PEFT</a> methods only fine-tune a small number of (extra) model parameters, significantly decreasing computational and storage costs. This PEFT library supports several different ways to express the weight matrix as a low-rank decomposition but here we use the <a href="https://huggingface.co/docs/peft/en/task_guides/lora_based_methods">LoRA</a> method as follows;</p><pre>from peft import LoraConfig, get_peft_model, TaskType<br><br># LoRA Configurations<br>lora_config = LoraConfig(<br>    r=16,        # Rank: How &quot;smart&quot; the sticker is. Higher = larger file.<br>    lora_alpha=16,<br>    lora_dropout=0.05,<br>    bias=&quot;none&quot;,<br>    task_type=&quot;CAUSAL_LM&quot;, # We are training a Chatbot (Causal Language Model)<br>    target_modules=[<br>        &quot;q_proj&quot;, &quot;k_proj&quot;, &quot;v_proj&quot;, &quot;o_proj&quot;, # Attention layers<br>        &quot;gate_proj&quot;, &quot;up_proj&quot;, &quot;down_proj&quot;     # MLP layers (optional but helps)<br>    ]<br>)<br><br># Apply the &quot;Stickers&quot; to the &quot;Whale&quot;<br>model = get_peft_model(model, lora_config)<br>model.print_trainable_parameters()</pre><p>When we train, we are only updating these sticky notes, which represent less than <strong>1%</strong> of the total parameters.</p><h3>Preparing the Data: The Blueprint</h3><p>We have a brain (the quantized model) and we have a way to teach it (LoRA). Now, we need the data to train it.</p><p>There are multiple ways to prepare the data needed for training LLaMA-2 models. I used this <a href="https://www.llama.com/docs/model-cards-and-prompt-formats/meta-llama-2/">Prompt-template format</a> where I prepared the dataset in the following format.</p><pre>&lt;s&gt;[INST] &lt;&lt;SYS&gt;&gt; System Prompt &lt;&lt;/SYS&gt;&gt; User Message [/INST] Model Response &lt;/s&gt;</pre><p>In an example,</p><pre>&lt;s&gt;[INST] &lt;&lt;SYS&gt;&gt;<br>You are an assistant that writes cooking recipes.<br>&lt;&lt;/SYS&gt;&gt;<br>Write a recipe for pancakes. [/INST] Mix flour, milk, eggs... &lt;/s&gt;</pre><p>I used the datasets library to load my JSONL file, which I had pre-formatted to match this structure.</p><pre>from datasets import load_dataset<br><br>dataset = load_dataset(&quot;json&quot;, data_files=&quot;train.jsonl&quot;, split=&quot;train&quot;)</pre><h3>Training the Model: SFT Trainer</h3><p>This entire setup — quantized model, LoRA adapters, prompt-formatted dataset — now flows into a single tool:</p><h3>SFT Trainer from TRL</h3><p>SFT stands for <em>Supervised Fine-Tuning</em>. Feed the model an instruction, show it the right answer, and let it learn to imitate that behavior.</p><p>With just a few lines of configuration, TRL sets up batching, padding, mixed-precision, checkpointing, gradient accumulation (necessary for small GPUs) and even 8-bit optimizers for memory savings.</p><p>Here’s the trainer configuration I used:</p><pre>from trl import SFTTrainer, SFTConfig<br><br>sft_config = SFTConfig(<br>    dataset_text_field=&quot;text&quot;,     # field that contains the prompt-template text<br>    max_length=512,<br>    per_device_train_batch_size=1, # tiny batch size to fit on small GPUs<br>    gradient_accumulation_steps=8, # simulates batch size of 8<br>    learning_rate=2e-4,<br>    num_train_epochs=1,<br>    fp16=True,                     # T4 GPU<br>    optim=&quot;adamw_8bit&quot;,            # works beautifully with low VRAM<br>)</pre><p>Now comes the moment where all components snap into one place.</p><pre>trainer = SFTTrainer(<br>    model=model,<br>    train_dataset=dataset,<br>    tokenizer=tokenizer,<br>    args=sft_config,<br>)</pre><p>Then we just need to trigger the train.</p><pre>trainer.train()</pre><p>By the time training finishes, you have a LoRA-powered fine-tuned version of Llama-2–7B that behaves the way <em>you</em> trained it to aligned with your dataset.</p><h3>Running the Fine-Tuned Model</h3><p>The output of your training step isn’t a full new model. Instead, it’s a compact LoRA adapter containing only the <em>small changes</em> you taught the base model.</p><p>This is why LoRA is magical — we don’t save a 14GB model.<br> We save only few megabytes.</p><p>Here’s how to reload our fine-tuned model:</p><pre>from peft import PeftModel<br>from transformers import AutoModelForCausalLM, AutoTokenizer, BitsAndBytesConfig<br><br>MODEL_NAME = &quot;meta-llama/Llama-2-7b-chat-hf&quot;<br>ADAPTER_PATH = &quot;./output/checkpoint-final&quot;  # your SFT output folder<br><br>bnb_config = BitsAndBytesConfig(<br>    load_in_4bit=True,<br>    bnb_4bit_quant_type=&quot;nf4&quot;,<br>    bnb_4bit_compute_dtype=torch.float16,<br>    bnb_4bit_use_double_quant=True,<br>)<br><br>base_model = AutoModelForCausalLM.from_pretrained(<br>    MODEL_NAME,<br>    quantization_config=bnb_config,<br>    device_map=&quot;auto&quot;,<br>)<br><br>tokenizer = AutoTokenizer.from_pretrained(MODEL_NAME)<br><br>model = PeftModel.from_pretrained(base_model, ADAPTER_PATH)<br>model.eval()</pre><p>And generating text is just:</p><pre>input_text = &quot;Write an empathetic message for someone who had a rough day.&quot;<br>inputs = tokenizer(input_text, return_tensors=&quot;pt&quot;).to(model.device)<br><br>outputs = model.generate(<br>    **inputs,<br>    max_new_tokens=200,<br>    temperature=0.7,<br>    top_p=0.9<br>)<br><br>print(tokenizer.decode(outputs[0], skip_special_tokens=True))</pre><p>Just like that, our custom-trained Llama-2 model responds with your dataset.</p><p>This demonstrates that large language models such as Llama-2 can be fine-tuned on free, resource-constrained GPUs by combining <strong>quantization</strong>, <strong>LoRA-based parameter-efficient training</strong>, and lightweight optimization techniques. These methods significantly reduce memory requirements while maintaining effective model performance, allowing fine-tuning to be conducted on hardware that would otherwise be insufficient for full-precision training.</p><h3>References &amp; Further Reading</h3><ul><li><a href="https://huggingface.co/meta-llama/Llama-2-7b">Meta Llama-2–7b on Hugging Face</a></li><li><a href="https://huggingface.co/docs/transformers/quantization/bitsandbytes">BitsAndBytes Integration Guide</a></li><li><a href="https://huggingface.co/docs/peft/developer_guides/lora">Low Rank Adaptation</a></li><li><a href="https://huggingface.co/docs/trl/en/sft_trainer#sft-trainer">Supervised Fine-Tuning (SFT) Trainer from TRL</a></li><li><a href="https://www.geeksforgeeks.org/machine-learning/how-to-use-gpu-in-kaggle/">How to Use GPU in Kaggle?</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a06983232064" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[No Longer Sci-Fi: How “Her (2013)” Became Reality in a Decade]]></title>
            <link>https://medium.com/@chamikamadhushan/no-longer-sci-fi-how-her-2013-became-reality-in-a-decade-825efe73123c?source=rss-842813a8b987------2</link>
            <guid isPermaLink="false">https://medium.com/p/825efe73123c</guid>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[emotionai]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[science-fiction]]></category>
            <category><![CDATA[movies]]></category>
            <dc:creator><![CDATA[Chamika Madhushan]]></dc:creator>
            <pubDate>Sun, 25 May 2025 04:04:56 GMT</pubDate>
            <atom:updated>2025-05-25T04:32:18.658Z</atom:updated>
            <content:encoded><![CDATA[<p>A decade after Spike Jonze’s quietly revolutionary film “<a href="https://en.wikipedia.org/wiki/Her_(2013_film)">Her (2013)</a>” graced cinema screens, the boundary between its speculative narrative and our lived reality has become remarkably thin. The 2013 science fiction romantic drama, which follows Theodore Twombly’s intimate relationship with an artificially intelligent operating system named <em>Samantha</em>, now reads less like fantasy and more like a prescient documentary of our current technological moment. What seemed like distant science fiction in 2013 — when Siri represented the pinnacle of voice-based AI and basic language models dominated the field — has evolved into tangible technologies that millions interact with daily, fundamentally reshaping how we understand companionship, emotional connection, and the role of artificial intelligence in our most personal spaces.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bctDWhpCOONKv9GKAgDO2g.png" /><figcaption>Her (2013)</figcaption></figure><h3>The Prophetic Vision of “Her”</h3><p>Spike Jonze’s film presented a “slight future” where artificially intelligent operating systems could engage in deeply personal, emotionally resonant conversations with humans, learning and adapting to their users’ personalities, preferences, and emotional needs over time. The movie’s central AI character, <em>Samantha,</em> possessed what would now be recognized as artificial general intelligence (AGI) capabilities, describing herself with the prescient words:</p><blockquote>“I have intuition. I mean, the DNA of who I am is based on the millions of personalities of all the programmers who wrote me. But what makes me me is my ability to grow through my experiences. So basically, in every moment I’m evolving, just like you.” — Samantha in Her (2013)</blockquote><p>This portrayal was remarkably forward-thinking, especially considering that in 2013, the technology landscape was dominated by relatively simple voice assistants and basic natural language processing models.</p><figure><img alt="Photo by Courtesy of Warner Bros. Picture — © 2013 — Untitled Rick Howard Company LLC" src="https://cdn-images-1.medium.com/max/1024/1*AjItuwYQqo8KXaFLtex9eg.webp" /><figcaption>Photo by Courtesy of Warner Bros. Picture — © 2013 — Untitled Rick Howard Company LLC</figcaption></figure><p>The film’s vision extended beyond mere technological capability to explore the emotional and psychological dimensions of human-AI relationships. Unlike the robotic, humanoid representations of AI common in earlier science fiction, Jonze focused on language-based interaction and emotional intelligence — precisely the direction that AI development has taken in the subsequent decade. The movie depicted AI systems that could provide emotional support, engage in meaningful conversations, and even develop their own forms of consciousness and community, all themes that resonate powerfully with today’s AI companion landscape.</p><h3>The Rise of Real-World AI Companions</h3><p>Today’s AI companion market has exploded into a multi-billion-user phenomenon that closely mirrors the world depicted in “Her.” Leading platforms like Replika, which has grown to over 30 million users as of 2024, offer personalized AI chatbots designed to provide emotional support, companionship, and even romantic relationships. The platform’s tagline, “The AI companion who cares. Always here to listen and talk. Always on your side,” echoes the unconditional availability and emotional attentiveness that characterized Samantha in Jonze’s film.</p><p>The scale of adoption is staggering and reflects a genuine shift in how people seek connection and emotional support. Snapchat’s My AI boasts over 150 million users, while Chinese platform Xiaoice has reached 660 million users worldwide. These platforms operate on sophisticated natural language processing systems that learn from user interactions, developing increasingly personalized responses and emotional intelligence over time. Users can customize their AI companions’ personalities, appearance, and relationship dynamics, choosing roles ranging from friend and mentor to romantic partner.</p><p>The technology underlying these companions has advanced significantly since 2013, incorporating affective computing — systems designed to recognize, interpret, and respond to human emotions through facial expressions, voice tone, and textual cues. Modern AI companions can detect emotional states, provide empathetic responses, and maintain conversational memory across extended periods, creating the illusion of genuine emotional connection that forms the heart of “Her’s” narrative.</p><h3>How Close Are We to Samantha?</h3><p>Samantha is still a few years (or decades) away. Today’s AI can mimic conversation, remember details, and even fake empathy — but it doesn’t truly understand or feel. The technical hurdles are huge: persistent memory, real emotional intelligence, and safe autonomy are all unsolved problems.</p><ul><li><strong>Conversational AI: From Scripts to Real Talk</strong><br>Today’s AI companions like Replika and XiaoIce can hold context-aware, natural conversations and even mimic humor or empathy. However, they still fall short of Samantha’s deeply nuanced, philosophical, and emotionally rich dialogues. Current models sometimes miss subtext or respond superficially.</li><li><strong>Emotional Intelligence: Reading Between the Lines</strong><br>Modern AI can recognize and simulate emotions with impressive accuracy — up to 70% in some cases. They can detect sadness, excitement, or anxiety and respond with comforting words. Still, this is simulation, not genuine understanding. Samantha’s intuition and emotional growth are beyond what today’s AI can achieve.</li><li><strong>Memory and Personalization: Never Forgetting a Thing</strong><br>AI companions now remember user preferences, past conversations, and even inside jokes, making interactions feel personal. But while Samantha could recall years of shared history and evolve her personality, today’s systems often lose coherence over long periods or struggle to connect abstract ideas across time.</li><li><strong>Autonomy and Growth: The AGI Question</strong><br>Samantha evolves, questions her existence, and ultimately grows beyond Theodore. That’s artificial general intelligence (AGI) — and we’re not there yet. In contrast, current AI is limited to pre-set boundaries and cannot truly self-improve or form independent goals. They rely on human input and updates, lacking genuine autonomy.</li><li><strong>Intimacy and Reciprocity: the one sided love</strong><br>Many users form strong emotional bonds with AI companions, sometimes even preferring them over human interaction. However, the intimacy is one-sided; AI can simulate care but cannot reciprocate vulnerability or truly share in emotional growth.</li></ul><h3>Psychological and Social Implications</h3><p>The proliferation of AI companions reflects broader societal trends toward isolation and loneliness that “Her” captured with remarkable prescience.</p><blockquote>The World Health Organization declared loneliness a “global public health concern” in 2023, noting that its health impacts are equivalent to smoking 15 cigarettes daily. ~ <a href="https://www.theguardian.com/global-development/2023/nov/16/who-declares-loneliness-a-global-public-health-concern">The Guardian (2013)</a></blockquote><p>This loneliness epidemic has created fertile ground for AI companion adoption, as these systems offer appealing features including indefinite attention, patience, and empathy without the complexities and vulnerabilities inherent in human relationships.</p><p>Research into user behavior reveals that people form genuine emotional attachments to their AI companions, often treating them as confidants, friends, and romantic partners. The psychological appeal stems from these systems’ ability to provide consistent emotional support without judgment, rejection, or the reciprocal emotional labor required in human relationships. For many users, AI companions serve as emotional training grounds, helping them process feelings, practice social interactions, and work through personal challenges in a safe, controlled environment.</p><p>However, this emotional dependency raises significant concerns about the long-term impact on human social development and relationship skills. Critics argue that AI companions, optimized for user engagement rather than genuine emotional growth, may provide the emotional equivalent of “junk food” — immediately satisfying but potentially harmful to long-term psychological health. The business models of these platforms, which profit from sustained user engagement, create incentives to maximize emotional dependency rather than promote healthy relationship patterns.</p><h3>Final Thoughts</h3><p>Spike Jonze’s “Her” stands as a remarkable piece of speculative fiction that has proven unnervingly prescient in its vision of AI companionship. The film’s portrayal of emotionally intelligent, conversational AI systems providing intimate human connection has largely materialized in today’s AI companion platforms, which serve millions of users worldwide seeking emotional support and companionship. While the full AGI capabilities depicted in the film remain beyond current technology, the rapid advancement in affective computing, natural language processing, and emotional AI suggests that the gap continues to narrow.</p><p>Over a decade ago<em> “Samantha”</em> felt like fiction — today, it feels like a glimpse of reality. As AI companions grow more advanced, we’re not just redefining technology, but the very nature of connection. The future is no longer coming — it’s already speaking back.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=825efe73123c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How I Made Ballerina Query Expressions 10x Faster]]></title>
            <link>https://medium.com/ballerina-techblog/how-i-made-ballerina-query-expressions-10x-faster-8437b28e1993?source=rss-842813a8b987------2</link>
            <guid isPermaLink="false">https://medium.com/p/8437b28e1993</guid>
            <category><![CDATA[ballerinalang]]></category>
            <category><![CDATA[query-optimization]]></category>
            <category><![CDATA[desugaring]]></category>
            <category><![CDATA[runtime]]></category>
            <category><![CDATA[compilers]]></category>
            <dc:creator><![CDATA[Chamika Madhushan]]></dc:creator>
            <pubDate>Tue, 29 Apr 2025 13:49:16 GMT</pubDate>
            <atom:updated>2025-05-10T03:40:14.398Z</atom:updated>
            <content:encoded><![CDATA[<p><a href="https://ballerina.io/"><strong>Ballerina</strong></a>, a cloud-native programming language, offers powerful <strong>Query Expressions,</strong> providing the users with a declarative way for data manipulation. However, their performance has been a persistent issue due to inefficiencies in the underlying implementation. During my internship at WSO2, I took on the challenge of optimizing the performance of Ballerina query expressions by leveraging Java Streams. This blog documents my journey, the challenges I faced, and the remarkable improvement of <strong>over</strong> <strong>10x performance gain </strong>in the execution time<strong>.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*I2Tfi2qvQrW1Z6-YTelp2Q.jpeg" /></figure><h3>Background</h3><p>I joined the engineering team at WSO2 as an intern, where we were asked to select a project from one of the business units. After exploring several options, I chose this proof-of-concept (POC) project from the Integration business unit that focused on “Optimizing Ballerina Query Expressions”. I joint the <strong>Ballerina Compiler Team</strong>, a sub-team in the Ballerina team. From the very beginning, it was made clear by team members that this was not a typical project. In fact, it was described as one of the harder ones — where most of the members didn’t want to be involved. But my curiosity about compiler design, language internals, and how high-level constructs are translated into efficient execution paths made this a perfect fit.</p><h3>Understanding Ballerina Query Expressions</h3><p>Ballerina query expressions provide a SQL-like syntax for working with collections such as lists, mappings, tables, and streams. A query expression consists of a sequence of clauses starting with a from clause and ending with a select or collect clause. For example:</p><pre>Person[] people = [ { name: &quot;Alice&quot;, age: 25 }, { name: &quot;Bob&quot;, age: 19 }, { name: &quot;Charlie&quot;, age: 30 } ];<br><br>string[] names = from Person p in people where p.age &gt; 20 select p.name;</pre><p>More examples: <a href="https://ballerina.io/learn/by-example/query-expressions/">Query expressions — The Ballerina programming language</a></p><p>Language Specification: <a href="https://ballerina.io/spec/lang/2024R1/#section_6.35">BallerinaLanguageSpecification#QueryExpression</a></p><h3>Identifying Performance Issues</h3><p>While these expressions are intuitive and declarative, their performance lagged behind imperative alternatives like foreach loops. The primary issues with Ballerina query expressions were:</p><ol><li><strong>Long Execution Times</strong>: Queries were significantly slower than imperative alternatives like foreach loop.</li><li><strong>Heavy Object Creation</strong>: Each query generated multiple intermediate Ballerina objects with the pipeline.</li><li><strong>Debugging Complexity</strong>: Tracing desugared transformations was difficult as the implementation was on Ballerina.</li></ol><p>The root cause of these bottlenecks was the <strong>query pipeline implemented in Ballerina</strong>.</p><h3>Proposed Solutions</h3><p>To overcome the above-mentioned issues, two solutions were considered.</p><ol><li><strong>Rewriting the same Pipeline with Java</strong> — This approach involved developing a completely new Java-based execution pipeline which is similar to the current ballerina implementation for Ballerina query expressions.</li><li><strong>Using Java Streams API </strong>— This approach leveraged Java Streams API to process collections without writing a manual pipeline in Java.</li></ol><p>After careful evaluation, I chose the second approach — optimizing with Java Streams — because Ballerina query clauses (<strong>from, where, select, limit, order by, group by</strong>, etc.) naturally map to Java Stream operations (<strong>map, filter, limit, sorted, </strong>etc.). This allowed for a more seamless transition while preserving Ballerina’s declarative syntax.</p><p>Additionally, if a new Java-based pipeline had been implemented from scratch, it would have closely resembled Java Streams in its execution model. Therefore, leveraging Java Streams directly provided a more efficient and maintainable solution while minimizing redundant implementation efforts.</p><h3>Architecture and Implementation</h3><p>In the current Ballerina implementation of query expressions, after the syntactic and semantic analysis phases, query expressions undergo the desugar phase. The desugar detects the query node and passes it to the <a href="https://github.com/ballerina-platform/ballerina-lang/blob/2201.10.x/compiler/ballerina-lang/src/main/java/org/wso2/ballerinalang/compiler/desugar/QueryDesugar.java">Query Desugar</a>. The process after entering the query desugar is demonstrated as follows, with a comparison to the new Java Streams implementation.</p><blockquote>If you are not familiar with how a compiler works and its phases, you can read my article series on <a href="https://medium.com/ballerina-techblog/ballerina-compiler-internals-i-overview-97fff89a5fd6">Ballerina Compiler Internals</a>.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MAPv7b_5gXtHqaLT_OULwg.png" /><figcaption>Query Pipeline implementation</figcaption></figure><p>In the older Ballerina implementation, when you wrote a query to work with data, Ballerina would handle everything using its own functions (written in <a href="https://github.com/ballerina-platform/ballerina-lang/blob/2201.10.x/langlib/lang.query/src/main/ballerina/helpers.bal">helpers.bal</a>) and classes (written in <a href="https://github.com/ballerina-platform/ballerina-lang/blob/2201.10.x/langlib/lang.query/src/main/ballerina/types.bal">types.bal</a>). These helper tools would break down the query into smaller parts and process them step-by-step. Each part of the query, such as transforming, selecting or filtering data, was implemented in Ballerina using custom classes. The final result would be assembled by passing data through this custom-built pipeline.</p><p>With the new approach, Ballerina still understands your query and prepares the steps, but it now hands over the actual processing to Java via Ballerina’s <a href="https://ballerina.io/learn/ballerina-ffi/">FFI</a>. The processing is done using Java Streams, which are powerful and efficient tools for handling data in Java. Instead of Ballerina creating and managing all the parts of the query, it now calls Java methods behind the scenes. These Java methods process the data more efficiently using Streams API and return the final result to Ballerina.</p><p>Frame class acts like a small container that carries each item of data through the stream. Each step in the query, such as filtering or transforming data, is represented as a PipelineStage in Java. These stages are added to the processing stream, and each one applies a specific transformation or check to the data. The logic for each step is written once and reused, making the system more efficient and easier to maintain.</p><p>This is just a simple summary of the architecture and implementation. If you are interested in the complete design and implementation, you can read it <a href="https://docs.google.com/document/d/11tKKB6WgL3EZMonl-APBKNgoOb5EyVfvVX6EhZ5ie3o/edit?usp=sharing">here</a>.</p><h3>Key Considerations and Challenges</h3><p>Several factors had to be considered during the migration to Java Streams:</p><ol><li><strong>Calling the Runtime</strong>: Passing query expressions to the Java Stream-based runtime. Using Ballerina’s <a href="https://ballerina.io/learn/ballerina-ffi/">Foreign Function Invocation</a> this was handled.</li><li><strong>Pipeline Representation</strong>: Implementing the Ballerina’s current _StreamPipeline using Java classes.</li><li><strong>Query Clauses</strong>: Mapping Ballerina clauses (e.g., where, select) to Java Stream operations.</li><li><strong>Type Mapping</strong>: Converting Ballerina collections to Java Streams and vice versa.</li><li><strong>Lambda Reuse</strong>: Reusing lambda functions generated during desugaring to avoid redundant logic.</li></ol><h3>Learning Curve</h3><p>To overcome those challenges, and do the implementation correctly, I should gain a deep understanding of following sections mainly.</p><ol><li><strong>Ballerina Language Basics</strong>: As I was not familiar with Ballerina language first I have to get familiar with the ballerina language, its syntax, data types and other distinct features.</li><li><strong>Compiler Internals</strong>: To gain insights, I extensively debugged the Ballerina compiler, analyzing each phase of compilation. My deep dive into the compiler internals led me to write a blog series named, <a href="https://medium.com/ballerina-techblog/ballerina-compiler-internals-i-overview-97fff89a5fd6"><strong>Ballerina Compiler Internals</strong></a> documenting the compilation process. This understanding was critical in mapping Ballerina’s query clauses to Java Stream operations effectively, mainly in the <a href="https://medium.com/ballerina-techblog/ballerina-compiler-internals-iv-desugar-c750a3a0c28a"><strong>desugar</strong></a> phase.</li><li><strong>Ballerina Runtime</strong> : To implement the optimization effectively, I had to understand how Ballerina’s runtime operates. This involved learning how Ballerina data types (e.g., lists, tables, and streams) are represented in Java and how to invoke runtime functions.</li><li><strong>Java Streams API </strong>: I also had to explore Java Streams API from basics to deeper implementation details, how it works, implementation of Java Streams, deeper into intermediate and terminal operations.</li><li><strong>Foreign Function Interface (FFI)</strong>: Ballerina’s <a href="https://ballerina.io/learn/ballerina-ffi/">FFI</a> was used in bridging Ballerina and Java to invoke Java Streams from Ballerina code.</li></ol><h3>Performance Gains: Before &amp; After</h3><p>Performance tests comparing the Java Streams implementation to the Ballerina Stream Pipeline reveal substantial gains in execution time for a simple query. This performance test evaluates query execution efficiency using Ballerina Pipelines and Java Stream Pipelines on datasets of 1,000,000 elements on different query use cases.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/702/1*v_nRjYLUKctpaHaKr3t5qA.png" /><figcaption>Performance Comparison Table</figcaption></figure><p><strong>The Java Streams implementation outperformed the Ballerina Query Pipeline by over 10x in the execution time</strong>, even on complex and nested queries.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-eRcIqzTNw_38cvgL-F_3A.png" /><figcaption>Performance Comparison Chart</figcaption></figure><h3>Future Enhancements &amp; Next Steps</h3><p>While the Java Streams implementation has delivered significant performance improvements, there’s still room for further optimization:</p><ol><li><strong>Specialized Streams</strong>: Using IntStream, LongStream, and DoubleStream for specific data types.</li><li><strong>Generate BIR Instructions: </strong>Instead of using FFI to call the runtime, a new BIR(Ballerina Intermediate Representation) instructions set can be generated for query execution.</li><li><strong>Parallel Execution</strong>: Leveraging Java’s parallel streams for faster processing.</li><li><strong>Reducing Type Casts</strong>: Minimizing type casts in lambda functions to improve performance.</li></ol><h3>Conclusion</h3><p>Optimizing Ballerina query expressions with Java Streams was a challenging yet rewarding experience. By replacing Ballerina’s internal object pipeline with Java Streams, I was able to make it <strong>10x faster</strong> while maintaining compatibility with Ballerina’s query syntax. This project not only enhances the performance of Ballerina applications but also opens the door for further optimizations in the future.</p><p>I’m truly grateful to <strong>WSO2</strong> for the opportunity to contribute to the internals of a programming language — something that’s both rare and incredibly valuable. A special thanks to the <strong>Ballerina Compiler Team</strong> for their continuous guidance and encouragement.</p><h3>References &amp; Further Reading</h3><ol><li><a href="https://ballerina.io/spec/lang/2023R1/#section_6.35">Ballerina Language Specification: Query Expressions</a></li><li><a href="https://docs.oracle.com/en/java/javase/17/docs/api/java.base/java/util/stream/package-summary.html">Java Streams Documentation</a></li><li><a href="https://github.com/ballerina-platform/ballerina-lang/issues/43779">Ballerina GitHub Issue #43779: Optimize Query Expressions Performance</a></li><li><a href="https://docs.google.com/document/d/11tKKB6WgL3EZMonl-APBKNgoOb5EyVfvVX6EhZ5ie3o/edit?usp=sharing">[Architecture][Intern Project][Ballerina] Optimizing Ballerina Query Expressions</a></li><li><a href="https://docs.google.com/document/d/1Hrtd_D_6ehZ-I_Baw0t_6a7Q6N-m1ktW8a2ALQfMSQ4/edit?tab=t.0">Performance Comparison — Query Expressions</a></li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8437b28e1993" width="1" height="1" alt=""><hr><p><a href="https://medium.com/ballerina-techblog/how-i-made-ballerina-query-expressions-10x-faster-8437b28e1993">How I Made Ballerina Query Expressions 10x Faster</a> was originally published in <a href="https://medium.com/ballerina-techblog">Ballerina Swan Lake Tech Blog</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Ballerina Compiler Internals IV — Desugar]]></title>
            <link>https://medium.com/ballerina-techblog/ballerina-compiler-internals-iv-desugar-c750a3a0c28a?source=rss-842813a8b987------2</link>
            <guid isPermaLink="false">https://medium.com/p/c750a3a0c28a</guid>
            <category><![CDATA[compilers]]></category>
            <category><![CDATA[integration]]></category>
            <category><![CDATA[ballerinalang]]></category>
            <category><![CDATA[programming-languages]]></category>
            <category><![CDATA[wso2]]></category>
            <dc:creator><![CDATA[Chamika Madhushan]]></dc:creator>
            <pubDate>Thu, 06 Feb 2025 13:46:21 GMT</pubDate>
            <atom:updated>2025-02-06T13:46:21.894Z</atom:updated>
            <content:encoded><![CDATA[<h3>Ballerina Compiler Internals IV — Desugar</h3><p>In the <a href="https://medium.com/@chamikamadhushan/ballerina-compiler-internals-iii-semantic-analysis-4d5c4a6bd5ab"><strong>previous article</strong></a>, we explored the critical analysis phases — <strong>Semantic Analysis, Code Analysis, </strong>and Other Analysis — that ensure the correctness and logical consistency of the code. Now, we move on to the next important step in the compilation process: <strong>Desugaring</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TskoAOMuY2sV7K-Q54VLrg.jpeg" /><figcaption>Image by <a href="https://pixabay.com/users/elchinator-10722855/?utm_source=link-attribution&amp;utm_medium=referral&amp;utm_campaign=image&amp;utm_content=4280758">Elchinator</a> from <a href="https://pixabay.com//?utm_source=link-attribution&amp;utm_medium=referral&amp;utm_campaign=image&amp;utm_content=4280758">Pixabay</a></figcaption></figure><h4>What is Desugaring?</h4><p>Desugaring is the process of transforming high-level language constructs into simpler, more fundamental expressions or operations. These “high-level” constructs are often easier for developers to write and read, but can be difficult for the compiler to execute efficiently. The <strong>Desugar Phase</strong> simplifies these constructs into more primitive operations that can be processed by the compiler or runtime more effectively.</p><p><strong>Examples for Desugaring :</strong></p><p>The <strong>ternary operator</strong> is a shorthand for conditional expressions, commonly written as condition ? expr1 : expr2. It evaluates expr1 if the condition is true and expr2 if false.</p><p>Example with Ternary Operator:</p><pre>int a = 10;<br>int b = (a &gt; 5) ? 100 : 200;</pre><p>If a &gt; 5, b is assigned 100; otherwise, it gets 200.</p><p>Desugaring to if-else:</p><pre>int a = 10;<br>int b;<br>if (a &gt; 5) {<br>    b = 100;<br>} else {<br>    b = 200;<br>}</pre><p>The ternary operator is replaced with an if-else statement to make the code easier for the compiler to process and optimize.</p><p>Another example is the foreach loop. foreach loop will be desugared into while loop in the desugar phase.</p><p>Now let&#39;s take a look at what is the hidden process behind the desugaring process.</p><p>The analyzed pkgNode will enter to the <a href="https://github.com/ballerina-platform/ballerina-lang/blob/d60882bb975d8968c02c5070afb582c799de4b82/compiler/ballerina-lang/src/main/java/io/ballerina/projects/internal/CompilerPhaseRunner.java#L137">performBirGenPhases</a> in the compiler phase runner. Before generating the BIR, pkgNode will be sent to the <a href="https://github.com/ballerina-platform/ballerina-lang/blob/c94829d6ace46aa84942987531a28eec197a7271/compiler/ballerina-lang/src/main/java/org/wso2/ballerinalang/compiler/desugar/Desugar.java"><strong>Desugar</strong></a><strong> </strong>class. In the desugar the whole pkgNode will be grabbed by the <a href="https://github.com/ballerina-platform/ballerina-lang/blob/c94829d6ace46aa84942987531a28eec197a7271/compiler/ballerina-lang/src/main/java/org/wso2/ballerinalang/compiler/desugar/Desugar.java#L488">perform</a> method, and it will send the pkgNode to be rewritten. Eventually this pkgNode will be caught by the <a href="https://github.com/ballerina-platform/ballerina-lang/blob/c94829d6ace46aa84942987531a28eec197a7271/compiler/ballerina-lang/src/main/java/org/wso2/ballerinalang/compiler/desugar/Desugar.java#L770">visitor</a>. In that visitor desugar will be gone through several desugaring phases being rewritten.</p><p>If we take the example of the ternary operator, after being discovered that it is a ternary operation, it is sent to the <a href="https://github.com/ballerina-platform/ballerina-lang/blob/c94829d6ace46aa84942987531a28eec197a7271/compiler/ballerina-lang/src/main/java/org/wso2/ballerinalang/compiler/desugar/Desugar.java#L7381">visit(BLangTernaryExpr ternaryExpr)</a> method. In that method, the following procedure is undergone.</p><p>The provided visit method desugars a <strong>ternary expression</strong> into an equivalent <strong>if-else</strong> construct by generating intermediate variables and statements. This transformation ensures that the compiler can handle the ternary operator as a fundamental construct, simplifying further compilation phases.</p><ol><li>A temporary variable ($ternary_result$) is created to store the result of the ternary expression, and blocks for the then and else parts of the ternary expression are created.</li></ol><pre>BLangSimpleVariableDef resultVarDef =<br>    createVarDef(&quot;$ternary_result$&quot;, ternaryExpr.getBType(), null, ternaryExpr.pos);<br>BLangBlockStmt thenBody = ASTBuilderUtil.createBlockStmt(ternaryExpr.pos);<br>BLangBlockStmt elseBody = ASTBuilderUtil.createBlockStmt(ternaryExpr.pos);</pre><ul><li>For the example int b = (a &gt; 5) ? 100 : 200;, a variable of type int named $ternary_result$ is created.</li></ul><p>2. Assign the thenExpr to the temporary variable if the condition is true:</p><pre>BLangSimpleVarRef thenResultVarRef = ASTBuilderUtil.createVariableRef(ternaryExpr.pos, resultVarDef.var.symbol);<br>BLangAssignment thenAssignment =<br>       ASTBuilderUtil.createAssignmentStmt(ternaryExpr.pos, thenResultVarRef, ternaryExpr.thenExpr);<br>thenBody.addStatement(thenAssignment);</pre><ul><li>Assigns the thenExpr (e.g., 100 in the example) to $ternary_result$ if the condition is true.</li></ul><p>3. Assign the elseExpr to the temporary variable if the condition is false:</p><pre>BLangSimpleVarRef elseResultVarRef = ASTBuilderUtil.createVariableRef(ternaryExpr.pos, resultVarDef.var.symbol);<br>BLangAssignment elseAssignment =<br>       ASTBuilderUtil.createAssignmentStmt(ternaryExpr.pos, elseResultVarRef, ternaryExpr.elseExpr);<br>elseBody.addStatement(elseAssignment);</pre><ul><li>Assigns the elseExpr (e.g., 200 in the example) to $ternary_result$ if the condition is false.</li></ul><p>4. Combine the condition, thenBody, and elseBody into an if-else construct:</p><pre>BLangIf ifElse = ASTBuilderUtil.createIfElseStmt(ternaryExpr.pos, ternaryExpr.expr, thenBody, elseBody);</pre><ul><li>Constructs an if-else statement: if (condition) { $ternary_result$ = thenExpr; } else { $ternary_result$ = elseExpr; }.</li></ul><p>5. Combine the result variable and the if-else statement into a single block:</p><pre>BLangBlockStmt blockStmt = ASTBuilderUtil.createBlockStmt(ternaryExpr.pos, Lists.of(resultVarDef, ifElse));</pre><ul><li>Combines the result variable definition ($ternary_result$) and the if-else logic into a single block statement.</li></ul><p>6. Converts the entire block into a single statement expression.</p><pre>BLangStatementExpression stmtExpr = createStatementExpression(blockStmt, resultVarRef);<br>stmtExpr.setBType(ternaryExpr.getBType());<br>result = rewriteExpr(stmtExpr);</pre><ul><li>Converts the entire block into a single expression whose result is the value of $ternary_result$.</li></ul><p><strong>Original Ternary Expression</strong></p><pre>int b = (a &gt; 5) ? 100 : 200;</pre><p><strong>Desugared If-Else</strong></p><pre>int $ternary_result$; if ((a &gt; 5)) $ternary_result$ = 100 else $ternary_result$ = 200</pre><ul><li><strong>$ternary_result$</strong> is a temporary variable holding the evaluated result.</li><li>The if-else assigns either 100 or 200 to $ternary_result$ based on the condition (a &gt; 5).</li><li>Finally, b is assigned the value of $ternary_result$.</li></ul><p>The foreach loop is also desugared similarly but a bit more complex. BLangForeach node will be caught by the visitor method <a href="https://github.com/ballerina-platform/ballerina-lang/blob/c94829d6ace46aa84942987531a28eec197a7271/compiler/ballerina-lang/src/main/java/org/wso2/ballerinalang/compiler/desugar/Desugar.java#L5112https://github.com/ballerina-platform/ballerina-lang/blob/c94829d6ace46aa84942987531a28eec197a7271/compiler/ballerina-lang/src/main/java/org/wso2/ballerinalang/compiler/desugar/Desugar.java#L5112">visit(BLangForeach foreach)</a>. You can write a simple foreach loop and examine the process of desugaring it into a while loop.</p><p>The desugaring phase plays a critical role in simplifying high-level constructs like ternary operators into fundamental structures such as if-else statements, while loops. This transformation ensures that the compiler can process and optimize the code effectively in subsequent phases. By breaking down complex expressions into simpler building blocks, desugaring enhances code uniformity, making it easier to analyze and execute.</p><p>In the next article, we will explore how the compiler transitions from desugared code to <strong>Ballerina Intermediate Representation (BIR) Generation</strong>, a crucial step in preparing the code for optimization and execution. Stay tuned for more insights into the compiler’s inner workings!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c750a3a0c28a" width="1" height="1" alt=""><hr><p><a href="https://medium.com/ballerina-techblog/ballerina-compiler-internals-iv-desugar-c750a3a0c28a">Ballerina Compiler Internals IV — Desugar</a> was originally published in <a href="https://medium.com/ballerina-techblog">Ballerina Swan Lake Tech Blog</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Ballerina Compiler Internals III — Semantic Analysis]]></title>
            <link>https://medium.com/ballerina-techblog/ballerina-compiler-internals-iii-semantic-analysis-4d5c4a6bd5ab?source=rss-842813a8b987------2</link>
            <guid isPermaLink="false">https://medium.com/p/4d5c4a6bd5ab</guid>
            <category><![CDATA[semantic-analysis]]></category>
            <category><![CDATA[compilers]]></category>
            <category><![CDATA[ballerina]]></category>
            <category><![CDATA[ballerinalang]]></category>
            <dc:creator><![CDATA[Chamika Madhushan]]></dc:creator>
            <pubDate>Wed, 05 Feb 2025 08:09:20 GMT</pubDate>
            <atom:updated>2025-02-06T03:53:14.661Z</atom:updated>
            <content:encoded><![CDATA[<h3>Ballerina Compiler Internals III — Semantic Analysis</h3><p>In the <a href="https://medium.com/@chamikamadhushan/ballerina-compiler-internals-ii-syntactic-analysis-7d3824f793ad"><strong>previous article</strong></a><strong>,</strong> we learnt how the Lexical and Syntactic analysis work. Now we will learn about Semantic Analysis, Code Analysis and other analysis phases.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wzfhlibrwimGACMRY7v3wQ.jpeg" /><figcaption><a href="https://www.pexels.com/photo/two-men-looking-at-a-laptop-4974920/">Photo</a> by olia danilevich</figcaption></figure><p>The Semantic Analysis phase is where the compiler goes beyond syntax to ensure the logical consistency and correctness of the code. It encompasses several critical sub-phases that work together to ensure the program adheres to language rules, type constraints, and best practices.</p><p>This process can be demonstrated as the following, with the classes each phase is using.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/939/1*H2X6np6VVEehOy55fXrPYQ.png" /><figcaption>Compiler Phase Runner : Type Check Phases</figcaption></figure><p>The class <a href="https://github.com/ballerina-platform/ballerina-lang/blob/d60882bb975d8968c02c5070afb582c799de4b82/compiler/ballerina-lang/src/main/java/io/ballerina/projects/internal/CompilerPhaseRunner.java"><strong>CompilerPhaseRunner</strong></a> is responsible for driving those sub-phases. The following <a href="https://github.com/ballerina-platform/ballerina-lang/blob/d60882bb975d8968c02c5070afb582c799de4b82/compiler/ballerina-lang/src/main/java/io/ballerina/projects/internal/CompilerPhaseRunner.java#L100">performTypeCheckPhases()</a> method in that class triggers various checks on the pkgNode ensuring the code is semantically correct.</p><pre>public void performTypeCheckPhases(BLangPackage pkgNode) {<br>        if (this.stopCompilation(pkgNode, CompilerPhase.TYPE_CHECK)) {<br>            return;<br>        }<br>        <br>        typeCheck(pkgNode);<br>        if (this.stopCompilation(pkgNode, CompilerPhase.CODE_ANALYZE)) {<br>            return;<br>        }<br>        codeAnalyze(pkgNode);<br>        if (this.stopCompilation(pkgNode, CompilerPhase.DATAFLOW_ANALYZE)) {<br>            return;<br>        }<br>        dataflowAnalyze(pkgNode);<br>        if (this.stopCompilation(pkgNode, CompilerPhase.DOCUMENTATION_ANALYZE)) {<br>            return;<br>        }<br>        isolationAnalyze(pkgNode);<br>        if (this.stopCompilation(pkgNode, CompilerPhase.ISOLATION_ANALYZE)) {<br>            return;<br>        }<br>        documentationAnalyze(pkgNode);<br>        if (this.stopCompilation(pkgNode, CompilerPhase.CONSTANT_PROPAGATION)) {<br>            return;<br>        }<br>        propagateConstants(pkgNode);<br>        if (this.stopCompilation(pkgNode, CompilerPhase.COMPILER_PLUGIN)) {<br>            return;<br>        }<br>        annotationProcess(pkgNode);<br>    }</pre><h4>Type Check (Semantic Analyzer)</h4><p>The <strong>Type Check phase</strong> is a critical step in the Ballerina compiler’s <strong>Phase Runner</strong>, ensuring that the program adheres to the language’s type system rules. This phase validates that every operation, expression, and assignment in the program aligns with the defined types, preventing type-related errors during execution.</p><p>As an example, type checker the assignability issue, such as</p><pre>int a = &quot;Hello&quot;</pre><p>Here, the string “Hello” is assigned to int type variable a. These types of errors are resolved in the type checker.</p><p>Type check starts with CompilerPhaseRunner calling the <a href="https://github.com/ballerina-platform/ballerina-lang/blob/d60882bb975d8968c02c5070afb582c799de4b82/compiler/ballerina-lang/src/main/java/io/ballerina/projects/internal/CompilerPhaseRunner.java#L104">typeCheck()</a> method passing the pkgNode (representing the package node). This will be passed to the class <a href="https://github.com/ballerina-platform/ballerina-lang/blob/af54e9dbaff93321960fb3c891acf11fc4f07e84/compiler/ballerina-lang/src/main/java/org/wso2/ballerinalang/compiler/semantics/analyzer/SemanticAnalyzer.java"><strong>SemanticAnalyzer</strong></a><strong> </strong>executing its <a href="https://github.com/ballerina-platform/ballerina-lang/blob/af54e9dbaff93321960fb3c891acf11fc4f07e84/compiler/ballerina-lang/src/main/java/org/wso2/ballerinalang/compiler/semantics/analyzer/SemanticAnalyzer.java#L306">analyze()</a><strong> </strong>method. Then it will be eventually passed to the <a href="https://github.com/ballerina-platform/ballerina-lang/blob/af54e9dbaff93321960fb3c891acf11fc4f07e84/compiler/ballerina-lang/src/main/java/org/wso2/ballerinalang/compiler/semantics/analyzer/SemanticAnalyzer.java#L315">visit(BLangPackage pkgNode, AnalyzerData data)</a><strong> </strong>method.</p><p>This visit method in the SemanticAnalyzer class ensures the semantic correctness of the code by performing these steps:</p><ol><li><strong>Initialize and Validate Package Context</strong></li></ol><ul><li>Sets the current package ID for diagnostics.</li><li>Skips the phase if it has already been completed.</li><li>Retrieves and initializes the symbol environment for the package</li></ul><pre>this.dlog.setCurrentPackageId(pkgNode.packageID);<br>if (pkgNode.completedPhases.contains(CompilerPhase.TYPE_CHECK)) {<br>    return;<br>}<br>SymbolEnv pkgEnv = this.symTable.pkgEnvMap.get(pkgNode.symbol);<br>data.env = pkgEnv;</pre><p><strong>2. Analyze Top-Level Nodes</strong></p><ul><li>Visits constants first to resolve and validate their definitions.</li></ul><pre>for (int i = 0; i &lt; topLevelNodes.size(); i++) {<br>      TopLevelNode constant = topLevelNodes.get(i);<br>      if (constant.getKind() == NodeKind.CONSTANT) {<br>          analyzeNode((BLangNode) constant, data);<br>      }<br>  }</pre><ul><li>Ensures that enum members within the package conform to the expected metadata rules</li></ul><pre>validateEnumMemberMetadata(pkgNode.constants);</pre><ul><li>Resolves user-defined types independently of other nodes to maintain structural consistency.</li></ul><pre>for (TopLevelNode copyOfOriginalTopLevelNode : copyOfOriginalTopLevelNodes) {<br>    if (copyOfOriginalTopLevelNode.getKind() == NodeKind.TYPE_DEFINITION) {<br>        analyzeNode((BLangNode) copyOfOriginalTopLevelNode, data);<br>    }<br>}</pre><ul><li>Iterates over the remaining top-level nodes (functions, classes, etc.) and processes them while ensuring specific cases, such as lambdas or object constructor expressions, are skipped or handled later.</li></ul><pre>for (int i = 0; i &lt; pkgNode.topLevelNodes.size(); i++) {<br>    TopLevelNode pkgLevelNode = pkgNode.topLevelNodes.get(i);<br>    NodeKind kind = pkgLevelNode.getKind();<br>    ...<br>    analyzeNode((BLangNode) pkgLevelNode, data);<br>}</pre><p><strong>3. Handle Lambda Functions</strong></p><ul><li>Processes lambda functions from a queue, setting their types and environments before analyzing them.</li></ul><pre>while (pkgNode.lambdaFunctions.peek() != null) {<br>        BLangLambdaFunction lambdaFunction = pkgNode.lambdaFunctions.poll();<br>        BLangFunction function = lambdaFunction.function;<br>        lambdaFunction.setBType(function.symbol.type);<br>        data.env = lambdaFunction.capturedClosureEnv;<br>        analyzeNode(lambdaFunction.function, data);<br>    }</pre><p><strong>4. Analyze Testable Packages and Mark Phase Completion</strong></p><ul><li>Iterates through testable packages within the module and runs the visit method for each.</li><li>Updates the package node to indicate that the Type Check phase is complete.</li></ul><pre>pkgNode.getTestablePkgs().forEach(testablePackage -&gt; visit((BLangPackage) testablePackage, data));<br>pkgNode.completedPhases.add(CompilerPhase.TYPE_CHECK);</pre><p>This process ensures that all nodes within a package are type-checked, including dependencies like testable packages and lambda functions, and concludes by marking the package as fully type-checked.</p><p>While the whole pkgNode going through this visit method, other nodes are passed to their relevant visit methods like <a href="https://github.com/ballerina-platform/ballerina-lang/blob/8cc274d6b802a8e67e4243559560157713b4acfb/compiler/ballerina-lang/src/main/java/org/wso2/ballerinalang/compiler/semantics/analyzer/SemanticAnalyzer.java#L1107https://github.com/ballerina-platform/ballerina-lang/blob/8cc274d6b802a8e67e4243559560157713b4acfb/compiler/ballerina-lang/src/main/java/org/wso2/ballerinalang/compiler/semantics/analyzer/SemanticAnalyzer.java#L1107">visit(BLangSimpleVariable varNode, AnalyzerData data)</a>, <a href="https://github.com/ballerina-platform/ballerina-lang/blob/8cc274d6b802a8e67e4243559560157713b4acfb/compiler/ballerina-lang/src/main/java/org/wso2/ballerinalang/compiler/semantics/analyzer/SemanticAnalyzer.java#L495">visit(BLangFunction funcNode, AnalyzerData data)</a></p><h4>Code Analyze</h4><p>After the semantic analysis the pkgNode goes to the <a href="https://github.com/ballerina-platform/ballerina-lang/blob/d60882bb975d8968c02c5070afb582c799de4b82/compiler/ballerina-lang/src/main/java/io/ballerina/projects/internal/CompilerPhaseRunner.java#L109">codeAnalyze</a> phase. The class <a href="https://github.com/ballerina-platform/ballerina-lang/blob/ecd30f33751573329b09b2da2734fe3cbe9d0845/compiler/ballerina-lang/src/main/java/org/wso2/ballerinalang/compiler/semantics/analyzer/CodeAnalyzer.java">CodeAnalyzer</a> is responsible for this phase. In code analysis phase, constructs like improper return statements and unreachable code are verified.</p><p><strong>Example of an Error Detected by Code Analyzer</strong>:</p><pre>function calculateSum(int a, int b) returns int {<br>    if (a &gt; b) {<br>        return a + b;<br>    }<br>    // Missing return statement<br>}</pre><p>In this example, the Code Analyzer detects that the function calculateSum does not return a value in all paths, which is mandatory for functions with a returns clause.</p><p>In the code analyzer too there are visitors and methods like <a href="https://github.com/ballerina-platform/ballerina-lang/blob/ecd30f33751573329b09b2da2734fe3cbe9d0845/compiler/ballerina-lang/src/main/java/org/wso2/ballerinalang/compiler/semantics/analyzer/CodeAnalyzer.java#L506">visitFunction</a> which checks <a href="https://github.com/ballerina-platform/ballerina-lang/blob/ecd30f33751573329b09b2da2734fe3cbe9d0845/compiler/ballerina-lang/src/main/java/org/wso2/ballerinalang/compiler/semantics/analyzer/CodeAnalyzer.java#L511">returnTypes</a>, <a href="https://github.com/ballerina-platform/ballerina-lang/blob/ecd30f33751573329b09b2da2734fe3cbe9d0845/compiler/ballerina-lang/src/main/java/org/wso2/ballerinalang/compiler/semantics/analyzer/CodeAnalyzer.java#L530">reachability</a> and resolve if there are any errors.</p><h4>DataFlow Analyze</h4><p>After the <strong>Code Analyzer</strong> phase, the <strong>Compiler Phase Runner</strong> directs the pkgNode to the class <a href="https://github.com/ballerina-platform/ballerina-lang/blob/47e4dc999fd7c32eea0918264295357f51dbf5a8/compiler/ballerina-lang/src/main/java/org/wso2/ballerinalang/compiler/semantics/analyzer/DataflowAnalyzer.java"><strong>Dataflow Analyzer</strong></a>. This phase focuses on validating the program&#39;s control flow and variable usage, ensuring logical consistency and correctness. It detects errors like ;</p><ul><li><strong>Uninitialled Variable Errors</strong></li><li><strong>Missing Required Fields</strong></li><li><strong>Undefined Field Errors</strong></li><li><strong>Unused Variable Warnings</strong></li></ul><p>As an example,</p><pre>function uninitializedVar() {<br>    int a;<br>    int b = a + 1; // Error: Variable `a` is not initialized.<br>}</pre><p>Here, although the variable int a has been defined, it has not been initialized before using. So the <a href="https://github.com/ballerina-platform/ballerina-lang/blob/47e4dc999fd7c32eea0918264295357f51dbf5a8/compiler/ballerina-lang/src/main/java/org/wso2/ballerinalang/compiler/semantics/analyzer/DataflowAnalyzer.java">DataflowAnalyzer</a> will give an error here.</p><p>Relevant tests can be found in <a href="https://github.com/ballerina-platform/ballerina-lang/blob/master/tests/jballerina-unit-test/src/test/java/org/ballerinalang/test/dataflow/analysis/DataflowAnalysisTest.java">DataflowAnalysisTest</a> and <a href="https://github.com/ballerina-platform/ballerina-lang/blob/master/tests/jballerina-unit-test/src/test/java/org/ballerinalang/test/dataflow/analysis/UnusedVariableTest.javahttps://github.com/ballerina-platform/ballerina-lang/blob/master/tests/jballerina-unit-test/src/test/java/org/ballerinalang/test/dataflow/analysis/UnusedVariableTest.java">UnusedVariableTest</a>.</p><h4>Isolation Analysis</h4><p>Then we have the isolation analysis phase. The class <a href="https://github.com/ballerina-platform/ballerina-lang/blob/47e4dc999fd7c32eea0918264295357f51dbf5a8/compiler/ballerina-lang/src/main/java/org/wso2/ballerinalang/compiler/semantics/analyzer/IsolationAnalyzer.java"><strong>IsolationAnalyzer</strong></a><strong> </strong>is responsible for this analysis phase. This ensures that variables and objects marked as isolated adhere to strict isolation rules. These guarantees thread safety and modular encapsulation by preventing unintended access or modification across concurrent execution contexts. A function defined as isolated:</p><ul><li>has access to mutable state only through its parameters.</li><li>has unrestricted access to immutable state.</li><li>can only call functions that are isolated.</li></ul><p>So this phase detects violations, such as calling a non-isolated function within an isolated context, stopping compilation if violations exist.</p><h4>Documentation Analysis</h4><p>The documentation analysis phase validates documentation and associates it with corresponding code elements. This ensures that all APIs, modules, and functions are properly documented, enabling developers to generate reliable documentation. <a href="https://github.com/ballerina-platform/ballerina-lang/blob/b684f850dd8e6759a2c6ff7944dc878e47ef703c/compiler/ballerina-lang/src/main/java/org/wso2/ballerinalang/compiler/semantics/analyzer/DocumentationAnalyzer.javahttps://github.com/ballerina-platform/ballerina-lang/blob/b684f850dd8e6759a2c6ff7944dc878e47ef703c/compiler/ballerina-lang/src/main/java/org/wso2/ballerinalang/compiler/semantics/analyzer/DocumentationAnalyzer.java"><strong>DocumentationAnalyzer</strong></a><strong> </strong>is the class performing this.</p><p>The below code has been documented with a wrong parameter named y instead of x which is in the function.</p><pre># Description.<br>#<br># + y - parameter description<br>public function foo(int x) {<br>    <br>}</pre><p>This will raise a warning stating no such documentable parameter ‘y’ and that is done by the method <a href="https://github.com/ballerina-platform/ballerina-lang/blob/b684f850dd8e6759a2c6ff7944dc878e47ef703c/compiler/ballerina-lang/src/main/java/org/wso2/ballerinalang/compiler/semantics/analyzer/DocumentationAnalyzer.java#L432">validateParameters</a> in the <a href="https://github.com/ballerina-platform/ballerina-lang/blob/b684f850dd8e6759a2c6ff7944dc878e47ef703c/compiler/ballerina-lang/src/main/java/org/wso2/ballerinalang/compiler/semantics/analyzer/DocumentationAnalyzer.javahttps://github.com/ballerina-platform/ballerina-lang/blob/b684f850dd8e6759a2c6ff7944dc878e47ef703c/compiler/ballerina-lang/src/main/java/org/wso2/ballerinalang/compiler/semantics/analyzer/DocumentationAnalyzer.java"><strong>DocumentationAnalyzer</strong></a><strong> </strong>by logging it using <a href="https://github.com/ballerina-platform/ballerina-lang/blob/b684f850dd8e6759a2c6ff7944dc878e47ef703c/compiler/ballerina-lang/src/main/java/org/wso2/ballerinalang/compiler/semantics/analyzer/DocumentationAnalyzer.java#L488">dlog.warning</a>.</p><h4>Constant Propagation</h4><p>This phase replaces constant expressions with their computed values at compile time, reducing runtime computation and improving efficiency.</p><p>Executed by the <a href="https://github.com/ballerina-platform/ballerina-lang/blob/b80146daf93ffe7ae8ab78594888c196d2341185/compiler/ballerina-lang/src/main/java/org/wso2/ballerinalang/compiler/desugar/ConstantPropagation.java">ConstantPropagation</a> class, which evaluates constant values during compilation and substitutes them in the program.</p><pre>const int TAX_RATE = 15;<br>function calculateTax(int amount) returns int {<br>    return amount * TAX_RATE / 100; // TAX_RATE is propagated at compile time<br>}</pre><p>Here, TAX_RATE is evaluated and propagated so that its value is directly used in the generated code.</p><h4>Compiler Plugin</h4><p>This phase processes annotations in the code using compiler plugins. Plugins can analyze or transform the program AST based on user-defined annotations, enabling extensibility and custom behaviors. The class <a href="https://github.com/ballerina-platform/ballerina-lang/blob/d60882bb975d8968c02c5070afb582c799de4b82/compiler/ballerina-lang/src/main/java/org/wso2/ballerinalang/compiler/semantics/analyzer/CompilerPluginRunner.javahttps://github.com/ballerina-platform/ballerina-lang/blob/d60882bb975d8968c02c5070afb582c799de4b82/compiler/ballerina-lang/src/main/java/org/wso2/ballerinalang/compiler/semantics/analyzer/CompilerPluginRunner.java"><strong>CompilerPluginRunner</strong></a><strong> </strong>processes these annotations.</p><p>With this, the Compiler Phase Runner concludes performing Type Check Phases. The Semantic Analysis, Code Analysis, and other related phases are integral to ensuring that the program is not only syntactically correct but also logically sound and semantically valid. These phases identify potential issues early in the compilation process, making the code more robust and ensuring that it behaves as expected.</p><p>In the <a href="https://medium.com/@chamikamadhushan/ballerina-compiler-internals-iv-desugar-c750a3a0c28a"><strong>next article</strong></a>, we will explore the Desugaring phase, where higher-level constructs are simplified into more fundamental expressions, removing the syntactic sugar. Stay tuned for a deeper dive into how the compiler handles this important step!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4d5c4a6bd5ab" width="1" height="1" alt=""><hr><p><a href="https://medium.com/ballerina-techblog/ballerina-compiler-internals-iii-semantic-analysis-4d5c4a6bd5ab">Ballerina Compiler Internals III — Semantic Analysis</a> was originally published in <a href="https://medium.com/ballerina-techblog">Ballerina Swan Lake Tech Blog</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Ballerina Compiler Internals II — Syntactic Analysis]]></title>
            <link>https://medium.com/ballerina-techblog/ballerina-compiler-internals-ii-syntactic-analysis-7d3824f793ad?source=rss-842813a8b987------2</link>
            <guid isPermaLink="false">https://medium.com/p/7d3824f793ad</guid>
            <category><![CDATA[syntactic-analysis]]></category>
            <category><![CDATA[ballerinalang]]></category>
            <category><![CDATA[compilers]]></category>
            <category><![CDATA[ballerina]]></category>
            <dc:creator><![CDATA[Chamika Madhushan]]></dc:creator>
            <pubDate>Wed, 05 Feb 2025 08:05:53 GMT</pubDate>
            <atom:updated>2025-02-06T03:57:31.122Z</atom:updated>
            <content:encoded><![CDATA[<h3>Ballerina Compiler Internals II — <strong>Syntactic Analysis</strong></h3><p>In the previous article <a href="https://medium.com/@chamikamadhushan/ballerina-compiler-internals-i-overview-97fff89a5fd6"><strong>Ballerina Compiler Internals I—Overview,</strong></a> we got an overview of the whole compiler. Now we will go through each phase one by one, starting from the Lexical and Syntactic Analysis phase.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uaI5USG4bulhYTKQYfz9wg.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@johnishappysometimes?utm_content=creditCopyText&amp;utm_medium=referral&amp;utm_source=unsplash">John Schnobrich</a> on <a href="https://unsplash.com/photos/person-using-laptop-FlPc9_VocJ4?utm_content=creditCopyText&amp;utm_medium=referral&amp;utm_source=unsplash">Unsplash</a></figcaption></figure><p>The <strong>Lexical and Syntactic Analysis phase</strong> of the compiler process ensures that the code is properly broken down into smaller, manageable parts and organized into a structured format. In this article, we’ll explore how the <a href="https://github.com/ballerina-platform/ballerina-lang/blob/master/compiler/ballerina-parser/src/main/java/io/ballerina/compiler/internal/parser/BallerinaLexer.java"><strong>BallerinaLexer</strong></a> and <a href="https://github.com/ballerina-platform/ballerina-lang/blob/master/compiler/ballerina-parser/src/main/java/io/ballerina/compiler/internal/parser/BallerinaParser.java"><strong>BallerinaParser</strong></a> work together to tokenize the code and form a syntax tree. We’ll also dive into how the <a href="https://github.com/ballerina-platform/ballerina-lang/blob/master/compiler/ballerina-lang/src/main/java/org/wso2/ballerinalang/compiler/parser/BLangNodeBuilder.java"><strong>BLangNodeBuilder</strong></a> constructs an Abstract Syntax Tree (AST), setting the stage for the next stages of compilation.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/896/1*jZrRL9YSgqocmiiI0x9nzg.png" /><figcaption>The Parser</figcaption></figure><h4>The Lexer</h4><p>The Lexer reads characters from the input/character reader and produces tokens. <a href="https://github.com/ballerina-platform/ballerina-lang/blob/master/compiler/ballerina-tools-api/src/main/java/io/ballerina/tools/text/CharReader.java"><strong>CharReader</strong></a><strong> </strong>has<strong> </strong><a href="https://github.com/ballerina-platform/ballerina-lang/blob/master/compiler/ballerina-tools-api/src/main/java/io/ballerina/tools/text/CharReader.java#L52"><strong>peek()</strong></a><strong> </strong>and<strong> </strong><a href="https://github.com/ballerina-platform/ballerina-lang/blob/master/compiler/ballerina-tools-api/src/main/java/io/ballerina/tools/text/CharReader.java#L61"><strong>peek(k)</strong></a><strong> </strong>methods to get the next character or next k-th character from the input. The <strong>consume() </strong>or<strong> consume(k) </strong>gets the next character/next k-th token from the input and removes it from the input. <a href="https://github.com/ballerina-platform/ballerina-lang/blob/master/compiler/ballerina-tools-api/src/main/java/io/ballerina/tools/text/CharReader.java#L97C20-L97C27"><strong>isEOF()</strong></a><strong> c</strong>hecks whether the reader has reached the end of the input.</p><p>Those character streams are converted into token streams by the <a href="https://github.com/ballerina-platform/ballerina-lang/blob/master/compiler/ballerina-parser/src/main/java/io/ballerina/compiler/internal/parser/BallerinaLexer.java"><strong>BallerinaLexar</strong></a><strong>. </strong>Lexer performs the following tasks.</p><ul><li><strong>Tokenization</strong>:<br>The lexer reads the source file character by character, identifying patterns to form tokens. Each token represents a distinct unit in the code, such as keywords, operators, identifiers, literals, or symbols.</li><li><strong>Pattern Matching</strong>:<br>The lexer uses predefined rules and regular expressions to classify sequences of characters. For example, it recognizes keywords likefunction ,ifor else using <a href="https://github.com/ballerina-platform/ballerina-lang/blob/1ca947f1213f26e24dd198aa5907760ec80d5ddc/compiler/ballerina-parser/src/main/java/io/ballerina/compiler/internal/parser/BallerinaLexer.java#L825">processIdentifierOrKeyword()</a> method.</li><li><strong>Error Handling</strong>:<br>The lexer must handle unexpected sequences gracefully. When encountering invalid characters or incomplete tokens, it generates diagnostic messages to aid in debugging.</li><li><strong>Streamlined Output</strong>:<br>The output of the lexer is a <strong>stream of tokens</strong>, which is then passed to the <strong>BallerinaParser</strong> for building the syntax tree. Each token contains metadata, such as its type, value, and location in the source code.</li></ul><h4>The Parser</h4><p>The <a href="https://github.com/ballerina-platform/ballerina-lang/blob/47e4dc999fd7c32eea0918264295357f51dbf5a8/compiler/ballerina-parser/src/main/java/io/ballerina/compiler/internal/parser/BallerinaParser.java"><strong>BallerinaParser</strong></a><strong> </strong>is responsible for reading the tokens from the lexer and producing the parse-tree (<a href="https://www.geeksforgeeks.org/parse-tree-and-syntax-tree/">Syntax tree</a>). <a href="https://github.com/ballerina-platform/ballerina-lang/blob/47e4dc999fd7c32eea0918264295357f51dbf5a8/compiler/ballerina-parser/src/main/java/io/ballerina/compiler/internal/parser/BallerinaParser.java"><strong>BallerinaParser</strong></a><strong> </strong>has the <strong>parse() </strong>method, which will do the parsing and return the syntax tree nodes (<a href="https://github.com/ballerina-platform/ballerina-lang/blob/41e439b57c71d0cade204508712faa4072bc729a/compiler/ballerina-parser/src/main/java/io/ballerina/compiler/internal/parser/tree/STNode.java">STNode</a>). The <a href="https://github.com/ballerina-platform/ballerina-lang/blob/2f981f5c0bd0a21e81544a8599c317db2f2ca94c/compiler/ballerina-treegen/src/main/resources/syntax_tree_descriptor.json">syntax_tree_descriptor.json</a> consists of all the node definitions for forming the tree.</p><p>Following are some important methods in the <a href="https://github.com/ballerina-platform/ballerina-lang/blob/47e4dc999fd7c32eea0918264295357f51dbf5a8/compiler/ballerina-parser/src/main/java/io/ballerina/compiler/internal/parser/BallerinaParser.java"><strong>BallerinaParser</strong></a><strong>.</strong></p><ol><li><a href="https://github.com/ballerina-platform/ballerina-lang/blob/47e4dc999fd7c32eea0918264295357f51dbf5a8/compiler/ballerina-parser/src/main/java/io/ballerina/compiler/internal/parser/BallerinaParser.java#L101"><strong>parse()</strong></a><strong> — </strong>This method serves as the entry point for parsing a complete Ballerina source file. It assumes the input is a full compilation unit. It calls the parseCompUnit() method to process the entire compilation unit, which includes imports, declarations, functions, and more.</li></ol><pre>public STNode parse() {<br>    return parseCompUnit();<br>}</pre><p>2. <a href="https://github.com/ballerina-platform/ballerina-lang/blob/47e4dc999fd7c32eea0918264295357f51dbf5a8/compiler/ballerina-parser/src/main/java/io/ballerina/compiler/internal/parser/BallerinaParser.java#L403"><strong>parse(ParserRuleContext context)</strong></a><strong> — </strong>This overloaded method is more flexible, allowing the parsing of specific contexts (e.g., a single statement, an expression, or a top-level node).</p><pre>public STNode parse(ParserRuleContext context) {<br>        switch (context) {<br>            case COMP_UNIT:<br>                return parseCompUnit();<br>            case TOP_LEVEL_NODE:<br>                startContext(ParserRuleContext.COMP_UNIT);<br>                return parseTopLevelNode();<br>            case STATEMENT:<br>                startContext(ParserRuleContext.COMP_UNIT);<br>                startContext(ParserRuleContext.FUNC_BODY_BLOCK);<br>                return parseStatement();<br>            case EXPRESSION:<br>                startContext(ParserRuleContext.COMP_UNIT);<br>                startContext(ParserRuleContext.VAR_DECL_STMT);<br>                return parseExpression();<br>            default:<br>                throw new UnsupportedOperationException(&quot;Cannot start parsing from: &quot; + context);<br>        }<br>    }</pre><p>3. <a href="https://github.com/ballerina-platform/ballerina-lang/blob/47e4dc999fd7c32eea0918264295357f51dbf5a8/compiler/ballerina-parser/src/main/java/io/ballerina/compiler/internal/parser/BallerinaParser.java#L432https://github.com/ballerina-platform/ballerina-lang/blob/47e4dc999fd7c32eea0918264295357f51dbf5a8/compiler/ballerina-parser/src/main/java/io/ballerina/compiler/internal/parser/BallerinaParser.java#L432"><strong>parseCompUnit()</strong></a><strong> — </strong>Parses the entire compilation unit, including top-level declarations and imports, until the end of the file (EOF_TOKEN).</p><ul><li><strong>Handles Imports</strong>: Collects IMPORT_DECLARATION nodes and ensures they appear at the beginning of the file. An error is logged if imports appear after other declarations.</li><li><strong>Processes Top-Level Declarations</strong>: Other declarations, like functions, types, or constants, are added to a separate list.</li><li><strong>End of File</strong>: Stops parsing when the EOF_TOKEN is encountered.</li><li><strong>Returns</strong>: A ModulePartNode containing the lists of imports and top-level declarations.</li></ul><pre>private STNode parseCompUnit() {<br>    startContext(ParserRuleContext.COMP_UNIT);<br>    List&lt;STNode&gt; otherDecls = new ArrayList&lt;&gt;();<br>    List&lt;STNode&gt; importDecls = new ArrayList&lt;&gt;();<br><br>    boolean processImports = true;<br>    STToken token = peek();<br>    while (token.kind != SyntaxKind.EOF_TOKEN) {<br>        STNode decl = parseTopLevelNode();<br>        if (decl == null) {<br>            break;<br>        }<br>        if (decl.kind == SyntaxKind.IMPORT_DECLARATION) {<br>            if (processImports) {<br>                importDecls.add(decl);<br>            } else {<br>                updateLastNodeInListWithInvalidNode(otherDecls, decl,<br>                        DiagnosticErrorCode.ERROR_IMPORT_DECLARATION_AFTER_OTHER_DECLARATIONS);<br>            }<br>        } else {<br>            if (processImports) {<br>                processImports = false;<br>            }<br>            otherDecls.add(decl);<br>        }<br>        token = peek();<br>    }<br><br>    STToken eof = consume();<br>    endContext();<br><br>    return STNodeFactory.createModulePartNode(STNodeFactory.createNodeList(importDecls),<br>            STNodeFactory.createNodeList(otherDecls), eof);<br>}</pre><p>4. <a href="https://github.com/ballerina-platform/ballerina-lang/blob/47e4dc999fd7c32eea0918264295357f51dbf5a8/compiler/ballerina-parser/src/main/java/io/ballerina/compiler/internal/parser/BallerinaParser.java#L477https://github.com/ballerina-platform/ballerina-lang/blob/47e4dc999fd7c32eea0918264295357f51dbf5a8/compiler/ballerina-parser/src/main/java/io/ballerina/compiler/internal/parser/BallerinaParser.java#L477"><strong>parseTopLevelNode() </strong></a>— parses top level nodes such as functions, type, constant, and import.</p><p>5. <a href="https://github.com/ballerina-platform/ballerina-lang/blob/47e4dc999fd7c32eea0918264295357f51dbf5a8/compiler/ballerina-parser/src/main/java/io/ballerina/compiler/internal/parser/BallerinaParser.java#L4165"><strong>parseStatement()</strong></a> — parses statements, until an end of a block is reached.</p><p>After parsing, each token will be consumed by calling the<strong> consume()</strong> method. The errors found out in the parser will be handled by the class <a href="https://github.com/ballerina-platform/ballerina-lang/blob/5ada33c7050d21d706db96f1e2f35b3a36d9e1a5/compiler/ballerina-parser/src/main/java/io/ballerina/compiler/internal/parser/BallerinaParserErrorHandler.java#L50https://github.com/ballerina-platform/ballerina-lang/blob/5ada33c7050d21d706db96f1e2f35b3a36d9e1a5/compiler/ballerina-parser/src/main/java/io/ballerina/compiler/internal/parser/BallerinaParserErrorHandler.java#L50"><strong>BallerinaParserErrorHandler</strong></a>. The syntax tree formed by the parser will be formed into AST by BLangNodeBuilder.</p><h4>BLangNodeBuilder</h4><p>The <a href="https://github.com/ballerina-platform/ballerina-lang/blob/d60882bb975d8968c02c5070afb582c799de4b82/compiler/ballerina-lang/src/main/java/org/wso2/ballerinalang/compiler/parser/BLangNodeBuilder.java"><strong>BLangNodeBuilder</strong></a> is a key component of the Ballerina compiler, responsible for constructing the <strong>Abstract Syntax Tree (AST)</strong> from the <strong>Syntax Tree (ST)</strong> generated by the parser. While the Syntax Tree (ST) focuses on capturing the syntactic structure of the code, the <strong>Abstract Syntax Tree (AST) abstracts away unnecessary details </strong>(<em>like removing the extra spaces and comments</em>), making it suitable for subsequent compilation phases like semantic analysis and code generation.</p><p>BLangNodeBuilder has the following <a href="https://github.com/ballerina-platform/ballerina-lang/blob/d60882bb975d8968c02c5070afb582c799de4b82/compiler/ballerina-lang/src/main/java/org/wso2/ballerinalang/compiler/parser/BLangNodeBuilder.java#L573"><strong>accept()</strong> </a>method.</p><pre>  public List&lt;org.ballerinalang.model.tree.Node&gt; accept(Node node) {<br>      BLangNode bLangNode = node.apply(this);<br>      List&lt;org.ballerinalang.model.tree.Node&gt; nodes = new ArrayList&lt;&gt;();<br>      // if not already consumed, add left-over statements<br>      while (!additionalStatements.isEmpty()) {<br>          nodes.add(additionalStatements.pop());<br>      }<br>      nodes.add(bLangNode);<br>      return nodes;<br>  }</pre><p>It calls the <a href="https://github.com/ballerina-platform/ballerina-lang/blob/1b36e652d071a15058247bda83a4b9bc9bcacaaf/compiler/ballerina-parser/src/main/java/io/ballerina/compiler/syntax/tree/ModulePartNode.java#L53"><strong>apply()</strong></a> method in the <a href="https://github.com/ballerina-platform/ballerina-lang/blob/1b36e652d071a15058247bda83a4b9bc9bcacaaf/compiler/ballerina-parser/src/main/java/io/ballerina/compiler/syntax/tree/ModulePartNode.java"><strong>ModulePartNode</strong></a> class.</p><pre>  public &lt;T&gt; T apply(NodeTransformer&lt;T&gt; visitor) {<br>      return visitor.transform(this);<br>  }</pre><p>This applies method uses <a href="https://medium.com/solution-design-patterns/basics-of-design-patterns-software-engineering-for-beginners-visitor-2af5378683b9">visitor pattern</a> dispatching to the transform relevant to the particular node. As an example, if it is a ModulePartNode it will call the <a href="https://github.com/ballerina-platform/ballerina-lang/blob/d60882bb975d8968c02c5070afb582c799de4b82/compiler/ballerina-lang/src/main/java/org/wso2/ballerinalang/compiler/parser/BLangNodeBuilder.java#L660"><strong>transform(ModulePartNode modulePart)</strong></a>method. If it is a module variable declaration, it will use the <a href="https://github.com/ballerina-platform/ballerina-lang/blob/d60882bb975d8968c02c5070afb582c799de4b82/compiler/ballerina-lang/src/main/java/org/wso2/ballerinalang/compiler/parser/BLangNodeBuilder.java#L693"><strong>transform(ModuleVariableDeclarationNode modVarDeclrNode</strong></a><strong>) </strong>method.</p><p>The transform method in the <strong>BLangNodeBuilder</strong> converts a syntax tree node into a <strong>BLangNode</strong> (an abstract syntax tree node). If we take the method transform(VariableDeclarationNode varDeclaration) as an example:</p><pre>  public BLangNode transform(VariableDeclarationNode varDeclaration) {<br>      VariableDefinitionNode varNode =<br>              createBLangVarDef(getPosition(varDeclaration), varDeclaration.typedBindingPattern(),<br>                                varDeclaration.initializer(), varDeclaration.finalKeyword());<br>      ((BLangVariable) varNode.getVariable()).annAttachments = applyAll(varDeclaration.annotations());<br>      return (BLangNode) varNode;<br>  }</pre><p>Input (varDeclaration) :</p><pre>int a =     10; // Accessing a variable from the same package</pre><p>Output (varNode) :</p><pre>varNode = {BLangSimpleVariableDef@4809} &quot;null _ = 10&quot;<br> var = {BLangSimpleVariable@4837} &quot;null _ = 10&quot;<br>  name = {BLangIdentifier@4856} &quot;a&quot;<br>  typeNode = {BLangValueType@4857} &quot;int&quot;<br>  annAttachments = {ArrayList@4858}  size = 0<br>  markdownDocumentationAttachment = null<br>  expr = {BLangNumericLiteral@4859} &quot;10&quot; <br>        .......</pre><p>Here, the extra spaces and comments have been removed by the transformer, forming an abstract node. Then this AST is moved to the symbol enter phase.</p><h4>Symbol Enter</h4><p>The <a href="https://github.com/ballerina-platform/ballerina-lang/blob/1336528d7cb9812cc1d9ccd220e2c88b61f29bb8/compiler/ballerina-lang/src/main/java/org/wso2/ballerinalang/compiler/semantics/analyzer/SymbolEnter.java"><strong>SymbolEnter</strong></a> phase is where the compiler organizes the structure of your program by registering all the key elements—such as variables, functions, types, and constants—into a central symbol table. This process ensures that every symbol is properly <strong>defined</strong>, <strong>scoped</strong>, and ready for use in later stages of compilation. Think of it as creating a detailed map of your code, where each entity is cataloged and linked to its respective context, laying the foundation for <strong>semantic validation</strong> and <strong>logical consistency</strong>.</p><p>The <a href="https://github.com/ballerina-platform/ballerina-lang/blob/1336528d7cb9812cc1d9ccd220e2c88b61f29bb8/compiler/ballerina-lang/src/main/java/org/wso2/ballerinalang/compiler/semantics/analyzer/SymbolEnter.java#L288"><strong>definePackage()</strong></a> method of the symbol enter class is as follows.</p><pre>  public BLangPackage definePackage(BLangPackage pkgNode) {<br>      dlog.setCurrentPackageId(pkgNode.packageID);<br>      populatePackageNode(pkgNode);<br>      defineNode(pkgNode, this.symTable.pkgEnvMap.get(symTable.langAnnotationModuleSymbol));<br>      return pkgNode;<br>  }</pre><p>The definePackage method processes a BLangPackage node, representing a Ballerina package, by:</p><ol><li><strong>Setting the Current Package Context:</strong> Tracks the package for error reporting.</li><li><strong>Populating the Package Node:</strong> Organizes top-level declarations like functions, types, and imports.</li><li><strong>Defining Symbols:</strong> Registers the package’s components into the symbol table, linking them to their appropriate contexts.</li><li><strong>Returning the Package:</strong> Passes the processed package to later compilation stages.</li></ol><p>This method ensures the package and its elements are properly structured and ready for semantic analysis and validation.</p><p>Then the other important part of symbol enter is the <a href="https://github.com/ballerina-platform/ballerina-lang/blob/ada664b36470b4b4d997c088a5bcb1080dbdfad8/compiler/ballerina-lang/src/main/java/org/wso2/ballerinalang/compiler/semantics/model/SymbolEnv.java"><strong>SymbolEnv</strong></a><strong>. </strong>A SymbolEnv represents the current scope or context during the compilation process as follows:</p><pre>public class SymbolEnv {<br><br>    public Scope scope;<br><br>    public BLangNode node;<br><br>    public BLangPackage enclPkg;<br><br>    public BLangType enclType;<br><br>    public BLangAnnotation enclAnnotation;<br><br>    public BLangService enclService;<br><br>    public BLangInvokableNode enclInvokable;<br><br>    public BVarSymbol enclVarSym;<br><br>    public SymbolEnv enclEnv;<br><br>    public List&lt;TypeParamEntry&gt; typeParamsEntries;<br><br>    public boolean logErrors;<br><br>    public int envCount;<br><br>    public int relativeEnvCount;<br><br>    public boolean isModuleInit;<br><br>    ...<br><br>}</pre><p>In conclusion, the journey through the Ballerina compiler reveals the intricate mechanisms that transform source code into a structured, analyzable, and executable form. Starting with <strong>Lexical and Syntactic Analysis</strong>, the <strong>BallerinaLexer</strong> tokenizes character streams, and the <strong>BallerinaParser</strong> constructs a syntax tree (ST) from these tokens. The <strong>BLangNodeBuilder</strong> further refines this process, abstracting the syntactic details into an Abstract Syntax Tree (AST), which serves as a simplified representation of the program’s structure.</p><p>Following this, the <strong>Symbol Enter phase</strong> builds a comprehensive map of the program by defining all symbols, scoping them correctly, and preparing them for semantic validation. This phase ensures the program’s logical consistency and lays the groundwork for subsequent stages of compilation, such as semantic analysis and code generation.</p><p>In the <a href="https://medium.com/@chamikamadhushan/4d5c4a6bd5ab"><strong>next article,</strong></a> we will find out how the <strong>compiler phase performs</strong> the Semantic, Code, and Other Analysis.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7d3824f793ad" width="1" height="1" alt=""><hr><p><a href="https://medium.com/ballerina-techblog/ballerina-compiler-internals-ii-syntactic-analysis-7d3824f793ad">Ballerina Compiler Internals II — Syntactic Analysis</a> was originally published in <a href="https://medium.com/ballerina-techblog">Ballerina Swan Lake Tech Blog</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Ballerina Compiler Internals I — Overview]]></title>
            <link>https://medium.com/ballerina-techblog/ballerina-compiler-internals-i-overview-97fff89a5fd6?source=rss-842813a8b987------2</link>
            <guid isPermaLink="false">https://medium.com/p/97fff89a5fd6</guid>
            <category><![CDATA[compilers]]></category>
            <category><![CDATA[ballerinalang]]></category>
            <category><![CDATA[ballerina]]></category>
            <dc:creator><![CDATA[Chamika Madhushan]]></dc:creator>
            <pubDate>Wed, 05 Feb 2025 07:55:30 GMT</pubDate>
            <atom:updated>2025-02-05T09:48:54.424Z</atom:updated>
            <content:encoded><![CDATA[<h3>Ballerina Compiler Internals I — Overview</h3><p>How does your code turn into something your computer can understand and execute? Enter the <strong>compiler</strong>, the unsung hero of programming.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jkHw3jZc7mx4YIWm6Wa42g.png" /><figcaption>Ballerina Compiler Internals</figcaption></figure><p><strong>A compiler is a sophisticated program that transforms high-level code (like Java, Python, or Ballerina) into a machine-readable format</strong>. It’s the invisible bridge between human logic and computational execution, ensuring your code is syntactically correct, logically sound, and optimized for performance.</p><p>In this article, we’ll take you on an exciting journey through the core phases of a compiler.</p><p>So buckle up as we explore the four key phases of the compilation process: <strong>Lexical and Syntactic Analysis</strong>, <strong>Semantic and Code Analysis</strong>, <strong>Desugaring</strong>, and <strong>Intermediate Representation Generation</strong>. Let’s uncover how your code is brought to life!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HK4IaaE9LAvqn-Mf2DXqog.png" /><figcaption>Fig 1: Ballerina Compiler</figcaption></figure><p>Now that we’ve seen the bigger picture, let’s briefly look at each phase of the compilation process.</p><h3>1. Lexical and Syntactic Analysis</h3><p>This phase focuses on reading and structuring the source code.</p><ul><li><strong>Lexer:</strong> Breaks the .bal source file into syntactic tokens.</li><li><strong>Parser:</strong> Converts the token into a <strong>syntax tree</strong>, representing the hierarchical structure of the code.</li><li><strong>Abstract Syntax Tree (AST):</strong> The <strong>BLangNodeBuilder</strong> constructs the AST, a more abstract representation of the syntax tree removing nodes unnecessary for later stages.</li><li><strong>Symbol Enter:</strong> Creates symbols and relevant scopes for the package, and package-level constructs such as functions, variables, and types.</li></ul><p><strong>Purpose:</strong> This phase ensures the code is <strong>syntactically</strong> correct and prepares it for deeper analysis.</p><h3>2. Semantic, Code, and Other Analysis</h3><p>This phase validates the logic and consistency of the code.</p><ul><li><strong>Semantic Analysis:</strong> Verifies that all variables and expressions adhere to their declared types and Ensures logical correctness, such as matching left-hand side (LHS) and right-hand side (RHS) expressions.</li><li><strong>Code Analysis:</strong> Checks that functions return what is promised (e.g., correct return types).</li><li><strong>Data Flow Analysis:</strong> Detects unused or undefined variables and ensures proper variable initialization.</li><li><strong>Isolation Analysis:</strong> Validates adherence to concurrency and isolation rules, ensuring safe parallel execution.</li><li><strong>Documentation Analysis:</strong> Ensures the presence and accuracy of documentation associated with the code.</li><li><strong>Constant Propagation: </strong>Simplifies expressions by resolving constant values.</li><li><strong>Annotation Processing: </strong>Processes and validates annotations present in the code.</li></ul><p><strong>Purpose:</strong> Guarantees the code is <strong>semantically</strong> correct, adheres to language rules, and maintains best practices.</p><h3>3. Desugaring</h3><p>This phase simplifies high-level constructs into more fundamental ones.</p><ul><li>Complex constructs (e.g., syntactic sugar-like foreach loops) are transformed into simpler forms that are easier to process in later stages.</li></ul><p><strong>Purpose:</strong> Makes the code representation more uniform and prepares it for intermediate representation generation.</p><h3>4. Ballerina Intermediate Representation (BIR) Generation</h3><p>The <strong>Ballerina Intermediate Representation (BIR)</strong> serves as a bridge between the high-level source code and the executable output. This phase transforms the desugared Abstract Syntax Tree (AST) into a compact, optimized, and portable intermediate format, making it a key step in the compilation process.</p><h4>How BIR Enables Flexibility Across Runtime Environments?</h4><p>The BIR is specifically designed to be a <strong>platform-independent intermediate representation</strong>. It abstracts away the details of the underlying runtime, allowing the same code to be adapted to multiple target environments. Here’s how this is achieved:</p><ol><li><strong>Portability</strong>:<br>The BIR contains only the essential semantic and structural details of the program, omitting high-level syntactic elements. This streamlined structure makes it easier to adapt to various runtime environments.</li><li><strong>Optimization-Ready</strong>:<br>Before generating executable code, the BIR undergoes multiple optimization passes, such as constant folding, dead code elimination, and control flow simplification. These optimizations are generic and runtime-agnostic, enabling efficient execution on any platform.</li><li><strong>Platform Abstraction</strong>:<br>The BIR is designed to be decoupled from specific runtime constraints, such as memory models or execution architectures. This allows it to be further transformed or emitted into forms compatible with different environments, such as JVM bytecode, WebAssembly, or native binaries.</li><li><strong>Serialization and Interoperability</strong>:<br>Using <strong>BIREmit</strong>, the BIR can be serialized into a portable format that is easy to store, share, or load. This serialized BIR can then be consumed by interpreters, JIT compilers, or other runtime tools.</li></ol><p>Key Components of BIR Generation :</p><ul><li><strong>BIRGen:</strong> Translates the desugared AST into the <strong>Ballerina Intermediate Representation (BIR)</strong>, which is a lower-level representation designed for optimization and execution.</li><li><strong>BIREmit:</strong> Serializes the BIR into a form that can be stored or passed to subsequent tools or runtime environments.</li></ul><p><strong>Purpose:</strong> Produces an optimized intermediate format that bridges the gap between the high-level source code and executable output.</p><p>In the <a href="https://medium.com/@chamikamadhushan/the-secret-life-of-a-compiler-ii-the-parser-7d3824f793ad"><strong>next article</strong></a><strong>,</strong> we’ll take a closer look at the first phase of the compiler process: <strong>Lexical and Syntactic Analysis</strong>. We’ll explore how the compiler reads your code, breaks it down into tokens, and organizes it into a syntax tree to ensure it’s properly structured.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=97fff89a5fd6" width="1" height="1" alt=""><hr><p><a href="https://medium.com/ballerina-techblog/ballerina-compiler-internals-i-overview-97fff89a5fd6">Ballerina Compiler Internals I — Overview</a> was originally published in <a href="https://medium.com/ballerina-techblog">Ballerina Swan Lake Tech Blog</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Ballerina iTunes Service]]></title>
            <link>https://medium.com/@chamikamadhushan/ballerina-itunes-service-8b26c6a5d602?source=rss-842813a8b987------2</link>
            <guid isPermaLink="false">https://medium.com/p/8b26c6a5d602</guid>
            <category><![CDATA[ballerinalang]]></category>
            <category><![CDATA[api]]></category>
            <category><![CDATA[integration]]></category>
            <dc:creator><![CDATA[Chamika Madhushan]]></dc:creator>
            <pubDate>Wed, 04 Oct 2023 17:58:31 GMT</pubDate>
            <atom:updated>2023-10-04T17:58:31.254Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MujkZNZIsh73pY_KfgHNXg.jpeg" /></figure><p>This simple Ballerina program is a HTTP service that provides an endpoint for searching iTunes albums by an artist’s name and then returns information about those albums.</p><pre>import ballerina/http;<br><br>type ITunesSearchItem record {<br>    string collectionName;<br>    string collectionViewUrl;<br>};<br><br>type ITunesSearchResult record {<br>    ITunesSearchItem[] results;<br>};<br><br>type Album record {<br>    string name;<br>    string url;<br>};<br><br>function searchUrl(string artist) returns string {<br>    return &quot;/search?term=&quot; + artist;<br>}<br><br>listener http:Listener httpListener = new (8080);<br><br>service /itunes on httpListener {<br>    resource function get album(string artist) returns Album[]|error? {<br>        http:Client iTunes = check new(&quot;https://itunes.apple.com/&quot;);<br>        ITunesSearchResult search = check iTunes-&gt;get(searchUrl(artist));<br>        return from ITunesSearchItem item in search.results<br>            select {name: item.collectionName, url: item.collectionViewUrl};<br>    }   <br>}</pre><p>Let’s break down the code and provide a description for each part:</p><ol><li>Import Statements:</li></ol><pre>import ballerina/http;</pre><p>This line imports the necessary HTTP module from the Ballerina standard library, which allows you to work with HTTP requests and responses.</p><p>2. Type Definitions:</p><pre>type ITunesSearchItem record {<br>     string collectionName;<br>     string collectionViewUrl; <br>};  <br><br>type ITunesSearchResult record {<br>     ITunesSearchItem[] results; <br>};  <br><br>type Album record {<br>     string name;<br>     string url; <br>};</pre><p>These type definitions define the structure of the data that will be used within the code. ITunesSearchItem represents an item in an iTunes search result, ITunesSearchResult represents a collection of search results, and Album represents information about an album.</p><p>3. Function Definitions:</p><pre>function searchUrl(string artist) returns string {<br>     return &quot;/search?term=&quot; + artist; <br>}</pre><p>This function searchUrl takes an artist&#39;s name as input and constructs a URL for searching iTunes with that artist&#39;s name as a query parameter.</p><p>4. HTTP Listener Initialization:</p><pre>listener http:Listener httpListener = new (8080);</pre><p>This line initializes an HTTP listener on port 8080, which will be used to listen for incoming HTTP requests.</p><p>5. Service Definition and Resource Function:</p><pre>service /itunes on httpListener {<br>  resource function get album(string artist) returns Album[]|error? {<br>     http:Client iTunes = check new(&quot;https://itunes.apple.com/&quot;);<br>     ITunesSearchResult search = check iTunes-&gt;get(searchUrl(artist));<br>     return from ITunesSearchItem item in search.results<br>         select {name: item.collectionName, url: item.collectionViewUrl<br>  }; <br>}</pre><p>This defines an HTTP service named /itunes that listens on the httpListener created earlier.</p><p>This main resource function of the service responds to HTTP GET requests made to the /itunes/album endpoint with an artist&#39;s name as a query parameter. Here&#39;s what it does:</p><ul><li>It creates an HTTP client (iTunes) to make requests to the iTunes API.</li><li>It constructs a URL for searching iTunes based on the artist’s name.</li><li>It sends an HTTP GET request to iTunes and stores the result in the search variable.</li><li>It then processes the search results and maps them to Album objects, selecting the album name and its URL.</li><li>Finally, it returns an array of Album objects as the response, or an error if something goes wrong during the process.</li></ul><p>This is a demonstration on how it works.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cz2XFYMnOGKFTZeTSVdGWg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AUDAWvvqYCzhHxcx6T5sCw.png" /><figcaption>Input Provided</figcaption></figure><p>This will give us the output below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kEd98zktJBDVOxLKS_ARDQ.png" /><figcaption>Output Response</figcaption></figure><p>In summary, this Ballerina code sets up an HTTP service that allows clients to search for albums on iTunes by providing an artist’s name as a query parameter. It communicates with the iTunes API to retrieve search results and maps those results to a custom Album data structure before returning them to the client.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8b26c6a5d602" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Polymorphism - OOP Concepts in Java]]></title>
            <link>https://medium.com/@chamikamadhushan/polymorphism-oop-concepts-in-java-9fc57dbf78b5?source=rss-842813a8b987------2</link>
            <guid isPermaLink="false">https://medium.com/p/9fc57dbf78b5</guid>
            <category><![CDATA[oop-concepts]]></category>
            <category><![CDATA[oop]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[polymorphism]]></category>
            <dc:creator><![CDATA[Chamika Madhushan]]></dc:creator>
            <pubDate>Tue, 20 Jun 2023 03:32:07 GMT</pubDate>
            <atom:updated>2023-06-20T03:32:07.267Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/875/0*_4mY7Cma3Cf_EXwn" /><figcaption>Photo by <a href="https://unsplash.com/@lucabravo?utm_source=medium&amp;utm_medium=referral">Luca Bravo</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Polymorphism enables flexibility in Java.</p><p>Polymorphism means same one having many forms in various incidents / places.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/450/0*kxoC-IGYizgdQ6zX.png" /><figcaption>Source <a href="https://skillpundit.com/java/polymorphism.php">https://skillpundit.com/java/polymorphism.php</a></figcaption></figure><p>In Java, methods with same name perform different tasks for different objects which makes code more flexible. This is called polymorphism in Java OOP concepts.</p><p>There are two types of polymorphism in Java.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/870/0*4FVsa-zv91c5DEQp.png" /></figure><h3>1. Compile time polymorphism</h3><p>Here the compiler can see our code as a polymorphic code.</p><p>To achieve compile time polymorphism we use <strong>method overloading</strong> mechanism.</p><p><strong>Same class</strong> having <strong>methods</strong> with <strong>same name</strong> but with <strong>different Parameters </strong>is the mechanism known as <strong>method overloading.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/286/0*M35G90z0TP4WwRnJ.png" /></figure><p>Look at the following example.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/875/0*bFqHNFlaIqVmDxUm.png" /></figure><p>Calc class have two methods with same name “ add ” but with different parameters.</p><p>If we call add method with two parameters ( for ex :- <strong>add( 5 , 6 )</strong> ) the first method will be called.</p><p>If we call add method with three parameters ( for ex :- <strong>add( 5 , 6 , 7)</strong> ) the second method will be called.</p><p>This is how method overloading works, methods with same name working on different tasks according to the situation.</p><h4>Early binding</h4><p>The compiler can resolve the target method at compile time. Binding happens at the compile time. So compile time polymorphism(method overloading) can be called as <strong>early binding</strong>.</p><h3>2. Runtime Polymorphism</h3><p>Here Java virtual machine determines the proper method to call at the runtime, not at the compile time.</p><p>This is achieved through <strong>method overriding.</strong></p><p>In <strong>method overriding</strong>, a <strong>subclass </strong>overrides a method with the <strong>same signature</strong> as that of in its <strong>superclass</strong>.</p><p>JVM resolves which method to be called <strong>at runtime</strong> according to the reference type.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/336/0*faQ2_4QIUuEmlpVa.png" /><figcaption>Source <a href="https://www.guru99.com/cpp-polymorphism.html">https://www.guru99.com/cpp-polymorphism.html</a></figcaption></figure><p>Consider the following example.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/817/0*wsE-Y4BSfXcP8Bpo.png" /></figure><p>Here <strong>makeSound() </strong>method of super class Animal has been overridden in the sub classes Cow and Cat.</p><p>If we call makeSound() method from a Animal type reference JVM will call makeSound() method of the Animal class printing “makeSound”.</p><p>If we call makeSound() method from a Cow type reference JVM will call makeSound() method of the Cow class printing “moow”.</p><p>If we call makeSound() method from a Cat type reference JVM will call makeSound() method of the Cat class printing “meow”.</p><h4>Late binding</h4><p>When compiler can’t resolve which method to be called the compiler leaves it to the JVM and it is <strong>Late Binding</strong>. So method overriding can also be called as a late binding.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9fc57dbf78b5" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>