Esempio n. 1
0
// ParseFile parses the source code of a single JavaScript/ECMAScript source file and returns
// the corresponding ast.Program node.
//
// If fileSet == nil, ParseFile parses source without a FileSet.
// If fileSet != nil, ParseFile first adds filename and src to fileSet.
//
// The filename argument is optional and is used for labelling errors, etc.
//
// src may be a string, a byte slice, a bytes.Buffer, or an io.Reader, but it MUST always be in UTF-8.
//
//      // Parse some JavaScript, yielding a *ast.Program and/or an ErrorList
//      program, err := parser.ParseFile(nil, "", `if (abc > 1) {}`, 0)
//
func ParseFile(fileSet *file.FileSet, filename string, src interface{}, mode Mode) (*ast.Program, error) {
	str, err := ReadSource(filename, src)
	if err != nil {
		return nil, err
	}
	{
		str := string(str)

		base := 1
		if fileSet != nil {
			base = fileSet.AddFile(filename, str)
		}

		parser := _newParser(filename, str, base)
		parser.mode = mode
		return parser.parse()
	}
}
Esempio n. 2
0
func ParseFileWithSourceMap(fileSet *file.FileSet, filename string, javascriptSource, sourcemapSource interface{}, mode Mode) (*ast.Program, error) {
	src, err := ReadSource(filename, javascriptSource)
	if err != nil {
		return nil, err
	}

	if sourcemapSource == nil {
		lines := bytes.Split(src, []byte("\n"))
		lastLine := lines[len(lines)-1]
		if bytes.HasPrefix(lastLine, []byte("//# sourceMappingURL=data:application/json")) {
			bits := bytes.SplitN(lastLine, []byte(","), 2)
			if len(bits) == 2 {
				if d, err := base64.StdEncoding.DecodeString(string(bits[1])); err == nil {
					sourcemapSource = d
				}
			}
		}
	}

	sm, err := ReadSourceMap(filename, sourcemapSource)
	if err != nil {
		return nil, err
	}

	base := 1
	if fileSet != nil {
		base = fileSet.AddFile(filename, string(src))
	}

	parser := _newParser(filename, string(src), base, sm)
	parser.mode = mode
	program, err := parser.parse()
	program.Comments = parser.comments.CommentMap

	return program, err
}