Ver código fonte

Add throw location to srcMap. Closes #354.

Dmitry Panov 3 anos atrás
pai
commit
6b16cd3920
5 arquivos alterados com 30 adições e 2 exclusões
  1. 7 0
      compiler.go
  2. 1 1
      compiler_expr.go
  3. 5 1
      compiler_stmt.go
  4. 16 0
      compiler_test.go
  5. 1 0
      parser/statement.go

+ 7 - 0
compiler.go

@@ -384,6 +384,13 @@ func (p *Program) sourceOffset(pc int) int {
 	return 0
 }
 
+func (p *Program) addSrcMap(srcPos int) {
+	if len(p.srcMap) > 0 && p.srcMap[len(p.srcMap)-1].srcPos == srcPos {
+		return
+	}
+	p.srcMap = append(p.srcMap, srcMapItem{pc: len(p.code), srcPos: srcPos})
+}
+
 func (s *scope) lookupName(name unistring.String) (binding *binding, noDynamics bool) {
 	noDynamics = true
 	toStash := false

+ 1 - 1
compiler_expr.go

@@ -300,7 +300,7 @@ func (e *baseCompiledExpr) emitUnary(func(), func(), bool, bool) {
 
 func (e *baseCompiledExpr) addSrcMap() {
 	if e.offset >= 0 {
-		e.c.p.srcMap = append(e.c.p.srcMap, srcMapItem{pc: len(e.c.p.code), srcPos: e.offset})
+		e.c.p.addSrcMap(e.offset)
 	}
 }
 

+ 5 - 1
compiler_stmt.go

@@ -202,9 +202,13 @@ func (c *compiler) compileTryStatement(v *ast.TryStatement, needResult bool) {
 	c.leaveBlock()
 }
 
+func (c *compiler) addSrcMap(node ast.Node) {
+	c.p.addSrcMap(int(node.Idx0()) - 1)
+}
+
 func (c *compiler) compileThrowStatement(v *ast.ThrowStatement) {
-	//c.p.srcMap = append(c.p.srcMap, srcMapItem{pc: len(c.p.code), srcPos: int(v.Throw) - 1})
 	c.compileExpression(v.Argument).emitGetter(true)
+	c.addSrcMap(v)
 	c.emit(throw)
 }
 

+ 16 - 0
compiler_test.go

@@ -4515,6 +4515,22 @@ func TestSrcLocations(t *testing.T) {
 	testScriptWithTestLib(SCRIPT, _undefined, t)
 }
 
+func TestSrcLocationThrowLiteral(t *testing.T) {
+	vm := New()
+	_, err := vm.RunString(`
+	const z = 1;
+	throw "";
+	`)
+	if ex, ok := err.(*Exception); ok {
+		pos := ex.stack[0].Position()
+		if pos.Line != 3 {
+			t.Fatal(pos)
+		}
+	} else {
+		t.Fatal(err)
+	}
+}
+
 func TestBadObjectKey(t *testing.T) {
 	_, err := Compile("", "({!:0})", false)
 	if err == nil {

+ 1 - 0
parser/statement.go

@@ -269,6 +269,7 @@ func (self *_parser) parseThrowStatement() ast.Statement {
 	}
 
 	node := &ast.ThrowStatement{
+		Throw:    idx,
 		Argument: self.parseExpression(),
 	}