IdentifiantMot de passe
Loading...
Mot de passe oublié ?Je m'inscris ! (gratuit)
Navigation

Inscrivez-vous gratuitement
pour pouvoir participer, suivre les réponses en temps réel, voter pour les messages, poser vos propres questions et recevoir la newsletter

EDI et Outils pour Java Discussion :

[ANTLR]Problème de fin de fichier


Sujet :

EDI et Outils pour Java

  1. #1
    Membre confirmé Avatar de anitshka
    Inscrit en
    Mai 2004
    Messages
    624
    Détails du profil
    Informations forums :
    Inscription : Mai 2004
    Messages : 624
    Points : 605
    Points
    605
    Par défaut [ANTLR]Problème de fin de fichier
    salut

    voici un parseur tout simple :
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
    75
    76
    77
    78
    79
    80
    81
    82
    83
    84
    85
    86
    87
    88
    89
    90
    91
    92
    93
    94
    95
    96
    97
    98
    99
    100
    101
    102
    103
    104
    105
    106
    107
    108
    109
    110
    111
    112
    113
    114
    115
    116
    117
    118
    119
    120
    121
    122
    123
    124
    125
    126
    127
    128
    129
    130
    131
    132
    133
    134
    135
    136
    137
    138
    139
    140
    141
    142
    143
    144
    145
    146
    147
    148
    149
    150
    151
    152
    153
    154
    155
    156
    157
    158
    159
    160
    161
    162
    163
    164
    165
    166
    167
    168
    169
    170
    171
    172
    173
    174
    175
    176
    177
    178
    179
    180
    181
    182
    183
    184
    185
    186
    187
    188
    189
    190
    191
    192
    193
    194
    195
    196
    197
    198
    199
    200
    201
    202
    203
    204
    205
    206
    207
    208
    209
    210
    211
    212
    213
    214
    215
    216
    217
    218
    219
    220
    221
    222
    223
    224
    225
    226
    227
    228
    229
    230
    231
    232
    233
    234
    235
    236
    237
    238
    239
    240
    241
    242
    243
    244
    245
    246
    247
    248
     
    class MonParser extends Parser;
    options {
      defaultErrorHandler = false;      // Don't generate parser error handlers
    }
     
    // Define some methods and variables to use in the generated parser.
    {
      public void parse() throws Exception{
        return mainStatement();
      }
    }
     
    mainStatement[] returns [] throws InvalidSymbolException, ParseException
      :  "hello" EOF {System.err.println("trouvé coucou ET EOF");}
      ;
     
    constantExpression[] returns [Object exp = null] throws InvalidSymbolException
      {
        Object constant = null;
        Integer aInteger;
        Double aDouble; String aString;Float aFloat;Long aLong;Character aCharacter;
      }
      : (
          aDouble = isDoubleLiteral[]
    	  { constant = new ConstantExpression(JavaObjectType.DOUBLE, aDouble); }
    	|
    	  aFloat = isFloatingPointLiteral[]
    	  { constant = new ConstantExpression(JavaObjectType.DOUBLE, aFloat); }
    	|
    	  aInteger = isIntegerLiteral[]
    	  { constant = new ConstantExpression(JavaObjectType.INTEGER, aInteger); }
    	|
    	  aLong = isLongLiteral[]
    	  { constant = new ConstantExpression(JavaObjectType.DOUBLE, aLong); }
    	)
    	{
    	    exp = constant;
    	}
      ;
     
    isDoubleLiteral []
      returns [Double self = null]
    :
      token : NUM_DOUBLE
        {
          String text = token.getText();
    	  self = new Double(text);
        }
    ;
     
    isFloatingPointLiteral []
      returns [Float self = null]
    :
      token : NUM_FLOAT
        {
          String	text = token.getText();
          self = new Float(text);
        }
    ;
     
    isIntegerLiteral []
      returns [Integer self = null]
    :
      token : INT_LITERAL
        {
    	  self = new Integer(token.getText());
        }
    ;
     
    isLongLiteral []
      returns [Long self = null]
    :
      token : LONG_LITERAL
        {
          self = new Long(token.getText());
        }
    ;
     
    isIdentifier[] returns [Object aIdentifier = null]
      : token : IDENTIFIER
          {
    	    aIdentifier = token.getText();
    	  }
      ;
     
     
     
    class SMSLexer extends Lexer;
     
    options {
      charVocabulary = '\0'..'\377';
      testLiterals=false;    // don't automatically test for literals
      k=2;                   // two characters of lookahead
    }
     
    // @@startrules
     
    //---------
    // COMMENTS
    // --------
     
    // Single-line comments
    COMMENT
      : "//" (~('\n'|'\r'))*
        {
            $setType(Token.SKIP);
        }
      ;
     
    // multiple-line comments
    ML_COMMENT
      : "/*"
        (               /* '\r' '\n' can be matched in one alternative or by matching
                           '\r' in one iteration and '\n' in another. I am trying to
                           handle any flavor of newline that comes in, but the language
                           that allows both "\r\n" and "\r" and "\n" to all be valid
                           newline is ambiguous. Consequently, the resulting grammar
                           must be ambiguous. I'm shutting this warning off.
                        */
          options {
            generateAmbigWarnings=false;
          }
          :  { LA(2)!='/' }? '*'
          | '\r' '\n' {newline();}
          | '\r' {newline();}
          | '\n' {newline();}
          | ~('*'|'\n'|'\r')
        )*
        "*/"
        {
            $setType(Token.SKIP);
        }
    ;
     
     
    //-----------------------
    // WHITESPACE -- ignored
    // ----------------------
     
    WS
      : ( ' '
        | '\t'
        | '\f'
     
        // handle newlines
        | ( "\r\n"  // DOS/Windows
          | '\r'    // Macintosh
          | '\n'    // Unix
          )
          // increment the line count in the scanner
          { newline(); }
        )
        {
            $setType(Token.SKIP);
        }
      ;
     
     
    //------------
    // IDENTIFIER
    // -----------
    IDENTIFIER
      options { testLiterals=true; }
      : LETTER (LETTER | DIGIT)*
      ;
     
    protected LETTER
      : ('a'..'z'|'A'..'Z')
      ;
     
    protected DIGIT
      :  ('0'..'9')
      ;
     
     
    //------------
    // LITERALS
    // -----------
     
    // hexadecimal digit (again, note it's protected!)
    protected HEX_DIGIT
      : (DIGIT|'A'..'F'|'a'..'f')
      ;
     
    // a numeric literal
    INT_LITERAL
      {  boolean	isDecimal = false;}
      : ( MINUS )?
        (
            '.' { $setType(DOT); }
            (('0'..'9')+ (EXPONENT)? (FLOAT_SUFFIX)? { $setType(NUM_FLOAT); })?
            | (
                '0' { isDecimal = true; } // special case for just '0'
                (
                  ('x' | 'X')
    	          (
                      // hex
                      // the 'e'|'E' and float suffix stuff look
                      // like hex digits, hence the (...)+ doesn't
                      // know when to stop: ambig.  ANTLR resolves
                      // it correctly by matching immediately.  It
                      // is therefor ok to hush warning.
                      options { warnWhenFollowAmbig = false; } :
    	              HEX_DIGIT
    	          )+
                  |	('0'..'7')+					// octal
                )?
                | ('1'..'9') ('0'..'9')*
                    { isDecimal = true; }		// non-zero decimal
              )
              (
                ('l' | 'L')
                { $setType(LONG_LITERAL); }
                |
    	        // only check to see if it's a float if looks like decimal so far
                { isDecimal }?
    	        { $setType(NUM_FLOAT); }
    	        (
    	          '.' ('0'..'9')* (EXPONENT)? ( FLOAT_SUFFIX | DOUBLE_SUFFIX { $setType(NUM_DOUBLE); } )?
    	            |  EXPONENT (FLOAT_SUFFIX | DOUBLE_SUFFIX { $setType(NUM_DOUBLE); })?
    	            |  FLOAT_SUFFIX
                    |  DOUBLE_SUFFIX { $setType(NUM_DOUBLE); }
    	        )
              )?
              | ( FLOAT_SUFFIX | DOUBLE_SUFFIX { $setType(NUM_DOUBLE); } )?
        )
      ;
     
    protected EXPONENT
      : ('e'|'E') ('+'|MINUS)? (DIGIT)+
      ;
     
    protected FLOAT_SUFFIX
      : 'f'|'F'
      ;
     
    protected DOUBLE_SUFFIX
      : 'd'|'D'
      ;
     
     
    //------------------
    // OPERATORS
    //------------------
     
    MINUS           : '-'   ;
    DOT             : '.'   ;
    en gros je souhaitais que mon parseur accepte la ligne suivante :
    Mais refuse la ligne suivante
    Or lorsqu'il fait match(Token.EOF_TYPE); il n'arrive pas a le detecter... avez vous une idée de contournement ?
    Ni Dieu, ni maître, mais des frites bordel!

  2. #2
    Membre éprouvé Avatar de MarneusCalgarXP
    Profil pro
    Inscrit en
    Juillet 2006
    Messages
    911
    Détails du profil
    Informations personnelles :
    Âge : 41
    Localisation : France, Nord (Nord Pas de Calais)

    Informations forums :
    Inscription : Juillet 2006
    Messages : 911
    Points : 1 118
    Points
    1 118
    Par défaut
    Euh, ta ligne

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
     
    mainStatement[] returns [] throws InvalidSymbolException, ParseException
      :  "hello" EOF {System.err.println("trouvé coucou ET EOF");}
      ;
    me parait bizarre ! normalement, dans le parser, tu n'analyses que des tokens...

    tu devrais donc avoir une alayse de ce token dans ton lexer et avoir un truc du style

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    ...
    
    mainStatement[] returns [] throws InvalidSymbolException, ParseException
      :  HELLO EOF {System.err.println("trouvé coucou ET EOF");}
      ;
    
    ...
    
    class SMSLexer extends Lexer;
    
    tokens {
      HELLO = "hello";
    }
    
    ...
    
    IDENTIFIER
      options { testLiterals=true; }
      : LETTER (LETTER | DIGIT)*
      ;
    
    ...

    Je ne répond à aucune question technique par MP.

    Si votre problème est réglé, n'oubliez pas Dans tous les cas

  3. #3
    Membre confirmé Avatar de anitshka
    Inscrit en
    Mai 2004
    Messages
    624
    Détails du profil
    Informations forums :
    Inscription : Mai 2004
    Messages : 624
    Points : 605
    Points
    605
    Par défaut
    ca ne change rien... en spécifiant mon token dans mon lexer je rend ma grammaire plus propre, mais c'est tout. Mon "hello" ainsi défini dans mon parseur me génère aussi un token.
    Le problème vient de mon literal pour mes numérique. Il semblerait qu'ainsi défini, je réécrive la définition du EOF
    Ni Dieu, ni maître, mais des frites bordel!

  4. #4
    Membre éprouvé Avatar de MarneusCalgarXP
    Profil pro
    Inscrit en
    Juillet 2006
    Messages
    911
    Détails du profil
    Informations personnelles :
    Âge : 41
    Localisation : France, Nord (Nord Pas de Calais)

    Informations forums :
    Inscription : Juillet 2006
    Messages : 911
    Points : 1 118
    Points
    1 118
    Par défaut
    Peut-être la règle que tu as décrite est-elle trop complexe... personnellement, j'aurais placé une telle règle dans le parser et non dans le lexer.

    Je ne répond à aucune question technique par MP.

    Si votre problème est réglé, n'oubliez pas Dans tous les cas

  5. #5
    Membre confirmé Avatar de anitshka
    Inscrit en
    Mai 2004
    Messages
    624
    Détails du profil
    Informations forums :
    Inscription : Mai 2004
    Messages : 624
    Points : 605
    Points
    605
    Par défaut
    Citation Envoyé par MarneusCalgarXP
    Peut-être la règle que tu as décrite est-elle trop complexe... personnellement, j'aurais placé une telle règle dans le parser et non dans le lexer.
    La regle pour les litéraux numérique est dans le lexer... et le problème vent bien de la car en remplaçant par une version que j'ai trouvé sur le net, ca marche sans problème
    Ni Dieu, ni maître, mais des frites bordel!

  6. #6
    Membre éprouvé Avatar de MarneusCalgarXP
    Profil pro
    Inscrit en
    Juillet 2006
    Messages
    911
    Détails du profil
    Informations personnelles :
    Âge : 41
    Localisation : France, Nord (Nord Pas de Calais)

    Informations forums :
    Inscription : Juillet 2006
    Messages : 911
    Points : 1 118
    Points
    1 118
    Par défaut
    Peux-tu poster la règle que tu as trouvé, ca pourrait me servir bientôt

    Je ne répond à aucune question technique par MP.

    Si votre problème est réglé, n'oubliez pas Dans tous les cas

  7. #7
    Membre confirmé Avatar de anitshka
    Inscrit en
    Mai 2004
    Messages
    624
    Détails du profil
    Informations forums :
    Inscription : Mai 2004
    Messages : 624
    Points : 605
    Points
    605
    Par défaut
    voili voilou
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
    75
    76
    77
    78
    79
    80
    81
    82
    83
    84
    85
    86
    87
    88
    89
    90
    91
    92
    93
    94
    95
    96
    97
    98
    99
    100
    101
    102
    103
    104
    105
    106
    107
    108
    109
    110
    111
    112
    113
    114
    115
    116
    117
    118
    119
    120
    121
    122
    123
    124
    125
    126
    127
     
     
     
    CHAR_LITERAL
    : '\'' ( { LA(1)=='\\' }? ESC | ~'\'' ) '\''
    ;
     
    STRING_LITERAL
    : '"' ({ LA(1)=='\\' }? ESC | ~('"'|'\\'))* '"'
    ;
     
     
    protected ESC
      : '\\'
        ( 'n' | 'r' | 't' | 'b' | 'f' | '"' | '\'' | '\\' | ('u')+ HEX_DIGIT HEX_DIGIT HEX_DIGIT HEX_DIGIT | ('0'..'3')
        (
            options
              {
                warnWhenFollowAmbig = false;
              }
              : ('0'..'9')
                (
                    options
                      {
                        warnWhenFollowAmbig = false;
                      }
                      : '0'..'9'
                )?
        )?
        | ('4'..'7')
        (
            options
              {
                warnWhenFollowAmbig = false;
              }
              : ('0'..'9') )?
                | { true }? .
        )
      ;
     
     
    protected
    HEX_DIGIT
    : ('0'..'9'|'A'..'F'|'a'..'f')
    ;
     
     
    INT_LITERAL
      {
        boolean isDecimal=false;
        int tokenType = DOUBLE_LITERAL;
      }
      : '.' {_ttype = DOT;}
        (
            ('0'..'9')+ (EXPONENT)? (tokenType = FLOAT_SUFFIX)? { _ttype = tokenType; })?
            | ( '0' {isDecimal = true;}
            (
                ('x'|'X')
                (
                    options
                      {
                        warnWhenFollowAmbig=false;
                      }
                    : HEX_DIGIT
                )+
                | ('0'..'7')+
            )?
            | ('1'..'9') ('0'..'9')* {isDecimal=true;}
        )
        (
            ('l'|'L') { _ttype = LONG_LITERAL; }
            | {isDecimal}?
            (
                '.' ('0'..'9')* (EXPONENT)? (tokenType = FLOAT_SUFFIX)?
                | EXPONENT (FLOAT_SUFFIX)?
                | tokenType = FLOAT_SUFFIX
            )
            { _ttype = tokenType; }
        )?
      ;
     
    protected EXPONENT
    : ('e'|'E') ('+'|'-')? ('0'..'9')+
    ;
     
     
    protected FLOAT_SUFFIX returns [int tokenType]
    { tokenType = DOUBLE_LITERAL; }
    : ( 'f' | 'F' ) { tokenType = FLOAT_LITERAL; }
    | ( 'd' | 'D' ) { tokenType = DOUBLE_LITERAL; }
    ;
     
    IDENTIFIER
    options
      {
        paraphrase = "an identifier";
        testLiterals=true;
      }
      : ( 'a'..'z' | 'A'..'Z' | '_' | '$' | UNICODE_STR | { Character.isJavaIdentifierStart(LA(1)) }? . )
        ( 'a'..'z' | 'A'..'Z' | '_' | '$' | UNICODE_STR | UNICODE_DIGIT | { Character.isJavaIdentifierPart(LA(1)) }? . )*
        | (
            "{"
            ( 'a'..'z' | 'A'..'Z' | MINUS | '_' | COLON | '$' | UNICODE_STR | UNICODE_DIGIT | { Character.isJavaIdentifierPart(LA(1)) }? . )*
            "}"
          )
      ;
     
    protected UNICODE_DIGIT
      : '0'..'9'
        | '\uff10'..'\uff19'
      ;
     
    protected UNICODE_STR
      : '\\' ('u')+ HEX_DIGIT HEX_DIGIT HEX_DIGIT HEX_DIGIT
        {
            try {
                String tmp = text.toString();
                char c = (char)Integer.parseInt(tmp.substring(tmp.length() - 4, tmp.length()), 16);
                // problems using ANTLR feature $setText => use generated code
                text.setLength(_begin);
                text.append(new Character(c).toString());
            }
            catch (NumberFormatException ex) {
                reportError(ex.getMessage());
            }
        }
      ;
    Ni Dieu, ni maître, mais des frites bordel!

Discussions similaires

  1. [Batch] Concaténation de fichiers. Problème en fin de fichier.
    Par cycy75 dans le forum Scripts/Batch
    Réponses: 5
    Dernier message: 08/06/2009, 11h23
  2. Problème de lecture de fin de fichier (eof(fichier))
    Par jailbomba dans le forum Pascal
    Réponses: 2
    Dernier message: 21/02/2007, 16h50
  3. Lire de la 2eme ligne à la fin du fichier
    Par iamspacy dans le forum Linux
    Réponses: 3
    Dernier message: 03/05/2004, 13h23
  4. Réponses: 4
    Dernier message: 16/04/2004, 08h20
  5. [langage] Problème de taille de fichier à mettre dans
    Par And_the_problem_is dans le forum Langage
    Réponses: 10
    Dernier message: 13/08/2002, 09h41

Partager

Partager
  • Envoyer la discussion sur Viadeo
  • Envoyer la discussion sur Twitter
  • Envoyer la discussion sur Google
  • Envoyer la discussion sur Facebook
  • Envoyer la discussion sur Digg
  • Envoyer la discussion sur Delicious
  • Envoyer la discussion sur MySpace
  • Envoyer la discussion sur Yahoo