<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Cycling &#39;74 Engineering on Medium]]></title>
        <description><![CDATA[Stories by Cycling &#39;74 Engineering on Medium]]></description>
        <link>https://medium.com/@c74eng?source=rss-3a4a0feb6ea8------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*MdOMg53fCNScpt9KpSYE-g.png</url>
            <title>Stories by Cycling &amp;#39;74 Engineering on Medium</title>
            <link>https://medium.com/@c74eng?source=rss-3a4a0feb6ea8------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 20 Nov 2026 19:19:50 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@c74eng/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Generating JavaScript from SVG, an Intro to Code Generation — Part 3]]></title>
            <link>https://c74eng.medium.com/generating-javascript-from-svg-an-intro-to-code-generation-part-3-383f9273308b?source=rss-3a4a0feb6ea8------2</link>
            <guid isPermaLink="false">https://medium.com/p/383f9273308b</guid>
            <category><![CDATA[code-generation]]></category>
            <category><![CDATA[svg]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Cycling '74 Engineering]]></dc:creator>
            <pubDate>Fri, 09 Jul 2021 14:33:03 GMT</pubDate>
            <atom:updated>2021-07-09T14:33:03.901Z</atom:updated>
            <content:encoded><![CDATA[<h3>Generating JavaScript from SVG, an Intro to Code Generation — Part 3</h3><p>Welcome back again to our introduction to code generation. Generating code from some non-code description is a big topic, so we’re focusing our attention for now on the specific problem of generating JavaScript code from an SVG drawing. In <a href="https://c74eng.substack.com/p/generating-javascript-from-svg-an">the last part</a>, we managed to generate code that could not only draw rectangles, but also render them at different sizes and aspect ratios.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/511/1*FXFJ9kXjOAkcFqjXVzOojA.gif" /><figcaption>Just look at those black rectangles go</figcaption></figure><p>In this last part of the series, we’re going to make our code generator smart enough to handle colors. We’re working from the repository at <a href="https://github.com/Cycling74/codegen-eng-blog">https://github.com/Cycling74/codegen-eng-blog</a>. If you want to pick up where we left off last time, you can checkout the step-3 tag, with something like this:</p><pre>git checkout tags/step-3</pre><p>For the grand finale, how would we make the rectangles have color? For this, we’re going to have to go back to the SVG file. If we make a drawing in Illustrator with colored rectangles, it looks like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/354/1*zaquIUWvL9TH6_U-NGUF4g.png" /></figure><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1297534be83a0c23e1ab99bb185be820/href">https://medium.com/media/1297534be83a0c23e1ab99bb185be820/href</a></iframe><p>Now we’ve got a really tricky situation on our hands. We’ve got an SVG file with inline CSS! However, in the same exact way that we parse SVG as XML, we can do just the same thing with CSS. The idea is, parse and walk through the CSS text. Every time you encounter a CSS class selector that has a fill property, create a function that will color our rectangle correctly. In our generated code we&#39;ll have something like this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/865fc001bbdfa7a6f5d882ff29d5d043/href">https://medium.com/media/865fc001bbdfa7a6f5d882ff29d5d043/href</a></iframe><p>So the challenge is twofold:</p><ol><li>Create a styling function for each CSS class.</li><li>Call that function before drawing each rectangle.</li></ol><h3>Parsing CSS</h3><p>First, let’s install our CSS parsing library.</p><p>npm i --save css-tree @types/css-tree</p><p>Now let’s think about how to get to the CSS text. If you look at the SVG file, you can see that the actual CSS is just the text of a tag called style. Still, this is a bit tough for us. While htmlparser2 does let us define a function ontext for when we encounter the text of an XML tag, it doesn&#39;t give us an easy way of knowing whether that text belongs to a style tag or not. The best solution I can come up with is something like this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/48310972287aa9e1929281db20375f93/href">https://medium.com/media/48310972287aa9e1929281db20375f93/href</a></iframe><p>Now in order to know how to handle each CSS class selector, it’s helpful to put the CSS into <a href="https://astexplorer.net/">AST Explorer</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xCxDdwY7trcSbsYbSMXIGg.png" /></figure><p>Let’s try saying this in English, then we’ll worry about code. Given a CSS Rule, look in its SelectorList for a ClassSelector. The name of that ClassSelector will be the name of our styling function. Within that same Rule, look for a Block with a series of Declaration. Get declarations with the property “fill” and extract their value as a HexColor.</p><p>Here’s what that looks like in code:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/32290d6e3878d3fb80ce4c75f25b059c/href">https://medium.com/media/32290d6e3878d3fb80ce4c75f25b059c/href</a></iframe><p>This relies on two helper functions createLegalName and hexColorToColorArray. The first, createLegalName, simply turns a CSS class selector into a legal name for a JavaScript variable. The second, hexColorToColorArray goes from a hex string like #fff or #ff00ff to [1.0, 1.0, 1.0, 1.0] and [1.0, 0.0, 1.0, 1.0] respectively (note that an alpha value has been appended automatically. The babel template that actually makes the style functions, makeStyleFunction, looks like this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e1a4c7cc7f443e51ed02306dfe7dbbcb/href">https://medium.com/media/e1a4c7cc7f443e51ed02306dfe7dbbcb/href</a></iframe><h3>Adding Styling to the Rectangles</h3><p>Now we need to modify our rectangle drawing code to be style aware. That’s as simple as adding a call to the styling function to the rectangle template, though we still want to be able to draw a rectangle without a style.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ee44d7b1764ade1a0953c6885294bc88/href">https://medium.com/media/ee44d7b1764ade1a0953c6885294bc88/href</a></iframe><p>Now we need to modify our rectangle drawing code to be style aware. That’s as simple as adding a call to the styling function to the rectangle template, though we still want to be able to draw a rectangle without a style.</p><p>And then we just need to pass the styleFunctionName when we create the rect drawing statements.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2a7badd82f44760f015076f8f3577034/href">https://medium.com/media/2a7badd82f44760f015076f8f3577034/href</a></iframe><h3>Adding the Style Functions</h3><p>The very last thing we need to do is add the style function definitions before the paint function. So, let’s add to the makePaintFunction template.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/722ac3ccfcd9eac6c597b5b1c59f8b5f/href">https://medium.com/media/722ac3ccfcd9eac6c597b5b1c59f8b5f/href</a></iframe><p>Nearly there now, just need to call the template function with the right argument.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c60cb1e5c045d9c22cea4a4203bb5908/href">https://medium.com/media/c60cb1e5c045d9c22cea4a4203bb5908/href</a></iframe><h3>Celebration</h3><p>Just look at that beautiful JavaScript output.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/25708b85859f179794d82133e78892b7/href">https://medium.com/media/25708b85859f179794d82133e78892b7/href</a></iframe><p>Imagine what that would have been like to program by hand? And now any kind of SVG drawing you make (provided it’s colored rectangles and colored rectangles only) can be turned into JavaScript instantly.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qr6c2Y0ejhHLsTSgQq4gkA.gif" /></figure><h3>Next Up</h3><p>If we were continuing this series, we might think about how to add behavior to our generated drawing. One of the really appealing parts of generating code is that it lets you define behaviors without having to code that behavior explicitly. So we might ask how we could define an interface object, like a slider or a knob, using just an SVG image.</p><p>Believe it or not we aren’t the first people to think about this kind of thing. If you’re familiar with Max you might also know about VCV Rack, a program for simulating Eurorack modules. VCV supports custom, user-defined modules, complete with a code generation script that will turn an <a href="https://vcvrack.com/manual/Panel">SVG drawing into an active interface</a>. This scheme uses different colors to denote different functionality, with green for inputs and blue for outputs. If you wanted to go deep into SVG-based code generation, you might follow a similar strategy for denoting different behaviors.</p><p>For now, this is the end of our code generation journey. I hope it’s been useful for you-certainly I learned a ton about working with different text parsers, and about using Babel to generate code from an AST. Until next time!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=383f9273308b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Generating JavaScript from SVG, an Intro to Code Generation — Part 2]]></title>
            <link>https://c74eng.medium.com/generating-javascript-from-svg-an-intro-to-code-generation-part-2-68939d6e656a?source=rss-3a4a0feb6ea8------2</link>
            <guid isPermaLink="false">https://medium.com/p/68939d6e656a</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[maxmsp]]></category>
            <dc:creator><![CDATA[Cycling '74 Engineering]]></dc:creator>
            <pubDate>Thu, 06 May 2021 17:06:04 GMT</pubDate>
            <atom:updated>2021-05-06T17:06:04.277Z</atom:updated>
            <content:encoded><![CDATA[<h3>Generating JavaScript from SVG, an Intro to Code Generation — Part 2</h3><p>Hi and welcome back to an introduction to code generation. If you haven’t read the <a href="https://c74eng.medium.com/generating-javascript-from-svg-an-intro-to-code-generation-part-1-bec4b1a595fe">first part of this series</a>, we’re trying to generate JavaScript code that will recreate an SVG drawing. In the last part, we managed to write a parser/generator that could understand any drawing, so long as it was made up entirely of black rectangles.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/178/0*oK4gMugFk2e97CCF.png" /><figcaption>This, I think you’ll agree, is art</figcaption></figure><p>In this part of the series, we’ll add generated code to scale and stretch our image as we resize our Max object. We’re working from the repository at <a href="https://github.com/Cycling74/codegen-eng-blog">https://github.com/Cycling74/codegen-eng-blog</a>. If you want to pick up where we left off last time, you can checkout the step-2 tag, with something like this:</p><pre>git checkout tags/step-2</pre><h3>Scaling and Stretching</h3><p>Let’s get started. Right now, if we start to resize our object in Max, our rectangles will just sit there.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/511/0*4DwnQySU9yXTcDeQ.gif" /></figure><p>Checking the jspainter documentation, there is a way to tell Max to automatically stretch the drawing. mgraphics.relative_coords = 1; at the beginning of our source file will turn on relative coordinate mode, putting (0, 0) in the center of the canvas and (-1, -1) in the top right (I agree, this is an idiosyncratic coordinate system). So now we’ve got to figure out how to convert the coordinates of the rectangles in our SVG file to jspainter’s relative coordinate system. Luckily, looking back at our SVG file, we see that it includes an explicit viewBox=&quot;0 0 177.3 307&quot;. So all we have to do is extract this while we walk through the SVG file with htmlparser2 and use it to scale our rectangles. There’s one other change: adding mgraphics.relative_coords = 1 to makePaintFunction.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0920f6c0d295bf2a98757a06de67c063/href">https://medium.com/media/0920f6c0d295bf2a98757a06de67c063/href</a></iframe><p>As you can see, the way we scale each rectangle is a little different than how you might expect, since we’re stretching to a coordinate system that goes from (-1, -1) in the top-left to (1, 1) in the bottom right. Or… did we do that scaling right?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*GvNfHwBqemcKxDqu.png" /><figcaption>That’s not how it’s supposed to look</figcaption></figure><p>That doesn’t look quite right. Ah, right, that’s because I made a mistake: the coordinate system for jspainter actually begins in the <em>bottom</em> left, so (-1, -1) is in the bottom-left and (1, 1) is in the top right. We have to change our scaling code accordingly:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/73f3b9fd15b906d71d21d3774cc0d170/href">https://medium.com/media/73f3b9fd15b906d71d21d3774cc0d170/href</a></iframe><p>The only bit that’s changed is the y coordinate. With that, we’ve can now resize and see our drawing resize as well.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/511/0*Ihv5o0flh9to4wI8.gif" /></figure><h3>Aspect Ratios</h3><p>This is fine so long as we’re happy with a fixed aspect ratio for our drawing. If we want the drawing to scale with the bounds of the object, then we need to incorporate an aspect ratio scaling into our code. The key is that we need to put this logic into the exported code itself. What’s kind of cool about this is that now we’re defining behavior that isn’t present in the original SVG file. First, we add a function to calculate aspect ratio to our generated paint code.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a57018a53928677b18330422ad56a47e/href">https://medium.com/media/a57018a53928677b18330422ad56a47e/href</a></iframe><p>As you can see, this adds a local aspect variable to our paint function. Now, since our rectangle drawing functions are just lists of statements in the paint function, we can make use of this local variable in our rectangle drawing code. We don’t have to pass the aspect variable to the rectangle function or anything like that, we can just use the local aspect variable directly.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f09a2fece964cb0c8ae13d32aa957c2f/href">https://medium.com/media/f09a2fece964cb0c8ae13d32aa957c2f/href</a></iframe><p>Surprisingly that’s all we need to do to get a drawing that will stretch to whatever aspect ratio we want in Max.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/511/0*9eF_lPcQ2f_3lioj.gif" /></figure><h3>Home Stretch</h3><p>If you want to jump ahead and see all the code we wrote in this section, checkout the step-3 tag:</p><pre>git checkout tags/step-3</pre><p>In the last part of the series, we’ll break with our monochromatic streak and see how to add some color to our drawing. Look out for some CSS-parsing action in the exciting conclusion to our code generation intro series!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=68939d6e656a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Generating JavaScript from SVG, an Intro to Code Generation — Part 1]]></title>
            <link>https://c74eng.medium.com/generating-javascript-from-svg-an-intro-to-code-generation-part-1-bec4b1a595fe?source=rss-3a4a0feb6ea8------2</link>
            <guid isPermaLink="false">https://medium.com/p/bec4b1a595fe</guid>
            <dc:creator><![CDATA[Cycling '74 Engineering]]></dc:creator>
            <pubDate>Mon, 01 Mar 2021 16:31:30 GMT</pubDate>
            <atom:updated>2021-03-01T16:31:30.339Z</atom:updated>
            <content:encoded><![CDATA[<h3>Generating JavaScript from SVG, an Intro to Code Generation — Part 1</h3><p>This post is all about code generation. When we’re done, we’ll have a working command line tool that will automatically generate JavaScript code from an SVG file. In later parts, we’ll add complexity and sophistication to that tool.</p><h3>Custom Drawing in Max</h3><p>In <a href="https://cycling74.com/products/max">Max</a> (our visual programming language for multimedia manipulation), you build programs by connecting together objects with things called patch cords. A patch that adds two numbers together could look like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5kwJa6T0dVNwLCYB0wNEUg.png" /></figure><p>Under the hood, so to speak, this “+” object is just a bit of C code that calls an “add” function. Most Max objects have pre-defined behavior. If you want to write a new object, you have to write that object in C or C++.</p><p>UI objects are an interesting exception to this though. You can change the appearance of objects like sliders, dials, buttons and number boxes by attaching a JavaScript file to the jspainter property of that object. When you specify such a file, rather than using its built-in C drawing implementation, the object will use your custom JavaScript implementation to render itself instead.</p><p>So if for some reason you wanted a toggle object to always appear brown, you just create a paint function and bind that to your toggle. On the left, you’ve got a regular toggle. In the middle, the code for turning a toggle brown. On the right, you’ve got yourself a brown toggle.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PbLu6KxIHMYGreKUlOv88Q.png" /></figure><h3>The challenge</h3><p>In principle this is amazing, it means that you can change the look of any Max UI object in any way you like. On the other hand, you have to do all your drawing using our mgraphics object. If you want to tweak your custom UI, perhaps changing a color or resizing an object, you have to do it in JavaScript. If you design your custom UI object in a drawing program, you have to translate your design to JavaScript by hand. Wouldn’t it be nice if you could design your custom UI in another application, say Adobe Illustrator, and then export your SVG file to a jspainter compatible file automatically? In other words, can we generate JavaScript from an SVG file?</p><p>Generating code this way might seem daunting, but it’s much less difficult than it might first appear. Not only that, but there are great resources for getting started. There is for example this blog post <a href="https://lihautan.com/manipulating-ast-with-javascript/">https://lihautan.com/manipulating-ast-with-javascript/</a>, describing at a high level how code generation works, as well as AST Explorer <a href="https://astexplorer.net/">https://astexplorer.net/</a> for viewing and understanding syntax trees. What we’re going to do now is to see how to put these ideas into practice, with our own, custom code generation tool.</p><h3>Getting set up</h3><p>First, checkout the <a href="https://github.com/Cycling74/codegen-eng-blog">repository containing the source code</a>.</p><p>This repository breaks this post down into steps. It starts at step 0, which you can check out by running git checkout tags/step-0. If you want to follow along with this tutorial, you can check this tag out to a new branch, with a command like git checkout tags/step-0 my-branch. Then if you get stuck, you can always go back to the master branch to move to the next step.</p><p>If you’re on step 0, you see that this just has a bunch of boilerplate in place. We’re using TypeScript, so rather than running node index.js to execute our script, we use ts-node to run index.ts. We’re also using <a href="https://www.npmjs.com/package/commander">commander</a> to parse command line arguments. So to parse an input file in input/01-input.svg and write it to a file out.js, simply run</p><pre>npm run start -- -i input/01-input.svg -o out.js</pre><h3>Parsing SVG (as if it were HTML)</h3><p>The first step in doing any code generation is to go from text to an Abstract Syntax Tree. For an overview of just what an AST is, I highly recommend <a href="https://lihautan.com/manipulating-ast-with-javascript/">https://lihautan.com/manipulating-ast-with-javascript/</a>. Once we have that tree, we can walk through the tree to continue our code generation algorithm.</p><p>For us, the first step is to get an AST for our SVG document. We’ll be using a library called htmlparser2, which actually treats the SVG document as XML. As we walk through that tree, we’ll print out lines of JavaScript based on what we encounter in the SVG document.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/178/1*w1FXLw4-p1FbYHoEvrlkEw.png" /></figure><p>To start, let’s keep things simple and focus on just one kind of drawing: drawings containing black rectangles only. Yes, there are many beautiful things in this world that are not black rectangles, but we’ll worry about those things in a later post. Here’s the SVG file that generated this image:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d88b783c2a7346134c125aa0a91df723/href">https://medium.com/media/d88b783c2a7346134c125aa0a91df723/href</a></iframe><p>As you can see, it’s pretty much what you’d expect. Within the <strong><em>svg</em></strong> tag, there are three <strong><em>rect</em></strong> tags that define the position of the three rectangles. It’s kind of interesting that there’s no mention of color — since black is the default, the SVG file is free to omit that information. The first rectangle also has no attribute for <strong><em>x</em></strong> and the last rectangle has no attribute for <strong><em>y</em></strong>. This is for a similar reason: zero is the default values, so for a shape at the left or top of the viewBox, the default value of zero is correct.</p><p>Before we go about translating this into JavaScript that will draw this in Max, it’s worth thinking about what the code generator should be doing. In plain English, it should more or less find every <strong><em>rect</em></strong> tag in the SVG, and for each such tag it should call <strong><em>mgraphics.rectangle</em></strong> with the correct origin and size. Unsurprisingly, that’s exactly what our code does. We’ll start by using a library called htmlparser2 to parse the SVG.</p><pre>npm i --save htmlparser2</pre><p>The htmlparser2 tool can handle HTML and XML, so it’s perfectly suited for walking through an SVG file. To use the htmlparser2 library, we first define a parser. That parser should have properties <strong><em>onopentag</em></strong> and <strong><em>onclosetag</em></strong> that define what to do when the parser encounters each such tag. For example:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/43c9b7e2d43cb8e08949e610e839f71d/href">https://medium.com/media/43c9b7e2d43cb8e08949e610e839f71d/href</a></iframe><p>This will print “entering an svg tag” when it reaches the first line of our SVG file, and will print “exiting an svg tag” when it reaches the last line of our SVG file. With just this and nothing else, it’s already possible to imagine building a simplistic code generator that just prints out templated text whenever it encounters a “rect” tag. It might look something like this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/10c6bb846d5838469c7f5d9fb84a0649/href">https://medium.com/media/10c6bb846d5838469c7f5d9fb84a0649/href</a></iframe><p>Already this is good enough for JavaScript output:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8e545dfbaf1f892c2b250efdb777528e/href">https://medium.com/media/8e545dfbaf1f892c2b250efdb777528e/href</a></iframe><p>And this works! If we create a UI object in Max and set its jspainterfile to our output, then we can see the rectangles as expected.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PDZIefkU-EdzOZ5pdGeLzw.png" /></figure><h3>Building an AST</h3><p>Okay, let’s take a look at this line:</p><pre>outputString += `\tmgraphics.rectangle(${x}, ${y}, ${w}, ${h});\n\tmgraphics.fill();\n`;</pre><p>As far as formatting and writing the output is concerned, this is by far the most important line. However, it’s far from perfect. First of all, it’s hard to read. Quick: did we remember to include a semicolon at the end of the first line? Also even this simplistic version, which can only draw a black rectangle, is already getting a little complex. What if we want to draw a rectangle with a gradient, or a dotted border? What if we want to draw one with a 2D transform applied? Clearly, this line can quickly get very unreadable and very unwieldy.</p><p>The way out is to take a big step back and to refuse to handle the code printing at all. Instead of worrying about semicolons and indentation, let’s leave all that to a library. That lets us focus on syntax — what function is being called with what argument. For this we’re going to use babel, specifically <strong><em>@babel/generate</em></strong>, <strong><em>@babel/types</em></strong> and <strong><em>@babel/template</em></strong>. We can get all of these by installing <strong><em>@babel/core</em></strong></p><pre>npm i --save <a href="http://twitter.com/babel/core">@babel/core</a> <a href="http://twitter.com/types/babel__core">@types/babel__core</a></pre><p>Here’s the main idea: rather than building up a function definition by gluing together a long string of semicolon-separated lines, we’re going to build a function definition by creating an array of statements. Using <a href="https://astexplorer.net/">AST Explorer</a>, you can get a general sense of what’s going on. If you ask AST Explorer to parse a function like this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7cf5136897b5d779fe2438e531a582c4/href">https://medium.com/media/7cf5136897b5d779fe2438e531a582c4/href</a></iframe><p>You’ll see something like this in the tree view:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PaVw9vVPlY7tA4J1VgLv9Q.png" /></figure><p>The important bit is the “body” of the BlockStatement, which as you can see is just an array of statements. Armed with this knowledge, we can start to build a statement array to implement our function. The pseudocode is something like this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/99d9e2f5ac4a69943a3d3a4c7d0d7bb3/href">https://medium.com/media/99d9e2f5ac4a69943a3d3a4c7d0d7bb3/href</a></iframe><h3>Better Living with Babel Templates</h3><p>So you want to build a statement. Well, <strong><em>@babel.types</em></strong> exports an object that contains constructors for the various syntactic nodes of an Abstract Syntax Tree. You can for example write:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/080ad1296333dc039ebba0feb1320be3/href">https://medium.com/media/080ad1296333dc039ebba0feb1320be3/href</a></iframe><p>As you can see, building an AST like this can be verbose and hard to read. The thing is, we already have a great, human-readable representation for programming languages: the code itself. This is why it’s so nice to use Babel templates to generate reusable AST-fragments. Instead of the above, we could write something like:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4e6351d9f46bda8441fea22f71b66d85/href">https://medium.com/media/4e6351d9f46bda8441fea22f71b66d85/href</a></iframe><p>This creates a function <strong><em>makeAddFive</em></strong> that will return part of an AST, as generated using the code fragment template we provided. So now we’re ready to make some serious progress on our code generator.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/48de8d0ab10b2d67abc51e0689c3a4e6/href">https://medium.com/media/48de8d0ab10b2d67abc51e0689c3a4e6/href</a></iframe><p>I’ve left out the last bit, where we actually print a string, but you can see the magic happening on line 33, where we build a branch of our AST that will draw a single rectangle. Then on lines 41–42, we create our full paint function and generate the root AST that implements our full program. There’s a tiny annoyance on 41, where we concat the result of <strong><em>makePaintFunction</em></strong> to an empty array. This simply guarantees that we pass an array of statements to <strong><em>t.Program</em></strong>. Actually generating the AST is very easy: we just use <strong><em>@babel/generate</em></strong>.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/88a4f3d5bbc7d80ba76b116ba7959ad0/href">https://medium.com/media/88a4f3d5bbc7d80ba76b116ba7959ad0/href</a></iframe><p>Putting it all together gives us something like this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/24e3c854e347271a30664ed53808ca83/href">https://medium.com/media/24e3c854e347271a30664ed53808ca83/href</a></iframe><p>Okay! Let’s run it and see the output! Oh… what happened?</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/570b4993c397f5328ad52aa1ffdd45af/href">https://medium.com/media/570b4993c397f5328ad52aa1ffdd45af/href</a></iframe><p>That’s a bit cryptic. So I’ve been a bit sloppy, it turns out that the values you pass to out AST-generating functions <strong><em>makeRectDrawStatements</em></strong> and <strong><em>makePaintFunction</em></strong> have to be AST nodes. They can’t just be regular JavaScript values. So you have to write something like this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9c4e3724d1ba98d966107f30094329d6/href">https://medium.com/media/9c4e3724d1ba98d966107f30094329d6/href</a></iframe><p>This uses the function <strong><em>numericLiteral</em></strong> to build an AST node of type <strong><em>NumericLiteral</em></strong> from whatever number you provide. With this tweak, now we can run our code and everything works as expected. This looks the same as it did before (which is good!) only now we’re using Babel to build and AST and using generate to print that to JavaScript automatically.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PDZIefkU-EdzOZ5pdGeLzw.png" /></figure><h3>Next up</h3><p>So far we’ve drawn black rectangles. Surely we can do more? In the next part we’ll look at black rectangles that stretch, and we’ll dream of a world where rectangles can have any color they want.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bec4b1a595fe" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>