1 package org.simantics.scl.compiler.commands;
3 import java.io.BufferedReader;
4 import java.io.FileNotFoundException;
5 import java.io.FileOutputStream;
6 import java.io.IOException;
7 import java.io.PrintStream;
9 import java.io.StringReader;
10 import java.io.UnsupportedEncodingException;
11 import java.util.ArrayList;
12 import java.util.Collection;
13 import java.util.Collections;
14 import java.util.LinkedList;
15 import java.util.List;
19 import org.simantics.scl.compiler.common.names.Name;
20 import org.simantics.scl.compiler.constants.StringConstant;
21 import org.simantics.scl.compiler.elaboration.expressions.EApply;
22 import org.simantics.scl.compiler.elaboration.expressions.EBlock;
23 import org.simantics.scl.compiler.elaboration.expressions.EConstant;
24 import org.simantics.scl.compiler.elaboration.expressions.EExternalConstant;
25 import org.simantics.scl.compiler.elaboration.expressions.ELiteral;
26 import org.simantics.scl.compiler.elaboration.expressions.EVariable;
27 import org.simantics.scl.compiler.elaboration.expressions.Expression;
28 import org.simantics.scl.compiler.elaboration.expressions.Variable;
29 import org.simantics.scl.compiler.elaboration.expressions.block.GuardStatement;
30 import org.simantics.scl.compiler.elaboration.expressions.block.Statement;
31 import org.simantics.scl.compiler.environment.AbstractLocalEnvironment;
32 import org.simantics.scl.compiler.environment.Environment;
33 import org.simantics.scl.compiler.environment.LocalEnvironment;
34 import org.simantics.scl.compiler.environment.specification.EnvironmentSpecification;
35 import org.simantics.scl.compiler.errors.CompilationError;
36 import org.simantics.scl.compiler.errors.Locations;
37 import org.simantics.scl.compiler.internal.codegen.utils.NameMangling;
38 import org.simantics.scl.compiler.internal.parsing.exceptions.SCLSyntaxErrorException;
39 import org.simantics.scl.compiler.internal.parsing.parser.SCLParserImpl;
40 import org.simantics.scl.compiler.internal.parsing.utils.LaxUTF8Reader;
41 import org.simantics.scl.compiler.internal.parsing.utils.MemoReader;
42 import org.simantics.scl.compiler.module.ImportDeclaration;
43 import org.simantics.scl.compiler.module.repository.ImportFailure;
44 import org.simantics.scl.compiler.module.repository.ImportFailureException;
45 import org.simantics.scl.compiler.module.repository.ModuleRepository;
46 import org.simantics.scl.compiler.runtime.RuntimeEnvironment;
47 import org.simantics.scl.compiler.top.ExpressionEvaluator;
48 import org.simantics.scl.compiler.top.LocalStorage;
49 import org.simantics.scl.compiler.top.SCLExpressionCompilationException;
50 import org.simantics.scl.compiler.types.TCon;
51 import org.simantics.scl.compiler.types.Type;
52 import org.simantics.scl.compiler.types.Types;
53 import org.simantics.scl.runtime.SCLContext;
54 import org.simantics.scl.runtime.function.Function;
55 import org.simantics.scl.runtime.function.FunctionImpl2;
56 import org.simantics.scl.runtime.reporting.DelegatingSCLReportingHandler;
57 import org.simantics.scl.runtime.reporting.SCLReporting;
58 import org.simantics.scl.runtime.reporting.SCLReportingHandler;
59 import org.simantics.scl.runtime.tuple.Tuple0;
61 import gnu.trove.map.hash.THashMap;
62 import gnu.trove.procedure.TObjectProcedure;
63 import gnu.trove.set.hash.THashSet;
66 public class CommandSession {
68 ModuleRepository moduleRepository;
69 SCLReportingHandler defaultHandler;
71 RuntimeEnvironment runtimeEnvironment;
72 ValueToStringConverter valueToStringConverter;
74 ArrayList<CommandSessionImportEntry> importEntries = new ArrayList<CommandSessionImportEntry>();
76 THashMap<String,Object> variableValues = new THashMap<String,Object>();
77 THashMap<String,Type> variableTypes = new THashMap<String,Type>();
79 PrintStream fileOutput;
81 private static final String CONTEXT_MODULE = "Expressions/Context";
82 private static final TCon CONTEXT_TYPE = Types.con(CONTEXT_MODULE, "Context");
83 private static final Name CONTEXT_GET = Name.create(CONTEXT_MODULE, "contextGet");
85 public CommandSession(ModuleRepository moduleRepository, SCLReportingHandler handler) {
86 this.moduleRepository = moduleRepository;
87 this.defaultHandler = new PrintDecorator(
88 handler == null ? SCLReportingHandler.DEFAULT : handler);
89 updateRuntimeEnvironment(true);
92 private static EnvironmentSpecification createEnvironmentSpecification(Collection<CommandSessionImportEntry> importEntries) {
93 EnvironmentSpecification spec = new EnvironmentSpecification();
94 spec.importModule("Builtin", "");
95 spec.importModule("StandardLibrary", "");
96 spec.importModule("Expressions/Context", null);
97 for(CommandSessionImportEntry entry : importEntries)
98 if(!entry.disabled && !entry.hasError)
99 spec.importModule(entry.moduleName, entry.localName);
103 public void updateRuntimeEnvironment(boolean clearErrorsFlags) {
105 for(CommandSessionImportEntry entry : importEntries)
106 entry.hasError = false;
107 EnvironmentSpecification environmentSpecification = createEnvironmentSpecification(importEntries);
109 runtimeEnvironment = null;
112 runtimeEnvironment = moduleRepository.createRuntimeEnvironment(
113 environmentSpecification,
114 getClass().getClassLoader());
115 } catch(ImportFailureException e) {
116 THashSet<String> failedModules = new THashSet<String>();
117 for(ImportFailure failure : e.failures) {
118 failedModules.add(failure.moduleName);
119 defaultHandler.printError(failure.toString());
120 if(failure.reason instanceof CompilationError[])
121 for(CompilationError error : (CompilationError[])failure.reason) {
122 defaultHandler.printError(" " + error.description);
125 for(CommandSessionImportEntry entry : importEntries)
126 if(failedModules.contains(entry.moduleName))
127 entry.hasError = true;
128 environmentSpecification = createEnvironmentSpecification(importEntries);
130 runtimeEnvironment = moduleRepository.createRuntimeEnvironment(
131 environmentSpecification,
132 getClass().getClassLoader());
133 } catch (ImportFailureException e1) {
134 for(ImportFailure failure : e1.failures)
135 defaultHandler.printError(failure.toString());
138 } catch(RuntimeException e) {
142 valueToStringConverter = new ValueToStringConverter(runtimeEnvironment);
145 public RuntimeEnvironment getRuntimeEnvironment() {
146 return runtimeEnvironment;
149 public ModuleRepository getModuleRepository() {
150 return moduleRepository;
153 private static class CancelExecution extends RuntimeException {
154 private static final long serialVersionUID = -6925642906311538873L;
157 private LocalStorage localStorage = new LocalStorage() {
159 public void store(String name, Object value, Type type) {
160 variableValues.put(name, value);
161 variableTypes.put(name, type);
165 private static class LocalFunction {
166 final Function function;
169 public LocalFunction(Function function, Type type) {
170 this.function = function;
175 private static final THashMap<String, LocalFunction> LOCAL_FUNCTIONS = new THashMap<String, LocalFunction>();
177 LOCAL_FUNCTIONS.put("runFromFile", new LocalFunction(new FunctionImpl2<CommandSession, String, Tuple0>() {
179 public Tuple0 apply(final CommandSession commandSession, String fileName) {
180 SCLContext context = SCLContext.getCurrent();
181 commandSession.runFromFile(fileName, (SCLReportingHandler)context.get(SCLReportingHandler.REPORTING_HANDLER));
182 return Tuple0.INSTANCE;
184 }, Types.functionE(Types.STRING, Types.PROC, Types.UNIT)));
185 LOCAL_FUNCTIONS.put("runTest", new LocalFunction(new FunctionImpl2<CommandSession, String, Tuple0>() {
187 public Tuple0 apply(final CommandSession commandSession, String fileName) {
188 SCLContext context = SCLContext.getCurrent();
189 SCLReportingHandler handler = (SCLReportingHandler)context.get(SCLReportingHandler.REPORTING_HANDLER);
191 BufferedReader reader = new BufferedReader(new LaxUTF8Reader(fileName));
193 new TestScriptExecutor(commandSession, reader, handler).execute();
197 } catch(IOException e) {
198 handler.printError(e.getMessage());
200 return Tuple0.INSTANCE;
202 }, Types.functionE(Types.STRING, Types.PROC, Types.UNIT)));
203 LOCAL_FUNCTIONS.put("reset", new LocalFunction(new FunctionImpl2<CommandSession, Tuple0, Tuple0>() {
205 public Tuple0 apply(CommandSession commandSession, Tuple0 _) {
206 commandSession.removeTransientImports();
207 commandSession.removeVariables();
208 commandSession.moduleRepository.getSourceRepository().checkUpdates();
209 commandSession.updateRuntimeEnvironment(true);
210 return Tuple0.INSTANCE;
212 }, Types.functionE(Types.UNIT, Types.PROC, Types.UNIT)));
213 LOCAL_FUNCTIONS.put("variables", new LocalFunction(new FunctionImpl2<CommandSession, Tuple0, List<String>>() {
215 public List<String> apply(CommandSession commandSession, Tuple0 _) {
216 ArrayList<String> result = new ArrayList<String>(commandSession.variableTypes.keySet());
217 Collections.sort(result);
220 }, Types.functionE(Types.PUNIT, Types.PROC, Types.list(Types.STRING))));
221 LOCAL_FUNCTIONS.put("startPrintingToFile", new LocalFunction(new FunctionImpl2<CommandSession, String, Tuple0>() {
223 public Tuple0 apply(final CommandSession commandSession, String fileName) {
225 if(commandSession.fileOutput != null) {
226 commandSession.fileOutput.close();
227 SCLReporting.printError("Printing to file was already enabled. Stopped the previous printing.");
229 commandSession.fileOutput = new PrintStream(fileName, "UTF-8");
230 } catch (FileNotFoundException e) {
231 throw new RuntimeException(e);
232 } catch (UnsupportedEncodingException e) {
233 throw new RuntimeException(e);
235 return Tuple0.INSTANCE;
237 }, Types.functionE(Types.STRING, Types.PROC, Types.UNIT)));
238 LOCAL_FUNCTIONS.put("startAppendingToFile", new LocalFunction(new FunctionImpl2<CommandSession, String, Tuple0>() {
240 public Tuple0 apply(final CommandSession commandSession, String fileName) {
242 if(commandSession.fileOutput != null) {
243 commandSession.fileOutput.close();
244 SCLReporting.printError("Printing to file was already enabled. Stopped the previous printing.");
246 FileOutputStream stream = new FileOutputStream(fileName, true);
247 commandSession.fileOutput = new PrintStream(stream, false, "UTF-8");
248 } catch (FileNotFoundException e) {
249 throw new RuntimeException(e);
250 } catch (UnsupportedEncodingException e) {
251 throw new RuntimeException(e);
253 return Tuple0.INSTANCE;
255 }, Types.functionE(Types.STRING, Types.PROC, Types.UNIT)));
256 LOCAL_FUNCTIONS.put("stopPrintingToFile", new LocalFunction(new FunctionImpl2<CommandSession, Tuple0, Tuple0>() {
258 public Tuple0 apply(final CommandSession commandSession, Tuple0 _) {
259 if(commandSession.fileOutput != null) {
260 commandSession.fileOutput.close();
261 commandSession.fileOutput = null;
263 return Tuple0.INSTANCE;
265 }, Types.functionE(Types.PUNIT, Types.PROC, Types.UNIT)));
268 private LocalEnvironment createLocalEnvironment() {
269 return new AbstractLocalEnvironment() {
270 Variable contextVariable = new Variable("context", CONTEXT_TYPE);
272 public Expression resolve(Environment environment, String localName) {
273 Type type = variableTypes.get(localName);
276 new EConstant(environment.getValue(CONTEXT_GET), type),
277 new EVariable(contextVariable),
278 new ELiteral(new StringConstant(localName))
280 LocalFunction localFunction = LOCAL_FUNCTIONS.get(localName);
281 if(localFunction != null) {
282 return new EExternalConstant(
283 localFunction.function.apply(CommandSession.this),
289 protected Variable[] getContextVariables() {
290 return new Variable[] { contextVariable };
293 public void forNames(TObjectProcedure<String> proc) {
294 for(String name : variableTypes.keySet())
296 for(String name : LOCAL_FUNCTIONS.keySet())
302 protected void removeTransientImports() {
303 ArrayList<CommandSessionImportEntry> newEntries = new ArrayList<CommandSessionImportEntry>(importEntries.size());
304 for(CommandSessionImportEntry entry : importEntries)
306 newEntries.add(entry);
307 importEntries = newEntries;
310 public THashMap<String,Type> localNamesForContentProposals() {
311 THashMap<String,Type> result = new THashMap<String,Type>();
312 for(Map.Entry<String,LocalFunction> entry : LOCAL_FUNCTIONS.entrySet())
313 result.put(entry.getKey(), entry.getValue().type);
314 result.putAll(variableTypes);
318 private CompiledCommand compile(Expression expression) throws SCLExpressionCompilationException {
319 LocalEnvironment localEnvironment = createLocalEnvironment();
320 if(runtimeEnvironment == null)
321 throw new SCLExpressionCompilationException(new CompilationError[] {
322 new CompilationError("Compilation failed: imports in the current environment have failed.")
324 ExpressionEvaluator evaluator = new ExpressionEvaluator(runtimeEnvironment, localStorage, expression);
325 Function command = (Function)evaluator
326 .localEnvironment(localEnvironment)
327 .decorateExpression(true)
329 return new CompiledCommand(command, evaluator.getType());
332 class PrintDecorator extends DelegatingSCLReportingHandler {
333 public PrintDecorator(SCLReportingHandler baseHandler) {
338 public void print(String text) {
340 if(fileOutput != null)
341 fileOutput.println(text);
345 public void printCommand(String command) {
346 super.printCommand(command);
347 if(fileOutput != null)
348 fileOutput.println("> " + command);
352 public void printError(String error) {
353 super.printError(error);
354 if(fileOutput != null)
355 fileOutput.println(error);
359 @SuppressWarnings("unchecked")
360 private void execute(MemoReader reader, Expression expression, final SCLReportingHandler handler) {
361 SCLContext context = SCLContext.getCurrent();
362 Object oldPrinter = context.put(SCLReportingHandler.REPORTING_HANDLER, handler);
364 CompiledCommand command;
366 handler.printCommand(reader.extractString(expression.location));
367 command = compile(expression);
368 } catch (SCLExpressionCompilationException e) {
369 CompilationError[] errors = ((SCLExpressionCompilationException)e).getErrors();
370 for(CompilationError error : errors) {
371 if(error.location != Locations.NO_LOCATION)
372 handler.printError(reader.locationUnderlining(error.location));
373 handler.printError(error.description);
375 throw new CancelExecution();
377 reader.forgetEverythingBefore(Locations.endOf(expression.location));
379 Object resultValue = command.command.apply(variableValues);
380 String resultString = toString(resultValue, command.type);
381 if(!resultString.isEmpty())
382 handler.print(resultString);
383 } catch(Exception e) {
384 if(!(e instanceof CancelExecution)) {
385 if(e instanceof InterruptedException)
386 handler.printError("Execution interrupted.");
388 formatException(handler, e);
390 throw new CancelExecution();
392 context.put(SCLReportingHandler.REPORTING_HANDLER, oldPrinter);
396 private String toString(Object value, Type type) {
397 if(type.equals(Types.UNIT))
400 return valueToStringConverter.show(value, type);
401 } catch (SCLExpressionCompilationException e) {
402 return "<value of type " + type + ">";
406 class CommandParser extends SCLParserImpl {
407 SCLReportingHandler handler;
409 public CommandParser(SCLReportingHandler handler, MemoReader reader) {
411 this.reader = reader;
412 this.handler = handler;
417 if(currentBlock != null) {
419 LinkedList<Statement> statements = currentBlock.getStatements();
420 currentBlock.location = Locations.combine(
421 statements.getFirst().location,
422 statements.getLast().location);
423 execute(reader, currentBlock, handler);
428 protected Object reduceStatementCommand() {
429 Statement statement = (Statement)get(0);
430 if(statement.mayBeRecursive()) {
431 if(currentBlock == null)
432 currentBlock = new EBlock();
433 currentBlock.addStatement(statement);
438 if(statement instanceof GuardStatement)
439 execute(reader, ((GuardStatement)statement).value, handler);
441 EBlock block = new EBlock();
442 block.addStatement(statement);
443 block.location = statement.location;
444 execute(reader, block, handler);
451 protected Object reduceImportCommand() {
455 ImportDeclaration importDeclaration = (ImportDeclaration)get(0);
456 handler.printCommand(reader.extractString(importDeclaration.location));
457 new CommandSessionImportEntry(importDeclaration.moduleName,
458 importDeclaration.localName).addTo(importEntries);
459 updateRuntimeEnvironment(false);
464 private void checkInterrupted() {
465 if(Thread.interrupted()) {
466 defaultHandler.printError("Execution interrupted.");
467 throw new CancelExecution();
471 public void execute(Reader commandReader, SCLReportingHandler handler) {
473 handler = defaultHandler;
474 else if (!(handler instanceof PrintDecorator))
475 handler = new PrintDecorator(handler);
476 CommandParser parser = new CommandParser(handler, new MemoReader(commandReader));
478 parser.parseCommands();
479 parser.finishBlock();
480 } catch(CancelExecution e) {
481 } catch(SCLSyntaxErrorException e) {
482 handler.printCommand(parser.reader.getLastCommand());
483 if(e.location != Locations.NO_LOCATION)
484 handler.printError(parser.reader.locationUnderlining(e.location));
485 handler.printError(e.getMessage());
486 } catch(Exception e) {
487 if(e instanceof InterruptedException)
488 handler.printError("Execution interrupted.");
490 formatException(handler, e);
494 public void execute(String command) {
495 execute(new StringReader(command), null);
498 public void execute(String command, SCLReportingHandler handler) {
499 execute(new StringReader(command), handler);
502 public CompilationError[] validate(String command) {
503 return CompilationError.EMPTY_ARRAY;
506 return CompilationError.EMPTY_ARRAY;
507 } catch(SCLExpressionCompilationException e) {
508 return e.getErrors();
512 private static final String THIS_CLASS_NAME = CommandSession.class.getName();
514 public static void formatException(
515 SCLReportingHandler handler,
517 formatException(handler, null, e);
520 private static void formatException(
521 SCLReportingHandler handler,
522 StackTraceElement[] enclosingTrace,
524 StackTraceElement[] elements = e.getStackTrace();
525 Throwable cause = e.getCause();
527 formatException(handler, elements, cause);
528 handler.printError("Rethrown as ");
530 handler.printError(e.toString());
531 int endPos = elements.length;
532 if(enclosingTrace != null) {
533 int p = enclosingTrace.length;
534 while(endPos > 0 && p > 0 && elements[endPos-1].equals(enclosingTrace[p-1])) {
540 for(int i=0;i<endPos;++i) {
541 StackTraceElement element = elements[i];
542 if(element.getMethodName().equals("execute") &&
543 element.getClassName().equals(THIS_CLASS_NAME)) {
546 element = elements[endPos-1];
547 String className = element.getClassName();
548 if(className.startsWith("org.simantics.scl.compiler.top.SCLExpressionCompiler")
549 //|| element.getClassName().startsWith("org.simantics.scl.compiler.interpreted.")
550 || className.startsWith("org.simantics.scl.runtime.function.FunctionImpl")
551 //|| className.startsWith("tempsclpackage")
561 for(int i=0;i<endPos;++i) {
562 StringBuilder b = new StringBuilder();
563 StackTraceElement element = elements[i];
564 String className = element.getClassName();
565 if(className.equals("org.simantics.scl.compiler.interpreted.IApply")
566 || className.equals("org.simantics.scl.compiler.interpreted.ILet")
567 || className.startsWith("tempsclpackage"))
569 if(className.startsWith("org.simantics.scl.compiler.interpreted.ILambda")) {
570 b.append("\tat command line\n");
573 String methodName = element.getMethodName();
574 if(className.startsWith("org.simantics.scl.runtime.function.FunctionImpl") &&
575 methodName.equals("applyArray"))
577 String fileName = element.getFileName();
578 if("_SCL_Closure".equals(fileName))
581 if("_SCL_Module".equals(fileName)
582 || "_SCL_TypeClassInstance".equals(fileName))
583 b.append(NameMangling.demangle(methodName))
584 .append('(').append(element.getLineNumber()).append(')');
587 handler.printError(b.toString());
591 public void setVariable(String name, Type type, Object value) {
592 variableValues.put(name, value);
593 variableTypes.put(name, type);
596 public Object getVariableValue(String name) {
597 return variableValues.get(name);
600 public Type getVariableType(String name) {
601 return variableTypes.get(name);
604 public void removeVariable(String name) {
605 variableValues.remove(name);
606 variableTypes.remove(name);
609 public void removeVariables() {
610 variableValues.clear();
611 variableTypes.clear();
614 public Set<String> getVariables() {
615 return variableTypes.keySet();
618 public ArrayList<CommandSessionImportEntry> getImportEntries() {
619 return importEntries;
622 public void setImportEntries(
623 ArrayList<CommandSessionImportEntry> importEntries) {
624 this.importEntries = importEntries;
625 updateRuntimeEnvironment(true);
628 public void runFromFile(String fileName, SCLReportingHandler handler) {
630 Reader reader = new LaxUTF8Reader(fileName);
632 execute(reader, handler);
636 } catch(IOException e) {
637 formatException(handler, e);