Changeset 1376


Ignore:
Timestamp:
Oct 29, 2011, 6:56:14 PM (6 years ago)
Author:
joerg
Message:

haskell scripting and tree magics

Location:
trunk
Files:
3 added
5 edited

Legend:

Unmodified
Added
Removed
  • trunk/scripting/haskell/Trees.hs

    r1370 r1376  
    11
    2 module Main where
     2module Trees where
    33
    44import IO hiding (try)
     
    1212import Text.ParserCombinators.Parsec as P
    1313import qualified Text.ParserCombinators.Parsec.Token as T
    14 import Text.ParserCombinators.Parsec.Language( javaStyle )
     14import Text.ParserCombinators.Parsec.Language( javaStyle, emptyDef )
    1515import Text.ParserCombinators.Parsec.Error hiding (Message)
    1616
     
    3333main :: IO ()
    3434main = do args <- getArgs
    35           case Main.parse (args !! 0) of
    36             Left errors -> hPutStrLn stderr $ show errors
    37             Right (term,highlights) -> do
    38                hPutStrLn stdout $ renderTerm term
    39                hPutStr stdout $ "\\begin{pgfonlayer}{background}"
    40                hPutStrLn stdout $ concat $ map (\h ->
    41                  -- "\n  " ++ intersections (nodes h) ++
    42                  "\n  " ++ renderHighlight term h) highlights
    43                hPutStrLn stdout $ "\\end{pgfonlayer}"
     35          tree $ args !! 0
     36
     37tree string =
     38    case Trees.parse string of
     39      Left errors -> hPutStrLn stderr $ show errors
     40      Right (term,highlights) -> do
     41        hPutStrLn stdout $ renderTerm term
     42        hPutStr stdout $ "\\begin{pgfonlayer}{background}"
     43        hPutStrLn stdout $ concat $ map (\h ->
     44          -- "\n  " ++ intersections (nodes h) ++
     45          "\n  " ++ renderHighlight term h) highlights
     46        hPutStrLn stdout $ "\\end{pgfonlayer}"
    4447
    4548renderTerm :: Term -> String
     
    130133
    131134lexer :: T.TokenParser ()
    132 lexer  = T.makeTokenParser (javaStyle { T.reservedOpNames = [] })
     135lexer  = T.makeTokenParser emptyDef -- (javaStyle { T.reservedOpNames = [], T.reservedNames = [] })
    133136
    134 delimiters    = [' ',',','.',':',';','(',')','[',']','=','\n']
     137delimiters    = [' ',',','.',':',';','(',')','{','}','[',']','=','\n']
    135138whiteSpace    = T.whiteSpace lexer
    136139lexeme        = T.lexeme lexer
     
    143146colon         = T.colon lexer
    144147constant c    = lexeme (P.string c)
     148stringLiteral = T.stringLiteral lexer
    145149
    146150identifier :: Parser String
    147 identifier = do
     151identifier = stringLiteral <|> escapedIdentifier <|> do
    148152  string <- lexeme $ many1 $ noneOf delimiters
    149153  return $ escape string
     154
     155escapedIdentifier :: Parser String
     156escapedIdentifier = do
     157  constant "{"
     158  strings <- many ((many1 $ noneOf "{}") <|> (do s <- escapedIdentifier; return $ "{" ++ s ++ "}"))
     159  constant "}"
     160  return $ concat strings
    150161
    151162-------------------------------------------------------------------------------
     
    153164-------------------------------------------------------------------------------
    154165
    155 getName name = foldr (\c s -> replace c "" s) name ["(",")","[","]","{","}","\\"
     166getName name = foldr (\c s -> replace c "" s) name ["(",")","[","]","{","}","\\","$"
    156167
    157168parseInput :: Parser  (Term,[Highlight])
     
    166177  pac <- parseOption
    167178  root <- identifier
    168   name <- (try $ do constant ":"; n <- identifier; return n) <|> return (getName root)
     179  name <- (try $ do constant "@"; n <- identifier; return n) <|> return (getName root)
    169180  pn <- parseOption
    170181  subterms <- try (parens $ sepBy parseTerm (constant ",")) <|> return []
  • trunk/src/de/endrullis/utils/ProgramUpdater.java

    r1372 r1376  
    55import my.XML.XMLException;
    66import my.XML.XMLParser;
     7import util.FileUtil;
    78import util.ProcessUtil;
    89import util.StreamUtils;
     
    9798  public boolean performUpdate(boolean confirmation) throws IOException {
    9899    // create update dir
    99     updateDir = createTempDirectory("update");
     100    updateDir = FileUtil.createTempDirectory("update");
    100101
    101102    setAlwaysOnTop(true);
     
    336337    }
    337338  }
    338 
    339   /**
    340    * Creates a temporary directory.
    341    */
    342   public static File createTempDirectory(String prefix) throws IOException {
    343     File file = File.createTempFile(prefix, Long.toString(System.nanoTime()));
    344     File dir = new File(file.getAbsolutePath() + ".d");
    345     dir.deleteOnExit();
    346     file.delete();
    347 
    348     if(!dir.mkdir()) {
    349       throw new IOException("Failed to create temporary directory: " + dir.getAbsolutePath());
    350     }
    351 
    352     return dir;
    353   }
    354339}
  • trunk/src/jlatexeditor/codehelper/ScriptingSupport.java

    r1370 r1376  
    11package jlatexeditor.codehelper;
    22
     3import de.endrullis.utils.ProgramUpdater;
    34import sce.codehelper.CodeAssistant;
    45import sce.codehelper.PatternPair;
     
    67import sce.codehelper.WordWithPos;
    78import sce.component.*;
     9import util.FileUtil;
     10import util.ProcessOutput;
     11import util.ProcessUtil;
    812import util.SpellChecker;
    913
    10 import java.io.File;
    11 import java.io.IOException;
     14import java.io.*;
    1215import java.util.ArrayList;
    1316import java.util.List;
     
    1821public class ScriptingSupport implements CodeAssistant {
    1922  private String genericBegin = "%!begin{";
    20   private String[] languages = new String [] {"haskell"};
     23  private String[] languages = new String [] {"haskell", "tree"};
    2124
    2225  public ScriptingSupport() {
     
    114117    }
    115118
    116     File[] files = new File("./scripting/" + language).listFiles();
    117     for(File file : files) {
    118       if(file.getName().startsWith(".")) continue;
    119       System.err.println(file);
     119    try {
     120      File scriptDir = FileUtil.createTempDirectory("script");
     121      scriptDir.deleteOnExit();
     122
     123      String libDir = language;
     124      if(language.equals("tree")) libDir = "haskell";
     125
     126      File[] files = new File("./scripting/" + libDir).listFiles();
     127      for(File file : files) {
     128        if(file.getName().startsWith(".")) continue;
     129        if(!file.isFile()) continue;
     130
     131        FileUtil.copyFile(file, new File(scriptDir, file.getName()));
     132      }
     133
     134      String output = "";
     135
     136      StringBuilder contentBuilder = new StringBuilder();
     137      for(int rowNr = startRow+1; rowNr <= codeEnd; rowNr++) {
     138        contentBuilder.append(rows.getRowAsString(rowNr).trim().substring(1));
     139      }
     140      String content = contentBuilder.toString();
     141
     142      if(language.equals("haskell") || language.equals("tree")) {
     143        String sourceName = "Main.hs";
     144        String executableName = "Main";
     145
     146        PrintWriter writer = new PrintWriter(new BufferedWriter(new FileWriter(new File(scriptDir, sourceName), true)));
     147        if(language.equals("haskell")) {
     148          writer.println(content);
     149        } else {
     150          writer.println("main = tree \"" + content.replace('\n', ' ').replaceAll("\"", "\\\"") + "\"");
     151          System.err.println(scriptDir);
     152        }
     153        writer.close();
     154
     155        ProcessUtil.execAndWait(new String[]{"ghc", "--make", sourceName}, scriptDir);
     156        ProcessOutput result = ProcessUtil.execAndWait(new String[] {"./" + executableName}, scriptDir);
     157        output = result.getStdout();
     158      }
     159
     160      pane.getDocument().replace(codeEnd+1,0,endRow,0, output + "\n");
     161    } catch (IOException e) {
     162      e.printStackTrace();
    120163    }
     164
     165    caret.moveTo(caretPos, false);
    121166  }
    122167}
  • trunk/src/util/ProcessUtil.java

    r1349 r1376  
    55import java.io.File;
    66import java.io.IOException;
     7import java.io.InputStream;
    78import java.util.ArrayList;
    89import java.util.Map;
     
    4243  }
    4344
     45  public static ProcessOutput execAndWait(String command[], File dir) throws IOException {
     46    Process process = exec(command, dir);
     47
     48    // empty the error stream to prevent blocking
     49    ErrorReader errorReader = new ErrorReader(process.getErrorStream());
     50    errorReader.start();
     51
     52    String stdout = StreamUtils.readInputStream(process.getInputStream());
     53    errorReader.waitFor();
     54    String stderr = errorReader.getError();
     55
     56    return new ProcessOutput(stdout, stderr);
     57  }
     58
    4459  public static Process exec(String command, File dir) throws IOException {
    4560    ArrayList<String> list = StringUtils.tokenize(command);
     
    4964    return exec(array, dir);
    5065  }
     66
     67  /**
     68   * Tread reading an error stream.
     69   */
     70  public static class ErrorReader extends Thread {
     71    private InputStream err;
     72    private String error = null;
     73
     74    private ErrorReader(InputStream err) {
     75      this.err = err;
     76    }
     77
     78    public void run() {
     79      try {
     80        error = StreamUtils. readInputStream(err);
     81      } catch (IOException e) {
     82        error = "";
     83        notifyAll();
     84      }
     85    }
     86
     87    public String getError() {
     88      return error;
     89    }
     90
     91    public void waitFor() {
     92      while(error == null) {
     93        synchronized (this) {
     94          try {
     95            wait(500);
     96          } catch (InterruptedException e) {}
     97        }
     98      }
     99    }
     100  }
    51101}
  • trunk/src/util/StreamUtils.java

    r1274 r1376  
    3131
    3232    return outputStream.toByteArray();
     33  }
     34
     35  public static String readInputStream(InputStream in) throws IOException {
     36    return new String(readBytesFromInputStream(in));
    3337  }
    3438
Note: See TracChangeset for help on using the changeset viewer.