Categories
Posts in this category
- Current State of Exceptions in Rakudo and Perl 6
- Meet DBIish, a Perl 6 Database Interface
- doc.perl6.org and p6doc
- Exceptions Grant Report for May 2012
- Exceptions Grant Report -- Final update
- Perl 6 Hackathon in Oslo: Be Prepared!
- Localization for Exception Messages
- News in the Rakudo 2012.05 release
- News in the Rakudo 2012.06 release
- Perl 6 Hackathon in Oslo: Report From The First Day
- Perl 6 Hackathon in Oslo: Report From The Second Day
- Quo Vadis Perl?
- Rakudo Hack: Dynamic Export Lists
- SQLite support for DBIish
- Stop The Rewrites!
- Upcoming Perl 6 Hackathon in Oslo, Norway
- Pattern Matching and Unpacking
- Rakudo's Abstract Syntax Tree
- The REPL trick
- A shiny perl6.org site
- Creating an entry point for newcomers
- An offer for software developers: free IRC logging
- Sprixel, a 6 compiler powered by JavaScript
- Announcing try.rakudo.org, an interactive Perl 6 shell in your browser
- Another perl6.org iteration
- Blackjack and Perl 6
- Why I commit Crud to the Perl 6 Test Suite
- This Week's Contribution to Perl 6 Week 5: Implement Str.trans
- This Week's Contribution to Perl 6
- This Week's Contribution to Perl 6 Week 8: Implement $*ARGFILES for Rakudo
- This Week's Contribution to Perl 6 Week 6: Improve Book markup
- This Week's Contribution to Perl 6 Week 2: Fix up a test
- This Week's Contribution to Perl 6 Week 9: Implement Hash.pick for Rakudo
- This Week's Contribution to Perl 6 Week 11: Improve an error message for Hyper Operators
- This Week's Contribution to Perl 6 - Lottery Intermission
- This Week's Contribution to Perl 6 Week 3: Write supporting code for the MAIN sub
- This Week's Contribution to Perl 6 Week 1: A website for proto
- This Week's Contribution to Perl 6 Week 4: Implement :samecase for .subst
- This Week's Contribution to Perl 6 Week 10: Implement samespace for Rakudo
- This Week's Contribution to Perl 6 Week 7: Implement try.rakudo.org
- What is the "Cool" class in Perl 6?
- Report from the Perl 6 Hackathon in Copenhagen
- Custom operators in Rakudo
- A Perl 6 Date Module
- Defined Behaviour with Undefined Values
- Dissecting the "Starry obfu"
- The case for distributed version control systems
- Perl 6: Failing Softly with Unthrown Exceptions
- Perl 6 Compiler Feature Matrix
- The first Perl 6 module on CPAN
- A Foray into Perl 5 land
- Gabor: Keep going
- First Grant Report: Structured Error Messages
- Second Grant Report: Structured Error Messages
- Third Grant Report: Structured Error Messages
- Fourth Grant Report: Structured Error Messages
- Google Summer of Code Mentor Recap
- How core is core?
- How fast is Rakudo's "nom" branch?
- Building a Huffman Tree With Rakudo
- Immutable Sigils and Context
- Is Perl 6 really Perl?
- Mini-Challenge: Write Your Prisoner's Dilemma Strategy
- List.classify
- Longest Palindrome by Regex
- Perl 6: Lost in Wonderland
- Lots of momentum in the Perl 6 community
- Monetize Perl 6?
- Musings on Rakudo's spectest chart
- My first executable from Perl 6
- My first YAPC - YAPC::EU 2010 in Pisa
- Trying to implement new operators - failed
- Programming Languages Are Not Zero Sum
- Perl 6 notes from February 2011
- Notes from the YAPC::EU 2010 Rakudo hackathon
- Let's build an object
- Perl 6 is optimized for fun
- How to get a parse tree for a Perl 6 Program
- Pascal's Triangle in Perl 6
- Perl 6 in 2009
- Perl 6 in 2010
- Perl 6 in 2011 - A Retrospection
- Perl 6 ticket life cycle
- The Perl Survey and Perl 6
- The Perl 6 Advent Calendar
- Perl 6 Questions on Perlmonks
- Physical modeling with Math::Model and Perl 6
- How to Plot a Segment of a Circle with SVG
- Results from the Prisoner's Dilemma Challenge
- Protected Attributes Make No Sense
- Publicity for Perl 6
- PVC - Perl 6 Vocabulary Coach
- Fixing Rakudo Memory Leaks
- Rakudo architectural overview
- Rakudo Rocks
- Rakudo "star" announced
- My personal "I want a PONIE" wish list for Rakudo Star
- Rakudo's rough edges
- Rats and other pets
- The Real World Strikes Back - or why you shouldn't forbid stuff just because you think it's wrong
- Releasing Rakudo made easy
- Set Phasers to Stun!
- Starry Perl 6 obfu
- Recent Perl 6 Developments August 2008
- The State of Regex Modifiers in Rakudo
- Strings and Buffers
- Subroutines vs. Methods - Differences and Commonalities
- A SVG plotting adventure
- A Syntax Highlighter for Perl 6
- Test Suite Reorganization: How to move tests
- The Happiness of Design Convergence
- Thoughts on masak's Perl 6 Coding Contest
- The Three-Fold Function of the Smart Match Operator
- Perl 6 Tidings from September and October 2008
- Perl 6 Tidings for November 2008
- Perl 6 Tidings from December 2008
- Perl 6 Tidings from January 2009
- Perl 6 Tidings from February 2009
- Perl 6 Tidings from March 2009
- Perl 6 Tidings from April 2009
- Perl 6 Tidings from May 2009
- Perl 6 Tidings from May 2009 (second iteration)
- Perl 6 Tidings from June 2009
- Perl 6 Tidings from August 2009
- Perl 6 Tidings from October 2009
- Timeline for a syntax change in Perl 6
- Visualizing match trees
- Want to write shiny SVG graphics with Perl 6? Port Scruffy!
- We write a Perl 6 book for you
- When we reach 100% we did something wrong
- Where Rakudo Lives Now
- Why Rakudo needs NQP
- Why was the Perl 6 Advent Calendar such a Success?
- What you can write in Perl 6 today
- Why you don't need the Y combinator in Perl 6
- You are good enough!
Wed, 17 Apr 2013
The REPL trick
Permanent link
A recent discussion on IRC prompted me to share a small but neat trick with you.
If there are things you want to do quite often in the Rakudo REPL (the interactive "Read-Evaluate-Print Loop"), it makes sense to create a shortcut for them. And creating shortcuts for often-used stuff is what programming languages excel at, so you do it right in Perl module:
use v6; module REPLHelper; sub p(Mu \x) is export { x.^mro.map: *.^name; }
I have placed mine in $HOME/.perl6/repl.
And then you make sure it's loaded automatically:
$ alias p6repl="perl6 -I$HOME/.perl6/repl/ -MREPLHelper" $ p6repl > p Int Int Cool Any Mu >
Now you have a neat one-letter function which tells you the parents of an object or a type, in method resolution order. And a way to add more shortcuts when you need them.
Sun, 31 Mar 2013
Rakudo's Abstract Syntax Tree
Permanent link
After or while a compiler parses a program, the compiler usually translates the source code into a tree format called Abstract Syntax Tree, or AST for short.
The optimizer works on this program representation, and then the code generation stage turns it into a format that the platform underneath it can understand. Actually I wanted to write about the optimizer, but noticed that understanding the AST is crucial to understanding the optimizer, so let's talk about the AST first.
The Rakudo Perl 6 Compiler uses an AST
format called QAST. QAST nodes derive from the common superclass
QAST::Node, which sets up the basic structure of all QAST
classes. Each QAST node has a list of child nodes, possibly a hash map for
unstructured annotations, an attribute (confusingly) named node
for storing the lower-level parse tree (which is used to extract line numbers
and context), and a bit of extra infrastructure.
The most important node classes are the following:
- QAST::Stmts
- A list of statements. Each child of the node is considered a separate statement.
- QAST::Op
- A single operation that usually maps to a primitive operation of the underlying platform, like adding two integers, or calling a routine.
- QAST::IVal, QAST::NVal, QAST::SVal
- Those hold integer, float ("numeric") and string constants respectively.
- QAST::WVal
- Holds a reference to a more complex object (for example a class) which is serialized separately.
- QAST::Block
- A list of statements that introduces a separate lexical scope.
- QAST::Var
- A variable
- QAST::Want
- A node that can evaluate to different child nodes, depending on the context it is compiled it.
To give you a bit of a feel of how those node types interact, I want to give a few examples of Perl 6 examples, and what AST they could produce. (It turns out that Perl 6 is quite a complex language under the hood, and usually produces a more complicated AST than the obvious one; I'll ignore that for now, in order to introduce you to the basics.)
Ops and Constants
The expression 23 + 42 could, in the simplest case, produce
this AST:
QAST::Op.new(
:op('add'),
QAST::IVal.new(:value(23)),
QAST::IVal.new(:value(42)),
);
Here an QAST::Op encodes a primitive operation, an addition of
two numbers. The :op argument specifies which operation to use.
The child nodes are two constants, both of type QAST::IVal, which
hold the operands of the low-level operation add.
Now the low-level add operation is not polymorphic, it always
adds two floating-point values, and the result is a floating-point value
again. Since the arguments are integers and not floating point values, they
are automatically converted to float first. That's not the desired semantics for Perl 6; actually the operator
+ is implemented as a subroutine of name
&infix:<+>, so the real generated code is closer to
QAST::Op.new(
:op('call'),
:name('&infix:<+>'), # name of the subroutine to call
QAST::IVal.new(:value(23)),
QAST::IVal.new(:value(42)),
);
Variables and Blocks
Using a variable is as simple as writing
QAST::Var.new(:name('name-of-the-variable')), but it must be declared
first. This is done with QAST::Var.new(:name('name-of-the-variable'),
:decl('var'), :scope('lexical')).
But there is a slight caveat: in Perl 6 a variable is always scoped to a
block. So while you can't ordinarily mention a variable prior to its
declaration, there are indirect ways to achieve that (lookup by name, and
eval(), to name just two).
So in Rakudo there is a convention to create QAST::Block nodes
with two QAST::Stmts children. The first holds all the
declarations, and the second all the actual code. That way all the declaration
always come before the rest of the code.
So my $x = 42; say $x compiles to roughly this:
QAST::Block.new(
QAST::Stmts.new(
QAST::Var.new(:name('$x'), :decl('var'), :scope('lexical')),
),
QAST::Stmts.new(
QAST::Op.new(
:op('p6store'),
QAST::Var.new(:name('$x')),
QAST::IVal.new(:value(42)),
),
QAST::Op.new(
:op('call'),
:name('&say'),
QAST::Var.new(:name('$x')),
),
),
);
Polymorphism and QAST::Want
Perl 6 distinguishes between native types and reference types. Native types are closer to the machine, and their type name is always lower case in Perl 6.
Integer literals are polymorphic in that they can be either a native
int or a "boxed" reference type Int.
To model this in the AST, QAST::Want nodes can contain
multiple child nodes. The compile-time context decides which of those is
acutally used.
So the integer literal 42 actually produces not just a simple
QAST::IVal node but rather this:
QAST::Want.new(
QAST::WVal(Int.new(42)),
'Ii',
QAST::Ival(42),
)
(Note that Int.new(42) is just a nice notation to indicate a
boxed integer object; it doesn't quite work like this in the code that
translate Perl 6 source code into ASTs).
The first child of a QAST::Want node is the one used by
default, if no other alternative matches. The comes a list where the elements
with odd indexes are format specifications (here Ii for
integers) and the elements at even-side indexes are the AST to use in that
case.
An interesting format specification is 'v' for void context,
which is always chosen when the return value from the current expression isn't
used at all. In Perl 6 this is used to eagerly evaluate lazy lists that are
used in void context, and for several optimizations.
Tue, 12 Feb 2013
Pattern Matching and Unpacking
Permanent link
When talking about pattern matching in the context of Perl 6, people usually think about regex or grammars. Those are indeed very powerful tools for pattern matching, but not the only one.
Another powerful tool for pattern matching and for unpacking data structures uses signatures.
Signatures are "just" argument lists:
sub repeat(Str $s, Int $count) { # ^^^^^^^^^^^^^^^^^^^^ the signature # $s and $count are the parameters return $s x $count }
Nearly all modern programming languages have signatures, so you might say: nothing special, move along. But there are two features that make them more useful than signatures in other languages.
The first is multi dispatch, which allows you to write several routines with the name, but with different signatures. While extremely powerful and helpful, I don't want to dwell on them. Look at Chapter 6 of the "Using Perl 6" book for more details.
The second feature is sub-signatures. It allows you to write a signature for a sigle parameter.
Which sounds pretty boring at first, but for example it allows you to do declarative validation of data structures. Perl 6 has no built-in type for an array where each slot must be of a specific but different type. But you can still check for that in a sub-signature
sub f(@array [Int, Str]) { say @array.join: ', '; } f [42, 'str']; # 42, str f [42, 23]; # Nominal type check failed for parameter ''; # expected Str but got Int instead in sub-signature # of parameter @array
Here we have a parameter called @array, and it is followed by
a square brackets, which introduce a sub-signature for an array. When calling
the function, the array is checked against the signature (Int,
Str), and so if the array doesn't contain of exactly one Int and one
Str in this order, a type error is thrown.
The same mechanism can be used not only for validation, but also for unpacking, which means extracting some parts of the data structure. This simply works by using variables in the inner signature:
sub head(*@ [$head, *@]) { $head; } sub tail(*@ [$, *@tail]) { @tail; } say head <a b c >; # a say tail <a b c >; # b c
Here the outer parameter is anonymous (the @), though it's
entirely possible to use variables for both the inner and the outer
parameter.
The anonymous parameter can even be omitted, and you can write sub
tail( [$, *@tail] ) directly.
Sub-signatures are not limited to arrays. For working on arbitrary objects, you surround them with parenthesis instead of brackets, and use named parameters inside:
multi key-type ($ (Numeric :$key, *%)) { "Number" } multi key-type ($ (Str :$key, *%)) { "String" } for (42 => 'a', 'b' => 42) -> $pair { say key-type $pair; } # Output: # Number # String
This works because the => constructs a Pair, which has a
key and a value attribute. The named parameter
:$key in the sub-signature extracts the attribute
key.
You can build quite impressive things with this feature, for example red-black tree balancing based on multi dispatch and signature unpacking. (More verbose explanation of the code.) Most use cases aren't this impressive, but still it is very useful to have occasionally. Like for this small evaluator.
Sun, 19 Aug 2012
Quo Vadis Perl?
Permanent link
The last two days we had a gathering in town named Perl (yes, a place with that name exists). It's a lovely little town next to the borders to France and Luxembourg, and our meeting was titled "Perl Reunification Summit".
Sadly I only managed to arrive in Perl on Friday late in the night, so I missed the first day. Still it was totally worth it.
We tried to answer the question of how to make the Perl 5 and the Perl 6 community converge on a social level. While we haven't found the one true answer to that, we did find that discussing the future together, both on a technical and on a social level, already brought us closer together.
It was quite a touching moment when Merijn "Tux" Brand explained that he was skeptic of Perl 6 before the summit, and now sees it as the future.
We also concluded that copying API design is a good way to converge on a technical level. For example Perl 6's IO subsystem is in desperate need of a cohesive design. However none of the Perl 6 specification and the Rakudo development team has much experience in that area, and copying from successful Perl 5 modules is a viable approach here. Path::Class and IO::All (excluding the crazy parts) were mentioned as targets worth looking at.
There is now also an IRC channel to continue our discussions -- join
#p6p5 on irc.perl.org if you are interested.
We also discussed ways to bring parallel programming to both perls. I missed most of the discussion, but did hear that one approach is to make easier to send other processes some serialized objects, and thus distribute work among several cores.
Patrick Michaud gave a short ad-hoc presentation on implicit parallelism in Perl 6. There are several constructs where the language allows parallel execution, for example for Hyper operators, junctions and feeds (think of feeds as UNIX pipes, but ones that allow passing of objects and not just strings). Rakudo doesn't implement any of them in parallel right now, because the Parrot Virtual Machine does not provide the necessary primitives yet.
Besides the "official" program, everybody used the time in meat space to discuss their favorite projects with everybody else. For example I took some time to discuss the future of doc.perl6.org with Patrick and Gabor Szabgab, and the relation to perl6maven with the latter. The Rakudo team (which was nearly completely present) also discussed several topics, and I was happy to talk about the relation between Rakudo and Parrot with Reini Urban.
Prior to the summit my expectations were quite vague. That's why it's hard for me to tell if we achieved what we and the organizers wanted. Time will tell, and we want to summarize the result in six to nine months. But I am certain that many participants have changed some of their views in positive ways, and left the summit with a warm, fuzzy feeling.
I am very grateful to have been invited to such a meeting, and enjoyed it greatly. Our host and organizers, Liz and Wendy, took care of all of our needs -- travel, food, drinks, space, wifi, accommodation, more food, entertainment, food for thought, you name it. Thank you very much!
Update: Follow the #p6p5 hash tag on twitter if you want to read more, I'm sure other participants will blog too.
Other blogs posts on this topic: PRS2012 – Perl5-Perl6 Reunification Summit by mdk and post-yapc by theorbtwo
Tue, 17 Jul 2012
Stop The Rewrites!
Permanent link
What follows is a rant. If you're not in the mood to read a rant right now, please stop and come back in an hour or two.
The Internet is full of people who know better than you how to manage your open source project, even if they only know some bits and pieces about it. News at 11.
But there is one particular instance of that advice that I hear often applied to Rakudo Perl 6: Stop the rewrites.
To be honest, I can fully understand the sentiment behind that advice. People see that it has taken us several years to get where we are now, and in their opinion, that's too long. And now we shouldn't waste our time with rewrites, but get the darn thing running already!
But Software development simply doesn't work that way. Especially not if your target is moving, as is Perl 6. (Ok, Perl 6 isn't moving that much anymore, but there are still areas we don't understand very well, so our current understanding of Perl 6 is a moving target).
At some point or another, you realize that with your current design, you can only pile workaround on top of workaround, and hope that the whole thing never collapses.

Image courtesy of sermoa
Those people who spread the good advice to never do any major rewrites again, they never address what you should do when you face such a situation. Build the tower of workarounds even higher, and pray to Cthulhu that you can build it robust enough to support a whole stack of third-party modules?
Curiously this piece of advice occasionally comes from people who otherwise know a thing or two about software development methodology.
I should also add that since the famous "nom" switchover, which admittedly caused lots of fallout, we had three major rewrites of subsystems (longest-token matching of alternative, bounded serialization and qbootstrap), All three of which caused no new test failures, and two of which caused no fallout from the module ecosystem at all. In return, we have much faster startup (factor 3 to 4 faster) and a much more correct regex engine.
Wed, 04 Jul 2012
doc.perl6.org and p6doc
Permanent link
Background
Earlier this year I tried to assess the readiness of the Perl 6 language, compilers, modules, documentation and so on. While I never got around to publish my findings, one thing was painfully obvious: there is a huge gap in the area of documentation.
There are quite a few resources, but none of them comprehensive (most comprehensive are the synopsis, but they are not meant for the end user), and no single location we can point people to.
Announcement
So, in the spirit of xkcd, I
present yet another incomplete documentation project:
doc.perl6.org and p6doc.
The idea is to take the same approach as perldoc for Perl 5: create user-level documentation in Pod format (here the Perl 6 Pod), and make it available both on a website and via a command line tool. The source (documentation, command line tool, HTML generator) lives at https://github.com/perl6/doc/. The website is doc.perl6.org.
Oh, and the last Rakudo Star release (2012.06) already shipped p6doc.
Status and Plans
Documentation, website and command line tool are all in very early stages of development.
In the future, I want both
p6doc SOMETHING and
http://doc.perl6.org/SOMETHING to either document or link to
documentation of SOMETHING, be it a built-in variable, an operator, a
type name, routine name, phaser, constant or... all the other possible
constructs that occur in Perl 6. URLs and command line arguments
specific to each type of construct will also be available
(/type/SOMETHING URLs already work).
Finally I want some way to get a "full" view of a type, ie providing all methods from superclasses and roles too.
Help Wanted
All of that is going to be a lot of work, though the most work will be to write the documentation. You too can help! You can write new documentation, gather and incorporate already existing documentation with compatible licenses (for example synopsis, perl 6 advent calendar, examples from rosettacode), add more examples, proof-read the documentation or improve the HTML generation or the command line tool.
If you have any questions about contributing, feel free to ask in #perl6. Of course you can also; create pull requests right away :-).
Fri, 22 Jun 2012
News in the Rakudo 2012.06 release
Permanent link
Rakudo development continues to progress nicely, and so there are a few changes in this month's release worth explaining.
Longest Token Matching, List Iteration
The largest chunk of development effort went into Longest-Token Matching for alternations in Regexes, about which Jonathan already blogged. Another significant piece was Patrick's refactor of list iteration. You probably won't notice much of that, except that for-loops are now a bit faster (maybe 10%), and laziness works more reliably in a couple of cases.
String to Number Conversion
String to number conversion is now stricter than before. Previously an
expression like +"foo" would simply return 0. Now it fails, ie
returns an unthrown exception. If you treat that unthrown exception like a
normal value, it blows up with a helpful error message, saying that the
conversion to a number has failed. If that's not what you want, you can still
write +$str // 0.
require With Argument Lists
require now supports argument lists, and that needs a bit more
explaining. In Perl 6 routines are by default only looked up in lexical
scopes, and lexical scopes are immutable at run time. So, when loading a
module at run time, how do you make functions available to the code that loads
the module? Well, you determine at compile time which symbols you want to
import, and then do the actual importing at run time:
use v6; require Test <&plan &ok &is>; # ^^^^^^^^^^^^^^^ evaluated at compile time, # declares symbols &plan, &ok and &is # ^^^ loaded at run time
Module Load Debugging
Rakudo had some trouble when modules were precompiled, but its dependencies were not. This happens more often than it sounds, because Rakudo checks timestamps of the involved files, and loads the source version if it is newer than the compiled file. Since many file operations (including simple copying) change the time stamp, that could happen very easily.
To make debugging of such errors easier, you can set the
RAKUDO_MODULE_DEBUG environment variable to 1 (or any positive
number; currently there is only one debugging level, in the future higher
numbers might lead to more output).
$ RAKUDO_MODULE_DEBUG=1 ./perl6 -Ilib t/spec/S11-modules/require.t MODULE_DEBUG: loading blib/Perl6/BOOTSTRAP.pbc MODULE_DEBUG: done loading blib/Perl6/BOOTSTRAP.pbc MODULE_DEBUG: loading lib/Test.pir MODULE_DEBUG: done loading lib/Test.pir 1..5 MODULE_DEBUG: loading t/spec/packages/Fancy/Utilities.pm MODULE_DEBUG: done loading t/spec/packages/Fancy/Utilities.pm ok 1 - can load Fancy::Utilities at run time ok 2 - can call our-sub from required module MODULE_DEBUG: loading t/spec/packages/A.pm MODULE_DEBUG: loading t/spec/packages/B.pm MODULE_DEBUG: loading t/spec/packages/B/Grammar.pm MODULE_DEBUG: done loading t/spec/packages/B/Grammar.pm MODULE_DEBUG: done loading t/spec/packages/B.pm MODULE_DEBUG: done loading t/spec/packages/A.pm ok 3 - can require with variable name ok 4 - can call subroutines in a module by name ok 5 - require with import list
Module Loading Traces in Compile-Time Errors
If module myA loads module myB, and myB dies during compilation, you now get a backtrace which indicates through which path the erroneous module was loaded:
$ ./perl6 -Ilib -e 'use myA' ===SORRY!=== Placeholder variable $^x may not be used here because the surrounding block takes no signature at lib/myB.pm:1 from module myA (lib/myA.pm:3) from -e:1
Improved autovivification
Perl allows you to treat not-yet-existing array and hash elements as arrays or hashes, and automatically creates those elements for you. This is called autovivification.
my %h; %h<x>.push: 1, 2, 3; # worked in the previous release too push %h<y>, 4, 5, 6; # newly works in the 2012.06
Thu, 07 Jun 2012
Localization for Exception Messages
Permanent link
Ok, my previous blog post wasn't quite as final as I thought.. My exceptions grant said that the design should make it easy to enable localization and internationalization hooks. I want to discuss some possible approaches and thereby demonstrate that the design is flexible enough as it is.
At this point I'd like to mention that much of the flexibility comes from either Perl 6 itself, or from the separation of stringifying and exception and generating the actual error message.
Mixins: the sledgehammer
One can always override a method in an object by mixing in a role which
contains the method on question. When the user requests error messages in a
different language, one can replace method Str or method
message with one that generates the error message in a different
language.
Where should that happen? The code throws exceptions is fairly scattered over the code base, but there is a central piece of code in Rakudo that turns Parrot-level exceptions into Perl 6 level exceptions. That would be an obvious place to muck with exceptions, but it would mean that exceptions that are created but not thrown don't get the localization. I suspect that's a fairly small problem in the real world, but it still carries code smell. As does the whole idea of overriding methods.
Another sledgehammer: alternative setting
Perl 6 provides built-in types and routines in an outer lexical scope known as a "setting". The default setting is called CORE. Due to the lexical nature of almost all lookups in Perl 6, one can "override" almost anything by providing a symbol of the same name in a lexical scope.
One way to use that for localization is to add another setting between the
user's code and CORE. For example a file DE.setting:
my class X::Signature::Placeholder does X::Comp { method message() { 'Platzhaltervariablen können keine bestehenden Signaturen überschreiben'; } }
After compiling, we can load the setting:
$ ./perl6 --target=pir --output=DE.setting.pir DE.setting
$ ./install/bin/parrot -o DE.setting.pbc DE.setting.pir
$ ./perl6 --setting=DE -e 'sub f() { $^x }'
===SORRY!===
Platzhaltervariablen können keine bestehenden Signaturen überschreiben
at -e:1
That works beautifully for exceptions that the compiler throws, because they look up exception types in the scope where the error occurs. Exceptions from within the setting are a different beast, they'd need special lookup rules (though the setting throws far fewer exceptions than the compiler, so that's probably manageable).
But while this looks quite simple, it comes with a problem: if a module is
precompiled without the custom setting, and it contains a reference to an
exception type, and then the l10n setting redefines it, other programs will
contain references to a different class with the same name. Which means that
our precompiled module might only catch the English version of
X::Signature::Placeholder, and lets our localized exception pass
through. Oops.
Tailored solutions
A better approach is probably to simply hack up the string conversion in
type Exception to consider a translator routine if present, and
pass the invocant to that routine. The translator routine can look up the
error message keyed by the type of the exception, and has access to all data
carried in the exception. In untested Perl 6 code, this might look like
this:
# required change in CORE my class Exception { multi method Str(Exception:D:) { return self.message unless defined $*LANG; if %*TRANSLATIONS{$*LANG}{self.^name} -> $translator { return $translator(self); } return self.message; # fallback } } # that's what a translator could write: %*TRANSLATIONS<de><X::TypeCheck::Assignment> = { "Typenfehler bei Zuweisung zu '$_.symbol()': " ~ "'{$_.expected.^name}' erwartet, aber '{$_.got.^name} bekommen" } }
And setting the dynamic language $*LANG to 'de'
would give a German error message for type check failures in assignment.
Another approach is to augment existing error classes and add methods that
generate the error message in different languages, for example method
message-fr for French, and check their existence in
Exception.Str if a different language is requested.
Conclusion
In conclusion there are many bad and enough good approaches; we will decide which one to take when the need arises (ie when people actually start to translate error messages).
Tue, 05 Jun 2012
Exceptions Grant Report -- Final update
Permanent link
In my previous blog post I mentioned that I'm nearly done with my exceptions Hague grant. I have since done all the things that I identified as still missing.
In particular I ack
through the setting for remaining uses of die, and the only thing
left are internal errors, error messages about not-yet-implemented things and
the actual declaration of die. Which means that everything that
should be a typed exception is now.
The error catalogue can be found in S32::Exception. Documentation for compiler writers is in a separate document, and the promised documentation for test authors is in the POD of Test::Util in the "roast" repository.
Now I wait for review of my work by the grant manager (thanks Will) and the grant committee.
I'd like to thank everybody who was involved with the grant.
Sun, 27 May 2012
Exceptions Grant Report for May 2012
Permanent link
It seems quite a long time since I started working on my grant on exceptions, and I until quite recently I felt that I still had quite a long way to go. And then I read the deliverables again, and found that I have actually achieved quite a bit of them already. I also noticed that some of them are quite ambiguously formulated.
Also when I wrote the grant application I had a clever system in the back of my mind that lets you categorize exceptions with different tags. After presenting that idea to the #perl6 channel, they uniformly told me that it was a (bad) reinvention of the existing type system. They were right, of course. So instead exceptions use the "real" type system now, which means that some aspects of the grant application do not make so much sense now.
Let's look at the deliverables in detail:
D1: Specification
S32::Exception contains my work in this area..
Since exceptions use the normal Perl 6 type system, the amount of work I had to do was less than I had expected. I consider it done, in the sense that everything is there that we need to throw typed exceptions and work with them in a meaningful and intuitive way.
There are certainly still open design question in the general space of exceptions (like, how do we indicate that an exception should or should not print its backtrace by default? There are ways to achieve this right now, but it's not as easy as it it should be for the end user). However those open questions are well outside the realm of this grant. I still plan to tackle them in due time.
D2: Error catalog, tests
The error catalog is compiled and in Rakudo's src/core/Exception.pm. It is not comprehensive (ie doesn't cover all possible errors that are thrown from current compilers), but the grant request only required an "initial" catalog. It is certainly enough to demonstrate the feasibility of the design, and to handle many very common cases. I will certainly summarize it in the S32::Exception document.
Tests are in the roast repository. At the time of writing there are 343 tests (Update 2012-06-04: 411 tests), of which Rakudo passes nearly all (the few failures are due to misparses, which cause wrong parse errors to be generated). They cover both the exceptions API and the individual exception types.
D3: Implementation, tests, documentation
The meat of the implementation is done. Not all exceptions thrown from the setting are typed yet, about 30 remain (plus a few for internal errors that don't make sense to improve much). (Update 2012-06-04: all of these 30 errors now throw typed exceptions too). The tests mentioned above already cover several RT tickets where people complained about wrong or less-than-awesome errors. Documentation is still missing, though I have given a walk through the process of adding a new typed exception to Rakudo on IRC, which might serve as a starting point for such documentation.
So in summary, still missing are
- Finish changing text based exceptions to typed exceptions in CORE
- Documenting the error catalog in S32::Exception
- Documentation for compiler writers and test writers
A surprisingly short list :-)
I'd also like to mention that I did several things related to exceptions which were not covered by this grant report:
- greatly improved backtrace printer
- Many exceptions from within the compilation process (such as parse errors, redeclarations etc.) are now typed.
- I enabled typed exceptions thrown from C code, and as a proof of concept I ported all user-visible exceptions in perl6.ops to their intended types.
- Exceptions from within the meta model can now be caught in the "actions" part of the compiler, augmented with line numbers and file name and re-thrown
Wed, 23 May 2012
News in the Rakudo 2012.05 release
Permanent link
The Rakudo Star release 2012.05 comes with many improvements to the compiler. Some people have asked what they mean, so I want to explain some of them here.
The new -I and -M allow manipulation of the library search path and loading of modules, similar to Perl 5.
perl6 -Ilib t/yourtest.t # finds your module under lib/
If you want to manipulate the search path from inside a script or module, you can now use the new lib module, again known from Perl 5.
# file t/yourtest.t; use v6; use lib 't/lib'; # now can load testing modules from t/lib/Yourmodule/Test.pm use Yourmodule::Test; ...
If you look at how lib.pm is
implemented, you'll notice another new feature: the ability to write a
custom EXPORT subroutine -- necessary exactly for things like
lib.pm.
But normal exporting and importing is now handled quite well from Rakudo. You can now mark routines as being exported to certain tag names:
module CGI { sub h1($text) is export(:HTML) { '<h1>' ~ $text ~ '</h1>' } sub param($key) is export { ... }; }
If you want to get only the HTML generating function(s), you can write
use CGI :HTML;
S11 has more details on the exporting and importing mechanism.
You can also import from within a single file by using import
instead of use:
module Greeter { sub hello($who) is export { say "Hello $who"; } } import Greeter; # make sub hello available in the current scope hello('Perl 6 fans');
Thu, 03 May 2012
SQLite support for DBIish
Permanent link
DBIish, the new database interface for Rakudo Perl 6, now has a working SQLite backend. It uses prepared statements and placeholders, and supports standard CRUD operations.
Previously the SQLite driver would randomly report "Malformed UTF-8 string" or segfault, but usually worked pretty well when run under valgrind. The problem turned out to be a mismatch between the caller's and the callee's ideas about memory management.
In particular, parrot's garbage collector would deallocate strings passed to sqlite3_bind_text after the call was done, but sqlite wants such values to stay around until the next call to sqlite3_step in the very least.
Fixing this mismatch was enabled by this patch, which lets you mark strings as explicitly managed. Such strings keep their marshalled C string equivalent around until they are garbage-collected themselves. So now the sqlite driver keeps a copy of the strings as long as necessary, and the SQLite tests pass reliably.
Currently it still needs the cstr branches in the nqp and
zavolaj repositories, but they will be merged soon -- certainly before the May
release of Rakudo.
Sat, 28 Apr 2012
Meet DBIish, a Perl 6 Database Interface
Permanent link
In the aftermath of the Oslo Perl 6 hackathon 2012, I have decided to fork and rename MiniDBI. MiniDBI is intended as a compatible port of Perl 5's excellent DBI module to Perl 6. While working on the MiniDBI backends, I noticed that I became more and more unhappy with that. Perl 6 is sufficiently different from Perl 5 to warrant different design decisions in the database interface layer.
Meet DBIish. It started with MiniDBI's code base, but has some substantial deviations from MiniDBI:
- Connection information is passed by named arguments to the driver (instead of a single DSN string)
- Different naming of several methods. There's not much point in having
both
fetchrow_arrayandfetchrow_arrayrefin Rakudo.fetchrowsimply returns an array or a list, and the caller decides what to do with it. - Backends only need to implement
fetchrowandcolumn_names, and get all the other fetching methods (likefetchrow-hash,fetchall-hash) for free. - Error handling from DB connection and statement handle are unified into a single row
The latter two changes brought quite a reduction in backend code size.
My plans for the future include experimenting with different names and maybe totally different APIs. When a language has lazy lists, one can simply return all rows lazily, instead of encouraging the user to fetch the rows one by one.
Currently the Postgresql and mysql backends support basic CRUD operations, Postgresql with proper prepared statements and placeholders. An SQLite backend is under way, but still needs better support from our native call interface.
Mon, 23 Apr 2012
Perl 6 Hackathon in Oslo: Report From The Second Day
Permanent link
Second day of the Perl 6 Patterns Hackathon. My plans to get the rest of placeholders and prepared statements working in the Postgresql backend for MiniDBI succeed about 10 minutes after midnight. I just wanted to give them a very quick try before going to bed, and was successful. Then I went to sleep.
It was night, and it was morning. Second day.
Next I wrote an SQLite backend for MiniDBI. It blocked on missing features in our native call infrastructure, on which arnsholt worked in parallel. So I haven't had a chance to try the SQLite backend yet. It probably requires some substantial amount of work before it will run, but at least it compiles.
I also investigated prepared statements and placeholders for the mysql backend. This is much less straight forward, because it requires filling in members of structs, not just function calls. This by itself wouldn't be much a problem, our native call infrastructure supports that. The problem is that it's a struct of mixed "private" and "public" members, so modelling the structure in Perl 6 requires modeling private data of the mysql client library. While possible, I don't find it desirable, because it is rather fragile.
Another notable event was the hacking dojo, where about 8 of us collaborated to write a roman numeral conversion, using pair programming, and fixed cycles of first writing a failing test, then getting it to run in the simplest possible way, and finally refactoring it. It was quite an interesting and fun experience.
I spent much of the rest of the hackathon discussing things. For example Patrick Michaud gave a quick walk through of how lists and related types are implemented and iterated in Rakudo.
In the evening we had very tasty Vietnamese food, and generally a good time.
Again it was a very productive and enjoyable day, and I'm very grateful for being invited to the Hackathon.
Sat, 21 Apr 2012
Perl 6 Hackathon in Oslo: Report From The First Day
Permanent link
Yesterday I arrived in the beautiful city of Oslo to attend the Perl 6 Patterns Hackathon. Yesterday we visited a pub, had great discussions, food and beverages, and generally a very good time.
Today we met at 10 am, and got straight to hacking. We are located in an office in the 6th floor of a big building, with a nice view over the center of town, harbor, and even the Holmenkollen.
I worked on the backtrace printer, which in alarmingly many cases reported
Error while creating error string: Method 'message' not found for
invocant of class 'Any', which wasn't too helpful.
It turns out there were actually two causes. One was a subtle error in the
backtrace printer that was triggered by stricter
implementation of the specification, which was easy to find. The
second bug was harder to find, considering that you don't get easily get
backtraces from errors within the backtrace printer. In the end it was the
usage of a code object in boolean context, which turned out to be harmful.
Because regexes are also code objects, and in boolean context they search for
the outer $_ variable and try to match the regex against it.
Which failed. Hard to find, but easy to fix.
My second big project today was database connectivity. Part of it was pestering Jonathan to fix the issues that arose from module precompilation mixed with calling C modules, and testing all the iterations he produced. I'm happy to report that it now works fine, which speeds up development quite a bit.
I also fixed the postgres driver. The root cause for the failing tests turned out to be rather simple too (a missing initialization), so simple that it's embarrassing how long it took me to find out. On the plus side I improved the code quite a bit in passing.
So now all tests in MiniDBI pass, which is a nice milestone, and an indication that we need more tests.
Tomorrow I plan to change the postgres driver to use proper prepared statments.
But the real value of such hackathon comes from interacting with the other hackers. I'm very happy about lots of discussions with other core hackers, as well as feedback and patches from new users and hackers.
At this occasion I'd also like to thank the organizers, Salve J. Nilsen, Karl Rune Nilsen and Jan Ingvoldstad. It has been a great event so far, both fun and productive. You are doing a great service to the Perl 6 community, and to the hackers you have invited.