DEV Community

Matheus
Matheus

Posted on

One-line control structure parsing


Hello. I'm writing this post as a matter of contribution. I forked Tcsh, and added some features. My most-recent contribution is on one-line control structure parsing. I'm currently working on an implementation to parse control structures in a single line, as in Bourne shells.

It's well known that, e.g., foreach n ( * ) ; echo $n ; end doesn't work on any C shell. The line is parsed as a whole before further action is taken. The issue here is that ; and a line feed can't be used interchangeably. This work is an attempt to implement this interchangeability.

At first, I thought on implementing this in sh.func.c, the source relating to built-in commands. The work was supposed to create and run temporary functions. However, I realized this would be dangerous and ineffective. Therefore, the implementation is now residing in sh.sem.c, the source relating to post-parsing execution. I parse semicolons into a new node mode (NODE_LINE). I implemented a new mode (F_LINE). I "reparse" the entire tree, setting the F_LINE bit to every command node (NODE_COMMAND). Then, in execute(), I walk through the entire tree, analyzing which of the NODE_COMMAND entries contain the F_LINE mode. The node shall be saved in a circular linked list for each containing the F_LINE mode. Next, the circular linked list is analyzed from search(). search() shall perform a recursive operation, and analyze the opening and enclosing block for each keyword.

Because I first tried to implement this on top of a temporary function, I altered how semicolons are parsed. Notably, the command-line must end with a semicolon. This is only true when a semicolon is inserted. E.g.: echo hello ; echo world ;.

Moreover, I guess this implementation shall make a good companion to aliases. Even though I've worked on the function built-in, I realized aliases may make a great fit for functions. With this ongoing implementation on one-line control structure parsing, aliases may come handy for functions.

alias myfunc 'if \!^ then ; echo hello ; else ; echo bye ; endif ;'
Enter fullscreen mode Exit fullscreen mode

This might be ugly, but is one way to implement functions.

I'm seeking for testers. The implementation is done.

I'd appreciate for contributions and feedback.

Thank you.

Top comments (0)