use of org.eclipse.ceylon.compiler.typechecker.context.PhasedUnit in project ceylon by eclipse.
the class ModuleComplianceVisitor method main.
public static void main(String[] args) throws IOException {
System.out.println("Finding JS language module...");
File jsmod = findModule("build/runtime", "js");
if (jsmod == null && System.getenv("ceylon.repo") != null) {
jsmod = findModule(System.getenv("ceylon.repo"), "js");
}
if (jsmod == null && System.getProperty("user.home") != null) {
jsmod = findModule(System.getProperty("user.home"), "js");
}
if (jsmod == null) {
throw new IllegalStateException("Cannot find JS language module");
}
System.out.println("Finding Ceylon Language Module");
File mod = findModule("../language/build/dist", "src");
if (mod == null && System.getenv("ceylon.repo") != null) {
mod = findModule(System.getenv("ceylon.repo"), "src");
}
if (mod == null && System.getProperty("user.home") != null) {
mod = findModule(System.getProperty("user.home"), "src");
}
if (mod == null) {
throw new IllegalStateException("Cannot find JVM language module");
}
System.out.println("Reading JS language module into memory...");
FileReader reader = new FileReader(jsmod);
char[] buf = new char[16384];
StringWriter writer = new StringWriter();
while (reader.ready()) {
reader.read(buf);
writer.write(buf);
}
reader.close();
ModuleComplianceVisitor v = new ModuleComplianceVisitor(writer.toString());
System.out.println("Checking Ceylon vs JS modules...");
VFS vfs = new VFS();
TypeChecker tc = new TypeCheckerBuilder().verbose(false).addSrcDirectory(vfs.getFromZipFile(mod)).getTypeChecker();
tc.process();
for (PhasedUnit pu : tc.getPhasedUnits().getPhasedUnits()) {
pu.getCompilationUnit().visit(v);
}
}
use of org.eclipse.ceylon.compiler.typechecker.context.PhasedUnit in project ceylon by eclipse.
the class TestModelAliases method initTests.
@SuppressWarnings("unchecked")
@BeforeClass
public static void initTests() {
TestModelMethodsAndAttributes.initTypechecker();
MetamodelVisitor mmg = null;
for (PhasedUnit pu : TestModelMethodsAndAttributes.tc.getPhasedUnits().getPhasedUnits()) {
if (pu.getPackage().getModule().getNameAsString().equals("t3")) {
if (mmg == null) {
mmg = new MetamodelVisitor(pu.getPackage().getModule());
}
pu.getCompilationUnit().visit(mmg);
}
}
topLevelModel = mmg.getModel();
model = (Map<String, Object>) topLevelModel.get("t3");
}
use of org.eclipse.ceylon.compiler.typechecker.context.PhasedUnit in project ceylon by eclipse.
the class NamingTests method getDecls.
protected List<Declaration> getDecls(String resource) throws Exception {
final String name = PKGNAME.replace('.', '/') + "/" + resource;
File file = new File("test/src", name);
if (!file.exists()) {
throw new RuntimeException("Unable to find resource " + name);
}
RepositoryManagerBuilder builder = new RepositoryManagerBuilder(new NullLogger(), false, 20000, java.net.Proxy.NO_PROXY);
RepositoryManager repoManager = builder.buildRepository();
VFS vfs = new VFS();
Context context = new Context(repoManager, vfs);
PhasedUnits pus = new PhasedUnits(context);
// Make the module manager think we're looking at this package
// even though there's no module descriptor
pus.getModuleSourceMapper().push(PKGNAME);
pus.parseUnit(vfs.getFromFile(file), vfs.getFromFile(new File("test-src")));
final java.util.List<PhasedUnit> listOfUnits = pus.getPhasedUnits();
PhasedUnit pu = listOfUnits.get(0);
pu.validateTree();
pu.scanDeclarations();
pu.scanTypeDeclarations();
pu.validateRefinement();
pu.analyseTypes();
pu.analyseFlow();
return pu.getDeclarations();
}
use of org.eclipse.ceylon.compiler.typechecker.context.PhasedUnit in project ceylon by eclipse.
the class ModelLoaderTests method verifyCompilerClassLoading.
protected void verifyCompilerClassLoading(String ceylon, final ModelComparison modelCompare) {
// now compile the ceylon decl file
CeyloncTaskImpl task = getCompilerTask(ceylon);
// get the context to grab the phased units
Context context = task.getContext();
if (simpleAnnotationModels) {
CeylonEnter.instance(context);
ExpressionTransformer.getInstance(context).simpleAnnotationModels = true;
CeylonTransformer.getInstance(context).simpleAnnotationModels = true;
StatementTransformer.getInstance(context).simpleAnnotationModels = true;
ClassTransformer.getInstance(context).simpleAnnotationModels = true;
}
Boolean success = task.call();
Assert.assertTrue(success);
PhasedUnits phasedUnits = LanguageCompiler.getPhasedUnitsInstance(context);
// find out what was in that file
Assert.assertEquals(2, phasedUnits.getPhasedUnits().size());
PhasedUnit one = phasedUnits.getPhasedUnits().get(0);
PhasedUnit two = phasedUnits.getPhasedUnits().get(1);
PhasedUnit phasedUnit = one.getUnitFile().getName().endsWith("module.ceylon") ? two : one;
final Map<String, Declaration> decls = new HashMap<String, Declaration>();
for (Declaration decl : phasedUnit.getUnit().getDeclarations()) {
if (decl.isToplevel()) {
decls.put(getQualifiedPrefixedName(decl), decl);
}
}
// now compile the ceylon usage file
// remove the extension, make lowercase and add "test"
String testfile = ceylon.substring(0, ceylon.length() - 7).toLowerCase() + "test.ceylon";
JavacTaskImpl task2 = getCompilerTask(testfile);
// get the context to grab the declarations
final Context context2 = task2.getContext();
// declarations from the jar anymore because we've overridden the jar and the javac jar index is corrupted
class Listener implements TaskListener {
@Override
public void started(TaskEvent e) {
}
@Override
public void finished(TaskEvent e) {
if (e.getKind() == Kind.ENTER) {
AbstractModelLoader modelLoader = CeylonModelLoader.instance(context2);
Modules modules = LanguageCompiler.getCeylonContextInstance(context2).getModules();
// now see if we can find our declarations
compareDeclarations(modelCompare, decls, modelLoader, modules);
}
}
}
Listener listener = new Listener();
task2.setTaskListener(listener);
success = task2.call();
Assert.assertTrue("Compilation failed", success);
// now check with the runtime model loader too
String module = moduleForJavaModelLoading();
String version = "1";
ModuleWithArtifact moduleWithArtifact = new ModuleWithArtifact(module, version);
synchronized (RUN_LOCK) {
// this initialises the metamodel, even if we don't use the resulting ClassLoader
URLClassLoader classLoader;
try {
classLoader = getClassLoader("runtime model loader tests", moduleWithArtifact);
} catch (MalformedURLException e) {
throw new RuntimeException(e);
}
try {
RuntimeModuleManager moduleManager = Metamodel.getModuleManager();
RuntimeModelLoader modelLoader = moduleManager.getModelLoader();
Modules modules = moduleManager.getModules();
// now see if we can find our declarations
compareDeclarations(modelCompare, decls, modelLoader, modules);
} finally {
try {
classLoader.close();
} catch (IOException e) {
// ignore
e.printStackTrace();
}
}
}
}
use of org.eclipse.ceylon.compiler.typechecker.context.PhasedUnit in project ceylon by eclipse.
the class JsCompiler method generate.
/**
* Compile all the phased units in the typechecker.
* @return true is compilation was successful (0 errors/warnings), false otherwise.
*/
public boolean generate() throws IOException {
errorVisitor.clear();
errCount = 0;
output.clear();
try {
if (opts.isVerbose()) {
logger.debug("Generating metamodel...");
}
List<PhasedUnit> typecheckerPhasedUnits = tc.getPhasedUnits().getPhasedUnits();
List<PhasedUnit> phasedUnits = new ArrayList<>(typecheckerPhasedUnits.size());
for (PhasedUnit pu : typecheckerPhasedUnits) {
if (srcFiles == null) {
phasedUnits.add(pu);
} else {
File path = getFullPath(pu);
if (srcFiles.contains(path)) {
phasedUnits.add(pu);
}
}
}
boolean generatedCode = false;
// First generate the metamodel
final Module defmod = tc.getContext().getModules().getDefaultModule();
for (PhasedUnit pu : phasedUnits) {
// #416 default module with packages
Module mod = pu.getPackage().getModule();
if (mod.getVersion() == null && !mod.isDefaultModule()) {
// Switch with the default module
for (org.eclipse.ceylon.model.typechecker.model.Package pkg : mod.getPackages()) {
defmod.getPackages().add(pkg);
pkg.setModule(defmod);
}
}
EnumSet<Warning> suppressedWarnings = opts.getSuppressWarnings();
if (suppressedWarnings == null)
suppressedWarnings = EnumSet.noneOf(Warning.class);
pu.getCompilationUnit().visit(new WarningSuppressionVisitor<>(Warning.class, suppressedWarnings));
// Perform capture analysis
for (org.eclipse.ceylon.model.typechecker.model.Declaration d : pu.getDeclarations()) {
if (d instanceof TypedDeclaration && d instanceof org.eclipse.ceylon.model.typechecker.model.Setter == false) {
pu.getCompilationUnit().visit(new ValueVisitor((TypedDeclaration) d));
}
}
pu.getCompilationUnit().visit(getOutput(pu).mmg);
if (opts.hasVerboseFlag("ast")) {
if (opts.getOutWriter() == null) {
logger.debug(pu.getCompilationUnit().toString());
} else {
opts.getOutWriter().write(pu.getCompilationUnit().toString());
opts.getOutWriter().write('\n');
}
}
}
// Then write it out and output the reference in the module file
names = new JsIdentifierNames(this);
if (!compilingLanguageModule) {
for (Map.Entry<Module, JsOutput> e : output.entrySet()) {
e.getValue().encodeModel(names);
}
}
// Output all the require calls for any imports
final Visitor importVisitor = new Visitor() {
public void visit(Tree.Import that) {
ImportableScope scope = that.getImportMemberOrTypeList().getImportList().getImportedScope();
Module _m = that.getUnit().getPackage().getModule();
if (scope instanceof Package) {
Package pkg = (Package) scope;
Module om = pkg.getModule();
if (!om.equals(_m) && (!om.isNative() || om.getNativeBackends().supports(Backend.JavaScript))) {
Module impmod = ((Package) scope).getModule();
if (impmod instanceof NpmAware && ((NpmAware) impmod).getNpmPath() != null) {
output.get(_m).requireFromNpm(impmod, names);
} else {
output.get(_m).require(impmod, names);
}
}
}
}
public void visit(Tree.ImportModule that) {
if (that.getImportPath() != null && that.getImportPath().getModel() instanceof Module) {
Module m = (Module) that.getImportPath().getModel();
// Binary version check goes here now
int binMajorVersion = m.getJsMajor();
int binMinorVersion = m.getJsMinor();
if (m.getJsMajor() == 0) {
// Check if it's something we're compiling
for (PhasedUnit pu : tc.getPhasedUnits().getPhasedUnits()) {
if (pu.getPackage() != null && pu.getPackage().getModule() == m) {
m.setJsMajor(Versions.JS_BINARY_MAJOR_VERSION);
m.setJsMinor(Versions.JS_BINARY_MINOR_VERSION);
binMajorVersion = Versions.JS_BINARY_MAJOR_VERSION;
binMinorVersion = Versions.JS_BINARY_MINOR_VERSION;
break;
}
}
if (m.getJsMajor() == 0) {
// Load the module (most likely we're in the IDE if we need to do this)
ArtifactContext ac = new ArtifactContext(null, m.getNameAsString(), m.getVersion(), ArtifactContext.JS_MODEL);
ac.setIgnoreDependencies(true);
ac.setThrowErrorIfMissing(false);
ArtifactResult ar = tc.getContext().getRepositoryManager().getArtifactResult(ac);
if (ar == null) {
return;
}
File js = ar.artifact();
if (js != null) {
Map<String, Object> json = JsModuleSourceMapper.loadJsonModel(js);
String binVersion = json.get("$mod-bin").toString();
int p = binVersion.indexOf('.');
binMajorVersion = Integer.valueOf(binVersion.substring(0, p));
binMinorVersion = Integer.valueOf(binVersion.substring(p + 1));
}
}
}
if (!Versions.isJsBinaryVersionSupported(binMajorVersion, binMinorVersion)) {
that.addError("version '" + m.getVersion() + "' of module '" + m.getNameAsString() + "' was compiled by an incompatible version of the compiler (binary version " + binMajorVersion + "." + binMinorVersion + " of module is not compatible with binary version " + Versions.JS_BINARY_MAJOR_VERSION + "." + Versions.JS_BINARY_MINOR_VERSION + " of this compiler)");
}
}
}
};
for (PhasedUnit pu : phasedUnits) {
pu.getCompilationUnit().visit(importVisitor);
}
// Then generate the JS code
List<PhasedUnit> pkgs = new ArrayList<>(4);
if (srcFiles == null && !phasedUnits.isEmpty()) {
for (PhasedUnit pu : phasedUnits) {
if ("module.ceylon".equals(pu.getUnitFile().getName())) {
final int t = compileUnit(pu);
generatedCode = true;
if (t != 0) {
return false;
}
}
}
for (PhasedUnit pu : phasedUnits) {
if ("package.ceylon".equals(pu.getUnitFile().getName())) {
pkgs.add(pu);
continue;
} else if ("module.ceylon".equals(pu.getUnitFile().getName())) {
continue;
}
final int t = compileUnit(pu);
generatedCode = true;
if (t == 1) {
return false;
} else if (t == 2) {
break;
}
}
} else if (srcFiles != null && !srcFiles.isEmpty() && // For the specific case of the Stitcher
!typecheckerPhasedUnits.isEmpty()) {
for (PhasedUnit pu : phasedUnits) {
if ("module.ceylon".equals(pu.getUnitFile().getName())) {
final int t = compileUnit(pu);
generatedCode = true;
if (t != 0) {
return false;
}
}
}
for (File path : srcFiles) {
if (path.getPath().endsWith(ArtifactContext.JS)) {
// Just output the file
File dir = path.getParentFile();
PhasedUnit lastUnit = phasedUnits.isEmpty() ? typecheckerPhasedUnits.get(0) : phasedUnits.get(0);
for (PhasedUnit pu : phasedUnits) {
if (pu.getUnitFile().getPath().startsWith(dir.getPath())) {
lastUnit = pu;
break;
}
}
final JsOutput lastOut = getOutput(lastUnit);
VirtualFile vpath = findFile(path);
try (BufferedReader reader = new BufferedReader(new InputStreamReader(vpath.getInputStream(), opts.getEncoding()))) {
String line = null;
while ((line = reader.readLine()) != null) {
if (opts.isMinify()) {
line = line.trim();
if (!opts.isComment() && line.startsWith("//") && !line.contains("*/")) {
continue;
}
}
if (line.length() == 0) {
continue;
}
lastOut.getWriter().write(line);
lastOut.getWriter().write('\n');
}
} finally {
lastOut.addSource(path);
}
generatedCode = true;
} else {
// Find the corresponding compilation unit
for (PhasedUnit pu : phasedUnits) {
File unitFile = getFullPath(pu);
if (path.equals(unitFile)) {
if (path.getName().equals("package.ceylon")) {
pkgs.add(pu);
continue;
} else if (path.getName().equals("module.ceylon")) {
continue;
}
final int t = compileUnit(pu);
generatedCode = true;
if (t == 1) {
return false;
} else if (t == 2) {
break;
}
}
}
}
}
if (resFiles != null) {
for (Map.Entry<Module, JsOutput> entry : output.entrySet()) {
Module module = entry.getKey();
final JsOutput lastOut = getOutput(module);
for (File file : filterForModule(resFiles, opts.getResourceDirs(), module.getNameAsString())) {
String type = Files.probeContentType(file.toPath());
String fileName = file.getName();
boolean isResourceFile = fileName.endsWith(".properties") || fileName.endsWith(".txt");
if (isResourceFile || type != null && type.startsWith("text")) {
Writer writer = lastOut.getWriter();
writer.write("ex$.");
writer.write(resourceKey(module, file));
writer.write("=\"");
Pattern pattern = Pattern.compile("\\\\|\\t|\\r|\\f|\\n");
try (BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(file), opts.getEncoding()))) {
String line = null;
while ((line = reader.readLine()) != null) {
if (isResourceFile && opts.isMinify()) {
line = line.trim();
if (line.length() == 0) {
continue;
}
if (!opts.isComment() && line.startsWith("#")) {
continue;
}
}
StringBuffer result = new StringBuffer();
Matcher matcher = pattern.matcher(line);
while (matcher.find()) {
String escaped;
switch(matcher.group(0)) {
case "\\":
escaped = "\\\\\\\\";
break;
case "\t":
escaped = "\\\\t";
break;
case "\r":
escaped = "\\\\r";
break;
case "\f":
escaped = "\\\\f";
break;
case "\n":
escaped = "\\\\n";
break;
default:
throw new IllegalStateException();
}
matcher.appendReplacement(result, escaped);
}
matcher.appendTail(result);
writer.write(result.toString());
if (reader.ready()) {
writer.write("\\n");
}
}
}
writer.write("\";\n");
generatedCode = true;
}
}
}
}
}
for (PhasedUnit pu : pkgs) {
final int t = compileUnit(pu);
generatedCode = true;
if (t == 1) {
return false;
} else if (t == 2) {
break;
}
}
if (!generatedCode) {
logger.error("No source units found to compile");
exitCode = 2;
}
} finally {
if (exitCode == 0) {
exitCode = finish();
}
}
return errCount == 0 && exitCode == 0;
}
Aggregations