[{"content":" Typesetting # I have a lifelong interest in typography and book design. The Go-ecosytem currently is lacking a bit in terms of typographic support, at least compared to e.g. Rust. The Go standard library includes packages for font parsing and Unicode handling, but I am not aware of production-grade font or typesetting packages. That said, my intent is not to provide a production-grade toolset right now, as I currently do not have enough spare time to polish everything up. Still, the code may be useful for other applications.\nFor blog posts on more in-depth discussions around typography, head over to the blog-articles on this site, or to my developer deep-dive on my home page.\nUnicode Text Segmentation Algorithms Text processing applications need to segment text into pieces (words, sentences, paragraphs, …). From a typographic viewpoint, some languages present serious challenges for correct segmenting. The Unicode consortium publishes recommendations for text segmentation in their Unicode Annexes (UAX). UAX on Github OpenType Font Parser and Shaper This package provides access to OpenType font tables and features. The intended audience for this package are text shapers, such as HarfBuzz, and glyph rasterizers, such as FreeType. This is work in progress. opentype on Github ","date":"2 January 2021","externalUrl":null,"permalink":"/docs/typesetting/","section":"Software-Projects","summary":"I have a lifelong interest in typography and book design. The Go-ecosytem is lacking in terms of typographic support and I try to improve on this.","title":"Digital Typesetting","type":"docs"},{"content":" The Joy of Formal Languages # These are Open Source projects of mine around parsing and parser generators. For blog posts about these topics, take a look at the “Parsing” topic page.\nGoRGO, A Parsing Toolbox There is no shortage of parser generator, ranging from good old bison to ANTLR and various Go variants like gocc. All these tools have their value and I appreciate the availability of compiler-compilers with a lot of horse power. But on the other hand, sometimes I want something more compact, a smart and lightweight tool to generate an interpreter for a custom language. GoRGO on Github Poor Man's MetaPost This is an experimental fun project, currently without any practical purpose. The first draft used ANTLR as a parser generator, but I intend to migrate it to GoRGO as test case for GoRGO's capabilities. I don't strive for fancy graphics, but rather aim at simple figures. PMMP on Github ","date":"2 January 2021","externalUrl":null,"permalink":"/docs/parsing/","section":"Software-Projects","summary":"DSLs and all kinds of parsers have been a passion of mine since university. If you share this interest, check out the Go tools here.","title":"Grammars \u0026 Parsers","type":"docs"},{"content":" Why GoRGO? Every software developer hates repetitive tasks. What’s the point of being a programmer if you can’t delegate your chores to a machine? And as a backend developer you are most likely open to the idea to employ some kind of domain specific language (DSL). That’s where a compiler generator may come into play. There is no shortage of them, ranging from good old bison to ANTLR and various Go variants like gocc. Why develop another one? Because GoRGO is a little different.\nWhat is it about? # I have used many of the aforementioned tools extensively in my life, plus a handful of situations where I’ve written recursive descent parsers by hand. All these tools have their value and I appreciate the availability of compiler-compilers with a lot of horse power. But on the other hand, sometimes I want something more compact, a smart and lightweight tool to generate an interpreter for a custom language. And I want it in native Go, as this is what I currently use for Open Source. That’s what GoRGO strives to be.\nThe Name # The “RGO” in GoRGO stands for Right-derivated Grammar Gperations, which may sound all gibberish to you (and I wouldn’t blame you). But there’s a hint in this name: we will focus on LR-parsing, i.e., we will construct bottom-up parsers which produce right-derivations. That’s exactly what yacc et al do (unlike ANTLR, which produces LL-parsers), so no surprise there—or is it? In fact it should be, as DSL parsers these days are implemented with PEGs most of the time. But PEGs (parser expression grammars) are top-down, so why opt for bottom-up parsing?\nGorgosaurus Gorgo⋅saurus (fierce lizard ) was not quite as big or famous as Tyrannosaurus Rex, but dangerous nevertheless. It lived some 75 million years ago in Northern America, eating anything it came across. We will meet its cousin T-Rex again when we'll talk about TeREx, a term rewriter.\u0026nbsp;\nPEG parsers have a number of disadvantages for the careless user—which includes myself. Although I love their simplicity, they lack a certain foolproofness which I expect for ad-hoc DSLs. Most ad-hoc grammars people write contain ambiguous rules, and PEGs hide ambiguity rather than resolving it. On the other hand, we do not want programmers to have to fix shift|reduce-conflicts and the like. The tool should just eat my grammar! Therefore we revert to LR-parsers, acknowledging the fact that we have to convince the parser to not be so tough on its users.\nNo Code Generation # Parser generators (compiler compilers) usually generate source code. That’s often a good idea, as many of these tools can handle a multitude of host-languages. Moreover, Go has a mechanism for preprocessing and code-generation (go-generate) which is well suited for parser generators. However, for small DSLs I prefer to skip a code-generation step and rather create the parser in place and immediately run it.\nDigesting the grammar is always the first step. This results in a bunch of LR parse tables. Instead of saving these tables as source code into a file, we keep them in memory and provide them to a parser. Table generation is quick for small languages and we usually can afford to go through this step once per program execution.\nAmbiguous Grammars # Conventional parser generator do not handle ambiguous grammars well. Especially for ad-hoc DSLs, however, grammar ambiguity is quite common. Parser which can handle these kinds of grammars have been known for some time, but rarely gained popularity (bison’s GLR-feature is an exception to this rule and ANTLR mitigates many of these problems, too). GoRGO implements two flavors of bottom-up parsers which are able to cope with ambiguity: Earley parsing and GLR-parsing.\nDuring tests for various DSL tasks I came to love Earley-parsing. Sketching out a grammar, attaching it into an Earley parser and feeding it some sample input, all with a couple lines of code, is a satisfying experience. In theory Earley parsing can severly degrade in performance, but I have yet to come across such a case in practice. I will talk more on Earley-parsing in a different post.\nGoRGO is an ongoing experiment. Stay tuned for some real-world application stories.\n","date":"2 January 2021","externalUrl":null,"permalink":"/posts/why-gorgo/","section":"Articles","summary":"Conventional parser generator do not handle ambiguous grammars well. Especially for ad-hoc DSLs, however, grammar ambiguity is quite common. GoRGO implements two types of bottom-up parsers to deal with ambiguity: Earley parsing and GLR-parsing.","title":"LR-Parsing in Go","type":"posts"},{"content":" I stumbled across the problem of bidirectional text in terminals while trying to test a variant of the Unicode Bidirectional Algorithm. The Unicode consortium publishes a set of bidi test-cases, which suffer from being somewhat “non-visual”. At the end of the day you want to deal with real sentences in real languages and scripts. Preparing that, you face a peculiar problem: how do you display your test output? After all, UAX#9 is about visual ordering of characters. So we just print it to the terminal, do we? But things get confused quickly.\nHow Hard can It Be? # Sure, terminal applications have to manage some of the messy parts of type, just as browsers do: They need fonts with glyphs for almost any foreseeable script, but restricted to monospace. Text shaping is hard, but probably less so for monospaced fonts. And at least there are no difficulties with sophisticated line breaking, complicated layout with different font sizes, graphics, etc. And bidirectional text should be a solved problem. Or is it?\nTurns out for terminal emulators this is an especially tricky topic!\nA Conspiracy to Not Let You Bidi # I started my tests from the kitty terminal I use on MacOS. Let’s go small first, with just a single phrase in Hebrew:\nThis is the output of the original string, prior to any reordering logic from my test. I’ve not been surprised by the output of MacOS Terminal: obviously it recognizes Hebrew script as right-to-left (RTL) and the errorneous positioning of the ‘!’ is a result of me not specifying overall RTL context. But what about kitty? Perhaps I did get the logical (memory) representation of the phrase wrong, so let’s check by opening it in vim. Surprise: It looks different, depending on the terminal vim runs in. Strange…!\nWhen working on bidirectional text there is a requirement for text-editors to help developers enter the logical (memory) order of characters, instead of the visual order. Unfortunately only Emacs has an option to turn off interpreting bidi (these days I program in Go on VSCode, and I’m not alone in my struggles). But shouldn’t an editor like vim, running in a terminal’s raw mode, operate independent of what the terminal emulator considers clever behaviour for bidi? Obviously no.\nThe Brave Gnome # Diving deeper, I read up on attempts to standardize bidi handling, including in terminal emulators. After all, the majority of the world’s population use non-Latin scripts, many of them with non-LTR writing direction. But obviously, as of today the behavious of Mac OS Terminal is the best the industry could come up with. And for good reasons: A terminal is not primarily concerned with paragraphs of text, but rather with (from a typesetting perspective) funny combinations of characters, where application of Unicode recommendations simply falls flat.\nA smart guy named Egmont Koblinger, contributor to a lot of stuff around Linux terminals (joe editor, mc file manager, etc.), came up with a proposal for an updated standard for bidi handling in terminals. It recommends letting applications decide whether they want implicit or explicit bidi handling, the former more or less meaning the Unicode Bidi Algorithm applied by the terminal. When writing tests for bidi yourself, you most certainly prefer explicit mode, i.e., short-curcuiting the terminal’s cleverness.\nWhat’s best: these ideas have already been implemented in VTE, which underlies the Gnome Terminal window. I installed VTE3 on my Mac, included some lines of code in my test to force VTE in explicit mode, and it gave me this:\nNow this made me happy 😄! VTE shows me the real thing, the characters in logical (memory) order. While this is of no use to an end-user of terminals, I consider it very valuable for application developers, at least those who have to work on the fine points of international text handling. (VTE even has you covered if your intuition about logical order is from right to left.)\nWrap Up # Terminals, text-editors, IDEs and web browsers all conspire to make it hard to develop and test algorithms for handling of international text. But a brave Gnome offers the best of two worlds: a level-headed implicit mode for day-to-day usage, and an explicit mode for bidi-nerds. Thank you!\nI will try to wrap my learnings into a Go package, but at the same time I am aware that this is a tiny niche in a programming universe dominated by web applications, where the browser is expected to do all the heavy lifting. But that’s a different story.\n","date":"24 February 2021","externalUrl":null,"permalink":"/posts/bidi-in-terminal/","section":"Articles","summary":"Terminal applications have to manage some of the messy parts of type, just as browsers do. Right-to-left text is one of them.","title":"Bidi – What You See isn't What You Get","type":"posts"},{"content":" Text processing applications need to segment text into pieces. Segments may be word, sentences, paragraphs and so on. For western languages this is not too hard of a problem, but it may become an involved endeavor if you consider Arabic or Asian languages. From a typographic viewpoint some of these languages present serious challenges for correct segmenting. The Unicode consortium publishes recommendations and algorithms for various aspects of text segmentation in their Unicode Annexes (UAX).\nText Segmentation in Go(lang) # There exist a number of Unicode standards describing best practices for text segmentation. Unfortunately, implementations in Go are sparse. Marcel van Lohuizen from the Go Core Team seems to be working on text segmenting, but with low priority. In the long run, it will be best to wait for the standard library to include functions for text segmentation. However, for now I will implement my own.\nTradeoffs # Handling character data is often part of the inner loop of applications, requiring fast implementations. The flip side are tiring implementations, with lots and lots of boring code. This is something I learned from working on text processing: I am even more susceptible to boredom than I suspected. In the Unicode committee world there are lots of brave people involved who spend a lot of energy on getting the details right. Progress in international language processing wouldn’t be possible without them–my thanks to every single one of them.\nI need a different approach, however. If your concern is all about efficiency and performance, you will probably shy away from U⋮A⋮X. I try to find a balance between performance and readability. Unicode algorithms are often stated as formal rules. Implementations in the wild usually follow these descriptions in a procedural manner, resulting in hard-to-read code for travelling back and forth in byte buffers. I won’t do that. Instead I prefer to design a programming environment which allows me to put in the problem description (i.e., the UAX-rules) and get a working algorithm out. Oftentimes that’s tougher and more time-consuming than a straightforward implementation–but hey!, Open Source development is about fun.\n","date":"18 January 2021","externalUrl":null,"permalink":"/posts/perils-of-segmenting-text/","section":"Articles","summary":"Text processing applications need to segment text into pieces. Segments may be word, sentences, paragraphs and so on. From a typographic viewpoint some languages present serious challenges for correct segmenting.","title":"⋮The⋮ ⋮Per⋮ils⋮ ⋮of⋮ ⋮Seg⋮ment⋮ing⋮ ⋮Text⋮","type":"posts"},{"content":" Putting an Earley-Parser to Work These days I spend some evenings programming a variant of MetaPost, a DSL for diagrams and illustrations. MetaPost inherits much of its syntax from MetaFont, which has been designed by D. E. Knuth. Mr Knuth is the “father of LR-parsing,” so one would expect some interesting language features in MetaPost—and we are not disappointed!\nWhat MetaPost does # MetaPost’s unique selling point is its ability to solve linear equations. In some situations, you’d rather not specifiy a point position, but let the computer figure out its location. Let’s take a look at an example:\nDon’t worry if this looks a bit like your last mathematics exam. The unique part are the lines like A'=whatever[A,C];. This is MetaPost’s way of requesting a point A\u0026rsquo; to lie somewhere on the line between points A and C. Given that A\u0026rsquo; should lie on [A,C] as well as on [B,D], MetaPost will find the intersection point by solving a set of linear equations. That’s a pretty cool feature! However, we will talk about MetaPost\u0026rsquo;s features in another post.\nVariables: It’s complicated… # The MetaPost language is designed to be somewhat reminiscent of mathematical writing. This is especially noticeable with its conventions for variable names. You already caught a glimpse of that with those primed point variables (A\u0026rsquo;), but that’s not the end of it. MetaPost will happily digest identifiers like \\(z'r\\) (denoted as z'.r) and \\(x_1\\) (x_1). Add to this the ability to handle fractions as numeric input, you are free to instruct MetaPost to calculate\n$$-{1\\over3}x_1$$ by typing -1/3x1. That might not appeal to everyone, but it sure is easy to type and MetaPost will usually understand what you had in mind.\nThose variable names look innocent enough, but from a parser’s point they carry slightly different semantics than with other programming languages. Let’s consider the input 7 - -a1r. By now you propably could guess that this means “\\(7-{-a_{1r}}\\).” Setting aside that you should enclose the second term in parenthesis anyway, put yourself in the shoes of the parser: it will see a sequence of tokens like 7 - - a 1 r. And just when you successfully taught your parser to accept it, someone types in y = 7 - - 1 / 3 x [ n - 1 ], intending to express the equation\n$$y = 7 - {-{1\\over 3} x_{n-1}}$$ Let’s try with Python:\n\u0026gt;\u0026gt;\u0026gt; n = 2 # pre-set subscript variable n \u0026gt;\u0026gt;\u0026gt; y = 7 - - 1 / 3 x [ n - 1 ] File \u0026#34;\u0026lt;stdin\u0026gt;\u0026#34;, line 1 y = 7 - - 1 / 3 x [ n - 1 ] ^ SyntaxError: invalid syntax We expected that, didn’t we? The error doesn’t result from the fact that x is an unknown quantity; it’s just that Python cannot handle the syntax: it misses a ‘*’ before the x. Now let’s have MetaPost a go:\nThis is MetaPost, version 1.999 **\\relax *n:=2; % pre-set subscript variable n *y = 7 - - 1 / 3 x [ n - 1 ]; *show y; \u0026gt;\u0026gt; 0.33333x1+7 The last line is MetaPost’s way of telling us that variable y is dependent on \\(x_1\\), which is of unknown value yet. It is worth noting that [n-1] is not your usual array indexing, but rather the “generation” of a mathematical subscript. Just for fun, create an irrational subscript:\n*y=x[sqrt 2]; *showvariable x x[]=numeric x1.41422=y Earley’s Attempt # Of course part of the complications arise from the usual unary plus/minus problem. But the notation of scalar prefixes for variables makes it a bit more difficult to implement. John Hobby, the author of MetaPost, has been kind enough to publish a BNF grammar for MetaPost by John Hobby (pp. 92–97). Remarkably, it contains the rule\n⟨scalar multiplication op ⟩ → + | −\n| ⟨ ‘⟨number or fraction ⟩’ not followed by ‘⟨add op ⟩ ⟨number ⟩’ ⟩\na strong hint that a dose of lookahead has been required to implement scalar prefixes (a.k.a. scalar multiplication op).\nGoRGO’s Earley-parser has (yet) no feature for operator precedence, so I was unsure of how difficult it would be to implement scalar prefixes. Turned out, not difficult at all—it worked first go! (Well, technically that’s a lie, because I ran into a subtle bug of the Earley parser code, but that’s a different story.) One especially pretty feature of Earley parsers is that you can watch them think. Doing so, I found the parser’s default behaviour for certain kinds of ambiguity spot on for the problem. The relevant rules of the MetaPost grammar had to be slightly adapted to get rid of the scanner hack and actually resulted in an easier to read version.\n⟨tertiary ⟩ → ⟨secondary ⟩\n| ⟨tertiary ⟩ PlusOrMinus ⟨secondary ⟩\n⟨primary ⟩ → ⟨atom ⟩\n| PlusOrMinus ⟨primary ⟩\n⟨atom ⟩ → ⟨variable ⟩\n| Signed ⟨variable ⟩\n(‘Signed’ is a number or fraction with an optional unary sign).\nUp to now it works just fine. Let’s see what other curious language features await.\n","date":"10 December 2020","externalUrl":null,"permalink":"/posts/parsing-metapost/","section":"Articles","summary":"The MetaPost language is reminiscent of mathematical writing. Its variable names look innocent enough, but from a parser’s point of view they carry different semantics than with other programming languages.","title":"Parsing MetaPost","type":"posts"},{"content":"","date":"24 February 2021","externalUrl":null,"permalink":"/posts/","section":"Articles","summary":"","title":"Articles","type":"posts"},{"content":"","date":"24 February 2021","externalUrl":null,"permalink":"/tags/bidi/","section":"Tags","summary":"","title":"Bidi","type":"tags"},{"content":"","date":"24 February 2021","externalUrl":null,"permalink":"/tags/","section":"Tags","summary":"","title":"Tags","type":"tags"},{"content":"","date":"24 February 2021","externalUrl":null,"permalink":"/tags/terminal/","section":"Tags","summary":"","title":"Terminal","type":"tags"},{"content":"","date":"24 February 2021","externalUrl":null,"permalink":"/tags/unicode/","section":"Tags","summary":"","title":"Unicode","type":"tags"},{"content":"This is my coding playground. I don’t spend much daytime on professional software projects anymore, so what’s here is driven by curiosity and fun.\nExplore Topics # Digital Typesetting I have a lifelong interest in typography and book design. The Go-ecosytem is lacking in terms of typographic support and I try to improve on this. Grammars \u0026amp; Parsers DSLs and all kinds of parsers have been a passion of mine since university. If you share this interest, check out the Go tools here. ","date":"24 February 2021","externalUrl":null,"permalink":"/","section":"Welcome","summary":"This is my coding playground. I don’t spend much daytime on professional software projects anymore, so what’s here is driven by curiosity and fun.\n","title":"Welcome","type":"page"},{"content":"","date":"2 January 2021","externalUrl":null,"permalink":"/tags/gorgo/","section":"Tags","summary":"","title":"GoRGO","type":"tags"},{"content":"","date":"2 January 2021","externalUrl":null,"permalink":"/tags/lr-parsing/","section":"Tags","summary":"","title":"LR-Parsing","type":"tags"},{"content":"","date":"2 January 2021","externalUrl":null,"permalink":"/tags/parser-generator/","section":"Tags","summary":"","title":"Parser-Generator","type":"tags"},{"content":"","date":"2 January 2021","externalUrl":null,"permalink":"/docs/","section":"Software-Projects","summary":"","title":"Software-Projects","type":"docs"},{"content":"","date":"10 December 2020","externalUrl":null,"permalink":"/tags/earley/","section":"Tags","summary":"","title":"Earley","type":"tags"},{"content":"","date":"10 December 2020","externalUrl":null,"permalink":"/tags/metapost/","section":"Tags","summary":"","title":"MetaPost","type":"tags"},{"content":"","externalUrl":null,"permalink":"/categories/","section":"Categories","summary":"","title":"Categories","type":"categories"},{"content":"","externalUrl":null,"permalink":"/series/","section":"Series","summary":"","title":"Series","type":"series"}]