summaryrefslogtreecommitdiff
path: root/chapter31/src/main
diff options
context:
space:
mode:
Diffstat (limited to 'chapter31/src/main')
-rw-r--r--chapter31/src/main/java/com/seaofnodes/simple/codegen/ParseAll.java5
-rw-r--r--chapter31/src/main/java/com/seaofnodes/simple/node/CallNode.java9
-rw-r--r--chapter31/src/main/java/com/seaofnodes/simple/node/LoadNode.java10
-rw-r--r--chapter31/src/main/java/com/seaofnodes/simple/node/StoreNode.java4
-rw-r--r--chapter31/src/main/java/com/seaofnodes/simple/parser/Declarations.java4
-rw-r--r--chapter31/src/main/java/com/seaofnodes/simple/parser/Functions.java61
-rw-r--r--chapter31/src/main/java/com/seaofnodes/simple/parser/MethodAccess.java130
-rw-r--r--chapter31/src/main/java/com/seaofnodes/simple/parser/Parser.java6
-rw-r--r--chapter31/src/main/java/com/seaofnodes/simple/parser/README.md13
-rw-r--r--chapter31/src/main/java/com/seaofnodes/simple/parser/References.java11
-rw-r--r--chapter31/src/main/java/com/seaofnodes/simple/parser/Types.java11
-rw-r--r--chapter31/src/main/java/com/seaofnodes/simple/parser/Var.java5
-rw-r--r--chapter31/src/main/smp/sys/draw/Canvas.smp2
13 files changed, 254 insertions, 17 deletions
diff --git a/chapter31/src/main/java/com/seaofnodes/simple/codegen/ParseAll.java b/chapter31/src/main/java/com/seaofnodes/simple/codegen/ParseAll.java
index 3306ff8f..882a0f8a 100644
--- a/chapter31/src/main/java/com/seaofnodes/simple/codegen/ParseAll.java
+++ b/chapter31/src/main/java/com/seaofnodes/simple/codegen/ParseAll.java
@@ -150,7 +150,8 @@ public abstract class ParseAll {
}
private static void addRequiredTypes(CodeGen code, CompUnit cunit) {
- for( String typeName : code.P._requiredTypes ) {
+ for( var required : code.P._requiredTypes.entrySet() ) {
+ String typeName = required.getKey();
// A forward use can have been resolved later in this source file.
if( Parser.TYPES.get(typeName) instanceof TypeStruct ts && !ts._fref ) continue;
try {
@@ -158,7 +159,7 @@ public abstract class ParseAll {
if( xcunit != null )
cunit.addDep(xcunit);
else
- assert false : "expected to find required type";
+ throw Parser.error("Unknown type '"+typeName+"'",required.getValue());
} catch( IOException ioe ) {
throw new RuntimeException(ioe);
}
diff --git a/chapter31/src/main/java/com/seaofnodes/simple/node/CallNode.java b/chapter31/src/main/java/com/seaofnodes/simple/node/CallNode.java
index 690acfb9..9e9c5224 100644
--- a/chapter31/src/main/java/com/seaofnodes/simple/node/CallNode.java
+++ b/chapter31/src/main/java/com/seaofnodes/simple/node/CallNode.java
@@ -256,6 +256,15 @@ public class CallNode extends CFGNode {
// Constructors return private memory and carry hidden self and
// selfMem arguments ahead of the source-level arguments.
int argno = i - (tfp.ret() instanceof TypeMem ? 2 : 0);
+ // Access qualifiers are not shown by the structural type dump.
+ // Report the differing permission instead of two huge shapes.
+ if( arg(i+2)._type instanceof TypeMemPtr actual && actual._ro &&
+ tfp.arg(i) instanceof TypeMemPtr formal && !formal._ro ) {
+ String who = i == 0 ? name() == null ? "Receiver" : "Receiver for method '"+name()+"'"
+ : "Argument #"+argno;
+ return Parser.error(who+" is read-only "+actual._obj.str()+
+ "; expected writable "+formal._obj.str(),_loc);
+ }
return Parser.error( "Argument #" + argno + " isa " + arg(i+2)._type + ", but must be a " + tfp.arg(i), _loc );
}
diff --git a/chapter31/src/main/java/com/seaofnodes/simple/node/LoadNode.java b/chapter31/src/main/java/com/seaofnodes/simple/node/LoadNode.java
index 35db4c2f..14efa315 100644
--- a/chapter31/src/main/java/com/seaofnodes/simple/node/LoadNode.java
+++ b/chapter31/src/main/java/com/seaofnodes/simple/node/LoadNode.java
@@ -98,7 +98,15 @@ public class LoadNode extends MemOpNode {
t = mem._alias==_alias ? mem._t : actual==null ? TypeScalar.BOT : actual._t;
} else if( mem._alias==_alias )
t = t.join(mem._t);
- if( !mem._one ) t = mem.outside(t);
+ // A final method's identity comes from its declaration, not from an
+ // unknown outside writer. It remains callable on a local object even
+ // when that function has never escaped to outside code.
+ if( !mem._one ) {
+ Type declared = Parser.TYPES.get(tmp._obj._name);
+ Field field = declared instanceof TypeStruct obj ? obj.field(_name) : null;
+ if( !(field != null && field._final && field._t instanceof TypeFunPtr fun && fun.isConstant()) )
+ t = mem.outside(t);
+ }
// Store forwarding is also a value fact during SCCP. Waiting for the
// later rewrite can turn a known non-null stored pointer into a
// nullable declaration, then BOTTOM at the next dereference.
diff --git a/chapter31/src/main/java/com/seaofnodes/simple/node/StoreNode.java b/chapter31/src/main/java/com/seaofnodes/simple/node/StoreNode.java
index 010d5f61..204e0c4b 100644
--- a/chapter31/src/main/java/com/seaofnodes/simple/node/StoreNode.java
+++ b/chapter31/src/main/java/com/seaofnodes/simple/node/StoreNode.java
@@ -243,6 +243,10 @@ public class StoreNode extends MemOpNode {
private byte storageType() {
if( !(ptr()._type instanceof TypeMemPtr tmp) )
return 0;
+ // Completing a forward declaration changes TYPES without changing
+ // this Store's inputs. Wait for the pointer's type upgrade, which
+ // queues its users, before consulting the completed declaration.
+ if( tmp._obj._fref ) return 0;
TypeStruct obj = (TypeStruct)Parser.TYPES.get(tmp._obj._name);
Field fld = obj.field(_name);
if( fld == null || fld._t == null )
diff --git a/chapter31/src/main/java/com/seaofnodes/simple/parser/Declarations.java b/chapter31/src/main/java/com/seaofnodes/simple/parser/Declarations.java
index 13fa59b8..473a7c24 100644
--- a/chapter31/src/main/java/com/seaofnodes/simple/parser/Declarations.java
+++ b/chapter31/src/main/java/com/seaofnodes/simple/parser/Declarations.java
@@ -91,6 +91,10 @@ final class Declarations {
// expr is a constant function
if( t instanceof TypeFunPtr decl && expr._type instanceof TypeFunPtr tfp && tfp.isConstant() ) {
t = decl.makeFrom(tfp.fidx());
+ // The explicit signature specifies source parameters/return;
+ // the receiver of a method body is still inferred.
+ if( expr instanceof FunPtrNode && P.structs.inStructDeclaration() )
+ t = ((TypeFunPtr)t).makeFrom(tfp.arg(0),0);
FunNode fun = P._code.link(tfp);
if( fun != null )
fun.setName(name); // Assign debug name to Simple function
diff --git a/chapter31/src/main/java/com/seaofnodes/simple/parser/Functions.java b/chapter31/src/main/java/com/seaofnodes/simple/parser/Functions.java
index 8047fabc..84bd509e 100644
--- a/chapter31/src/main/java/com/seaofnodes/simple/parser/Functions.java
+++ b/chapter31/src/main/java/com/seaofnodes/simple/parser/Functions.java
@@ -14,6 +14,11 @@ final class Functions {
// Merge all function exits here.
ScopeNode _returnScope;
+ // Instance method headers are available immediately; their bodies need
+ // the complete field scope, just like explicitly declared constructors.
+ private record Method(FunPtrNode ptr, Lexer body, Lexer loc, BitSet finals, String[] ids) {}
+ private Ary<Method> _methods;
+
Functions(Parser P) { this.P = P; }
/**
@@ -29,6 +34,7 @@ final class Functions {
Ary<String> ids = new Ary<>(String.class);
BitSet finals = new BitSet();
Type self = P.types.implicitSelfType();
+ if( P.structs.inStructDeclaration() ) self = self.makeRO();
ts.push(self);
ids.push(self == TypePtr.PTR ? "#self" : "self");
@@ -38,10 +44,49 @@ final class Functions {
parameters(ts,ids,finals,false);
// Make a concrete function type, with a fidx
TypeFunPtr tfp = TypeFunPtr.make1((byte)2,true,ts.asAry(),Type.BOTTOM,P._code.fidx(P._ref._cname));
+ if( P.structs.inStructDeclaration() ) {
+ FunPtrNode ptr = (FunPtrNode)new FunPtrNode(tfp,P._code._start,null).peephole().keep();
+ _methods.push(new Method(ptr,P.loc(),loc,finals,ids.asAry()));
+ P._lexer.skipTo('{','}',"method body");
+ return ptr;
+ }
ReturnNode ret = parseFunctionBody(tfp,loc,finals,ids.asAry());
return new FunPtrNode(tfp,P._code._start,ret).peephole();
}
+ private void finishMethods() {
+ if( _methods == null ) return;
+ Ary<Method> methods = _methods;
+ Lexer after = P._lexer;
+ for( Method method : methods ) {
+ P._lexer = new Lexer(method.body());
+ TypeFunPtr sig = (TypeFunPtr)method.ptr()._con;
+ ReturnNode ret = parseFunctionBody(sig,method.loc(),method.finals(),method.ids());
+ method.ptr().setDef(1,ret);
+ P.require("}");
+ }
+ Ary<FunNode> functions = new Ary<>(FunNode.class);
+ for( Method method : methods ) functions.add(method.ptr().fun());
+ MethodAccess.infer(functions);
+ for( Method method : methods ) {
+ ReturnNode ret = method.ptr().ret();
+ TypeFunPtr sig = ret.fun().sig();
+ method.ptr().peephole();
+ // Declarations saw the header before its FunNode existed.
+ for( Var var : P._scope._vars )
+ if( var.type() instanceof TypeFunPtr tfp && tfp.isConstant() && tfp.fidx() == sig.fidx() ) {
+ ret.fun().setName(var._name);
+ var.refineType(var.type().join(method.ptr()._type));
+ TypeStruct self = P._scope.constructorSelf();
+ TypeStruct shape = (TypeStruct)Parser.TYPES.get(self._name);
+ Parser.TYPES.put(shape._name,shape.replace(shape.field(var._name).makeFrom(var.type())));
+ break;
+ }
+ method.ptr().unkeep();
+ }
+ P._lexer = after;
+ }
+
Node parseConstructor(String name, boolean explicit) {
P.require("{");
Ary<Type> ts = new Ary<>(Type.class);
@@ -203,6 +248,8 @@ final class Functions {
Structs.Constructor outerCtor = P.structs._pendingCtor;
P.structs._pendingCtor = null;
boolean isInit = FunNode.isInit(funName);
+ Ary<Method> outerMethods = _methods;
+ _methods = FunNode.isInstance(funName) ? new Ary<>(Method.class) : null;
boolean isCtor = isInit || P.structs.isExplicitConstructorName(funName);
String typeName = isCtor ? ((TypeMemPtr)sig._sig[0])._obj._name : null;
@@ -235,7 +282,11 @@ final class Functions {
nvar = P.structs.updateSelfAsFieldsDiscovered( typeName, nvar );
}
- if( isInit ) P.structs.finishConstructor();
+ if( isInit ) {
+ finishMethods();
+ P.structs.finishConstructor();
+ }
+ _methods = outerMethods;
P.structs._pendingCtor = outerCtor;
ParmNode self = fun.parm(2);
@@ -303,8 +354,14 @@ final class Functions {
// All args, "as-if" called externally
for( int i = 0; i<ids.length; i++ ) {
Type t = sig.arg(i);
+ // Parse an implicit receiver with write access, then infer the
+ // public requirement from its uses once every method is present.
+ if( i == 0 && ids[0].equals("self") && !FunNode.isInit(funName) &&
+ !(sig.ret() instanceof TypeMem) && t instanceof TypeMemPtr ptr )
+ t = ptr.withAccess(false);
// Args take a default input if called from Start/external-world
- Node parm = new ParmNode(ids[i],i+2,t,fun,ConstantNode.seed(fun.defaultArg(i)).peephole()).peephole();
+ Type seed = i == 0 && t instanceof TypeMemPtr ? t : fun.defaultArg(i);
+ Node parm = new ParmNode(ids[i],i+2,t,fun,ConstantNode.seed(seed).peephole()).peephole();
if( t instanceof TypeMemPtr ptr && ptr._partial ) parm = new ConstructNode(parm).peephole();
P._scope.define(ids[i], t, (i==0 && ids[0]=="self") || (finals!=null && finals.get(i)), parm, loc);
}
diff --git a/chapter31/src/main/java/com/seaofnodes/simple/parser/MethodAccess.java b/chapter31/src/main/java/com/seaofnodes/simple/parser/MethodAccess.java
new file mode 100644
index 00000000..099ba036
--- /dev/null
+++ b/chapter31/src/main/java/com/seaofnodes/simple/parser/MethodAccess.java
@@ -0,0 +1,130 @@
+package com.seaofnodes.simple.parser;
+
+import com.seaofnodes.simple.node.*;
+import com.seaofnodes.simple.codegen.CodeGen;
+import com.seaofnodes.simple.type.*;
+import com.seaofnodes.simple.util.Ary;
+import java.util.ArrayDeque;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.Collections;
+import java.util.IdentityHashMap;
+import java.util.Set;
+
+/** Infer the access required through an instance method's receiver. */
+final class MethodAccess {
+ private final FunNode _fun;
+ private final Set<Node> _aliases = Collections.newSetFromMap(new IdentityHashMap<>());
+ private final Set<MethodAccess> _calls = new HashSet<>();
+ private boolean _writes;
+
+ private MethodAccess(FunNode fun) { _fun = fun; }
+
+ static void infer(Ary<FunNode> functions) {
+ HashMap<Integer,MethodAccess> methods = new HashMap<>();
+ for( FunNode fun : functions ) methods.put(fun.sig().fidx(),new MethodAccess(fun));
+ for( MethodAccess method : methods.values() ) method.scan(methods);
+ boolean changed;
+ do {
+ changed = false;
+ for( MethodAccess method : methods.values() )
+ if( !method._writes )
+ for( MethodAccess callee : method._calls )
+ if( callee._writes ) { method._writes = true; changed = true; break; }
+ } while( changed );
+ for( MethodAccess method : methods.values() ) method.finish();
+ }
+
+ private void scan(HashMap<Integer,MethodAccess> methods) {
+ if( _fun.parm(2) == null ) return; // Unused receiver.
+ ArrayDeque<Node> work = new ArrayDeque<>();
+ work.add(_fun.parm(2));
+ while( !work.isEmpty() ) {
+ Node value = work.remove();
+ if( !_aliases.add(value) ) continue;
+ for( Node use : value._outputs ) {
+ if( use == null || use instanceof ReadOnlyNode ) continue;
+ if( use instanceof StoreNode store ) {
+ if( store.ptr() == value || store.val() == value ) _writes = true;
+ } else if( use instanceof CallNode call ) {
+ for( int i = 2; i < call.nIns()-1; i++ )
+ if( call.in(i) == value ) call(call,i-2,methods);
+ } else if( use instanceof ReturnNode ret ) {
+ // Returning a writable alias must not grant write access
+ // to an object reached through a read-only receiver.
+ if( ret.expr() == value ) _writes = true;
+ } else if( use instanceof LoadNode load && load.ptr() == value ) {
+ Type type = type(load);
+ if( type instanceof TypeMemPtr ptr ) {
+ if( !ptr._ro ) work.add(load);
+ } else if( type == Type.BOTTOM || type == TypeScalar.BOT ) _writes = true;
+ } else if( use instanceof PhiNode || use instanceof GuardNode ) {
+ work.add(use);
+ } else if( use instanceof ConvertNode convert ) {
+ if( !(convert.dst() instanceof TypeMemPtr ptr && ptr._ro) ) _writes = true;
+ } else if( use instanceof BoolNode || use instanceof NotNode ||
+ use instanceof FldOffNode || use instanceof ScopeNode || use instanceof CLInitNode ) {
+ // Comparisons and field offsets do not expose write access.
+ } else {
+ // Includes raw-address casts and unrecognized escapes.
+ _writes = true;
+ }
+ }
+ }
+ }
+
+ private void call(CallNode call, int arg, HashMap<Integer,MethodAccess> methods) {
+ // Every member of this struct is now declared. An unresolved bare
+ // function name belongs to an outer scope, whose hidden slot is not self.
+ if( arg == 0 && call.fptr() instanceof FRefNode ) return;
+ Type type = type(call.fptr());
+ if( !(type instanceof TypeFunPtr sig) || arg >= sig.nargs() ) { _writes = true; return; }
+ if( arg == 0 && sig.arg(0) == TypePtr.PTR ) return;
+ if( arg == 0 ) {
+ if( XInt.isHigh(sig.fidxs()) ) { _writes = true; return; }
+ for( int fidx = XInt.next(sig.fidxs(),-1); fidx >= 0; fidx = XInt.next(sig.fidxs(),fidx) ) {
+ MethodAccess local = methods.get(fidx);
+ if( local != null ) _calls.add(local);
+ else {
+ FunNode target = CodeGen.CODE.link(fidx);
+ Type receiver = target == null ? sig.arg(0) : target.sig().arg(0);
+ if( !(receiver instanceof TypeMemPtr ptr && ptr._ro) ) _writes = true;
+ }
+ }
+ return;
+ }
+ if( !(sig.arg(arg) instanceof TypeMemPtr ptr && ptr._ro) ) _writes = true;
+ }
+
+ private static Type type(Node value) {
+ // Flow types can still be BOTTOM while the parser discovers fields.
+ if( value instanceof LoadNode load ) {
+ TypeStruct obj = load.off() instanceof ConFldOffNode off ? off._ts :
+ type(load.ptr()) instanceof TypeMemPtr ptr ? ptr._obj : null;
+ if( obj != null ) {
+ if( !obj.isAry() && Parser.TYPES.get(obj._name) instanceof TypeStruct latest ) obj = latest;
+ Field field = obj.field(load._name);
+ if( field != null ) return field._t;
+ }
+ }
+ return value._type;
+ }
+
+ private void finish() {
+ ParmNode self = _fun.parm(2);
+ if( self == null ) return;
+ TypeMemPtr receiver = ((TypeMemPtr)self._declaredType).withAccess(!_writes);
+ _fun.setSig(_fun.sig().makeFrom(receiver,0));
+ if( _writes ) return;
+ self._declaredType = receiver;
+ self.setDef(1,ConstantNode.seed(receiver).peephole());
+ // These parser-time assumptions are settled before Iter/SCCP. No
+ // writable alias escapes a method classified as read-only.
+ for( Node alias : _aliases )
+ if( alias._type instanceof TypeMemPtr ptr ) {
+ alias._type = ptr.makeRO();
+ CodeGen.CODE.add(alias);
+ CodeGen.CODE.addAll(alias._outputs);
+ }
+ }
+}
diff --git a/chapter31/src/main/java/com/seaofnodes/simple/parser/Parser.java b/chapter31/src/main/java/com/seaofnodes/simple/parser/Parser.java
index 3e7bb6b8..9c18385d 100644
--- a/chapter31/src/main/java/com/seaofnodes/simple/parser/Parser.java
+++ b/chapter31/src/main/java/com/seaofnodes/simple/parser/Parser.java
@@ -7,7 +7,7 @@ import com.seaofnodes.simple.type.*;
import com.seaofnodes.simple.util.Ary;
import java.util.HashMap;
import java.util.HashSet;
-import java.util.LinkedHashSet;
+import java.util.LinkedHashMap;
import java.util.Stack;
/** Source-unit entry point and shared cursor, scope, and IR utilities.
@@ -92,7 +92,7 @@ public class Parser {
public final Stack<ScopeNode> _xScopes = new Stack<>();
// Layouts needed by field accesses in this source file. Resolve after
// parsing, since a later local struct declaration can satisfy the use.
- public final LinkedHashSet<String> _requiredTypes = new LinkedHashSet<>();
+ public final LinkedHashMap<String,Lexer> _requiredTypes = new LinkedHashMap<>();
// Mapping from a type name to a Type. The string name matches
// `type.str()` call.
@@ -271,7 +271,7 @@ public class Parser {
// Field offset for an unknown type
public Node fldoff( Node n, String name ) {
if( n._type instanceof TypeMemPtr ptr && ptr._obj._fref )
- _requiredTypes.add(ptr._obj._name);
+ _requiredTypes.putIfAbsent(ptr._obj._name,loc());
return new FldOffNode(n,name,loc()).peephole();
}
public Node peep( Node n ) {
diff --git a/chapter31/src/main/java/com/seaofnodes/simple/parser/README.md b/chapter31/src/main/java/com/seaofnodes/simple/parser/README.md
index c70dcaba..e6281e50 100644
--- a/chapter31/src/main/java/com/seaofnodes/simple/parser/README.md
+++ b/chapter31/src/main/java/com/seaofnodes/simple/parser/README.md
@@ -14,6 +14,7 @@ productions to their entry points.
| `Declarations.java` | Bindings, initializers, mutability modifiers, and native declarations. |
| `Types.java` | Type syntax, qualified-name lookup, arrays, function types, and forward types. |
| `Functions.java` | Function expressions, parameters, arguments, calls, and function entry/return graphs. |
+| `MethodAccess.java` | Infers whether an instance method needs writable access through its receiver. |
| `Structs.java` | Struct and constructor declarations, field discovery, and initialization Stores. |
| `Construction.java` | Selects private self memory during parsing; its comment explains BOT fields, the TypeMemPtr qualifier, and checks deferred to TypeCheck. |
| `References.java` | Bare-name and field resolution, implicit receivers, assignments, and forward references. |
@@ -23,8 +24,16 @@ productions to their entry points.
| `Var.java` | Lexical binding metadata: name, type, scope slot, and mutability. |
Start with `Statements.parseStatement` or `Expressions.parseAssignment` to follow
-the grammar. Loop updates are parsed after their bodies, and declared constructor
-bodies after field discovery; `Lexer.skipTo` scans these deferred fragments.
+the grammar. Loop updates are parsed after their bodies. Instance method headers
+are parsed immediately, but their bodies and declared constructor bodies wait
+until all fields are known. Methods can therefore use fields declared later in
+the struct. `Lexer.skipTo` scans these deferred fragments.
+
+Method receivers accept read-only access unless the body needs writable access.
+The check follows aliases, child references, array elements, and calls between
+methods. Writing an independent argument does not require a writable receiver.
+Returning or storing a writable receiver alias also requires writable access;
+an explicit read-only view can be exposed without that requirement.
`Parser` keeps the short cursor, scope/memory, IR-building, and diagnostic helpers
used by these components. Independent helpers live with their data: class-object
diff --git a/chapter31/src/main/java/com/seaofnodes/simple/parser/References.java b/chapter31/src/main/java/com/seaofnodes/simple/parser/References.java
index f170cae2..7724103e 100644
--- a/chapter31/src/main/java/com/seaofnodes/simple/parser/References.java
+++ b/chapter31/src/main/java/com/seaofnodes/simple/parser/References.java
@@ -280,7 +280,7 @@ final class References {
// Check for assign-update, "ptr.fld += expr" or "ary[idx]++"
char ch = pre==0 ? P._lexer.matchOperAssign() : (char)pre;
if( ch!=0 ) {
- if( fld!=null && decl==Type.BOTTOM )
+ if( fld!=null && decl==Type.BOTTOM && !ts._fref )
throw Parser.error( "'" + ts._name + "' is not fully initialized, field '" + fld._fname + "' needs to be set in a constructor",site );
Node op = P.expressions.opAssign(ch,load, decl ).keep();
mem.keep();
@@ -308,10 +308,15 @@ final class References {
// Fields are lvalues in memory, including inside their initializer and
// explicit constructor. Scope slots retain declaration metadata only.
private Node fieldSelf(Var var) {
- int kx = P._scope.kindx(var), fx = P._scope.enclosingFuncOrDecl();
+ int kx = P._scope.kindx(var);
ScopeNode.Kind kind = P._scope._kinds.at(kx);
if( !(kind instanceof Kind.Func inst) || !FunNode.isInstance(inst._name) || var._idx<inst._lexSize+2 ) return null;
- if( kx==fx || kx+1==fx ) return defaultSelf();
+ // Nested functions have their own receiver parameter. Resolve fields
+ // through it even across intervening function and block scopes.
+ Node self = defaultSelf();
+ Type owner = P._scope.var(inst._lexSize).type();
+ if( self._type instanceof TypeMemPtr ptr && owner instanceof TypeMemPtr declared &&
+ ptr._obj._name.equals(declared._obj._name) ) return self;
return null;
}
diff --git a/chapter31/src/main/java/com/seaofnodes/simple/parser/Types.java b/chapter31/src/main/java/com/seaofnodes/simple/parser/Types.java
index 827518fd..501924f0 100644
--- a/chapter31/src/main/java/com/seaofnodes/simple/parser/Types.java
+++ b/chapter31/src/main/java/com/seaofnodes/simple/parser/Types.java
@@ -37,6 +37,12 @@ final class Types {
if( t0==Type.BOTTOM || t0==Type.TOP ) return t0; // var/val
tname = typeName(tname).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;
@@ -135,9 +141,8 @@ final class Types {
Type implicitSelfType() {
TypeStruct self = P._scope.constructorSelf();
- // Ordinary instance methods accept the declared object shape. The
- // constructor-only receiver starts at the low/default field values,
- // and is built explicitly by parseConstructor().
+ // Function types without a body must allow for writes. Function
+ // expressions can infer a weaker requirement in MethodAccess.
return self == null ? TypePtr.PTR : TypeMemPtr.make(self);
}
diff --git a/chapter31/src/main/java/com/seaofnodes/simple/parser/Var.java b/chapter31/src/main/java/com/seaofnodes/simple/parser/Var.java
index ddbb91d8..5361148f 100644
--- a/chapter31/src/main/java/com/seaofnodes/simple/parser/Var.java
+++ b/chapter31/src/main/java/com/seaofnodes/simple/parser/Var.java
@@ -33,6 +33,11 @@ public class Var {
public Type type() { return _type; }
public Type _type() { return _type; } // ScopeNode printer needs to have no side effects
+ void refineType(Type type) {
+ assert type.isa(_type) : _name+": "+_type+" -> "+type;
+ _type = type;
+ }
+
// Forward reference variables (not types) must be BOTTOM and
// distinct from inferred variables
public boolean isFRef() { return _fref; }
diff --git a/chapter31/src/main/smp/sys/draw/Canvas.smp b/chapter31/src/main/smp/sys/draw/Canvas.smp
index 2fbcf6ea..9ba3514a 100644
--- a/chapter31/src/main/smp/sys/draw/Canvas.smp
+++ b/chapter31/src/main/smp/sys/draw/Canvas.smp
@@ -3,7 +3,7 @@ struct Canvas {
u32 height;
u32[] pixels;
- new Canvas = { int w, int h ->
+ new Canvas = { u32 w, u32 h ->
i64 count = w;
count *= h;
if( w <= 0 || h <= 0 || count > sys.integer.MAX_I32 ) libc._exit(1);