Start line:  
End line:  

Snippet Preview

Snippet HTML Code

Stack Overflow Questions
BEGIN LICENSE BLOCK ***** Version: EPL 1.0/GPL 2.0/LGPL 2.1 The contents of this file are subject to the Eclipse Public License Version 1.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.eclipse.org/legal/epl-v10.html Software distributed under the License is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License for the specific language governing rights and limitations under the License. Copyright (C) 2010 Charles O Nutter <headius@headius.com> Alternatively, the contents of this file may be used under the terms of either of the GNU General Public License Version 2 or later (the "GPL"), or the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), in which case the provisions of the GPL or the LGPL are applicable instead of those above. If you wish to allow use of your version of this file only under the terms of either the GPL or the LGPL, and not to allow others to use your version of this file under the terms of the EPL, indicate your decision by deleting the provisions above and replace them with the notice and other provisions required by the GPL or the LGPL. If you do not delete the provisions above, a recipient may use your version of this file under the terms of any one of the EPL, the GPL or the LGPL. END LICENSE BLOCK ***
 
 package org.jruby.ext.psych;
 
 import java.util.Map;
 
 import org.jruby.Ruby;
 import static org.jruby.ext.psych.PsychLibrary.YAMLEncoding.*;
 import static org.jruby.runtime.Helpers.invoke;
 
 public class PsychParser extends RubyObject {
 
     private static final Logger LOG = LoggerFactory.getLogger("PsychParser");
     
     public static void initPsychParser(Ruby runtimeRubyModule psych) {
         RubyClass psychParser = runtime.defineClassUnder("Parser"runtime.getObject(), new ObjectAllocator() {
             public IRubyObject allocate(Ruby runtimeRubyClass klazz) {
                 return new PsychParser(runtimeklazz);
             }
         }, psych);
 
         RubyKernel.require(runtime.getNil(),
                 runtime.newString("psych/syntax_error"), .);
         psychParser.defineConstant("ANY"runtime.newFixnum(.ordinal()));
         psychParser.defineConstant("UTF8"runtime.newFixnum(.ordinal()));
         psychParser.defineConstant("UTF16LE"runtime.newFixnum(.ordinal()));
         psychParser.defineConstant("UTF16BE"runtime.newFixnum(.ordinal()));
 
         psychParser.defineAnnotatedMethods(PsychParser.class);
     }
 
     public PsychParser(Ruby runtimeRubyClass klass) {
         super(runtimeklass);
     }
    public IRubyObject parse(ThreadContext contextIRubyObject yaml) {
        Ruby runtime = context.runtime;
        return parse(contextyamlruntime.getNil());
    }
    private IRubyObject stringOrNilFor(Ruby runtimeString valueboolean tainted) {
        if (value == nullreturn runtime.getNil(); // No need to taint nil
        return stringFor(runtimevaluetainted);
    }
    
    private RubyString stringFor(Ruby runtimeString valueboolean tainted) {
        Encoding encoding = runtime.getDefaultInternalEncoding();
        if (encoding == null) {
            encoding = .;
        }
        Charset charset = .;
        if (encoding.getCharset() != null) {
            charset = encoding.getCharset();
        }
        ByteList bytes = new ByteList(value.getBytes(charset), encoding);
        RubyString string = RubyString.newString(runtimebytes);
        
        string.setTaint(tainted);
        
        return string;
    }
    
    private StreamReader readerFor(ThreadContext contextIRubyObject yaml) {
        Ruby runtime = context.runtime;
        if (yaml instanceof RubyString) {
            ByteList byteList = ((RubyString)yaml).getByteList();
            ByteArrayInputStream bais = new ByteArrayInputStream(byteList.getUnsafeBytes(), byteList.getBegin(), byteList.getRealSize());
            Charset charset = byteList.getEncoding().getCharset();
            if (charset == nullcharset = Charset.defaultCharset();
            InputStreamReader isr = new InputStreamReader(baischarset);
            return new StreamReader(isr);
        }
        // fall back on IOInputStream, using default charset
        if (yaml.respondsTo("read")) {
            Charset charset = (yaml instanceof RubyIO)
                ? ((RubyIO)yaml).getReadEncoding().getCharset()
                : Charset.defaultCharset();
            return new StreamReader(new InputStreamReader(new IOInputStream(yaml), charset));
        } else {
            throw runtime.newTypeError(yamlruntime.getIO());
        }
    }
    public IRubyObject parse(ThreadContext contextIRubyObject yamlIRubyObject path) {
        Ruby runtime = context.runtime;
        boolean tainted = yaml.isTaint() || yaml instanceof RubyIO;
        try {
             = new ParserImpl(readerFor(contextyaml));
            if (path.isNil() && yaml.respondsTo("path")) {
                path = yaml.callMethod(context"path");
            }
            IRubyObject handler = getInstanceVariable("@handler");
            while (true) {
                 = .getEvent();
                // FIXME: Event should expose a getID, so it can be switched
                if (.is(.)) {
                    invoke(contexthandler"start_stream"runtime.newFixnum(.ordinal()));
                } else if (.is(.)) {
                    handleDocumentStart(context, (DocumentStartEventtaintedhandler);
                } else if (.is(.)) {
                    IRubyObject notExplicit = runtime.newBoolean(!((DocumentEndEvent).getExplicit());
                    
                    invoke(contexthandler"end_document"notExplicit);
                } else if (.is(.)) {
                    IRubyObject alias = stringOrNilFor(runtime, ((AliasEvent)).getAnchor(), tainted);
                    invoke(contexthandler"alias"alias);
                } else if (.is(.)) {
                    handleScalar(context, (ScalarEventtaintedhandler);
                } else if (.is(.)) {
                    handleSequenceStart(context,(SequenceStartEventtaintedhandler);
                } else if (.is(.)) {
                    invoke(contexthandler"end_sequence");
                } else if (.is(.)) {
                    handleMappingStart(context, (MappingStartEventtaintedhandler);
                } else if (.is(.)) {
                    invoke(contexthandler"end_mapping");
                } else if (.is(.)) {
                    invoke(contexthandler"end_stream");
                    
                    break;
                }
            }
        } catch (ParserException pe) {
             = null;
            raiseParserException(contextyamlpepath);
        } catch (ScannerException se) {
             = null;
            StringBuilder message = new StringBuilder("syntax error");
            if (se.getProblemMark() != null) {
                message.append(se.getProblemMark().toString());
            }
            raiseParserException(contextyamlsepath);
        } catch (ReaderException re) {
             = null;
            raiseParserException(contextyamlrepath);
        } catch (Throwable t) {
            Helpers.throwException(t);
            return this;
        }
        return this;
    }
    
    private void handleDocumentStart(ThreadContext contextDocumentStartEvent dseboolean taintedIRubyObject handler) {
        Ruby runtime = context.runtime;
        DumperOptions.Version _version = dse.getVersion();
        Integer[] versionInts = _version == null ? null : _version.getArray();
        IRubyObject version = versionInts == null ?
            RubyArray.newArray(runtime) :
            RubyArray.newArray(runtimeruntime.newFixnum(versionInts[0]), runtime.newFixnum(versionInts[1]));
        
        Map<StringStringtagsMap = dse.getTags();
        RubyArray tags = RubyArray.newArray(runtime);
        if (tagsMap != null && tagsMap.size() > 0) {
            for (Map.Entry<StringStringtag : tagsMap.entrySet()) {
                IRubyObject key   = stringFor(runtimetag.getKey(), tainted);
                IRubyObject value = stringFor(runtimetag.getValue(), tainted);
                tags.append(RubyArray.newArray(runtimekeyvalue));
            }
        }
        IRubyObject notExplicit = runtime.newBoolean(!dse.getExplicit());
        invoke(contexthandler"start_document"versiontagsnotExplicit);
    }
    
    private void handleMappingStart(ThreadContext contextMappingStartEvent mseboolean taintedIRubyObject handler) {
        Ruby runtime = context.runtime;
        IRubyObject anchor = stringOrNilFor(runtimemse.getAnchor(), tainted);
        IRubyObject tag = stringOrNilFor(runtimemse.getTag(), tainted);
        IRubyObject implicit = runtime.newBoolean(mse.getImplicit());
        IRubyObject style = runtime.newFixnum(translateFlowStyle(mse.getFlowStyle()));
        invoke(contexthandler"start_mapping"anchortagimplicitstyle);
    }
        
    private void handleScalar(ThreadContext contextScalarEvent seboolean taintedIRubyObject handler) {
        Ruby runtime = context.runtime;
        IRubyObject anchor = stringOrNilFor(runtimese.getAnchor(), tainted);
        IRubyObject tag = stringOrNilFor(runtimese.getTag(), tainted);
        IRubyObject plain_implicit = runtime.newBoolean(se.getImplicit().canOmitTagInPlainScalar());
        IRubyObject quoted_implicit = runtime.newBoolean(se.getImplicit().canOmitTagInNonPlainScalar());
        IRubyObject style = runtime.newFixnum(translateStyle(se.getStyle()));
        IRubyObject val = stringFor(runtimese.getValue(), tainted);
        invoke(contexthandler"scalar"valanchortagplain_implicit,
                quoted_implicitstyle);
    }
    
    private void handleSequenceStart(ThreadContext contextSequenceStartEvent sseboolean taintedIRubyObject handler) {
        Ruby runtime = context.runtime;
        IRubyObject anchor = stringOrNilFor(runtimesse.getAnchor(), tainted);
        IRubyObject tag = stringOrNilFor(runtimesse.getTag(), tainted);
        IRubyObject implicit = runtime.newBoolean(sse.getImplicit());
        IRubyObject style = runtime.newFixnum(translateFlowStyle(sse.getFlowStyle()));
        invoke(contexthandler"start_sequence"anchortagimplicitstyle);
    }
    private static void raiseParserException(ThreadContext contextIRubyObject yamlReaderException reIRubyObject rbPath) {
        Ruby runtime;
        RubyClass se;
        IRubyObject exception;
        runtime = context.runtime;
        se = (RubyClass)runtime.getModule("Psych").getConstant("SyntaxError");
        exception = se.newInstance(context,
                new IRubyObject[] {
                    rbPath,
                    runtime.newFixnum(0),
                    runtime.newFixnum(0),
                    runtime.newFixnum(re.getPosition()),
                    (null == re.getName() ? runtime.getNil() : runtime.newString(re.getName())),
                    (null == re.toString() ? runtime.getNil() : runtime.newString(re.toString()))
                },
                .);
        RubyKernel.raise(contextruntime.getKernel(), new IRubyObject[] { exception }, .);
    }
    private static void raiseParserException(ThreadContext contextIRubyObject yamlMarkedYAMLException myeIRubyObject rbPath) {
        Ruby runtime;
        Mark mark;
        RubyClass se;
        IRubyObject exception;
        runtime = context.runtime;
        se = (RubyClass)runtime.getModule("Psych").getConstant("SyntaxError");
        mark = mye.getProblemMark();
        exception = se.newInstance(context,
                new IRubyObject[] {
                    rbPath,
                    runtime.newFixnum(mark.getLine() + 1),
                    runtime.newFixnum(mark.getColumn() + 1),
                    runtime.newFixnum(mark.getIndex()),
                    (null == mye.getProblem() ? runtime.getNil() : runtime.newString(mye.getProblem())),
                    (null == mye.getContext() ? runtime.getNil() : runtime.newString(mye.getContext()))
                },
                .);
        RubyKernel.raise(contextruntime.getKernel(), new IRubyObject[] { exception }, .);
    }
    private static int translateStyle(Character style) {
        if (style == nullreturn 0; // any
        switch (style) {
            case 0: return 1; // plain
            case '\''return 2; // single-quoted
            case '"'return 3; // double-quoted
            case '|'return 4; // literal
            case '>'return 5; // folded
            defaultreturn 0; // any
        }
    }
    
    private static int translateFlowStyle(Boolean flowStyle) {
        if (flowStyle == nullreturn 0; // any
        if (flowStylereturn 2;
        return 1;
    }
    public IRubyObject mark(ThreadContext context) {
        Ruby runtime = context.runtime;
        Event event = null;
        if ( != null) {
            event = .peekEvent();
            if (event == nullevent = this.;
        }
        if (event == null) {
            return ((RubyClass)context.runtime.getClassFromPath("Psych::Parser::Mark")).newInstance(
                    context,
                    runtime.newFixnum(0),
                    runtime.newFixnum(0),
                    runtime.newFixnum(0),
                    .
            );
        }
        Mark mark = event.getStartMark();
        return ((RubyClass)context.runtime.getClassFromPath("Psych::Parser::Mark")).newInstance(
                context,
                runtime.newFixnum(mark.getIndex()),
                runtime.newFixnum(mark.getLine()),
                runtime.newFixnum(mark.getColumn()),
                .
        );
    }
    private Parser parser;
    private Event event;
New to GrepCode? Check out our FAQ X