package org.shedlang.compiler.backends; import org.shedlang.compiler.backends.paths.PartialTargetPath; import org.shedlang.compiler.backends.paths.TargetDir; import org.shedlang.compiler.backends.targets.ShedTarget; import org.shedlang.compiler.config.ProfileConfig; import org.shedlang.compiler.config.ProjectConfig; import org.shedlang.compiler.patio.PatioCompilationUnit; import org.shedlang.compiler.patio.PatioSerializer; import org.shedlang.compiler.shid.ShidNamespace; import org.shedlang.compiler.typechecker.TypeInfos; import org.shedlang.compiler.types.NamespaceName; import java.io.IOException; import java.nio.file.Files; import java.util.List; import java.util.Optional; public class PatioTextBackend implements Backend { public static final BackendFactory FACTORY = new BackendFactory() { @Override public String name() { return "patio-text"; } @Override public Optional backendForTarget(ShedTarget target) { if (target == ShedTarget.PATIO_TEXT) { return Optional.of(PatioTextBackend.INSTANCE); } else { return Optional.empty(); } } }; public static final PatioTextBackend INSTANCE = new PatioTextBackend(); private PatioTextBackend() { } @Override public String targetName() { return "patio-text"; } public void compile( ProjectConfig config, ProfileConfig profileConfig, List namespaces, TypeInfos typeInfos, TargetDir targetDir ) throws IOException, InterruptedException { PatioBackends.compile( config, profileConfig, namespaces, typeInfos, new PatioToText(targetDir) ); } private static class PatioToText implements PatioBackends.PatioToTarget { private final TargetDir targetDir; public PatioToText(TargetDir targetDir) { this.targetDir = targetDir; } @Override public PatioBackends.PatioToTarget namespace( NamespaceName namespaceName, PatioCompilationUnit patioCompilationUnit ) throws IOException, InterruptedException { serializeToDisk( targetDir.namespace(namespaceName), patioCompilationUnit ); return this; } @Override public void bin( String binName, PatioCompilationUnit patioCompilationUnit, String mainFunctionName, ProfileConfig profileConfig ) throws IOException, InterruptedException { serializeToDisk( targetDir.bin(binName), patioCompilationUnit ); } private void serializeToDisk( PartialTargetPath partialTargetPath, PatioCompilationUnit patioCompilationUnit ) throws IOException { var builder = new StringBuilder(); PatioSerializer.serializeCompilationUnit(patioCompilationUnit, builder); var compilationUnitString = builder.toString(); var path = partialTargetPath.withExtension(".patio-text"); Files.createDirectories(path.getParent()); Files.writeString(path, compilationUnitString); } } }