<?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 Brandon Yanofsky on Medium]]></title>
        <description><![CDATA[Stories by Brandon Yanofsky on Medium]]></description>
        <link>https://medium.com/@byanofsky?source=rss-857b06cc363------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*uhvQzEywiNSbxHrU.JPG</url>
            <title>Stories by Brandon Yanofsky on Medium</title>
            <link>https://medium.com/@byanofsky?source=rss-857b06cc363------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 24 Nov 2026 11:47:36 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@byanofsky/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[ChatGPT Helped Me Build a Compiler]]></title>
            <link>https://medium.com/@byanofsky/chatgpt-helped-me-build-a-compiler-7aebcd2a2c20?source=rss-857b06cc363------2</link>
            <guid isPermaLink="false">https://medium.com/p/7aebcd2a2c20</guid>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[compilers]]></category>
            <category><![CDATA[learning-to-code]]></category>
            <category><![CDATA[chatgpt]]></category>
            <dc:creator><![CDATA[Brandon Yanofsky]]></dc:creator>
            <pubDate>Mon, 24 Apr 2023 00:18:32 GMT</pubDate>
            <atom:updated>2023-04-24T16:03:41.855Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*jQB0C2E5K0HBdGJ4" /><figcaption>Photo by <a href="https://unsplash.com/es/@alex0631?utm_source=medium&amp;utm_medium=referral">Alex</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Two things have been on my mind lately:</p><ol><li>How compilers work</li><li>How to use ChatGPT for programming projects</li></ol><p>I decided to tackle two bird with one stone: leverage ChatGPT to help me build a compiler.</p><p>I’d built a basic compiler a few years ago for the <a href="https://www.nand2tetris.org/">Nand2Tetris course</a>. But I was rusty on the concepts. What better way to review than trying to build a compiler again. Plus, I could lead on ChatGPT to guide me and (hopefully) help when I get stuck.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2Fl41YsxKKVYnucStag%2Ftwitter%2Fiframe&amp;display_name=Giphy&amp;url=https%3A%2F%2Fmedia.giphy.com%2Fmedia%2Fl41YsxKKVYnucStag%2Fgiphy.gif&amp;image=https%3A%2F%2Fi.giphy.com%2Fmedia%2Fl41YsxKKVYnucStag%2Fgiphy.gif&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=giphy" width="435" height="326" frameborder="0" scrolling="no"><a href="https://medium.com/media/0629267c6be89c9641e5ed0b60f5a88e/href">https://medium.com/media/0629267c6be89c9641e5ed0b60f5a88e/href</a></iframe><p>This article is my attempt to <a href="https://gist.github.com/sw-yx/9720bd4a30606ca3ffb8d407113c0fe5#1-learn-in-public">learn in public</a>. Hopefully this will inspire you to do the same.</p><p>Structure of this article: I’ll first describe the learning goals I established before starting this project. Then I’ll walk through the steps to builder the compiler. I’ve highlighted my interactions with ChatGPT. Finally, I reflect on the experience and talk about what I’d do next.</p><p>If you’d like to skip to the final result, see the GitHub repo: <a href="https://github.com/byanofsky/simple-compiler">https://github.com/byanofsky/simple-compiler</a></p><h3>Learning Goals</h3><p>My primary goal was to learn how compilers work by building a compiler.</p><p>Some secondary goals:</p><ul><li>Understand how ChatGPT can be utilized as a coding partner</li><li>Gain some additional experience with C programming language</li><li>Utilize some compiler related tool I hadn’t used before</li></ul><p>Next, I’ll walk you through highlights of the process.</p><h3>Getting Started</h3><p>I decided it’d be best to build a compiler for a simple programming language. This way, I could concentrate on building the end-to-end compiler instead of getting stuck building out features.</p><p>The simplest language I could think of would consist of the following:</p><ul><li>integer data type only</li><li>values can be stored in variables</li><li>addition and subtraction are the only arithmetic operators</li></ul><figure><a href="https://xkcd.com/2309/"><img alt="" src="https://cdn-images-1.medium.com/max/740/1*6exPl8ebvHzVdTuiSZPyow.png" /></a><figcaption><a href="https://xkcd.com/2309"><strong>https://xkcd.com/2309/</strong></a></figcaption></figure><p>Thus, I started with my first prompt to ChatGPT:</p><blockquote>Help me build a compiler for a simple programming language. To start off, the language will only have integers as the data type. The only operations are addition and subtraction.</blockquote><p>ChatGPT responded with 6 steps required to build a compiler. I’ve summarized the response:</p><ol><li><strong>Define a syntax.</strong> Example &lt;variable_name&gt; = &lt;expression&gt; ;</li><li><strong>Write a lexer. </strong>The lexer breaks the source code into tokens. Tokens would include integers, variables, addition/subtraction operators.</li><li><strong>Write a parser.</strong> The parser reads tokens produced by the lexer and builds a syntax tree. Each node in the tree represents a construct in the language, such as an assignment statement or expression.</li><li><strong>Write a code generator.</strong> The code generator traverses the syntax tree and generates code in some target language.</li><li><strong>Write a driver program. </strong>The driver program reads the source code, runs the lexer and parser, generates the target code, and then executes the target code.</li><li><strong>Test your compiler.</strong> Ensure that the compiler generates the correct output for different inputs.</li></ol><p>The next few sections address each step.</p><h3>Step 1: Define a syntax</h3><p>I asked ChatGPT to help me define the syntax for my language. ChatGPT produced the following grammar (which I believe is <a href="https://en.wikipedia.org/wiki/Backus%E2%80%93Naur_form">BNF notation</a>):</p><pre>&lt;program&gt; ::= &lt;statement_list&gt;<br>&lt;statement_list&gt; ::= &lt;statement&gt; | &lt;statement&gt; &lt;statement_list&gt;<br>&lt;statement&gt; ::= &lt;variable&gt; &#39;=&#39; &lt;expression&gt; &#39;;&#39;<br>&lt;expression&gt; ::= &lt;term&gt; | &lt;term&gt; &lt;add_op&gt; &lt;expression&gt;<br>&lt;term&gt; ::= &lt;integer&gt; | &lt;variable&gt; | &#39;(&#39; &lt;expression&gt; &#39;)&#39;<br>&lt;add_op&gt; ::= &#39;+&#39; | &#39;-&#39;<br>&lt;integer&gt; ::= &lt;digit&gt; | &lt;integer&gt; &lt;digit&gt;<br>&lt;variable&gt; ::= &lt;letter&gt; | &lt;variable&gt; &lt;letter&gt; | &lt;variable&gt; &lt;digit&gt;<br>&lt;digit&gt; ::= &#39;0&#39; | &#39;1&#39; | &#39;2&#39; | &#39;3&#39; | &#39;4&#39; | &#39;5&#39; | &#39;6&#39; | &#39;7&#39; | &#39;8&#39; | &#39;9&#39;<br>&lt;letter&gt; ::= &#39;a&#39; | &#39;b&#39; | ... | &#39;z&#39; | &#39;A&#39; | &#39;B&#39; | ... | &#39;Z&#39;</pre><p>I reviewed and it seemed to align with my expectations. However, I realized such a language wouldn’t be useful without any mechansim for printing values. I asked ChatGPT to update the grammar:</p><blockquote>I’d like to be able to print results of add operations. Can we add a print operation?</blockquote><p>ChatGPT modified the &lt;statement&gt; entry as such:</p><pre>&lt;statement&gt; ::= &lt;variable&gt; &#39;=&#39; &lt;expression&gt; &#39;;&#39; | &#39;print&#39; &#39;(&#39; &lt;expression&gt; &#39;)&#39; &#39;;&#39;</pre><p>This looked good and I was ready for the next step.</p><h3>Step 3: Write a lexer</h3><p>I asked ChatGPT to produce a lexer for this language. I specified that the lexer should be written in C. The below code block shows sections of the produced code (see full code in <a href="https://gist.github.com/byanofsky/1f11d74222ee6acf897c74b16c1f8095">gist</a>):</p><pre>enum TokenType <br>{<br>  TOKEN_INTEGER,<br>  TOKEN_VARIABLE,<br>  ...<br>}<br><br>struct Token get_next_token()<br>{<br>  char c;<br>  struct Token token;<br>  token.type = TOKEN_UNKNOWN;<br>  memset(token.lexeme, &#39;\0&#39;, MAX_TOKEN_LENGTH);<br>  while ((c = getchar()) != EOF)<br>  {<br>    if (is_whitespace(c))<br>    {<br>      continue;<br>    }<br>    else if (is_add_op(c))<br>    {<br>      token.type = TOKEN_ADD_OP;<br>      sprintf(token.lexeme, &quot;%c&quot;, c);<br>      break;<br>    }<br>    ...<br>  }<br>  return token;<br>}</pre><p>Additionally, it provided me this explanation:</p><blockquote>This lexer uses getchar() to read characters from standard input and returns a Token structure with the appropriate type and lexeme. It supports the following tokens:</blockquote><blockquote>TOKEN_INTEGER: a sequence of digits<br>TOKEN_VARIABLE: a sequence of letters and digits starting with a letter that is not the keyword “print”<br>TOKEN_ADD_OP: either “+” or “-”<br>TOKEN_ASSIGN_OP: “=”<br>TOKEN_PRINT: the keyword “print”<br>TOKEN_LPAREN: “(“<br>TOKEN_RPAREN: “)”<br>TOKEN_SEMICOLON: “;”<br>TOKEN_UNKNOWN: any other character that doesn’t match any of the above<br>To use the lexer, you can call get_next_token() repeatedly until it returns a TOKEN_END token,</blockquote><p>The provided code mostly worked as is, with only slight modifications required. You can see the final code for the lexer here: <a href="https://github.com/byanofsky/simple-compiler/blob/main/lexer-v1.c">https://github.com/byanofsky/simple-compiler/blob/main/lexer-v1.c</a></p><h3>Step 3: Write a parser</h3><p>With the lexer completed, I was ready for the next step. So I asked ChatGPT. Here is the response:</p><blockquote>After building a lexer, the next step is to build a parser that can take the stream of tokens produced by the lexer and generate an abstract syntax tree (AST) that represents the structure of the program. The parser reads the stream of tokens and checks whether they conform to the syntax rules of the language. If the input program is syntactically correct, the parser generates an AST that captures the structure of the program in a more structured way than the stream of tokens.</blockquote><blockquote>There are many ways to implement a parser, but one common technique is to use a parsing algorithm called a recursive descent parser. A recursive descent parser is a top-down parser that works by recursively descending through the grammar rules of the language, generating nodes in the AST as it goes. Each non-terminal symbol in the grammar is associated with a parsing function that implements the corresponding rule. The parsing functions use the current token and lookahead tokens to determine which rule to apply and how to construct the AST.</blockquote><p>Here‘s the example code it provided for a parser function:</p><pre>// Parse an expression and return its AST node.<br>ASTNode* parse_expression() {<br>  ASTNode* node = parse_term();<br><br>  while (current_token.type == TOKEN_ADD_OP || current_token.type == TOKEN_SUB_OP) {<br>    Token op_token = current_token;<br>    eat(op_token.type);<br>    ASTNode* rhs = parse_term();<br>    if (op_token.type == TOKEN_ADD_OP) {<br>      node = create_add_node(node, rhs);<br>    } else {<br>      node = create_sub_node(node, rhs);<br>    }<br>  }<br>  return node;<br>}</pre><p>At this point, I decided I wanted to do some of the coding myself. So I wrote the required parsing functions for each token type.</p><p>Now, I needed some way to verify that both the parser and lexer worked as expected. I decided I could write a small driver program that would receive input, call the parse_program function to produce the AST, and then print the resulting AST.</p><p>For example:</p><pre>./parser-test &lt; ./sample-program.txt<br><br>PROGRAM<br>  STATEMENT_LIST<br>    STATEMENT<br>      ASSIGNMENT_STATEMENT<br>        ...<br>    STATEMENT<br>      PRINT_STATEMENT</pre><p>I needed a function to traverse the AST and print each node. Writing such a function is not too complex, but I decided to let ChatGPT handle it for me.</p><h4>Printing Syntax Tree</h4><p>Here is the code ChatGPT produced:</p><pre>#include &lt;stdio.h&gt;<br>#include &lt;stdlib.h&gt;<br>#include &quot;ASTNode.h&quot;<br><br>void printTree(ASTNode *node, int depth) {<br>    if(node == NULL) {<br>        return;<br>    }<br>    for(int i = 0; i &lt; depth; i++) {<br>        printf(&quot;\t&quot;);<br>    }<br>    printf(&quot;%d\n&quot;, node-&gt;type);<br>    printTree(node-&gt;left, depth+1);<br>    printTree(node-&gt;right, depth+1);<br>}</pre><p>At first glance, seemed correct. But when I integrated it into the parse-test program, it printed this result:</p><pre>0<br>  1<br>    2<br>      3</pre><p>I forgot that the NodeType enum is represented as an integer. Thus, I had to produce a function that would return a string representation for each node type.</p><p>With that done, I was able to verify that parser and lexer worked.</p><p>However, one thing bothered me about the ASTNode struct I was using.</p><h4>Modifying ASTNode</h4><p>At first, the ASTNode struct had this shape:</p><pre>struct ASTNode {<br>  string type; <br>  ASTNode* left_child; <br>  ASTNode* right_child; <br>};</pre><p>However, such a shape had limitations. For example, variables and integers had values that needed to be stored with ASTNode.</p><p>I had some ideas of how I could extend the struct, I wasn’t sure if they algined with best practices. So I asked ChatGPT for some help. I provided the grammar we’d been working with and asked for a suggestion of an ASTNode struct. Here is what it provided:</p><pre>struct ASTNode {<br>  string type; <br>  string value; <br>  ASTNode* left_child; <br>  ASTNode* right_child; <br>};</pre><p>It also gave me an example:</p><pre>          Program<br>             |<br>      StatementList<br>        /         \<br>  Statement      Statement<br>      |              |<br>  Variable &#39;=&#39;  FunctionCall<br>      |              |<br>   Integer         Variable<br>      |              |<br>     1+2             x</pre><blockquote>In this example, the type field of the top-level ASTNode would be “Program”. Its left child would be a StatementList node, which would have two children: a Statement node representing the assignment x = 1 + 2; and another Statement node representing the function call print(x);. The Variable node would have a value of “x” and two children: an Integer node with a value of “1+2”, and a FunctionCall node with a value of “print” and a child of Variable with a value of “x”.</blockquote><p>This didn’t align with the grammar we’d been working with thus far. For example, this didn’t accurately account for arithmetic expressions. Instead, it stored the expression as a string value on the Integer node. How would this work when we introduced arithmetic expressions using variables?</p><p>Thus, I continued working with it.</p><p>One suggestion arrived at that I liked was utilizing a union type on a data property:</p><pre>typedef struct ASTNode<br>{<br>  enum NodeType type;<br>  struct ASTNode *left;<br>  struct ASTNode *right;<br>  union<br>  {<br>    int int_value;<br>    char *string_value;<br>  } data;<br>} ASTNode;</pre><p>I wasn’t as familiar with the union type. But it seemed to work here. Perhaps there are ways to improve it, but I decided to continue with this.</p><p>Another sticking point I’d encountered with the current ASTNode was how we represented the StatementList:</p><pre>StatementList<br>  Statement<br>  StatementList<br>    Statement<br>    StatementList<br>      ...</pre><p>This seemed unnecessarily verbose. I was thinking we could use an array of list. So I asked ChatGPT:</p><blockquote><em>Using an array or a linked list to represent the list of statements in the AST node would be a better way to represent the statement_list. This way, the ASTNode will have a pointer to the first element in the list, and each element in the list will have a pointer to the next element.</em></blockquote><p>It provided an implementatin using a linked list. <a href="https://github.com/byanofsky/simple-compiler/blob/main/parser-v1.h#L24-L28">You can see this implementation in the final parser code</a>.</p><h4>Final ASTNode</h4><p>Here is the resulting ASTNode:</p><pre>typedef struct ASTNode<br>{<br>  enum NodeType type;<br>  struct ASTNode *left;<br>  struct ASTNode *right;<br>  union<br>  {<br>    int int_value;<br>    char *string_value;<br>    enum OpType op_type;<br>    StatementList *statement_list;<br>  } data;<br>} ASTNode;</pre><p>To reiterate, perhaps this is still not optimal, but it works for now.</p><p>The final parser code can be viewed here: <a href="https://github.com/byanofsky/simple-compiler/blob/main/parser-v1.c">https://github.com/byanofsky/simple-compiler/blob/main/parser-v1.c</a></p><h3>Step 4: Write a code generator</h3><p>Next step after the parser was code generator.</p><p>I asked ChatGPT to produce a code generator using C. Here is portions of the produced code:</p><pre>void generate_code(ASTNode *node) {<br>    if (!node) return;<br>    generate_code(node-&gt;left);<br>    generate_code(node-&gt;right);<br>    switch (node-&gt;type) {<br>        case NODE_TYPE_INTEGER:<br>            printf(&quot;PUSH %d\n&quot;, node-&gt;data.int_value);<br>            break;<br>        case NODE_TYPE_VARIABLE:<br>            printf(&quot;PUSH %s\n&quot;, node-&gt;data.string_value);<br>            break;<br>        ...<br>        default:<br>            fprintf(stderr, &quot;Unsupported node type: %d\n&quot;, node-&gt;type);<br>            exit(1);<br>    }<br>}</pre><p>It stated that the code it provided “generates assembly code for a hypothetical stack-based machine.”</p><p>I didn’t want to generate code for a hypothetical machine. I wanted the code produced by my compiler to run on my machine.</p><p>Luckily, ChatGPT included a hint at the end of the mssage:</p><blockquote>You can modify the generated assembly code instructions to match the instruction set of your target machine or generate code for another output format, such as LLVM IR or actual machine code.</blockquote><p>LLVM had been on my mind ever since I’d listened to Lex Fridman’s interview with <a href="https://en.wikipedia.org/wiki/Chris_Lattner">Chris Lattner</a> (co-founder of LLVM):</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FyCd3CzGSte8%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DyCd3CzGSte8&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FyCd3CzGSte8%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/95af1cb93d748ea6b30d51b2046e6d73/href">https://medium.com/media/95af1cb93d748ea6b30d51b2046e6d73/href</a></iframe><p>However, I’d never worked with LLVM before. I wasn’t even sure how to get started.</p><p>Luckily, I had ChatGPT to help me.</p><h4>LLVM IR</h4><p>I asked ChatGPT to modify the program to produce LLVM IR code. The resulting code’s structure remained the same, but the printf statements changed:</p><pre>case NODE_TYPE_ASSIGNMENT:<br>            printf(&quot;  store i32 %%x%d, i32* @%s\n&quot;, var_counter - 1, node-&gt;left-&gt;data.string_value);<br>            break;</pre><p>I decided to test this out. I fed it a sample program: var1 = 5 + 1;. Here is an example of the LLVM IR it emitted:</p><pre>%x1 = add i32 0, 5<br>%x2 = add i32 0, 1<br>%x3 = add i32 %x1, %x2<br>store i32 %x3, i32* @var1</pre><p>Even with my limited knowledge of LLVM IR, there seemed to be some performance optimizations available. Most glaringly: why did an add operation of two integers (ie, 5+1 ) require loading both integers into variables first. And why did the loading operations require adding the integers to 0 first?</p><p>Instead, it seemed we could just do the following when adding two integers:</p><pre>%x1 = add i32 5, 1<br>store i32 %x1, i32* @var1</pre><p>However, I decided not to dive deep into this rabbit hole at this point.</p><h4>Variable Table</h4><p>When I tried to compile the LLVM IR code via clang, I encountered an error:</p><pre>main.ll:6:24: error: use of undefined value &#39;@testVar&#39;<br>  %x1 = load i32, i32* @testVar</pre><p>I copied this error into ChatGPT:</p><blockquote>This error occurs because LLVM IR is trying to load a value from a global variable named testVar, but the variable has not been defined. To fix this error, you need to define global variables in your generated LLVM IR code for each variable that appears in your input program.</blockquote><p>ChatGPT showed me how to use global variables. I started with that, but then decided to pivot to using a variable lookup table so that variables are not globally defined.</p><p>ChatGPT helped me set up the scaffolding for a variable lookup table.</p><p>To initialize the variable lookup table, I would iterate through all nodes and find the variable nodes. For each variable node, I would add an entry where the key is the variable name and the value is a unique LLVM IR variable name.</p><p>Then, when generating the IR code, we can lookup the appropriate LLVM IR variable name to use.</p><p>Here is the code relevant to the variable lookup table: <a href="https://github.com/byanofsky/simple-compiler/blob/main/generate_llvm_ir.c#L9-L78">https://github.com/byanofsky/simple-compiler/blob/main/generate_llvm_ir.c#L9-L78</a></p><blockquote>Note: While writing this article, I did uncover a bug. If a variable is assigned a value twice, it will attempt to allocate the variable twice. I assume this will result in an error. The variable lookup table code probably needs additional work</blockquote><h4>Example LLVM IR code</h4><p>Here is one test program with the resulting LLVM IR code:</p><pre>// Test Program<br>testVar1 = 2 - 3;<br>testVar2 = 5 + 6;<br>testVar3 = testVar1 + testVar2;<br>print(testVar3);<br><br>// LLVM IR<br>target triple = &quot;arm64-apple-macosx12.0.0&quot;<br>; ModuleID = &#39;main&#39;<br>declare void @print_integer(i32)<br>define i32 @main() {<br>  %x0 = add i32 0, 2<br>  %x1 = add i32 0, 3<br>  %x2 = sub i32 %x0, %x1<br>  %ptr_3 = alloca i32<br>  store i32 %x2, i32* %ptr_3<br>  %x3 = add i32 0, 5<br>  %x4 = add i32 0, 6<br>  %x5 = add i32 %x3, %x4<br>  %ptr_4 = alloca i32<br>  store i32 %x5, i32* %ptr_4<br>  %x6 = load i32, i32* %ptr_3<br>  %x7 = load i32, i32* %ptr_4<br>  %x8 = add i32 %x6, %x7<br>  %ptr_5 = alloca i32<br>  store i32 %x8, i32* %ptr_5<br>  %x9 = load i32, i32* %ptr_5<br>  call void @print_integer(i32 %x9)<br>  ret i32 0<br>}</pre><h3>Step 5: Write a driver program</h3><p>At this point in my progress, I had a compiled program called generate_llvm_ir. I could feed it a test program and it would output resulting LLVM IR code. I could compile this resulting code with clang. Then run the resulting executable to ensure expected output.</p><p>However, this required multiple steps.</p><p>I realized the current problem with my program was that my code generation was printing the LLVM IR code to stdout. Instead, I wondered if I could use some LLVM API instead.</p><p>In fact, in an earlier message, ChatGPT hinted at this. When it produced the generate_llvm_ir code, it included a message:</p><blockquote>This example demonstrates generating textual LLVM IR, but you can also use the LLVM C++ API or the LLVM C API (<a href="https://llvm.org/doxygen/group__LLVMC.html">https://llvm.org/doxygen/group__LLVMC.html</a>) to generate IR programmatically. Using the API allows for more control over the IR generation process and better integration with the rest of the LLVM infrastructure, such as optimization passes and target-specific code generation.</blockquote><p>However, I wasn’t sure if I’d have enough time to refactor to use this API.</p><p>Therefore, I decided to keep the textual LLVM IR and use a hacky solution.</p><p>I wrote a C program that executes the generate_llvm_ir and clang commands. It uses the former program to produce the LLVM IR code and write to a temp.ll file. Then, the temp.ll is fed as input to the latter command. The user provides the input file (to feed to generate_llvm_ir) and an output file (where clang writes the resulting executable):</p><pre>./compiler &lt;input-file&gt; &lt;output-file&gt;</pre><p>Not a very elegant solution, but it works (for now).</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2FVhWVAa7rUtT3xKX6Cd%2Ftwitter%2Fiframe&amp;display_name=Giphy&amp;url=https%3A%2F%2Fmedia.giphy.com%2Fmedia%2FVhWVAa7rUtT3xKX6Cd%2Fgiphy.gif&amp;image=https%3A%2F%2Fi.giphy.com%2Fmedia%2FVhWVAa7rUtT3xKX6Cd%2Fgiphy.gif&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=giphy" width="435" height="326" frameborder="0" scrolling="no"><a href="https://medium.com/media/6fa523b069be7d4b86855abd2d1530cc/href">https://medium.com/media/6fa523b069be7d4b86855abd2d1530cc/href</a></iframe><h3>Step 6: Test your compiler</h3><p>Because the language is not too overly complex and because I had limited time, I didn’t do extensive testing.</p><p>However, one annoyance while testing were the error messages. With my original code, I’d get messages like this on syntax errors:</p><pre>Unexpected token &quot;&quot;. Expected 4.</pre><p>First, I modified the error message to output the string representation of a token instead of the enum integer:</p><pre>Unexpected token &quot;&quot;. Expected &quot;semicolon&quot;.</pre><p>Then, I modified the lexer to add starting position to each token. With this, I updated my error messages to:</p><pre>Unexpected token &quot;&quot; at position 6. Expected &quot;semicolon&quot;.</pre><p>Much better. I could quickly find and fix these syntax errors in my sample programs.</p><h3>Conclusions</h3><p>Here are some general thoughts after completing this project:</p><ul><li>I have a better understanding of compilers. However, I realize I’ve barely touched the surface. There is so much more to learn.</li><li>ChatGPT is an interesting coding partner. It is extremely helpful with ideating and debugging. Its code generation saves a lot of time, but you need to check the code it produces. There are subtle bugs in the code.</li><li>The C programming language still feels daunting to me. It seems there are myriad of ways to accomplish things. And it’s hard to determine which way is optimal. ChatGPT was helpful here.</li></ul><h3>What’s Next</h3><p>I try to time box my projects. But if I have time in the future, here’s what I’d do:</p><ul><li>Dive deeper into compilers. Specifically, check out the resources suggested in <a href="https://teachyourselfcs.com/#languages">teachyourselfcs</a>. This includes the <a href="https://www.amazon.com/Compilers-Principles-Techniques-Tools-2nd/dp/0321486811?redirectFromSmile=1">“Dragon book”</a> and <a href="https://craftinginterpreters.com/contents.html">Crafting Interpreters</a>.</li><li>Add features to my language, such as functions/procedures, additional data types (strings, arrays, dictionaries, booleans), and control flow (if/else, while, for)</li><li>Leverage existing tools. Further leverage <a href="https://llvm.org/">LLVM</a>. Or try a tool like <a href="https://www.antlr.org/">ANTLR</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7aebcd2a2c20" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Quick Update On ‘Bookmark Web Service’, And Building The Full Application]]></title>
            <link>https://medium.com/@byanofsky/quick-update-on-bookmark-web-service-and-building-the-full-application-496c697fb3de?source=rss-857b06cc363------2</link>
            <guid isPermaLink="false">https://medium.com/p/496c697fb3de</guid>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[flask]]></category>
            <category><![CDATA[api]]></category>
            <dc:creator><![CDATA[Brandon Yanofsky]]></dc:creator>
            <pubDate>Tue, 10 Oct 2017 23:33:51 GMT</pubDate>
            <atom:updated>2017-10-10T23:37:25.515Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TqHXoekpMom_i5xPQh8eVQ.jpeg" /></figure><p>It’s been a few weeks since I’ve been able to work on my <a href="https://github.com/byanofsky/bookmarks-service">Bookmark Web Service</a>.</p><p>I’d taken a short hiatus from Python to study JavaScript some more, and put this project on a temporary hold during that time.</p><p>This week, I’ve had some time to jump back into my Bookmark service and launched an updated version to Heroku (<a href="https://bookmarks-service.herokuapp.com/">https://bookmarks-service.herokuapp.com</a>).</p><p>While it is not 100% complete, the Bookmark service is at a point where I can use it to build out the full bookmarking web application I’ve been planning to build for a few months now.</p><p>As such, I’d like to update you on where I am with my bookmarking web service, how I plan to use this web service in my full application, and future plans for improving it.</p><p><strong>One final note before we jump in:</strong> I made a lot of mistakes along the way and learned some valuable lessons, so in the near future I plan to write posts discussing what I’ve learned.</p><p>Now, let’s discuss what this bookmarking web service actually does.</p><h3>1. An Overview of the Bookmarking Web Service</h3><p>If you’d like to try out my Bookmarking service, you can do so here: <a href="https://bookmarks-service.herokuapp.com/">https://bookmarks-service.herokuapp.com</a>. It is a live, working version. Just shoot me an email at <a href="/service/mailto:byanofsky@me.com">byanofsky@me.com</a> and I’ll set you up with an account.</p><p>I launched <a href="https://github.com/byanofsky/bookmarks-service/blob/master/API.md">(crude) API Documentation</a> so you’ll know how to work with the API, but in the meantime, here is a quick overview:</p><h3>How The Bookmarking Service Works</h3><p>To interact with any aspect of the service, you’ll need to include an <a href="https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Authorization">HTTP Authorization header using the Basic authentication type</a>. Which username and password you use depends on the type of request you make.</p><h4>SuperUsers</h4><p>SuperUsers are the starting point, and are able to create new Users. Because SuperUsers have so much power and will rarely be added, I’ve intentionally left it a bit cumbersome to add, and as such must be added via Python code.</p><p>Each SuperUser will have an ID and a Password which they can use in the next step.</p><p>I’ve provided <a href="https://github.com/byanofsky/bookmarks-service/blob/master/README.md#creating-a-superuser">instructions on adding a SuperUser in my GitHub Readme</a>.</p><h4>Creating &amp; Viewing Users</h4><p>SuperUsers authenticate with their ID and Password and are then able to view all Users by making a GET request to /users. They can also create Users by making a POST request to the same endpoint, also passing form data for name, email, and password. The response will include a user id.</p><h4>Creating &amp; Viewing API Keys</h4><p>Users authenticate with their ID and Password and are able to create an API Key by making a POST request to /api_keys. The response will include an API Key ID and Secret. To view all existing API Keys associated with the user, make a GET request to /api_keys.</p><h4>Creating &amp; Viewing Bookmarks</h4><p>To work with bookmarks, users must authenticate with their API Key ID and Secret.</p><p>To create a bookmark, make a POST request to /bookmarks, including form data for:</p><ul><li>url</li><li>follow_redirects – This is optional, but setting this to True has the service follow all redirects on the url and save the final URL to the bookmark</li></ul><p>The response from the POST request will include an id that is a random and unique 6 character alphanumeric sequence, such as &#39;abcdef&#39;.</p><p>Making a GET request to /bookmarks/abcdef, for instance, will return a response with the original URL.</p><p>Making a GET request to /bookmarks will show all bookmarks which that user has added.</p><h3>2. How I Plan To Use This Bookmarking Service</h3><p>For my own bookmarking application, I plan to use this web service to handle storing the bookmarks.</p><p>A user will be able to visit my application homepage and enter a URL to bookmark. A request will then be made from the application to this web service, which will return a bookmark ID. This ID will be directly associated with the shortened link that my application will return to the user.</p><p>Then, if anyone visits that shortened link, the application will make a request to the web service, passing the bookmark ID, find the associated URL, and redirect the user to this URL.</p><h3>Application Timeline</h3><p>By the end of October, I’d like to launch the full application utilizing a microservices architecture. This Bookmarking web service I’ve built handles the majority of backend functionality, so I can now concentrate on building the frontend of the application.</p><p>I haven’t had a chance to play with some of the popular frontend frameworks, so I will use this project as an exercise to gain experience working with React.</p><h3>Future Plans For The Application</h3><p>After I build out the frontend of the application, I would like to add in some more functionality, including tracking/analytics on all bookmarks, allow users to create an account to edit their bookmarks, and provide users a way to make bookmarks private or public.</p><p>Should be fun!</p><h3>3. What I’ll Be Adding To This Web Service In The Future</h3><p>As I mentioned in the beginning, even though I’ve launched my web service and will be using it as part of a larger application, it is not done yet.</p><p>Here are some of the areas I need to improve.</p><h3>Turn Off URL Checking</h3><p>Right now, when a request is made to add a bookmark, the service makes a request to the URL and checks the status code. If the status code is not 200 or 300 level, it will return an error to the user and not create the bookmark.</p><p>While this is a nice feature to help users who may make typos when entering URLs, there may be a use case for users who want to add URLs that either don’t exist yet or return an error code for now but not in the future.</p><p>So I’d like to add another option that users can pass when creating a bookmark that will turn this checking off.</p><h3>Editing and Deleting</h3><p>There is currently no way for someone to edit or delete users or bookmarks.</p><p>But this is definitely a needed functionality.</p><p>Adding this functionality is rather easy (I just need to add PUT and DELETE methods to the appropriate routes), but there are some complexities I’d like to address.</p><p>For instance, if a user is deleted, what happens to all of their bookmarks?</p><h3>Password Resetting</h3><p>In the same line of thinking, if a user is created with a password, there is no way for them to reset their password. If they forget their password, they will get locked out of their account.</p><p>I’d like for users to be able to reset their passwords. At first I imagined using emails to allow resets, but this is probably too much for a web service.</p><p>Instead, SuperUsers should be granted the ability to reset user passwords.</p><h3>Security</h3><p>I spent some time researching how to make this service secure. But I realized I was spending too much time and decided that the best way for now would be to use basic authentication. Although this is not the most secure way, as long as the data is sent over HTTPS, it should be secure. But I still would like to research more secure options.</p><h3>Final Thoughts</h3><p>I have some work still ahead of me, but I’m excited to integrate my web service into a full application that utilizes a microservices architecture.</p><p>Obviously, I’m not inventing anything groundbreaking (there are tons of link shortening services out there already), but the process of building out this application has allowed me to learn some of the intricacies of how the Internet works, how REST APIs work, and how to build a larger application.</p><p><em>Originally published at </em><a href="http://byanofsky.com/2017/10/10/update-on-bookmark-service/"><em>byanofsky.com</em></a><em> on October 10, 2017.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=496c697fb3de" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Implementing a Microservices Architecture on my ‘Bookmarks’ Application]]></title>
            <link>https://medium.com/@byanofsky/implementing-a-microservices-architecture-on-my-bookmarks-application-36f11adbb8e6?source=rss-857b06cc363------2</link>
            <guid isPermaLink="false">https://medium.com/p/36f11adbb8e6</guid>
            <category><![CDATA[software-architecture]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[microservices]]></category>
            <dc:creator><![CDATA[Brandon Yanofsky]]></dc:creator>
            <pubDate>Thu, 10 Aug 2017 16:47:29 GMT</pubDate>
            <atom:updated>2017-08-11T00:01:35.454Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*aFa6FS6LpY_TDM1mfDVqrg.jpeg" /></figure><p>For the last few weeks, I’ve been developing a <a href="https://bay-bookmarks.herokuapp.com/">bookmarking and link shortening application</a>. (<a href="https://github.com/byanofsky/bookmarks/tree/8c0ecc88140f1b4aa1dc829b5ccb466920e61bd5">Click here to view the latest commit as of the time of this writing</a>)</p><p>I’d built out most of the backend logic, but ran into an issue with the frontend. As I started introducing frontend tools, frameworks, and libraries, my application started to feel like it was becoming hard to maintain.</p><p>I also realized that if a developer wanted to implement my code in their own application, it would be very difficult. They’d have to remove all of my frontend code to replace with their own.</p><p>Almost like divine intervention, I started hearing a lot about microservices. I didn’t fully understand what it meant, but from what I did know, it seemed like it may help with my issue.</p><p>So I did a bit of research and rethinking of my application.</p><p>Here is what I found.</p><h3>My Intro To Microservices</h3><p>The first time I had a solid understanding of the concept of microservices was when I read <a href="https://medium.com/netflix-techblog/starting-the-avalanche-640e69b14a06">Netflix’s blog post discussing how a new form of DDoS would target its microservices architecture</a>. I saw how Netflix’s applications were really made up of a number of tiers of services all handling different aspects of the application. This helped me conceptualize the microservices architecture.</p><p>When I did more research into the microservices architecture, I discovered that it basically is about splitting an application into separate services. Each service acts as its own application in a way. They each can have their own environment, including hardware, software, and database. And usually they communicate over a network (most likely via HTTP).</p><p>The upside to a microservices architecture is that it makes everything more maintainable and scalable. Because of the modular nature, each service can be easily rebuilt or replaced with another service. It just needs to follow the protocols set up for each service to communicate. Abstraction at its best!</p><p><a href="https://en.wikipedia.org/wiki/Microservices">You can learn more about the specifics of microservices here</a>.</p><h3>Refactoring the Bookmarks Application</h3><p>Analyzing my bookmarks application, I see how I can split it into 2 different services.</p><p>The first is the bookmarks API. I can build a REST API that controls the creation and lookup of bookmarks. A user can send requests to create a new bookmark, look up the URL of an existing bookmark, and view all bookmarks they’ve created.</p><p>The second service would be the web application. It would be user facing and handle the UI as well as user authentication (maybe in the future I’ll split this up too).</p><p>The nice thing is that any developer could take my bookmarks API code and easily make their own bookmarking service from it. I also have the possibility of creating different applications which utilize my bookmarking service. Or I can open my deployed bookmarking service to anyone who wants to use it to build their own applications.</p><h3>Final Thoughts</h3><p>I have a few things I still need to figure out:</p><ul><li>Architecture of the bookmarks API</li><li>How to authenticate users of my API</li><li>Connecting the web application with the API</li></ul><p>I plan on writing a few followup posts as I complete each task.</p><p>If you have any suggestions on ways I can improve what I’m doing, please let me know.</p><p><em>Originally published at </em><a href="https://byanofsky.com/2017/08/10/implementing-a-microservices-architecture-on-my-bookmarks-application/"><em>byanofsky.com</em></a><em> on August 10, 2017.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=36f11adbb8e6" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[My Flask Configuration Handling]]></title>
            <link>https://medium.com/@byanofsky/my-flask-configuration-handling-93bc2df734fe?source=rss-857b06cc363------2</link>
            <guid isPermaLink="false">https://medium.com/p/93bc2df734fe</guid>
            <category><![CDATA[flask]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Brandon Yanofsky]]></dc:creator>
            <pubDate>Tue, 08 Aug 2017 16:10:36 GMT</pubDate>
            <atom:updated>2017-08-08T16:13:26.973Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OfHoVys-lwFeM9DfOB3jew.png" /><figcaption>Gist of my Flask configuration file</figcaption></figure><p>I’ve built a few applications using Flask, but I’ve had trouble handling configuration, especially when it comes to handling different environments.</p><p>But I’ve found a way that works, is simple, and is easy even when using multiple environments. I’ll share the details below, or you can go <a href="https://gist.github.com/byanofsky/957c464c49cb46d282df19fb2e59df80">view it on Gist</a>.</p><h3>The Problem</h3><p>As mentioned, the main issue I’d had was with switching between different environments (production, development, testing). For instance, in each environment, I’d need to specify the URL of a different database to use.</p><p>In previous applications, I would handle this issue by using different configuration files for each environment, and switch the file depending on the environment I was working with.</p><p>I didn’t like this approach for 2 reasons:</p><ol><li>It was open to user error (what if I forgot to switch settings files and launched to production)</li><li>It seemed like more work than was necessary (overly complex)</li></ol><p>So I went seeking for a solution.</p><p>The <a href="http://flask.pocoo.org/docs/0.12/config/#configuring-from-files">Flask documentation presents a few ways to handle configuration</a>, but I wasn’t thrilled with their options. They either required too much input from a user (open to human error) or were a bit too complex (I wanted to make this as simple as possible).</p><p>But I did see a line in the documentation which stated: “Use an environment variable to switch between the configurations.”</p><p>Going with this idea and combining it with some of the example configurations, I came up with an elegant solution.</p><h3>The Solution</h3><p>The basic idea is to set all configurations within one configuration file. Then the user can set an environment variable which Flask can use to tell which environment it is in. Switching environments just requires changing that environment variable.</p><p>I liked this approach because it required only one action of the user (setting an environment variable) and abstracted the complexity away (no more need for multiple configuration files). I also can easily use the same code in each environment (no more multiple repos).</p><p>Here is the code I ended up with:</p><p>So what’s going on here?</p><p>We are first reading the environment variable APPLICATION_ENVIRONMENT. If there is none set, it defaults to &#39;development&#39;.</p><p>We can then set the configuration settings which are applicable to all environments (such as the SECRET_KEY).</p><p>Then, we can override settings depending on the current environment, such as setting a different database for each environment.</p><h3>How I Used This In My Workflow</h3><p>I’ve been working on a bookmarking/link shortening application (<a href="https://github.com/byanofsky/bookmarks/">https://github.com/byanofsky/bookmarks/</a>) which I deployed to Heroku.</p><p>On the Heroku production server, I set the APPLICATION_ENVIRONMENT to &#39;production&#39;.</p><p>On my local Vagrant server where I do development and testing, I easily switch between the two environments as needed.</p><p>I also created a fourth environment that I use for staging that connects with a staging server on Heroku and test with <a href="https://devcenter.heroku.com/articles/heroku-local">Heroku Local</a>.</p><p>Switching between environments is easy, which makes managing my code simpler.</p><h3>Last Thoughts</h3><p>Hopefully this helps you with your Flask configuration handling.</p><p>If you find ways I can improve this, please let me know in the comments.</p><p>Thanks!</p><p><em>Originally published at </em><a href="https://byanofsky.com/2017/08/08/my-flask-configuration-handling/"><em>byanofsky.com</em></a><em> on August 8, 2017.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=93bc2df734fe" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building a Simple Chess AI]]></title>
            <link>https://medium.com/@byanofsky/building-a-simple-chess-ai-c84e14f4acf9?source=rss-857b06cc363------2</link>
            <guid isPermaLink="false">https://medium.com/p/c84e14f4acf9</guid>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[chess]]></category>
            <dc:creator><![CDATA[Brandon Yanofsky]]></dc:creator>
            <pubDate>Thu, 06 Jul 2017 15:54:17 GMT</pubDate>
            <atom:updated>2017-07-06T16:18:17.168Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CWW7tjLR1T3hYS-NDziATw.png" /></figure><p>I’ve been wanting to build a chess AI for a few years now. I was excited by the idea of building a program that could make decisions ,and maybe in the future, learn from those decisions.</p><p>With the help of <a href="https://medium.freecodecamp.com/@lhartikk">Lauri Hartikka’s</a> tutorial <a href="https://medium.freecodecamp.com/simple-chess-ai-step-by-step-1d55a9266977">“A step-by-step guide to building a simple chess AI “</a>, I was finally able to build my own chess AI (My details below are simply an extension of his).</p><p>You can play it here: <a href="https://bay-chess-ai.herokuapp.com/">https://bay-chess-ai.herokuapp.com</a>.</p><p>When playing, I would recommend opening your browser’s console so you can see the output as the computer thinks through each move.</p><h3>Want To See How It’s Built?</h3><p>In the rest of this article, I’ll walk you through the ideas behind the different iterations of the chess AI, and how I implemented them, so you can build your own. Where applicable, I’ve provided links to resources that helped me understand some of the theories behind the ideas I implemented.</p><p>Each iteration has increasing “intelligence”, which allows it to make better moves. I’ve included all iterations as functions within my code.</p><p>If you’d like to see the full code, you can view it here: <a href="https://github.com/byanofsky/chess-ai-2">https://github.com/byanofsky/chess-ai-2</a></p><p>The file which contains the code for calculating moves it located here: <a href="https://github.com/byanofsky/chess-ai-2/blob/master/public/js/movecalc.js">https://github.com/byanofsky/chess-ai-2/blob/master/public/js/movecalc.js</a></p><h3>Setup</h3><p>The goal of this project is to build the chess AI, not the board visuals or chess logic (what moves are allowed, when the game is over, etc).</p><p>Luckily, there are 2 libraries which handle both of these, and work well together.</p><p><a href="http://chessboardjs.com/">chessboard.js</a> handles creating the visuals (the chess board and pieces), as well as the interface for when a user makes a move (dragging pieces to a square).</p><p><a href="https://github.com/jhlywa/chess.js">chess.js</a> is a library which, as its README states, “…is used for chess move generation/validation, piece placement/movement, and check/checkmate/stalemate detection — basically everything but the AI.”</p><p>For server-side code, it is just Node.js and Express. I’m not overly familiar with Node and Express at this time, so I tried to keep it as simple as possible. In the future, once I get more familiar, I’ll improve this.</p><p>I created 3 JavaScript files which handle different aspects of the chess AI:</p><ol><li><a href="https://github.com/byanofsky/chess-ai-2/blob/master/public/js/boardconfig.js">boardconfig.js</a> — sets configuration for chessboard.js, and creates an instance of the board and chess game</li><li><a href="https://github.com/byanofsky/chess-ai-2/blob/master/public/js/movecalc.js">movecalc.js</a> — contains the functions which calculate the move to make</li><li><a href="https://github.com/byanofsky/chess-ai-2/blob/master/public/js/main.js">main.js</a> — contains functions for initiating the computer to move</li></ol><p>Now, let’s discuss the move calculation functions. I’ll discuss each iteration that I built.</p><h3>Iteration 1: Random Moves</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/402/0*tnchZt-X5Dp5lMN4." /><figcaption>Making random moves</figcaption></figure><p>This first iteration really sucked, but was quick to implement.</p><p>The AI simply finds all possible moves it can make this turn, and randomly picks one to make.</p><p>The function I used here is actually available on the chessboard.js website as example code. You can view it here: <a href="http://chessboardjs.com/examples#5001">http://chessboardjs.com/examples#5001</a></p><p>It also includes the code for integrating chess.js and chessboard.js, so it is a great starting point.</p><h3>Iteration 2: Choose Best Move, Looking One Move Ahead</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/402/0*2DY936DaVqo11uVd." /><figcaption>Looks one move ahead</figcaption></figure><p>This next iteration starts adding some decision making to the chess AI.</p><p>It looks at all possible moves it can make this turn, and evaluates it’s position after each move. It then picks the move which leads to the best position.</p><p>To implement this iteration, we need 2 functions:</p><ol><li>One function to evaluate the position</li><li>Another to evaluate the outcome of each possible move</li></ol><h3>Position Evaluation Function</h3><p>In chess, you can ‘score’ a current position to see which player is ahead. This will then allow the AI to basically say, “Move A leads to a position of -100, but move B leads to a position of 50. So I’ll choose move B.”</p><p>There are many ways to calculate this, but for this chess AI, we’ll use a relatively simple function to figure this out:</p><p>Relative to the player for whom we want to evaluate the position, any of their own pieces will add to their score, and their opponent’s pieces will subtract.</p><p>So the return value will be the player’s position relative to its opponents.</p><p><strong>What about the value for each piece?</strong> There are many different ways you can assign these values (<a href="https://en.wikipedia.org/wiki/Chess_piece_relative_value">https://en.wikipedia.org/wiki/Chess_piece_relative_value</a>), but I decided to go with Larry Kaufman’s suggested values for the middle game, multiplied by 100, so there are no floating numbers to deal with:</p><ul><li>pawn = 100</li><li>knight = 350</li><li>bishop = 350</li><li>rook = 525</li><li>q = 1000</li><li>king = 10000</li></ul><p>The function, shown below, takes the 2D array that is returned by chess.js’s function chess.board(). It loops through each piece and either adds the piece if its color matches with the player color passed to the function, or subtracts it.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/af9d32be7593617ae5aa708e31a8ccd8/href">https://medium.com/media/af9d32be7593617ae5aa708e31a8ccd8/href</a></iframe><p>Improving this evaluation function will also improve each iteration.</p><p>But for now, it is a good starting point.</p><h3>Evaluate All Possible Moves</h3><p>This function uses the position evaluation function to evaluate the position after every possible move.</p><p>We’ll build upon the random move function from the previous iteration.</p><p>Instead of randomly choosing the move from the list of possible moves, our program will make every move and evaluate the position. After it makes each move, it will undo the move. All the while, the function is tracking which move leads to the best position.</p><p>You’ll notice that I randomized the order of the possible moves. Without this randomization, if all moves lead to an equal outcome, it will choose the first move in the list (which is the first piece that can move in the upper left corner). This leads to the knight moving, then the rook moving back and forth until a piece comes close enough to capture.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ad2230e41524eee37681812be544e673/href">https://medium.com/media/ad2230e41524eee37681812be544e673/href</a></iframe><h3>Iteration 3: Looking Multiple Moves Ahead</h3><p>While the last iteration now encourages the computer to capture pieces (it will pick moves that increase its relative position), it is still lacking. Because the chess AI is only looking one move ahead, it isn’t able to predict what its opponent will do after its move. So it isn’t able to determine if it should move a piece about to be captured, and will actually move a piece into a position to get captured.</p><p>So, in this third iteration, we’ll give the AI the ability to look more than one move ahead.</p><p>To implement this, we’ll use an algorithm called Minimax.</p><p>I’ll explain what Minimax is, and then show my implementation.</p><h3>Minimax</h3><p>I’ll provide a short overview of Minimax here, but I highly recommend the Wikipedia article on it: <a href="https://en.wikipedia.org/wiki/Minimax">https://en.wikipedia.org/wiki/Minimax</a>. You’ll even find a pseudocode example there.</p><p>Minimax is an algorithm we can use to evaluate all possible moves a player can make. We follow each move to a certain depth, which in this instance is how many moves ahead we want to look. Our evaluation will be relative to a player, and that player will be trying to get the best score possible (maximize their position). The opponent be doing the opposite: trying to minimize the original player’s value (which is, in essence, maximizing the opponent’s own value).</p><p>To further understand this concept, it helps to create a tree. In this instance, we are starting with the maximizing player, and looking 2 moves ahead:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*SRIrSjcDWP7P93ks." /></figure><p>Each square is a node when the maximizing player chooses a move, and a circle is a node when the minimizing player chooses a move.</p><p>We can follow the tree and see the outcomes for each possible move lead to these positions: 100, -100, 0, and 10.</p><p>Naturally, the maximizing player will want to reach an outcome of 100. But if the maximizing player chooses that route, the minimizing player will make a move that leads to -100 (hence why -100 trickles up).</p><p>Instead, if the maximizing player goes with the other move, the minimizing player will choose 0.</p><p>So the maximizing player will need to go with the move that leads to 0 since it leads to the greatest possible outcome.</p><h3>Implementing Minimax</h3><p>Just as we did with the iteration looking one move ahead, we’ll still loop through all possible moves, but the value of each move will not be the current board position, but the final board position as we trickle down the tree.</p><p>For this, we’ll need to use recursion.</p><p>Each recursive call, we decrease our depth by 1, until we get to a depth of 0, at which point we evaluate the position.</p><p>These values trickle up and allows the AI to pick a move that leads to the best position.</p><p>One thing to remember: we are evaluating from the viewpoint of one player. So when we enter a recursive call and are evaluating from the viewpoint of the opponent, the opponent is choosing a move that leads to the MINIMUM value.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/80a258286e7f4f5bbc7a29a9122aa197/href">https://medium.com/media/80a258286e7f4f5bbc7a29a9122aa197/href</a></iframe><p>Hence the if/else statement.</p><h3>Iteration 4: Minimax with Alpha Beta Pruning</h3><p>At this point, the chess AI is starting to make good moves. It will protect valuable pieces from being captured, and if it looks far enough ahead, it can start to formulate a strategy.</p><p>The only problem is the algorithm takes a long time.</p><p>That’s because of the number of branches it needs to evaluate.</p><p>Luckily, there is a way to remove branches that aren’t worth evaluating.</p><p>For this, we’ll use alpha beta pruning.</p><h3>What Is Alpha Beta Pruning?</h3><p>When I was researching alpha beta pruning, I found these notes to be the best resource possible: <a href="http://web.cs.ucla.edu/~rosen/161/notes/alphabeta.html">http://web.cs.ucla.edu/~rosen/161/notes/alphabeta.html</a></p><p>I highly recommend looking through these notes for a great example that walk through how it works.</p><p>But on a very high level, the idea is that we can eliminate branches when searching through the tree of moves, which makes our evaluating much faster. Take this tree as an example:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*HvOGe966YrT7Yv4q." /></figure><p>We start on the first branch, and come up with a 3, so that trickles up.</p><p>We then go down the second branch, and the first move the min player comes across is a 2.</p><p>But we run into a problem.</p><p>The max player already found a branch with a 3. So unless there is a value in the other branch greater than 3, the max player won’t choose it. So we need to find a value greater than 3. But because the min player is choosing and already found a 2, they only want to find a value less than 2.</p><p>So we are looking for:</p><p>x &lt; 2 and x &gt; 3</p><p>That doesn’t exist, so there is no point evaluating further down this branch.</p><p>In this example, there’s only 1 other branch, but in our chess game, this could be many more branches as we trickle down each move. Alpha beta pruning saves a lot of time!</p><h3>Implementing Alpha Beta Pruning</h3><p>This is just an extension of our Minimax implementation.</p><p>We simply add in variables to track alpha and beta.</p><p>We start with default alpha and beta values, but within each recursive call, we pass the alpha and beta values as they currently are.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/99c7c98616e6f690ff670777a068f77d/href">https://medium.com/media/99c7c98616e6f690ff670777a068f77d/href</a></iframe><p>And as these values trickle up, we use min and max functions to compare them to the values, and change the alpha/beta values.</p><p>Finally, if we find we are on a branch when alpha is greater than beta, we know we are on a branch that isn’t a candidate, and prune it.</p><h3>Final Thoughts and Way To Improve</h3><p>The final iteration here is actually a pretty good chess player. But it still has many limitations.</p><p>The biggest: it is still very slow. Having the computer look 4 or more moves ahead is still really slow. The AI could be much better if it could look more moves ahead, but it would take an ungodly amount of time.</p><p>One way I’ve considered to improve speed is to organize the possible moves. Right now, they are randomly organized before evaluating. But if they were organized with the best potential moves first (such as ones that capture pieces), alpha beta pruning would be able to eliminate more branches. But the sort function may take more time than is saved.</p><p>Another issue is the position evaluation function. Currently, it is based on how many pieces are remaining on the board. But it does not take the piece position into consideration. <a href="http://%22A%20step-by-step%20guide%20to%20building%20a%20simple%20chess%C2%A0AI%20%22/">Lauri Hartikka does implement this in his tutorial</a>, but which position is better for a piece must be determined by the programmer, not the computer. I’d like to find a way for the computer to figure this out.</p><p>Going forward, there are other algorithms I’d like to try to solve these issues, as well as attempt to incorporate some form of machine learning.</p><p><em>Originally published at </em><a href="https://byanofsky.com/2017/07/06/building-a-simple-chess-ai/"><em>byanofsky.com</em></a><em> on July 6, 2017.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c84e14f4acf9" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Simple Blog: A Multi-User Blogging Framework]]></title>
            <link>https://medium.com/@byanofsky/simple-blog-a-multi-user-blogging-framework-e5bacfaa3416?source=rss-857b06cc363------2</link>
            <guid isPermaLink="false">https://medium.com/p/e5bacfaa3416</guid>
            <category><![CDATA[google-cloud-platform]]></category>
            <category><![CDATA[backend-development]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Brandon Yanofsky]]></dc:creator>
            <pubDate>Tue, 07 Feb 2017 02:05:24 GMT</pubDate>
            <atom:updated>2017-02-07T14:21:33.415Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/660/0*6ZhMn41_KcRaeNn8." /></figure><p>As part of my Full Stack Web Developer Nanodegree at <a href="https://www.udacity.com/">Udacity</a>, we were assigned the project of building a multi-user blogging software.</p><p>Its intent is to teach an intro to backend programming.</p><p>I built Simple Blog, a simple blogging framework.</p><p>It is built with Python using <a href="http://jinja.pocoo.org/">Jinja2 template engine,</a> and can be deployed to <a href="https://cloud.google.com/appengine/">Google App Engine</a>. It’s database is built with <a href="https://cloud.google.com/datastore/">Google Datastore</a> and connects to the application with <a href="https://cloud.google.com/appengine/docs/python/ndb/">NDB Datastore API</a>.</p><p>To handle encrypting passwords and authentication, I used the <a href="https://passlib.readthedocs.io/en/stable/">Passlib</a> Python library.</p><p>See a working example of Simple Blog:<br><a href="https://simple-blog-151718.appspot.com/">https://simple-blog-151718.appspot.com</a></p><p>Here is the GitHub repo for: <br><a href="https://github.com/byanofsky/simple-blog">https://github.com/byanofsky/simple-blog</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1010/1*qDrPn0nqunOLVpx0tf94vA.png" /><figcaption>Screenshot of Simple Blog’s homepage</figcaption></figure><h3>What It Does</h3><p>Udacity required some basic functionality to be included in the final project. This included:</p><ul><li>Users can create accounts</li><li>Account passwords are encrypted and stored in the database</li><li>Users can login and logout</li><li>Logged in users can create new posts, or edit and delete their existing posts</li></ul><p>I learned how to build this functionality during the Udacity course.</p><p>As recommended by Udacity, I expanded upon these capabilities by adding:</p><ul><li>Commenting — users can create comments; and edit/delete their own comments</li><li>Liking — users can like other users’ posts, and unlike ones they have already liked</li></ul><p>The course did not teach how to build this functionality; I had to learn these on my own to implement properly.</p><h3>What I Learned</h3><p>I won’t lie. I struggled through a few aspects of building Simple Blog.</p><p>But struggling through helped me learn quite a bit.</p><p>Here’s just some of what I learned:</p><h3>Ways To Improve</h3><p>There are a few things I’d still like to do to improve upon this application:</p><ol><li>I’d like to introduce some CSS to give it basic styling. But because I want this to be a framework, I want the styling to be easily changed or customized.</li><li>Right now when a post is displayed, it outputs as preformatted text. I’d like it to output HTML.</li><li>Add more functionality to the like, such as showing who else has liked a post.</li><li>Simple Blog was built to run on Google App Engine. I’d like to build it so it can run on other platforms (such as a server through AWS).</li><li>While user passwords are stored securely, if someone copies a cookie from one browser to another, they can be logged in to a user’s account. I’d like to research an implement a way to prevent this. I believe tokens may help with this, but need to learn more about them.</li><li>I want to build a more extensive user dashboard. Right now, user’s can log out and create a new post from the dashboard. It’d be nice to allow them to view their own posts, and view posts they’ve liked.</li></ol><p><em>Photo Credit: </em><a href="https://www.flickr.com/photos/128629824@N06/"><em>NOGRAN s.r.o.</em></a><em>, </em><a href="https://creativecommons.org/licenses/by/2.0/"><em>Some rights reserved</em></a></p><p><em>Originally published at </em><a href="https://byanofsky.com/2017/02/06/simple-blog-a-multi-user-blogging-framework/"><em>byanofsky.com</em></a><em> on February 7, 2017.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e5bacfaa3416" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Art, By A Neural Network]]></title>
            <link>https://medium.com/@byanofsky/art-by-a-neural-network-11a7a98052c4?source=rss-857b06cc363------2</link>
            <guid isPermaLink="false">https://medium.com/p/11a7a98052c4</guid>
            <category><![CDATA[neural-networks]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <dc:creator><![CDATA[Brandon Yanofsky]]></dc:creator>
            <pubDate>Mon, 30 Jan 2017 04:07:30 GMT</pubDate>
            <atom:updated>2017-01-30T06:17:22.852Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/660/0*aBsZGYYZVaBluCkh." /></figure><p><a href="https://byanofsky.com/2017/01/24/first-steps-into-deep-learning/">Udacity’s Deep Learning Nanodegree foundations course</a> has finally begun.</p><p>One of the first things we got to do was make art with a neural network.</p><p>Using <a href="https://github.com/lengstrom/fast-style-transfer">Logan Engstrom’s Fast Style Transfer</a>, I input different pictures into a trained neural network. The network then output that picture, but made in the style of a famous artist.</p><p>For example, The fast style transfer network was trained on this painting, “A Muse” by Pablo Picasso:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/300/0*c-qwRJz5vDhgmGVq." /></figure><p>I then provided the neural net with this picture of my girlfriend and me:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/300/0*q5YG6fjw666E56cq." /></figure><p>And the result is:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/660/0*kggjP5Jk_j67Zur6." /></figure><p>Admittedly, I do look a bit strange there.</p><p>I tried another. With the neural network trained on “The Scream”…</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/238/0*EqEU14EzJQF2ammh." /></figure><p>…I got this painting of my friends and me:</p><h3>“That’s cool, but don’t phones already do this? What’s so life-changing about this?”</h3><p>That was my first question when I heard about neural nets creating this type of art.</p><p>But after playing around with deep learning a bit, I realized 2 things:</p><ol><li>Yes, our phones can do this, but software like this is the of technology that actually powers these effects in our phones. It’s like learning to program 2 + 2 = 4. A calculator can already do that, but it’s the first step in learning to program.</li><li>While having a computers create art in the style of famous artists may not change the world, that same technology <strong>WILL</strong> do and <strong>ALREADY IS</strong> doing incredible things. Powering translation software, self-driving cars, computers that detect cancer, etc. Deep learning powers all of it.</li></ol><p>That’s what excites me so much about this!</p><p>Going from a computer recreating pictures in some artist’s style, all on its own, to world changing applications is not as huge a leap as it may initially seem.</p><p>Plus, seeing Grumpy Cat in the style of Van Gogh ain’t so bad.</p><h3>What’s Next?</h3><p>While I got the chance to play around with deep learning here a bit, I only understand the surface of it.</p><p>I can roughly explain the idea of what deep learning does, but can’t begin to explain how it works. That’s why there isn’t any technical information in this post.</p><p>But expect some technical info soon. Earlier today I spent some time building my very first neural network from scratch.</p><p>So keep an eye out for even cooler stuff coming soon!</p><p><em>Originally published at </em><a href="https://byanofsky.com/2017/01/29/art-by-a-neural-network/"><em>byanofsky.com</em></a><em> on January 30, 2017.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=11a7a98052c4" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>