haskell / happy

The Happy parser generator for Haskell
Other
276 stars 85 forks source link

ProduceCode using syntax combinators #218

Open int-index opened 2 years ago

int-index commented 2 years ago

@Ericson2314 Before I continue, do you agree with the approach I’m taking here? In particular, is it fine to add a dependency on pretty?

Ericson2314 commented 2 years ago

Yeah I checked before and pretty has nicely few deps. Looks good to me!

knothed commented 2 years ago

Maybe a dumb question, but... what hinders us from actually creating a TemplateHaskell backend?

int-index commented 2 years ago

@knothed Currently happy does not parse the contents of reduction rules, so if you have e.g. expr ‘+’ expr { $1 + $2 } it will simply substitute happy_var_1 and happy_var_2 instead of $1 and $2, producing happy_var_1 + happy_var_2. Changing that would require embedding a Haskell parser to process .y files (in practice it would mean using GHC API), which is a rather invasive and possibly undesired change.

Instead, I want to keep processing .y files in a string-centric way, and add Template Haskell as an alternative option. So the backends should be polymorphic over the way they generate their code.

In this patch, I introduce combinators such as

appE :: DocExp -> DocExp -> DocExp
tupE :: [DocExp] -> DocExp
...

but DocExp is just a fancy way to work with strings.

But as the next step, I will overload those combinators:

class GenExpr e where
  appE :: e -> e -> e
  tupE :: [e] -> e

and then we could have instance GenExpr DocExp (for string-based code generation) and instance GenExpr TH.ExpQ (for TH-based code generation).

knothed commented 2 years ago

Okay, awesome! So for generating Template Haskell we would need to replace the .y files with some kind of EDSL allowing us to specify the reduction actions directly in TH?

int-index commented 2 years ago

Yes. And if we use typed TH, type errors in the reduction rules can be reported in the original source code, not in the generated code.

knothed commented 2 years ago

Sounds pretty cool. Let me know if I can be of any help :)