summaryrefslogtreecommitdiff
path: root/chapter33/src
diff options
context:
space:
mode:
Diffstat (limited to 'chapter33/src')
-rw-r--r--chapter33/src/main/java/com/seaofnodes/simple/parser/Allocations.java9
-rw-r--r--chapter33/src/main/java/com/seaofnodes/simple/parser/References.java32
-rw-r--r--chapter33/src/main/java/com/seaofnodes/simple/parser/Types.java97
-rw-r--r--chapter33/src/test/java/com/seaofnodes/simple/Chapter33Test.java55
4 files changed, 110 insertions, 83 deletions
diff --git a/chapter33/src/main/java/com/seaofnodes/simple/parser/Allocations.java b/chapter33/src/main/java/com/seaofnodes/simple/parser/Allocations.java
index 64234045..481d2851 100644
--- a/chapter33/src/main/java/com/seaofnodes/simple/parser/Allocations.java
+++ b/chapter33/src/main/java/com/seaofnodes/simple/parser/Allocations.java
@@ -16,13 +16,8 @@ final class Allocations {
Node parseNew() {
P._lexer.skipWhiteSpace();
Lexer site=P.loc();
- Type t = P.types.parseType();
- if( t==null ) {
- String tname = P._lexer.matchId();
- if( tname==null || Parser.KEYWORDS.contains(tname) )
- throw Parser.error("Expected a type after 'new'",site);
- t = P.types.forwardRefType(tname);
- }
+ Type t = P.types.parseType(true);
+ if( t==null ) throw Parser.error("Expected a type after 'new'",site);
// Parse ary[ length_expr ]
if( P.match("[") ) {
boolean readonly = P.match("~");
diff --git a/chapter33/src/main/java/com/seaofnodes/simple/parser/References.java b/chapter33/src/main/java/com/seaofnodes/simple/parser/References.java
index 91cf6859..4796995f 100644
--- a/chapter33/src/main/java/com/seaofnodes/simple/parser/References.java
+++ b/chapter33/src/main/java/com/seaofnodes/simple/parser/References.java
@@ -34,7 +34,7 @@ final class References {
P.ctrl(),P.mem(),receiver,P.fldoff(receiver,name)));
}
- // Resolve a primary name, retaining its use site before speculative type lookup.
+ // Resolve a primary name, retaining its use site before class lookup.
Node parseName(String id, int pre, int pos, int pos2) {
Lexer site=P.loc();
site._position=pos;
@@ -42,29 +42,16 @@ final class References {
// Attempt a local var lookup first
Var var = P._scope.lookup(id);
if( var==null ) {
- // Not a local var, try again as a type name
- P.pos(pos);
- Lexer nameLoc = P.loc();
- Type t = P.types.parseType();
- if( t!=null ) {
- // Static <clinit> typename lookup
- if( P.peek('.') ) // type.fld, which is really a field lookup in the class object
- return P.expressions.parsePostfix(P.con(t));
- // Direct reference to a <clinit> type. Convert the instance
- // type to a class type name
- if( !(t instanceof TypeMemPtr tmp) ) {
- //return new FRefNode(addClzPrefix(tmp._obj._name), loc()).peephole();
- // Not a local var, but yes a bare type... disallow a local
- // FREF and return null, not-a-primary parse.
- P.pos(pos);
- return null;
- }
- }
+ // A class name is a value here. Resolve only this identifier;
+ // every following dot is a Load, never part of a type parse.
+ String name = P.types.knownTypeName(id);
+ Type clz0 = name==null ? null : Parser.TYPES.get(TypeStruct.addClzPrefix(name));
// Insert FREF outside enclosing Kind.Func scope.
P.pos(pos2);
- t = FRefNode.FREF_TYPE;
+ Type t = FRefNode.FREF_TYPE;
// Check if this is a class.
+ // Even a known module needs an FRef so ParseAll records its dependency.
CompUnit cu = ParseAll.findCompUnit(P._code,P._ref,id);
if( cu!=null ) {
// Must be a final class-type
@@ -73,9 +60,10 @@ final class References {
if( clz == null )
Parser.TYPES.put(clzName,clz = TypeStruct.make(clzName,true));
t = TypeMemPtr.make((byte)2,clz,true);
- }
+ } else if( clz0 instanceof TypeStruct clz )
+ return P.expressions.parsePostfix(P.con(TypeMemPtr.make((byte)2,clz,true)));
// Define the FRef
- var = P._scope.defineFRef(id,t,true,nameLoc);
+ var = P._scope.defineFRef(id,t,true,site);
P.references._frefs.push((FRefNode)P._scope.in(var));
}
diff --git a/chapter33/src/main/java/com/seaofnodes/simple/parser/Types.java b/chapter33/src/main/java/com/seaofnodes/simple/parser/Types.java
index 501924f0..8c19e897 100644
--- a/chapter33/src/main/java/com/seaofnodes/simple/parser/Types.java
+++ b/chapter33/src/main/java/com/seaofnodes/simple/parser/Types.java
@@ -21,7 +21,11 @@ final class Types {
// Will also match external names like "sys.io" or "externModule.subtype.subtype"
- Type parseType() {
+ Type parseType() { return parseType(false); }
+
+ // After new, a type needs no following binding. In a declaration/parameter
+ // an unknown name is only a type when followed by a binding name.
+ Type parseType(boolean allocation) {
if( P.peek('{') ) return parseFunctionType();
int old1 = P.pos();
@@ -30,19 +34,14 @@ final class Types {
String tname = P._lexer.matchId();
if( tname==null ) return P.posT(old1);
+ Ary<String> forwards = new Ary<>(String.class);
Type t0 = Parser.TYPES.get(tname);
if( Parser.KEYWORDS.contains(tname) ) {
if( t0==null ) return P.posT(old1);
} else {
if( t0==Type.BOTTOM || t0==Type.TOP ) return t0; // var/val
- tname = typeName(tname).intern();
+ tname = typeName(tname,forwards).intern();
t0 = Parser.TYPES.get(tname);
- // Bare forward types use the same file-relative name as `new`.
- // A later sibling declaration must complete this very type.
- if( t0 == null && tname.indexOf('.') == -1 ) {
- tname = fullTypeName(tname);
- t0 = Parser.TYPES.get(tname);
- }
}
Type t1 = t0==null ? TypeStruct.forward(tname) : t0;
@@ -76,36 +75,31 @@ final class Types {
break;
}
- // Check no forward ref
- if( t0 != null ) return t2;
// Check valid forward ref, after parsing all the type extra bits.
// Cannot check earlier, because cannot find required 'id' until after "[]?" syntax
- int old2 = P.pos();
- P.match("^"); // Constructor parameter qualifier; parsed by Functions.
- if( !P.match("!") ) P.match("~");
- String id = P._lexer.matchId();
- if( !(P.peek(',') || P.peek(';') || P.peek('=') || P.match("->")) || id==null )
- return P.posT(old1); // Reset lexer to reparse
- P.pos(old2); // Reset lexer to reparse
- // Yes a forward ref, so declare it
- forwardRefType(tname,(TypeStruct)((TypeMemPtr)t1)._obj);
+ if( t0==null && !allocation ) {
+ int old2 = P.pos();
+ P.match("^"); // Constructor parameter qualifier; parsed by Functions.
+ if( !P.match("!") ) P.match("~");
+ String id = P._lexer.matchId();
+ if( !(P.peek(',') || P.peek(';') || P.peek('=') || P.match("->")) || id==null )
+ return P.posT(old1); // Reset lexer to reparse
+ P.pos(old2); // Reset lexer to reparse
+ }
+ // Commit only after recognizing a type, never during expression lookahead.
+ for( String name : forwards )
+ forwardRefType(name,TypeStruct.forward(name));
// Return the (array, final) type
return t2;
}
- TypeMemPtr forwardRefType( String tname, TypeStruct tself ) {
+ private void forwardRefType( String tname, TypeStruct tself ) {
Parser.TYPES.put(tname,tself);
String clzName = TypeStruct.addClzPrefix( tname );
// Only a struct declaration publishes an instance initializer. A
// forward type may name a file with just <clinit>, so do not invent
// a constructor field (or overwrite an already parsed class).
Parser.TYPES.putIfAbsent(clzName,TypeStruct.make(clzName,true));
- return TypeMemPtr.make(tself);
- }
-
- TypeMemPtr forwardRefType( String tname ) {
- tname = fullTypeName(tname);
- return forwardRefType(tname,TypeStruct.forward(tname));
}
String fullTypeName( String tname ) {
@@ -195,57 +189,52 @@ final class Types {
return fld;
}
- // typeName: walk known local types first, then enclosing namespaces, then
- // file modules. A missing suffix of a known type belongs to field parsing.
- private String typeName(String name) {
- if( Parser.TYPES.containsKey(name) ) return dottedName(name,false);
+ // TODO: Backport qualified-name parsing to Chapters 28a-32.
+ // Resolve only the first component. Expression lookup uses this without
+ // consuming member access; type lookup then consumes the qualified tail.
+ String knownTypeName(String name) {
+ if( Parser.TYPES.containsKey(name) || Parser.TYPES.containsKey(TypeStruct.addClzPrefix(name)) ) return name;
String root = P._nestedType;
int dot = root.indexOf('.');
if( dot!=-1 ) root = root.substring(0,dot);
- if( name.equals(root) ) return rootedName(name);
+ if( name.equals(root) ) return name;
for( String nest = P._nestedType; ; ) {
String full = nest+"."+name;
- if( Parser.TYPES.containsKey(full) ) return dottedName(full,false);
+ if( Parser.TYPES.containsKey(full) || Parser.TYPES.containsKey(TypeStruct.addClzPrefix(full)) ) return full;
int idx = nest.lastIndexOf('.');
if( idx==-1 ) break;
nest = nest.substring(0,idx);
}
- CompUnit cu = ParseAll.findCompUnit(P._code,P._ref,name);
- return dottedName(cu==null ? name : cu._cname,true);
+ return null;
}
- private String dottedName(String name, boolean forward) {
+ private String typeName(String id, Ary<String> forwards) {
+ String name = knownTypeName(id);
+ if( name==null ) {
+ CompUnit cu = ParseAll.findCompUnit(P._code,P._ref,id);
+ name = cu==null ? fullTypeName(id) : cu._cname;
+ }
+ if( !Parser.TYPES.containsKey(name) ) forwards.push(name.intern());
while( true ) {
int old = P.pos();
if( !P.match(".") ) return name;
String part = P.matchId();
- if( part==null || (!forward && !Parser.TYPES.containsKey(name+"."+part)) ) {
+ if( part==null ) {
P.pos(old);
return name;
}
- name += "."+part;
- }
- }
-
- // A root-qualified name may introduce an as-yet-undeclared nested type
- // inside the current lexical namespace. Once forward, keep its full tail.
- private String rootedName(String name) {
- boolean forward = false;
- while( true ) {
- int old = P.pos();
- if( !P.match(".") ) return name;
- String part = P.matchId();
- if( part==null ) { P.pos(old); return name; }
String full = name+"."+part;
- boolean known = Parser.TYPES.containsKey(full);
- if( !known && !forward &&
- !(P._nestedType.equals(name) || P._nestedType.startsWith(name+".")) ) {
+ Type parent = Parser.TYPES.get(name);
+ // Closed types can still be followed by an allocation's member
+ // access, e.g. new Counter.step(). Open types admit nested names,
+ // whether they are forward refs or definitions still being parsed.
+ if( !Parser.TYPES.containsKey(full) && parent instanceof TypeStruct ts && !ts._open ) {
P.pos(old);
return name;
}
- name = full;
- forward |= !known;
+ name = full.intern();
+ if( !Parser.TYPES.containsKey(name) ) forwards.push(name);
}
}
diff --git a/chapter33/src/test/java/com/seaofnodes/simple/Chapter33Test.java b/chapter33/src/test/java/com/seaofnodes/simple/Chapter33Test.java
index 99dc4452..b625f989 100644
--- a/chapter33/src/test/java/com/seaofnodes/simple/Chapter33Test.java
+++ b/chapter33/src/test/java/com/seaofnodes/simple/Chapter33Test.java
@@ -3,6 +3,9 @@ package com.seaofnodes.simple;
import com.seaofnodes.simple.codegen.CodeGen;
import com.seaofnodes.simple.node.*;
import com.seaofnodes.simple.util.WorkList;
+import com.seaofnodes.simple.type.TypeInteger;
+import java.nio.file.Files;
+import java.nio.file.Path;
import org.junit.Test;
import static org.junit.Assert.*;
@@ -41,4 +44,56 @@ public class Chapter33Test {
assertTrue(rewritten.isDead());
assertEquals("42",Eval2.eval(code,42));
}
+ // Reduced from Clock: the preceding qualified new used to leave only
+ // a sys placeholder, causing the parameter to stop at the first dot.
+ @Test public void testSourceQualifiedCanvasParameter() throws Exception {
+ Path out=Files.createTempDirectory(Files.createDirectories(Path.of("build/objs")),"canvas-source-");
+ CodeGen code=new CodeGen("src/main/smp",out.toString(),null,"Clock","""
+ val _survey_sys = sys;
+ val main = { -> new sys.draw.Canvas(320,240); };
+ val _draw = { sys.draw.Canvas screen -> screen.width; };
+ return 0;
+ """,456,true,TypeInteger.BOT);
+ code.driver(CodeGen.Phase.Parse);
+ }
+
+ @Test public void testQualifiedForwardTypeChain() {
+ CodeGen code=new CodeGen("""
+ val make={ -> new A.B.C.D(); };
+ val read={ A.B.C.D d -> d.x; };
+ A.B.C.D? saved=null;
+ struct A { struct B { struct C { struct D { int x=42; }; }; }; };
+ return read(make());
+ """).driver(CodeGen.Phase.TypeCheck);
+ assertEquals("42",Eval2.eval(code,0));
+ }
+
+ @Test public void testQualifiedTypeThroughOpenDefinition() {
+ CodeGen code=new CodeGen("""
+ struct A {
+ val make={ -> new A.B.C.D(); };
+ struct B { struct C { struct D { int x=42; }; }; };
+ };
+ return new A.make().x;
+ """).driver(CodeGen.Phase.TypeCheck);
+ assertEquals("42",Eval2.eval(code,0));
+ }
+
+ @Test public void testQualifiedExpressionIsMemberAccess() throws Exception {
+ Path root=Files.createTempDirectory(Files.createDirectories(Path.of("build/objs")),"qualified-expr-");
+ Files.createDirectories(root.resolve("sys/draw"));
+ Files.writeString(root.resolve("sys.smp"),"val draw=draw;");
+ Files.writeString(root.resolve("sys/draw.smp"),"val Canvas=Canvas;");
+ Files.writeString(root.resolve("sys/draw/Canvas.smp"),"int foo=42;");
+ CodeGen code=new CodeGen(root.toString(),root.resolve("obj").toString(),null,"Clock","""
+ val keep=sys;
+ sys.draw.Canvas.foo;
+ if( sys.draw.Canvas.foo ) return sys.draw.Canvas.foo;
+ return 0;
+ """,456,true,TypeInteger.BOT).driver(CodeGen.Phase.TypeCheck);
+ assertEquals("42",Eval2.eval(code,0));
+ for( String name : com.seaofnodes.simple.parser.Parser.TYPES.keySet() )
+ assertFalse("Expression lookahead created a type: "+name,name.endsWith(".foo"));
+ }
+
}