From 5ad578c96835da4360d7a2ca189a299d5403c819 Mon Sep 17 00:00:00 2001 From: odersky Date: Fri, 23 Dec 2005 18:12:51 +0000 Subject: [PATCH] git-svn-id: http://lampsvn.epfl.ch/svn-repos/scala/scala/trunk@5409 5e8d7ff9-d8ef-0310-90f0-a4852d11357a --- .../scala/tools/nsc/ast/parser/Scanners.scala | 614 ++++++------ .../tools/nsc/backend/icode/Checkers.scala | 1 - .../scala/tools/nsc/symtab/Symbols.scala | 8 +- .../scala/tools/nsc/typechecker/Typers.scala | 907 +++++++++--------- 4 files changed, 771 insertions(+), 759 deletions(-) diff --git a/src/compiler/scala/tools/nsc/ast/parser/Scanners.scala b/src/compiler/scala/tools/nsc/ast/parser/Scanners.scala index 6f36210fc..986965505 100644 --- a/src/compiler/scala/tools/nsc/ast/parser/Scanners.scala +++ b/src/compiler/scala/tools/nsc/ast/parser/Scanners.scala @@ -3,44 +3,44 @@ * @author Martin Odersky */ // $Id$ -package scala.tools.nsc.ast.parser; +package scala.tools.nsc.ast.parser -import Tokens._; +import Tokens._ import scala.tools.nsc.util.{Position, SourceFile} import SourceFile.{LF, FF, CR, SU} -import scala.tools.nsc.util.CharArrayReader; +import scala.tools.nsc.util.CharArrayReader [_trait_] abstract class Scanners: SyntaxAnalyzer { - import global._; + import global._ /** A class for representing a token's data. */ class TokenData { /** the next token */ - var token: int = EMPTY; + var token: int = EMPTY /** the token's position */ - protected var pos: int = 0; + protected var pos: int = 0 /** the first character position after the previous token */ - var lastPos: int = 0; + var lastPos: int = 0 - def currentPos = pos - 1; + def currentPos = pos - 1 /** the name of an identifier or token */ - var name: Name = null; + var name: Name = null /** the base of a number */ - var base: int = 0; + var base: int = 0 def copyFrom(td: TokenData) = { - this.token = td.token; - this.pos = td.pos; - this.lastPos = td.lastPos; - this.name = td.name; - this.base = td.base; + this.token = td.token + this.pos = td.pos + this.lastPos = td.lastPos + this.name = td.name + this.base = td.base } } @@ -51,48 +51,48 @@ import scala.tools.nsc.util.CharArrayReader; */ class Scanner(unit: CompilationUnit) extends TokenData { - import Tokens._; + import Tokens._ import java.lang.{Integer, Long, Float, Double, Character} /** Character input reader */ - val in = new CharArrayReader(unit.source.getContent(), true, syntaxError); + val in = new CharArrayReader(unit.source.getContent(), true, syntaxError) /** character buffer for literals */ - val cbuf = new StringBuffer(); + val cbuf = new StringBuffer() /** append Unicode character to "lit" buffer */ - protected def putChar(c: char) = cbuf.append(c); + protected def putChar(c: char) = cbuf.append(c) /** Clear buffer and set name */ private def setName = { - name = newTermName(cbuf.toString()); + name = newTermName(cbuf.toString()) cbuf.setLength(0) } /** buffer for the documentation comment */ - var docBuffer: StringBuffer = null; + var docBuffer: StringBuffer = null /** add the given character to the documentation buffer */ protected def putDocChar(c: char): unit = - if (docBuffer != null) docBuffer.append(c); + if (docBuffer != null) docBuffer.append(c) /** we need one token lookahead */ - val next = new TokenData(); - val prev = new TokenData(); + val next = new TokenData() + val prev = new TokenData() /** the last error position */ - var errpos = -1; + var errpos = -1 /** a stack which indicates whether line-ends can be statement separators */ - var sepRegions: List[int] = List(); + var sepRegions: List[int] = List() // Get next token ------------------------------------------------------------ @@ -115,7 +115,7 @@ import scala.tools.nsc.util.CharArrayReader; sepRegions = ARROW :: sepRegions } else if (token == RBRACE) { while (!sepRegions.isEmpty && sepRegions.head != RBRACE) - sepRegions = sepRegions.tail; + sepRegions = sepRegions.tail if (!sepRegions.isEmpty) sepRegions = sepRegions.tail } else if (token == RBRACKET || token == RPAREN || token == ARROW) { @@ -123,45 +123,45 @@ import scala.tools.nsc.util.CharArrayReader; sepRegions = sepRegions.tail } - val lastToken = token; + val lastToken = token if (next.token == EMPTY) { - fetchToken(); + fetchToken() } else { - this.copyFrom(next); + this.copyFrom(next) next.token = EMPTY } if (token == CASE) { - prev.copyFrom(this); - fetchToken(); + prev.copyFrom(this) + fetchToken() if (token == CLASS) { - token = CASECLASS; - lastPos = prev.lastPos; + token = CASECLASS + lastPos = prev.lastPos } else if (token == OBJECT) { - token = CASEOBJECT; - lastPos = prev.lastPos; + token = CASEOBJECT + lastPos = prev.lastPos } else { - next.copyFrom(this); - this.copyFrom(prev); + next.copyFrom(this) + this.copyFrom(prev) } } else if (token == SEMI) { - prev.copyFrom(this); - fetchToken(); + prev.copyFrom(this) + fetchToken() if (token != ELSE) { - next.copyFrom(this); - this.copyFrom(prev); + next.copyFrom(this) + this.copyFrom(prev) } } if (afterLineEnd() && inLastOfStat(lastToken) && inFirstOfStat(token) && (sepRegions.isEmpty || sepRegions.head == RBRACE)) { - next.copyFrom(this); - pos = in.lineStartPos; + next.copyFrom(this) + pos = in.lineStartPos token = NEWLINE /* } else if (lastToken == RBRACE) { System.out.println("failing to insert NL after RBRACE: " + sepRegions + " " + - lastPos + " " + in.lineStartPos + " " + pos); + lastPos + " " + in.lineStartPos + " " + pos) */ } // System.out.println("token: " + toString());//DEBUG @@ -171,24 +171,24 @@ import scala.tools.nsc.util.CharArrayReader; lastPos < in.lineStartPos && (in.lineStartPos <= pos || lastPos < in.lastLineStartPos && in.lastLineStartPos <= pos) - ); + ) /** read next token */ private def fetchToken(): unit = { - if (token == EOF) return; - lastPos = in.cpos - 1; // Position.encode(in.cline, in.ccol); - //var index = bp; + if (token == EOF) return + lastPos = in.cpos - 1; // Position.encode(in.cline, in.ccol) + //var index = bp while (true) { in.ch match { case ' ' | '\t' | CR | LF | FF => - in.next; + in.next case _ => - pos = in.cpos; // Position.encode(in.cline, in.ccol); + pos = in.cpos; // Position.encode(in.cline, in.ccol) in.ch match { case '\u21D2' => - in.next; token = ARROW; - return; + in.next; token = ARROW + return case 'A' | 'B' | 'C' | 'D' | 'E' | 'F' | 'G' | 'H' | 'I' | 'J' | 'K' | 'L' | 'M' | 'N' | 'O' | @@ -201,65 +201,65 @@ import scala.tools.nsc.util.CharArrayReader; 'p' | 'q' | 'r' | 's' | 't' | 'u' | 'v' | 'w' | 'x' | 'y' | // scala-mode: need to understand multi-line case patterns 'z' => - putChar(in.ch); - in.next; + putChar(in.ch) + in.next getIdentRest; // scala-mode: wrong indent for multi-line case blocks return; case '<' => // is XMLSTART? - val last = in.last; - in.next; + val last = in.last + in.next last match { case ' '|'\t'|'\n'|'{'|'('|'>' if xml.Parsing.isNameStart(in.ch) => - token = XMLSTART; + token = XMLSTART case _ => // Console.println("found '<', but last is '"+in.last+"'"); // DEBUG - putChar('<'); - getOperatorRest; + putChar('<') + getOperatorRest } - return; + return case '~' | '!' | '@' | '#' | '%' | '^' | '*' | '+' | '-' | /*'<' | */ '>' | '?' | ':' | '=' | '&' | '|' | '\\' => - putChar(in.ch); - in.next; + putChar(in.ch) + in.next getOperatorRest; // XXX - return; + return case '/' => - in.next; + in.next if (!skipComment()) { - putChar('/'); - getOperatorRest; - return; + putChar('/') + getOperatorRest + return } case '0' => - putChar(in.ch); - in.next; + putChar(in.ch) + in.next if (in.ch == 'x' || in.ch == 'X') { - in.next; + in.next base = 16 } else { - base = 8; + base = 8 } - getNumber; + getNumber return; // scala-mode: return is a keyword case '1' | '2' | '3' | '4' | '5' | '6' | '7' | '8' | '9' => - base = 10; - getNumber; - return; + base = 10 + getNumber + return case '`' => //" scala-mode: need to understand literals - getStringLit('`'); - token = IDENTIFIER; - return; + getStringLit('`') + token = IDENTIFIER + return case '\"' => //" scala-mode: need to understand literals - getStringLit('\"'); - return; + getStringLit('\"') + return case '\'' => - in.next; + in.next in.ch match { case 'A' | 'B' | 'C' | 'D' | 'E' | 'F' | 'G' | 'H' | 'I' | 'J' | @@ -273,86 +273,86 @@ import scala.tools.nsc.util.CharArrayReader; 'p' | 'q' | 'r' | 's' | 't' | 'u' | 'v' | 'w' | 'x' | 'y' | 'z' => - putChar(in.ch); - in.next; + putChar(in.ch) + in.next if (in.ch != '\'') { - getIdentRest; - token = SYMBOLLIT; - return; + getIdentRest + token = SYMBOLLIT + return } case _ => if (Character.isUnicodeIdentifierStart(in.ch)) { - putChar(in.ch); - in.next; + putChar(in.ch) + in.next if (in.ch != '\'') { - getIdentRest; - token = SYMBOLLIT; - return; + getIdentRest + token = SYMBOLLIT + return } } else { getlitch() } } if (in.ch == '\'') { - in.next; - token = CHARLIT; + in.next + token = CHARLIT setName } else { - syntaxError("unclosed character literal"); + syntaxError("unclosed character literal") } - return; + return case '.' => in.next; if ('0' <= in.ch && in.ch <= '9') { - putChar('.'); getFraction; + putChar('.'); getFraction } else { token = DOT } - return; + return case ';' => - in.next; token = SEMI; - return; + in.next; token = SEMI + return case ',' => - in.next; token = COMMA; - return; + in.next; token = COMMA + return case '(' => //scala-mode: need to understand character quotes in.next; token = LPAREN; - return; + return case '{' => - in.next; token = LBRACE; - return; + in.next; token = LBRACE + return case ')' => - in.next; token = RPAREN; - return; + in.next; token = RPAREN + return case '}' => - in.next; token = RBRACE; - return; + in.next; token = RBRACE + return case '[' => - in.next; token = LBRACKET; - return; + in.next; token = LBRACKET + return case ']' => - in.next; token = RBRACKET; - return; + in.next; token = RBRACKET + return case SU => - if (!in.hasNext) token = EOF; + if (!in.hasNext) token = EOF else { syntaxError("illegal character"); in.next } - return; + return case _ => if (Character.isUnicodeIdentifierStart(in.ch)) { - putChar(in.ch); - in.next; - getIdentRest; + putChar(in.ch) + in.next + getIdentRest } else if (isSpecial(in.ch)) { - putChar(in.ch); - getOperatorRest; + putChar(in.ch) + getOperatorRest } else { syntaxError("illegal character"); - in.next; + in.next } - return; + return } } } @@ -361,33 +361,33 @@ import scala.tools.nsc.util.CharArrayReader; private def skipComment(): boolean = if (in.ch == '/') { do { - in.next; - } while ((in.ch != CR) && (in.ch != LF) && (in.ch != SU)); + in.next + } while ((in.ch != CR) && (in.ch != LF) && (in.ch != SU)) true } else if (in.ch == '*') { - docBuffer = null; - var openComments = 1; - in.next; - if (in.ch == '*') docBuffer = new StringBuffer("/**"); + docBuffer = null + var openComments = 1 + in.next + if (in.ch == '*') docBuffer = new StringBuffer("/**") while (openComments > 0) { do { do { if (in.ch == '/') { - in.next; putDocChar(in.ch); + in.next; putDocChar(in.ch) if (in.ch == '*') { - in.next; putDocChar(in.ch); - openComments = openComments + 1; + in.next; putDocChar(in.ch) + openComments = openComments + 1 } } - in.next; putDocChar(in.ch); - } while (in.ch != '*' && in.ch != SU); + in.next; putDocChar(in.ch) + } while (in.ch != '*' && in.ch != SU) while (in.ch == '*') { - in.next; putDocChar(in.ch); + in.next; putDocChar(in.ch) } - } while (in.ch != '/' && in.ch != SU); - if (in.ch == '/') in.next; - else syntaxError("unclosed comment"); - openComments = openComments - 1; + } while (in.ch != '/' && in.ch != SU) + if (in.ch == '/') in.next + else syntaxError("unclosed comment") + openComments = openComments - 1 } true } else { @@ -395,8 +395,8 @@ import scala.tools.nsc.util.CharArrayReader; } def inFirstOfStat(token: int) = token match { - case EOF | ELSE | CASE | EXTENDS | WITH | YIELD | CATCH | FINALLY | MATCH | - REQUIRES | COMMA | SEMI | NEWLINE | DOT | USCORE | COLON | EQUALS | ARROW | + case EOF | CASE | CATCH | ELSE | EXTENDS | FINALLY | MATCH | REQUIRES | WITH | YIELD | + COMMA | SEMI | NEWLINE | DOT | USCORE | COLON | EQUALS | ARROW | LARROW | SUBTYPE | VIEWBOUND | SUPERTYPE | HASH | AT | RPAREN | RBRACKET | RBRACE => false @@ -420,17 +420,17 @@ import scala.tools.nsc.util.CharArrayReader; ('a' <= c && c <= 'a') || (c == '_') || (c == '$') || Character.isUnicodeIdentifierStart(c) - ); + ) def isIdentPart(c: char) = ( isIdentStart(c) || ('0' <= c && c <= '9') || Character.isUnicodeIdentifierPart(c) - ); + ) def isSpecial(c: char) = { - val chtp = Character.getType(c); - chtp == Character.MATH_SYMBOL || chtp == Character.OTHER_SYMBOL; + val chtp = Character.getType(c) + chtp == Character.MATH_SYMBOL || chtp == Character.OTHER_SYMBOL } private def getIdentRest: unit = @@ -450,24 +450,24 @@ import scala.tools.nsc.util.CharArrayReader; 'z' | '0' | '1' | '2' | '3' | '4' | '5' | '6' | '7' | '8' | '9' => - putChar(in.ch); - in.next; + putChar(in.ch) + in.next case '_' => - putChar(in.ch); - in.next; - getIdentOrOperatorRest; - return; + putChar(in.ch) + in.next + getIdentOrOperatorRest + return case SU => - setName; - token = name2token(name); - return; + setName + token = name2token(name) + return case _ => if(java.lang.Character.isUnicodeIdentifierPart(in.ch)) { - putChar(in.ch); + putChar(in.ch) in.next } else { - setName; - token = name2token(name); + setName + token = name2token(name) return } } @@ -480,25 +480,25 @@ import scala.tools.nsc.util.CharArrayReader; '^' | '*' | '+' | '-' | '<' | '>' | '?' | ':' | '=' | '&' | '|' | '\\' => - putChar(in.ch); + putChar(in.ch) in.next case '/' => - in.next; + in.next if (skipComment()) { - setName; - token = name2token(name); - return; + setName + token = name2token(name) + return } else { - putChar('/'); + putChar('/') } case _ => if (isSpecial(in.ch)) { - putChar(in.ch); - in.next; + putChar(in.ch) + in.next } else { - setName; - token = name2token(name); - return; + setName + token = name2token(name) + return } } } @@ -511,26 +511,26 @@ import scala.tools.nsc.util.CharArrayReader; '^' | '*' | '+' | '-' | '<' | '>' | '?' | ':' | '=' | '&' | '|' | '\\' | '/' => - getOperatorRest; + getOperatorRest case _ => if (isSpecial(in.ch)) getOperatorRest else { - setName; + setName token = name2token(name) } } private def getStringLit(delimiter: char): unit = { - in.next; + in.next while (in.ch != delimiter && (in.isUnicode || in.ch != CR && in.ch != LF && in.ch != SU)) { - getlitch(); + getlitch() } if (in.ch == delimiter) { - token = STRINGLIT; - setName; + token = STRINGLIT + setName in.next } else { - syntaxError("unclosed string literal"); + syntaxError("unclosed string literal") } } @@ -540,20 +540,20 @@ import scala.tools.nsc.util.CharArrayReader; */ protected def getlitch() = if (in.ch == '\\') { - in.next; + in.next if ('0' <= in.ch && in.ch <= '7') { - val leadch: char = in.ch; - var oct: int = in.digit2int(in.ch, 8); - in.next; + val leadch: char = in.ch + var oct: int = in.digit2int(in.ch, 8) + in.next if ('0' <= in.ch && in.ch <= '7') { - oct = oct * 8 + in.digit2int(in.ch, 8); - in.next; + oct = oct * 8 + in.digit2int(in.ch, 8) + in.next if (leadch <= '3' && '0' <= in.ch && in.ch <= '7') { - oct = oct * 8 + in.digit2int(in.ch, 8); - in.next; + oct = oct * 8 + in.digit2int(in.ch, 8) + in.next } } - putChar(oct.asInstanceOf[char]); + putChar(oct.asInstanceOf[char]) } else { in.ch match { case 'b' => putChar('\b') @@ -566,53 +566,53 @@ import scala.tools.nsc.util.CharArrayReader; case '\\' => putChar('\\') case _ => syntaxError(in.cpos - 1, // Position.encode(in.cline, in.ccol - 1), - "invalid escape character"); - putChar(in.ch); + "invalid escape character") + putChar(in.ch) } in.next } } else { - putChar(in.ch); - in.next; + putChar(in.ch) + in.next } /** read fractional part and exponent of floating point number * if one is present. */ protected def getFraction = { - token = DOUBLELIT; + token = DOUBLELIT while ('0' <= in.ch && in.ch <= '9') { - putChar(in.ch); - in.next; + putChar(in.ch) + in.next } if (in.ch == 'e' || in.ch == 'E') { - val lookahead = in.copy; - lookahead.next; + val lookahead = in.copy + lookahead.next if (lookahead.ch == '+' || lookahead.ch == '-') { - lookahead.next; + lookahead.next } if ('0' <= lookahead.ch && lookahead.ch <= '9') { - putChar(in.ch); - in.next; + putChar(in.ch) + in.next if (in.ch == '+' || in.ch == '-') { - putChar(in.ch); - in.next; + putChar(in.ch) + in.next } while ('0' <= in.ch && in.ch <= '9') { - putChar(in.ch); - in.next; + putChar(in.ch) + in.next } } - token = DOUBLELIT; + token = DOUBLELIT } if ((in.ch == 'd') || (in.ch == 'D')) { - putChar(in.ch); - in.next; - token = DOUBLELIT; + putChar(in.ch) + in.next + token = DOUBLELIT } else if ((in.ch == 'f') || (in.ch == 'F')) { - putChar(in.ch); - in.next; - token = FLOATLIT; + putChar(in.ch) + in.next + token = FLOATLIT } setName } @@ -623,74 +623,74 @@ import scala.tools.nsc.util.CharArrayReader; if (token == CHARLIT && !negated) { if (name.length > 0) name(0) else 0 } else { - var value: long = 0; - val divider = if (base == 10) 1 else 2; + var value: long = 0 + val divider = if (base == 10) 1 else 2 val limit: long = - if (token == LONGLIT) Long.MAX_VALUE else Integer.MAX_VALUE; - var i = 0; - val len = name.length; + if (token == LONGLIT) Long.MAX_VALUE else Integer.MAX_VALUE + var i = 0 + val len = name.length while (i < len) { - val d = in.digit2int(name(i), base); + val d = in.digit2int(name(i), base) if (d < 0) { - syntaxError("malformed integer number"); - return 0; + syntaxError("malformed integer number") + return 0 } if (value < 0 || limit / (base / divider) < value || limit - (d / divider) < value * (base / divider) && !(negated && limit == value * base - 1 + d)) { - syntaxError("integer number too large"); - return 0; + syntaxError("integer number too large") + return 0 } - value = value * base + d; - i = i + 1; + value = value * base + d + i = i + 1 } if (negated) -value else value } } - def intVal: long = intVal(false); + def intVal: long = intVal(false) /** convert name, base to double value */ def floatVal(negated: boolean): double = { val limit: double = - if (token == DOUBLELIT) Double.MAX_VALUE else Float.MAX_VALUE; + if (token == DOUBLELIT) Double.MAX_VALUE else Float.MAX_VALUE try { - val value = Double.valueOf(name.toString()).doubleValue(); + val value = Double.valueOf(name.toString()).doubleValue() if (value > limit) - syntaxError("floating point number too large"); + syntaxError("floating point number too large") if (negated) -value else value } catch { case _: NumberFormatException => - syntaxError("malformed floating point number"); + syntaxError("malformed floating point number") 0.0 } } - def floatVal: double = floatVal(false); + def floatVal: double = floatVal(false) /** read a number into name and set base */ protected def getNumber:unit = { while (in.digit2int(in.ch, if (base < 10) 10 else base) >= 0) { - putChar(in.ch); - in.next; + putChar(in.ch) + in.next } - token = INTLIT; + token = INTLIT if (base <= 10 && in.ch == '.') { - val lookahead = in.copy; - lookahead.next; + val lookahead = in.copy + lookahead.next lookahead.ch match { case '0' | '1' | '2' | '3' | '4' | '5' | '6' | '7' | '8' | '9' | 'd' | 'D' | 'e' | 'E' | 'f' | 'F' => - putChar(in.ch); - in.next; + putChar(in.ch) + in.next return getFraction case _ => if (!isIdentStart(lookahead.ch)) { - putChar(in.ch); - in.next; + putChar(in.ch) + in.next return getFraction } } @@ -701,18 +701,18 @@ import scala.tools.nsc.util.CharArrayReader; in.ch == 'd' || in.ch == 'D')) { return getFraction } - setName; + setName if (in.ch == 'l' || in.ch == 'L') { - in.next; - token = LONGLIT; + in.next + token = LONGLIT } } // XML lexing---------------------------------------------------------------- def xSync = { token = NEWLINE; // avoid getting NEWLINE from nextToken if last was RBRACE - //in.next; - nextToken(); + //in.next + nextToken() } // Errors ----------------------------------------------------------------- @@ -720,95 +720,95 @@ import scala.tools.nsc.util.CharArrayReader; /** generate an error at the given position */ def syntaxError(pos: int, msg: String): unit = { - unit.error(pos, msg); - token = ERROR; - errpos = pos; + unit.error(pos, msg) + token = ERROR + errpos = pos } /** generate an error at the current token position */ - def syntaxError(msg: String): unit = syntaxError(pos, msg); + def syntaxError(msg: String): unit = syntaxError(pos, msg) // Keywords ----------------------------------------------------------------- /** Keyword array; maps from name indices to tokens */ - private var key: Array[byte] = _; - private var maxKey = 0; - private var tokenName = new Array[Name](128); + private var key: Array[byte] = _ + private var maxKey = 0 + private var tokenName = new Array[Name](128) { - var tokenCount = 0; + var tokenCount = 0 // Enter keywords def enterKeyword(n: Name, tokenId: int): unit = { while (tokenId >= tokenName.length) { - val newTokName = new Array[Name](tokenName.length * 2); - System.arraycopy(tokenName, 0, newTokName, 0, newTokName.length); - tokenName = newTokName; + val newTokName = new Array[Name](tokenName.length * 2) + System.arraycopy(tokenName, 0, newTokName, 0, newTokName.length) + tokenName = newTokName } - tokenName(tokenId) = n; - if (n.start > maxKey) maxKey = n.start; - if (tokenId >= tokenCount) tokenCount = tokenId + 1; + tokenName(tokenId) = n + if (n.start > maxKey) maxKey = n.start + if (tokenId >= tokenCount) tokenCount = tokenId + 1 } - enterKeyword(nme.ABSTRACTkw, ABSTRACT); - enterKeyword(nme.CASEkw, CASE); - enterKeyword(nme.CATCHkw, CATCH); - enterKeyword(nme.CLASSkw, CLASS); - enterKeyword(nme.DEFkw, DEF); - enterKeyword(nme.DOkw, DO); - enterKeyword(nme.ELSEkw, ELSE); - enterKeyword(nme.EXTENDSkw, EXTENDS); - enterKeyword(nme.FALSEkw, FALSE); - enterKeyword(nme.FINALkw, FINAL); - enterKeyword(nme.FINALLYkw, FINALLY); - enterKeyword(nme.FORkw, FOR); - enterKeyword(nme.IFkw, IF); - enterKeyword(nme.IMPLICITkw, IMPLICIT); - enterKeyword(nme.IMPORTkw, IMPORT); - enterKeyword(nme.MATCHkw, MATCH); - enterKeyword(nme.REQUIRESkw, REQUIRES); - enterKeyword(nme.NEWkw, NEW); - enterKeyword(nme.NULLkw, NULL); - enterKeyword(nme.OBJECTkw, OBJECT); - enterKeyword(nme.OVERRIDEkw, OVERRIDE); - enterKeyword(nme.PACKAGEkw, PACKAGE); - enterKeyword(nme.PRIVATEkw, PRIVATE); - enterKeyword(nme.PROTECTEDkw, PROTECTED); - enterKeyword(nme.RETURNkw, RETURN); - enterKeyword(nme.SEALEDkw, SEALED); - enterKeyword(nme.SUPERkw, SUPER); - enterKeyword(nme.THISkw, THIS); - enterKeyword(nme.THROWkw, THROW); - enterKeyword(nme.TRAITkw, TRAIT); - enterKeyword(nme.TRUEkw, TRUE); - enterKeyword(nme.TRYkw, TRY); - enterKeyword(nme.TYPEkw, TYPE); - enterKeyword(nme.VALkw, VAL); - enterKeyword(nme.VARkw, VAR); - enterKeyword(nme.WHILEkw, WHILE); - enterKeyword(nme.WITHkw, WITH); - enterKeyword(nme.YIELDkw, YIELD); - enterKeyword(nme.DOTkw, DOT); - enterKeyword(nme.USCOREkw, USCORE); - enterKeyword(nme.COLONkw, COLON); - enterKeyword(nme.EQUALSkw, EQUALS); - enterKeyword(nme.ARROWkw, ARROW); - enterKeyword(nme.LARROWkw, LARROW); - enterKeyword(nme.SUBTYPEkw, SUBTYPE); - enterKeyword(nme.VIEWBOUNDkw, VIEWBOUND); - enterKeyword(nme.SUPERTYPEkw, SUPERTYPE); - enterKeyword(nme.HASHkw, HASH); - enterKeyword(nme.ATkw, AT); + enterKeyword(nme.ABSTRACTkw, ABSTRACT) + enterKeyword(nme.CASEkw, CASE) + enterKeyword(nme.CATCHkw, CATCH) + enterKeyword(nme.CLASSkw, CLASS) + enterKeyword(nme.DEFkw, DEF) + enterKeyword(nme.DOkw, DO) + enterKeyword(nme.ELSEkw, ELSE) + enterKeyword(nme.EXTENDSkw, EXTENDS) + enterKeyword(nme.FALSEkw, FALSE) + enterKeyword(nme.FINALkw, FINAL) + enterKeyword(nme.FINALLYkw, FINALLY) + enterKeyword(nme.FORkw, FOR) + enterKeyword(nme.IFkw, IF) + enterKeyword(nme.IMPLICITkw, IMPLICIT) + enterKeyword(nme.IMPORTkw, IMPORT) + enterKeyword(nme.MATCHkw, MATCH) + enterKeyword(nme.REQUIRESkw, REQUIRES) + enterKeyword(nme.NEWkw, NEW) + enterKeyword(nme.NULLkw, NULL) + enterKeyword(nme.OBJECTkw, OBJECT) + enterKeyword(nme.OVERRIDEkw, OVERRIDE) + enterKeyword(nme.PACKAGEkw, PACKAGE) + enterKeyword(nme.PRIVATEkw, PRIVATE) + enterKeyword(nme.PROTECTEDkw, PROTECTED) + enterKeyword(nme.RETURNkw, RETURN) + enterKeyword(nme.SEALEDkw, SEALED) + enterKeyword(nme.SUPERkw, SUPER) + enterKeyword(nme.THISkw, THIS) + enterKeyword(nme.THROWkw, THROW) + enterKeyword(nme.TRAITkw, TRAIT) + enterKeyword(nme.TRUEkw, TRUE) + enterKeyword(nme.TRYkw, TRY) + enterKeyword(nme.TYPEkw, TYPE) + enterKeyword(nme.VALkw, VAL) + enterKeyword(nme.VARkw, VAR) + enterKeyword(nme.WHILEkw, WHILE) + enterKeyword(nme.WITHkw, WITH) + enterKeyword(nme.YIELDkw, YIELD) + enterKeyword(nme.DOTkw, DOT) + enterKeyword(nme.USCOREkw, USCORE) + enterKeyword(nme.COLONkw, COLON) + enterKeyword(nme.EQUALSkw, EQUALS) + enterKeyword(nme.ARROWkw, ARROW) + enterKeyword(nme.LARROWkw, LARROW) + enterKeyword(nme.SUBTYPEkw, SUBTYPE) + enterKeyword(nme.VIEWBOUNDkw, VIEWBOUND) + enterKeyword(nme.SUPERTYPEkw, SUPERTYPE) + enterKeyword(nme.HASHkw, HASH) + enterKeyword(nme.ATkw, AT) // Build keyword array - key = new Array[byte](maxKey+1); + key = new Array[byte](maxKey+1) for (val i <- Iterator.range(0, maxKey + 1)) - key(i) = IDENTIFIER; + key(i) = IDENTIFIER for (val j <- Iterator.range(0, tokenCount)) if (tokenName(j) != null) - key(tokenName(j).start) = j.asInstanceOf[byte]; + key(tokenName(j).start) = j.asInstanceOf[byte] } @@ -816,7 +816,7 @@ import scala.tools.nsc.util.CharArrayReader; /** Convert name to token */ def name2token(name: Name): int = - if (name.start <= maxKey) key(name.start) else IDENTIFIER; + if (name.start <= maxKey) key(name.start) else IDENTIFIER /** Returns the string representation of given token. */ def token2string(token: int): String = token match { @@ -902,7 +902,7 @@ import scala.tools.nsc.util.CharArrayReader; /** INIT: read lookahead character and token. */ - in.next; - nextToken(); + in.next + nextToken() } } diff --git a/src/compiler/scala/tools/nsc/backend/icode/Checkers.scala b/src/compiler/scala/tools/nsc/backend/icode/Checkers.scala index 927c1f592..70f07c849 100644 --- a/src/compiler/scala/tools/nsc/backend/icode/Checkers.scala +++ b/src/compiler/scala/tools/nsc/backend/icode/Checkers.scala @@ -13,7 +13,6 @@ import scala.tools.nsc.symtab._; abstract class Checkers { val global: Global; import global._; - import global.icodes.toTypeKind; /** * This class performs a set of checks similar to what the bytecode diff --git a/src/compiler/scala/tools/nsc/symtab/Symbols.scala b/src/compiler/scala/tools/nsc/symtab/Symbols.scala index 810d680f4..5508f54a0 100644 --- a/src/compiler/scala/tools/nsc/symtab/Symbols.scala +++ b/src/compiler/scala/tools/nsc/symtab/Symbols.scala @@ -666,6 +666,9 @@ import Flags._; def expandedName(name: Name): Name = newTermName(fullNameString('$') + nme.EXPAND_SEPARATOR_STRING + name); + def sourceFile: AbstractFile = + (if (isModule) moduleClass else toplevelClass).sourceFile; + /* def referenced: Symbol = throw new Error("referenced inapplicable for " + this); @@ -939,8 +942,10 @@ import Flags._; /** A class for class symbols */ class ClassSymbol(initOwner: Symbol, initPos: int, initName: Name) extends TypeSymbol(initOwner, initPos, initName) { + private var source: AbstractFile = null; + override def sourceFile = source + def sourceFile_=(f: AbstractFile): unit = { source = f } - var sourceFile: AbstractFile = null; private var thissym: Symbol = this; override def isClass: boolean = true; override def reset(completer: Type): unit = { @@ -1025,6 +1030,7 @@ import Flags._; override def toplevelClass: Symbol = this; override def enclMethod: Symbol = this; override def owner: Symbol = throw new Error(); + override def sourceFile: AbstractFile = null; override def ownerChain: List[Symbol] = List(); override def alternatives: List[Symbol] = List(); override def reset(completer: Type): unit = {} diff --git a/src/compiler/scala/tools/nsc/typechecker/Typers.scala b/src/compiler/scala/tools/nsc/typechecker/Typers.scala index cc285d361..4c2f60d5a 100644 --- a/src/compiler/scala/tools/nsc/typechecker/Typers.scala +++ b/src/compiler/scala/tools/nsc/typechecker/Typers.scala @@ -4,38 +4,38 @@ */ // $Id$ //todo: rewrite or disallow new T where T is a trait (currently: not a member of T) -package scala.tools.nsc.typechecker; +package scala.tools.nsc.typechecker -import symtab.Flags._; -import scala.tools.nsc.util.Position; +import symtab.Flags._ +import scala.tools.nsc.util.Position import scala.collection.mutable.{HashMap, ListBuffer} /** Methods to create symbols and to enter them into scopes. */ [_trait_] abstract class Typers: Analyzer { - import global._; - import definitions._; - import posAssigner.atPos; + import global._ + import definitions._ + import posAssigner.atPos - var appcnt = 0; - var idcnt = 0; - var selcnt = 0; - var implcnt = 0; - var impltime = 0l; + var appcnt = 0 + var idcnt = 0 + var selcnt = 0 + var implcnt = 0 + var impltime = 0l - private val transformed = new HashMap[Tree, Tree]; + private val transformed = new HashMap[Tree, Tree] - private val superDefs = new HashMap[Symbol, ListBuffer[Tree]]; + private val superDefs = new HashMap[Symbol, ListBuffer[Tree]] def resetTyper: unit = { - resetContexts; - transformed.clear; - superDefs.clear; + resetContexts + transformed.clear + superDefs.clear } - def newTyper(context: Context): Typer = new Typer(context); + def newTyper(context: Context): Typer = new Typer(context) class Typer(context0: Context) { - import context0.unit; + import context0.unit val infer = new Inferencer(context0) { override def isCoercible(tp: Type, pt: Type): boolean = ( @@ -46,7 +46,7 @@ import scala.collection.mutable.{HashMap, ListBuffer} } private def inferView(pos: int, from: Type, to: Type, reportAmbiguous: boolean): Tree = { - if (settings.debug.value) log("infer view from " + from + " to " + to);//debug + if (settings.debug.value) log("infer view from "+from+" to "+to);//debug if (phase.erasedTypes) EmptyTree else from match { case MethodType(_, _) => EmptyTree @@ -57,29 +57,29 @@ import scala.collection.mutable.{HashMap, ListBuffer} } private def inferView(pos: int, from: Type, name: Name, reportAmbiguous: boolean): Tree = { - val to = refinedType(List(WildcardType), NoSymbol); + val to = refinedType(List(WildcardType), NoSymbol) val psym = (if (name.isTypeName) to.symbol.newAbstractType(pos, name) - else to.symbol.newValue(pos, name)) setInfo WildcardType; - to.decls.enter(psym); + else to.symbol.newValue(pos, name)) setInfo WildcardType + to.decls.enter(psym) inferView(pos, from, to, reportAmbiguous) } - import infer._; + import infer._ - private var namerCache: Namer = null; + private var namerCache: Namer = null def namer = { - if (namerCache == null || namerCache.context != context) namerCache = new Namer(context); + if (namerCache == null || namerCache.context != context) namerCache = new Namer(context) namerCache } - private var context = context0; + private var context = context0 /** Mode constants */ - val NOmode = 0x000; + val NOmode = 0x000 val EXPRmode = 0x001; // these 3 modes are mutually exclusive. - val PATTERNmode = 0x002; - val TYPEmode = 0x004; + val PATTERNmode = 0x002 + val TYPEmode = 0x004 val INCONSTRmode = 0x008; // orthogonal to above. When set we are // in the body of a constructor @@ -101,7 +101,7 @@ import scala.collection.mutable.{HashMap, ListBuffer} val SUPERCONSTRmode = 0x100; // Set for the `super' in a superclass constructor call // super. - private val stickyModes: int = EXPRmode | PATTERNmode | TYPEmode; + private val stickyModes: int = EXPRmode | PATTERNmode | TYPEmode /** Report a type error. * @param pos The position where to report the error @@ -111,16 +111,16 @@ import scala.collection.mutable.{HashMap, ListBuffer} case CyclicReference(sym, info: TypeCompleter) => info.tree match { case ValDef(_, _, tpt, _) if (tpt.tpe == null) => - "recursive " + sym + " needs type" + "recursive "+sym+" needs type" case DefDef(_, _, _, _, tpt, _) if (tpt.tpe == null) => - "recursive " + sym + " needs result type" + "recursive "+sym+" needs result type" case _ => ex.getMessage() } case _ => ex.getMessage() } - if (settings.debug.value) ex.printStackTrace(); + if (settings.debug.value) ex.printStackTrace() if (context.reportGeneralErrors) error(pos, msg) else throw new Error(msg) } @@ -128,23 +128,23 @@ import scala.collection.mutable.{HashMap, ListBuffer} /** Check that tree is a stable expression. */ def checkStable(tree: Tree): Tree = - if (treeInfo.isPureExpr(tree) || tree.tpe.isError) tree; - else errorTree(tree, "stable identifier required, but " + tree + " found."); + if (treeInfo.isPureExpr(tree) || tree.tpe.isError) tree + else errorTree(tree, "stable identifier required, but "+tree+" found.") /** Check that type `tp' is not a subtype of itself. */ def checkNonCyclic(pos: int, tp: Type): unit = { def checkNotLocked(sym: Symbol): boolean = { - sym.initialize; + sym.initialize if (sym hasFlag LOCKED) { - error(pos, "cyclic aliasing or subtyping involving " + sym); false + error(pos, "cyclic aliasing or subtyping involving "+sym); false } else true } tp match { case TypeRef(pre, sym, args) => if (checkNotLocked(sym) && (sym.isAliasType || sym.isAbstractType)) { - //System.out.println("checking " + sym);//DEBUG - checkNonCyclic(pos, pre.memberInfo(sym).subst(sym.typeParams, args), sym); + //System.out.println("checking "+sym);//DEBUG + checkNonCyclic(pos, pre.memberInfo(sym).subst(sym.typeParams, args), sym) } case SingleType(pre, sym) => checkNotLocked(sym) @@ -157,39 +157,39 @@ import scala.collection.mutable.{HashMap, ListBuffer} } def checkNonCyclic(pos: int, tp: Type, lockedSym: Symbol): unit = { - lockedSym.setFlag(LOCKED); - checkNonCyclic(pos, tp); + lockedSym.setFlag(LOCKED) + checkNonCyclic(pos, tp) lockedSym.resetFlag(LOCKED) } /** Check that type of given tree does not contain local or private components */ object checkNoEscaping extends TypeMap { - private var owner: Symbol = _; - private var scope: Scope = _; - private var badSymbol: Symbol = _; + private var owner: Symbol = _ + private var scope: Scope = _ + private var badSymbol: Symbol = _ /** Check that type `tree' does not refer to private components unless itself is wrapped * in something private (`owner' tells where the type occurs). */ def privates[T <: Tree](owner: Symbol, tree: T): T = { - check(owner, EmptyScope, tree); + check(owner, EmptyScope, tree) } /** Check that type `tree' does not refer to entities defined in scope `scope'. */ def locals[T <: Tree](scope: Scope, pt: Type, tree: T): T = - if (isFullyDefined(pt)) tree setType pt else check(NoSymbol, scope, tree); + if (isFullyDefined(pt)) tree setType pt else check(NoSymbol, scope, tree) def check[T <: Tree](owner: Symbol, scope: Scope, tree: T): T = { - this.owner = owner; - this.scope = scope; - badSymbol = NoSymbol; + this.owner = owner + this.scope = scope + badSymbol = NoSymbol assert(tree.tpe != null, tree);//debug - apply(tree.tpe); + apply(tree.tpe) if (badSymbol == NoSymbol) tree else { error(tree.pos, (if (badSymbol.hasFlag(PRIVATE)) "private " else "") + badSymbol + - " escapes its defining scope as part of type " + tree.tpe); + " escapes its defining scope as part of type "+tree.tpe) setError(tree) } } @@ -197,12 +197,12 @@ import scala.collection.mutable.{HashMap, ListBuffer} override def apply(t: Type): Type = { def checkNoEscape(sym: Symbol): unit = { if (sym.hasFlag(PRIVATE)) { - var o = owner; + var o = owner while (o != NoSymbol && o != sym.owner && !o.isLocal && !o.hasFlag(PRIVATE)) - o = o.owner; + o = o.owner if (o == sym.owner) badSymbol = sym } else if (sym.owner.isTerm) { - val e = scope.lookupEntry(sym.name); + val e = scope.lookupEntry(sym.name) if (e != null && e.sym == sym && e.owner == scope && !e.sym.isTypeParameterOrSkolem) badSymbol = e.sym } @@ -218,7 +218,7 @@ import scala.collection.mutable.{HashMap, ListBuffer} } def reenterValueParams(vparamss: List[List[ValDef]]): unit = - for (val vparams <- vparamss; val vparam <- vparams) context.scope enter vparam.symbol; + for (val vparams <- vparamss; val vparam <- vparams) context.scope enter vparam.symbol def reenterTypeParams(tparams: List[AbsTypeDef]): List[Symbol] = for (val tparam <- tparams) yield { @@ -232,7 +232,7 @@ import scala.collection.mutable.{HashMap, ListBuffer} case Literal(value) => value case arg => - error(arg.pos, "attribute argument needs to be a constant; found: " + arg); + error(arg.pos, "attribute argument needs to be a constant; found: "+arg) null }) } @@ -243,12 +243,12 @@ import scala.collection.mutable.{HashMap, ListBuffer} * (3) Turn tree type into stable type if possible and required by context. */ private def stabilize(tree: Tree, pre: Type, mode: int, pt: Type): Tree = { if (tree.symbol.hasFlag(OVERLOADED) && (mode & FUNmode) == 0) - inferExprAlternative(tree, pt); - val sym = tree.symbol; + inferExprAlternative(tree, pt) + val sym = tree.symbol if ((mode & (PATTERNmode | FUNmode)) == PATTERNmode && tree.isTerm) { // (1) checkStable(tree) } else if ((mode & (EXPRmode | QUALmode)) == EXPRmode && !sym.isValue) { // (2) - errorTree(tree, sym.toString() + " is not a value"); + errorTree(tree, ""+sym+" is not a value") } else if (sym.isStable && pre.isStable && tree.tpe.symbol != ByNameParamClass && (pt.isStable || (mode & QUALmode) != 0 && !sym.isConstant || sym.isModule && !sym.isMethod)) { @@ -257,7 +257,7 @@ import scala.collection.mutable.{HashMap, ListBuffer} } def stabilizeFun(tree: Tree, mode: int, pt: Type): Tree = { - val sym = tree.symbol; + val sym = tree.symbol val pre = tree match { case Select(qual, _) => qual.tpe case _ => NoPrefix @@ -309,74 +309,74 @@ import scala.collection.mutable.{HashMap, ListBuffer} inferExprAlternative(tree, pt); adapt(tree, mode, pt) case PolyType(List(), restpe) => // (2) - adapt(tree setType restpe, mode, pt); + adapt(tree setType restpe, mode, pt) case TypeRef(_, sym, List(arg)) if ((mode & EXPRmode) != 0 && sym == ByNameParamClass) => // (2) - adapt(tree setType arg, mode, pt); + adapt(tree setType arg, mode, pt) case PolyType(tparams, restpe) if ((mode & TAPPmode) == 0) => // (3) - val tparams1 = cloneSymbols(tparams); + val tparams1 = cloneSymbols(tparams) val tree1 = if (tree.isType) tree else TypeApply(tree, tparams1 map (tparam => - TypeTree(tparam.tpe) setPos tree.pos)) setPos tree.pos; - context.undetparams = context.undetparams ::: tparams1; + TypeTree(tparam.tpe) setPos tree.pos)) setPos tree.pos + context.undetparams = context.undetparams ::: tparams1 adapt(tree1 setType restpe.substSym(tparams, tparams1), mode, pt) case mt: ImplicitMethodType if ((mode & (EXPRmode | FUNmode)) == EXPRmode) => // (4.1) val tree1 = if (!context.undetparams.isEmpty & (mode & POLYmode) == 0) { // (9) - val tparams = context.undetparams; - context.undetparams = List(); - inferExprInstance(tree, tparams, pt); + val tparams = context.undetparams + context.undetparams = List() + inferExprInstance(tree, tparams, pt) adapt(tree, mode, pt) - } else tree; + } else tree typed(applyImplicitArgs(tree1), mode, pt) case mt: MethodType if (((mode & (EXPRmode | FUNmode)) == EXPRmode) && (context.undetparams.isEmpty || (mode & POLYmode) != 0)) => if (!tree.symbol.isConstructor && pt != WildcardType && isCompatible(mt, pt) && (pt <:< functionType(mt.paramTypes map (t => WildcardType), WildcardType))) { // (4.2) - if (settings.debug.value) log("eta-expanding " + tree + ":" + tree.tpe + " to " + pt); + if (settings.debug.value) log("eta-expanding "+tree+":"+tree.tpe+" to "+pt) typed(etaExpand(tree), mode, pt) } else if (!tree.symbol.isConstructor && mt.paramTypes.isEmpty && isCompatible(mt.resultType, pt)) { // (4.3) typed(Apply(tree, List()) setPos tree.pos) } else { if (context.reportGeneralErrors) - error(tree.pos, "missing arguments for " + tree.symbol); + error(tree.pos, "missing arguments for "+tree.symbol) setError(tree) } case _ => if (tree.isType) { - val clazz = tree.tpe.symbol; + val clazz = tree.tpe.symbol if ((mode & PATTERNmode) != 0) { // (5) if (tree.tpe.isInstanceOf[MethodType]) { tree // everything done already } else { - clazz.initialize; + clazz.initialize if (clazz.hasFlag(CASE)) { // (5.1) - val tree1 = TypeTree(clazz.primaryConstructor.tpe.asSeenFrom(tree.tpe.prefix, clazz.owner)) setOriginal(tree); + val tree1 = TypeTree(clazz.primaryConstructor.tpe.asSeenFrom(tree.tpe.prefix, clazz.owner)) setOriginal(tree) // tree.tpe.prefix.memberType(clazz.primaryConstructor); //!!! - inferConstructorInstance(tree1, clazz.unsafeTypeParams, pt); + inferConstructorInstance(tree1, clazz.unsafeTypeParams, pt) tree1 } else if (clazz.isSubClass(SeqClass)) { // (5.2) pt.baseType(clazz).baseType(SeqClass) match { case TypeRef(pre, seqClass, args) => tree.setType(MethodType(List(typeRef(pre, RepeatedParamClass, args)), pt)) case NoType => - errorTree(tree, "expected pattern type " + pt + - " does not conform to sequence " + clazz) + errorTree(tree, "expected pattern type "+pt + + " does not conform to sequence "+clazz) } } else { if (!tree.tpe.isError) - error(tree.pos, clazz.toString() + " is neither a case class nor a sequence class"); + error(tree.pos, ""+clazz+" is neither a case class nor a sequence class") setError(tree) } } } else if ((mode & FUNmode) != 0) { tree } else if (tree.hasSymbol && !tree.symbol.unsafeTypeParams.isEmpty) { // (7) - errorTree(tree, "" + clazz + " takes type parameters"); + errorTree(tree, ""+clazz+" takes type parameters") } else tree match { // (6) case TypeTree() => tree case _ => TypeTree(tree.tpe) setOriginal(tree) @@ -388,9 +388,9 @@ import scala.collection.mutable.{HashMap, ListBuffer} .filter(m => m.tpe.paramSectionCount > 0) != NoSymbol) { // (8) typed(atPos(tree.pos)(Select(adaptToName(tree, nme.apply), nme.apply)), mode, pt) } else if (!context.undetparams.isEmpty & (mode & POLYmode) == 0) { // (9) - val tparams = context.undetparams; - context.undetparams = List(); - inferExprInstance(tree, tparams, pt); + val tparams = context.undetparams + context.undetparams = List() + inferExprInstance(tree, tparams, pt) adapt(tree, mode, pt) } else if (tree.tpe <:< pt) { tree @@ -409,20 +409,20 @@ import scala.collection.mutable.{HashMap, ListBuffer} } if (context.reportGeneralErrors && !tree.tpe.isError && !pt.isError) { // (13); the condition prevents chains of views - if (settings.debug.value) log("inferring view from " + tree.tpe + " to " + pt); - val coercion = inferView(tree.pos, tree.tpe, pt, true); + if (settings.debug.value) log("inferring view from "+tree.tpe+" to "+pt) + val coercion = inferView(tree.pos, tree.tpe, pt, true) if (coercion != EmptyTree) { - if (settings.debug.value) log("inferred view from " + tree.tpe + " to " + pt + " = " + coercion + ":" + coercion.tpe); - return typed(Apply(coercion, List(tree)) setPos tree.pos, mode, pt); + if (settings.debug.value) log("inferred view from "+tree.tpe+" to "+pt+" = "+coercion+":"+coercion.tpe) + return typed(Apply(coercion, List(tree)) setPos tree.pos, mode, pt) } } } - if (settings.debug.value) log("error tree = " + tree); + if (settings.debug.value) log("error tree = "+tree) typeErrorTree(tree, tree.tpe, pt) } } } -// System.out.println("adapt " + tree + ":" + tree.tpe + ", mode = " + mode + ", pt = " + pt); +// System.out.println("adapt "+tree+":"+tree.tpe+", mode = "+mode+", pt = "+pt) // adapt(tree, mode, pt) // } @@ -430,29 +430,29 @@ import scala.collection.mutable.{HashMap, ListBuffer} if (qual.isTerm && (qual.symbol == null || qual.symbol.isValue) && !phase.erasedTypes && !qual.tpe.widen.isError && qual.tpe.nonLocalMember(name) == NoSymbol) { - val coercion = inferView(qual.pos, qual.tpe, name, true); + val coercion = inferView(qual.pos, qual.tpe, name, true) if (coercion != EmptyTree) typedQualifier(atPos(qual.pos)(Apply(coercion, List(qual)))) else qual - } else qual; + } else qual private def completeParentType(tpt: Tree, tparams: List[Symbol], enclTparams: List[Symbol], vparamss: List[List[ValDef]], superargs: List[Tree]): Type = { - enclTparams foreach context.scope.enter; - namer.enterValueParams(context.owner, vparamss); + enclTparams foreach context.scope.enter + namer.enterValueParams(context.owner, vparamss) val newTree = New(tpt) - .setType(PolyType(tparams, appliedType(tpt.tpe, tparams map (.tpe)))); - val tree = typed(atPos(tpt.pos)(Apply(Select(newTree, nme.CONSTRUCTOR), superargs))); - if (settings.debug.value) log("superconstr " + tree + " co = " + context.owner);//debug + .setType(PolyType(tparams, appliedType(tpt.tpe, tparams map (.tpe)))) + val tree = typed(atPos(tpt.pos)(Apply(Select(newTree, nme.CONSTRUCTOR), superargs))) + if (settings.debug.value) log("superconstr "+tree+" co = "+context.owner);//debug tree.tpe } /* def completeParentType(tpt: Tree, templ: Template): Tree = if (tpt.hasSymbol) { - val tparams = tpt.symbol.typeParams; + val tparams = tpt.symbol.typeParams if (!tparams.isEmpty) { - val constr @ DefDef(_, _, _, vparamss, _, rhs) = treeInfo.firstConstructor(templ.body); - val Apply(_, superargs) = treeInfo.superCall(rhs, tpt.symbol.name); - val outercontext = context.outer; + val constr @ DefDef(_, _, _, vparamss, _, rhs) = treeInfo.firstConstructor(templ.body) + val Apply(_, superargs) = treeInfo.superCall(rhs, tpt.symbol.name) + val outercontext = context.outer TypeTree( newTyper(outercontext.makeNewScope(constr, outercontext.owner)) .completeParentType( @@ -460,26 +460,26 @@ import scala.collection.mutable.{HashMap, ListBuffer} tparams, context.owner.unsafeTypeParams, vparamss map (.map(.duplicate.asInstanceOf[ValDef])), - superargs map (.duplicate))) setPos tpt.pos; + superargs map (.duplicate))) setPos tpt.pos } else tpt } else tpt */ def parentTypes(templ: Template): List[Tree] = try { if (templ.parents.isEmpty) List() else { - var supertpt = typedTypeConstructor(templ.parents.head); - var mixins = templ.parents.tail map typedType; + var supertpt = typedTypeConstructor(templ.parents.head) + var mixins = templ.parents.tail map typedType // If first parent is trait, make it first mixin and add its superclass as first parent while (supertpt.tpe.symbol != null && supertpt.tpe.symbol.initialize.isTrait) { - mixins = typedType(supertpt) :: mixins; - supertpt = TypeTree(supertpt.tpe.parents.head) setPos supertpt.pos; + mixins = typedType(supertpt) :: mixins + supertpt = TypeTree(supertpt.tpe.parents.head) setPos supertpt.pos } if (supertpt.hasSymbol) { - val tparams = supertpt.symbol.typeParams; + val tparams = supertpt.symbol.typeParams if (!tparams.isEmpty) { val constr @ DefDef(_, _, _, vparamss, _, Apply(_, superargs)) = - treeInfo.firstConstructor(templ.body); - val outercontext = context.outer; + treeInfo.firstConstructor(templ.body) + val outercontext = context.outer supertpt = TypeTree( newTyper(outercontext.makeNewScope(constr, outercontext.owner)) .completeParentType( @@ -487,15 +487,15 @@ import scala.collection.mutable.{HashMap, ListBuffer} tparams, context.owner.unsafeTypeParams, vparamss map (.map(.duplicate.asInstanceOf[ValDef])), - superargs map (.duplicate))) setPos supertpt.pos; + superargs map (.duplicate))) setPos supertpt.pos } } - //System.out.println("parents(" + context.owner + ") = " + supertpt :: mixins);//DEBUG + //System.out.println("parents("+context.owner+") = "+supertpt :: mixins);//DEBUG List.mapConserve(supertpt :: mixins)(tpt => checkNoEscaping.privates(context.owner, tpt)) } } catch { case ex: TypeError => - reportTypeError(templ.pos, ex); + reportTypeError(templ.pos, ex) List(TypeTree(AnyRefClass.tpe)) } @@ -510,82 +510,82 @@ import scala.collection.mutable.{HashMap, ListBuffer} * - no two parents define same symbol. */ def validateParentClasses(parents: List[Tree], selfType: Type): unit = { - var c = context; - do { c = c.outer } while (c.owner == context.owner); - val defscope = c.scope; + var c = context + do { c = c.outer } while (c.owner == context.owner) + val defscope = c.scope def validateParentClass(parent: Tree, isFirst: boolean): unit = if (!parent.tpe.isError) { - val psym = parent.tpe.symbol.initialize; + val psym = parent.tpe.symbol.initialize if (!psym.isClass) - error(parent.pos, "class type expected"); + error(parent.pos, "class type expected") else if (!isFirst && !psym.isTrait) - error(parent.pos, "" + psym + " is not a trait; cannot be used as mixin"); + error(parent.pos, ""+psym+" is not a trait; cannot be used as mixin") else if (psym.hasFlag(FINAL)) - error(parent.pos, "illegal inheritance from final class"); + error(parent.pos, "illegal inheritance from final class") else if (psym.isSealed && !phase.erasedTypes) { // are we in same scope as base type definition? - val e = defscope.lookupEntry(psym.name); + val e = defscope.lookupEntry(psym.name) if (!(e != null && e.sym == psym && e.owner == defscope)) { // we are not within same statement sequence - var c = context; - while (c != NoContext && c.owner != psym) c = c.outer.enclClass; - if (c == NoContext) error(parent.pos, "illegal inheritance from sealed " + psym) + var c = context + while (c != NoContext && c.owner != psym) c = c.outer.enclClass + if (c == NoContext) error(parent.pos, "illegal inheritance from sealed "+psym) } } if (!(selfType <:< parent.tpe.typeOfThis) && !phase.erasedTypes) { System.out.println(context.owner);//debug System.out.println(context.owner.unsafeTypeParams);//debug System.out.println(List.fromArray(context.owner.info.closure));//debug - error(parent.pos, "illegal inheritance;\n self-type " + - selfType + " does not conform to " + parent + - "'s selftype " + parent.tpe.typeOfThis); - if (settings.explaintypes.value) explainTypes(selfType, parent.tpe.typeOfThis); + error(parent.pos, "illegal inheritance;\n self-type "+ + selfType+" does not conform to "+parent + + "'s selftype "+parent.tpe.typeOfThis) + if (settings.explaintypes.value) explainTypes(selfType, parent.tpe.typeOfThis) } if (parents exists (p => p != parent && p.tpe.symbol == psym && !psym.isError)) - error(parent.pos, "" + psym + " is inherited twice") + error(parent.pos, ""+psym+" is inherited twice") } if (!parents.isEmpty) { - validateParentClass(parents.head, true); - for (val p <- parents.tail) validateParentClass(p, false); + validateParentClass(parents.head, true) + for (val p <- parents.tail) validateParentClass(p, false) } } def typedClassDef(cdef: ClassDef): Tree = { - val clazz = cdef.symbol; - reenterTypeParams(cdef.tparams); - val tparams1 = List.mapConserve(cdef.tparams)(typedAbsTypeDef); - val tpt1 = checkNoEscaping.privates(clazz.thisSym, typedType(cdef.tpt)); + val clazz = cdef.symbol + reenterTypeParams(cdef.tparams) + val tparams1 = List.mapConserve(cdef.tparams)(typedAbsTypeDef) + val tpt1 = checkNoEscaping.privates(clazz.thisSym, typedType(cdef.tpt)) val impl1 = newTyper(context.make(cdef.impl, clazz, new Scope())) - .typedTemplate(cdef.impl, parentTypes(cdef.impl)); - val impl2 = addSyntheticMethods(impl1, clazz); + .typedTemplate(cdef.impl, parentTypes(cdef.impl)) + val impl2 = addSyntheticMethods(impl1, clazz) val ret = copy.ClassDef(cdef, cdef.mods, cdef.name, tparams1, tpt1, impl2) - .setType(NoType); - ret; + .setType(NoType) + ret } def typedModuleDef(mdef: ModuleDef): Tree = { - val clazz = mdef.symbol.moduleClass; + val clazz = mdef.symbol.moduleClass val impl1 = newTyper(context.make(mdef.impl, clazz, new Scope())) - .typedTemplate(mdef.impl, parentTypes(mdef.impl)); - val impl2 = addSyntheticMethods(impl1, clazz); + .typedTemplate(mdef.impl, parentTypes(mdef.impl)) + val impl2 = addSyntheticMethods(impl1, clazz) copy.ModuleDef(mdef, mdef.mods, mdef.name, impl2) setType NoType } def addGetterSetter(stat: Tree): List[Tree] = stat match { case ValDef(mods, name, tpe, rhs) if !(mods hasFlag LOCAL) && !stat.symbol.isModuleVar => - val vdef = copy.ValDef(stat, mods | PRIVATE | LOCAL, nme.getterToLocal(name), tpe, rhs); - val value = vdef.symbol; - val getter = if (mods hasFlag DEFERRED) value else value.getter(value.owner); + val vdef = copy.ValDef(stat, mods | PRIVATE | LOCAL, nme.getterToLocal(name), tpe, rhs) + val value = vdef.symbol + val getter = if (mods hasFlag DEFERRED) value else value.getter(value.owner) assert(getter != NoSymbol, getter);//debug val getterDef: DefDef = { val result = atPos(vdef.pos)( DefDef(getter, vparamss => if (mods hasFlag DEFERRED) EmptyTree - else typed(atPos(vdef.pos)(Select(This(value.owner), value)), EXPRmode, value.tpe))); - checkNoEscaping.privates(getter, result.tpt); + else typed(atPos(vdef.pos)(Select(This(value.owner), value)), EXPRmode, value.tpe))) + checkNoEscaping.privates(getter, result.tpt) result } def setterDef: DefDef = { @@ -598,7 +598,7 @@ import scala.collection.mutable.{HashMap, ListBuffer} Ident(vparamss.head.head))))) } val gs = if (mods hasFlag MUTABLE) List(getterDef, setterDef) - else List(getterDef); + else List(getterDef) if (mods hasFlag DEFERRED) gs else vdef :: gs case DocDef(comment, defn) => addGetterSetter(defn) map (stat => DocDef(comment, stat)) @@ -609,31 +609,31 @@ import scala.collection.mutable.{HashMap, ListBuffer} } def typedTemplate(templ: Template, parents1: List[Tree]): Template = { - val clazz = context.owner; - if (templ.symbol == NoSymbol) templ setSymbol clazz.newLocalDummy(templ.pos); + val clazz = context.owner + if (templ.symbol == NoSymbol) templ setSymbol clazz.newLocalDummy(templ.pos) val selfType = if (clazz.isAnonymousClass && !phase.erasedTypes) intersectionType(clazz.info.parents, clazz.owner) else if (settings.Xgadt.value) clazz.typeOfThis.asSeenFrom(context.prefix, clazz) - else clazz.typeOfThis; + else clazz.typeOfThis // the following is necessary for templates generated later - new Namer(context.outer.make(templ, clazz, clazz.info.decls)).enterSyms(templ.body); + new Namer(context.outer.make(templ, clazz, clazz.info.decls)).enterSyms(templ.body) validateParentClasses(parents1, selfType); - val body1 = typedStats(templ.body flatMap addGetterSetter, templ.symbol); + val body1 = typedStats(templ.body flatMap addGetterSetter, templ.symbol) copy.Template(templ, parents1, body1) setType clazz.tpe } def typedValDef(vdef: ValDef): ValDef = { - val sym = vdef.symbol; + val sym = vdef.symbol val typer1 = if (sym.hasFlag(PARAM) && sym.owner.isConstructor) newTyper(context.makeConstructorContext) - else this; - var tpt1 = checkNoEscaping.privates(sym, typer1.typedType(vdef.tpt)); - checkNonCyclic(vdef.pos, tpt1.tpe, sym); + else this + var tpt1 = checkNoEscaping.privates(sym, typer1.typedType(vdef.tpt)) + checkNonCyclic(vdef.pos, tpt1.tpe, sym) val rhs1 = if (vdef.rhs.isEmpty) { if (sym.isVariable && sym.owner.isTerm && phase.id <= currentRun.typerPhase.id) - error(vdef.pos, "local variables must be initialized"); + error(vdef.pos, "local variables must be initialized") vdef.rhs } else { newTyper(context.make(vdef, sym)).transformedOrTyped(vdef.rhs, tpt1.tpe) @@ -643,44 +643,44 @@ import scala.collection.mutable.{HashMap, ListBuffer} /** Enter all aliases of local parameter accessors. */ def computeParamAliases(clazz: Symbol, vparamss: List[List[ValDef]], rhs: Tree): unit = { - if (settings.debug.value) log("computing param aliases for " + clazz + ":" + clazz.primaryConstructor.tpe + ":" + rhs);//debug + if (settings.debug.value) log("computing param aliases for "+clazz+":"+clazz.primaryConstructor.tpe+":"+rhs);//debug def decompose(call: Tree): Pair[Tree, List[Tree]] = call match { case Apply(fn, args) => - val Pair(superConstr, args1) = decompose(fn); - val formals = fn.tpe.paramTypes; + val Pair(superConstr, args1) = decompose(fn) + val formals = fn.tpe.paramTypes val args2 = if (formals.isEmpty || formals.last.symbol != RepeatedParamClass) args - else args.take(formals.length - 1) ::: List(EmptyTree); - if (args2.length != formals.length) assert(false, "mismatch " + clazz + " " + formals + " " + args2);//debug + else args.take(formals.length - 1) ::: List(EmptyTree) + if (args2.length != formals.length) assert(false, "mismatch "+clazz+" "+formals+" "+args2);//debug Pair(superConstr, args1 ::: args2) case Block(stats, expr) => decompose(stats.head) case _ => Pair(call, List()) } - val Pair(superConstr, superArgs) = decompose(rhs); + val Pair(superConstr, superArgs) = decompose(rhs) assert(superConstr.symbol != null);//debug if (superConstr.symbol.isPrimaryConstructor) { - val superClazz = superConstr.symbol.owner; + val superClazz = superConstr.symbol.owner if (!superClazz.hasFlag(JAVA)) { - val superParamAccessors = superClazz.constrParamAccessors; + val superParamAccessors = superClazz.constrParamAccessors if (superParamAccessors.length != superArgs.length) { - System.out.println("" + superClazz + ":" + superClazz.info.decls.toList.filter(.hasFlag(PARAMACCESSOR))); - assert(false, "mismatch: " + superParamAccessors + ";" + rhs + ";" + superClazz.info.decls); //debug + System.out.println(""+superClazz+":"+superClazz.info.decls.toList.filter(.hasFlag(PARAMACCESSOR))) + assert(false, "mismatch: "+superParamAccessors+";"+rhs+";"+superClazz.info.decls); //debug } List.map2(superParamAccessors, superArgs) { (superAcc, superArg) => superArg match { case Ident(name) => if (vparamss.exists(.exists(vp => vp.symbol == superArg.symbol))) { - var alias = superAcc.initialize.alias; + var alias = superAcc.initialize.alias if (alias == NoSymbol) - alias = superAcc.getter(superAcc.owner); + alias = superAcc.getter(superAcc.owner) if (alias != NoSymbol && superClazz.info.nonPrivateMember(alias.name) != alias) - alias = NoSymbol; + alias = NoSymbol if (alias != NoSymbol) { - var ownAcc = clazz.info.decl(name); - if (ownAcc hasFlag ACCESSOR) ownAcc = ownAcc.accessed; - if (settings.debug.value) log("" + ownAcc + " has alias " + alias + alias.locationString);//debug + var ownAcc = clazz.info.decl(name) + if (ownAcc hasFlag ACCESSOR) ownAcc = ownAcc.accessed + if (settings.debug.value) log(""+ownAcc+" has alias "+alias + alias.locationString);//debug ownAcc.asInstanceOf[TermSymbol].setAlias(alias) } } @@ -693,23 +693,23 @@ import scala.collection.mutable.{HashMap, ListBuffer} } def typedSuperCall(tree: Tree): Tree = - typed(tree, EXPRmode | INCONSTRmode, UnitClass.tpe); + typed(tree, EXPRmode | INCONSTRmode, UnitClass.tpe) def typedDefDef(ddef: DefDef): DefDef = { - val meth = ddef.symbol; - reenterTypeParams(ddef.tparams); - reenterValueParams(ddef.vparamss); - val tparams1 = List.mapConserve(ddef.tparams)(typedAbsTypeDef); + val meth = ddef.symbol + reenterTypeParams(ddef.tparams) + reenterValueParams(ddef.vparamss) + val tparams1 = List.mapConserve(ddef.tparams)(typedAbsTypeDef) val vparamss1 = List.mapConserve(ddef.vparamss)(vparams1 => - List.mapConserve(vparams1)(typedValDef)); + List.mapConserve(vparams1)(typedValDef)) for (val vparams <- vparamss1; val vparam <- vparams) { checkNoEscaping.locals(context.scope, WildcardType, vparam.tpt); () } var tpt1 = checkNoEscaping.locals(context.scope, WildcardType, checkNoEscaping.privates(meth, - typedType(ddef.tpt))); - checkNonCyclic(ddef.pos, tpt1.tpe, meth); + typedType(ddef.tpt))) + checkNonCyclic(ddef.pos, tpt1.tpe, meth) val rhs1 = if (ddef.name == nme.CONSTRUCTOR) { if (!meth.hasFlag(SYNTHETIC) && @@ -717,10 +717,10 @@ import scala.collection.mutable.{HashMap, ListBuffer} meth.owner.isModuleClass || meth.owner.isAnonymousClass || meth.owner.isRefinementClass)) - error(ddef.pos, "constructor definition not allowed here " + meth.owner);//debug + error(ddef.pos, "constructor definition not allowed here "+meth.owner);//debug val result = ddef.rhs match { case Block(stat :: stats, expr) => - val stat1 = typedSuperCall(stat); + val stat1 = typedSuperCall(stat) newTyper(context.makeConstructorSuffixContext).typed( copy.Block(ddef.rhs, stats, expr), UnitClass.tpe) match { case block1 @ Block(stats1, expr1) => @@ -730,24 +730,24 @@ import scala.collection.mutable.{HashMap, ListBuffer} typedSuperCall(ddef.rhs) } if (meth.isPrimaryConstructor && !phase.erasedTypes && reporter.errors == 0) - computeParamAliases(meth.owner, vparamss1, result); + computeParamAliases(meth.owner, vparamss1, result) result - } else transformedOrTyped(ddef.rhs, tpt1.tpe); + } else transformedOrTyped(ddef.rhs, tpt1.tpe) copy.DefDef(ddef, ddef.mods, ddef.name, tparams1, vparamss1, tpt1, rhs1) setType NoType } def typedAbsTypeDef(tdef: AbsTypeDef): AbsTypeDef = { - val lo1 = checkNoEscaping.privates(tdef.symbol, typedType(tdef.lo)); - val hi1 = checkNoEscaping.privates(tdef.symbol, typedType(tdef.hi)); - checkNonCyclic(tdef.pos, tdef.symbol.tpe); + val lo1 = checkNoEscaping.privates(tdef.symbol, typedType(tdef.lo)) + val hi1 = checkNoEscaping.privates(tdef.symbol, typedType(tdef.hi)) + checkNonCyclic(tdef.pos, tdef.symbol.tpe) copy.AbsTypeDef(tdef, tdef.mods, tdef.name, lo1, hi1) setType NoType } def typedAliasTypeDef(tdef: AliasTypeDef): AliasTypeDef = { - reenterTypeParams(tdef.tparams); - val tparams1 = List.mapConserve(tdef.tparams)(typedAbsTypeDef); - val rhs1 = checkNoEscaping.privates(tdef.symbol, typedType(tdef.rhs)); - checkNonCyclic(tdef.pos, tdef.symbol.tpe); + reenterTypeParams(tdef.tparams) + val tparams1 = List.mapConserve(tdef.tparams)(typedAbsTypeDef) + val rhs1 = checkNoEscaping.privates(tdef.symbol, typedType(tdef.rhs)) + checkNonCyclic(tdef.pos, tdef.symbol.tpe) copy.AliasTypeDef(tdef, tdef.mods, tdef.name, tparams1, rhs1) setType NoType } @@ -755,39 +755,39 @@ import scala.collection.mutable.{HashMap, ListBuffer} case ldef @ LabelDef(_, _, _) => if (ldef.symbol == NoSymbol) ldef.symbol = namer.enterInScope( - context.owner.newLabel(ldef.pos, ldef.name) setInfo MethodType(List(), UnitClass.tpe)); + context.owner.newLabel(ldef.pos, ldef.name) setInfo MethodType(List(), UnitClass.tpe)) case _ => } def typedLabelDef(ldef: LabelDef): LabelDef = { - val restpe = ldef.symbol.tpe.resultType; - val rhs1 = typed(ldef.rhs, restpe); - ldef.params foreach (param => param.tpe = param.symbol.tpe); + val restpe = ldef.symbol.tpe.resultType + val rhs1 = typed(ldef.rhs, restpe) + ldef.params foreach (param => param.tpe = param.symbol.tpe) copy.LabelDef(ldef, ldef.name, ldef.params, rhs1) setType restpe } def typedBlock(block: Block, mode: int, pt: Type): Block = { - namer.enterSyms(block.stats); - block.stats foreach enterLabelDef; - val stats1 = typedStats(block.stats, context.owner); - val expr1 = typed(block.expr, mode & ~(FUNmode | QUALmode), pt); + namer.enterSyms(block.stats) + block.stats foreach enterLabelDef + val stats1 = typedStats(block.stats, context.owner) + val expr1 = typed(block.expr, mode & ~(FUNmode | QUALmode), pt) val block1 = copy.Block(block, stats1, expr1) - .setType(if (treeInfo.isPureExpr(block)) expr1.tpe else expr1.tpe.deconst); + .setType(if (treeInfo.isPureExpr(block)) expr1.tpe else expr1.tpe.deconst) if (isFullyDefined(pt)) block1 else { if (block1.tpe.symbol.isAnonymousClass) - block1 setType intersectionType(block1.tpe.parents, block1.tpe.symbol.owner); + block1 setType intersectionType(block1.tpe.parents, block1.tpe.symbol.owner) checkNoEscaping.locals(context.scope, pt, block1) } } def typedCase(cdef: CaseDef, pattpe: Type, pt: Type): CaseDef = { - val pat1: Tree = typedPattern(cdef.pat, pattpe); + val pat1: Tree = typedPattern(cdef.pat, pattpe) val guard1: Tree = if (cdef.guard == EmptyTree) EmptyTree - else typed(cdef.guard, BooleanClass.tpe); - var body1: Tree = typed(cdef.body, pt); + else typed(cdef.guard, BooleanClass.tpe) + var body1: Tree = typed(cdef.body, pt) if (!context.savedTypeBounds.isEmpty) { - context.restoreTypeBounds; + context.restoreTypeBounds // the following is a hack to make the pattern matcher work body1 = typed { @@ -812,47 +812,47 @@ import scala.collection.mutable.{HashMap, ListBuffer} fun.vparams.length == 1 && fun.body.isInstanceOf[Match]) Triple(pt.symbol, pt.typeArgs.init, pt.typeArgs.last) else - Triple(FunctionClass(fun.vparams.length), fun.vparams map (x => NoType), WildcardType); + Triple(FunctionClass(fun.vparams.length), fun.vparams map (x => NoType), WildcardType) val Triple(clazz, argpts, respt) = - decompose(if (pt.symbol == TypedCodeClass) pt.typeArgs.head else pt); + decompose(if (pt.symbol == TypedCodeClass) pt.typeArgs.head else pt) val vparamSyms = List.map2(fun.vparams, argpts) { (vparam, argpt) => if (vparam.tpt.isEmpty) vparam.tpt.tpe = if (argpt == NoType) { error(vparam.pos, "missing parameter type"); ErrorType } - else argpt; - namer.enterSym(vparam); + else argpt + namer.enterSym(vparam) vparam.symbol } - val vparams = List.mapConserve(fun.vparams)(typedValDef); + val vparams = List.mapConserve(fun.vparams)(typedValDef) for (val vparam <- vparams) { checkNoEscaping.locals(context.scope, WildcardType, vparam.tpt); () } - val body = checkNoEscaping.locals(context.scope, respt, typed(fun.body, respt)); - val formals = vparamSyms map (.tpe); - val restpe = body.tpe.deconst; - val funtpe = typeRef(clazz.tpe.prefix, clazz, formals ::: List(restpe)); + val body = checkNoEscaping.locals(context.scope, respt, typed(fun.body, respt)) + val formals = vparamSyms map (.tpe) + val restpe = body.tpe.deconst + val funtpe = typeRef(clazz.tpe.prefix, clazz, formals ::: List(restpe)) val fun1 = copy.Function(fun, vparams, checkNoEscaping.locals(context.scope, restpe, body)) - .setType(funtpe); + .setType(funtpe) if (pt.symbol == TypedCodeClass) typed(atPos(fun.pos)(codify(fun1))) else fun1 } def typedRefinement(stats: List[Tree]): List[Tree] = { - namer.enterSyms(stats); - for (val stat <- stats) stat.symbol setFlag OVERRIDE; - typedStats(stats, NoSymbol); + namer.enterSyms(stats) + for (val stat <- stats) stat.symbol setFlag OVERRIDE + typedStats(stats, NoSymbol) } def typedStats(stats: List[Tree], exprOwner: Symbol): List[Tree] = List.mapConserve(stats) { stat => if (context.owner.isRefinementClass && !treeInfo.isDeclaration(stat)) - errorTree(stat, "only declarations allowed here"); + errorTree(stat, "only declarations allowed here") stat match { case imp @ Import(_, _) => - context = context.makeNewImport(imp); - stat.symbol.initialize; + context = context.makeNewImport(imp) + stat.symbol.initialize EmptyTree case _ => (if (exprOwner != context.owner && (!stat.isDef || stat.isInstanceOf[LabelDef])) @@ -862,79 +862,78 @@ import scala.collection.mutable.{HashMap, ListBuffer} protected def typed1(tree: Tree, mode: int, pt: Type): Tree = { - def funmode = mode & stickyModes | FUNmode | POLYmode; + def funmode = mode & stickyModes | FUNmode | POLYmode - def ptOrLub(tps: List[Type]) = if (isFullyDefined(pt)) pt else lub(tps); + def ptOrLub(tps: List[Type]) = if (isFullyDefined(pt)) pt else lub(tps) def typedTypeApply(fun: Tree, args: List[Tree]): Tree = fun.tpe match { case OverloadedType(pre, alts) => - inferPolyAlternatives(fun, args.length); + inferPolyAlternatives(fun, args.length) typedTypeApply(fun, args) case PolyType(tparams, restpe) if (tparams.length != 0) => if (tparams.length == args.length) { - val targs = args map (.tpe); - checkBounds(tree.pos, tparams, targs, ""); - copy.TypeApply(tree, fun, args) setType restpe.subst(tparams, targs); + val targs = args map (.tpe) + checkBounds(tree.pos, tparams, targs, "") + copy.TypeApply(tree, fun, args) setType restpe.subst(tparams, targs) } else { - errorTree(tree, "wrong number of type parameters for " + treeSymTypeMsg(fun)) + errorTree(tree, "wrong number of type parameters for "+treeSymTypeMsg(fun)) } case ErrorType => setError(tree) case _ => - System.out.println(fun.toString() + " " + args);//debug - errorTree(tree, treeSymTypeMsg(fun) + " does not take type parameters."); + errorTree(tree, treeSymTypeMsg(fun)+" does not take type parameters.") } def typedArg(arg: Tree, pt: Type): Tree = { val argTyper = if ((mode & INCONSTRmode) != 0) newTyper(context.makeConstructorContext) - else this; + else this argTyper.typed(arg, mode & stickyModes, pt) } def typedApply(fun: Tree, args: List[Tree]): Tree = fun.tpe match { case OverloadedType(pre, alts) => val args1 = List.mapConserve(args)(arg => - typedArg(arg, WildcardType)); - inferMethodAlternative(fun, context.undetparams, args1 map (.tpe.deconst), pt); - typedApply(adapt(fun, funmode, WildcardType), args1); + typedArg(arg, WildcardType)) + inferMethodAlternative(fun, context.undetparams, args1 map (.tpe.deconst), pt) + typedApply(adapt(fun, funmode, WildcardType), args1) case MethodType(formals0, restpe) => - val formals = formalTypes(formals0, args.length); + val formals = formalTypes(formals0, args.length) if (formals.length != args.length) { - //System.out.println("" + formals.length + " " + args.length);//DEBUG - errorTree(tree, "wrong number of arguments for " + treeSymTypeMsg(fun)) + //System.out.println(""+formals.length+" "+args.length);//DEBUG + errorTree(tree, "wrong number of arguments for "+treeSymTypeMsg(fun)) } else { - val tparams = context.undetparams; - context.undetparams = List(); + val tparams = context.undetparams + context.undetparams = List() if (tparams.isEmpty) { - val args1 = List.map2(args, formals)(typedArg); + val args1 = List.map2(args, formals)(typedArg) def ifPatternSkipFormals(tp: Type) = tp match { case MethodType(_, rtp) if ((mode & PATTERNmode) != 0) => rtp case _ => tp } - constfold(copy.Apply(tree, fun, args1).setType(ifPatternSkipFormals(restpe))); + constfold(copy.Apply(tree, fun, args1).setType(ifPatternSkipFormals(restpe))) } else { assert((mode & PATTERNmode) == 0); // this case cannot arise for patterns - val lenientTargs = protoTypeArgs(tparams, formals, restpe, pt); + val lenientTargs = protoTypeArgs(tparams, formals, restpe, pt) val strictTargs = List.map2(lenientTargs, tparams)((targ, tparam) => - if (targ == WildcardType) tparam.tpe else targ); + if (targ == WildcardType) tparam.tpe else targ) def typedArgToPoly(arg: Tree, formal: Type): Tree = { - val lenientPt = formal.subst(tparams, lenientTargs); - val arg1 = typedArg(arg, lenientPt); - val argtparams = context.undetparams; - context.undetparams = List(); + val lenientPt = formal.subst(tparams, lenientTargs) + val arg1 = typedArg(arg, lenientPt) + val argtparams = context.undetparams + context.undetparams = List() if (!argtparams.isEmpty) { - val strictPt = formal.subst(tparams, strictTargs); - inferArgumentInstance(arg1, argtparams, strictPt, lenientPt); + val strictPt = formal.subst(tparams, strictTargs) + inferArgumentInstance(arg1, argtparams, strictPt, lenientPt) } arg1 } - val args1 = List.map2(args, formals)(typedArgToPoly); + val args1 = List.map2(args, formals)(typedArgToPoly) if (args1 exists (.tpe.isError)) setError(tree) else { - if (settings.debug.value) log("infer method inst " + fun + ", tparams = " + tparams + ", args = " + args1.map(.tpe) + ", pt = " + pt + ", lobounds = " + tparams.map(.tpe.bounds.lo));//debug - val undetparams = inferMethodInstance(fun, tparams, args1, pt); - val result = typedApply(fun, args1); - context.undetparams = undetparams; + if (settings.debug.value) log("infer method inst "+fun+", tparams = "+tparams+", args = "+args1.map(.tpe)+", pt = "+pt+", lobounds = "+tparams.map(.tpe.bounds.lo));//debug + val undetparams = inferMethodInstance(fun, tparams, args1, pt) + val result = typedApply(fun, args1) + context.undetparams = undetparams result } } @@ -942,19 +941,19 @@ import scala.collection.mutable.{HashMap, ListBuffer} case ErrorType => setError(tree) case _ => - errorTree(tree, "" + fun + " does not take parameters"); + errorTree(tree, ""+fun+" does not take parameters") } /** The qualifying class of a this or super with prefix `qual' */ def qualifyingClassContext(qual: Name): Context = { if (qual == nme.EMPTY.toTypeName) { if (context.enclClass.owner.isPackageClass) - error(tree.pos, "" + tree + " can be used only in a class, object, or template"); + error(tree.pos, ""+tree+" can be used only in a class, object, or template") context.enclClass } else { - var c = context.enclClass; - while (c != NoContext && c.owner.name != qual) c = c.outer.enclClass; - if (c == NoContext) error(tree.pos, "" + qual + " is not an enclosing class"); + var c = context.enclClass + while (c != NoContext && c.owner.name != qual) c = c.outer.enclClass + if (c == NoContext) error(tree.pos, ""+qual+" is not an enclosing class") c } } @@ -965,15 +964,15 @@ import scala.collection.mutable.{HashMap, ListBuffer} def typedSelect(qual: Tree, name: Name): Tree = { val sym = if (tree.symbol != NoSymbol) { - if (phase.erasedTypes && qual.isInstanceOf[Super]) qual.tpe = tree.symbol.owner.tpe; + if (phase.erasedTypes && qual.isInstanceOf[Super]) qual.tpe = tree.symbol.owner.tpe if (false && settings.debug.value) { // todo: replace by settings.check.value? - val alts = qual.tpe.member(tree.symbol.name).alternatives; + val alts = qual.tpe.member(tree.symbol.name).alternatives if (!(alts exists (alt => alt == tree.symbol || alt.isTerm && (alt.tpe matches tree.symbol.tpe)))) - assert(false, "symbol " + tree.symbol + tree.symbol.locationString + " not in " + alts + " of " + qual.tpe + - "\n members = " + qual.tpe.members + - "\n type history = " + qual.tpe.symbol.infosString + - "\n phase = " + phase); + assert(false, "symbol "+tree.symbol+tree.symbol.locationString+" not in "+alts+" of "+qual.tpe+ + "\n members = "+qual.tpe.members+ + "\n type history = "+qual.tpe.symbol.infosString+ + "\n phase = "+phase) } tree.symbol } else qual.tpe match { @@ -983,24 +982,24 @@ import scala.collection.mutable.{HashMap, ListBuffer} qual.tpe.nonLocalMember(name) } if (sym == NoSymbol) { - val qual1 = adaptToName(qual, name); + val qual1 = adaptToName(qual, name) if (qual1 ne qual) return typed(copy.Select(tree, qual1, name), mode, pt) } if (sym.info == NoType) { - if (settings.debug.value) log("qual = " + qual + ":" + qual.tpe + "\nSymbol=" + qual.tpe.symbol + "\nsymbol-info = " + qual.tpe.symbol.info + "\nscope-id = " + qual.tpe.symbol.info.decls.hashCode() + "\nmembers = " + qual.tpe.members + "\nfound = " + sym); + if (settings.debug.value) log("qual = "+qual+":"+qual.tpe+"\nSymbol="+qual.tpe.symbol+"\nsymbol-info = "+qual.tpe.symbol.info+"\nscope-id = "+qual.tpe.symbol.info.decls.hashCode()+"\nmembers = "+qual.tpe.members+"\nfound = "+sym) if (!qual.tpe.widen.isError) error(tree.pos, - decode(name) + " is not a member of " + qual.tpe.widen + + decode(name)+" is not a member of "+qual.tpe.widen + (if (Position.line(context.unit.source, qual.pos) < Position.line(context.unit.source, tree.pos)) - "\npossible cause: maybe a semicolon is missing before `" + name + "'?" else "")); + "\npossible cause: maybe a semicolon is missing before `"+name+"'?" else "")) setError(tree) } else { val tree1 = tree match { case Select(_, _) => copy.Select(tree, qual, name) - case SelectFromTypeTree(_, _) => copy.SelectFromTypeTree(tree, qual, name); + case SelectFromTypeTree(_, _) => copy.SelectFromTypeTree(tree, qual, name) } - stabilize(checkAccessible(tree1, sym, qual.tpe, qual), qual.tpe, mode, pt); + stabilize(checkAccessible(tree1, sym, qual.tpe, qual), qual.tpe, mode, pt) } } @@ -1012,7 +1011,7 @@ import scala.collection.mutable.{HashMap, ListBuffer} */ def typedIdent(name: Name): Tree = { def ambiguousError(msg: String) = - error(tree.pos, "reference to " + name + " is ambiguous;\n" + msg); + error(tree.pos, "reference to "+name+" is ambiguous;\n"+msg) var defSym: Symbol = tree.symbol; // the directly found symbol var pre: Type = NoPrefix; // the prefix type of defSym, if a class member @@ -1021,25 +1020,25 @@ import scala.collection.mutable.{HashMap, ListBuffer} if (defSym == NoSymbol) { var defEntry: ScopeEntry = null; // the scope entry of defSym, if defined in a local scope - var cx = context; + var cx = context while (defSym == NoSymbol && cx != NoContext) { - pre = cx.enclClass.prefix; - defEntry = cx.scope.lookupEntry(name); + pre = cx.enclClass.prefix + defEntry = cx.scope.lookupEntry(name) if (defEntry != null) { - defSym = defEntry.sym; + defSym = defEntry.sym } else { - cx = cx.enclClass; - defSym = pre.member(name) filter (sym => context.isAccessible(sym, pre, false)); - if (defSym == NoSymbol) cx = cx.outer; + cx = cx.enclClass + defSym = pre.member(name) filter (sym => context.isAccessible(sym, pre, false)) + if (defSym == NoSymbol) cx = cx.outer } } val symDepth = if (defEntry == null) cx.depth - else cx.depth - (cx.scope.nestingLevel - defEntry.owner.nestingLevel); + else cx.depth - (cx.scope.nestingLevel - defEntry.owner.nestingLevel) var impSym: Symbol = NoSymbol; // the imported symbol var imports = context.imports; // impSym != NoSymbol => it is imported from imports.head while (impSym == NoSymbol && !imports.isEmpty && imports.head.depth > symDepth) { - impSym = imports.head.importedSymbol(name); - if (impSym == NoSymbol) imports = imports.tail; + impSym = imports.head.importedSymbol(name) + if (impSym == NoSymbol) imports = imports.tail } // detect ambiguous definition/import, @@ -1047,64 +1046,72 @@ import scala.collection.mutable.{HashMap, ListBuffer} // update `pre' to be `sym's prefix type in case it is an imported member, // and compute value of: - // imported symbols take precedence over external package-owned symbols (hack?) - if (defSym.tpe != NoType && impSym.tpe != NoType && defSym.isExternal && defSym.owner.isPackageClass) - defSym = NoSymbol; + // imported symbols take precedence over package-owned symbols in different + // compilation units + if (defSym.tpe != NoType && impSym.tpe != NoType && + defSym.owner.isPackageClass && + (defSym.isExternal || + context.unit != null && defSym.sourceFile != context.unit.source.file)) + defSym = NoSymbol if (defSym.tpe != NoType) { if (impSym.tpe != NoType) ambiguousError( - "it is both defined in " + defSym.owner + - " and imported subsequently by \n" + imports.head); + "it is both defined in "+defSym.owner + + " and imported subsequently by \n"+imports.head) else if (!defSym.owner.isClass || defSym.owner.isPackageClass || defSym.isTypeParameterOrSkolem) pre = NoPrefix else - qual = atPos(tree.pos)(gen.mkQualifier(pre)); + qual = atPos(tree.pos)(gen.mkQualifier(pre)) } else { if (impSym.tpe != NoType) { - var impSym1 = NoSymbol; - var imports1 = imports.tail; + var impSym1 = NoSymbol + var imports1 = imports.tail def ambiguousImportError = ambiguousError( - "it is imported twice in the same scope by\n" + imports.head + "\nand " + imports1.head); - while (!imports1.isEmpty && imports1.head.depth == imports.head.depth) { - var impSym1 = imports1.head.importedSymbol(name); + "it is imported twice in the same scope by\n"+imports.head + "\nand "+imports1.head) + while (!imports1.isEmpty && + (!imports.head.isExplicitImport(name) || + imports1.head.depth == imports.head.depth)) { + var impSym1 = imports1.head.importedSymbol(name) if (impSym1 != NoSymbol) { if (imports1.head.isExplicitImport(name)) { - if (imports.head.isExplicitImport(name)) ambiguousImportError; - impSym = impSym1; - imports = imports1; - } else if (!imports.head.isExplicitImport(name)) ambiguousImportError + if (imports.head.isExplicitImport(name) || + imports1.head.depth != imports.head.depth) ambiguousImportError + impSym = impSym1; + imports = imports1 + } else if (!imports.head.isExplicitImport(name) && + imports1.head.depth == imports.head.depth) ambiguousImportError } - imports1 = imports1.tail; + imports1 = imports1.tail } - defSym = impSym; - qual = imports.head.qual; - pre = qual.tpe; + defSym = impSym + qual = imports.head.qual + pre = qual.tpe } else { if (settings.debug.value) { log(context.imports);//debug } - error(tree.pos, "not found: " + decode(name)); - defSym = context.owner.newErrorSymbol(name); + error(tree.pos, "not found: "+decode(name)) + defSym = context.owner.newErrorSymbol(name) } } } - if (defSym.owner.isPackageClass) pre = defSym.owner.thisType; + if (defSym.owner.isPackageClass) pre = defSym.owner.thisType val tree1 = if (qual == EmptyTree) tree else atPos(tree.pos)(Select(qual, name)); // atPos necessary because qualifier might come from startContext - //System.out.println("check acc: " + defSym + " " + pre);//DEBUG + //System.out.println("check acc: "+defSym+" "+pre);//DEBUG stabilize(checkAccessible(tree1, defSym, pre, qual), pre, mode, pt) } // begin typed1 - val sym: Symbol = tree.symbol; - if (sym != null) sym.initialize; - //if (settings.debug.value && tree.isDef) log("typing definition of " + sym);//DEBUG + val sym: Symbol = tree.symbol + if (sym != null) sym.initialize + //if (settings.debug.value && tree.isDef) log("typing definition of "+sym);//DEBUG tree match { case PackageDef(name, stats) => val stats1 = newTyper(context.make(tree, sym.moduleClass, sym.info.decls)) - .typedStats(stats, NoSymbol); + .typedStats(stats, NoSymbol) copy.PackageDef(tree, name, stats1) setType NoType case cdef @ ClassDef(_, _, _, _, _) => @@ -1126,51 +1133,51 @@ import scala.collection.mutable.{HashMap, ListBuffer} newTyper(context.makeNewScope(tree, sym)).typedAliasTypeDef(tdef) case ldef @ LabelDef(_, _, _) => - var lsym = ldef.symbol; - var typer1 = this; + var lsym = ldef.symbol + var typer1 = this if (lsym == NoSymbol) { // labeldef is part of template - typer1 = newTyper(context.makeNewScope(tree, context.owner)); - typer1.enterLabelDef(ldef); + typer1 = newTyper(context.makeNewScope(tree, context.owner)) + typer1.enterLabelDef(ldef) } typer1.typedLabelDef(ldef) case Attributed(attr, defn) => - val attr1 = typed(attr, AttributeClass.tpe); - val defn1 = typed(defn, mode, pt); - val ai = attrInfo(attr1); - if (ai != null) defn1.symbol.attributes = defn1.symbol.attributes ::: List(ai); + val attr1 = typed(attr, AttributeClass.tpe) + val defn1 = typed(defn, mode, pt) + val ai = attrInfo(attr1) + if (ai != null) defn1.symbol.attributes = defn1.symbol.attributes ::: List(ai) defn1 case DocDef(comment, defn) => - typed(defn, mode, pt); + typed(defn, mode, pt) case block @ Block(_, _) => newTyper(context.makeNewScope(tree, context.owner)) .typedBlock(block, mode, pt) case Sequence(elems) => - val elems1 = List.mapConserve(elems)(elem => typed(elem, mode, pt)); + val elems1 = List.mapConserve(elems)(elem => typed(elem, mode, pt)) copy.Sequence(tree, elems1) setType pt case Alternative(alts) => - val alts1 = List.mapConserve(alts)(alt => typed(alt, mode, pt)); + val alts1 = List.mapConserve(alts)(alt => typed(alt, mode, pt)) copy.Alternative(tree, alts1) setType pt case Star(elem) => - val elem1 = typed(elem, mode, pt); + val elem1 = typed(elem, mode, pt) copy.Star(tree, elem1) setType pt case Bind(name, body) => - var vble = tree.symbol; - if (vble == NoSymbol) vble = context.owner.newValue(tree.pos, name); - if (vble.name != nme.WILDCARD) namer.enterInScope(vble); - val body1 = typed(body, mode, pt); - vble.setInfo(if (treeInfo.isSequenceValued(body)) seqType(body1.tpe) else body1.tpe); + var vble = tree.symbol + if (vble == NoSymbol) vble = context.owner.newValue(tree.pos, name) + if (vble.name != nme.WILDCARD) namer.enterInScope(vble) + val body1 = typed(body, mode, pt) + vble.setInfo(if (treeInfo.isSequenceValued(body)) seqType(body1.tpe) else body1.tpe) copy.Bind(tree, name, body1) setSymbol vble setType body1.tpe; // buraq, was: pt case ArrayValue(elemtpt, elems) => - val elemtpt1 = typedType(elemtpt); - val elems1 = List.mapConserve(elems)(elem => typed(elem, mode, elemtpt1.tpe)); + val elemtpt1 = typedType(elemtpt) + val elems1 = List.mapConserve(elems)(elem => typed(elem, mode, elemtpt1.tpe)) copy.ArrayValue(tree, elemtpt1, elems1) .setType(if (isFullyDefined(pt) && !phase.erasedTypes) pt else appliedType(ArrayClass.typeConstructor, List(elemtpt1.tpe))) @@ -1180,7 +1187,7 @@ import scala.collection.mutable.{HashMap, ListBuffer} newTyper(context.makeNewScope(tree, context.owner)).typedFunction(fun, mode, pt) */ tree.symbol = context.owner.newValue(tree.pos, nme.ANON_FUN_NAME) - .setFlag(SYNTHETIC).setInfo(NoType); + .setFlag(SYNTHETIC).setInfo(NoType) newTyper(context.makeNewScope(tree, tree.symbol)).typedFunction(fun, mode, pt) case Assign(lhs, rhs) => @@ -1188,8 +1195,8 @@ import scala.collection.mutable.{HashMap, ListBuffer} case PolyType(List(), _) => sym.owner.isClass && !sym.isStable case _ => false } - val lhs1 = typed(lhs); - val varsym = lhs1.symbol; + val lhs1 = typed(lhs) + val varsym = lhs1.symbol if (varsym != null && isGetter(varsym)) { lhs1 match { case Select(qual, name) => @@ -1199,66 +1206,66 @@ import scala.collection.mutable.{HashMap, ListBuffer} List(rhs)) setPos tree.pos, mode, pt) } } else if (varsym != null && (varsym.isVariable || varsym.isValue && phase.erasedTypes)) { - val rhs1 = typed(rhs, lhs1.tpe); - copy.Assign(tree, lhs1, rhs1) setType UnitClass.tpe; + val rhs1 = typed(rhs, lhs1.tpe) + copy.Assign(tree, lhs1, rhs1) setType UnitClass.tpe } else { - System.out.println("" + lhs1 + " " + varsym + " " + varsym.isValue + " " + flagsToString(varsym.flags));//debug - if (!lhs1.tpe.isError) error(tree.pos, "assignment to non-variable "); + System.out.println(""+lhs1+" "+varsym+" "+varsym.isValue+" "+flagsToString(varsym.flags));//debug + if (!lhs1.tpe.isError) error(tree.pos, "assignment to non-variable ") setError(tree) } case If(cond, thenp, elsep) => - val cond1 = typed(cond, BooleanClass.tpe); + val cond1 = typed(cond, BooleanClass.tpe) if (elsep.isEmpty) { - val thenp1 = typed(thenp, UnitClass.tpe); + val thenp1 = typed(thenp, UnitClass.tpe) copy.If(tree, cond1, thenp1, elsep) setType UnitClass.tpe } else { - val thenp1 = typed(thenp, pt); - val elsep1 = typed(elsep, pt); - copy.If(tree, cond1, thenp1, elsep1) setType ptOrLub(List(thenp1.tpe, elsep1.tpe)); + val thenp1 = typed(thenp, pt) + val elsep1 = typed(elsep, pt) + copy.If(tree, cond1, thenp1, elsep1) setType ptOrLub(List(thenp1.tpe, elsep1.tpe)) } case Match(selector, cases) => - val selector1 = typed(selector); - val cases1 = typedCases(tree, cases, selector1.tpe.widen, pt); + val selector1 = typed(selector) + val cases1 = typedCases(tree, cases, selector1.tpe.widen, pt) copy.Match(tree, selector1, cases1) setType ptOrLub(cases1 map (.tpe)) case Return(expr) => - val enclFun = if (tree.symbol != NoSymbol) tree.symbol else context.owner.enclMethod; + val enclFun = if (tree.symbol != NoSymbol) tree.symbol else context.owner.enclMethod if (!enclFun.isMethod || enclFun.isConstructor) errorTree(tree, "return outside method definition") else if (!context.owner.isInitialized) - errorTree(tree, "method " + context.owner + " has return statement; needs result type") + errorTree(tree, "method "+context.owner+" has return statement; needs result type") else { - val expr1: Tree = typed(expr, enclFun.tpe.finalResultType); - copy.Return(tree, expr1) setSymbol enclFun setType AllClass.tpe; + val expr1: Tree = typed(expr, enclFun.tpe.finalResultType) + copy.Return(tree, expr1) setSymbol enclFun setType AllClass.tpe } case Try(block, catches, finalizer) => - val block1 = typed(block, pt); - val catches1 = typedCases(tree, catches, ThrowableClass.tpe, pt); + val block1 = typed(block, pt) + val catches1 = typedCases(tree, catches, ThrowableClass.tpe, pt) val finalizer1 = if (finalizer.isEmpty) finalizer - else typed(finalizer, UnitClass.tpe); + else typed(finalizer, UnitClass.tpe) copy.Try(tree, block1, catches1, finalizer1) .setType(ptOrLub(block1.tpe :: (catches1 map (.tpe)))) case Throw(expr) => - val expr1 = typed(expr, ThrowableClass.tpe); + val expr1 = typed(expr, ThrowableClass.tpe) copy.Throw(tree, expr1) setType AllClass.tpe case New(tpt: Tree) => - var tpt1 = typedTypeConstructor(tpt); + var tpt1 = typedTypeConstructor(tpt) if (tpt1.hasSymbol && !tpt1.symbol.typeParams.isEmpty) { - context.undetparams = cloneSymbols(tpt1.symbol.unsafeTypeParams); + context.undetparams = cloneSymbols(tpt1.symbol.unsafeTypeParams) tpt1 = TypeTree() .setPos(tpt1.pos) - .setType(appliedType(tpt1.tpe, context.undetparams map (.tpe))); + .setType(appliedType(tpt1.tpe, context.undetparams map (.tpe))) } - if (tpt1.tpe.symbol.isTrait) error(tree.pos, "traits cannot be instantiated"); + if (tpt1.tpe.symbol.isTrait) error(tree.pos, "traits cannot be instantiated") copy.New(tree, tpt1).setType(tpt1.tpe) case Typed(expr, tpt @ Ident(name)) if (name == nme.WILDCARD_STAR.toTypeName) => - val expr1 = typed(expr, mode & stickyModes, seqType(pt)); + val expr1 = typed(expr, mode & stickyModes, seqType(pt)) expr1.tpe.baseType(SeqClass) match { case TypeRef(_, _, List(elemtp)) => copy.Typed(tree, expr1, tpt setType elemtp) setType elemtp @@ -1266,12 +1273,12 @@ import scala.collection.mutable.{HashMap, ListBuffer} setError(tree) } case Typed(expr, tpt) => - val tpt1 = typedType(tpt); - val expr1 = typed(expr, mode & stickyModes, tpt1.tpe); + val tpt1 = typedType(tpt) + val expr1 = typed(expr, mode & stickyModes, tpt1.tpe) copy.Typed(tree, expr1, tpt1) setType tpt1.tpe case TypeApply(fun, args) => - val args1 = List.mapConserve(args)(typedType); + val args1 = List.mapConserve(args)(typedType) // do args first in order to maintain conext.undetparams on the function side. typedTypeApply(typed(fun, funmode | TAPPmode, WildcardType), args1) @@ -1279,26 +1286,26 @@ import scala.collection.mutable.{HashMap, ListBuffer} typed1(Block(stats, Apply(expr, args)), mode, pt) case Apply(fun, args) => - val stableApplication = fun.symbol != null && fun.symbol.isMethod && fun.symbol.isStable; + val stableApplication = fun.symbol != null && fun.symbol.isMethod && fun.symbol.isStable if (stableApplication && (mode & PATTERNmode) != 0) { // treat stable function applications f() as expressions. typed1(tree, mode & ~PATTERNmode | EXPRmode, pt) } else { - val funpt = if ((mode & PATTERNmode) != 0) pt else WildcardType; - var fun1 = typed(fun, funmode, funpt); - if (stableApplication) fun1 = stabilizeFun(fun1, mode, pt); + val funpt = if ((mode & PATTERNmode) != 0) pt else WildcardType + var fun1 = typed(fun, funmode, funpt) + if (stableApplication) fun1 = stabilizeFun(fun1, mode, pt) // if function is overloaded, filter all alternatives that match // number of arguments and expected result type. - // if (settings.debug.value) log("trans app " + fun1 + ":" + fun1.symbol + ":" + fun1.tpe + " " + args);//DEBUG + // if (settings.debug.value) log("trans app "+fun1+":"+fun1.symbol+":"+fun1.tpe+" "+args);//DEBUG if (fun1.hasSymbol && fun1.symbol.hasFlag(OVERLOADED)) { - val argtypes = args map (arg => AllClass.tpe); - val pre = fun1.symbol.tpe.prefix; + val argtypes = args map (arg => AllClass.tpe) + val pre = fun1.symbol.tpe.prefix val sym = fun1.symbol filter (alt => - isApplicable(context.undetparams, pre.memberType(alt), argtypes, pt)); + isApplicable(context.undetparams, pre.memberType(alt), argtypes, pt)) if (sym != NoSymbol) fun1 = adapt(fun1 setSymbol sym setType pre.memberType(sym), funmode, WildcardType) } - if (util.Statistics.enabled) appcnt = appcnt + 1; + if (util.Statistics.enabled) appcnt = appcnt + 1 typedApply(fun1, args) } @@ -1307,7 +1314,7 @@ import scala.collection.mutable.{HashMap, ListBuffer} if (tree.symbol != NoSymbol) { Pair(tree.symbol, tree.symbol.thisType) } else { - val clazzContext = qualifyingClassContext(qual); + val clazzContext = qualifyingClassContext(qual) Pair(clazzContext.owner, clazzContext.prefix) } if (clazz == NoSymbol) setError(tree) @@ -1317,10 +1324,10 @@ import scala.collection.mutable.{HashMap, ListBuffer} if ((mode & SUPERCONSTRmode) != 0) clazz.info.parents.head else intersectionType(clazz.info.parents) else { - val ps = clazz.info.parents dropWhile (p => p.symbol.name != mix); + val ps = clazz.info.parents dropWhile (p => p.symbol.name != mix) if (ps.isEmpty) { System.out.println(clazz.info.parents map (.symbol.name));//debug - error(tree.pos, "" + mix + " does not name a base class of " + clazz); + error(tree.pos, ""+mix+" does not name a base class of "+clazz) ErrorType } else ps.head } @@ -1332,29 +1339,29 @@ import scala.collection.mutable.{HashMap, ListBuffer} if (tree.symbol != NoSymbol) { Pair(tree.symbol, tree.symbol.thisType) } else { - val clazzContext = qualifyingClassContext(qual); + val clazzContext = qualifyingClassContext(qual) Pair(clazzContext.owner, clazzContext.prefix) } if (clazz == NoSymbol) setError(tree) else { val owntype = if (pt.isStable || (mode & QUALmode) != 0) selftype - else selftype.singleDeref; + else selftype.singleDeref tree setSymbol clazz setType owntype } case Select(qual @ Super(_, _), nme.CONSTRUCTOR) => - val qual1 = typed(qual, EXPRmode | QUALmode | POLYmode | SUPERCONSTRmode, WildcardType); + val qual1 = typed(qual, EXPRmode | QUALmode | POLYmode | SUPERCONSTRmode, WildcardType) // the qualifier type of a supercall constructor is its first parent class - typedSelect(qual1, nme.CONSTRUCTOR); + typedSelect(qual1, nme.CONSTRUCTOR) case Select(qual, name) => - if (util.Statistics.enabled) selcnt = selcnt + 1; - var qual1 = typedQualifier(qual); - if (name.isTypeName) qual1 = checkStable(qual1); - typedSelect(qual1, name); + if (util.Statistics.enabled) selcnt = selcnt + 1 + var qual1 = typedQualifier(qual) + if (name.isTypeName) qual1 = checkStable(qual1) + typedSelect(qual1, name) case Ident(name) => - idcnt = idcnt + 1; + idcnt = idcnt + 1 if (name == nme.WILDCARD && (mode & (PATTERNmode | FUNmode)) == PATTERNmode) tree setType pt else @@ -1367,44 +1374,44 @@ import scala.collection.mutable.{HashMap, ListBuffer} else ConstantType(value)) case SingletonTypeTree(ref) => - val ref1 = checkStable(typed(ref, EXPRmode | QUALmode, AnyRefClass.tpe)); - tree setType ref1.tpe.resultType; + val ref1 = checkStable(typed(ref, EXPRmode | QUALmode, AnyRefClass.tpe)) + tree setType ref1.tpe.resultType case SelectFromTypeTree(qual, selector) => tree setType typedSelect(typedType(qual), selector).tpe case CompoundTypeTree(templ: Template) => tree setType { - val parents1 = List.mapConserve(templ.parents)(typedType); + val parents1 = List.mapConserve(templ.parents)(typedType) if (parents1 exists (.tpe.isError)) ErrorType else { - val decls = new Scope(); - val self = refinedType(parents1 map (.tpe), context.enclClass.owner, decls); - newTyper(context.make(templ, self.symbol, decls)).typedRefinement(templ.body); + val decls = new Scope() + val self = refinedType(parents1 map (.tpe), context.enclClass.owner, decls) + newTyper(context.make(templ, self.symbol, decls)).typedRefinement(templ.body) self } } case AppliedTypeTree(tpt, args) => - val tpt1 = typed1(tpt, mode | FUNmode | TAPPmode, WildcardType); - val tparams = tpt1.symbol.typeParams; - val args1 = List.mapConserve(args)(typedType); + val tpt1 = typed1(tpt, mode | FUNmode | TAPPmode, WildcardType) + val tparams = tpt1.symbol.typeParams + val args1 = List.mapConserve(args)(typedType) if (tpt1.tpe.isError) { setError(tree) } else if (tparams.length == args1.length) { - val argtypes = args1 map (.tpe); + val argtypes = args1 map (.tpe) val owntype = if (tpt1.symbol.isClass) appliedType(tpt1.tpe, argtypes) - else tpt1.tpe.subst(tparams, argtypes); + else tpt1.tpe.subst(tparams, argtypes) TypeTree(owntype) setOriginal(tree) // setPos tree.pos } else if (tparams.length == 0) { - errorTree(tree, "" + tpt1.tpe + " does not take type parameters") + errorTree(tree, ""+tpt1.tpe+" does not take type parameters") } else { - //System.out.println("\{tpt1}:\{tpt1.symbol}:\{tpt1.symbol.info}"); - System.out.println("" + tpt1 + ":" + tpt1.symbol + ":" + tpt1.symbol.info);//debug - errorTree(tree, "wrong number of type arguments for " + tpt1.tpe + ", should be " + tparams.length) + //System.out.println("\{tpt1}:\{tpt1.symbol}:\{tpt1.symbol.info}") + System.out.println(""+tpt1+":"+tpt1.symbol+":"+tpt1.symbol.info);//debug + errorTree(tree, "wrong number of type arguments for "+tpt1.tpe+", should be "+tparams.length) } case _ => - throw new Error("unexpected tree: " + tree);//debug + throw new Error("unexpected tree: "+tree);//debug } } @@ -1412,65 +1419,65 @@ import scala.collection.mutable.{HashMap, ListBuffer} try { if (settings.debug.value) { assert(pt != null, tree);//debug - //System.out.println("typing " + tree);//DEBUG + //System.out.println("typing "+tree);//DEBUG } - val tree1 = if (tree.tpe != null) tree else typed1(tree, mode, pt); - //System.out.println("typed " + tree1 + ":" + tree1.tpe);//debug - val result = if (tree1.isEmpty) tree1 else adapt(tree1, mode, pt); - //System.out.println("adapted " + tree1 + ":" + tree1.tpe + " to " + pt);//debug + val tree1 = if (tree.tpe != null) tree else typed1(tree, mode, pt) + //System.out.println("typed "+tree1+":"+tree1.tpe);//debug + val result = if (tree1.isEmpty) tree1 else adapt(tree1, mode, pt) + //System.out.println("adapted "+tree1+":"+tree1.tpe+" to "+pt);//debug result } catch { case ex: TypeError => - //System.out.println("caught " + ex + " in typed");//DEBUG - reportTypeError(tree.pos, ex); + //System.out.println("caught "+ex+" in typed");//DEBUG + reportTypeError(tree.pos, ex) setError(tree) case ex: Throwable => if (settings.debug.value) - System.out.println("exception when typing " + tree + ", pt = " + pt); + System.out.println("exception when typing "+tree+", pt = "+pt) throw(ex) } def atOwner(owner: Symbol): Typer = - new Typer(context.make(context.tree, owner)); + new Typer(context.make(context.tree, owner)) def atOwner(tree: Tree, owner: Symbol): Typer = - new Typer(context.make(tree, owner)); + new Typer(context.make(tree, owner)) /** Types expression or definition `tree' */ def typed(tree: Tree): Tree = - typed(tree, EXPRmode, WildcardType); + typed(tree, EXPRmode, WildcardType) /** Types expression `tree' with given prototype `pt' */ def typed(tree: Tree, pt: Type): Tree = - typed(tree, EXPRmode, pt); + typed(tree, EXPRmode, pt) /** Types qualifier `tree' of a select node. E.g. is tree occurs in acontext like `tree.m'. */ def typedQualifier(tree: Tree): Tree = - typed(tree, EXPRmode | QUALmode | POLYmode, WildcardType); + typed(tree, EXPRmode | QUALmode | POLYmode, WildcardType) /** Types function part of an application */ def typedOperator(tree: Tree): Tree = - typed(tree, EXPRmode | FUNmode | POLYmode | TAPPmode, WildcardType); + typed(tree, EXPRmode | FUNmode | POLYmode | TAPPmode, WildcardType) /** Types a pattern with prototype `pt' */ def typedPattern(tree: Tree, pt: Type): Tree = - typed(tree, PATTERNmode, pt); + typed(tree, PATTERNmode, pt) /** Types a (fully parameterized) type tree */ def typedType(tree: Tree): Tree = - typed(tree, TYPEmode, WildcardType); + typed(tree, TYPEmode, WildcardType) /** Types a type constructor tree used in a new or supertype */ def typedTypeConstructor(tree: Tree): Tree = { - val result = typed(tree, TYPEmode | FUNmode, WildcardType); + val result = typed(tree, TYPEmode | FUNmode, WildcardType) if (!phase.erasedTypes && result.tpe.isInstanceOf[TypeRef] && !result.tpe.prefix.isStable) - error(tree.pos, result.tpe.prefix.toString() + " is not a legal prefix for a constructor"); + error(tree.pos, ""+result.tpe.prefix+" is not a legal prefix for a constructor") result } def computeType(tree: Tree): Type = { - val tree1 = typed(tree); - transformed(tree) = tree1; + val tree1 = typed(tree) + transformed(tree) = tree1 tree1.tpe } @@ -1494,54 +1501,54 @@ import scala.collection.mutable.{HashMap, ListBuffer} private def typedImplicit(pos: int, info: ImplicitInfo, pt: Type, local: boolean): Tree = if (isCompatible(depoly(info.tpe), pt)) { - var tree: Tree = EmptyTree; + var tree: Tree = EmptyTree def fail(reason: String, sym1: Symbol, sym2: Symbol): Tree = { if (settings.debug.value) - log(tree.toString() + " is not a valid implicit value because:\n" + reason + - sym1 + " " + sym2); + log(""+tree+" is not a valid implicit value because:\n"+reason + + sym1+" "+sym2); EmptyTree } try { - tree = Ident(info.name) setPos pos; - if (!local) tree setSymbol info.sym; - tree = typed1(tree, EXPRmode, pt); + tree = Ident(info.name) setPos pos + if (!local) tree setSymbol info.sym + tree = typed1(tree, EXPRmode, pt) if (settings.debug.value) - log("typed implicit " + tree + ":" + tree.tpe + ", pt = " + pt);//debug - val tree1 = adapt(tree, EXPRmode, pt); + log("typed implicit "+tree+":"+tree.tpe+", pt = "+pt);//debug + val tree1 = adapt(tree, EXPRmode, pt) if (settings.debug.value) - log("adapted implicit " + tree.symbol + ":" + tree1.tpe + " to " + pt);//debug + log("adapted implicit "+tree.symbol+":"+tree1.tpe+" to "+pt);//debug if (tree1.tpe != ErrorType && info.sym == tree.symbol) tree1 else fail("syms differ: ", tree.symbol, info.sym) } catch { case ex: TypeError => fail(ex.getMessage(), NoSymbol, NoSymbol) } - } else EmptyTree; + } else EmptyTree private def inferImplicit(pos: int, pt: Type, isView: boolean, reportAmbiguous: boolean): Tree = { - if (util.Statistics.enabled) implcnt = implcnt + 1; - val startTime = if (util.Statistics.enabled) System.currentTimeMillis() else 0l; + if (util.Statistics.enabled) implcnt = implcnt + 1 + val startTime = if (util.Statistics.enabled) System.currentTimeMillis() else 0l def isBetter(sym1: Symbol, tpe1: Type, sym2: Symbol, tpe2: Type): boolean = ( sym2.isError || (sym1.owner != sym2.owner) && (sym1.owner isSubClass sym2.owner) && (tpe1 matches tpe2) - ); - val tc = newTyper(context.makeImplicit(reportAmbiguous)); + ) + val tc = newTyper(context.makeImplicit(reportAmbiguous)) def searchImplicit(implicitInfoss: List[List[ImplicitInfo]], local: boolean): Tree = { - var iss = implicitInfoss; - var tree: Tree = EmptyTree; + var iss = implicitInfoss + var tree: Tree = EmptyTree while (tree == EmptyTree && !iss.isEmpty) { - var is = iss.head; - iss = iss.tail; + var is = iss.head + iss = iss.tail while (!is.isEmpty) { - tree = tc.typedImplicit(pos, is.head, pt, local); - if (settings.debug.value) log("tested " + is.head.sym + is.head.sym.locationString + ":" + is.head.tpe + "=" + tree);//debug - val is0 = is; - is = is.tail; + tree = tc.typedImplicit(pos, is.head, pt, local) + if (settings.debug.value) log("tested "+is.head.sym + is.head.sym.locationString+":"+is.head.tpe+"="+tree);//debug + val is0 = is + is = is.tail if (tree != EmptyTree) { while (!is.isEmpty) { - val tree1 = tc.typedImplicit(pos, is.head, pt, local); + val tree1 = tc.typedImplicit(pos, is.head, pt, local) if (tree1 != EmptyTree) { if (isBetter(is.head.sym, tree1.tpe, is0.head.sym, tree.tpe)) tree = tree1 @@ -1549,13 +1556,13 @@ import scala.collection.mutable.{HashMap, ListBuffer} error( pos, "ambiguous implicit value:\n" + - " both " + is0.head.sym + is0.head.sym.locationString + " of type " + tree.tpe + - "\n and " + is.head.sym + is.head.sym.locationString + " of type " + tree1.tpe + + " both "+is0.head.sym + is0.head.sym.locationString+" of type "+tree.tpe + + "\n and "+is.head.sym + is.head.sym.locationString+" of type "+tree1.tpe + (if (isView) - "\n are possible conversion functions from " + - pt.typeArgs(0) + " to " + pt.typeArgs(1) + "\n are possible conversion functions from "+ + pt.typeArgs(0)+" to "+pt.typeArgs(1) else - "\n match expected type " + pt)); + "\n match expected type "+pt)) } is = is.tail } @@ -1566,27 +1573,27 @@ import scala.collection.mutable.{HashMap, ListBuffer} } def implicitsOfType(tp: Type): List[List[ImplicitInfo]] = { - val tp1 = if (isFunctionType(tp)) intersectionType(tp.typeArgs.reverse) else tp; - tp1.baseClasses map implicitsOfClass; + val tp1 = if (isFunctionType(tp)) intersectionType(tp.typeArgs.reverse) else tp + tp1.baseClasses map implicitsOfClass } def implicitsOfClass(clazz: Symbol): List[ImplicitInfo] = ( clazz.initialize.linkedModule.moduleClass.info.decls.toList.filter(.hasFlag(IMPLICIT)) map (sym => ImplicitInfo(sym.name, clazz.linkedModule.tpe.memberType(sym), sym)) - ); + ) - var tree = searchImplicit(context.implicitss, true); - if (tree == EmptyTree) tree = searchImplicit(implicitsOfType(pt.widen), false); - if (util.Statistics.enabled) impltime = impltime + System.currentTimeMillis() - startTime; + var tree = searchImplicit(context.implicitss, true) + if (tree == EmptyTree) tree = searchImplicit(implicitsOfType(pt.widen), false) + if (util.Statistics.enabled) impltime = impltime + System.currentTimeMillis() - startTime tree } def applyImplicitArgs(tree: Tree): Tree = tree.tpe match { case MethodType(formals, _) => def implicitArg(pt: Type) = { - val arg = inferImplicit(tree.pos, pt, false, true); + val arg = inferImplicit(tree.pos, pt, false, true) if (arg != EmptyTree) arg - else errorTree(tree, "no implicit argument matching parameter type " + pt + " was found.") + else errorTree(tree, "no implicit argument matching parameter type "+pt+" was found.") } Apply(tree, formals map implicitArg) setPos tree.pos }