Feature request: provide Template Haskell quasiquoter that generates lexer definition in-place

Abierto
#108 1 comentario 3 reacciones 0 asignados Ver en GitHub

Nadie ha tomado este issue todavía.

Evaluación

Dificultad
5/5
Tiempo estimado
Más de una semana
Aptitud para principiantes
28/100
Tipo de issue
Nueva funcionalidad
Claridad
Bastante claro
Estado de actividad
Estancado
Stack tecnológico
haskell

Línea de trabajo

Comienza con el alex test-suite case tokens_scan_user.x y la ruta de preprocesamiento existente de la línea de comandos, y compárala después con el ejemplo propuesto TokensScanUser.hs y la importación Alex.TH. Se considera terminado cuando un quasiquoter acepta el formato existente de definición del lexer y produce expresiones equivalentes de Template Haskell sin un archivo generado; el contenido no nombra ningún archivo de implementación específico ni ningún comando de prueba.

Escrito por el modelo de indexación a partir del texto del issue.

Descripción

Currently alex is a command-line tool that takes files in its own format and relies on support from Cabal-the-library to invoke alex command in order to preprocess .x files before passing them to ghc. This works reasonably well, but I think there's something to be gained if alex package would provide quasiquoter that takes lexer definition in the currently used format but spits out TH expressions instead of generating new file.

E.g. take tokens_scan_user.x test from the alex test suite. Instead of

{
module Main (main) where
import System.Exit
}

%wrapper "basic" -- Defines: AlexInput, alexGetByte, alexPrevChar

$digit = 0-9
$alpha = [a-zA-Z]
$ws    = [\ \t\n]

tokens :-

  5 / {\ u _ibt _l _iat -> u == FiveIsMagic} { \s -> TFive (head s) }
  $digit { \s -> TDigit (head s) }
  $alpha { \s -> TAlpha (head s) }
  $ws    { \s -> TWSpace (head s) }

{

data Token = TDigit Char
           | TAlpha Char
           | TWSpace Char
           | TFive Char -- Predicated only
           | TLexError
    deriving (Eq,Show)

data UserLexerMode = NormalMode
                   | FiveIsMagic
    deriving Eq

main | test1 /= result1 = exitFailure
     | test2 /= result2 = exitFailure
     -- all succeeded
     | otherwise        = exitWith ExitSuccess

run_lexer :: UserLexerMode -> String -> [Token]
run_lexer m s = go ('\n', [], s)
    where go i@(_,_,s') = case alexScanUser m i 0 of
                     AlexEOF             -> []
                     AlexError  _i       -> [TLexError]
                     AlexSkip   i' _len  ->                   go i'
                     AlexToken  i' len t -> t (take len s') : go i'

test1 = run_lexer FiveIsMagic "5 x"
result1 = [TFive '5',TWSpace ' ',TAlpha 'x']

test2 = run_lexer NormalMode "5 x"
result2 = [TDigit '5',TWSpace ' ',TAlpha 'x']
}

I'd like to write TokensScanUser.hs file that looks like:

{-# LANGUAGE QuasiQuotes #-}

module Main (main) where
import System.Exit

import Alex.TH

genLexer defaultLexer [alex|
%wrapper "basic" -- Defines: AlexInput, alexGetByte, alexPrevChar

$digit = 0-9
$alpha = [a-zA-Z]
$ws    = [\ \t\n]

tokens :-

  5 / {\u _ibt _l _iat -> u == FiveIsMagic} { \s -> TFive (head s) }
  $digit { \s -> TDigit (head s) }
  $alpha { \s -> TAlpha (head s) }
  $ws    { \s -> TWSpace (head s) }
|]

data Token = TDigit Char
           | TAlpha Char
           | TWSpace Char
           | TFive Char -- Predicated only
           | TLexError
    deriving (Eq,Show)

data UserLexerMode = NormalMode
                   | FiveIsMagic
    deriving Eq

main | test1 /= result1 = exitFailure
     | test2 /= result2 = exitFailure
     -- all succeeded
     | otherwise        = exitWith ExitSuccess

run_lexer :: UserLexerMode -> String -> [Token]
run_lexer m s = go ('\n', [], s)
    where go i@(_,_,s') = case alexScanUser m i 0 of
                     AlexEOF             -> []
                     AlexError  _i       -> [TLexError]
                     AlexSkip   i' _len  ->                   go i'
                     AlexToken  i' len t -> t (take len s') : go i'

test1 = run_lexer FiveIsMagic "5 x"
result1 = [TFive '5',TWSpace ' ',TAlpha 'x']

test2 = run_lexer NormalMode "5 x"
result2 = [TDigit '5',TWSpace ' ',TAlpha 'x']

Having such quasiquoter will provide following benefits:

  • This will provide an option to use alex independent of system's preprocessor if, say, clang starts to behave funny
  • This can help end confusion of text editors with overly long lines as mentioned #84
  • There will be no nowelines in the generated files (becase there will be no generated files) that may annoy someone #105
  • User will be able to just start ghci in his or hers project and load lexer definition to play with - no need to add dist/build/ directory (or different directory, depending on build target and the build tool (cabal has one prefix here, stack has another depending on the snapshot))to ghci path any more
  • Indexing with e.g. tag generators should also improve because these programs will just skip quasiquoter part and index all user-defined functions.
Lenguaje dominante
Haskell
Estrellas
323
Forks
87
Métricas de merge de PR
Sin PR fusionados en 30 d

Preparar el entorno

Primeros pasos

  1. Lee el issue completo y luego la guía de contribución del proyecto.
  2. Comenta en el issue que vas a ocuparte — evita que dos personas hagan lo mismo.
  3. Haz un fork del repositorio y trabaja en una rama.
  4. Abre un pull request que haga referencia al número del issue.

Más de haskell/alex

Todos los issues de haskell/alex

Issues similares

Más issues de Haskell

Recibe los nuevos issues en tu correo

Un resumen breve de issues de GitHub para principiantes.