Parse an allocation
()
| 767 | Parse an allocation |
| 768 | */ |
| 769 | private Node alloc() { |
| 770 | Type t = type(); |
| 771 | if( t==null ) throw error("Expected a type"); |
| 772 | // Parse ary[ length_expr ] |
| 773 | if( match("[") ) { |
| 774 | Node len = parseExpression().keep(); |
| 775 | if( !(len._type instanceof TypeInteger) ) |
| 776 | throw error("Cannot allocate an array with length "+len._type); |
| 777 | require("]"); |
| 778 | TypeMemPtr tmp = typeAry(t); |
| 779 | return newArray(tmp._obj,len); |
| 780 | } |
| 781 | |
| 782 | if( !(t instanceof TypeMemPtr tmp) ) |
| 783 | throw error("Cannot allocate a "+t.str()); |
| 784 | |
| 785 | // Parse new struct { default_initialization } |
| 786 | StructNode s = INITS.get(tmp._obj._name); |
| 787 | if( s==null ) throw error("Unknown struct type '" + tmp._obj._name + "'"); |
| 788 | |
| 789 | Field[] fs = s._ts._fields; |
| 790 | // if the object is fully initialized, we can skip a block here. |
| 791 | // Check for constructor block: |
| 792 | boolean hasConstructor = match("{"); |
| 793 | Ary<Node> init=s._inputs; int idx=0; |
| 794 | if( hasConstructor ) { |
| 795 | idx = _scope.nIns(); |
| 796 | // Push a scope, and pre-assign all struct fields. |
| 797 | _scope.push(); |
| 798 | for( int i=0; i<fs.length; i++ ) |
| 799 | _scope.define(fs[i]._fname, fs[i]._type, fs[i]._final, s.in(i)); |
| 800 | // Parse the constructor body |
| 801 | parseBlock(); |
| 802 | require("}"); |
| 803 | init = _scope._inputs; |
| 804 | } |
| 805 | // Check that all fields are initialized |
| 806 | for( int i=idx; i<init.size(); i++ ) |
| 807 | if( init.get(i)._type == Type.TOP ) |
| 808 | throw error("'"+tmp._obj._name+"' is not fully initialized, field '" + fs[i-idx]._fname + "' needs to be set in a constructor"); |
| 809 | Node ptr = newStruct(tmp._obj, con(tmp._obj.offset(fs.length)), idx, init ); |
| 810 | if( hasConstructor ) |
| 811 | _scope.pop(); |
| 812 | return ptr; |
| 813 | } |
| 814 | |
| 815 | |
| 816 | /** |
no test coverage detected