Esempio n. 1
0
// FormatMappedECMASource parses and formats the given ECMAScript source code.
func FormatMappedECMASource(source string, sm *sourcemap.SourceMap) (string, *sourcemap.SourceMap, error) {
	// Parse the ES source.
	program, err := parser.ParseFile(nil, "", source, 0)
	if err != nil {
		return "", nil, err
	}

	// Reformat nicely.
	formatter := &sourceFormatter{
		file: program.File,

		indentationLevel: 0,
		hasNewline:       true,

		newlineCount:     0,
		charactersOnLine: 0,

		existingSourceMap:  sm,
		formattedSourceMap: sourcemap.NewSourceMap(sm.GeneratedFilePath(), sm.SourceRoot()),

		positionMapper: compilercommon.CreateSourcePositionMapper([]byte(source)),
	}

	formatter.formatProgram(program)
	return formatter.buf.String(), formatter.formattedSourceMap, nil
}
Esempio n. 2
0
func (runtime *_runtime) cmpl_parse(filename string, src interface{}) (*_nodeProgram, error) {
	program, err := parser.ParseFile(nil, filename, src, 0)
	if err != nil {
		return nil, err
	}
	return cmpl_parse(program), nil
}
Esempio n. 3
0
func Test_cmpl(t *testing.T) {
	tt(t, func() {
		vm := New()

		test := func(src string, expect ...interface{}) {
			program, err := parser.ParseFile(nil, "", src, 0)
			is(err, nil)
			{
				program := cmpl_parse(program)
				value := vm.runtime.cmpl_evaluate_nodeProgram(program, false)
				if len(expect) > 0 {
					is(value, expect[0])
				}
			}
		}

		test(``, Value{})

		test(`var abc = 1; abc;`, 1)

		test(`var abc = 1 + 1; abc;`, 2)

		test(`1 + 2;`, 3)
	})
}
Esempio n. 4
0
func (r *jsRouter) IsValid(routedef string) bool {
	routedef = r.sanitizeRoute(routedef)

	//validate routedef is valid
	if _, err := parser.ParseFile(nil, "", routedef, 0); err != nil {
		log.WithFields(log.Fields{"Error": err, "RouteDefinition": routedef}).Error("Error parsing route definition in javascript.")
		return false
	}
	log.WithFields(log.Fields{"RouteDef": routedef}).Debug("Route valid for javascript router.")
	return true
}
Esempio n. 5
0
// Run performs extension tests from the file specified at runner's creation
func (runner *TestRunner) Run() map[string]error {
	src, err := ioutil.ReadFile(runner.testFileName)
	if err != nil {
		return map[string]error{
			GeneralError: fmt.Errorf("Failed to read file '%s': %s", runner.testFileName, err.Error()),
		}
	}

	program, err := parser.ParseFile(nil, runner.testFileName, src, 0)
	if err != nil {
		return map[string]error{
			GeneralError: fmt.Errorf("Failed to parse file '%s': %s", runner.testFileName, err.Error()),
		}
	}
	tests := []string{}
	for _, declaration := range program.DeclarationList {
		if functionDeclaration, ok := declaration.(*ast.FunctionDeclaration); ok {
			name := functionDeclaration.Function.Name.Name
			switch {
			case setUpPattern.MatchString(name):
				runner.setUp = true
			case tearDownPattern.MatchString(name):
				runner.tearDown = true
			case testPattern.MatchString(name):
				tests = append(tests, name)
			}
		}
	}

	env := NewEnvironment(runner.testFileName, src)

	directory, _ := os.Getwd()
	if err := os.Chdir(filepath.Dir(runner.testFileName)); err != nil {
		return map[string]error{
			GeneralError: fmt.Errorf("Failed to change directory to '%s': %s",
				filepath.Dir(runner.testFileName),
				err.Error()),
		}
	}
	defer os.Chdir(directory)

	errors := map[string]error{}
	for _, test := range tests {
		errors[test] = runner.runTest(test, env)
		if _, ok := errors[test].(metaError); ok {
			return map[string]error{
				GeneralError: errors[test],
			}
		}
	}

	return errors
}
Esempio n. 6
0
func getFunctionLiteral(name string, script string) (string, error) {
	program, err := parser.ParseFile(nil, "", script, 0)
	if err != nil {
		return "", err
	}
	for _, node := range program.Body {
		if stmt, ok := node.(*ast.ExpressionStatement); ok {
			if exp, ok := stmt.Expression.(*ast.AssignExpression); ok {
				if left, ok := exp.Left.(*ast.Identifier); ok {
					if _, ok := exp.Right.(*ast.FunctionLiteral); ok {
						if left.Name == name {
							return script[stmt.Idx0()-1 : stmt.Idx1()], nil
						}
					}
				}
			}
		}
	}
	return fmt.Sprintf("%s = function() {};", name), nil
}
Esempio n. 7
0
func TestParse_cmpl(t *testing.T) {
	tt(t, func() {

		test := func(src string) {
			program, err := parser.ParseFile(nil, "", src, 0)
			is(err, nil)
			is(cmpl_parse(program), "!=", nil)
		}

		test(``)

		test(`var abc = 1; abc;`)

		test(`
            function abc() {
                return;
            }
        `)
	})
}
Esempio n. 8
0
func test(filename string) error {
	script, err := ioutil.ReadFile(filename)
	if err != nil {
		return err
	}

	if !*flag_report {
		fmt.Fprintln(os.Stdout, filename, len(script))
	}

	parse := false
	option := target[filename]

	if option != "parse" {
		vm := otto.New()
		_, err = vm.Run(string(script))
		if err != nil {
			value := err.Error()
			switch {
			case match_ReferenceError_not_defined.MatchString(value):
			case match_TypeError_undefined.MatchString(value):
			case match_lookahead.MatchString(value):
			case match_backreference.MatchString(value):
			default:
				return err
			}
			parse = true
		}
	}

	if parse {
		_, err = parser.ParseFile(nil, filename, string(script), parser.IgnoreRegExpErrors)
		if err != nil {
			return err
		}
		target[filename] = "parse"
	}

	return nil
}
Esempio n. 9
0
func (eng *ScriptEngine) GetVar(name, script string) (interface{}, error) {
	program, err := parser.ParseFile(nil, "", script, 0)
	if err != nil {
		return nil, err
	}
	for _, node := range program.Body {
		if stmt, ok := node.(*ast.VariableStatement); ok {
			if len(stmt.List) == 0 {
				continue
			}
			if exp, ok := stmt.List[0].(*ast.VariableExpression); ok {
				if literal, ok := exp.Initializer.(*ast.NumberLiteral); ok {
					return literal.Value, nil
				}
				if literal, ok := exp.Initializer.(*ast.StringLiteral); ok {
					return literal.Value, nil
				}
			}
		}
	}
	return nil, nil
}
Esempio n. 10
0
func (runtime *_runtime) parse(filename string, src interface{}) (*ast.Program, error) {
	return parser.ParseFile(nil, filename, src, 0)
}
Esempio n. 11
0
func TestOttoRun(t *testing.T) {
	tt(t, func() {
		vm := New()

		program, err := parser.ParseFile(nil, "", "", 0)
		is(err, nil)
		value, err := vm.Run(program)
		is(err, nil)
		is(value, UndefinedValue())

		program, err = parser.ParseFile(nil, "", "2 + 2", 0)
		is(err, nil)
		value, err = vm.Run(program)
		is(err, nil)
		is(value, 4)
		value, err = vm.Run(program)
		is(err, nil)
		is(value, 4)

		program, err = parser.ParseFile(nil, "", "var abc; if (!abc) abc = 0; abc += 2; abc;", 0)
		value, err = vm.Run(program)
		is(err, nil)
		is(value, 2)
		value, err = vm.Run(program)
		is(err, nil)
		is(value, 4)
		value, err = vm.Run(program)
		is(err, nil)
		is(value, 6)

		{
			src := []byte("var abc; if (!abc) abc = 0; abc += 2; abc;")
			value, err = vm.Run(src)
			is(err, nil)
			is(value, 8)

			value, err = vm.Run(bytes.NewBuffer(src))
			is(err, nil)
			is(value, 10)

			value, err = vm.Run(io.Reader(bytes.NewBuffer(src)))
			is(err, nil)
			is(value, 12)
		}

		{
			script, err := vm.Compile("", `var abc; if (!abc) abc = 0; abc += 2; abc;`)
			is(err, nil)

			value, err = vm.Run(script)
			is(err, nil)
			is(value, 14)

			value, err = vm.Run(script)
			is(err, nil)
			is(value, 16)

			is(script.String(), "// \nvar abc; if (!abc) abc = 0; abc += 2; abc;")
		}
	})
}
Esempio n. 12
0
// RunWithPromptAndPrelude runs a REPL with the given prompt and prelude.
func RunWithPromptAndPrelude(l *loop.Loop, prompt, prelude string) error {
	if prompt == "" {
		prompt = ">"
	}

	prompt = strings.Trim(prompt, " ")
	prompt += " "

	rl, err := readline.New(prompt)
	if err != nil {
		return err
	}

	l.VM().Set("console", map[string]interface{}{
		"log": func(c otto.FunctionCall) otto.Value {
			s := make([]string, len(c.ArgumentList))
			for i := 0; i < len(c.ArgumentList); i++ {
				s[i] = c.Argument(i).String()
			}

			rl.Stdout().Write([]byte(strings.Join(s, " ") + "\n"))
			rl.Refresh()

			return otto.UndefinedValue()
		},
		"warn": func(c otto.FunctionCall) otto.Value {
			s := make([]string, len(c.ArgumentList))
			for i := 0; i < len(c.ArgumentList); i++ {
				s[i] = c.Argument(i).String()
			}

			rl.Stderr().Write([]byte(strings.Join(s, " ") + "\n"))
			rl.Refresh()

			return otto.UndefinedValue()
		},
	})

	if prelude != "" {
		if _, err := io.Copy(rl.Stderr(), strings.NewReader(prelude+"\n")); err != nil {
			return err
		}

		rl.Refresh()
	}

	var d []string

	for {
		ll, err := rl.Readline()
		if err != nil {
			if err == readline.ErrInterrupt {
				if d != nil {
					d = nil

					rl.SetPrompt(prompt)
					rl.Refresh()

					continue
				}

				break
			}

			return err
		}

		if len(d) == 0 && ll == "" {
			continue
		}

		d = append(d, ll)
		s := strings.Join(d, "\n")

		if _, err := parser.ParseFile(nil, "repl", s, 0); err != nil {
			rl.SetPrompt(strings.Repeat(" ", len(prompt)))
		} else {
			rl.SetPrompt(prompt)

			d = nil

			t := looptask.NewEvalTask(s)
			// don't report errors to the loop - this lets us handle them and
			// resume normal operation
			t.SoftError = true
			l.Add(t)
			l.Ready(t)

			v, err := <-t.Value, <-t.Error
			if err != nil {
				if oerr, ok := err.(*otto.Error); ok {
					io.Copy(rl.Stdout(), strings.NewReader(oerr.String()))
				} else {
					io.Copy(rl.Stdout(), strings.NewReader(err.Error()))
				}
			} else {
				f, err := format(v, 80, 2, 5)
				if err != nil {
					panic(err)
				}

				rl.Stdout().Write([]byte(f + "\n"))
			}
		}

		rl.Refresh()
	}

	return rl.Close()
}
Esempio n. 13
0
func (eng *ScriptEngine) Validate(script string) error {
	_, err := parser.ParseFile(nil, "", script, 0)
	return err
}