Je crée un compilateur simple, et j'utilise flex et hashtable (unordered_set
) pour vérifier si un mot d'entrée est un identifiant ou un mot-clé.Les jetons Flex ne fonctionnent pas avec char * hashtable
%{
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <unordered_set>
using std::unordered_set;
void yyerror(char*);
int yyparse(void);
typedef unordered_set<const char*> cstrset;
const cstrset keywords = {"and", "bool", "class"};
%}
%%
[ \t\n\r\f] ;
[a-z][a-zA-Z0-9_]* { if (keywords.count(yytext) > 0)
printf("%s", yytext);
else
printf("object-identifier"); };
%%
void yyerror(char* str) {printf("ERROR: Could not parse!\n");}
int yywrap() {}
int main(int argc, char** argv)
{
if (argc != 2) {printf("no input file");}
FILE* file = fopen(argv[1], "r");
if (file == NULL) {printf("couldn't open file");}
yyin = file;
yylex();
fclose(file);
return 0;
}
J'ai essayé avec un fichier d'entrée qui n'a que le mot « classe » écrite, et la sortie est object_identifier
, pas class
.
J'ai essayé avec un programme simple, sans utiliser de flex et le unordered_set
fonctionne très bien.
int main()
{
cstrset keywords = {"and", "class"};
const char* str = "class";
if (keywords.count(str) > 0)
printf("works");
return 0;
}
Quel pourrait être le problème?
C++ Tagged 11: 'envisager l'aide cstrset =' unordered_set au lieu de 'typedef' –
kfsone