DEV Community

Cover image for Write Code That Writes Code
Mohammad Amin Khakzadan
Mohammad Amin Khakzadan

Posted on

Write Code That Writes Code

We always write codes with our fingers, we always type on our keyboards, and we work hours and hours to create computer programs.

But things we write can be written by a computer. and currently, programming languages like C, C++, Python, Java, ... in the final compilation step will be translated to the machine byte codes, and that means programs that write codes.

But this should not be the end. We must write programs that can write codes in other programming languages like C, C++, Python, java, ruby or whatever else.

maybe that be a new programming language or some frameworks that change code structure or a text stream processor that translate text to something else.

I will show you a simple example for every subject I've mentioned, but that is not the only way you can do it.

a new programming language

During the time, we always hear about new programming languages that provide a set of features and obey a design philosophy, but most of them always copying other programming language principles, and they can't be used for the everyday use cases. But if we forget them, and try to create a new programming language from the zero ground with our creativity, that will bring us a whole of new ideas to accomplish our goals.

for example, think you want to make a simple text editor, a programming language for that purpose can be something like this:

OpenWindow
{
    text_area: TextArea[editable, fullsize]
    KeyPress('CTRL+s') =>
    {
        path = AskPath('Save As', 'Save', 'Cancel)
        open(path, 'wt').write(text_area.text)
    }
    KeyPress('CTRL+o') =>
    {
        path = AskPath('Open', 'Open', 'Cancel)
        text_area.text = open(path).read()
    }
}

or maybe you be an artist and want to draw some pixel arts:

use random, new_image

image = new_image([500, 500])
image.fill('Navy Blue')

repeat (40)
{
    image.draw_dot(
        random.position_range([0, 0], [image.width, 300]),
        random.color_range('bw:200', 'bw:256')
    )
}

image.draw_rectangle([0, 300], image.size, 'Dark Blue')

repeat(10)
{
    start = random.position_range([40, 200], [image.width - 40, 300])
    end = [start.x + random.choice(1, -1) * random.range(20, 35), 300]
    image.draw_rectangle(start, end, 'Dark Blue')
}

Can you guess what the program will draw?

or some programming languages like this one:

set total_words to zero.
open "article.txt" then,
    for each line,
        add number of words in line to total_words.
    end.
end.
print total_words.

Metaprogramming

If you understand how compilers work, what's really going on is not so much that Lisp has a strange syntax as that Lisp has no syntax. You write programs in the parse trees that get generated within the compiler when other languages are parsed. But these parse trees are fully accessible to your programs. You can write programs that manipulate them. In Lisp, these programs are called macros. They are programs that write programs.

Programs that write programs? When would you ever want to do that? Not very often, if you think in Cobol. All the time, if you think in Lisp. It would be convenient here if I could give an example of a powerful macro, and say there! how about that? But if I did, it would just look like gibberish to someone who didn't know Lisp; there isn't room here to explain everything you'd need to know to understand what it meant. In Ansi Common Lisp I tried to move things along as fast as I could, and even so I didn't get to macros until page 160.

source link: https://stackoverflow.com/questions/514644/what-exactly-is-metaprogramming

or a framework that can edit program structure, an example in python:

from auto_code_gene import python as py
import sys

writer = py.PyWriter(sys.stdout)
node = \
py.Function('parse_argv', 'argv', [
    py.For('arg', 'argv', [
        py.If("len(argv) == 0", [
            py.Raise('ValueError', py.Str('empty argument')),
        ]),
        py.If("arg == '-'", [
            py.Pass()
        ])
    ])
])

node.write(writer)

result:

def parse_argv(argv):
    for arg in argv:
        if len(argv) == 0:
            raise ValueError('empty argument')
        if arg == '-':
            pass

text stream processor

some programs that can translate this text:

INC stdlib.h
ST buffer:
    char *pntr, size_t start, size_t len, size_t size
    FN ${buffer}, allocate_buffer,
        pntr = malloc($size), start = 0, len = 0, size = $(size)

to this C file:

#include <stdlib.h>

struct buffer
{
    char *pntr;
    size_t start;
    size_t len;
    size_t size;
};

struct buffer *
allocate_buffer(size_t size)
{
    struct buffer *result;

    result = malloc(sizeof(struct buffer));
    if (result == NULL)
    {
        return NULL;
    }

    result->pntr = malloc(size);
    if (result->pntr == NULL)
    {
        free(result);
        return NULL;
    }

    result->start = 0;
    result->len = 0;
    result->size = size;

    return result;
}

Conclusion

Never write programs with your fingers, always write programs that make codes. and do it for each time you want to write something. because computers can automate the job.

Top comments (16)

Collapse
 
val_baca profile image
Valentin Baca • Edited

Compilers, transpilers, macros, metaprogramming are all powerful and can be incredibly useful. I've seen thousands of lines of code reduced to hundreds or even just dozens of lines of code. However, they shouldn't be what one goes to first and can severely impact clarity if not used judiciously. I wouldn't go so far as to say to "always" write programs that write code. Avoid overengineering. Sometimes you do just need the one-off script or program.

Nit pick: "code" is already plural, so the "s" in "codes" is redundant. "Write Code That Writes Code" (Edit: this isn't 100% correct either. See replies)

Collapse
 
jdknox profile image
Jeff

Just to nitpick the nitpick: "code" is technically uncountable, like "water." It can be both plural and singular. 😁

"Codes" can also be used properly, e.g., "She has two codes to crack," or "I have two different machine codes to deal with." So the distinction isn't merely pedantic. 😎

Collapse
 
val_baca profile image
Valentin Baca

You are correct. In referring to computer instructions, "code" is uncountable, not plural.

For others: english.stackexchange.com/question...

Collapse
 
mak12776 profile image
Mohammad Amin Khakzadan

In new programming languages we always have a level of abstraction, we have written programming languages to pave the way for us. And that means some works automated by computers.
For example, in the past that we have no programming language except assembly language, for comparing strings, programmers have to write 5 or 6 lines of code, but now we can compare two strings in python or ruby just by putting some equal signs between them. And that is automating the process of writing codes.
We can have more advanced programming languages, or other approaches that short the way of writing programs. But they not invented, and they are not exist.

Thanks for mentioning mistake.
I do not have enough knowledge of English language, but I can understand programming languages very well. 😃

Collapse
 
davehoran profile image
Dave Horan

Ironically, you mention that it would not be needed much with COBOL. In the early 80s when I was a teen, I used code generators all the time to create basic CRUD file maintenance programs that I would then modify for specific business logic. Since just the pre-modidied code was like 40 printed pages long (days of for matrix) it was crazy to write all that by hand. Manual typing errors alone could add days to debugging. The code generators guarantee some level of code consistency and quality, so you knew any problems introduced were from the additional manual code you added.

This is why I like a lot of the CLI tools for various frameworks that will generate the basic boilerplate for a component, model, etc for your app.

Metaprogramming has been around a long time thanks to 'lazy' (aka smart) developers leveraging DYI mindsets.

Collapse
 
itr13 profile image
Mikael Klages

Though I'm all for code that writes code, it should always be done in a way that is understandable, and preferably compile-time with type+syntax checking if possible.

Personally I've been using c# attributes and python decorators to automate a lot of code for me, and it has been delightful

Collapse
 
lakes_todd profile image
Todd Lakes

I believe that in the future, the computer software environment will be able to independently write the necessary code to create the necessary functions for a person. I am surprised that there is still no such thing. But modern technologies can help me write my research paper on special services. One of these websites is the paperial.com/write-my-research-paper I think this will be useful to many students. Students will be able to improve their skills through similar educational services and this will require a minimum of resources.

Collapse
 
juancarlospaco profile image
Juan Carlos

You are literally describing nim-lang.org

Collapse
 
mak12776 profile image
Mohammad Amin Khakzadan

That has come a part of the way. But that isn't complete and perfect. we can always have something better than what we already have. maybe a program that writes nim languages codes.

Collapse
 
balkac profile image
Kral Balkizar

I'm really frightening about the age, when code really starts to write code.

Collapse
 
mdhesari profile image
Mohammad Fazel

That is so true we need to foresee the future and make thimgs impler by inventing new approaches.

Good job

Collapse
 
triptych profile image
Andrew Wooldridge

Here's a link to their newsletter procjam.com/seeds/issues/3/

Collapse
 
triptych profile image
Andrew Wooldridge

Have you heard of Procjam? ( twitter.com/procjam ) you should take a look at their work and potentially collaborate perhaps?

Collapse
 
mak12776 profile image
Mohammad Amin Khakzadan

very good ideas for being generative, and best place for those who do not have time.

Collapse
 
wiltel492019 profile image
Wiltel492019

I don't understand your logic exactly!!!

Collapse
 
mak12776 profile image
Mohammad Amin Khakzadan • Edited

Have you ever tried to maintain a big and unmaintainable source code?