The First C code I Ever Wrote
Learing to program is hard ass work.
I've been writing code for thiry years. I've done Perl, Ruby, Python, JavaScript, HTML, XSLT, CSS, Lisp, Lua, and Rust. But, I've never written in C. Until today.
I'm working on a Tree-sitter parser for the file format I'm making. It'll let me add syntax highlighting to my text editor which is a huge quality-of-life imporvement. The dive into C is because the basic features available for Tree-sitter parsers don't cover all my use cases. Creating an extension is required and those are written in C.
And, Away We Go
The code is a bit long. So, I put it at the bottom of the page. It took five or six hours to come up with. That may seem like a long time for that much code, but it's not. Most of the time was spent learning enough about C to be able to get things working.
Said another way, writing the code was the easy part. Figuring out _what__ to write is what took all the time.
The Ingredients
I used three references/resources to get me going:
-
The Tree-sitter "External Scanners" Documentation^docs^^
-
The source code of another parser that uses C^code^^
-
The LearnXinYminutes C examples^learn^^
I could have done it without the source code sample, but it probably saved me half an hour of experimenting and troulbeshooting by acting as an reference example.
Learning The Language
I don't know how much time I spent going through the C page of Learn X In Y Minutues. I'd guess half an hour, but I was skimming for parts of it. And, I didn't really learn what I was doing. Really, I was just looking for code I could copy/paste to get me going.
def terminator(lexer, pattern):
lexer.mark_end()
chars = [ord(char) for char in pattern]
tracker = 0
while not lexer.eof():
if lexer.lookahead() == chars[tracker]:
tracker += 1
lexer.advance()
if tracker == len(chars):
return True
else:
tracker = 0
lexer.advance()
lexer.mark_end()
return False
Reference
My main resource for figuring out what to do. I would have strugged with some parts of it if it wasn't for being able to look at the source code sample. Genearlly speaking though, it's quality documentation
Reference
I didn't end up using much of anything from this, but just seeing the file helped me get an idea of what I needed to do. The Tree-sitter docs describe most of what needs to be done, but there's nothing like being able to look at a sample of working code
Reference
This is the page discussing "lookahead" searches (which tree-sitter doesn't support natively) that lead me to the source code
Reference
This was my first time really using this site. It covera a bunch of stuff and I couldn't do most of it without going back to the docs, but it got me far enough along to figure out a basic. solution.