1// Copyright 2017 The Bazel Authors. All rights reserved. 2// Use of this source code is governed by a BSD-style 3// license that can be found in the LICENSE file. 4 5// The skylark command interprets a Skylark file. 6// With no arguments, it starts a read-eval-print loop (REPL). 7package main 8 9import ( 10 "flag" 11 "fmt" 12 "log" 13 "os" 14 "runtime/pprof" 15 "sort" 16 "strings" 17 18 "github.com/google/skylark" 19 "github.com/google/skylark/repl" 20 "github.com/google/skylark/resolve" 21) 22 23// flags 24var ( 25 cpuprofile = flag.String("cpuprofile", "", "gather CPU profile in this file") 26 showenv = flag.Bool("showenv", false, "on success, print final global environment") 27) 28 29// non-standard dialect flags 30func init() { 31 flag.BoolVar(&resolve.AllowFloat, "fp", resolve.AllowFloat, "allow floating-point numbers") 32 flag.BoolVar(&resolve.AllowSet, "set", resolve.AllowSet, "allow set data type") 33 flag.BoolVar(&resolve.AllowLambda, "lambda", resolve.AllowLambda, "allow lambda expressions") 34 flag.BoolVar(&resolve.AllowNestedDef, "nesteddef", resolve.AllowNestedDef, "allow nested def statements") 35 flag.BoolVar(&resolve.AllowBitwise, "bitwise", resolve.AllowBitwise, "allow bitwise operations (&, |, ^, ~, <<, and >>)") 36} 37 38func main() { 39 log.SetPrefix("skylark: ") 40 log.SetFlags(0) 41 flag.Parse() 42 43 if *cpuprofile != "" { 44 f, err := os.Create(*cpuprofile) 45 if err != nil { 46 log.Fatal(err) 47 } 48 if err := pprof.StartCPUProfile(f); err != nil { 49 log.Fatal(err) 50 } 51 defer pprof.StopCPUProfile() 52 } 53 54 thread := &skylark.Thread{Load: repl.MakeLoad()} 55 globals := make(skylark.StringDict) 56 57 switch len(flag.Args()) { 58 case 0: 59 fmt.Println("Welcome to Skylark (github.com/google/skylark)") 60 repl.REPL(thread, globals) 61 case 1: 62 // Execute specified file. 63 filename := flag.Args()[0] 64 var err error 65 globals, err = skylark.ExecFile(thread, filename, nil, nil) 66 if err != nil { 67 repl.PrintError(err) 68 os.Exit(1) 69 } 70 default: 71 log.Fatal("want at most one Skylark file name") 72 } 73 74 // Print the global environment. 75 if *showenv { 76 var names []string 77 for name := range globals { 78 if !strings.HasPrefix(name, "_") { 79 names = append(names, name) 80 } 81 } 82 sort.Strings(names) 83 for _, name := range names { 84 fmt.Fprintf(os.Stderr, "%s = %s\n", name, globals[name]) 85 } 86 } 87} 88