<?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" xmlns:media="http://search.yahoo.com/mrss/" version="2.0">
    <channel>
        
        <title>
            <![CDATA[ compilers - freeCodeCamp.org ]]>
        </title>
        <description>
            <![CDATA[ Browse thousands of programming tutorials written by experts. Learn Web Development, Data Science, DevOps, Security, and get developer career advice. ]]>
        </description>
        <link>https://www.freecodecamp.org/news/</link>
        <image>
            <url>https://cdn.freecodecamp.org/universal/favicons/favicon.png</url>
            <title>
                <![CDATA[ compilers - freeCodeCamp.org ]]>
            </title>
            <link>https://www.freecodecamp.org/news/</link>
        </image>
        <generator>Eleventy</generator>
        <lastBuildDate>Tue, 02 Jun 2026 21:43:28 +0000</lastBuildDate>
        <atom:link href="https://www.freecodecamp.org/news/tag/compilers/rss.xml" rel="self" type="application/rss+xml" />
        <ttl>60</ttl>
        
            <item>
                <title>
                    <![CDATA[ How to Build a Clang AST-Based C++ Static Analysis Tool ]]>
                </title>
                <description>
                    <![CDATA[ Clang is a set of tools and projects that provides infrastructure for languages in the C family like C, C++, OpenCL, and CUDA. It is a part of the LLVM project. This article will show you how to use Clang's front end libraries to build a simple stati... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/clang-ast-based-static-analysis-tools/</link>
                <guid isPermaLink="false">66b99d5065fc624db0255e07</guid>
                
                    <category>
                        <![CDATA[ C++ ]]>
                    </category>
                
                    <category>
                        <![CDATA[ compilers ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Jayant Chowdhary ]]>
                </dc:creator>
                <pubDate>Thu, 30 Nov 2023 19:01:21 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2023/11/ClangCover-2.jpg" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>Clang is a set of tools and projects that provides infrastructure for languages in the C family like C, C++, OpenCL, and CUDA. It is a part of the <a target="_blank" href="https://www.llvm.org/">LLVM</a> project.</p>
<p>This article will show you how to use Clang's front end libraries to build a simple static analysis tool which will operate on C++ source / header files. It will use the power of AST (Abstract Syntax Tree) traversal. </p>
<p>An abstract syntax tree is a tree structure representing the syntactical structure of code. <a target="_blank" href="https://en.wikipedia.org/wiki/Abstract_syntax_tree">Here</a> is a good explanation of how it works, and <a target="_blank" href="https://astexplorer.net/">here</a> is a tool to help you explore the AST for a given piece of code. </p>
<p>Here, I will teach you how you can use the Clang AST to find information about the code given to it to show you how powerful it is.</p>
<p>This article goes through everything step by step, and I’ll explain the terminology I'm using briefly at each step.</p>
<p>In the first section, you'll learn how to get the open source Clang project. Then, we'll explore how you can build a static analysis tool with a simple goal: to check if each <code>Class</code> defined in a source / header file starts with an uppercase character. We'll do this using Clang's frontend libraries which will analyze the C++ source AST. </p>
<p>So go ahead and grab your favorite coding beverage, get comfortable, and read on!</p>
<p>Here's what we'll cover:</p>
<ul>
<li><a class="post-section-overview" href="#heading-prerequisites">Prerequisites</a></li>
<li><a class="post-section-overview" href="#how-to-get-the-clang-project-and-access-front-end-libraries">How to Get the Clang Project and Access the Front-end Libraries</a></li>
<li><a class="post-section-overview" href="#heading-how-to-create-the-scaffolding-for-the-static-analysis-tool">How to Create the Scaffolding for the Static Analysis Tool</a></li>
<li><a class="post-section-overview" href="#heading-putting-it-all-together-in-code">Putting it All Together in Code</a></li>
<li><a class="post-section-overview" href="#heading-summary">Summary</a></li>
</ul>
<h2 id="heading-prerequisites">Prerequisites</h2>
<p>Before getting started, it would be beneficial to have a basic understanding of the following:</p>
<ul>
<li>Compilers: <a target="_blank" href="https://en.wikipedia.org/wiki/Compiler#:~:text=In%20computing%2C%20a%20compiler%20is,language%20(the%20target%20language).">this</a> page is a good primer for beginners.</li>
<li>C++ : For readers not familiar with C++, <a target="_blank" href="https://www.freecodecamp.org/news/learn-c-with-free-31-hour-course/">Learn C++ Programming for Beginners – Free 31-Hour Course</a> is a helpful resource.</li>
<li>Git: <a target="_blank" href="https://www.freecodecamp.org/news/how-to-use-git-best-practices-for-beginners/">Git Best Practices – A Guide to Version Control for Beginners</a> is an excellent starting point.</li>
</ul>
<h2 id="heading-how-to-get-the-clang-project-and-access-the-front-end-libraries">How to Get the Clang Project and Access the Front-end Libraries</h2>
<p>Since <code>clang</code> and <code>llvm</code> are open source projects, they have very comprehensive documentation around how to get started with getting the code and building tools using them. </p>
<p>You can check out the <a target="_blank" href="https://llvm.org/docs/GettingStarted.html">Getting Started</a> page of the <code>llvm</code> project to get more information about this. I've referenced that in this article as well.</p>
<p>###1. Get the Clang project </p>
<p>On a UNIX like terminal, clone the <code>llvm</code> Git project into your own directory. I'll call it <code>ast-anaylzer</code>.</p>
<ol>
<li><code>mkdir -p  ~/ast-analyzer; cd ~/ast-analyzer</code></li>
<li><code>git clone https://github.com/llvm/llvm-project.git</code> #Clone the llvm project source </li>
</ol>
<p>###2. Get the CMake build system and Ninja build tool</p>
<p><a target="_blank" href="https://cmake.org/">CMake</a> and <a target="_blank" href="https://ninja-build.org/">ninja</a> work in conjunction to form a build system. <code>CMake</code> generates <code>build.ninja</code> files, which contain commands that tell <code>ninja</code> how to generate output targets. We’ll get into this more a little later.</p>
<p>####2.1 Get and install Ninja</p>
<p>Here are the steps you can follow to install Ninja:</p>
<ol>
<li><code>cd ~/ast-analyzer</code></li>
<li>Clone the ninja source project with this command: <code>git clone https://github.com/martine/ninja.git</code> </li>
<li><code>cd ninja</code></li>
<li>Checkout the release branch - this is the stable branch - with this command: <code>git checkout release</code></li>
<li><code>python3 configure.py –bootstrap</code> This prepares and creates a Ninja binary (<code>configure.py –help</code> will give you more information).</li>
<li>Install ninja with this command: <code>sudo cp ninja /usr/local/bin</code>. After this step, as a basic validity check, do <code>which ninja</code> to make sure it says /usr/local/bin/ninja.</li>
</ol>
<p>####2.2. Get and install CMake</p>
<p>Here are the steps you can follow to install cmake:</p>
<ol>
<li><code>cd ~/ast-analyzer</code></li>
<li>Clone the cmake project source code: <code>git clone git://cmake.org/stage/cmake.git</code></li>
<li><code>cd cmake</code></li>
<li>Checkout the release branch - this is the stable branch - with this command: <code>git checkout release</code>.</li>
<li>Run the bootstrap script: <code>./bootstrap</code>. This prepares cmake to be built and installed on your host machine.</li>
<li>Build cmake from source with this command: <code>make</code>.</li>
<li>Then finally install cmake: <code>sudo make install</code>.</li>
</ol>
<p>Once we’ve gotten Clang, we’ll build it and configure it so we can build Clang-based tools as well.</p>
<p>###3. Build Clang and configure it</p>
<p>Create a ‘build’ directory. This is where our build.ninja/ output binaries and so on will get created:</p>
<pre><code>cd ~/ast-analyzer; mkdir -p build; cd build
</code></pre><p>Now we need to generate the <code>build.ninja file</code> in order to build Clang and also the tools in the directory from the project cloned earlier (<code>llvm/clang-tools-extra</code>). You can do this using <code>CMake</code> like this:</p>
<pre><code>cmake -G Ninja ../llvm-project/llvm -DLLVM_ENABLE_PROJECTS=<span class="hljs-string">"clang;clang-tools-extra"</span> # Enable the clang-tools projects <span class="hljs-keyword">in</span> our build <span class="hljs-keyword">as</span> well
</code></pre><p>This should generate a build.ninja file, which I encourage you to open and check out the contents. You will see that it contains a list of targets followed by dependencies. For example, one of the targets may look something like this: </p>
<pre><code>#############################################
# Utility command <span class="hljs-keyword">for</span> install-llvm-headers

build install-llvm-headers: phony CMakeFiles/install-llvm-headers llvm-headers
</code></pre><p> We’ll also do this for the custom static analysis tool we build in the next steps.</p>
<p>###4. Build and install all targets specified in the build.ninja file</p>
<p><code>ninja; ninja install</code></p>
<p>Okay, the setup is done and now we get to the fun part!</p>
<h2 id="heading-how-to-create-the-scaffolding-for-the-static-analysis-tool">How to Create the Scaffolding for the Static Analysis Tool</h2>
<p>We’ll be building our tool as a part of the <code>clang-tools-extra</code> directory in <code>llvm-project/clang-tools-extra</code>. Let's go ahead and create that directory. We’ll call our tool <code>class-analyzer</code>.</p>
<pre><code>mkdir ~<span class="hljs-regexp">/ast-analyzer/</span>llvm-project/clang-tools-extra/<span class="hljs-class"><span class="hljs-keyword">class</span>-<span class="hljs-title">analyzer</span>
<span class="hljs-title">cd</span> ~/<span class="hljs-title">ast</span>-<span class="hljs-title">analyzer</span>/<span class="hljs-title">llvm</span>-<span class="hljs-title">project</span>/<span class="hljs-title">clang</span>-<span class="hljs-title">tools</span>-<span class="hljs-title">extra</span>/<span class="hljs-title">class</span>-<span class="hljs-title">analyzer</span></span>
</code></pre><p>Now we need to create a <code>CMakeLists.txt</code>. This is basically a file that tells the <code>CMake</code> build system to add the source files in this tool to the <code>build.ninja</code> file it will generate. This lets <code>ninja</code> know how to build our tool.</p>
<p>Our <code>CMakeLists.txt</code> file will look like this:</p>
<p>CMakeLists.txt</p>
<pre><code>set(LLVM_LINK_COMPONENTS support)
set(CMAKE_CXX_COMPILER /usr/bin/clang++)  


add_clang_executable(<span class="hljs-class"><span class="hljs-keyword">class</span>-<span class="hljs-title">analyzer</span>
  <span class="hljs-title">ClassAnalzyer</span>.<span class="hljs-title">cpp</span>
  <span class="hljs-title">MyFrontendActionFactory</span>.<span class="hljs-title">cpp</span>
  <span class="hljs-title">MyFrontendAction</span>.<span class="hljs-title">cpp</span>
  <span class="hljs-title">MyASTConsumer</span>.<span class="hljs-title">cpp</span>
  )
<span class="hljs-title">target_link_libraries</span>(<span class="hljs-title">class</span>-<span class="hljs-title">analyzer</span>
  <span class="hljs-title">PRIVATE</span>
  <span class="hljs-title">clangAST</span>
  <span class="hljs-title">clangFrontend</span>
  <span class="hljs-title">clangTooling</span>
  )</span>
</code></pre><p>The first couple lines tell the build system that the compiler should be <code>/usr/local/bin/clang++</code> (the one just built in the previous steps).</p>
<p>The next <code>add_clang_executable</code> section tells the build system which source files to build as a part of our executable. We'll get more into the details of what each source file does soon. It also tells defines the name of the executable for the build system. Here it is called <code>class-analyzer</code> since it analyzes class names. </p>
<p>The <code>target_link_libraries</code> section informs the build system about the Clang front end libraries we should be linking against. These are the libraries which really expose the power of Clang’s AST to the tool we'll build.</p>
<p>Clang's API documentation is a good place to start looking for hints on how we should start writing the <code>class-analyzer</code> tool. Another good place to start is by scanning the source code of the Clang project we cloned earlier, for other tools! <code>[clang-tools-extra](https://github.com/llvm/llvm-project/tree/main/clang-tools-extra)</code> has multiple examples – these have been a source of inspiration for the code written here.</p>
<p>So now, let's start with the code for our very first source file. This file is contains the <code>main()</code> function of the executable. It looks something like this:</p>
<pre><code class="lang-cpp">
<span class="hljs-meta">#<span class="hljs-meta-keyword">include</span> <span class="hljs-meta-string">"clang/Tooling/CommonOptionsParser.h"</span></span>
<span class="hljs-meta">#<span class="hljs-meta-keyword">include</span> <span class="hljs-meta-string">"clang/Tooling/Tooling.h"</span></span>

<span class="hljs-meta">#<span class="hljs-meta-keyword">include</span> <span class="hljs-meta-string">"MyFrontendActionFactory.h"</span></span>

<span class="hljs-meta">#<span class="hljs-meta-keyword">include</span> <span class="hljs-meta-string">&lt;memory&gt;</span></span>

<span class="hljs-keyword">using</span> <span class="hljs-keyword">namespace</span> clang::tooling;
<span class="hljs-keyword">using</span> <span class="hljs-keyword">namespace</span> llvm;

<span class="hljs-keyword">static</span> llvm::<span class="hljs-function">cl::OptionCategory <span class="hljs-title">toolCategory</span><span class="hljs-params">(<span class="hljs-string">"class-analyzer &lt;options&gt;"</span>)</span></span>;

<span class="hljs-function"><span class="hljs-keyword">int</span> <span class="hljs-title">main</span><span class="hljs-params">(<span class="hljs-keyword">int</span> argc, <span class="hljs-keyword">const</span> <span class="hljs-keyword">char</span>** argv)</span>
</span>{
    <span class="hljs-comment">// Use clang's argument parser infrastructure</span>
    <span class="hljs-comment">// This is used for giving clang tooling the path</span>
    <span class="hljs-comment">// to the source files passed in to the tool.</span>
    <span class="hljs-comment">// It also gets the compilation database - a collection</span>
    <span class="hljs-comment">// of the compiler options used in the invocation of the tool</span>
    <span class="hljs-keyword">auto</span> argsParser = CommonOptionsParser::create(
        argc, argv, toolCategory);
    <span class="hljs-keyword">if</span> (!expectedArgsParser) {
        llvm::errs() &lt;&lt; argsParser.takeError();
        <span class="hljs-keyword">return</span> <span class="hljs-number">-1</span>;
    }
    CommonOptionsParser&amp; optionsParser
        = argsParser.get();
    <span class="hljs-function">ClangTool <span class="hljs-title">tool</span><span class="hljs-params">(optionsParser.getCompilations(),
                   optionsParser.getSourcePathList())</span></span>;
    <span class="hljs-keyword">auto</span> myActionFactory
        = <span class="hljs-built_in">std</span>::make_unique&lt;MyFrontendActionFactory&gt;();

    <span class="hljs-keyword">return</span> tool.run(myActionFactory.get());
}
</code></pre>
<p>This source file essentially creates a tool which runs a <code>clang</code> <a target="_blank" href="https://clang.llvm.org/doxygen/classclang_1_1tooling_1_1FrontendActionFactory.html"><code>FrontendActionFactory</code></a>. Now to understand what <code>FrontendActionFactory</code> does, let's take a look at Clang's documentation for it. </p>
<p>We see that it has a pure virtual method, </p>
<pre><code class="lang-cpp"><span class="hljs-function"><span class="hljs-keyword">virtual</span> <span class="hljs-built_in">std</span>::<span class="hljs-built_in">unique_ptr</span>&lt;FrontendAction&gt; <span class="hljs-title">create</span> <span class="hljs-params">()</span> </span>= <span class="hljs-number">0</span>;
</code></pre>
<p>which returns an <a target="_blank" href="https://en.cppreference.com/w/cpp/memory/unique_ptr"><code>std::unique_ptr</code></a> to a <code>[FrontendAction](https://clang.llvm.org/doxygen/classclang_1_1FrontendAction.html)</code> object. <code>FrontendAction</code> is, in its essence, a class which allows callers to perform custom actions as Clang parses the AST of a translation unit given to it. A <a target="_blank" href="https://en.wikipedia.org/wiki/Translation_unit_(programming)">translation unit</a> in simple words is the combined code given to the compiler to create an object file. It contains code included through all the header files + code in a C / C++ source file</p>
<p> This will become clearer as we get further along in the article.</p>
<p>Now we come to writing our own <code>FrontendActionFactory</code> which you can call <code>MyFrontendActionFactory</code>. This is a very simple class which just overrides the <code>create()</code> virtual method. It looks like this:</p>
<pre><code class="lang-cpp"><span class="hljs-comment">// Header file MyFrontendActionFactory.h</span>
<span class="hljs-meta">#<span class="hljs-meta-keyword">pragma</span> once</span>

include&lt;clang/Tooling/Tooling.h&gt;


<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">MyFrontendActionFactory</span> :</span> <span class="hljs-keyword">public</span> clang::tooling::FrontendActionFactory{
    <span class="hljs-keyword">public</span>:
    MyFrontendActionFactory();
    <span class="hljs-function"><span class="hljs-built_in">std</span>::<span class="hljs-built_in">unique_ptr</span>&lt;clang::FrontendAction&gt; <span class="hljs-title">create</span><span class="hljs-params">()</span> <span class="hljs-keyword">override</span></span>;
};                                                         

<span class="hljs-comment">// Source file MyFrontendActionFactory.cpp</span>

<span class="hljs-meta">#<span class="hljs-meta-keyword">include</span> <span class="hljs-meta-string">"MyFrontendActionFactory.h"</span></span>
<span class="hljs-meta">#<span class="hljs-meta-keyword">include</span> <span class="hljs-meta-string">"MyFrontendAction.h"</span></span>

MyFrontendActionFactory::MyFrontendActionFactory() {

}

<span class="hljs-function"><span class="hljs-built_in">std</span>::<span class="hljs-built_in">unique_ptr</span>&lt;clang::FrontendAction&gt; <span class="hljs-title">MyFrontendActionFactory::create</span><span class="hljs-params">()</span> </span>{
    <span class="hljs-keyword">return</span> <span class="hljs-built_in">std</span>::make_unique&lt;MyFrontendAction&gt;();
}
</code></pre>
<p>Since <code>MyFrontendActionFactory::create()</code> needs to return an <code>std::unique_ptr</code> to <code>clang::FrontendAction</code>, we'll need to create a <code>clang::FrontendAction</code> object. </p>
<p>If we look at the Clang documentation for <a target="_blank" href="https://clang.llvm.org/doxygen/classclang_1_1FrontendAction.html"><code>FrontendAction</code></a>, we'll be particularly interested in looking at what we can do with the AST (Abstract Syntax Tree) of the source. </p>
<p>We might spot the following method:</p>
<pre><code class="lang-cpp"><span class="hljs-function"><span class="hljs-keyword">virtual</span> <span class="hljs-built_in">std</span>::<span class="hljs-built_in">unique_ptr</span>&lt; ASTConsumer &gt;
<span class="hljs-title">CreateASTConsumer</span> <span class="hljs-params">(CompilerInstance &amp;CI, StringRef InFile)</span> </span>= <span class="hljs-number">0</span>;
</code></pre>
<p>This is a virtual method that a class which inherits from FrontendAction can implement. It returns an <a target="_blank" href="https://clang.llvm.org/doxygen/classclang_1_1ASTConsumer.html#details"><code>ASTConsumer</code></a> which according to the documentation,</p>
<blockquote>
<p> <em>"...is an abstract interface that should be implemented by clients that read ASTs."</em></p>
</blockquote>
<p>So, this method looks really promising if we want to create something that will let us read the Clang generated AST!</p>
<p>If we look at the <code>FrontendAction</code> documentation again, it shows us that <code>ASTFrontend</code> is a class that inherits from <code>FrontendAction</code>. We also learn that it is:</p>
<blockquote>
<p>"The Abstract base class to use for AST consumer-based frontend actions."</p>
</blockquote>
<p>It only has one pure virtual method: <code>CreateASTConsumer()</code>. This seems promising, since...we might be able to create our own <code>ASTConsumer</code> object.</p>
<p>So, we start by reading through <code>ASTConsumer</code>'s <a target="_blank" href="https://clang.llvm.org/doxygen/classclang_1_1ASTConsumer.html">documentation</a>. We see that it has a virtual method</p>
<pre><code class="lang-cpp"><span class="hljs-keyword">virtual</span> <span class="hljs-keyword">void</span>
clang::ASTConsumer::HandleTranslationUnit(ASTContext &amp;Ctx)
</code></pre>
<p>where the documentation states:</p>
<blockquote>
<p> "<code>HandleTranslationUnit</code> - This method is called when the ASTs for entire translation unit have been parsed". </p>
</blockquote>
<p>This is exactly what we want. We can override this method to do interesting things with the parsed AST.</p>
<p>You might now be wondering – how exactly can we use the parameter passed to this function <code>ASTContext</code> to actually go through the AST? </p>
<p>There's a class in the Clang front end API which can help us here: <a target="_blank" href="https://clang.llvm.org/doxygen/classclang_1_1RecursiveASTVisitor.html"><code>RecursiveASTVisitor</code></a>. This is a class that does a depth-first traversal of the Clang AST and visits each node. It has methods such as <code>VisitDecl()</code>, <code>VisitStmt()</code> and so on which can help us go through virtually the whole source file's AST. </p>
<p>It also has a method which is particularly interesting: <a target="_blank" href="https://clang.llvm.org/doxygen/classclang_1_1RecursiveASTVisitor.html#a99a9e941a07a015bc18d3613c5aa0914"><code>TraverseDecl()</code></a>. This method recursively traverses through all the declarations starting from the root declaration given to it.</p>
<h2 id="heading-putting-it-all-together-in-code">Putting it All Together in Code</h2>
<p>So now what we need to do is give <code>TraverseDecl()</code> the root declaration of our translation unit and it will traverse the entirety of it. We can define special 'hooks' which will get called as this traversal happens. One such hook is:</p>
<pre><code class="lang-cpp"><span class="hljs-function"><span class="hljs-keyword">bool</span> <span class="hljs-title">VisitRecordDecl</span><span class="hljs-params">(<span class="hljs-keyword">const</span> clang::RecordDecl *record)</span></span>;
</code></pre>
<p>This is called each time the <code>RecursiveASTVisitor</code> traverses through a <code>CXXRecordDecl</code> – which is Clang speak for a C++ class. We'll overload this method with our own version to do something interesting: getting the C++ Class' name and seeing if it starts with an upper-case character. </p>
<p>Putting all this together, here's what we get:</p>
<pre><code class="lang-cpp"><span class="hljs-comment">// MyFrontendAction.h header file</span>
<span class="hljs-meta">#<span class="hljs-meta-keyword">pragma</span> once</span>

<span class="hljs-meta">#<span class="hljs-meta-keyword">include</span> <span class="hljs-meta-string">&lt;clang/Frontend/FrontendAction.h&gt;</span></span>

<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">MyFrontendAction</span> :</span> <span class="hljs-keyword">public</span> clang::ASTFrontendAction {
    <span class="hljs-keyword">protected</span>:
        <span class="hljs-function"><span class="hljs-built_in">std</span>::<span class="hljs-built_in">unique_ptr</span>&lt;clang::ASTConsumer&gt; <span class="hljs-title">CreateASTConsumer</span><span class="hljs-params">(clang::CompilerInstance &amp;ci, llvm::StringRef file)</span> <span class="hljs-keyword">override</span></span>;
};    

<span class="hljs-comment">// MyFrontendAction.cpp source file</span>
<span class="hljs-meta">#<span class="hljs-meta-keyword">include</span> <span class="hljs-meta-string">"MyFrontendAction.h"</span></span>
<span class="hljs-meta">#<span class="hljs-meta-keyword">include</span> <span class="hljs-meta-string">"MyASTConsumer.h"</span></span>

<span class="hljs-function"><span class="hljs-built_in">std</span>::<span class="hljs-built_in">unique_ptr</span>&lt;clang::ASTConsumer&gt; <span class="hljs-title">MyFrontendAction::CreateASTConsumer</span><span class="hljs-params">(clang::CompilerInstance &amp;ci, llvm::StringRef file)</span> </span>{
    <span class="hljs-keyword">return</span> <span class="hljs-built_in">std</span>::make_unique&lt;MyASTConsumer&gt;(ci, file);
}
</code></pre>
<pre><code class="lang-cpp">
<span class="hljs-comment">//MyASTConsumer.h header file</span>

<span class="hljs-meta">#<span class="hljs-meta-keyword">pragma</span> once</span>

<span class="hljs-meta">#<span class="hljs-meta-keyword">include</span><span class="hljs-meta-string">&lt;clang/AST/ASTConsumer.h&gt;</span></span>
<span class="hljs-meta">#<span class="hljs-meta-keyword">include</span><span class="hljs-meta-string">&lt;clang/Frontend/CompilerInstance.h&gt;</span></span>

<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">MyASTConsumer</span> :</span> <span class="hljs-keyword">public</span> clang::ASTConsumer {

<span class="hljs-keyword">public</span>:
    MyASTConsumer(clang::CompilerInstance &amp;ci, llvm::StringRef file) {}
    <span class="hljs-function"><span class="hljs-keyword">void</span> <span class="hljs-title">HandleTranslationUnit</span><span class="hljs-params">(clang::ASTContext &amp;context)</span> <span class="hljs-keyword">override</span></span>;
};

<span class="hljs-comment">// MyASTConsumer.cpp source file</span>

<span class="hljs-meta">#<span class="hljs-meta-keyword">include</span> <span class="hljs-meta-string">&lt;clang/AST/RecursiveASTVisitor.h&gt;</span></span>
<span class="hljs-meta">#<span class="hljs-meta-keyword">include</span> <span class="hljs-meta-string">"MyASTConsumer.h"</span></span>

<span class="hljs-meta">#<span class="hljs-meta-keyword">include</span> <span class="hljs-meta-string">&lt;iostream&gt;</span></span>

<span class="hljs-function"><span class="hljs-keyword">static</span> <span class="hljs-keyword">bool</span> <span class="hljs-title">isFirstLetterUpperCase</span><span class="hljs-params">(<span class="hljs-keyword">const</span> <span class="hljs-built_in">std</span>::<span class="hljs-built_in">string</span> &amp;str)</span> </span>{
    <span class="hljs-keyword">return</span> str.size() != <span class="hljs-number">0</span> &amp;&amp; <span class="hljs-built_in">std</span>::<span class="hljs-built_in">isupper</span>(str[<span class="hljs-number">0</span>]);
}
<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">MyASTVisitor</span> :</span> <span class="hljs-keyword">public</span> clang::RecursiveASTVisitor&lt;MyASTVisitor&gt; {
    <span class="hljs-keyword">public</span>:
    <span class="hljs-function"><span class="hljs-keyword">bool</span> <span class="hljs-title">VisitCXXRecordDecl</span><span class="hljs-params">(<span class="hljs-keyword">const</span> clang::RecordDecl *record)</span> </span>{
        <span class="hljs-built_in">std</span>::<span class="hljs-built_in">string</span> name = record-&gt;getNameAsString();

        <span class="hljs-keyword">if</span> (!isFirstLetterUpperCase(name)) {
            <span class="hljs-built_in">std</span>::<span class="hljs-built_in">cout</span> &lt;&lt; <span class="hljs-string">"Record Decl : "</span> &lt;&lt; name
                      &lt;&lt;<span class="hljs-string">" doesn't start with uppercase! \n"</span>;
        }

        <span class="hljs-keyword">return</span> <span class="hljs-literal">true</span>;
    }
    <span class="hljs-function"><span class="hljs-keyword">bool</span> <span class="hljs-title">TraverseDecl</span><span class="hljs-params">(clang::Decl *decl)</span>  </span>{
        <span class="hljs-keyword">return</span>
           clang::RecursiveASTVisitor&lt;MyASTVisitor&gt;::TraverseDecl(decl);
    }
};

<span class="hljs-function"><span class="hljs-keyword">void</span> <span class="hljs-title">MyASTConsumer::HandleTranslationUnit</span><span class="hljs-params">(clang::ASTContext &amp;ctx)</span> </span>{
    clang::TranslationUnitDecl *tuDecl = ctx.getTranslationUnitDecl();
    MyASTVisitor visitor;
    visitor.TraverseDecl(tuDecl);
}
</code></pre>
<p>Now to build, we just do:</p>
<p><code>cd ~/ast-analyzer/build/;  ninja class-analyzer</code></p>
<p>This builds the <code>class-analyzer</code> executable in the <code>build/bin</code> directory.</p>
<p>Now to test out the analyzer, we create a test.cpp source file:</p>
<pre><code class="lang-cpp"><span class="hljs-comment">// test.cpp</span>
<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Test</span> {</span>
<span class="hljs-keyword">public</span>:
 <span class="hljs-keyword">int</span> a;
};

<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">testLower</span> {</span>
<span class="hljs-keyword">public</span>:
 <span class="hljs-keyword">int</span> b;
};

<span class="hljs-function"><span class="hljs-keyword">int</span> <span class="hljs-title">main</span><span class="hljs-params">()</span> </span>{
        <span class="hljs-keyword">return</span> <span class="hljs-number">0</span>;
}
</code></pre>
<p>Run <code>class-analyzer</code> on it:</p>
<pre><code>bin/<span class="hljs-class"><span class="hljs-keyword">class</span>-<span class="hljs-title">analyzer</span> <span class="hljs-title">test</span>.<span class="hljs-title">cpp</span></span>
</code></pre><p>The output of this command is :</p>
<pre><code>Record Decl : testLower doesn<span class="hljs-string">'t start with uppercase!</span>
</code></pre><p>We can use a multitude of such <code>Visit*</code> methods such as <code>VisitEnumDecl</code>, <code>VisitFunctionDecl</code>, <code>VisitVarDecl</code>, and so on to get valuable information about the source file and create our own tools. Just think about any tool which runs and performs actions on code or gives suggestions to the user. </p>
<p>You may think that this seems like a lot of work for a small task. But think about the potential. For example, you could write a tool which automatically gives a user suggestions to improve their code style. Or you could create a tool which analyses C++ code and finds lines of code where there might be security vulnerabilities. </p>
<p>The possibilities are endless. Clang's front-end libraries are extremely powerful and you can build many cool projects and tools with them.</p>
<h2 id="heading-summary">Summary</h2>
<p>In this article, you learned how to get and use the rich collection of Clang's Front-end libraries to parse a C++ source AST. You can use these libraries to write interesting static code analysis tools. </p>
<p>As this article showed, one of the most important parts of the journey of exploring Clang's libraries is the art of reading the API documentation and applying it to the problems your tools aim to solve. I hope you enjoyed the article! </p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ How to Write And Run C and C++ Code in Visual Studio Code ]]>
                </title>
                <description>
                    <![CDATA[ Visual Studio Code (or VS Code for short) is a very common and widely used text editor and IDE (Integrated Development Environment). You can make VS Code very powerful like an IDE using a lot of extensions. Before approaching the process of running y... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/how-to-write-and-run-c-cpp-code-on-visual-studio-code/</link>
                <guid isPermaLink="false">66b9030605ed142b6e64c273</guid>
                
                    <category>
                        <![CDATA[ C++ ]]>
                    </category>
                
                    <category>
                        <![CDATA[ c programming ]]>
                    </category>
                
                    <category>
                        <![CDATA[ compilers ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Visual Studio Code ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Visual Studio Code ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Md. Fahim Bin Amin ]]>
                </dc:creator>
                <pubDate>Fri, 20 Jan 2023 21:45:48 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2023/01/asd.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>Visual Studio Code (or VS Code for short) is a very common and widely used text editor and IDE (Integrated Development Environment). You can make VS Code very powerful like an IDE using a lot of extensions.</p>
<p>Before approaching the process of running your first C or C++ code on Visual Studio Code, let me guide you through the process and get it all set up based on the operating system you are using on your computer.</p>
<h2 id="heading-c-and-c-compilers">C and C++ compilers</h2>
<p>For running C or C++ code, you just need to have a valid C/C++ compiler installed on your computer. If you are using a Linux operating system, then there is a high chance that it is already installed on your system. But we need to make sure that it is correctly installed.</p>
<p>For checking whether or not you have the compiler (GCC/G++/MinGW) installed on your system or not, you have to check the compiler version first. </p>
<p>Simply open your terminal and use <code>gcc --version</code> and <code>g++ --version</code>. If you get the version number, then the compiler is already installed on your system. </p>
<p>You can check the version using the same commands on any operating system, whether that is a Windows, Linux, or macOS-based operating system. </p>
<p>If you get feedback on your terminal that it does not know anything about GCC or G++, then you have to install the compiler correctly. </p>
<p>If you are using the most used Windows operating system, then I already have written an in-depth article showing you all the processes step-by-step on freeCodeCamp. Make sure to read the entire article first, as it also contains a complete video to provide you with complete support.</p>
<p><a target="_blank" href="https://www.freecodecamp.org/news/how-to-install-c-and-cpp-compiler-on-windows/">Embedded content</a></p>
<p>If you are using another operating system, and you don't have the compilers installed, then make sure to install them before proceeding.</p>
<h2 id="heading-how-to-install-vs-code-or-vs-code-insiders">How to Install VS Code or VS Code Insiders</h2>
<p>You have to download Visual Studio Code directly from the official website: <a target="_blank" href="https://code.visualstudio.com/">https://code.visualstudio.com/</a>.</p>
<p>If you want, you can also install VS Code Insiders, and the same process is applicable for that as well. </p>
<p>Visual Studio Code Insiders is actually the "Insiders" build of Visual Studio Code, which contains all the latest features that are shipped daily. You can think of VS Code as the stable release and the VS Code Insiders as the Insiders release of that.</p>
<p>If you want to experience the latest updates instantly, then you might also try Visual Studio Code Insiders (I use it myself). For downloading VS Code Insiders, you can visit the official website for VS Code Insiders here: <a target="_blank" href="https://code.visualstudio.com/insiders/">https://code.visualstudio.com/insiders/</a></p>
<p>Make sure to download the exact file for your operating system.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/01/image-163.png" alt="Image" width="600" height="400" loading="lazy">
<em><strong>Download Page: VS Code</strong></em></p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/01/image-164.png" alt="Image" width="600" height="400" loading="lazy">
<em><strong>Download Page: VS Code Insiders</strong></em></p>
<p>The installation process is pretty basic. But I am going to show you all the steps sequentially. For now, I am going to show you the installation process using VS Code Insiders, but everything you will see here is going to be exactly the same for VS Code as well.</p>
<p>Make sure to click the box on the "I accept the agreement " box and click on <strong>Next</strong>.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/01/image-165.png" alt="Image" width="600" height="400" loading="lazy">
<em><strong>Accept the agreement and click Next</strong></em></p>
<p>Keep everything as it is. Do not change anything from here.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/01/image-168.png" alt="Image" width="600" height="400" loading="lazy">
<em><strong>Click Next</strong></em></p>
<p> Click <strong>Next</strong>. Again, simply click <strong>Next</strong>.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/01/image-170.png" alt="Image" width="600" height="400" loading="lazy">
<em><strong>Click Next</strong></em></p>
<p>Make sure to add the checkmark (✔) on all of the boxes. Then click on <strong>Next</strong>.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/01/image-171.png" alt="Image" width="600" height="400" loading="lazy">
<em><strong>Check all of the boxes, and click Next</strong></em></p>
<p>Click on <strong>Install</strong>.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/01/image-172.png" alt="Image" width="600" height="400" loading="lazy">
<em><strong>Click Install</strong></em></p>
<p>It might take a little time to finish the installation.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/01/image-173.png" alt="Image" width="600" height="400" loading="lazy">
<em><strong>Let it finish...</strong></em></p>
<p>Click on <strong>Finish</strong>.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/01/image-175.png" alt="Image" width="600" height="400" loading="lazy">
<em><strong>Click Finish</strong></em></p>
<p>Congrats - you've successfully installed VS Code/VS Code Insiders on your system. Now, cheers! 🥂</p>
<h2 id="heading-how-to-prepare-vs-codevs-code-insiders-for-c-and-c-code">How to Prepare VS Code/VS Code Insiders For C and C++ Code</h2>
<p>First, open VS Code or VS Code Insiders.</p>
<p>Go to the Extension tab. Search for "C" or "C++" and install the first one that is already verified by Microsoft itself.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/01/image-178.png" alt="Image" width="600" height="400" loading="lazy">
<em><strong>Install C/C++ extension</strong></em></p>
<p>Also, install <strong>C/C++ Extension Pack</strong>. It should also be verified by Microsoft.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/01/image-179.png" alt="Image" width="600" height="400" loading="lazy">
<em><strong>Install C/C++ Extension Pack</strong></em></p>
<p>Then you have to search for <strong>Code Runner</strong> and install the extension as well.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/01/image-180.png" alt="Image" width="600" height="400" loading="lazy">
<em><strong>Install Code Runner Extension</strong></em></p>
<p>Now, we need to change some settings.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/01/image-177.png" alt="Image" width="600" height="400" loading="lazy">
<em><strong>Change some settings</strong></em></p>
<p>Click the <strong>gear</strong> box (It is called the Manage section), and then click <strong>Settings</strong>. Alternatively, you can also use the shortcut keys <code>Ctrl</code> + <code>,</code>. You need to replace the <code>Ctrl</code> key with the Command key for Mac.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/01/image-182.png" alt="Image" width="600" height="400" loading="lazy">
<em><strong>Type "Run code in terminal" and press Enter key</strong></em></p>
<p>In the search bar, type "Run code in terminal" and press the Enter key.</p>
<p>Scroll down a little bit until you find <code>Code-runner: Run In Terminal</code>. Make sure that the box is checked (✔).</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/01/image-184.png" alt="Image" width="600" height="400" loading="lazy">
<em><strong>Make sure to check the box</strong></em></p>
<p>Now you need to restart your VS Code/VS Code Insiders. Simply close and reopen the program.</p>
<h2 id="heading-how-to-test-your-code">How to Test Your Code</h2>
<p>Simply open VS Code/VS Code Insiders, open any folder, and create any file with the extension <code>.c</code> for the C file and <code>.cpp</code> for the C++ file. </p>
<p>After writing your code, you can run the code directly using the play button you'll find in the upper right corner.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/01/image-185.png" alt="Image" width="600" height="400" loading="lazy">
<em><strong>This is how you can run any C/C++ program from VS Code/Insiders</strong></em></p>
<p>It will compile and then run the code directly. After running a code, the code runner button would be set default to run directly. So, your computer is 100% ready for compiling and running any C/C++ programming code.  😀</p>
<h2 id="heading-conclusion">Conclusion</h2>
<p>Thanks for reading the entire article. If it helps you then you can also check out other articles of mine at <a target="_blank" href="https://www.freecodecamp.org/news/author/fahimbinamin/">freeCodeCamp</a>.</p>
<p>If you want to get in touch with me, then you can do so using <a target="_blank" href="https://twitter.com/Fahim_FBA">Twitter</a>, <a target="_blank" href="https://www.linkedin.com/in/fahimfba/">LinkedIn</a>, and <a target="_blank" href="https://github.com/FahimFBA">GitHub</a>. </p>
<p>You can also <a target="_blank" href="https://www.youtube.com/@FahimAmin?sub_confirmation=1">SUBSCRIBE to my YouTube channel</a> (Code With FahimFBA) if you want to learn various kinds of programming languages with a lot of practical examples regularly.</p>
<p>If you want to check out my highlights, then you can do so at my <a target="_blank" href="https://www.polywork.com/fahimbinamin">Polywork timeline</a>.</p>
<p>You can also <a target="_blank" href="https://fahimbinamin.com/">visit my website</a> to learn more about me and what I'm working on.</p>
<p>Thanks a bunch!</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ What is a Compiler? Compilers in C Explained for Beginners ]]>
                </title>
                <description>
                    <![CDATA[ Did you know that it is thanks to compilers that software exists? Exactly – compilers are very important, and some form of a compiler exists in all programming languages. But, what is a compiler? What do they do exactly? This article will teach you: ... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/what-is-a-compiler-in-c/</link>
                <guid isPermaLink="false">66ba534ef77647345442b9d3</guid>
                
                    <category>
                        <![CDATA[ beginners guide ]]>
                    </category>
                
                    <category>
                        <![CDATA[ c programming ]]>
                    </category>
                
                    <category>
                        <![CDATA[ compilers ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Tiago Capelo Monteiro ]]>
                </dc:creator>
                <pubDate>Mon, 14 Mar 2022 18:39:43 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2022/03/1-YhjIVZXE56R6YZaTF-Lzig.jpeg" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>Did you know that it is thanks to compilers that software exists?</p>
<p>Exactly – compilers are very important, and some form of a compiler exists in all programming languages.</p>
<p>But, what is a compiler? What do they do exactly?</p>
<p>This article will teach you:</p>
<ol>
<li><p>What a compiler is with an analogy.</p>
</li>
<li><p>The basic history of C compilers.</p>
</li>
</ol>
<p>Don’t worry, you don’t need programming experience to understand what a compiler is.</p>
<p>You just need to understand the concept first, and then if you want, you can go for the technical definition.</p>
<h2 id="heading-1-what-is-a-compiler-an-analogy">1. What is a Compiler? An Analogy</h2>
<p><img src="https://miro.medium.com/max/1400/1*xFzl6UbF6XI6V0_Tnx-PYg.jpeg" alt="Image of phone" width="600" height="400" loading="lazy"></p>
<p><em>Photo by</em> <a target="_blank" href="https://www.pexels.com/@lastly?utm_content=attributionCopyText&amp;utm_medium=referral&amp;utm_source=pexels"><strong><em>Tyler Lastovich</em></strong></a> <strong><em>from</em></strong> <a target="_blank" href="https://www.pexels.com/photo/black-iphone-7-on-brown-table-699122/?utm_content=attributionCopyText&amp;utm_medium=referral&amp;utm_source=pexels"><strong><em>Pexels</em></strong></a></p>
<p><strong>Imagine that you are learning a language (French, Spanish, or Portuguese) and you want to know the meaning of a word or sentence.</strong></p>
<p><strong>To do that, you are going to use Google Translate.</strong></p>
<p><strong>The first step is knowing what you will type into Google Translate and checking if it is typed correctly.</strong></p>
<p><strong>The second step is choosing the language you want to convert. For many readers, it will be English.</strong></p>
<p><strong>The third and final step is just getting to know what that sentence means in English.</strong></p>
<p><strong>Essentially, you just typed in Google Translate a sentence or word you did not understand. Google Translate translated that sentence into English.</strong></p>
<p><strong><em>Example: nadar(Portuguese) –&gt; swimming (English)</em></strong></p>
<p><strong>The same thing happens in programming.</strong></p>
<p><strong>In this case, we are using the C language.</strong></p>
<p><strong>The first step you must take is to know what you will type in the .c file and if it is typed correctly.</strong></p>
<p><strong>In this example, the file is called main.c_._</strong></p>
<pre><code class="lang-c"><span class="hljs-meta">#<span class="hljs-meta-keyword">include</span> <span class="hljs-meta-string">&lt;stdio.h&gt;</span></span>

<span class="hljs-function"><span class="hljs-keyword">int</span> <span class="hljs-title">main</span><span class="hljs-params">()</span>
</span>{
    <span class="hljs-built_in">printf</span>(<span class="hljs-string">"Hello World"</span>);

    <span class="hljs-keyword">return</span> <span class="hljs-number">0</span>;
}
</code></pre>
<p><strong><em>First step: This code will print “Hello world”\</em>**</strong></p>
<p><strong>The second step is to compile it. It will be compiled according to the compiler you have.</strong></p>
<pre><code class="lang-bash">gcc -o main main.c -Wall
</code></pre>
<p><strong><em>Second step: Command to compile c code\</em>**</strong></p>
<p><strong>The third and final step is simply getting to know the output of the program – to make sure it is running like we want.</strong></p>
<p><strong>Quick note: if you want to know what each word in the command line terminal means, please check out the “More…” section in this article!</strong></p>
<p><strong><em>Third step: Hello world!\</em>**</strong></p>
<p><strong>You can see in the image below a visual explanation of the compiling process:</strong></p>
<p><strong><em>Comparing the compilation of a C file with the translation of words</em></strong></p>
<h2 id="heading-how-c-compilers-work"><strong>How C Compilers Work</strong></h2>
<p><strong><em>Photo by</em></strong> <a target="_blank" href="https://www.pexels.com/@jeshoots?utm_content=attributionCopyText&amp;utm_medium=referral&amp;utm_source=pexels"><strong><em>JÉSHOOTS\</em>**</strong></a> <strong><em>from</em></strong> <a target="_blank" href="https://www.pexels.com/photo/person-holding-sony-ps4-dualshock-4-21067/?utm_content=attributionCopyText&amp;utm_medium=referral&amp;utm_source=pexels"><strong><em>Pexels\</em>**</strong></a></p>
<p><strong>Over the years, tech has evolved at an incredible pace. The same applies to compilers.</strong></p>
<p><strong>The C compiler has, over time, evolved into many versions.</strong></p>
<p><strong>Just like PlayStation – there is the Playstation 2, Playstation 3, Playstation 4, and so on.</strong></p>
<p><strong>The same is true for C compilers. Once it was <em>standardized,</em> many versions were created:</strong></p>
<ul>
<li><p><strong>C89/90, a version of C once <em>standardized,</em></strong></p>
</li>
<li><p><strong>C99 replaced C89 and C90 in 1999.</strong></p>
</li>
<li><p><strong>C11 replaced C99 in 2011.</strong></p>
</li>
<li><p><strong>C17 replaced C11 in 2018.</strong></p>
</li>
<li><p><strong>C2X will replace C17 in 2023.</strong></p>
</li>
</ul>
<p><strong>Just like with a PlayStation, each new version has new features.</strong></p>
<p><strong>Some people prefer just playing on their PlayStation2.</strong></p>
<p><strong>It’s the same with programmers. For a variety of reasons, programmers may prefer to write and debug C code with the C99 or C11.</strong></p>
<h2 id="heading-more-about-compilers"><strong>More About Compilers</strong></h2>
<p><strong>What exactly does <em>“gcc -o main main.c -Wall”</em> mean, that we saw in the code above? Let's break it down piece by piece.</strong></p>
<p><code>gcc</code> is the command that invokes the compilation process (preprocessing, compilation, assembly, and linking).</p>
<p><code>-o main</code> indicates that the name of the executable file created by the compilation of "main.c" is going to be called "main".</p>
<p><code>main.c</code> is the name of the file to be compiled.</p>
<p><strong>The</strong> <code>-Wall</code> option enables compiler warnings. Compiler warnings let you know that something in your code isn't quite right.</p>
<p><strong>This is similar to Grammarly. If Grammarly suggests changing a sentence, you should in most cases change it to make it clearer and more correct.</strong></p>
<p><strong>Otherwise, if you try to change something in a phrase that's already right, it can become illegible.</strong></p>
<p><strong>In the same way, if you ignore warnings in code, it can ultimately cause major bugs and your project might even fail.</strong></p>
<h3 id="heading-what-does-standardized-mean"><strong>What does "Standardized" mean?</strong></h3>
<p><strong>So you might be wondering, what does “<em>standardized</em>” mean that we saw above?</strong></p>
<p><strong><em>Photo by</em></strong> <a target="_blank" href="https://www.pexels.com/@pixabay?utm_content=attributionCopyText&amp;utm_medium=referral&amp;utm_source=pexels"><strong><em>Pixabay\</em>**</strong></a> <strong><em>from</em></strong> <a target="_blank" href="https://www.pexels.com/photo/architecture-building-construction-daylight-534220/?utm_content=attributionCopyText&amp;utm_medium=referral&amp;utm_source=pexels"><strong><em>Pexels\</em>**</strong></a></p>
<p><strong>Let's look at it through another analogy. There are many ways to build a house. But there is a certain way that is generally both the most efficient and the safest.</strong></p>
<p><strong>Because of this, people and organizations must agree that there is a standard way of building a house.</strong></p>
<p><strong>The process of creating that standard is called standardization.</strong></p>
<p><strong>When a set of rules becomes a standard, the set of rules becomes standardized_._</strong></p>
<p><strong>This set of rules can be a law, a certificate, or just a basic convention used by workers in a certain field.</strong></p>
<p><strong>The same applies to C compilers.</strong></p>
<p><strong>It is standardization that helps people agree on how things should be done, whether it is C compilers, car components, or anything else.</strong></p>
<p><strong>Standardization can also help people agree on which version of C to use. C compilers are an example.</strong></p>
<p><strong>The C compiler has long been considered a fundamental component of software development.</strong></p>
<p><strong>As a result of the C compiler standard, developers can compile and run other people's code without worrying that their compilers will not work.</strong></p>
<p><strong>In order to create such an important building block of the industry, there must be an organization that is responsible for establishing standards</strong></p>
<p><strong>Many organizations create and manage standards. In the case of C compilers, ISO (International Organization for Standardization) manages the standards.</strong></p>
<p><strong>As long as the ISO manages future C compiler standards, programmers and companies can develop reliable software.</strong></p>
<h2 id="heading-wrapping-up"><strong>Wrapping Up</strong></h2>
<p><strong>Thanks for reading! Now you understand:</strong></p>
<ul>
<li><p><strong>What a compiler is</strong></p>
</li>
<li><p><strong>The basic history of C compilers</strong></p>
</li>
<li><p><strong>What standardization means</strong></p>
</li>
</ul>
<p><a target="_blank" href="https://github.com/tiagomonteiro0715/freecodecamp-my-articles-source-code/tree/main/What%20exactly%20is%20a%20compiler%3F"><strong>Here is the GitHub repository</strong></a> <strong>with the code and image files I created.</strong></p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ How to Install C and C++ Compilers on Windows ]]>
                </title>
                <description>
                    <![CDATA[ If you want to run C or C++ programs in your Windows operating system, then you need to have the right compilers.  The MinGW compiler is a well known and widely used software for installing GCC and G++ compilers for the C and C++ programming language... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/how-to-install-c-and-cpp-compiler-on-windows/</link>
                <guid isPermaLink="false">66b902e23eae8584882959b9</guid>
                
                    <category>
                        <![CDATA[ C++ ]]>
                    </category>
                
                    <category>
                        <![CDATA[ c programming ]]>
                    </category>
                
                    <category>
                        <![CDATA[ compilers ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Md. Fahim Bin Amin ]]>
                </dc:creator>
                <pubDate>Tue, 22 Feb 2022 18:04:59 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2022/02/banner_freeCodeCamp.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>If you want to run C or C++ programs in your Windows operating system, then you need to have the right compilers. </p>
<p>The MinGW compiler is a well known and widely used software for installing GCC and G++ compilers for the C and C++ programming languages. </p>
<p>But many devs face difficulties when installing the compiler, so I am going to show you all the steps to do so in this article with screenshots to help you get it done. </p>
<p>I will be using Windows 11, but the same process is applicable for all other Windows operating systems unless you are using Windows XP (You need to change some steps in Windows XP).</p>
<p>If you'd like to watch the video I made on this topic as well, here it is:</p>
<div class="embed-wrapper">
        <iframe width="560" height="315" src="https://www.youtube.com/embed/c7FjV8Gwk_M" style="aspect-ratio: 16 / 9; width: 100%; height: auto;" title="YouTube video player" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" referrerpolicy="strict-origin-when-cross-origin" allowfullscreen="" loading="lazy"></iframe></div>
<h2 id="heading-install-msys2">Install MSYS2</h2>
<p>Firstly we need to download an executable file from MSYS2. Go to the official website of MSYS2: <a target="_blank" href="https://www.msys2.org/">https://www.msys2.org/</a>. The website looks like below as of today.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/02/Screenshot--8-.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>Scroll down a little bit until you find the download button for the executable file.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/02/Screenshot--9-.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>Simply click on the installer button and save the installer file in any place you want.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/02/Screenshot--10--1.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>Finish downloading the executable file. It should not take much time depending on your internet speed.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/02/Screenshot--11-.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>After downloading the file, we will get this executable file.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/02/Screenshot--12-.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>Double click on the executable file. Then click <code>Next</code>.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/02/Screenshot--13-.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>Keep the name as it is, and click <code>Next</code>.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/02/Screenshot--14--1.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>Keep all this as it is, and click <code>Next</code>.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/02/Screenshot--15-.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>Give it some time to finish the installation process.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/02/Screenshot--16-.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>If you keep the checkmark, then the MSYS2 terminal will open once you click <code>Finish</code>. </p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/02/Screenshot--17-.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>I prefer to do it this way, but if you want to do the remaining tasks later, then you need to open the terminal by yourself from the start menu. </p>
<p>In that case, you have to click the start button &gt; Search for <code>MSYS2</code> and click on the terminal like in the following picture:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/02/Screenshot--26-.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>Let me assume that we have opened the <strong>MSYS2 MSYS</strong> terminal successfully.</p>
<p>Apply the command <code>pacman -Syu</code> to update the package database and the base packages.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/02/Screenshot--19-.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>Type <code>Y</code> and press the enter key if you get this type of installation prompt.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/02/Screenshot--20-.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/02/Screenshot--21-.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/02/Screenshot--22-.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>Type <code>Y</code> and press the enter key.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/02/Screenshot--23-.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/02/Screenshot--24-.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>The terminal will be closed. We have to open the terminal manually and update the rest of the packages.</p>
<p>Click the start button.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/02/Screenshot--25-.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>Search the folder named <strong>MSYS2 64bit</strong>. Click on the folder to expand and get the terminal. Open the terminal by clicking <strong>MSYS2 MSYS</strong>.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/02/Screenshot--26--1.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>Update the rest of the packages by applying the command, <code>pacman -Su</code>. You might need to apply the command <code>pacman -Sy</code> if the terminal tells you to do that.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/02/Screenshot--27-.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>If you get any installation prompt, then you need to type <code>Y</code> or <code>y</code> and press the enter key.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/02/Screenshot--28-.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/02/Screenshot--29-.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>Wait a little to finish the installation.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/02/Screenshot--30-.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/02/Screenshot--31-.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>Close the window after finishing the installation.</p>
<h2 id="heading-install-the-gcc-and-g-compilers">Install the GCC and G++ Compilers</h2>
<p>Click the start button. Find the <strong>MSYS2 64bit</strong> folder. Click on that folder to expand it.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/02/Screenshot--32-.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>If you are using a <strong>64 bit</strong> operating system like I am, then we need to use the <strong>MSYS2 MinGW x64</strong> terminal. Click on the terminal to open that.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/02/Screenshot--33-.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>⚠️ But, if you are using a <strong>32 bit</strong> operating system, then you have to use the <strong>MSYS2 MinGW x86</strong> terminal. Then, you need to open that terminal.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/02/Screenshot--34-.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>As I am using a <strong>64 bit</strong> operating system, I have opened the terminal for 64 bit. Apply the command <code>pacman -S mingw-w64-x86_64-gcc</code> to install the compilers.</p>
<p>⚠️ If you are using a <strong>32 bit</strong> operating system, then you have to apply the command <code>pacman -S mingw-w64-i686-gcc</code> in your 32 bit terminal.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/02/Screenshot--35-.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>Wait for a little while.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/02/Screenshot--36-.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>Type <code>Y</code> or <code>y</code> and press the enter key if you get the installation prompts.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/02/Screenshot--37-.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/02/Screenshot--38-.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>Give it some time to finish the installation process.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/02/Screenshot--39-.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/02/Screenshot--39--1.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>You've now finished installing the compilers.</p>
<h2 id="heading-how-to-install-the-debugger">How to Install the Debugger</h2>
<p>If you are using a <strong>64 bit</strong> operating system like I am, then you have to apply the command <code>pacman -S mingw-w64-x86_64-gdb</code>.</p>
<p>⚠️ If you are using a <strong>32 bit</strong> operating system, then you have to apply the command <code>pacman -S mingw-w64-i686-gdb</code> in your 32 bit terminal.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/02/Screenshot--41-.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>If you get any installation prompt, then simply type <code>Y</code> or <code>y</code> and press the enter key.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/02/Screenshot--42-.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/02/Screenshot--38--1.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>Give it some time to finish the installation.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/02/Screenshot--44-.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/02/Screenshot--45-.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>You can close the terminal.</p>
<h2 id="heading-how-to-add-the-directory-to-the-path-of-the-environment-variables">How to Add the Directory to the Path of the Environment Variables</h2>
<p>Open the file explorer.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/02/Screenshot--46-.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>I am assuming that you have installed the MSYS into the default directory like I have. If you used custom directories, then you need to go to the directory where you installed it.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/02/Screenshot--47-.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>If you are using a 64 bit operating system like I am, then go to the <strong>mingw64</strong> folder.</p>
<p>⚠️ If you are using a 32 bit operating system, then go to the <strong>mingw32</strong> folder.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/02/Screenshot--48-.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>We have to go to the binary folder now. Go to the <strong>bin</strong> folder.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/02/Screenshot--49-.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>⚠️ If you are using a 32 bit operating system, then you have to go into your <strong>mingw32</strong> folder &gt; <strong>bin</strong> folder.</p>
<p>Copy the directory.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/02/Screenshot--51-.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>⚠️ If you are using a 32 bit operating system, and you also installed the MSYS2 in the default directory, then your directory should be like the following:</p>
<pre><code>C:\msys64\mingw32\bin
</code></pre><p>Open the <strong>Advanced System Settings</strong>. You can do that in many ways. A simple way is to simply click the start button and search for it like the below screenshot.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/02/Screenshot--52-.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>Click <strong>Environment Variables</strong> from the Advanced tab.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/02/Screenshot--54-.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>Click on <strong>Path</strong> and select that. Then click <strong>Edit</strong>.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/02/Screenshot--57-.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>A window will appear as below:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/02/Screenshot--58-.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>Click <strong>New</strong>.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/02/Screenshot--59-.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>A blank box will appear.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/02/Screenshot--60-.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>Paste the directory here.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/02/Screenshot--61-.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/02/Screenshot--62-.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>Click <strong>OK</strong>.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/02/Screenshot--63-.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>Click <strong>OK</strong>.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/02/Screenshot--65-.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>Click <strong>OK</strong>.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/02/Screenshot--66-.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>If you want to get all the steps in a video, then you can watch <a target="_blank" href="https://www.youtube.com/watch?v=0HD0pqVtsmw">this video</a> as well.</p>
<h2 id="heading-check-the-install">Check the Install</h2>
<p>Now it is time to check whether we have successfully installed all of the above or not.</p>
<p>Open the terminal / PowerShell / CMD and apply the commands serially:</p>
<p>For checking the <strong>GCC</strong> version:</p>
<pre><code class="lang-powershell">gcc -<span class="hljs-literal">-version</span>
</code></pre>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/02/Screenshot--68-.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>For checking the <strong>G++</strong> version:</p>
<pre><code class="lang-powershell">g++ -<span class="hljs-literal">-version</span>
</code></pre>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/02/Screenshot--69-.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>For checking the <strong>GDB</strong> version:</p>
<pre><code class="lang-powershell">gdb -<span class="hljs-literal">-version</span>
</code></pre>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/02/Screenshot--70-.png" alt="Image" width="600" height="400" loading="lazy"></p>
<h2 id="heading-conclusion">Conclusion</h2>
<p>I hope this article helps you install your compilers on the Windows operating system for C and C++ programs. </p>
<p>Thanks for reading the entire article. If it helps you then you can also check out other articles of mine at <a target="_blank" href="https://www.freecodecamp.org/news/author/fahimbinamin/">freeCodeCamp</a>.</p>
<p>If you want to get in touch with me, then you can do so using <a target="_blank" href="https://twitter.com/Fahim_FBA">Twitter</a>, <a target="_blank" href="https://www.linkedin.com/in/fahimfba/">LinkedIn</a>, and <a target="_blank" href="https://github.com/FahimFBA">GitHub</a>. </p>
<p>You can also <a target="_blank" href="https://www.youtube.com/@FahimAmin?sub_confirmation=1">SUBSCRIBE to my YouTube channel</a> (Code With FahimFBA) if you want to learn various kinds of programming languages with a lot of practical examples regularly.</p>
<p>If you want to check out my highlights, then you can do so at my <a target="_blank" href="https://www.polywork.com/fahimbinamin">Polywork timeline</a>.</p>
<p>You can also <a target="_blank" href="https://fahimbinamin.com/">visit my website</a> to learn more about me and what I'm working on.</p>
<p>Thanks a bunch!</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ TypeScript Types Explained – A Mental Model to Help You Think in Types ]]>
                </title>
                <description>
                    <![CDATA[ By TK One day I came across this tweet from Lari Mazza: As a software engineer who learned Python, Ruby, JavaScript, and Clojure first, when I tried C++ it was a horror movie. I couldn't do much, and it was so counterproductive and frustrating. Mayb... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/a-mental-model-to-think-in-typescript-2/</link>
                <guid isPermaLink="false">66d852a75732345ee5fa9335</guid>
                
                    <category>
                        <![CDATA[ compilers ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Functional Programming ]]>
                    </category>
                
                    <category>
                        <![CDATA[ JavaScript ]]>
                    </category>
                
                    <category>
                        <![CDATA[ programming languages ]]>
                    </category>
                
                    <category>
                        <![CDATA[ software development ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Software Engineering ]]>
                    </category>
                
                    <category>
                        <![CDATA[ TypeScript ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Web Development ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ freeCodeCamp ]]>
                </dc:creator>
                <pubDate>Tue, 21 Jul 2020 11:05:00 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2020/07/cover.jpg" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>By TK</p>
<p>One day I came across this <a target="_blank" href="https://twitter.com/larimaza/status/1275747670989176833">tweet</a> from Lari Mazza:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2020/07/typescript.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>As a software engineer who learned Python, Ruby, JavaScript, and Clojure first, when I tried C++ it was a horror movie. I couldn't do much, and it was so counterproductive and frustrating. Maybe because I was doing everything wrong and I didn't understand types the right way.</p>
<p>But even though I had so many problems, I could implement a bunch of <a target="_blank" href="https://github.com/leandrotk/algorithms">algorithms and data structures</a>.</p>
<p>Now that I'm using more and more TypeScript in my day-to-day job and <a target="_blank" href="https://github.com/leandrotk/laziness">my side projects</a>, I feel I'm more prepared to confront types. Actually, not confront, but use them in my favor.</p>
<p>This post is my attempt to help developers think more in types and understand this mental model.</p>
<h2 id="heading-thinking-in-javascript-types">Thinking in JavaScript types</h2>
<p>If you're here, you've probably heard that TypeScript is a superset of JavaScript. If not, great, you just learned something new today. YAY!</p>
<p>TypeScript is a superset because any JavaScript code is valid in TypeScript, syntactically speaking. It may or may not compile depending on the TypeScript compiler configuration. But in terms of syntax, it works just fine. </p>
<p>This is why you can migrate JavaScript to TypeScript progressively by just replacing the <code>.js</code> extension with the <code>.ts</code>. Everything will be without type declarations (the <code>any</code> type), but that's another story.</p>
<p>Also, if you code in JavaScript - or any other programming language - you probably think in types:</p>
<ul>
<li>"Hm, it is a list of integers, so I'll need to filter only the even numbers and return a new list"</li>
<li>"This is an object, but I just need to get this string value from the property X"</li>
<li>"This function receives two parameters. Both A and B are integers and I want to sum them"</li>
</ul>
<p>Yeah, you get the idea. We think in types. But they are just in our heads. We constantly think about them because we need to know how to handle, parse, or modify data. We need to know which methods we are allowed to use in this object type.</p>
<p>To give a more concrete example, imagine you want to sum the price of all products. A product object looks like this:</p>
<pre><code class="lang-typescript"><span class="hljs-keyword">const</span> product = {
  title: <span class="hljs-string">'Some product'</span>,
  price: <span class="hljs-number">100.00</span>,
};
</code></pre>
<p>But now with a list of products:</p>
<pre><code class="lang-typescript"><span class="hljs-keyword">const</span> products = [
  {
    title: <span class="hljs-string">'Product 1'</span>,
    price: <span class="hljs-number">100.00</span>,
  },
  {
    title: <span class="hljs-string">'Product 2'</span>,
    price: <span class="hljs-number">25.00</span>,
  },
  {
    title: <span class="hljs-string">'Product 3'</span>,
    price: <span class="hljs-number">300.00</span>,
  }
];
</code></pre>
<p>Ok! Now we want a function to sum all the products prices.</p>
<pre><code class="lang-typescript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">sumAllPrices</span>(<span class="hljs-params">products</span>) </span>{
  <span class="hljs-keyword">return</span> products.reduce(<span class="hljs-function">(<span class="hljs-params">sum, product</span>) =&gt;</span> sum + product.price, <span class="hljs-number">0</span>);
};

sumAllPrices(products); <span class="hljs-comment">// 425</span>
</code></pre>
<p>Just receive the products as the argument and reduce all product prices. JavaScript works just fine. But while building this function you start to think about the data and how to handle it properly.</p>
<p>The first part: products as an argument. Here you just think: "well, we're receiving a list of some objects". Yeah, in our heads the products are a list. This is why we can think of using the <code>reduce</code> method. It is a method from the <code>Array</code> prototype.</p>
<p>Then we can think about the object in detail. We know that the product object has a <code>price</code> property. And this property is a number. This is why we can do <code>product.price</code> and sum with the accumulator.</p>
<p>Recapping:</p>
<ul>
<li><code>products</code> is a list of objects.</li>
<li>As a list, we can use the <code>reduce</code> method, as this method is a member of the <code>Array</code> prototype.</li>
<li>The <code>produce</code> object has some properties. One of them is the <code>price</code>, which is a number.</li>
<li>As a number property, we can use it to sum with the reduce accumulator.</li>
<li>We wanted to return a number, the sum of all products prices.</li>
</ul>
<p>We are always thinking of data types, we just need to add the type annotations to make it more explicit and ask the compiler for help. Our memory is limited and the compilers are here to help us, humans.</p>
<p>The type system will not only make our data more consistent, but it can also provide autocompletion for data types. It knows the types, so it can show the members for the data. We will take a look at this idea later. Here I just wanted to show that we think in types in our heads.</p>
<h2 id="heading-simples-types-amp-simple-uses">Simples Types &amp; Simple Uses</h2>
<p>So we are ready to use some strongly typed programming languages like TypeScript. We simply need to explicitly add type annotations to our data structures. It's simple, right? </p>
<p>But sometimes it's not that easy (usually it's not easy when you come from dynamically typed languages. You feel unproductive. It feels like a battle against types). The idea here is to make this learning curve smoother and more fun.</p>
<p>Here we will see many examples of how to use types in TypeScript. We'll start with easy and silly examples and progressively make it more complex while designing the mental model to think in types.</p>
<p>As in JavaScript, TypeScript also has basic data types like <code>number</code>, <code>string</code>, <code>boolean</code>, <code>null</code>, etc. You can find all the basic data types in the <a target="_blank" href="https://www.typescriptlang.org/docs/handbook/basic-types.html">TypeScript Docs</a>.</p>
<p>With these units of data, we can make our programs more useful. To be more practical, let's get a simple example. A <code>sum</code> function.</p>
<p>How does it work in JavaScript?</p>
<pre><code class="lang-typescript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">sum</span>(<span class="hljs-params">a, b</span>) </span>{
  <span class="hljs-keyword">return</span> a + b;
}
</code></pre>
<p>Everything ok? Good.</p>
<p>Now let's use it:</p>
<pre><code class="lang-typescript">sum(<span class="hljs-number">1</span>, <span class="hljs-number">2</span>); <span class="hljs-comment">// 3</span>
sum(<span class="hljs-number">2</span>, <span class="hljs-number">2</span>); <span class="hljs-comment">// 4</span>
sum(<span class="hljs-number">0</span>, <span class="hljs-string">'string'</span>); <span class="hljs-comment">// '0string'   WTF!</span>
</code></pre>
<p>The first two calls are what we expect to happen in our system. But JavaScript is very flexible, it lets us provide any value to this function. </p>
<p>The last call is bizarre. We can call with a string, but it will return an unexpected result. It doesn't break in development, but it will result in strange behavior in runtime.</p>
<p>What do we want? We want to add some constraints to the function. It will only be able to receive numbers. That way, we narrow the possibility of having unexpected behaviors. And the function return type is also a number.</p>
<pre><code class="lang-typescript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">sum</span>(<span class="hljs-params">a: <span class="hljs-built_in">number</span>, b: <span class="hljs-built_in">number</span></span>): <span class="hljs-title">number</span> </span>{
  <span class="hljs-keyword">return</span> a + b;
}
</code></pre>
<p>Great! It was very simple. Let's call again.</p>
<pre><code class="lang-typescript">sum(<span class="hljs-number">1</span>, <span class="hljs-number">2</span>); <span class="hljs-comment">// 3</span>
sum(<span class="hljs-number">2</span>, <span class="hljs-number">2</span>); <span class="hljs-comment">// 4</span>
sum(<span class="hljs-number">0</span>, <span class="hljs-string">'string'</span>); <span class="hljs-comment">// Argument of type '"string"' is not assignable to parameter of type 'number'.</span>
</code></pre>
<p>As we type annotate our function, we provide information to the compiler to see if everything is correct. It will follow the constraints we added to the function.</p>
<p>So the first two calls are the same as in JavaScript. It will return the correct calculation. But in the last one we have an error in compile time. This is important. The error now happens in compile time and prevents us from shipping incorrect code to production. It says that the <code>string</code> type is not part of the set of values in the <code>number</code> type universe.</p>
<p>For basic types, we just need to add a colon followed by the type definition.</p>
<pre><code class="lang-typescript"><span class="hljs-keyword">const</span> isTypescript: <span class="hljs-built_in">boolean</span> = <span class="hljs-literal">true</span>;
<span class="hljs-keyword">const</span> age: <span class="hljs-built_in">number</span> = <span class="hljs-number">24</span>;
<span class="hljs-keyword">const</span> username: <span class="hljs-built_in">string</span> = <span class="hljs-string">'tk'</span>;
</code></pre>
<p>Now let's increase the challenge. Remember the product object code we wrote in JavaScript? Let's implement it again, but now with the TypeScript mindset.</p>
<p>Just to remember what we are talking about:</p>
<pre><code class="lang-typescript"><span class="hljs-keyword">const</span> product = {
  title: <span class="hljs-string">'Some product'</span>,
  price: <span class="hljs-number">100.00</span>,
};
</code></pre>
<p>This is the product value. It has a <code>title</code> as <code>string</code> and the <code>price</code> as <code>number</code>. For now, this is what we need to know.</p>
<p>The object type would be something like this:</p>
<pre><code class="lang-typescript">{ title: <span class="hljs-built_in">string</span>, price: <span class="hljs-built_in">number</span> }
</code></pre>
<p>And we use this type to annotate our function:</p>
<pre><code class="lang-typescript"><span class="hljs-keyword">const</span> product: { title: <span class="hljs-built_in">string</span>, price: <span class="hljs-built_in">number</span> } = {
  title: <span class="hljs-string">'Some product'</span>,
  price: <span class="hljs-number">100.00</span>,
};
</code></pre>
<p>With this type, the compiler will know how to handle inconsistent data:</p>
<pre><code class="lang-typescript"><span class="hljs-keyword">const</span> wrongProduct: { title: <span class="hljs-built_in">string</span>, price: <span class="hljs-built_in">number</span> } = {
  title: <span class="hljs-number">100.00</span>, <span class="hljs-comment">// Type 'number' is not assignable to type 'string'.</span>
  price: <span class="hljs-string">'Some product'</span>, <span class="hljs-comment">// Type 'string' is not assignable to type 'number'.</span>
};
</code></pre>
<p>Here it breaks down into two different properties:</p>
<ul>
<li>The <code>title</code> is a <code>string</code> and should not receive a <code>number</code>.</li>
<li>The <code>price</code> is a <code>number</code> and should not receive a <code>string</code>.</li>
</ul>
<p>The compiler helps us to catch type errors like that.</p>
<p>We could improve this type annotation by using a concept called <code>Type Aliases</code>. It's a way to create a new name for a specific type.</p>
<p>In our case, the product type could be:</p>
<pre><code class="lang-typescript"><span class="hljs-keyword">type</span> Product = {
  title: <span class="hljs-built_in">string</span>;
  price: <span class="hljs-built_in">number</span>;
};

<span class="hljs-keyword">const</span> product: Product = {
  title: <span class="hljs-string">'Some product'</span>,
  price: <span class="hljs-number">100.00</span>,
};
</code></pre>
<p>It's better to visualize the type, add semantics, and maybe reuse in our system.</p>
<p>Now that we have this product type, we can use it to type the products list. The syntax looks like this: <code>MyType[]</code>. In our case, <code>Product[]</code>.</p>
<pre><code class="lang-typescript"><span class="hljs-keyword">const</span> products: Product[] = [
  {
    title: <span class="hljs-string">'Product 1'</span>,
    price: <span class="hljs-number">100.00</span>,
  },
  {
    title: <span class="hljs-string">'Product 2'</span>,
    price: <span class="hljs-number">25.00</span>,
  },
  {
    title: <span class="hljs-string">'Product 3'</span>,
    price: <span class="hljs-number">300.00</span>,
  }
];
</code></pre>
<p>Now the function <code>sumAllPrices</code>. It will receive the product and return a number, the sum of all product prices.</p>
<pre><code class="lang-typescript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">sumAllPrices</span>(<span class="hljs-params">products: Product[]</span>): <span class="hljs-title">number</span> </span>{
  <span class="hljs-keyword">return</span> products.reduce(<span class="hljs-function">(<span class="hljs-params">sum, product</span>) =&gt;</span> sum + product.price, <span class="hljs-number">0</span>);
};
</code></pre>
<p>This is very interesting. As we typed the product, when we write <code>product.</code>, it will show the possible properties we can use. In the product type case, it will show the properties <code>price</code> and <code>title</code>.</p>
<pre><code class="lang-typescript">sumAllPrices(products); <span class="hljs-comment">// 425</span>
sumAllPrices([]); <span class="hljs-comment">// 0</span>
sumAllPrices([{ title: <span class="hljs-string">'Test'</span>, willFail: <span class="hljs-literal">true</span> }]); <span class="hljs-comment">// Type '{ title: string; willFail: true; }' is not assignable to type 'Product'.</span>
</code></pre>
<p>Passing the <code>products</code> will result in the value <code>425</code>. An empty list will result in the value <code>0</code>. And if we pass an object with a different structure - TypeScript has a structural type system and we will dig deep into this topic later - the compiler will throw a type error telling that the structure is not part of the <code>Product</code> type.</p>
<h2 id="heading-structural-typing">Structural Typing</h2>
<p>Structural typing is a type of type compatibility. It's a way to understand the compatibility between types based on its structure: features, members, properties. Some languages have type compatibility based on the names of the types, and it's called nominal typing.</p>
<p>For example, in Java, even if different types have the same structure, it will throw a compile error because we are using a different type to instantiate and define a new instance.</p>
<pre><code class="lang-typescript"><span class="hljs-keyword">class</span> Person {
  <span class="hljs-built_in">String</span> name;
}

<span class="hljs-keyword">class</span> Client {
  <span class="hljs-built_in">String</span> name;
}

Client c = <span class="hljs-keyword">new</span> Person();  <span class="hljs-comment">// compiler throws an error</span>
Client c = <span class="hljs-keyword">new</span> Client();  <span class="hljs-comment">// OK!</span>
</code></pre>
<p>In nominal type systems, the relevant part of a type is the name, not the structure.</p>
<p>TypeScript, on another hand, verifies the structural compatibility to allow or not specific data. Its type system is based on structural typing.</p>
<p>The same code implementation that crashes in Java, would work in TypeScript.</p>
<pre><code class="lang-typescript"><span class="hljs-keyword">class</span> Person {
  name: <span class="hljs-built_in">string</span>;
}

<span class="hljs-keyword">class</span> Client {
  name: <span class="hljs-built_in">string</span>;
}

<span class="hljs-keyword">const</span> c1: Client = <span class="hljs-keyword">new</span> Person(); <span class="hljs-comment">// OK!</span>
<span class="hljs-keyword">const</span> c2: Client = <span class="hljs-keyword">new</span> Client(); <span class="hljs-comment">// OK!</span>
</code></pre>
<p>We want to use the <code>Client</code> type, and it has the property <code>name</code>, to point to the <code>Person</code> type. It also has the property type. So TypeScript will understand that both types have the same shape.</p>
<p>But it is not only about classes, but it works for any other "object".</p>
<pre><code class="lang-typescript"><span class="hljs-keyword">const</span> c3: Client = {
  name: <span class="hljs-string">'TK'</span>
};
</code></pre>
<p>This code compiles too because we have the same structure here. The TypeScript type system doesn't care about if it is a class, or an object literal if it has the same members, it will be flexible and compile.</p>
<p>But now we will add a third type: the <code>Customer</code>.</p>
<pre><code class="lang-typescript"><span class="hljs-keyword">class</span> Customer {
  name: <span class="hljs-built_in">string</span>;
  age: <span class="hljs-built_in">number</span>;
};
</code></pre>
<p>It not only has the <code>name</code> property, but also the <code>age</code>. What would happen if we instantiate a <code>Client</code> instance in a constant of type <code>Customer</code>?</p>
<pre><code class="lang-typescript"><span class="hljs-keyword">const</span> c4: Customer = <span class="hljs-keyword">new</span> Client();
</code></pre>
<p>The compiler will not accept that. We want to use the <code>Customer</code>, that has <code>name</code> and <code>age</code>. But we are instantiating the <code>Client</code> that has only the <code>name</code> property. So it doesn't have the same shape. It will cause an error:</p>
<pre><code class="lang-bash">Property <span class="hljs-string">'age'</span> is missing <span class="hljs-keyword">in</span> <span class="hljs-built_in">type</span> <span class="hljs-string">'Client'</span> but required <span class="hljs-keyword">in</span> <span class="hljs-built_in">type</span> <span class="hljs-string">'Customer'</span>.
</code></pre>
<p>The other way around would work because we want <code>Client</code>, and <code>Customer</code> has all the properties (<code>name</code>) from <code>Client</code>.</p>
<pre><code class="lang-typescript"><span class="hljs-keyword">const</span> c5: Client = <span class="hljs-keyword">new</span> Customer();
</code></pre>
<p>It works fine!</p>
<p>We can go on for enums, object literals, and any other type, but the idea here is to understand that the structure of the type is the relevant part.</p>
<h2 id="heading-runtime-and-compile-time">Runtime and Compile time</h2>
<p>This is a much more complex topic in programming language theory, but I wanted to give some examples to distinguish runtime from compile time.</p>
<p>Basically, the runtime is the execution time of a program. Imagine your backend receiving data from a frontend form page, handling this data, and saving it. Or when your frontend is requesting data from a server to render a list of Pokemons products.</p>
<p>Compile time is basically when the compiler is executing operations in the source code to satisfy the programming language's requirements. It can include type checking as an operation, for example. </p>
<p>Compile time errors in TypeScript, for example, are very related to the code that we wrote before:</p>
<ul>
<li>When the type is missing property: <code>Property 'age' is missing in type 'Client' but required in type 'Customer'.</code></li>
<li>When the type doesn't match: <code>Type '{ title: string; willFail: true; }' is not assignable to type 'Product'.</code></li>
</ul>
<p>Let's see some examples to have a better understanding.</p>
<p>I want to write a function to get the index of a part of the passed programming language.</p>
<pre><code class="lang-typescript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">getIndexOf</span>(<span class="hljs-params">language, part</span>) </span>{
  <span class="hljs-keyword">return</span> language.indexOf(part);
}
</code></pre>
<p>It receives the <code>language</code> and the <code>part</code> that we will look for to get the index.</p>
<pre><code class="lang-typescript">getIndexOf(<span class="hljs-string">'Typescript'</span>, <span class="hljs-string">'script'</span>); <span class="hljs-comment">// 4</span>
getIndexOf(<span class="hljs-number">42</span>, <span class="hljs-string">'script'</span>); <span class="hljs-comment">// Uncaught TypeError: language.indexOf is not a function at getIndexOf</span>
</code></pre>
<p>When passing a string, it works fine. But passing a number, we got a runtime error <code>Uncaught TypeError</code>. Because a number doesn't have an <code>indexOf</code> function, so we can't really use it.</p>
<p>But if we give type information to the compiler, in compile time, it will throw an error before running the code.</p>
<pre><code class="lang-typescript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">getIndexOf</span>(<span class="hljs-params">language: <span class="hljs-built_in">string</span>, part: <span class="hljs-built_in">string</span></span>): <span class="hljs-title">number</span> </span>{
  <span class="hljs-keyword">return</span> language.indexOf(part);
}
</code></pre>
<p>Now our program knows that it will need to receive two strings and return a number. The compiler can use this information to throw errors when we get a type error... before runtime.</p>
<pre><code class="lang-typescript">getIndexOf(<span class="hljs-string">'Typescript'</span>, <span class="hljs-string">'script'</span>); <span class="hljs-comment">// 4</span>
getIndexOf(<span class="hljs-number">42</span>, <span class="hljs-string">'script'</span>); <span class="hljs-comment">// Argument of type '42' is not assignable to parameter of type 'string'.</span>
</code></pre>
<p>Maybe, for small projects (or small functions like ours) we don't really see too much benefit. </p>
<p>In this case, we know that we need to pass a string, so we won't pass a number to the function. But when the codebase grows or you have many people adding code and more complexity, it's clear to me that a type system can help us a lot to get errors in compile time before shipping code to production.</p>
<p>At first, we need all the learning curve to understand types and all the mental models, but after a while, you'll be more used to type annotations and eventually become friends with the compiler. It would be a <em>helper</em>, not a <em>yeller</em>.</p>
<p>As we are learning about the basic difference between compile time and runtime, I think it's great to differentiate types from values.</p>
<p>All the examples I'll show here can be copied and run in the <a target="_blank" href="https://www.typescriptlang.org/play">TypeScript Playground</a> to understand the compiler and the result of the compilation process (aka the <em>"JavaScript"</em>).</p>
<p>In TypeScript, we have two different universes: the value and the type spaces. The type space is where types are defined and used to enable the compiler to do all the great magic. And the value space is the values in our programs like variables, constants, functions, value literals, and things that we have in runtime.</p>
<p>It's good to have an understanding of this concept because in TypeScript we can't use type checking in runtime. It has a very clear separation between type checking and the compilation process.</p>
<p>TypeScript has the process of type checking the source code types and sees if everything is correct and consistent. And then it can compile to JavaScript. </p>
<p>As these two parts are separate, we can't use type checking in runtime. Only in "compile time". If you try to use a type as a value, it will throw an error: <code>only refers to a type, but is being used as a value here</code>.</p>
<p>Let's see examples of this idea.</p>
<p>Imagine we want to write a function called <code>purchase</code> where we receive a payment method and based on this method, we want to do some action. We have a credit card and a debit card. Let's define them here:</p>
<pre><code class="lang-typescript"><span class="hljs-keyword">type</span> CreditCard = {
  <span class="hljs-built_in">number</span>: <span class="hljs-built_in">number</span>;
  cardholder: <span class="hljs-built_in">string</span>;
  expirationDate: <span class="hljs-built_in">Date</span>;
  secutiryCode: <span class="hljs-built_in">number</span>;
};

<span class="hljs-keyword">type</span> DebitCard = {
  <span class="hljs-built_in">number</span>: <span class="hljs-built_in">number</span>;
  cardholder: <span class="hljs-built_in">string</span>;
  expirationDate: <span class="hljs-built_in">Date</span>;
  secutiryCode: <span class="hljs-built_in">number</span>;
};

<span class="hljs-keyword">type</span> PaymentMethod = CreditCard | DebitCard;
</code></pre>
<p>These types are in the <em>Type space</em>, so it only works in compile time. After type checking this function, the compiler removes all the types.</p>
<p>If you add these types in the TypeScript Playground, the output will be only a strict definition <code>"use strict";</code>.</p>
<p>The idea here is to really understand that the types live in the <em>Type space</em> and will not be available in the runtime. So in our function, it won't be possible to do this:</p>
<pre><code class="lang-typescript"><span class="hljs-keyword">const</span> purchase = <span class="hljs-function">(<span class="hljs-params">paymentMethod: PaymentMethod</span>) =&gt;</span> {
  <span class="hljs-keyword">if</span> (paymentMethod <span class="hljs-keyword">instanceof</span> CreditCard) {
    <span class="hljs-comment">// purchase with credit card</span>
  } <span class="hljs-keyword">else</span> {
    <span class="hljs-comment">// purchase with debit card</span>
  }
}
</code></pre>
<p>In the compiler it throws an error: <code>'CreditCard' only refers to a type, but is being used as a value here.</code>.</p>
<p>The compiler knows the difference between the two spaces and that the type <code>CreditCard</code> lives in the <em>Type space</em>.</p>
<p>The playground is a very cool tool to see the output of your TypeScript code. If you create a new credit card object like this:</p>
<pre><code class="lang-typescript"><span class="hljs-keyword">const</span> creditCard: CreditCard = {
  <span class="hljs-built_in">number</span>: <span class="hljs-number">2093</span>,
  cardholder: <span class="hljs-string">'TK'</span>,
  expirationDate: <span class="hljs-keyword">new</span> <span class="hljs-built_in">Date</span>(),
  secutiryCode: <span class="hljs-number">101</span>
};
</code></pre>
<p>The compiler will type check it and do all the magic and then it transpiles the TypeScript code to JavaScript. And we have this:</p>
<pre><code class="lang-typescript"><span class="hljs-keyword">const</span> creditCard = {
    <span class="hljs-built_in">number</span>: <span class="hljs-number">2093</span>,
    cardholder: <span class="hljs-string">'TK'</span>,
    expirationDate: <span class="hljs-keyword">new</span> <span class="hljs-built_in">Date</span>(,
    secutiryCode: <span class="hljs-number">101</span>
};
</code></pre>
<p>The same object, but now only with the value and without the type.</p>
<h2 id="heading-constraints-amp-type-narrowing">Constraints &amp; Type Narrowing</h2>
<p>When we restrict what we can do, it’s easier to understand what we can do.</p>
<p>We use types as constraints to limit the bugs in your program. To understand this concept, I'm stealing an example from Lauren Tan's talk about Type Systems.</p>
<pre><code class="lang-typescript"><span class="hljs-keyword">const</span> half = <span class="hljs-function"><span class="hljs-params">x</span> =&gt;</span> x / <span class="hljs-number">2</span>;
</code></pre>
<p>How many ways does this function can fail? Imagine a number of possible inputs:</p>
<pre><code class="lang-typescript">[
  <span class="hljs-literal">null</span>,
  <span class="hljs-literal">undefined</span>,
  <span class="hljs-number">0</span>,
  <span class="hljs-string">'0'</span>,
  <span class="hljs-string">'TK'</span>,
  { username: <span class="hljs-string">'tk'</span> },
  [<span class="hljs-number">42</span>, <span class="hljs-number">3.14</span>],
  <span class="hljs-function">(<span class="hljs-params">a, b</span>) =&gt;</span> a + b,
]
</code></pre>
<p>And what are the results for input:</p>
<pre><code class="lang-typescript">half(<span class="hljs-literal">null</span>); <span class="hljs-comment">// 0</span>
half(<span class="hljs-literal">undefined</span>); <span class="hljs-comment">// NaN</span>
half(<span class="hljs-number">0</span>); <span class="hljs-comment">// 0</span>
half(<span class="hljs-string">'0'</span>); <span class="hljs-comment">// 0</span>
half(<span class="hljs-string">'TK'</span>); <span class="hljs-comment">// NaN</span>
half({ username: <span class="hljs-string">'tk'</span> }); <span class="hljs-comment">// NaN</span>
half([<span class="hljs-number">42</span>, <span class="hljs-number">3.14</span>]); <span class="hljs-comment">// NaN</span>
half(<span class="hljs-function">(<span class="hljs-params">a, b</span>) =&gt;</span> a + b); <span class="hljs-comment">// NaN</span>
</code></pre>
<p>We have different and unexpected results here. Here it's clear that we want a number as the <code>half</code> function, do the calculation, and great, it's done! But sometimes we don't control the input or the codebase is big, or new/unfamiliar, and we're able to make these little mistakes.</p>
<p>The idea of adding constraints to our code is to narrow the possibilities of a range of types. In this case, we want to limit the input type to a <code>number</code> type. It's the only type that we care about to do the half calculation. With type narrowing, we again give type information to the compiler.</p>
<pre><code class="lang-typescript"><span class="hljs-keyword">const</span> half = <span class="hljs-function">(<span class="hljs-params">x: <span class="hljs-built_in">number</span></span>) =&gt;</span> x / <span class="hljs-number">2</span>;
</code></pre>
<p>And with this new information, if we call the function with the test cases again, we have different results:</p>
<pre><code class="lang-typescript">half(<span class="hljs-literal">null</span>); <span class="hljs-comment">// Argument of type 'null' is not assignable to parameter of type 'number'.</span>
half(<span class="hljs-literal">undefined</span>); <span class="hljs-comment">// Argument of type 'undefined' is not assignable to parameter of type 'number'.(</span>
half(<span class="hljs-number">0</span>); <span class="hljs-comment">// 0</span>
half(<span class="hljs-string">'0'</span>); <span class="hljs-comment">// Argument of type '"0"' is not assignable to parameter of type 'number'.</span>
half(<span class="hljs-string">'TK'</span>); <span class="hljs-comment">// Argument of type '"TK"' is not assignable to parameter of type 'number'.</span>
half({ username: <span class="hljs-string">'tk'</span> }); <span class="hljs-comment">// Argument of type '{ username: string; }' is not assignable to parameter of type 'number'.</span>
half([<span class="hljs-number">42</span>, <span class="hljs-number">3.14</span>]); <span class="hljs-comment">// Argument of type 'number[]' is not assignable to parameter of type 'number'.</span>
half(<span class="hljs-function">(<span class="hljs-params">a, b</span>) =&gt;</span> a + b); <span class="hljs-comment">// Argument of type '(a: any, b: any) =&gt; any' is not assignable to parameter of type 'number'.</span>
</code></pre>
<p>Basically the compiler will tell us that only the number type, in this case, the <code>0</code> value, is a valid input, it will compile, and allow to run the code. We narrow the input type and allow only the value we really want for this function.</p>
<p>But are other ways to narrow the types in TypeScript. Imagine we have a function that receives a parameter that can be either a string or a number.</p>
<pre><code class="lang-typescript"><span class="hljs-keyword">type</span> StringOrNumber = <span class="hljs-built_in">string</span> | <span class="hljs-built_in">number</span>;

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">stringOrNumber</span>(<span class="hljs-params">value: StringOrNumber</span>) </span>{}
</code></pre>
<p>In the function body, the compiler won't know which methods or properties we can use for this type. Is it a string or number? We only know about the value in runtime. But we can narrow the type using the <code>typeof</code>:</p>
<pre><code class="lang-typescript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">stringOrNumber</span>(<span class="hljs-params">value: StringOrNumber</span>) </span>{
  <span class="hljs-keyword">if</span> (<span class="hljs-keyword">typeof</span> value === <span class="hljs-string">'string'</span>) {
    <span class="hljs-comment">// value.</span>
        <span class="hljs-comment">// your ide will show you the possible methods from the string type</span>
        <span class="hljs-comment">// (parameter) value: string</span>
    value
  }

  <span class="hljs-keyword">if</span> (<span class="hljs-keyword">typeof</span> value === <span class="hljs-string">'number'</span>) {
    <span class="hljs-comment">// value.</span>
        <span class="hljs-comment">// your ide will show you the possible methods from the number type</span>
        <span class="hljs-comment">// (parameter) value: number</span>
    value
  }
}
</code></pre>
<p>With an <code>if</code> statement and the <code>typeof</code>, we can give more information to the compiler. Now it will know the specific type for each <code>if</code> body.</p>
<p>The IDE knows what to show for the specific type. In runtime, when the value is a string, it will go to the first <code>if</code> statement, and the compiler will infer that the type is a string: <code>(parameter) value: string</code>.</p>
<p>When the value is a number, it will go to the second <code>if</code> statement and the compiler will infer that a type is a number: <code>(parameter) value: number</code>.</p>
<p>The <code>if</code> statement can be a helper to the compiler.</p>
<p>Another example is when we have an optional property in an object, but in a function, we need to return a value based on this optional value.</p>
<p>Imagine we have this type:</p>
<pre><code class="lang-typescript"><span class="hljs-keyword">type</span> User = {
  name: <span class="hljs-built_in">string</span>;
  address: {
    street: <span class="hljs-built_in">string</span>;
    complement?: <span class="hljs-built_in">string</span>;
  }
};
</code></pre>
<p>It's a simple <code>User</code> type. Let's focus on the <code>complement</code> property. It's optional (take a closer look at the <code>?</code> symbol), which means that it can be a <code>string</code> or <code>undefined</code>.</p>
<p>Now we want to build a function to receive the user and get the length of the address complement. What about this?</p>
<pre><code class="lang-typescript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">getComplementLength</span>(<span class="hljs-params">user: User</span>): <span class="hljs-title">number</span> </span>{
  <span class="hljs-keyword">return</span> user.address.complement.length;
    <span class="hljs-comment">// (property) complement?: string | undefined</span>
  <span class="hljs-comment">// Object is possibly 'undefined'.</span>
}
</code></pre>
<p>As we see earlier, the <code>complement</code> can be a <code>string</code> or <code>undefined</code>. <code>undefined</code> doesn't really have a property called <code>length</code>:</p>
<pre><code class="lang-typescript">Uncaught <span class="hljs-built_in">TypeError</span>: Cannot read property <span class="hljs-string">'length'</span> <span class="hljs-keyword">of</span> <span class="hljs-literal">undefined</span>
</code></pre>
<p>We could make something like:</p>
<pre><code class="lang-typescript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">getComplementLength</span>(<span class="hljs-params">user: User</span>) </span>{
  <span class="hljs-keyword">return</span> user.address.complement?.length;
}
</code></pre>
<p>If the <code>complement</code> has a string value, we can call <code>length</code>, otherwise, it will return <code>undefined</code>. </p>
<p>So this function has two possible return types: <code>number | undefined</code>. But we want to ensure that we only return <code>number</code>. So we use a <code>if</code> or a ternary condition to narrow the type. It will only call <code>.length</code> when it has real value (or when it is not <code>undefined</code>).</p>
<pre><code class="lang-typescript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">getComplementLength</span>(<span class="hljs-params">user: User</span>): <span class="hljs-title">number</span> </span>{
  <span class="hljs-keyword">return</span> user.address.complement
    ? user.address.complement.length
    : <span class="hljs-number">0</span>;
}
</code></pre>
<p>If it is <code>undefined</code>, we return the minimum length: <code>0</code>. Now we can use the function with the right type design with and without the complement. Without compile and runtime errors.</p>
<pre><code class="lang-typescript">getComplementLength({
  name: <span class="hljs-string">'TK'</span>,
  address: {
    street: <span class="hljs-string">'Shinjuku Avenue'</span>
  }
}); <span class="hljs-comment">// 0</span>

getComplementLength({
  name: <span class="hljs-string">'TK'</span>,
  address: {
    street: <span class="hljs-string">'Shinjuku Avenue'</span>,
    complement: <span class="hljs-string">'A complement'</span>
  }
}); <span class="hljs-comment">// 12</span>
</code></pre>
<p>We'll get <code>0</code> from the first function call and <code>12</code> from the second call.</p>
<p>With this <code>if</code> concept, we can also use other helpers to do the same thing. We could use the <code>in</code> operator to verify a property from an object, a <code>Array.isArray</code> to verify an array, or the <code>instanceof</code> for any other class type.</p>
<p>We could also use more advanced concepts like assertion function or type guards, but I'll leave these concepts to future posts.</p>
<p>One thing that I want to dig deep in this <em>Constraints</em> topic is immutability.</p>
<p>In JavaScript and TypeScript, we have the idea of mutable objects. If you define value in a variable, we can reassign it with another value later.</p>
<pre><code class="lang-typescript"><span class="hljs-keyword">let</span> email = <span class="hljs-string">'harry.potter@mail.com'</span>;
email <span class="hljs-comment">// 'harry.potter@mail.com'</span>
email = <span class="hljs-string">'hermione.granger@mail.com'</span>;
email <span class="hljs-comment">// 'hermione.granger@mail.com'</span>
</code></pre>
<p>Now imagine you have a list of numbers. And you want to use a function to sum all of its numbers. The function looks like this:</p>
<pre><code class="lang-typescript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">sumNumbers</span>(<span class="hljs-params">numbers: <span class="hljs-built_in">number</span>[]</span>) </span>{
  <span class="hljs-keyword">let</span> sum = <span class="hljs-number">0</span>;
  <span class="hljs-keyword">let</span> num = numbers.pop();

  <span class="hljs-keyword">while</span> (num !== <span class="hljs-literal">undefined</span>) {
    sum += num;
    num = numbers.pop();
  }

  <span class="hljs-keyword">return</span> sum;
}
</code></pre>
<p>You call the function passing your list and get the result. It works just fine.</p>
<pre><code class="lang-typescript"><span class="hljs-keyword">const</span> list = [<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>, <span class="hljs-number">4</span>];
sumNumbers(list); <span class="hljs-comment">// 10</span>
</code></pre>
<p>But what happened to your list? Did the function mutate it entirely?</p>
<pre><code class="lang-typescript">list; <span class="hljs-comment">// []</span>
</code></pre>
<p>If we use the list, it's empty now. The <code>pop</code> in the <code>sumNumbers</code> function is a "mutate" function. It gets the references and removes the item from them. It's not a copy, it's the real reference.</p>
<p>In runtime, we can use other functions or ways to do the same thing: using reduce, do a for loop without the need to <code>pop</code> items from the array.</p>
<p>But using TypeScript, we can provide immutability in compile time. If you are not using types, it's possible to use a type assertion <code>as const</code>. Imagine this:</p>
<pre><code class="lang-typescript"><span class="hljs-keyword">const</span> author = {
  name: <span class="hljs-string">'Walter Isaacson'</span>,
  email: <span class="hljs-string">'walter.isaacson@mail.com'</span>,
  books: [
    {
      title: <span class="hljs-string">'Leonardo Da Vinci'</span>,
      price: <span class="hljs-number">50.00</span>,
    }
  ]
};

author.books.push({
  title: <span class="hljs-string">'Steve Jobs'</span>,
  price: <span class="hljs-number">10.00</span>
});
</code></pre>
<p>Just an author object and then we add a new book to this author. The <code>push</code> method updates the book's array reference. It's a "mutate" method. Let's see if you use the const assertion <code>as const</code>:</p>
<pre><code class="lang-typescript"><span class="hljs-keyword">const</span> author = {
  name: <span class="hljs-string">'Walter Isaacson'</span>,
  email: <span class="hljs-string">'walter.isaacson@mail.com'</span>,
  books: [
    {
      title: <span class="hljs-string">'Leonardo Da Vinci'</span>,
      price: <span class="hljs-number">50.00</span>,
    }
  ]
} <span class="hljs-keyword">as</span> <span class="hljs-keyword">const</span>;

author.books.push({
  title: <span class="hljs-string">'Steve Jobs'</span>,
  price: <span class="hljs-number">10.00</span>
});
<span class="hljs-comment">// Property 'push' does not exist on type</span>
<span class="hljs-comment">// 'readonly [{ readonly title: "Leonardo Da Vinci"; readonly price: 50; }]'</span>
</code></pre>
<p>The compiler won't compile. It gets an error on the author's object. It's is now readonly, and as a readonly object, it has no method called <code>push</code> (or any "mutate" method). </p>
<p>We added a constraint to the author's object. Before it was a specific type (with all the "mutate" methods), and now we narrowed the type to be almost the same, but without the "mutate" methods. Type narrowing.</p>
<p>To continue, let's add types to this object. The <code>book</code> and the <code>author</code>:</p>
<pre><code class="lang-typescript"><span class="hljs-keyword">type</span> Book = {
  title: <span class="hljs-built_in">string</span>;
  price: <span class="hljs-built_in">number</span>;
};

<span class="hljs-keyword">type</span> Author = {
  name: <span class="hljs-built_in">string</span>;
  email: <span class="hljs-built_in">string</span>;
  books: Book[];
};
</code></pre>
<p>Add the type to the author object:</p>
<pre><code class="lang-typescript"><span class="hljs-keyword">const</span> author: Author = {
  name: <span class="hljs-string">'Walter Isaacson'</span>,
  email: <span class="hljs-string">'walter.isaacson@mail.com'</span>,
  books: [
    {
      title: <span class="hljs-string">'Leonardo Da Vinci'</span>,
      price: <span class="hljs-number">50.00</span>,
    }
  ]
};
</code></pre>
<p>Add the type to a new book object:</p>
<pre><code class="lang-typescript"><span class="hljs-keyword">const</span> book: Book = {
  title: <span class="hljs-string">'Steve Jobs'</span>,
  price: <span class="hljs-number">30</span>
};
</code></pre>
<p>And now we can add the new book to the author:</p>
<pre><code class="lang-typescript">author.name = <span class="hljs-string">'TK'</span>;
author.books.push(book);
</code></pre>
<p>It works just fine!</p>
<p>I want to show another way to add immutability in compile time. TypeScript has a utility type called <code>Readonly</code>.</p>
<p>You can add the <code>readonly</code> for each property in an object. Something like this:</p>
<pre><code class="lang-typescript"><span class="hljs-keyword">type</span> Book = {
  <span class="hljs-keyword">readonly</span> title: <span class="hljs-built_in">string</span>;
  <span class="hljs-keyword">readonly</span> price: <span class="hljs-built_in">number</span>;
};
</code></pre>
<p>But it can be very repetitive. So we can use the <code>Readonly</code> utility to add the <code>readonly</code> to all properties of an object:</p>
<pre><code class="lang-typescript"><span class="hljs-keyword">type</span> Book = Readonly&lt;{
  title: <span class="hljs-built_in">string</span>;
  price: <span class="hljs-built_in">number</span>;
}&gt;;
</code></pre>
<p>One thing to keep in mind is that it doesn't add the readonly for nested properties. For example, if we add the <code>Readonly</code> to the <code>Author</code> type, it won't add the <code>readonly</code> to the <code>Book</code> type too.</p>
<pre><code class="lang-typescript"><span class="hljs-keyword">type</span> Author = Readonly&lt;{
  name: <span class="hljs-built_in">string</span>;
  email: <span class="hljs-built_in">string</span>;
  books: Book[];
}&gt;;
</code></pre>
<p>All the properties from the author can't be reassigned, but you can mutate the <code>books</code> list here (<code>push</code>, <code>pop</code>, ...) because the <code>Book[]</code> is not readonly. Let's see it.</p>
<pre><code class="lang-typescript"><span class="hljs-keyword">const</span> author: Author = {
  name: <span class="hljs-string">'Walter Isaacson'</span>,
  email: <span class="hljs-string">'walter.isaacson@mail.com'</span>,
  books: [
    {
      title: <span class="hljs-string">'Leonardo Da Vinci'</span>,
      price: <span class="hljs-number">50.00</span>,
    }
  ]
};

<span class="hljs-keyword">const</span> book: Book = {
  title: <span class="hljs-string">'Steve Jobs'</span>,
  price: <span class="hljs-number">30</span>
};

author.books.push(book);
author.books;
<span class="hljs-comment">/* =&gt;
 *
 * [
 *   {
 *     title: 'Leonardo Da Vinci',
 *     price: 50.00,
 *   },
 *   {
 *    title: 'Steve Jobs',
 *    price: 30
 *   }
 * ]
 *
 */</span>
</code></pre>
<p>The <code>push</code> will work just fine.</p>
<p>So, how do we enforce a readonly to the <code>books</code>? We need to make sure that the array is a readonly type. We can use the <code>Readonly</code>, or use another utility from TypeScript called <code>ReadonlyArray</code>. Let's see the two ways to do it.</p>
<p>With <code>Readonly</code>:</p>
<pre><code class="lang-typescript"><span class="hljs-keyword">type</span> Author = Readonly&lt;{
  name: <span class="hljs-built_in">string</span>;
  email: <span class="hljs-built_in">string</span>;
  books: Readonly&lt;Book[]&gt;;
}&gt;;
</code></pre>
<p>With <code>ReadonlyArray</code>:</p>
<pre><code class="lang-typescript"><span class="hljs-keyword">type</span> Author = Readonly&lt;{
  name: <span class="hljs-built_in">string</span>;
  email: <span class="hljs-built_in">string</span>;
  books: ReadonlyArray&lt;Book&gt;;
}&gt;;
</code></pre>
<p>For me, both work great! But in my opinion, <code>ReadonlyArray</code> is more semantic and I also feel it is less verbose (not that the <code>Readonly</code> with an array is).</p>
<p>What happened if we try to mutate the author object now?</p>
<pre><code class="lang-typescript">author.name = <span class="hljs-string">'TK'</span>; <span class="hljs-comment">// Cannot assign to 'name' because it is a read-only property.</span>
author.books.push(book); <span class="hljs-comment">// Property 'push' does not exist on type 'readonly [{ readonly title: "Leonardo Da Vinci"; readonly price: 50; }]'.</span>
</code></pre>
<p>Great! Now we can catch mutable operations in compile time. This is a way to use the concept of adding constraints to our types to make sure they only do what is really needed.</p>
<h2 id="heading-semantics-amp-readability">Semantics &amp; Readability</h2>
<p>At first, I felt that TypeScript could be very verbose because of the types and make the code much more complex than it should be. And it actually can. Strive for simplicity is the goal and it is difficult at the same time.</p>
<p>This idea is very related to clean code and how we can write code to be human-readable and maintainable. TypeScript is no different. Most of the cases, we don't need super complex types. Let the simple types do the work.</p>
<p>Another thing that I find very useful is semantic of types.</p>
<p>Imagine you need to add a string to the <code>sessionStorage</code> to save it in the browser. Your function looks like this:</p>
<pre><code class="lang-typescript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">saveMyString</span>(<span class="hljs-params">value: <span class="hljs-built_in">string</span></span>): <span class="hljs-title">any</span> </span>{
  sessionStorage.myString = value;
}
</code></pre>
<p>You add a type annotation to the string input and as you don't know about the returning type, you probably add a <code>any</code> type.</p>
<p>But what's the real meaning behind this returning type? Is it returning anything?</p>
<p>It just saves the string to the <code>sessionStorage</code>. It doesn't return anything. The <code>void</code> type was what you're looking for. As TypeScript docs says: <code>the absence of having any type at all</code>.</p>
<pre><code class="lang-typescript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">saveMyString</span>(<span class="hljs-params">value: <span class="hljs-built_in">string</span></span>): <span class="hljs-title">void</span> </span>{
  sessionStorage.myString = value;
}
</code></pre>
<p>Great, the meaning of the type is correct now. The correctness is very important in a type system. It's a way to model our data, but also help maintain systems for future developers. Even if the developer is ... you!</p>
<p>Before we were talking about verbose code. And we can improve a lot of our code by using TypeScript type inference.</p>
<p>For some code, we don't need to explicitly add type annotation. The TypeScript compiler will understand and infer it implicitly. For example:</p>
<pre><code class="lang-typescript"><span class="hljs-keyword">const</span> num: <span class="hljs-built_in">number</span> = <span class="hljs-number">1</span>;
</code></pre>
<p>This code is redundant. We can just let the compiler infers it like this:</p>
<pre><code class="lang-typescript"><span class="hljs-keyword">const</span> num = <span class="hljs-number">1</span>;
</code></pre>
<p>In our example earlier, we add the annotation <code>void</code> to the <code>saveMyString</code> function. But as the function doesn't return any value, the compiler will infer that the returning type is <code>void</code> implicitly.</p>
<p>When I learned this, I thought with myself. But one of the biggest advantages of using TypeScript (or any other type system / static type language) is types as documentation. If we let the compiler infer most of the types, we won't have the documentation we want.</p>
<p>But if you hover over the TypeScript code in your editor (at least VS Code works like that), you can see the type information and relevant documentation.</p>
<p>Let's see other examples of redundant code and make the code less verbose and let the compiler works for us.</p>
<pre><code class="lang-typescript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">sum</span>(<span class="hljs-params">a: <span class="hljs-built_in">number</span>, b: <span class="hljs-built_in">number</span></span>): <span class="hljs-title">number</span> </span>{
  <span class="hljs-keyword">return</span> a + b;
};
</code></pre>
<p>We don't need the returning type <code>number</code>, because the compiler knows that a <code>number</code> + another <code>number</code> is equal to a <code>number</code> type, and it is the returning type. It can be:</p>
<pre><code class="lang-typescript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">sum</span>(<span class="hljs-params">a: <span class="hljs-built_in">number</span>, b: <span class="hljs-built_in">number</span></span>) </span>{
  <span class="hljs-keyword">return</span> a + b;
};
</code></pre>
<p>Implicit code, but with documentation, and the compiler does the work.</p>
<p>Type inference works for methods too:</p>
<pre><code class="lang-typescript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">squareAll</span>(<span class="hljs-params">numbers: <span class="hljs-built_in">number</span>[]</span>): <span class="hljs-title">number</span>[] </span>{
  <span class="hljs-keyword">return</span> numbers.map(<span class="hljs-function"><span class="hljs-params">number</span> =&gt;</span> <span class="hljs-built_in">number</span> * <span class="hljs-built_in">number</span>);
};
</code></pre>
<p>This function gets a list of numbers and makes every number a squared value. The returning type is <code>number[]</code>, even though the result of a map is always a list, and as we have a list of numbers, it will always be a list of numbers. So we let the compiler infers this too:</p>
<pre><code class="lang-typescript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">squareAll</span>(<span class="hljs-params">numbers: <span class="hljs-built_in">number</span>[]</span>) </span>{
  <span class="hljs-keyword">return</span> numbers.map(<span class="hljs-function"><span class="hljs-params">number</span> =&gt;</span> <span class="hljs-built_in">number</span> * <span class="hljs-built_in">number</span>);
};
</code></pre>
<p>This works the same way for objects too.</p>
<pre><code class="lang-typescript"><span class="hljs-keyword">const</span> person: { name: <span class="hljs-built_in">string</span>, age: <span class="hljs-built_in">number</span> } = {
  name: <span class="hljs-string">'TK'</span>,
  age: <span class="hljs-number">24</span>
};
</code></pre>
<p>A person object with a string name and a number age. But as we are assigning these values, the compiler can infer these types.</p>
<pre><code class="lang-typescript"><span class="hljs-keyword">const</span> person = {
  name: <span class="hljs-string">'TK'</span>,
  age: <span class="hljs-number">24</span>
};
</code></pre>
<p>If you hover the <code>person</code>, you get this:</p>
<pre><code class="lang-typescript"><span class="hljs-keyword">const</span> person: {
  name: <span class="hljs-built_in">string</span>;
  age: <span class="hljs-built_in">number</span>;
}
</code></pre>
<p>The types are documented here.</p>
<p>Another benefit of type inference is that we can easily refactor our code. It's a simple example, but good to illustrate the refactoring process. Let's get the <code>sum</code> function again.</p>
<pre><code class="lang-typescript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">sum</span>(<span class="hljs-params">a: <span class="hljs-built_in">number</span>, b: <span class="hljs-built_in">number</span></span>): <span class="hljs-title">number</span> </span>{
  <span class="hljs-keyword">return</span> a + b;
};
</code></pre>
<p>Instead of returning the sum number, we want to return <code>"Sum: {a + b}"</code>. So for <code>a = 1</code> and <code>b = 2</code>, we have the resulting string as <code>"Sum: 3"</code>.</p>
<pre><code class="lang-typescript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">sum</span>(<span class="hljs-params">a: <span class="hljs-built_in">number</span>, b: <span class="hljs-built_in">number</span></span>): <span class="hljs-title">string</span> </span>{
  <span class="hljs-keyword">return</span> <span class="hljs-string">`Sum: <span class="hljs-subst">${a + b}</span>`</span>;
};

sum(<span class="hljs-number">1</span>, <span class="hljs-number">2</span>); <span class="hljs-comment">// Sum: 3</span>
</code></pre>
<p>Great! But now letting the compiler infers this.</p>
<pre><code class="lang-typescript"><span class="hljs-comment">// function sum(a: number, b: number): number</span>
<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">sum</span>(<span class="hljs-params">a: <span class="hljs-built_in">number</span>, b: <span class="hljs-built_in">number</span></span>) </span>{
  <span class="hljs-keyword">return</span> a + b;
};

<span class="hljs-comment">// function sum(a: number, b: number): string</span>
<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">sum</span>(<span class="hljs-params">a: <span class="hljs-built_in">number</span>, b: <span class="hljs-built_in">number</span></span>) </span>{
  <span class="hljs-keyword">return</span> <span class="hljs-string">`Sum: <span class="hljs-subst">${a + b}</span>`</span>;
};
</code></pre>
<p>We just need to modify the returning value and the type inference will work. No need to think about the returning type. This is a small example, but for more complex functions, it would work too.</p>
<p>Back to the readability part, we can use <code>Enum</code>. A utility that defines a set of named constants. It's a way to give more meaning to the data in your application.</p>
<p>In your node app or a frontend app, you possibly do some fetching to request data. You commonly use a fetch object to perform a request and sometimes you need to pass the accept headers.</p>
<pre><code class="lang-typescript">fetch(<span class="hljs-string">'/pokemons'</span>, {
  headers: {
    Accept: <span class="hljs-string">'application/json'</span>
  }
});

fetch(<span class="hljs-string">'/harry-potter/spells'</span>, {
  headers: {
    Accept: <span class="hljs-string">'application/json'</span>
  }
});
</code></pre>
<p>It's good, but we can also use an enum to separate this accept string in a constant and reuse.</p>
<pre><code class="lang-typescript"><span class="hljs-built_in">enum</span> MediaTypes {
  <span class="hljs-built_in">JSON</span> = <span class="hljs-string">'application/json'</span>
}

fetch(<span class="hljs-string">'/pokemons'</span>, {
  headers: {
    Accept: MediaTypes.JSON
  }
});

fetch(<span class="hljs-string">'/harry-potter/spells'</span>, {
  headers: {
    Accept: MediaTypes.JSON
  }
});
</code></pre>
<p>And we are able to add more data related to the <code>MediaTypes</code> like <code>PDF</code>:</p>
<pre><code class="lang-typescript"><span class="hljs-built_in">enum</span> MediaTypes {
  <span class="hljs-built_in">JSON</span> = <span class="hljs-string">'application/json'</span>,
  PDF = <span class="hljs-string">'application/pdf'</span>
}
</code></pre>
<p>With <code>Enum</code>, we can encapsulate data into a meaningful block of code.</p>
<p>Recently, I was implementing a "state" React component. It's basically a component that renders an empty state or an error state based on the request response.</p>
<p>The UI for the empty and the error states were very similar. Only the title and the description text and the image icon were different. So I thought: "I have two ways in my mind to implement this: do the logic outside the component and pass all the information needed or pass a 'state type' and let the component render the correct icon and messages."</p>
<p>So I built an enum:</p>
<pre><code class="lang-typescript"><span class="hljs-keyword">export</span> <span class="hljs-built_in">enum</span> StateTypes {
  Empty = <span class="hljs-string">'Empty'</span>,
  <span class="hljs-built_in">Error</span> = <span class="hljs-string">'Error'</span>
};
</code></pre>
<p>And I could just pass this data to the component as the <code>type</code>:</p>
<pre><code class="lang-typescript"><span class="hljs-keyword">import</span> ComponentState, { StateTypes } <span class="hljs-keyword">from</span> <span class="hljs-string">'./ComponentState'</span>;

&lt;ComponentState <span class="hljs-keyword">type</span>={StateTypes.Empty} /&gt;
&lt;ComponentState <span class="hljs-keyword">type</span>={StateTypes.Error} /&gt;
</code></pre>
<p>In the component, it had a state object with all the information related to the <code>title</code>, <code>description</code>, and <code>icon</code>.</p>
<pre><code class="lang-typescript"><span class="hljs-keyword">const</span> stateInfo = {
  Empty: {
    title: messages.emptyTitle,
    description: messages.emptyDescription,
    icon: EmptyIcon,
  },
  <span class="hljs-built_in">Error</span>: {
    title: messages.errorTitle,
    description: messages.errorDescription,
    icon: ErrorIcon,
  },
};
</code></pre>
<p>So I could just receive the type based on the enum and use this <code>stateInfo</code> object with the <code>State</code> component from our design system:</p>
<pre><code class="lang-typescript"><span class="hljs-keyword">export</span> <span class="hljs-keyword">const</span> ComponentState = <span class="hljs-function">(<span class="hljs-params">{ <span class="hljs-keyword">type</span> }</span>) =&gt;</span> (
  &lt;State
    title={stateInfo[<span class="hljs-keyword">type</span>].title}
    subtitle={stateInfo[<span class="hljs-keyword">type</span>].subtitle}
    icon={stateInfo[<span class="hljs-keyword">type</span>].icon}
  /&gt;
);
</code></pre>
<p>This is a way to use an enum to encapsulate important data into a meaningful block of code in your application.</p>
<p>Another cool feature from TypeScript is optional properties. When we have properties from an object that can be a real value or undefined, we use an optional property to be explicitly that the property can be or not be there. The syntax for this is a simple <code>?</code> operator in the object property. Imagine this function:</p>
<pre><code class="lang-typescript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">sumAll</span>(<span class="hljs-params">a: <span class="hljs-built_in">number</span>, b: <span class="hljs-built_in">number</span>, c: <span class="hljs-built_in">number</span></span>) </span>{
  <span class="hljs-keyword">return</span> a + b + c;
}
</code></pre>
<p>But now the <code>c</code> value is optional:</p>
<pre><code class="lang-typescript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">sumAll</span>(<span class="hljs-params">a: <span class="hljs-built_in">number</span>, b: <span class="hljs-built_in">number</span>, c?: <span class="hljs-built_in">number</span></span>) </span>{
  <span class="hljs-keyword">return</span> a + b + c;
}
</code></pre>
<p>We add the <code>?</code> after <code>c</code>. But now we have a compiler error saying:</p>
<pre><code class="lang-typescript">(parameter) c: <span class="hljs-built_in">number</span> | <span class="hljs-literal">undefined</span>
<span class="hljs-built_in">Object</span> is possibly <span class="hljs-string">'undefined'</span>.
</code></pre>
<p>We can't sum an <code>undefined</code> value (well, actually in JavaScript we can, but we receive a <code>NaN</code> value).</p>
<p>We need to ensure that the <code>c</code> exists. Type narrowing!</p>
<pre><code class="lang-typescript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">sumAll</span>(<span class="hljs-params">a: <span class="hljs-built_in">number</span>, b: <span class="hljs-built_in">number</span>, c?: <span class="hljs-built_in">number</span></span>) </span>{
  <span class="hljs-keyword">if</span> (c) {
    <span class="hljs-keyword">return</span> a + b + c;
  }

  <span class="hljs-keyword">return</span> a + b;
}
</code></pre>
<p>If the <code>c</code> exists, it will be a <code>number</code> and we can sum all. If not, sum only the <code>a</code> and <code>b</code> values.</p>
<p>An interesting part of this optional property is that it is a <code>undefined</code> not <code>null</code>. This is why we do this, we get a compile error:</p>
<pre><code class="lang-typescript"><span class="hljs-keyword">let</span> <span class="hljs-built_in">number</span> = <span class="hljs-literal">null</span>;
sumAll(<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-built_in">number</span>);
<span class="hljs-comment">// Argument of type 'null' is not assignable to parameter of type 'number | undefined'.</span>
</code></pre>
<p>As the <code>?</code> operator doesn't handle the <code>null</code> value, choose to use the <code>undefined</code> type in your application and so you can still use the optional property and make the types consistent. We can use it like this:</p>
<pre><code class="lang-typescript"><span class="hljs-keyword">let</span> value: <span class="hljs-built_in">number</span> | <span class="hljs-literal">undefined</span>;
sumAll(<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, value); <span class="hljs-comment">// 3</span>
</code></pre>
<p>If you add a default value to the parameter, you won't need the <code>?</code> operator. Actually, the compiler will say that the <code>Parameter cannot have question mark and initializer</code>.</p>
<pre><code class="lang-typescript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">sumAll</span>(<span class="hljs-params">a: <span class="hljs-built_in">number</span>, b: <span class="hljs-built_in">number</span>, c: <span class="hljs-built_in">number</span> = 3</span>) </span>{
  <span class="hljs-keyword">return</span> a + b + c;
}
</code></pre>
<p>Optional properties not only works on variables and parameters, but also in objects.</p>
<p>An API response is a good example of type definition and optional property together. In API responses, data can be optional. Sometimes the API sends, sometimes it has no value.</p>
<p>How we model our types is really important for an application. If an optional property is defined as a required type, we can make our application breaks in runtime. But if we design the types correctly, we have the possible errors in compile time.</p>
<p>Imagine we are fetching a user data and this is the way we modeled the response type:</p>
<pre><code class="lang-typescript"><span class="hljs-keyword">type</span> UserResponse = {
  name: <span class="hljs-built_in">string</span>;
  email: <span class="hljs-built_in">string</span>;
  username: <span class="hljs-built_in">string</span>;
  age: <span class="hljs-built_in">number</span>;
  isActive: <span class="hljs-built_in">boolean</span>;
};
</code></pre>
<p>But in reality, the email is optional for the user. The API endpoint could return or not. But the <code>UserResponse</code> type we built treat it as a required property.</p>
<p>After fetching the user data, we want to see if the user email matches with a specific domain.</p>
<pre><code class="lang-typescript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">matchDomain</span>(<span class="hljs-params">email: <span class="hljs-built_in">string</span></span>) </span>{
  <span class="hljs-keyword">return</span> email.endsWith(domain);
}
</code></pre>
<p>As the <code>email</code> property is required in the <code>UserResponse</code> type, the <code>email</code> parameter will also be required in the <code>matchDomain</code> function.</p>
<p>This is the runtime we can get if the <code>email</code> is <code>undefined</code>:</p>
<pre><code class="lang-typescript"><span class="hljs-comment">// Uncaught TypeError: Cannot read property 'endsWith' of undefined</span>
</code></pre>
<p>But what would happen if we modeled the <code>UserResponse</code> correctly?</p>
<pre><code class="lang-typescript"><span class="hljs-keyword">type</span> UserResponse = {
  name: <span class="hljs-built_in">string</span>;
  email?: <span class="hljs-built_in">string</span>;
  username: <span class="hljs-built_in">string</span>;
  age: <span class="hljs-built_in">number</span>;
  isActive: <span class="hljs-built_in">boolean</span>;
};
</code></pre>
<p>Now the <code>email</code> is possibly <code>undefined</code> and it is explicit.</p>
<p>But if we still keep the function <code>matchDomain</code> the same way, we get a compile error:</p>
<pre><code class="lang-typescript"><span class="hljs-comment">// Argument of type 'undefined' is not assignable to parameter of type 'string'.</span>
</code></pre>
<p>And this is great! Now we can fix the <code>email</code> parameter in this function using the <code>?</code> operator:</p>
<pre><code class="lang-typescript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">matchDomain</span>(<span class="hljs-params">email?: <span class="hljs-built_in">string</span></span>) </span>{
  <span class="hljs-keyword">return</span> email.endsWith(<span class="hljs-string">'email.com'</span>);
}
</code></pre>
<p>But now we get a compile error when running <code>email.endsWith</code>, because it could be <code>undefined</code> too:</p>
<pre><code class="lang-typescript"><span class="hljs-comment">// (parameter) email: string | undefined</span>
<span class="hljs-comment">// Object is possibly 'undefined'.</span>
</code></pre>
<p>Type narrowing! We use an if block to return a <code>false</code> when the <code>email</code> is <code>undefined</code>. And run <code>endsWith</code> method only if the <code>email</code> is really a string:</p>
<pre><code class="lang-typescript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">matchDomain</span>(<span class="hljs-params">email?: <span class="hljs-built_in">string</span></span>) </span>{
  <span class="hljs-keyword">if</span> (!email) <span class="hljs-keyword">return</span> <span class="hljs-literal">false</span>;
  <span class="hljs-keyword">return</span> email.endsWith(<span class="hljs-string">'email.com'</span>);
}
</code></pre>
<p>It's pretty nice when we can get runtime errors in compile time. Better to code than debugging after we ship in production, isn't it?</p>
<h2 id="heading-type-composition">Type composition</h2>
<p>Type composition is very useful when trying to reuse existing types for new places of the codebase. We don't need to rewrite new types, we can create a new type by composing existing ones.</p>
<p>One example of composition I always have to handle using Redux or the <code>useReducer</code> hook from React is the idea of "reducers". A reducer can always receive a number of different actions.</p>
<p>In this context, actions are objects with at least a <code>type</code> property. It looks like this:</p>
<pre><code class="lang-typescript"><span class="hljs-built_in">enum</span> ActionTypes {
  FETCH = <span class="hljs-string">'FETCH'</span>
}

<span class="hljs-keyword">type</span> FetchAction = {
  <span class="hljs-keyword">type</span>: <span class="hljs-keyword">typeof</span> ActionTypes.FETCH;
};

<span class="hljs-keyword">const</span> fetchAction: FetchAction = {
  <span class="hljs-keyword">type</span>: ActionTypes.FETCH
};
</code></pre>
<p>A <code>fetchAction</code> has a type <code>FetchAction</code> that has a property type that is a typeof <code>FETCH</code>.</p>
<p>But a reducer can receive other actions too. For example a submit action:</p>
<pre><code class="lang-typescript"><span class="hljs-built_in">enum</span> ActionTypes {
  FETCH = <span class="hljs-string">'FETCH'</span>,
  SUBMIT = <span class="hljs-string">'SUBMIT'</span>
}

<span class="hljs-keyword">type</span> SubmitAction = {
  <span class="hljs-keyword">type</span>: <span class="hljs-keyword">typeof</span> ActionTypes.SUBMIT;
};

<span class="hljs-keyword">const</span> submitAction: SubmitAction = {
  <span class="hljs-keyword">type</span>: ActionTypes.SUBMIT
};
</code></pre>
<p>For a specific container, we can compose all these actions into just one type and use it for the reducer parameter type.</p>
<p>It would look like this:</p>
<pre><code class="lang-typescript"><span class="hljs-keyword">type</span> Actions = FetchAction | SubmitAction;

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">reducer</span>(<span class="hljs-params">state, action: Actions</span>) </span>{
  <span class="hljs-keyword">switch</span> (action.type) {
    <span class="hljs-keyword">case</span> ActionTypes.FETCH:
    <span class="hljs-comment">// fetching action</span>
    <span class="hljs-keyword">case</span> ActionTypes.SUBMIT:
    <span class="hljs-comment">// submiting action</span>
  }
}
</code></pre>
<p>All the possible actions are the <code>Actions</code> type. And we use a union type to "join" all action types. The action in the reducer can have the <code>FetchAction</code> or the <code>SubmitAction</code>.</p>
<p>As a Potterhead, I couldn't miss a Harry Potter example. I want to build a simple function to choose a Hogwarts House based on the person trait. Let's start with the houses first.</p>
<pre><code class="lang-typescript"><span class="hljs-keyword">type</span> House = {
  name: <span class="hljs-built_in">string</span>;
  traits: <span class="hljs-built_in">string</span>[];
}

<span class="hljs-keyword">const</span> gryffindor: House = {
  name: <span class="hljs-string">'Gryffindor'</span>,
  traits: [<span class="hljs-string">'courage'</span>, <span class="hljs-string">'bravery'</span>]
};

<span class="hljs-keyword">const</span> slytherin: House = {
  name: <span class="hljs-string">'Slytherin'</span>,
  traits: [<span class="hljs-string">'ambition'</span>, <span class="hljs-string">'leadership'</span>]
};

<span class="hljs-keyword">const</span> ravenclaw: House = {
  name: <span class="hljs-string">'Ravenclaw'</span>,
  traits: [<span class="hljs-string">'intelligence'</span>, <span class="hljs-string">'learning'</span>]
};

<span class="hljs-keyword">const</span> hufflepuff: House = {
  name: <span class="hljs-string">'Hufflepuff'</span>,
  traits: [<span class="hljs-string">'hard work'</span>, <span class="hljs-string">'patience'</span>]
};

<span class="hljs-keyword">const</span> houses: House[] = [
  gryffindor,
  slytherin,
  ravenclaw,
  hufflepuff
];
</code></pre>
<p>I want to keep it simple, so the <code>House</code> type has only the <code>name</code> and the <code>traits</code>, a list of possible traits from people related to the house.</p>
<p>And then, I create each house and added all of them to the <code>houses</code> list.</p>
<p>Great! Now I'll build the <code>Person</code> type. A person can be a witch or a muggle.</p>
<pre><code class="lang-typescript"><span class="hljs-keyword">type</span> Witch = {
  name: <span class="hljs-built_in">string</span>;
  trait: <span class="hljs-built_in">string</span>;
    magicFamily: <span class="hljs-built_in">string</span>;
}

<span class="hljs-keyword">type</span> Muggle = {
  name: <span class="hljs-built_in">string</span>;
    trait: <span class="hljs-built_in">string</span>;
  email: <span class="hljs-built_in">string</span>;
}
</code></pre>
<p>And this is the part we combine these two different types using the union type:</p>
<pre><code class="lang-typescript"><span class="hljs-keyword">type</span> Person = Muggle | Witch;
</code></pre>
<p>Using the intersection type, the <code>Person</code> type has all properties from <code>Muggle</code> or all from  <code>Witch</code>.</p>
<p>So now, if I create a <code>Muggle</code>, I need just the name, the trait, and the email:</p>
<pre><code class="lang-typescript"><span class="hljs-keyword">const</span> hermione: Muggle = {
  name: <span class="hljs-string">'Hermione Granger'</span>,
    trait: <span class="hljs-string">'bravery'</span>,
  email: <span class="hljs-string">'hermione@mail.com'</span>
};
</code></pre>
<p>If I create a <code>Witch</code>, I need the name, the trait, and the magic family name:</p>
<pre><code class="lang-typescript"><span class="hljs-keyword">const</span> harry: Witch = {
  name: <span class="hljs-string">'Harry Potter'</span>,
  trait: <span class="hljs-string">'courage'</span>,
  magicFamily: <span class="hljs-string">'Potter'</span>
};
</code></pre>
<p>And if I create a <code>Person</code>, I need at least the <code>name</code> and the <code>trait</code> properties from <code>Muggle</code> and <code>Witch</code>:</p>
<pre><code class="lang-typescript"><span class="hljs-keyword">const</span> tk: Person = {
  name: <span class="hljs-string">'TK'</span>,
  email: <span class="hljs-string">'tk@mail.com'</span>,
  trait: <span class="hljs-string">'learning'</span>,
  magicFamily: <span class="hljs-string">'Kinoshita'</span>
};
</code></pre>
<p>The <code>chooseHouse</code> is very simple. We just pas the houses and the person. Based on the person trait, the function will return the chosen house:</p>
<pre><code class="lang-typescript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">chooseHouse</span>(<span class="hljs-params">houses: House[], person: Person</span>) </span>{
  <span class="hljs-keyword">return</span> houses.find(<span class="hljs-function">(<span class="hljs-params">house</span>) =&gt;</span> house.traits.includes(person.trait))
}
</code></pre>
<p>And applying all the people we created:</p>
<pre><code class="lang-typescript">chooseHouse(houses, harry); <span class="hljs-comment">// { name: 'Gryffindor', traits: ['courage', 'bravery'] }</span>
chooseHouse(houses, hermione); <span class="hljs-comment">// { name: 'Gryffindor', traits: ['courage', 'bravery'] }</span>
chooseHouse(houses, tk); <span class="hljs-comment">// { name: 'Ravenclaw', traits: ['intelligence', 'learning'] }</span>
</code></pre>
<p>Nice!</p>
<p>The intersection type is a bit different, but it can also be used to combine existing types.</p>
<p>When I was implementing a web app to <a target="_blank" href="https://github.com/leandrotk/ux-studies">apply my studies on UX</a>, I needed to create a prop type for the Image component.</p>
<p>I had the type <code>ImageUrl</code> from the product type:</p>
<pre><code class="lang-typescript"><span class="hljs-keyword">type</span> ImageUrl = {
  imageUrl: <span class="hljs-built_in">string</span>;
};
</code></pre>
<p>And the <code>ImageAttr</code> to represent all the attributes for the image:</p>
<pre><code class="lang-typescript"><span class="hljs-keyword">type</span> ImageAttr = {
  imageAlt: <span class="hljs-built_in">string</span>;
  width?: <span class="hljs-built_in">string</span>
};
</code></pre>
<p>But the props expected all this information in the component. Intersection type for the rescue!</p>
<pre><code class="lang-typescript"><span class="hljs-keyword">type</span> ImageProps = ImageUrl &amp; ImageAttr;
</code></pre>
<p>Simple as that. So now, the component needs all these properties. The type looks like this:</p>
<pre><code class="lang-typescript"><span class="hljs-keyword">type</span> ImageProps = {
  imageUrl: <span class="hljs-built_in">string</span>;
  imageAlt: <span class="hljs-built_in">string</span>;
  width?: <span class="hljs-built_in">string</span>
};
</code></pre>
<p>And we can use this type this way:</p>
<pre><code class="lang-typescript"><span class="hljs-keyword">const</span> imageProps: ImageProps = {
  imageUrl: <span class="hljs-string">'www.image.com'</span>,
  imageAlt: <span class="hljs-string">'an image'</span>,
};

<span class="hljs-keyword">const</span> imagePropsWithWidth: ImageProps = {
  imageUrl: <span class="hljs-string">'www.image.com'</span>,
  imageAlt: <span class="hljs-string">'an image'</span>,
  width: <span class="hljs-string">'100%'</span>
};
</code></pre>
<p>Nice! One more concept to reuse and compose types.</p>
<p>I also find the <code>Pick</code> type very interesting and useful. We have other <a target="_blank" href="https://leandrotk.github.io/tk/2020/05/typescript-learnings-interesting-types/index.html">interesting types</a> that we could write here, but the idea here is to understand that we can compose type and there is no limit to reuse types. If you're interested in study other types, take a look at this post I wrote: <a target="_blank" href="https://leandrotk.github.io/tk/2020/05/typescript-learnings-interesting-types/index.html">TypeScript Learnings: Interesting Types</a>.</p>
<h2 id="heading-tooling">Tooling</h2>
<p>When you <code>npm install typescript</code>, you don't just get the compiler, you get the language service API, a standalone server called tsserver that editors can run to provide autocompletion, go-to, and other cool features.</p>
<p>These features are what some people from the TypeScript team call developer productivity tools like smart errors when type checking and IntelliSense (code completion, hover info, signature information). We look at these features throughout the whole article, but I want to make a special topic to talk about it.</p>
<p>The TypeScript type checker is powerful in the sense that it can infer types and provide information to some possible issues. Example: It inferred that the city is a string. And the <code>uppercase</code> is used the wrong way. As it knows it is a string, it also tries to find a possible method that the engineer is looking for.</p>
<pre><code class="lang-typescript"><span class="hljs-keyword">const</span> city = <span class="hljs-string">'Tokyo'</span>;
city.toUppercase();
<span class="hljs-comment">// Property 'toUppercase' does not exist on type</span>
<span class="hljs-comment">// 'string'. Did you mean 'toUpperCase'?</span>
</code></pre>
<p>In this case, the compiler is really smart, because it finds exatcly what we wanted.</p>
<p>It also works for objects:</p>
<pre><code class="lang-typescript"><span class="hljs-keyword">const</span> people = [
  { name: <span class="hljs-string">'TK'</span>, age: <span class="hljs-number">24</span> },
  { name: <span class="hljs-string">'Kaio'</span>, age: <span class="hljs-number">12</span> },
  { name: <span class="hljs-string">'Kazumi'</span>, age: <span class="hljs-number">31</span> },
];

<span class="hljs-keyword">for</span> (<span class="hljs-keyword">const</span> person <span class="hljs-keyword">of</span> people) {
  <span class="hljs-built_in">console</span>.log(person.agi);
  <span class="hljs-comment">// Property 'agi' does not exist on type '{ name: string; age: number; }'</span>
}
</code></pre>
<p>With the static types, the tooling can provide a great developer experience with code completion, hover info to show defined types, and signature information for methods and other data.</p>
<p>If you type: <code>'TK'.</code>, the editor will show all the possible methods for the string object. The compiler knows it is a string. And it knows the methods from the <code>String</code> prototype. But it also provides the method signature. This is very interesting because we don't necessarily need to go to the docs. The "docs" is already in our code editor.</p>
<p>It's an awesome experience while coding.</p>
<p>The type definition "on hover" is another thing that we saw earlier in this article. Let the compiler infer the types implicitly and you won't lose the type documentation. Using the hover in the object, the IDE or editor will always be able to show the type definition.</p>
<p>Another interesting thing is that TypeScript will not only flag what could go wrong on runtime, but it also helps to find code that doesn't do what you intend.</p>
<p>Imagine we have a function to open a snackbar if it is still closed. It would verify the status of the snackbar. If it is closed, just call another function to open it.</p>
<pre><code class="lang-typescript"><span class="hljs-keyword">const</span> buildSnackbar = <span class="hljs-function">(<span class="hljs-params">status: SnackbarStatus</span>) =&gt;</span> {
  <span class="hljs-keyword">if</span> (status.isClosed) {
    openSnackbar();
  }
};
</code></pre>
<p>And the type information for this snackbar is:</p>
<pre><code class="lang-typescript"><span class="hljs-keyword">type</span> SnackbarStatus = {
  isClosed: <span class="hljs-built_in">boolean</span>;
};
</code></pre>
<p>What happens if I call this function like this:</p>
<pre><code class="lang-typescript">buildSnackbar({ isclosed: <span class="hljs-literal">true</span> });
</code></pre>
<p>It won't break in runtime, because the <code>status</code> object has no <code>isClosed</code> attribute and the <code>undefined</code> object is a <code>falsy</code> value, so it will skip the if condition and not call the <code>openSnackbar</code> function. No runtime error. But probably it will behavior different than the expected.</p>
<p>In TypeScript, the compiler will give some hints to make it works properly. First it will show this error:</p>
<pre><code class="lang-typescript"><span class="hljs-comment">// Argument of type '{ isclosed: boolean; }' is not assignable to</span>
<span class="hljs-comment">// parameter of type 'SnackbarStatus'.</span>
</code></pre>
<p><code>isclosed</code> with downcased <code>C</code> is not assignable to the type. It's not defined there. This is the first hint to make you correct your code.</p>
<p>The second is even better:</p>
<pre><code class="lang-typescript"><span class="hljs-comment">// Object literal may only specify known properties,</span>
<span class="hljs-comment">// but 'isclosed' does not exist in type 'SnackbarStatus'.</span>
<span class="hljs-comment">// Did you mean to write 'isClosed'?</span>
</code></pre>
<p>It tells exactly what you probably need to do: rename the <code>isclosed</code> to <code>isClosed</code>.</p>
<p>We can talk a lot of things about the tooling about I think this is the main part.</p>
<p>My suggestion to learn more about this is to just code in TypeScript and "have a conversation" with the compiler. Read the errors. Play with the hover. See the autocompletion. Understand the method signatures. It's really a productive way to code.</p>
<h2 id="heading-tips-amp-learnings">Tips &amp; Learnings</h2>
<p>As the article is coming to an end, I want to just add some final thoughts, learnings, and tips to help you in your journey learning TypeScript or just applying it in your projects.</p>
<ul>
<li>Really read the type error: this will help you better understand the issue and the types.</li>
<li><code>strictNullChecks</code> and <code>noImplicitAny</code> can be very helpful in finding bugs. Enable this as soon as possible in your project. Use <code>strictNullChecks</code> to prevent “undefined is not an object”-style runtime errors. Use <code>noImplicitAny</code> to type the source code to give more type information for the compiler.</li>
<li>Together with the compiler's configurations, I always recommend being very precise about your types. Mainly with the values that occur only in runtime like an API response. Correctness is important to catch as many bugs as possible in compile time.</li>
<li>Understand the difference between runtime and compile time: types only affect in compile type. It runs the type checker and then compiles to JavaScript. The JavaScript source code doesn't use any type of references or type operations.</li>
<li>Learn about utility types. We talked more specifically about the <code>Readonly</code> in the immutability in compile time, but TypeScript has a box of helpers like <code>Required</code>, <code>Pick</code>, and many more.</li>
<li>If possible, prefer letting the compiler infers the types for you. Most of the types and returning types are redundant. The TypeScript compiler is very smart in this area. If not possible, you can always add type annotations. And leave the type assertions as the last option.</li>
<li>As you're writing code, take a look at the tooling. The design of the tooling provided in an IDE is amazing. The IntelliSense and type checking provide a really good experience.</li>
</ul>
<p>This post was originally published at <a target="_blank" href="https://leandrotk.github.io/tk/2020/07/a-mental-model-to-think-in-typescript/index.html">TK's blog</a>. And you can find more content like this in my blog at <a target="_blank" href="https://leandrotk.github.io/tk/">https://leandrotk.github.io/tk</a>.</p>
<p>You can also follow me on <a target="_blank" href="https://twitter.com/leandrotk_">Twitter</a> and <a target="_blank" href="https://github.com/leandrotk">GitHub</a>.</p>
<h1 id="heading-resources">Resources</h1>
<p>I compiled (pun very much intended!) a bunch of resources to help you learn more about programming languages, type systems, and the type mental model.</p>
<p>Also, if you found the examples on this post useful, I added all of them this repository: <a target="_blank" href="https://github.com/leandrotk/thinking-in-types">Thinking in Types</a>. So you can fork and play with it.</p>
<h3 id="heading-type-systems">Type Systems</h3>
<ul>
<li><a target="_blank" href="https://www.typescriptlang.org/docs/handbook/type-compatibility.html">Type Compatibility</a></li>
<li><a target="_blank" href="https://medium.com/@thejameskyle/type-systems-structural-vs-nominal-typing-explained-56511dd969f4">Type Systems: Structural vs. Nominal typing explained</a></li>
<li><a target="_blank" href="https://yakovfain.com/2018/07/11/learning-typescript-structural-vs-nominal-typing-system/">Learning TypeScript: Structural vs nominal typing systems</a></li>
<li><a target="_blank" href="https://www.youtube.com/watch?v=GqmsQeSzMdw&amp;feature=youtu.be">Constraints Liberate, Liberties Constrain — Runar Bjarnason</a></li>
<li><a target="_blank" href="https://www.no.lol/2019-12-27-type-narrowing/">Type Narrowing in TypeScript</a></li>
<li><a target="_blank" href="https://2ality.com/2020/06/type-guards-assertion-functions-typescript.html">TypeScript: narrowing types via type guards and assertion functions</a></li>
<li><a target="_blank" href="https://leandrotk.github.io/tk/2020/05/typescript-learnings-interesting-types/index.html">TypeScript Learnings: Interesting Types</a></li>
</ul>
<h3 id="heading-tooling-amp-developer-experience">Tooling &amp; Developer Experience</h3>
<ul>
<li><a target="_blank" href="https://www.youtube.com/watch?v=fnTEZk-oECM">Advanced TypeScript tooling at scale</a></li>
<li><a target="_blank" href="https://www.youtube.com/watch?v=4C4wCGcsiT0">Type Systems &amp; Props Design</a></li>
<li><a target="_blank" href="https://www.youtube.com/watch?v=wSdV1M7n4gQ">Anders Hejlsberg on Modern Compiler Construction</a></li>
<li><a target="_blank" href="https://www.youtube.com/watch?v=f6TCB61fDwY">TypeScript Compiler explained by the Author Anders Hejlsberg</a></li>
</ul>
<h3 id="heading-compile-time-vs-runtime">Compile time vs Runtime</h3>
<ul>
<li><a target="_blank" href="https://stackoverflow.com/questions/846103/runtime-vs-compile-time">Compile time vs Runtime</a></li>
<li><a target="_blank" href="https://stackoverflow.com/questions/9471837/what-is-the-difference-between-run-time-error-and-compiler-error">Compile error vs Runtime error</a></li>
<li><a target="_blank" href="https://stackoverflow.com/a/51132333/3159162">Value space and Type space</a></li>
<li><a target="_blank" href="https://www.typescriptlang.org/play">A playground tool to play with TypeScript and see the JavaScript output</a></li>
</ul>
<h3 id="heading-best-practices">Best Practices</h3>
<ul>
<li><a target="_blank" href="https://engineering.zalando.com/posts/2019/02/typescript-best-practices.html">TypeScript Best Practices</a></li>
<li><a target="_blank" href="https://www.typescriptlang.org/docs/handbook/declaration-files/do-s-and-don-ts.html">Do's and Don'ts for General Types</a></li>
</ul>
<h3 id="heading-books">Books</h3>
<ul>
<li><a target="_blank" href="https://www.goodreads.com/book/show/48920810-programming-with-types">Programming with Types Book</a></li>
<li><a target="_blank" href="https://www.goodreads.com/book/show/48570456-effective-typescript">Effective TypeScript: 62 Specific Ways to Improve Your TypeScript Book</a></li>
<li><a target="_blank" href="https://thinkingwithtypes.com/">Thinking with Types</a></li>
</ul>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ C++ Compiler Explained: What is the Compiler and How Do You Use it? ]]>
                </title>
                <description>
                    <![CDATA[ Intro to C++ Compilers In order to get started with C++, you will need to learn a little about compilers and how C++ runs on your computer. When all is said and done, computers only understand one language, machine language. Machine language is entir... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/c-compiler-explained-what-is-the-compiler-and-how-do-you-use-it/</link>
                <guid isPermaLink="false">66c347142d93bf5de64ebe04</guid>
                
                    <category>
                        <![CDATA[ C++ ]]>
                    </category>
                
                    <category>
                        <![CDATA[ compilers ]]>
                    </category>
                
                    <category>
                        <![CDATA[ toothbrush ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ freeCodeCamp ]]>
                </dc:creator>
                <pubDate>Mon, 10 Feb 2020 23:40:00 +0000</pubDate>
                <media:content url="https://cdn-media-2.freecodecamp.org/w1280/5f9c9ca5740569d1a4ca3364.jpg" medium="image" />
                <content:encoded>
                    <![CDATA[ <h2 id="heading-intro-to-c-compilers">Intro to C++ Compilers</h2>
<p>In order to get started with C++, you will need to learn a little about compilers and how C++ runs on your computer.</p>
<p>When all is said and done, computers only understand one language, machine language. Machine language is entirely made up of binary bits, or 0s and 1s. </p>
<p>While it would be possible to program in binary, it would be incredibly tedious and time consuming. So, we humans developed programming languages to make it easier to develop software. </p>
<p>Assembly language is a direct 1 to 1 with machine language. Languages like C, C++, and COBOL are a little higher and need to be compiled down. It goes even higher. Languages like JavaScript and Python have components that get translated into C++ or other low level languages before they get compiled, effectively making them “higher” languages than C or C++. </p>
<p>Because computer architecture is made up of electronic switches and cables that can only work with binary 1s and 0s, you need a compiler to translate your code from high level C++ to machine language that the CPU can understand.</p>
<h2 id="heading-how-compilers-work">How compilers work</h2>
<p>Compilers are utility programs that take your code and transform it into executable machine code files. </p>
<p>When you run a compiler on your code, first, the preprocessor reads the source code (the C++ file you just wrote). The preprocessor searches for any preprocessor directives (lines of code starting with a #). Preprocessor directives cause the preprocessor to change your code in some way (by usually adding some library or another C++ file). </p>
<p>Next, the compiler works through the preprocessed code line by line translating each line into the appropriate machine language instruction. This will also uncover any syntax errors that are present in your source code and will throw an error to the command line. </p>
<p>Finally, if no errors are present, the compiler creates an object file with the machine language binary necessary to run on your machine. While the object file that the compiler just created is likely enough to do something on your computer, it still isn’t a working executable of your C++ program. There is a final important step to reach an executable program.</p>
<p>C++ contains a vast library to aid in performing difficult tasks like I/O and hardware manipulation. You can include these libraries with preprocessor directives, but the preprocessor doesn’t automatically add them to your code. </p>
<p>In order for you to have a final executable program, another utility known as the linker must combine your object files with the library functions necessary to run the code. </p>
<p>Think of it as having all the necessary blocks to build a house. The compiler made all the blocks but the linker is the one that sticks them all together to finally create a house. Once this is done, you now have a functioning executable file!</p>
<h2 id="heading-how-to-compile-a-file"><strong>How to Compile a file</strong></h2>
<p>Let’s say you have a C++ file called <code>helloWorld.cpp</code> …</p>
<h3 id="heading-if-you-are-on-windows"><strong>If you are on Windows</strong></h3>
<h4 id="heading-using-and-ide-like-codeblocks"><strong>Using and IDE like CodeBlocks</strong></h4>
<p>It is as simple as clicking the build and run buttons, they will create a file in the project folder.</p>
<p><img src="https://i.imgur.com/FwZuFGy.png" alt="img" width="1268" height="143" loading="lazy"></p>
<h4 id="heading-using-command-prompt"><strong>Using Command Prompt</strong></h4>
<ol>
<li>Open a Developer Command Prompt - For this step, you will need to have Microsoft Visual Studio or some other IDE that enables you to compile your program from the command line. You can also search online for C++ compilers.</li>
<li>Navigate to the source code directly</li>
<li>Run the Compiler on your source code (assuming you are using the Microsoft Visual Studio compiler) <code>cl /EHsc helloWorld.cpp</code></li>
</ol>
<p>This will now create an object file and automatically link it for you. If you look in that same folder, you will see a hellWorld.exe executable file (note the exe extension) is now present.</p>
<ol>
<li>Type <code>helloWorld</code> into the prompt to run the executable</li>
</ol>
<p>Alternatively, many IDEs allow for quick building and viewing of your program. This may be easier since your version of windows may not come pre packaged with a compiler utility.</p>
<h3 id="heading-if-you-are-on-linux-or-osx"><strong>If you are on Linux or OSX</strong></h3>
<ol>
<li>Open up a terminal window and navigate to the source code directory</li>
<li>Run the Compiler on your source code <code>g++ helloWorld.cpp -o helloWorld</code></li>
</ol>
<p>This will create an object file and automatically link it for you. Look in the folder and you will see a helloWorld.exe executable file (note the exe extension).</p>
<ol>
<li>Type <code>./helloWorld</code> in the terminal window to run the executable file</li>
</ol>
<p>g++ is the standard Linux compiler and is a great utility. It comes packaged with the operating system.</p>
<p>NOTE: to compile and execute your code directly, run <code>g++ -o helloWorld helloWorld.cpp; ./helloWorld</code> so when you need to compile and run your code multiple times, up arrow-enter.</p>
<p>There are a number of different types of compilers. The two listed are the two that are usually packaged with Windows or Linux/OSX.</p>
<h2 id="heading-more-info-on-c">More info on C++</h2>
<ul>
<li><a target="_blank" href="https://www.freecodecamp.org/news/the-c-plus-plus-programming-language/">Intro to C++ programming</a></li>
<li><a target="_blank" href="https://www.freecodecamp.org/news/object-oriented-programming-in-c/">Object-oriented programming in C++</a></li>
<li><a target="_blank" href="https://www.freecodecamp.org/news/graph-algorithms-and-data-structures-explained-with-java-and-c-examples/">Graph algorithms and data structures explained in C++ and Java</a></li>
<li><a target="_blank" href="https://www.freecodecamp.org/news/how-to-compile-your-c-code-in-visual-studio-code/">How to compile your C++ code in VS Code</a></li>
</ul>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ Just in Time Compilation Explained ]]>
                </title>
                <description>
                    <![CDATA[ Just-in-time compilation is a method for improving the performance of interpreted programs. During execution the program may be compiled into native code to improve its performance. It is also known as dynamic compilation. Dynamic compilation has som... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/just-in-time-compilation-explained/</link>
                <guid isPermaLink="false">66c359624217dc7d72c63d11</guid>
                
                    <category>
                        <![CDATA[ compilers ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Computer Science ]]>
                    </category>
                
                    <category>
                        <![CDATA[ toothbrush ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ freeCodeCamp ]]>
                </dc:creator>
                <pubDate>Sat, 01 Feb 2020 00:00:00 +0000</pubDate>
                <media:content url="https://cdn-media-2.freecodecamp.org/w1280/5f9c9d05740569d1a4ca357b.jpg" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>Just-in-time compilation is a method for improving the performance of interpreted programs. During execution the program may be compiled into native code to improve its performance. It is also known as dynamic compilation.</p>
<p>Dynamic compilation has some advantages over static compilation. When running Java or C# applications, the runtime environment can profile the application while it is being run. This allows for more optimized code to be generated. If the behavior of the application changes while it is running, the runtime environment can recompile the code.</p>
<p>Some of the disadvantages include startup delays and the overhead of compilation during runtime. To limit the overhead, many JIT compilers only compile the code paths that are frequently used.</p>
<h2 id="heading-overview">Overview</h2>
<p>Traditionally there are two methods for converting source code into a form that can be run on a platform. Static compilation converts the code into a language for a specific platform. An interpreter directly executes the source code.</p>
<p>JIT compilation attempts to use the benefits of both. While the interpreted program is being run, the JIT compiler determines the most frequently used code and compiles it to machine code. Depending on the compiler, this can be done on a method or smaller section of code.</p>
<p>Dynamic compilation was first described in a paper by J. McCarthy on LISP in 1960.</p>
<p>Just In Time Compilation, JIT, or Dynamic Translation, is compilation that is being done during the execution of a program. Meaning, at run time, as opposed to prior to execution. What happens is the translation to machine code. The advantages of a JIT are due to the fact, that since the compilation takes place in run time, a JIT compiler has access to dynamic runtime information enabling it to make better optimizations (such as inlining functions).</p>
<p>What is important to understand about the JIT compilation, is that it will compile the bytecode into machine code instructions of the running machine. Meaning, that the resulting machine code is optimized for the running machine’s CPU architecture.</p>
<p>Some examples of JIT Compilers are JVM (Java Virtual Machine) in Java and CLR (Common Language Runtime), in C#.</p>
<h2 id="heading-history">History</h2>
<p>In the beginning, a compiler was responsible for turning a high-level language (defined as higher level than assembler) into object code (machine instructions), which would then be linked (by a linker) into an executable.</p>
<p>At one point in the evolution of languages, compilers would compile a high-level language into pseudo-code, which would then be interpreted (by an interpreter) to run your program. This eliminated the object code and executables, and allowed these languages to be portable to multiple operating systems and hardware platforms. Pascal (which compiled to P-Code) was one of the first; Java and C# are more recent examples. Eventually the term P-Code was replaced with bytecode, since most of the pseudo-operations are a byte long.</p>
<p>A Just-In-Time (JIT) compiler is a feature of the run-time interpreter, that instead of interpreting bytecode every time a method is invoked, will compile the bytecode into the machine code instructions of the running machine, and then invoke this object code instead. Ideally the efficiency of running object code will overcome the inefficiency of recompiling the program every time it runs.</p>
<h3 id="heading-typical-scenario">Typical scenario</h3>
<p>The source code is completely converted into machine code</p>
<h3 id="heading-jit-scenario">JIT scenario</h3>
<p>The source code will be converted into assembly language like structure [for ex IL (intermediate language) for C#, ByteCode for java].</p>
<p>The intermediate code is converted into machine language only when the application needs that is required codes are only converted to machine code.</p>
<h2 id="heading-jit-vs-non-jit-comparison"><strong>JIT vs Non-JIT comparison</strong></h2>
<p>In JIT not all the code is converted into machine code first a part of the code that is necessary will be converted into machine code then if a method or functionality called is not in machine then that will be turned into machine code, which reduces burden on the CPU. As the machine code will be generated on run time, the JIT compiler will produce machine code that is optimized for running machine’s CPU architecture. </p>
<p>Some examples of JIT are:</p>
<ul>
<li>Java: JVM (Java Virtual Machine) </li>
<li>C#: CLR (Common Language Runtime) </li>
<li>Android: DVM (Dalvik Virtual Machine) or ART (Android RunTime) in newer versions</li>
</ul>
<p>The Java Virtual Machine (JVM) executes bytecode and maintains a count as of how many time a function is executed. If this count exceeds a predefined limit JIT compiles the code into machine language which can directly be executed by the processor (unlike the normal case in which javac compiles the code into bytecode and then Java, the interpreter interprets this bytecode line by line converts it into machine code and executes).</p>
<p>Also next time this function is calculated same compiled code is executed again unlike normal interpretation in which the code is interpreted again line by line. This makes execution faster.</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ What are Context Free Grammars? ]]>
                </title>
                <description>
                    <![CDATA[ By Aditya Have you ever noticed that, when you are writing code in a text editor like VS code, it recognizes things like unmatched braces? And it also sometimes warns you, with an irritating red highlight, about the incorrect syntax that you have wri... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/context-free-grammar/</link>
                <guid isPermaLink="false">66d45dd951f567b42d9f843b</guid>
                
                    <category>
                        <![CDATA[ compilers ]]>
                    </category>
                
                    <category>
                        <![CDATA[ finite state machine ]]>
                    </category>
                
                    <category>
                        <![CDATA[ linguistics ]]>
                    </category>
                
                    <category>
                        <![CDATA[ programming languages ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ freeCodeCamp ]]>
                </dc:creator>
                <pubDate>Tue, 14 Jan 2020 09:39:14 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2020/01/Lee---Company.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>By Aditya</p>
<p>Have you ever noticed that, when you are writing code in a text editor like VS code, it recognizes things like unmatched braces? And it also sometimes warns you, with an irritating red highlight, about the incorrect syntax that you have written? </p>
<p>If not, then think about it. That is after all a piece of code. How can you write code for such a task? What would be the underlying logic behind it? </p>
<p>These are the kinds of questions that you will face if you have to write a compiler for a programming language. Writing a compiler is not an easy task. It is bulky job that demands a significant amount of time and effort. </p>
<p>In this article, we are not going to talk about how to build compilers. But we will talk about a concept that is a core component of the compiler: Context Free Grammars.</p>
<h2 id="heading-introduction">Introduction</h2>
<p>All the questions we asked earlier represent a problem that is significant to compiler design called Syntax Analysis. As the name suggests, the challenge is to analyze the syntax and see if it is correct or not. This is where we use Context Free Grammars. A Context Free Grammar is a set of rules that define a language. </p>
<p>Here, I would like to draw a distinction between Context Free Grammars and grammars for natural languages like English. </p>
<p>Context Free Grammars or CFGs define a formal language. Formal languages work strictly under the defined rules and their sentences are not influenced by the context. And that's where it gets the name <em>context free</em>. </p>
<p>Languages such as English fall under the category of Informal Languages since they are affected by context. They have many other features which a CFG cannot describe.</p>
<p>Even though CFGs cannot describe the context in the natural languages, they can still define the syntax and structure of sentences in these languages. In fact, that is the reason why the CFGs were introduced in the first place. </p>
<p>In this article we will attempt to generate English sentences using CFGs. We will learn how to describe the sentence structure and write rules for it. To do this, we will use a JavaScript library called Tracery which will generate sentences on the basis of rules we defined for our grammar.</p>
<p>Before we dive into the code and start writing the rules for the grammar, let's just discuss some basic terms that we will use in our CFG.</p>
<p><strong>Terminals</strong>: These are the characters that make up the actual content of the final sentence. These can include words or letters depending on which of these is used as the basic building block of a sentence.</p>
<p>In our case we will use words as the basic building blocks of our sentences. So our terminals will include words such as "to", "from", "the", "car", "spaceship", "kittens" and so on.</p>
<p><strong>Non Terminals</strong>: These are also called variables. These act as a sub language within the language defined by the grammar. Non terminals are placeholders for the terminals. We can use non terminals to generate different patterns of terminal symbols.</p>
<p>In our case we will use these Non terminals to generate noun phrases, verb phrases, different nouns, adjectives, verbs and so on.</p>
<p><strong>Start Symbol</strong>: a start symbol is a special non terminal that represents the initial string that will be generated by the grammar.</p>
<p>Now that we know the terminology let's start learning about the grammatical rules. </p>
<p>While writing grammar rules, we will start by defining the set of terminals and a start state. As we learned before, that start symbol is a non-terminal. This means it will belong to the set of non-terminals. </p>
<pre><code>T: (<span class="hljs-string">"Monkey"</span>, <span class="hljs-string">"banana"</span>, <span class="hljs-string">"ate"</span>, <span class="hljs-string">"the"</span>)
<span class="hljs-attr">S</span>: Start state.
</code></pre><p>And the rules are:</p>
<pre><code>S --&gt; nounPhrase verbPhrase
nounPhrase --&gt; adj nounPhrase | adj noun
verbPhrase --&gt; verb nounPhrase
adjective  --&gt; the
noun --&gt; Monkey | banana
verb --&gt; ate
</code></pre><p>The above grammatical rules may seem somewhat cryptic at first. But if we look carefully, we can see a pattern that is being generated out of these rules. </p>
<p>A better way to think about the above rules is to visualise them in the form of a tree structure. In that tree we can put <em>S</em> in the root and <em>nounPhrase</em> and <em>verbPhrase</em> can be added as children of the root. We can proceed in the same way with <em>nounPhrase</em> and <em>verbPhrase</em> too. The tree will have terminals as its leaf nodes because that is where we end these derivations. </p>
<p><img src="https://www.freecodecamp.org/news/content/images/2020/01/parsetree.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>In the above image we can see that <em>S</em> (a nonterminal)  derives two non terminals <em>NP</em>(<em>nounPhrase</em>) and <em>VP</em>(<em>verbPhrase</em>). In the case of <em>NP</em>, it has derived two non terminals, <em>Adj</em> and <em>Noun</em>. </p>
<p>If you look at the grammar, <em>NP</em> could also have chosen <em>Adj</em> and <em>nounPhrase</em>. While generating text, these choices are made randomly. </p>
<p>And finally the leaf nodes have terminals which are written in the bold text. So if you move from left to right, you can see that a sentence is formed.</p>
<p>The term often used for this tree is a Parse Tree. We can create another parse tree for a different sentence generated by this grammar in a similar way. </p>
<p>Now let's proceed further to the code. As I mentioned earlier, we will use a JavaScript library called Tracery for text generation using CFGs. We will also write some code in HTML and CSS for the front-end part.</p>
<h2 id="heading-the-code">The Code</h2>
<p>Let's start by first getting the tracery library. You can clone the library from GitHub <a target="_blank" href="https://github.com/galaxykate/tracery">here</a>. I have also left the link to the GitHub repository by galaxykate at the end of the article.</p>
<p>Before we use the library we will have to import it. We can do this simply in an HTML file like this. </p>
<pre><code class="lang-html"><span class="hljs-tag">&lt;<span class="hljs-name">html</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">head</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">script</span> <span class="hljs-attr">src</span>=<span class="hljs-string">"tracery-master/js/vendor/jquery-1.11.2.min.js"</span>&gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">script</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">script</span> <span class="hljs-attr">src</span>=<span class="hljs-string">"tracery-master/tracery.js"</span>&gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">script</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">script</span> <span class="hljs-attr">src</span>=<span class="hljs-string">"tracery-master/js/grammars.js"</span>&gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">script</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">script</span> <span class="hljs-attr">src</span>=<span class="hljs-string">'app.js'</span>&gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">script</span>&gt;</span>
    <span class="hljs-tag">&lt;/<span class="hljs-name">head</span>&gt;</span>

<span class="hljs-tag">&lt;/<span class="hljs-name">html</span>&gt;</span>
</code></pre>
<p>I have added the cloned tracery file as a script in my HTML code. We will also have to add JQuery to our code because tracery depends on JQuery. Finally, I have added <em>app.js</em> which is the file where I will add rules for the grammar.</p>
<p>Once that is done, create a JavaScript file where we will define our grammar rules.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">var</span> rules = {
        <span class="hljs-string">"start"</span>: [<span class="hljs-string">"#NP# #VP#."</span>],
        <span class="hljs-string">"NP"</span>: [<span class="hljs-string">"#Det# #N#"</span>, <span class="hljs-string">"#Det# #N# that #VP#"</span>, <span class="hljs-string">"#Det# #Adj# #N#"</span>],
        <span class="hljs-string">"VP"</span>: [<span class="hljs-string">"#Vtrans# #NP#"</span>, <span class="hljs-string">"#Vintr#"</span>],
        <span class="hljs-string">"Det"</span>: [<span class="hljs-string">"The"</span>, <span class="hljs-string">"This"</span>, <span class="hljs-string">"That"</span>],
        <span class="hljs-string">"N"</span>: [<span class="hljs-string">"John Keating"</span>, <span class="hljs-string">"Bob Harris"</span>, <span class="hljs-string">"Bruce Wayne"</span>, <span class="hljs-string">"John Constantine"</span>, <span class="hljs-string">"Tony Stark"</span>, <span class="hljs-string">"John Wick"</span>, <span class="hljs-string">"Sherlock Holmes"</span>, <span class="hljs-string">"King Leonidas"</span>],
        <span class="hljs-string">"Adj"</span>: [<span class="hljs-string">"cool"</span>, <span class="hljs-string">"lazy"</span>, <span class="hljs-string">"amazed"</span>, <span class="hljs-string">"sweet"</span>],
        <span class="hljs-string">"Vtrans"</span>: [<span class="hljs-string">"computes"</span>, <span class="hljs-string">"examines"</span>, <span class="hljs-string">"helps"</span>, <span class="hljs-string">"prefers"</span>, <span class="hljs-string">"sends"</span>, <span class="hljs-string">"plays with"</span>, <span class="hljs-string">"messes up with"</span>],
        <span class="hljs-string">"Vintr"</span>: [<span class="hljs-string">"coughs"</span>, <span class="hljs-string">"daydreams"</span>, <span class="hljs-string">"whines"</span>, <span class="hljs-string">"slobbers"</span>, <span class="hljs-string">"appears"</span>, <span class="hljs-string">"disappears"</span>, <span class="hljs-string">"exists"</span>, <span class="hljs-string">"cries"</span>, <span class="hljs-string">"laughs"</span>]
    }
</code></pre>
<p>Here you will notice that the syntax for defining rules is not much different from how we defined our grammar earlier. There are very minor differences such as the way non-terminals are defined between the hash symbols. And also the way in which different derivations are written. Instead of using the "|" symbol for separating them, here we will put all the different derivations as different elements of an array. Other than that, we will use the semicolons instead of arrows to represent the transition. </p>
<p>This new grammar is a little more complicated than the one we defined earlier. This one includes many other things such as Determiners, Transitive Verbs and Intransitive Verbs. We do this to make the generated text look more natural. </p>
<p>Let's now call the tracery function "createGrammar" to create the grammar we just defined. </p>
<pre><code class="lang-javascript"><span class="hljs-keyword">let</span> grammar = tracery.createGrammar(rules);
</code></pre>
<p>This function will take the rules object and generate a grammar on the basis of these rules. After creating the grammar, we now want to generate some end result from it. To do that we will use a function called "flatten".</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">let</span> expansion = grammar.flatten(<span class="hljs-string">'#start#'</span>);
</code></pre>
<p>It will generate a random sentence based on the rules that we defined earlier. But let's not stop there. Let's also build a user interface for it. There's not much we will have to do for that part – we just need a button and some basic styles for the interface.</p>
<p>In the same HTML file where we added the libraries we will add some elements.</p>
<pre><code class="lang-html"><span class="hljs-tag">&lt;<span class="hljs-name">html</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">head</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">title</span>&gt;</span>Weird Sentences<span class="hljs-tag">&lt;/<span class="hljs-name">title</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">link</span> <span class="hljs-attr">rel</span>=<span class="hljs-string">"stylesheet"</span> <span class="hljs-attr">href</span>=<span class="hljs-string">"style.css"</span>/&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">link</span> <span class="hljs-attr">href</span>=<span class="hljs-string">"https://fonts.googleapis.com/css?family=UnifrakturMaguntia&amp;display=swap"</span> <span class="hljs-attr">rel</span>=<span class="hljs-string">"stylesheet"</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">link</span> <span class="hljs-attr">href</span>=<span class="hljs-string">"https://fonts.googleapis.com/css?family=Harmattan&amp;display=swap"</span> <span class="hljs-attr">rel</span>=<span class="hljs-string">"stylesheet"</span>&gt;</span>

        <span class="hljs-tag">&lt;<span class="hljs-name">script</span> <span class="hljs-attr">src</span>=<span class="hljs-string">"tracery-master/js/vendor/jquery-1.11.2.min.js"</span>&gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">script</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">script</span> <span class="hljs-attr">src</span>=<span class="hljs-string">"tracery-master/tracery.js"</span>&gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">script</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">script</span> <span class="hljs-attr">src</span>=<span class="hljs-string">"tracery-master/js/grammars.js"</span>&gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">script</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">script</span> <span class="hljs-attr">src</span>=<span class="hljs-string">'app.js'</span>&gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">script</span>&gt;</span>
    <span class="hljs-tag">&lt;/<span class="hljs-name">head</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">body</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">h1</span> <span class="hljs-attr">id</span>=<span class="hljs-string">"h1"</span>&gt;</span>Weird Sentences<span class="hljs-tag">&lt;/<span class="hljs-name">h1</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">button</span> <span class="hljs-attr">id</span>=<span class="hljs-string">"generate"</span> <span class="hljs-attr">onclick</span>=<span class="hljs-string">"generate()"</span>&gt;</span>Give me a Sentence!<span class="hljs-tag">&lt;/<span class="hljs-name">button</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">id</span>=<span class="hljs-string">"sentences"</span>&gt;</span>

        <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
    <span class="hljs-tag">&lt;/<span class="hljs-name">body</span>&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">html</span>&gt;</span>
</code></pre>
<p>And finally we will add some styles to it.</p>
<pre><code class="lang-css"><span class="hljs-selector-tag">body</span> {
    <span class="hljs-attribute">text-align</span>: center;
    <span class="hljs-attribute">margin</span>: <span class="hljs-number">0</span>;
    <span class="hljs-attribute">font-family</span>: <span class="hljs-string">'Harmattan'</span>, sans-serif;
}

<span class="hljs-selector-id">#h1</span> {
    <span class="hljs-attribute">font-family</span>: <span class="hljs-string">'UnifrakturMaguntia'</span>, cursive;
    <span class="hljs-attribute">font-size</span>: <span class="hljs-number">4em</span>;
    <span class="hljs-attribute">background-color</span>: <span class="hljs-built_in">rgb</span>(<span class="hljs-number">37</span>, <span class="hljs-number">146</span>, <span class="hljs-number">235</span>);
    <span class="hljs-attribute">color</span>: white;
    <span class="hljs-attribute">padding</span>: .<span class="hljs-number">5em</span>;
    <span class="hljs-attribute">box-shadow</span>: <span class="hljs-number">1px</span> <span class="hljs-number">1px</span> <span class="hljs-number">1px</span> <span class="hljs-number">1px</span> <span class="hljs-built_in">rgb</span>(<span class="hljs-number">206</span>, <span class="hljs-number">204</span>, <span class="hljs-number">204</span>);
}

<span class="hljs-selector-id">#generate</span> {
    <span class="hljs-attribute">font-family</span>: <span class="hljs-string">'Harmattan'</span>, sans-serif;
    <span class="hljs-attribute">font-size</span>: <span class="hljs-number">2em</span>;
    <span class="hljs-attribute">font-weight</span>: bold;
    <span class="hljs-attribute">padding</span>: .<span class="hljs-number">5em</span>;
    <span class="hljs-attribute">margin</span>: .<span class="hljs-number">5em</span>;
    <span class="hljs-attribute">box-shadow</span>: <span class="hljs-number">1px</span> <span class="hljs-number">1px</span> <span class="hljs-number">1px</span> <span class="hljs-number">1px</span> <span class="hljs-built_in">rgb</span>(<span class="hljs-number">206</span>, <span class="hljs-number">204</span>, <span class="hljs-number">204</span>);
    <span class="hljs-attribute">background-color</span>: <span class="hljs-built_in">rgb</span>(<span class="hljs-number">255</span>, <span class="hljs-number">0</span>, <span class="hljs-number">64</span>);
    <span class="hljs-attribute">color</span>: white;
    <span class="hljs-attribute">border</span>: none;
    <span class="hljs-attribute">border-radius</span>: <span class="hljs-number">2px</span>;
    <span class="hljs-attribute">outline</span>: none;
}

<span class="hljs-selector-id">#sentences</span> <span class="hljs-selector-tag">p</span> {
    <span class="hljs-attribute">box-shadow</span>: <span class="hljs-number">1px</span> <span class="hljs-number">1px</span> <span class="hljs-number">1px</span> <span class="hljs-number">1px</span> <span class="hljs-built_in">rgb</span>(<span class="hljs-number">206</span>, <span class="hljs-number">204</span>, <span class="hljs-number">204</span>);
    <span class="hljs-attribute">margin</span>: <span class="hljs-number">2em</span>;
    <span class="hljs-attribute">margin-left</span>: <span class="hljs-number">15em</span>;
    <span class="hljs-attribute">margin-right</span>: <span class="hljs-number">15em</span>;
    <span class="hljs-attribute">padding</span>: <span class="hljs-number">2em</span>;
    <span class="hljs-attribute">border-radius</span>: <span class="hljs-number">2px</span>;
    <span class="hljs-attribute">font-size</span>: <span class="hljs-number">1.5em</span>;
}
</code></pre>
<p>We will also have to add some more JavaScript to manipulate the interface.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">let</span> sentences = []
<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">generate</span>(<span class="hljs-params"></span>) </span>{
    <span class="hljs-keyword">var</span> data = {
        <span class="hljs-string">"start"</span>: [<span class="hljs-string">"#NP# #VP#."</span>],
        <span class="hljs-string">"NP"</span>: [<span class="hljs-string">"#Det# #N#"</span>, <span class="hljs-string">"#Det# #N# that #VP#"</span>, <span class="hljs-string">"#Det# #Adj# #N#"</span>],
        <span class="hljs-string">"VP"</span>: [<span class="hljs-string">"#Vtrans# #NP#"</span>, <span class="hljs-string">"#Vintr#"</span>],
        <span class="hljs-string">"Det"</span>: [<span class="hljs-string">"The"</span>, <span class="hljs-string">"This"</span>, <span class="hljs-string">"That"</span>],
        <span class="hljs-string">"N"</span>: [<span class="hljs-string">"John Keating"</span>, <span class="hljs-string">"Bob Harris"</span>, <span class="hljs-string">"Bruce Wayne"</span>, <span class="hljs-string">"John Constantine"</span>, <span class="hljs-string">"Tony Stark"</span>, <span class="hljs-string">"John Wick"</span>, <span class="hljs-string">"Sherlock Holmes"</span>, <span class="hljs-string">"King Leonidas"</span>],
        <span class="hljs-string">"Adj"</span>: [<span class="hljs-string">"cool"</span>, <span class="hljs-string">"lazy"</span>, <span class="hljs-string">"amazed"</span>, <span class="hljs-string">"sweet"</span>],
        <span class="hljs-string">"Vtrans"</span>: [<span class="hljs-string">"computes"</span>, <span class="hljs-string">"examines"</span>, <span class="hljs-string">"helps"</span>, <span class="hljs-string">"prefers"</span>, <span class="hljs-string">"sends"</span>, <span class="hljs-string">"plays with"</span>, <span class="hljs-string">"messes up with"</span>],
        <span class="hljs-string">"Vintr"</span>: [<span class="hljs-string">"coughs"</span>, <span class="hljs-string">"daydreams"</span>, <span class="hljs-string">"whines"</span>, <span class="hljs-string">"slobbers"</span>, <span class="hljs-string">"appears"</span>, <span class="hljs-string">"disappears"</span>, <span class="hljs-string">"exists"</span>, <span class="hljs-string">"cries"</span>, <span class="hljs-string">"laughs"</span>]
    }

    <span class="hljs-keyword">let</span> grammar = tracery.createGrammar(data);
    <span class="hljs-keyword">let</span> expansion = grammar.flatten(<span class="hljs-string">'#start#'</span>);

    sentences.push(expansion);

    printSentences(sentences);
}

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">printSentences</span>(<span class="hljs-params">sentences</span>) </span>{
    <span class="hljs-keyword">let</span> textBox = <span class="hljs-built_in">document</span>.getElementById(<span class="hljs-string">"sentences"</span>);
    textBox.innerHTML = <span class="hljs-string">""</span>;
    <span class="hljs-keyword">for</span>(<span class="hljs-keyword">let</span> i=sentences.length<span class="hljs-number">-1</span>; i&gt;=<span class="hljs-number">0</span>; i--) {
        textBox.innerHTML += <span class="hljs-string">"&lt;p&gt;"</span>+sentences[i]+<span class="hljs-string">"&lt;/p&gt;"</span>
    }
}
</code></pre>
<p>Once you have finished writing the code, run your HTML file. It should look something like this.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2020/01/ws2.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>Every time you click the red button it will generate a sentence. Some of these sentences might not make any sense. This is because, as I said earlier, CFGs cannot describe the context and some other features that natural languages possess. It is used only to define the syntax and structure of the sentences. </p>
<p>You can check out the live version of this <a target="_blank" href="https://aditya2000.github.io/weird-sentences/">here</a>.</p>
<h2 id="heading-conclusion">Conclusion</h2>
<p>If you have made it this far, I highly appreciate your resilience. It might be a new concept for some of you, and others might have learnt about it in their college courses. But still, Context Free Grammars have interesting applications that range widely from Computer Science to Linguistics. </p>
<p>I have tried my best to present the main ideas of CFGs here, but there is a lot more that you can learn about them. Here I have left links to some great resources: </p>
<ul>
<li><a target="_blank" href="https://youtu.be/C3EwsSNJeOE">Context Free Grammars</a> by Daniel Shiffman.</li>
<li><a target="_blank" href="https://youtu.be/R_OVyFrBhiU">Context Free Grammars Examples</a> by Fullstack Academy</li>
<li><a target="_blank" href="https://github.com/galaxykate/tracery">Tracery</a> by Galaxykate</li>
</ul>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ How to compile your C++ code in Visual Studio Code ]]>
                </title>
                <description>
                    <![CDATA[ C++ is a statically-typed, free-form, (usually) compiled, multi-paradigm, intermediate-level general-purpose middle-level programming language. In simple terms, C++ is a sophisticated, efficient, general-purpose programming language based on C. It wa... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/how-to-compile-your-c-code-in-visual-studio-code/</link>
                <guid isPermaLink="false">66d84e18c15439a8d5631e45</guid>
                
                    <category>
                        <![CDATA[ C++ ]]>
                    </category>
                
                    <category>
                        <![CDATA[ compilers ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Visual Studio Code ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Bolaji Ayodeji ]]>
                </dc:creator>
                <pubDate>Mon, 07 Oct 2019 05:14:17 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2019/10/banner-1.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>C++ is a statically-typed, free-form, (usually) compiled, multi-paradigm, intermediate-level general-purpose middle-level programming language.</p>
<p>In simple terms, C++ is a sophisticated, efficient, general-purpose programming language based on C.</p>
<p>It was developed by <a target="_blank" href="http://www.stroustrup.com/">Bjarne Stroustrup</a> in 1979.</p>
<p>One of C++'s main features is the compiler. This is used to compile and run C++ code.</p>
<blockquote>
<p>A compiler is a special program that processes statements written in a particular programming language like C++ and turns them into machine language or "code" that a computer's processor uses. (<a target="_blank" href="https://en.wikipedia.org/wiki/Compiler">Source</a>)</p>
</blockquote>
<p>I actually wrote this article because I had a C++ assignment which required using a compiler. As usual, everyone was using the <a target="_blank" href="http://www.codeblocks.org/">CodeBlocks IDE</a> and <a target="_blank" href="https://visualstudio.microsoft.com/">Visual Studio IDE</a>. But I was already used to Visual Studio Code for all my programming stuff.</p>
<p>I then set out to find a way of compiling C++ directly inside my own VsCode Editor, hence this article :).</p>
<p>In this article, I'll show you how to set up your compiler in VsCode and give you some links to some of the best C++ resources.</p>
<p><img src="https://media0.giphy.com/media/3o7TKUM3IgJBX2as9O/giphy.gif" alt="Image" width="267" height="200" loading="lazy"></p>
<h1 id="heading-prerequisites">Prerequisites</h1>
<ul>
<li><p>Prior knowledge of C++<br>  (I assume you're learning C++, about to start learning, or just reading this for fun. This article is not a C++ 101 tutorial – some understanding of C++ is needed.)</p>
</li>
<li><p>Visual Studio Code Editor<br>  Download <a target="_blank" href="https://code.visualstudio.com/#alt-downloads">here</a> and read the setup docs for <a target="_blank" href="https://code.visualstudio.com/docs/?dv=win">Windows</a>, <a target="_blank" href="https://code.visualstudio.com/docs/?dv=linux64_deb">Linux</a> and <a target="_blank" href="https://code.visualstudio.com/docs/?dv=osx">Mac</a></p>
</li>
<li><p><strong>Internet connection (!important)</strong></p>
</li>
</ul>
<h3 id="heading-disclaimer"><strong>Disclaimer!</strong></h3>
<p>I will be using a Windows OS throughout this article, but I'll provide links to resources that will help those using other operating systems.</p>
<p>Now let's get started!</p>
<h1 id="heading-download-and-install-a-c-compiler">Download and install a C++ compiler</h1>
<ul>
<li>Head to www.mingw.org and click the “Download/Installer” link to download the MinGW setup file, or click <a target="_blank" href="https://osdn.net/projects/mingw/downloads/68260/mingw-get-setup.exe/">here</a> for Windows, <a target="_blank" href="http://www.mingw.org/wiki/LinuxCrossMinGW">here</a> for Linux, and <a target="_blank" href="https://brewinstall.org/Install-mingw-w64-on-Mac-with-Brew/">here</a> for Mac</li>
</ul>
<blockquote>
<p>MinGW, a contraction of "Minimalist GNU for Windows", is a minimalist development environment for native Microsoft Windows applications. (<a target="_blank" href="https://mingw.osdn.io/">Source</a>)</p>
</blockquote>
<ul>
<li>After downloading, install MinGW and wait for the “MinGW Installation Manager” to show up.</li>
</ul>
<p><img src="https://www.freecodecamp.org/news/content/images/2019/10/Capture1.png" alt="Image" width="600" height="400" loading="lazy"></p>
<ul>
<li>When the “MinGW Installation Manager” shows up, click on <code>mingw32-gcc-g++</code> then select “Mark for Installation”</li>
</ul>
<p><img src="https://www.freecodecamp.org/news/content/images/2019/10/Capture2.png" alt="Image" width="600" height="400" loading="lazy"></p>
<ul>
<li>In the menu at the top left corner, click on “Installation &gt; Apply Changes”</li>
</ul>
<p><img src="https://www.freecodecamp.org/news/content/images/2019/10/Capture3.png" alt="Image" width="600" height="400" loading="lazy"></p>
<ul>
<li>Wait and allow to install completely. Ensure you have a stable internet connection during this process.</li>
</ul>
<h1 id="heading-edit-your-path-environment-variable-to-include-the-directory-where-the-c-compiler-is-located">Edit your PATH environment variable to include the directory where the C++ compiler is located</h1>
<blockquote>
<p>PATH is an environment variable on Unix-like operating systems, DOS, OS/2, and Microsoft Windows, specifying a set of directories where executable programs are located. In general, each executing process or user session has its own PATH setting. - <a target="_blank" href="https://en.wikipedia.org/wiki/PATH_(variable)">Wikipedia</a></p>
</blockquote>
<p>After installing MinGW, it can be found in <code>C:\MinGW\bin</code>. Now you have to include this directory in your environment variable PATH. If you've been using computers for a while now you should know how to do this already, but if you don't, here are a few resources:</p>
<ul>
<li><p>Click <a target="_blank" href="https://www.computerhope.com/issues/ch000549.htm">here</a> for a Windows OS guide</p>
</li>
<li><p>Click <a target="_blank" href="https://www.cyberciti.biz/faq/unix-linux-adding-path/">here</a> for Linux</p>
</li>
<li><p>Click <a target="_blank" href="https://hathaway.cc/2008/06/how-to-edit-your-path-environment-variables-on-mac/">here</a> for a Mac OS guide</p>
</li>
</ul>
<h1 id="heading-install-code-runner-extension-in-vs-code">Install Code Runner extension in VS Code</h1>
<p>Now we have our compiler set up, let's install Code Runner</p>
<p>Code Runner allows you to Run code snippet or code file for multiple languages:</p>
<blockquote>
<p>C, C++, Java, JavaScript, PHP, Python, Perl, Perl 6, Ruby, Go, Lua, Groovy, PowerShell, BAT/CMD, BASH/SH, F# Script, F# (.NET Core), C# Script, C# (.NET Core), VBScript, TypeScript, CoffeeScript, Scala, Swift, Julia, Crystal, OCaml Script, R, AppleScript, Elixir, Visual Basic .NET, Clojure, Haxe, Objective-C, Rust, Racket, AutoHotkey, AutoIt, Kotlin, Dart, Free Pascal, Haskell, Nim, D, Lisp, Kit, and custom command.</p>
</blockquote>
<ul>
<li><p>Click <a target="_blank" href="https://marketplace.visualstudio.com/items?itemName=formulahendry.code-runner">here</a> to download</p>
</li>
<li><p>Or search in VsCode marketplace tab</p>
</li>
</ul>
<p><img src="https://www.freecodecamp.org/news/content/images/2019/10/Capture4.png" alt="Image" width="600" height="400" loading="lazy"></p>
<ul>
<li><p>After installing restart VsCode</p>
</li>
<li><p>Open your C++ file in Vscode. Here's a basic hello world program below:</p>
</li>
</ul>
<pre><code class="lang-c++"><span class="hljs-meta">#<span class="hljs-meta-keyword">include</span> <span class="hljs-meta-string">&lt;iostream&gt;</span></span>
<span class="hljs-keyword">using</span> <span class="hljs-keyword">namespace</span> <span class="hljs-built_in">std</span>;
<span class="hljs-function"><span class="hljs-keyword">int</span> <span class="hljs-title">main</span><span class="hljs-params">()</span> 
</span>{
    <span class="hljs-built_in">cout</span> &lt;&lt; <span class="hljs-string">"Hello world!"</span>;
    <span class="hljs-keyword">return</span> <span class="hljs-number">0</span>;
}
</code></pre>
<p>Save this file as <code>test.cpp</code></p>
<h1 id="heading-run-your-code-using-code-runner">Run your code using Code Runner</h1>
<ul>
<li><p>Use the shortcut <code>Ctrl+Alt+N</code></p>
</li>
<li><p>Or press F1 and then select/type Run Code</p>
</li>
<li><p>Or right-click the Text Editor and then click Run Code in the editor context menu</p>
</li>
</ul>
<p>The code will run and the output will be shown in the Output Window. Open the output window with `Ctrl+ shortcut.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2019/10/Capture5.png" alt="Image" width="600" height="400" loading="lazy"></p>
<h1 id="heading-to-stop-the-running-code">To stop the running code</h1>
<ul>
<li><p>Use the shortcut <code>Ctrl+Alt+M</code></p>
</li>
<li><p>Or press F1 and then select/type Stop Code Run</p>
</li>
<li><p>Or right-click the Output Channel and then click Stop Code Run in the context menu</p>
</li>
</ul>
<p>Hurray, you just successfully set up your C++ environment in VsCode!</p>
<h1 id="heading-conclusion">Conclusion</h1>
<p>Here's a quick hint: By default, VsCode's output terminal is read-only. If you're running code that requires user input like:</p>
<pre><code class="lang-c++"><span class="hljs-meta">#<span class="hljs-meta-keyword">include</span> <span class="hljs-meta-string">&lt;iostream&gt;</span></span>
<span class="hljs-keyword">using</span> <span class="hljs-keyword">namespace</span> <span class="hljs-built_in">std</span>;

<span class="hljs-keyword">const</span> <span class="hljs-keyword">double</span> pi = <span class="hljs-number">3.14159</span>; 

<span class="hljs-function"><span class="hljs-keyword">void</span> <span class="hljs-title">calculate</span><span class="hljs-params">()</span>
</span>{
  <span class="hljs-keyword">double</span> area; 
  <span class="hljs-keyword">double</span> radius;

  <span class="hljs-built_in">cout</span>&lt;&lt;<span class="hljs-string">"Enter Radius: "</span>&lt;&lt;<span class="hljs-built_in">endl</span>; 
  <span class="hljs-built_in">cin</span>&gt;&gt;radius;

  area = pi * radius * radius; 

  <span class="hljs-built_in">cout</span>&lt;&lt;<span class="hljs-string">"area is: "</span>&lt;&lt;area&lt;&lt;<span class="hljs-built_in">endl</span>;
 }

<span class="hljs-function"><span class="hljs-keyword">int</span> <span class="hljs-title">main</span><span class="hljs-params">()</span>
</span>{
  calculate(); 
  <span class="hljs-keyword">return</span> <span class="hljs-number">0</span>;
}
</code></pre>
<p>you won't be able to type into the terminal, <code>Cannot edit in read-only terminal</code>.<br>To fix this, you need to manually enable read-write.</p>
<ul>
<li><p>In VsCode, Go to File &gt; Preference &gt; Setting.</p>
</li>
<li><p>In the User tab on the left panel, find the extensions section</p>
</li>
<li><p>Scroll and find 'Run Code Configuration'</p>
</li>
<li><p>Scroll and find a checkbox <code>Run in Terminal</code> (Whether to run code in Integrated Terminal) Check the box.</p>
</li>
</ul>
<p>OR</p>
<ul>
<li>In your <code>setting.json</code> file, add:</li>
</ul>
<pre><code class="lang-python"><span class="hljs-string">"code-runner.runInTerminal"</span>: true
</code></pre>
<p>Hurray, you're done and ready to roll :).</p>
<h1 id="heading-c-resources">C++ resources</h1>
<p>Here are some C++ resources you can use to get started with learning C++</p>
<ul>
<li><p><a target="_blank" href="https://www.learncpp.com/">https://www.learncpp.com/</a></p>
</li>
<li><p><a target="_blank" href="https://www.codecademy.com/learn/learn-c-plus-plus">https://www.codecademy.com/learn/learn-c-plus-plus</a></p>
</li>
<li><p><a target="_blank" href="https://www.udemy.com/free-learn-c-tutorial-beginners/">https://www.udemy.com/free-learn-c-tutorial-beginners/</a></p>
</li>
<li><p><a target="_blank" href="https://www.sololearn.com/Course/CPlusPlus/">https://www.sololearn.com/Course/CPlusPlus/</a></p>
</li>
<li><p><a target="_blank" href="https://www.youtube.com/watch?v=vLnPwxZdW4Y">https://www.youtube.com/watch?v=vLnPwxZdW4Y</a></p>
</li>
<li><p><a target="_blank" href="https://www.tutorialspoint.com/cplusplus/cpp_useful_resources.htm">https://www.tutorialspoint.com/cplusplus/cpp_useful_resources.htm</a></p>
</li>
<li><p><a target="_blank" href="https://www.tutorialspoint.com/cplusplus/cpp_useful_resources.htm">https://makeawebsitehub.com/learning-c/</a></p>
</li>
</ul>
<h1 id="heading-credits">Credits</h1>
<ul>
<li><p><a target="_blank" href="http://www.mingw.org/">MinGW Project</a></p>
</li>
<li><p><a target="_blank" href="https://marketplace.visualstudio.com/items?itemName=formulahendry.code-runner">Code Runner</a> by <a target="_blank" href="https://marketplace.visualstudio.com/publishers/formulahendry">Jun Han</a></p>
</li>
</ul>
<p>Thank you for reading!</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ How to write a compiler in Go: a quick guide ]]>
                </title>
                <description>
                    <![CDATA[ By Joseph Livni Compilers are awesome! ? ? ? They combine theory and application and touch on a lot of software related topics such as parsing and language construction. At their core, compilers are a program that make a program readable by the compu... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/write-a-compiler-in-go-quick-guide-30d2f33ac6e0/</link>
                <guid isPermaLink="false">66c3679a40438b5931fe09ba</guid>
                
                    <category>
                        <![CDATA[ compilers ]]>
                    </category>
                
                    <category>
                        <![CDATA[ golang ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Productivity ]]>
                    </category>
                
                    <category>
                        <![CDATA[ General Programming ]]>
                    </category>
                
                    <category>
                        <![CDATA[ technology ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ freeCodeCamp ]]>
                </dc:creator>
                <pubDate>Mon, 07 Jan 2019 14:54:04 +0000</pubDate>
                <media:content url="https://cdn-media-1.freecodecamp.org/images/1*xwPzWlZJoBbgrtEvwslRdg.jpeg" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>By Joseph Livni</p>
<p>Compilers are awesome! ? ? ? They combine theory and application and touch on a lot of software related topics such as parsing and language construction. At their core, compilers are a program that make a program readable by the computer.</p>
<p>The inspiration for this came out of a compilers course I took this past Fall and my love for Go.</p>
<p>This is the guide I wish I had when starting my journey into compilers. There are a lot of books, videos, and tutorials on how to create compilers. The goal of this post is to strike a balance between providing a nontrivial example of some of the things a compiler can do while avoid getting stuck in the weeds. ?</p>
<p>The result will be a compiler that can execute a small made up language.To checkout and run the final project see the instructions below. ?</p>
<p><strong>Note:</strong> Remember that Go is strict about absolute paths when running this</p>
<pre><code>cd $GOPATH/src/github.com/Lebonescogit clone https:<span class="hljs-comment">//github.com/Lebonesco/go-compiler.gitcd go-compilergo test -vgo run main.go ./examples/math.bx</span>
</code></pre><h4 id="heading-outline-of-the-compiler">Outline of the Compiler</h4>
<ul>
<li><strong>Lexer/Parser</strong></li>
<li><strong>AST Generator</strong></li>
<li><strong>Type Checker</strong></li>
<li><strong>Code Generation</strong></li>
</ul>
<h4 id="heading-the-language">The Language</h4>
<p>The goal of this post is to get you familiar with compilers as quickly as a possible so we’ll keep the language simple. For <strong>Types</strong> we’ll work with <code>strings</code>, <code>integers</code>, and <code>bools</code>. It will have <strong>Statements</strong> that include <code>func</code>, <code>if</code>, <code>else</code>, <code>let</code>, and <code>return</code>. This should be enough to have fun working with some of the complexities of a compiler.</p>
<p>The first compiler that I built, I completed over the course of two months and took up <strong>1000’s of lines</strong> of code. I took some shortcuts in this post in order to show you the key fundamentals.</p>
<p>Two common components that our language is missing are <code>classes</code> and <code>arrays</code>. These add additional complications we don’t have time for right now. If it turns out that people really want to know how to handle these elements I’ll write a followup.</p>
<p>Some example code:</p>
<pre><code>func add(a Int, b int) Int {    <span class="hljs-keyword">return</span> a + b;}
</code></pre><pre><code>func hello(name <span class="hljs-built_in">String</span>) <span class="hljs-built_in">String</span> {    <span class="hljs-keyword">return</span> <span class="hljs-string">"hello:"</span> + <span class="hljs-string">" "</span> + name;}
</code></pre><pre><code><span class="hljs-keyword">let</span> num = add(<span class="hljs-number">1</span>, <span class="hljs-number">2</span>);<span class="hljs-keyword">let</span> phrase = string hello(<span class="hljs-string">"Jeff"</span>);<span class="hljs-keyword">let</span> i = int <span class="hljs-number">0</span>;<span class="hljs-keyword">let</span> result = <span class="hljs-string">""</span>;
</code></pre><pre><code><span class="hljs-keyword">if</span> (i == <span class="hljs-number">2</span>) {    result = hello(<span class="hljs-string">"cat"</span>);} <span class="hljs-keyword">else</span> {    result = hello(<span class="hljs-string">"dog"</span>);}
</code></pre><pre><code>PRINT(result);
</code></pre><h4 id="heading-quick-setup">Quick Setup</h4>
<p>The only outside package we need is <code>**gocc**</code><strong>,</strong> which will help build the lexer and parser.</p>
<p>To get it run:</p>
<pre><code>go get github.com/goccmack/gocc
</code></pre><p>Make sure the bin folder where gocc is located is in your <code>**PATH**</code> <strong>:</strong></p>
<pre><code><span class="hljs-keyword">export</span> PATH=$GOPATH/bin:$PATH
</code></pre><p><strong>Note:</strong> If you’re having problems at this stage try running <code>go env</code> to make sure that your <code>$GOROOT</code> and <code>$GOPATH</code> are correctly assigned.</p>
<p>Cool, let’s dive into some code.</p>
<h4 id="heading-building-the-lexer">Building the Lexer</h4>
<p>The lexer’s job is to read the program and output a stream of tokens that are consumed by the parser. Each <code>Token</code> contains the <code>type</code> that the token represents in the language and the string <code>Literal</code> of that token.</p>
<p>To identify the pieces of the program we will be using regular expressions. gocc will then convert these regular expressions into a <strong>DFA</strong> (<em>Deterministic Finite Automata</em>) which can theoretically run in linear time.</p>
<p>The notation that we’ll be using is <strong>BNF</strong> (<em>Backus–Naur form</em>). Don’t confuse this with <strong>EBNF</strong> (<em>extended Backus–Naur form</em>) or <strong>ABNF</strong> (<em>augmented Backus–Naur form</em>) which have some added features. Keep this in mind when looking at other examples online that could be using other forms which provide more syntactic sugar.</p>
<p>Let’s start with the basics and define what <code>strings</code> and <code>integers</code> will look like.</p>
<p>Note that:</p>
<ul>
<li>All token names must be lower case</li>
<li>Any key preceded by ‘!’ will be ignored</li>
<li>Any key preceded by ‘_’ will not by turned into a token</li>
<li>Any expression enclosed by ‘{‘ <code>expression</code> ‘}’ can be repeated 0 or more times</li>
</ul>
<p>In the below example we are ignoring all white space and have defined an <code>int</code> and <code>string_literal</code> <code>token</code>.</p>
<p>Every language has built in <code>keywords</code> that are reserved words that deliver special functionality. But, how will the lexer know whether a <code>string</code> is a <code>keyword</code> or a user created <code>identifier</code>? It handles this be giving preference to the order in which tokens are defined. Therefore, let’s define <code>keywords</code> next.</p>
<p>We’ll finish this up by adding the punctuation necessary for expressions.</p>
<p>Cool! Let’s see if this is actually doing what we want with some <strong>unit tests</strong>. Feel free to just paste this part into your IDE. ?</p>
<p><strong>Note:</strong> It’s generally good practice in Go to place test files in the relevant subdirectory, but for simplicity I’m placing all tests in the root.</p>
<p>To test our <strong>scanner</strong> run:</p>
<pre><code>$ gocc grammer.bnf$ go test -v=== RUN   TestToken--- PASS: TestToken (<span class="hljs-number">0.00</span>s)PASSok      github.com/Lebonesco/compiler       <span class="hljs-number">0.364</span>s
</code></pre><p>Great, we now have a working <code>**Lexer**</code> ?</p>
<h4 id="heading-building-the-parser">Building the Parser</h4>
<p>Building the <code>**Parser**</code> is similar to how we built the <code>**Lexer**</code>. We will construct a set of element sequences that when correctly match a stream of tokens produce a grammar. This will also run in linear time by internally converting our <strong>NFA</strong> (<em>Non-Deterministic Automaton</em>) grammar to <strong>DFA</strong> (<em>Deterministic Finite Automaton</em>).</p>
<p>Let’s keep things simple. What actually is our program? Well, it’s a bunch of <code>Statements</code> in which each <code>Statement</code> can contain a set of <code>Statements</code> and/or <code>Expressions</code>. This seems like a good place to start our grammar.</p>
<p>Below is the beginning recursive hierarchy of the program. <code>Statements</code> is a sequence of zero or more <code>Statements</code> and <code>Functions</code> is a list of functions. Our languages requires functions to be defined before other <code>Statement</code> types. This will reduce some headache during the type checking phase. <code>empty</code> is a keyword in <strong>BNF</strong> that represents an empty space.</p>
<p>But wait! What is a <code>Statement</code>? It’s a unit of code that doesn’t return a value. This includes: <code>if</code>, <code>let</code>, and <code>return</code> statements. This is opposed to <code>Expressions</code> which do return values. We will get to those next.</p>
<p>Below is our grammar for <code>Statement</code> and <code>Function</code>. A <code>StatementBlock</code> is a larger abstraction that encapsulates a list of <code>Statements</code> with braces <code>{</code> <code>}</code>.</p>
<p>Next lets build out our <code>Expression</code> which handles all infix operations such as <code>+</code>, <code>-</code>, <code>*</code>, <code>&amp;</code>lt<code>;</code>, <code>&amp;g</code>t;<code>, =</code>=, and<code>,</code> and or.</p>
<p>Almost done with a fully working grammar! Let’s wrap things up by defining our parameter insertion. Each <code>function</code> can accept any amount of values. When <strong>defining a function</strong> we need to label the argument types in the signature while a <strong>called function</strong> can accept any amount of <code>Expressions</code>.</p>
<p>Now that our parser is completed let’s add some code to our driver, <code>main.go</code>.</p>
<p>As we progress through the compiler we will add more functionality to this driver.</p>
<p>One of the things challenging about building a parser is that there’re many different ways to define the grammar. ?</p>
<p>We won’t really know how well we did until we get into the next section which uses the output we just generated. The difficulty of building the static type checker will be strongly influenced by our grammar design. Keep your fingers crossed ?.</p>
<h4 id="heading-test-parser">Test Parser</h4>
<p>We’ll keep this simple because at this point our parser can still produce false positives. Once we start working on the AST we can check its accuracy.</p>
<pre><code>go test -v=== RUN   TestParser--- PASS: TestParser (<span class="hljs-number">0.00</span>s)=== RUN   TestToken--- PASS: TestToken (<span class="hljs-number">0.00</span>s)PASSok      github.com/Lebonesco/go-compiler        <span class="hljs-number">7.295</span>s
</code></pre><p>Congrats ? ? ?! You now have a fully working Lexer and Parser. Time to move onto the AST <strong>(A</strong>bs<em>tract Syntax Tree).</em> </p>
<h3 id="heading-abstract-syntax-tree">Abstract Syntax Tree</h3>
<p>The best way to understand an abstract syntax tree is in relation to a parse tree which is what we generated in the last post. A parse tree represents each part of the program that is matched in our grammar.</p>
<blockquote>
<p>By contrast, an AST only contains the information related to type checking and code generation, and skips any other extra content that is used while parsing the text.</p>
</blockquote>
<p>Don’t worry if that definition doesn’t makes sense right now. I always learn best by actually coding, so let’s jump into it!</p>
<p>Create a new directory and two new files. <code>ast.go</code> will contain our AST generating functions and <code>types.go</code> will have the <em>tree node types</em>.</p>
<pre><code>mkdir astcd asttouch ast.gotouch types.go
</code></pre><p>Like with the parse tree, we will define our structure from top to bottom. Every <code>node</code> will either be a <code>Statement</code> or <code>Expression</code>. Go isn’t object oriented so we’ll use a composition pattern utilizing <code>interface</code> and <code>struct</code> to represent our <code>node</code> categories. Our AST will return a <code>Program</code> node that contains the rest of the program. From now on, any struct we created with a <code>TokenLiteral()</code> method is a <code>node</code>. If that <code>node</code> has a <code>statementNode()</code> method it will fit the <code>Statement</code> interface and if it has a <code>expressionNode()</code> method it’s an <code>Expression</code>.</p>
<p>In addition, we’ll be adding <code>json</code> tags to each struct field to make it easier when we convert our AST into <code>json</code> for testing purposes.</p>
<p>Now let’s start building our <code>Statement</code> structs based off of the <code>Statement</code> and <code>Node</code> interfaces.</p>
<p><strong><em>Note:</em></strong> <code>json:"-"</code> means that the field will be omitted from our json.</p>
<p>Next we need some hooks to connect our <code>nodes</code> and <code>parser</code>. The code below allows our <code>Statement</code> nodes to fit the <code>Node</code> and <code>Statement</code> interfaces.</p>
<p>We then need the hooks that will be called by the parser.</p>
<p>As you can see, <strong>most of our code</strong> is checking and casting our input type.</p>
<p>These hooks will then be called by the parser in <code>grammar.bnf</code>. To access these functions we’ll need to <code>import "github.com/Lebonesco/go-compiler/ast</code>.</p>
<p>Now when a piece of grammar is identified, it calls an AST hook and passes in the necessary data to construct a <code>node</code>.</p>
<p>As you could imagine, there is a lot of flexibility in how you want to generate your AST. There are <strong>design strategies</strong> that reduce the amount of unique nodes in the AST . However, having more node types will make your life easier when we get to the <code>typechecker</code> and <code>code generation</code>. ?</p>
<p>This part has a lot of code. However, it’s not very difficult and mostly all the same. The error handling in Go can feel a bit tedious, but in the long run it’ll be worth it when we make a silly mistake. Safety First ?</p>
<p>We’re not going to do anything too crazy with our error handling because I want to save on lines of code. However, if you feel so inclined you can add more descriptive and useful errors.</p>
<p>Let’s move on to <code>Expressions</code>!</p>
<p>Fit them into the <code>Node</code> and <code>Expression</code> interfaces.</p>
<p>And create the <code>Expression</code> hooks.</p>
<p>Finally, insert the hooks into the <code>parser</code>.</p>
<h4 id="heading-test-ast-generator">Test AST Generator</h4>
<p>The test cases for the AST generator are the most tedious to write. But trust me, this is not a part you want to mess up on. If you have problems here, those bugs will rollover into your <code>type checker</code> and <code>code generator</code>. ?</p>
<p>In my opinion, if code doesn’t have tests it’s broken</p>
<p>In our AST test we will construct what our final result should look like. To avoid comparing elements such as <code>tokens</code>, that could create false negatives, we convert our result and expected output into json before comparing with a <strong>deep comparison</strong> function, <code>reflect.DeepEqual()</code>.</p>
<p>Run Test:</p>
<pre><code>go test -v=== RUN   TestAST--- PASS: TestAST (<span class="hljs-number">0.00</span>s)=== RUN   TestParser--- PASS: TestParser (<span class="hljs-number">0.00</span>s)=== RUN   TestToken--- PASS: TestToken (<span class="hljs-number">0.00</span>s)PASSok      github.com/Lebonesco/go-compiler        <span class="hljs-number">9.020</span>s
</code></pre><p>Half way to a working compiler! ? While you give this post some ? ? ? don’t forget to give yourself a hand for making it this far.</p>
<p>Let’s add some more code to the driver.</p>
<p>Now onto my favorite part, the <strong>Type Checker</strong>.</p>
<h3 id="heading-type-checker">Type Checker</h3>
<p>Our type checker will make sure that users don’t write code that conflicts with our <strong>statically typed</strong> language.</p>
<p>The core backbone of our <strong>type checker</strong> will be a combination of data structures that track identifier types, initialization, and valid type operations. This can get vastly more complicated once we start dealing with different levels of scope and classes. However, we’re keeping it as simple as possible. ?</p>
<p>To start:</p>
<pre><code>touch checker_test.gomkdir checkercd checkertouch checker.gotouch environment.go
</code></pre><p><code>environment.go</code> will contain all of our helper functions that will be used by our <strong>checker</strong> and <strong>code generator</strong> to access and manipulate our set of variables and corresponding types. Our environment is simple so this will be straight forward.</p>
<p>We’ll begin by setting all of our constant values including <strong>operation types</strong>, <strong>variable types</strong>, and <strong>mapping of each type to its valid methods</strong>.</p>
<p><strong>Note:</strong> If we had classes in our language our checker would handle this third part rather than us doing it by hand.</p>
<p>The rest of <code>environment.go</code> are basic <strong>getters</strong> and <strong>setters</strong> that handle identifiers and functions.</p>
<p>The foundation of our type checker will be a single <strong>dispatch</strong> function, <code>checker()</code>, that takes in a <code>Node</code> and fires the corresponding checker function</p>
<p>I felt like saving lines of code so we’ll be using a global environment to store our variable types.</p>
<p><strong>Note:</strong> This wouldn’t be possible if we allowed <code>Block Statements</code> and <code>Functions</code> to have their own scope or if we were abiding by best practices.</p>
<p>Now eval <code>Statements</code>. <code>Block Statements</code> are the only statement in which we return a type in order to handle the case when it is inside a function. If there is a <code>Return Statement</code> inside the <code>Block Statement</code> its type is returned. Otherwise, the <code>Nothing_Type</code> is returned.</p>
<p>Onto evaluating <code>Expressions</code>. The most complicated part will be <code>evalFunctionCall()</code> because it could either be a built in function such as <code>PRINT()</code> or user defined.</p>
<p><strong>Note:</strong> Currently, there is only one <strong>builtin</strong> function. However, more could be easily added given the framework that we’ve built.</p>
<p>Awesome! Let’s add a small snippet to our driver.</p>
<h4 id="heading-test-type-checker">Test Type Checker</h4>
<pre><code>go test -v=== RUN   TestAST--- PASS: TestAST (<span class="hljs-number">0.00</span>s)=== RUN   TestOperations--- PASS: TestOperations (<span class="hljs-number">0.00</span>s)=== RUN   TestIdents--- PASS: TestIdents (<span class="hljs-number">0.00</span>s)=== RUN   TestFunctions--- PASS: TestFunctions (<span class="hljs-number">0.00</span>s)=== RUN   TestParser--- PASS: TestParser (<span class="hljs-number">0.00</span>s)=== RUN   TestToken--- PASS: TestToken (<span class="hljs-number">0.00</span>s)PASSok      github.com/Lebonesco/go-compiler        <span class="hljs-number">9.020</span>s
</code></pre><p>I made some deliberate choices to leave things out of this language such as <code>classes</code>, <code>for loops</code>, and function <code>scope</code>. Most of the complexities that arise from these occur in the <code>checker</code> and <code>code generator</code>. If I added those elements this post would be a lot lot longer. ?</p>
<h3 id="heading-code-generation">Code Generation</h3>
<p>We have finally made it to the last stage! ? ? ?</p>
<p>In order to handle the most cases with the least amount of hassle every <code>expression</code> will be assigned to a temporary variable. It might make our generated code look bloated, but it will solve for any nested expressions.</p>
<p>Bloated code won’t have any impact on final program speed because the optimizer will remove any redundancy when we compile our final generated C++ code.</p>
<p>Our generator will look similar to the type checker. The main difference is that we’ll be passing down a <code>buffer</code> to store the generated code.</p>
<p>While I chose to compile into C++, you can substitute in any language . The main purpose of this <strong>Go Compiler Guide</strong> was to enable you to be able to understand the pieces well enough to go out and create your own.</p>
<p>To start:</p>
<pre><code>touch gen_test.gomkdir gencd gentouch gen.go
</code></pre><p>We’ll begin by importing all of the necessary packages and defining three <strong>utility functions,</strong> <code>write()</code> to write generated code to a buffer, <code>check()</code>to do error handling, and <code>freshTemp()</code>to generate <strong>unique</strong> variable names for temporary variables we create on the fly.</p>
<p><strong>Note:</strong> It’s generally bad practice to use <code>panic()</code>for normal error handling in Go, but I’m tired of writing <code>if statements</code>.</p>
<p>Similar to the <strong>checker</strong>, our <strong>generator</strong> has a core dispatch function that accepts a <code>Node</code> and calls the corresponding <strong>gen</strong> function.</p>
<p>Let’s generate some <code>Statements</code>. <code>genProgram()</code> generates necessary headers and <code>main()</code> function.</p>
<p>Generating <code>Expressions</code> will look very similar to the code above. The main difference is that a <code>temp</code> variable is returned representing that expression. This helps us handle more complex <code>Expression</code> nesting.</p>
<p>The final piece of code will be our C++ <strong>Builtin types.</strong> Without this nothing will work.</p>
<h4 id="heading-test-code-generator">Test Code Generator</h4>
<h3 id="heading-bringing-it-all-together">Bringing It All Together</h3>
<p>We’re now going to combine our <strong>lexer</strong>, <strong>parser</strong>, <strong>AST generator</strong>, <strong>type checker</strong>, and <strong>code generator</strong> into a final runnable program, <code>main.go</code>.</p>
<p><strong>Note:</strong> I’m running this on a Windows so my C++ compiles into <code>main.exe</code>. If this doesn’t work for you remove the <code>.exe</code> extension.</p>
<p>To find some test programs to run go to <code>github.com/Lebonesco/go-compiler/examples</code>.</p>
<pre><code>go run main.go ./example/<span class="hljs-keyword">function</span>.bxhello Jeff3
</code></pre><p>And there you have it! We have completed a fully working compiler in Go!</p>
<p>Thank you for taking the time to read this article.</p>
<p>If you found it helpful or interesting please let me know ???.</p>
 ]]>
                </content:encoded>
            </item>
        
    </channel>
</rss>
