javacompiler-constructionfilenamesjflex

Jflex get input filename


In Jflex, how does one extract the input filename?

DisplayFilename.jflex:

%%

%class DisplayFilename

%eof{
    /* code to print the input filename goes here */
%eof}

%%

\n { /* do nothing */ }
. { /* do nothing */ }

Commands ran

jflex DisplayFilename
javac DisplayFilename.java
java DisplayFilename someinputfile.txt

desired output:

someinputfile.txt

Solution

  • This can be achieved by omitting the %standalone tag at the top of the jflex file. This makes jflex not generate the default main() method and allows the user to set their own custom main() method inside of a %{ %} code segment.

    Within this main(), the user can place the original code for the autogenerated main(), but can update to the desired outcome.

    Within this context:

    %%
    
    %class DisplayFilename
    
    %{
      private static String inputfilename = "";
      
      private static class Yytoken {
        /* empty class to allow yylex() to compile */
      }
    
      public static void main(String argv[]) {
        if (argv.length == 0) {
          System.out.println("Usage : java DisplayFilename");
        }
        else {
          int firstFilePos = 0;
          String encodingName = "UTF-8";
          for (int i = firstFilePos; i < argv.length; i++) {
            inputfilename = argv[i]; // LINE OF INTEREST
            WC scanner = null;
            try {
              java.io.FileInputStream stream = new java.io.FileInputStream(argv[i]);
              java.io.Reader reader = new java.io.InputStreamReader(stream, encodingName);
              scanner = new WC(reader);
              while ( !scanner.zzAtEOF ) scanner.yylex();
            }
            catch (java.io.FileNotFoundException e) {
              System.out.println("File not found : \""+argv[i]+"\"");
            }
            catch (java.io.IOException e) {
              System.out.println("IO error scanning file \""+argv[i]+"\"");
              System.out.println(e);
            }
            catch (Exception e) {
              System.out.println("Unexpected exception:");
              e.printStackTrace();
            }
          }
        }
      }
    %}
    
    
    %eof{
        /* code to print the input filename goes here */
          System.out.println(inputfilename);
    %eof}
    
    %%
    
    \n { /* do nothing */ }
    . { /* do nothing */ }