pax_global_header 0000666 0000000 0000000 00000000064 11233025100 0014475 g ustar 00root root 0000000 0000000 52 comment=157cf1334ffa1834a00aec3489560cb79f9c650f
yecht-0.0.2/ 0000775 0000000 0000000 00000000000 11233025100 0012610 5 ustar 00root root 0000000 0000000 yecht-0.0.2/.gitignore 0000664 0000000 0000000 00000000063 11233025100 0014577 0 ustar 00root root 0000000 0000000 build
rels
prj.el
lib/yecht-*.jar
build.properties
yecht-0.0.2/TIMINGS 0000664 0000000 0000000 00000013402 11233025100 0013645 0 ustar 00root root 0000000 0000000 Syck
scanning ../jruby_newyaml/bench/big_yaml.yml 10000 times took 13959ms
parsing ../jruby_newyaml/bench/big_yaml.yml 10000 times took 16101ms
JvYAMLb
scanning ../jruby_newyaml/bench/big_yaml.yml 10000 times took 5325ms
parsing ../jruby_newyaml/bench/big_yaml.yml 10000 times took 15794ms
Yecht - Original
scanning ../jruby_newyaml/bench/big_yaml.yml 10000 times took 93658ms
parsing ../jruby_newyaml/bench/big_yaml.yml 10000 times took 117213ms
Yecht - Fixed scanner
scanning ../jruby_newyaml/bench/big_yaml.yml 10000 times took 12207ms
parsing ../jruby_newyaml/bench/big_yaml.yml 10000 times took 31280ms
Yecht - Fixed parser (switched to Jay)
scanning ../jruby_newyaml/bench/big_yaml.yml 10000 times took 12960ms
parsing ../jruby_newyaml/bench/big_yaml.yml 10000 times took 15411ms
Yecht - Optimized parser (Tom's fixes from JRuby) (no difference, really)
scanning ../jruby_newyaml/bench/big_yaml.yml 10000 times took 12951ms
parsing ../jruby_newyaml/bench/big_yaml.yml 10000 times took 16298ms
Yecht - Handwritten document-section in Scanner
scanning ../jruby_newyaml/bench/big_yaml.yml 10000 times took 11226ms
parsing ../jruby_newyaml/bench/big_yaml.yml 10000 times took 14059ms
Yecht - Handwritten plain-section in Scanner
scanning ../jruby_newyaml/bench/big_yaml.yml 10000 times took 9581ms
parsing ../jruby_newyaml/bench/big_yaml.yml 10000 times took 12838ms
Yecht - Rewrite the implicit-scanner
scanning ../jruby_newyaml/bench/big_yaml.yml 10000 times took 4804ms
parsing ../jruby_newyaml/bench/big_yaml.yml 10000 times took 8424ms
MRI
user system total real
1k small parse 0.090000 0.000000 0.090000 ( 0.104769)
1k small loads 0.060000 0.010000 0.070000 ( 0.072829)
1k small dumps 0.370000 0.000000 0.370000 ( 0.396296)
1k small roundtrip 0.410000 0.010000 0.420000 ( 0.429103)
1k big parse 4.440000 0.050000 4.490000 ( 4.615258)
1k big loads 1.920000 0.020000 1.940000 ( 1.991891)
1k big dumps 22.170000 0.270000 22.440000 ( 23.361924)
1k big roundtrip 24.180000 0.300000 24.480000 ( 25.483744)
JRuby trunk
user system total real
1k small parse 0.327000 0.000000 0.327000 ( 0.326000)
1k small loads 0.100000 0.000000 0.100000 ( 0.099000)
1k small dumps 0.202000 0.000000 0.202000 ( 0.202000)
1k small roundtrip 0.322000 0.000000 0.322000 ( 0.322000)
1k big parse 16.259000 0.000000 16.259000 ( 16.259000)
1k big loads 1.752000 0.000000 1.752000 ( 1.752000)
1k big dumps 10.333000 0.000000 10.333000 ( 10.333000)
1k big roundtrip 13.886000 0.000000 13.886000 ( 13.886000)
JRuby with old Yecht
user system total real
1k small parse 0.380000 0.000000 0.380000 ( 0.380000)
1k small loads 0.284000 0.000000 0.284000 ( 0.284000)
1k small dumps 0.347000 0.000000 0.347000 ( 0.347000)
1k small roundtrip 0.582000 0.000000 0.582000 ( 0.582000)
1k big parse 23.629000 0.000000 23.629000 ( 23.630000)
1k big loads 14.802000 0.000000 14.802000 ( 14.802000)
1k big dumps 19.526000 0.000000 19.526000 ( 19.526000)
1k big roundtrip 36.202000 0.000000 36.202000 ( 36.202000)
JRuby with new Yecht
user system total real
1k small parse 0.165000 0.000000 0.165000 ( 0.165000)
1k small loads 0.089000 0.000000 0.089000 ( 0.089000)
1k small dumps 0.299000 0.000000 0.299000 ( 0.299000)
1k small roundtrip 0.386000 0.000000 0.386000 ( 0.386000)
1k big parse 10.558000 0.000000 10.558000 ( 10.558000)
1k big loads 2.678000 0.000000 2.678000 ( 2.678000)
1k big dumps 19.109000 0.000000 19.109000 ( 19.110000)
1k big roundtrip 23.039000 0.000000 23.039000 ( 23.039000)
JRuby with some slight optimizations to Yecht
user system total real
1k small parse 0.188000 0.000000 0.188000 ( 0.188000)
1k small loads 0.076000 0.000000 0.076000 ( 0.076000)
1k small dumps 0.323000 0.000000 0.323000 ( 0.323000)
1k small roundtrip 0.362000 0.000000 0.362000 ( 0.363000)
1k big parse 9.053000 0.000000 9.053000 ( 9.053000)
1k big loads 2.262000 0.000000 2.262000 ( 2.262000)
1k big dumps 18.551000 0.000000 18.551000 ( 18.551000)
1k big roundtrip 21.675000 0.000000 21.675000 ( 21.675000)
JRuby with some call site caching in Yecht
user system total real
1k small parse 0.142000 0.000000 0.142000 ( 0.142000)
1k small loads 0.076000 0.000000 0.076000 ( 0.076000)
1k small dumps 0.278000 0.000000 0.278000 ( 0.278000)
1k small roundtrip 0.346000 0.000000 0.346000 ( 0.346000)
1k big parse 9.042000 0.000000 9.042000 ( 9.042000)
1k big loads 2.200000 0.000000 2.200000 ( 2.200000)
1k big dumps 18.451000 0.000000 18.451000 ( 18.451000)
1k big roundtrip 22.087000 0.000000 22.087000 ( 22.087000)
yecht-0.0.2/build.xml 0000664 0000000 0000000 00000015061 11233025100 0014434 0 ustar 00root root 0000000 0000000
Yecht is a Syck port, a YAML 1.0 processor for Ruby
yecht-0.0.2/default.build.properties 0000775 0000000 0000000 00000000756 11233025100 0017463 0 ustar 00root root 0000000 0000000 # Defaults. To override, create a file called build.properties in
# the same directory and put your changes in that.
src.dir=src
main.src.dir=${src.dir}/main
test.src.dir=${src.dir}/test
lib.dir=lib
build.dir=build
classes.dir=${build.dir}/classes
yecht.classes.dir=${classes.dir}/yecht
test.classes.dir=${classes.dir}/test
ruby.classes.dir=${classes.dir}/ruby
docs.dir=docs
api.docs.dir=${docs.dir}/api
release.dir=rels
javac.version=1.5
ruby.src.dir=ext/ruby/src/java
jruby.lib=../jruby/lib
yecht-0.0.2/ext/ 0000775 0000000 0000000 00000000000 11233025100 0013410 5 ustar 00root root 0000000 0000000 yecht-0.0.2/ext/ruby/ 0000775 0000000 0000000 00000000000 11233025100 0014371 5 ustar 00root root 0000000 0000000 yecht-0.0.2/ext/ruby/lib/ 0000775 0000000 0000000 00000000000 11233025100 0015137 5 ustar 00root root 0000000 0000000 yecht-0.0.2/ext/ruby/lib/okay.rb 0000664 0000000 0000000 00000011306 11233025100 0016430 0 ustar 00root root 0000000 0000000 #
# vim:sw=4:ts=4
# $Id$
#
# Okay Project
#
require 'yaml'
module Okay
@@type_registry = {
'boolean' => nil,
'str' => nil,
'int' => nil,
'null' => nil,
'float' => nil,
'seq' => nil,
'map' => nil
}
class Error < StandardError; end
# Transfer methods for okay types
TRANSFER_TYPES = {}
OKAY_TYPE_DOMAIN = 'okay.yaml.org,2002'
OKAY_TYPE_REGEXP = /^tag:#{ Regexp::quote( OKAY_TYPE_DOMAIN ) }:([^;]+)((?:;\w+)*)$/
#
# Base class for Okay types
# All types should inherit this class to use modules
#
class ModuleBase
attr_accessor :modules
end
#
# Quick Okay type handler, handles modules
#
def Okay.add_type( type_name, &transfer_proc )
type_re = /^(#{Regexp::quote( type_name )})((?:;\w+)*)$/
Okay::TRANSFER_TYPES[ type_name ] = transfer_proc
YAML.add_domain_type( OKAY_TYPE_DOMAIN, type_re ) { |type, val|
type, mods = OKAY_TYPE_REGEXP.match( type ).to_a[1,2]
unless mods.to_s.empty?
mod_re = /^(#{ mods.slice( 1..-1 ).gsub( /;/, '|' ) });/
modules = {}
val.reject! { |k, v|
if k =~ mod_re
modules[ $1 ] ||= {}
modules[ $1 ][ $' ] = v
true
else
false
end
}
end
Okay::TRANSFER_TYPES[ type ].call( type, val, modules )
}
end
def Okay.object_maker( obj_class, val, modules )
obj = YAML.object_maker( obj_class, val )
unless obj.respond_to?( :modules= )
raise Okay::Error, "Modules #{modules.keys.join( ',' )} can't be handled by class #{obj_class}" if modules
end
obj.modules = modules
obj
end
def Okay.load_schema( schema )
schema = YAML::load( schema )
schema.each { |k,v|
@@type_registry[k] = v['schema']
}
end
def Okay.schema( type_name )
@@type_registry[type_name]
end
def Okay.validate_node( node )
type, mods = OKAY_TYPE_REGEXP.match( node.type_id ).to_a[1,2]
unless @@type_registry.has_key?( type )
raise Okay::Error, "Type `#{type}' not found in loaded schema."
end
return true if @@type_registry[ type ].nil?
node_vs_schema( @@type_registry[ type ], node, [], true )
end
def Okay.node_vs_schema( schema, node, depth, head )
#
# Head type can be matched against a core type
#
type_id = head ? node.kind : node.type_id
type_id = node.kind if type_id.empty?
if type_id =~ /^okay\//
type_id, mods = OKAY_TYPE_REGEXP.match( type_id ).to_a[1,2]
end
if schema.has_key?( type_id )
attr = schema[ type_id ]
else
raise Okay::Error, "Node of type !#{type_id} invalid at /" + depth.join( "/" )
end
if @@type_registry[ type_id ]
node_vs_schema( @@type_registry[ type_id ], node, depth, true )
end
#
# Descend and match types of nodes
#
if attr
attr.each { |prop, prop_schema|
#
# Mini-paths
#
if prop =~ /^\//
key = $'
if key == "*"
node.children_with_index.each { |c|
node_vs_schema( prop_schema, c[0], depth + [c[1]], false )
}
else
if node[key]
child = node[key]
node_vs_schema( prop_schema, child, depth + [key], false )
else
unless Array === attr['optional'] and attr['optional'].include?( "/" + key )
raise Okay::Error, "No key '#{key}' found at /" + depth.join( "/" )
end
end
end
end
}
else
end
return true
end
def Okay.make_schema_flexhash( type_root )
type_root = YAML::transfer( 'tag:ruby.yaml.org,2002:flexhash', type_root )
type_root.collect! { |e|
if Hash === e[1]
e[1].each { |k,v|
if k =~ /^\// and Array === v
e[1][k] = make_schema_flexhash( v )
end
}
end
e
}
type_root
end
Okay.add_type( 'schema' ) { |type, val, modules|
val.each { |k,v|
v['schema'] = make_schema_flexhash( v['schema'] )
}
}
end
yecht-0.0.2/ext/ruby/lib/okay/ 0000775 0000000 0000000 00000000000 11233025100 0016102 5 ustar 00root root 0000000 0000000 yecht-0.0.2/ext/ruby/lib/okay/news.rb 0000664 0000000 0000000 00000002650 11233025100 0017406 0 ustar 00root root 0000000 0000000 #
# The !okay/news module for YAML.rb
#
require 'okay'
module Okay
class News < ModuleBase
attr_accessor :title, :link, :description, :updatePeriod, :items
def to_yaml_properties
[ '@title', '@link', '@description', '@updatePeriod', '@items' ]
end
def to_yaml_type
"!okay/news"
end
end
Okay.add_type( "news" ) { |type, val, modules|
Okay.object_maker( Okay::News, val, modules )
}
class NewsItem < ModuleBase
attr_accessor :title, :link, :description, :pubTime
def to_yaml_properties
[ '@title', '@link', '@description', '@pubTime' ]
end
def to_yaml_type
"!okay/news/item"
end
end
Okay.add_type( "news/item" ) { |type, val, modules|
Okay.object_maker( Okay::NewsItem, val, modules )
}
end
Okay.load_schema( <
Inspired by RSS, more limited...
examples: >
If I had a news site...
schema:
- map:
/title: [ str ]
/link: [ str ]
/description: [ str ]
/updatePeriod: [ str ]
/items:
- seq: { /*: [ okay/news/item ] }
okay/news/item:
description: >
Inside okay/news lies...
examples: >
See okay/news examples...
schema:
- map:
/title: [ str ]
/pubTime: [ time ]
/link: [ str ]
/description: [ str ]
optional: [ /title ]
EOY
yecht-0.0.2/ext/ruby/lib/okay/rpc.rb 0000664 0000000 0000000 00000034330 11233025100 0017216 0 ustar 00root root 0000000 0000000 #
# The !okay/rpc module for YAML.rb
# Specification at http://wiki.yaml.org/yamlwiki/OkayRpcProtocol
#
require 'okay'
require 'net/http'
module Okay
module RPC
VERSION = '0.06'
class Method
attr_accessor :methodName, :params
def initialize( mn, p )
@methodName = mn
@params = p
end
def to_yaml( opts = {} )
YAML::quick_emit( self.id, opts ) { |out|
out.map( "!okay/rpc/method" ) { |map|
map.add( self.methodName, self.params )
}
}
end
end
YAML.add_domain_type( "okay.yaml.org,2002", "rpc/method" ) { |type, val|
if val.class == Hash and val.length == 1
val = val.to_a.first
RPC::Method.new( val[0], val[1] )
end
}
class Fault
attr_accessor :code, :message
def initialize( c, m )
@code = c
@message = m
end
def to_yaml( opts = {} )
YAML::quick_emit( self.id, opts ) { |out|
out.map( "!okay/rpc/fault" ) { |map|
map.add( self.code, self.message )
}
}
end
end
YAML.add_domain_type( "okay.yaml.org,2002", "rpc/fault" ) { |type, val|
if val.class == Hash and val.length == 1
val = val.to_a.first
Fault.new( val[0], val[1] )
end
}
class Client
USER_AGENT = "Okay::RPC::Client (Ruby #{RUBY_VERSION})"
def initialize(host=nil, path=nil, port=nil, proxy_host=nil, proxy_port=nil,
user=nil, password=nil, use_ssl=nil, timeout=nil)
@host = host || "localhost"
@path = path || "/okayRpc/"
@proxy_host = proxy_host
@proxy_port = proxy_port
@proxy_host ||= 'localhost' if @proxy_port != nil
@proxy_port ||= 8080 if @proxy_host != nil
@use_ssl = use_ssl || false
@timeout = timeout || 30
@queue = YAML::Stream.new( :UseHeader => true )
if use_ssl
require "net/https"
@port = port || 443
else
@port = port || 80
end
@user, @password = user, password
set_auth
# convert ports to integers
@port = @port.to_i if @port != nil
@proxy_port = @proxy_port.to_i if @proxy_port != nil
# HTTP object for synchronous calls
Net::HTTP.version_1_2
@http = Net::HTTP.new(@host, @port, @proxy_host, @proxy_port)
@http.use_ssl = @use_ssl if @use_ssl
@http.read_timeout = @timeout
@http.open_timeout = @timeout
@parser = nil
@create = nil
end
# Attribute Accessors -------------------------------------------------------------------
attr_reader :timeout, :user, :password
def timeout=(new_timeout)
@timeout = new_timeout
@http.read_timeout = @timeout
@http.open_timeout = @timeout
end
def user=(new_user)
@user = new_user
set_auth
end
def password=(new_password)
@password = new_password
set_auth
end
# Call methods --------------------------------------------------------------
def call(method, *args)
meth = Method.new( method, args )
YAML::load( do_rpc(meth.to_yaml, false) )
end
def qcall(method, *args)
@queue.add( Method.new( method, args ) )
end
def qrun
ret = YAML.load_stream( do_rpc( @queue.emit, false ) )
@queue = YAML::Stream.new( :UseHeader => true )
ret
end
private # ----------------------------------------------------------
def set_auth
if @user.nil?
@auth = nil
else
a = "#@user"
a << ":#@password" if @password != nil
@auth = ("Basic " + [a].pack("m")).chomp
end
end
def do_rpc(request, async=false)
header = {
"User-Agent" => USER_AGENT,
"Content-Type" => "text/yaml",
"Content-Length" => request.size.to_s,
"Connection" => (async ? "close" : "keep-alive")
}
if @auth != nil
# add authorization header
header["Authorization"] = @auth
end
if async
# use a new HTTP object for each call
Net::HTTP.version_1_2
http = Net::HTTP.new(@host, @port, @proxy_host, @proxy_port)
http.use_ssl = @use_ssl if @use_ssl
http.read_timeout = @timeout
http.open_timeout = @timeout
else
# reuse the HTTP object for each call => connection alive is possible
http = @http
end
# post request
resp = http.post2(@path, request, header)
data = resp.body
http.finish if async
if resp.code == "401"
# Authorization Required
raise "Authorization failed.\nHTTP-Error: #{resp.code} #{resp.message}"
elsif resp.code[0,1] != "2"
raise "HTTP-Error: #{resp.code} #{resp.message}"
end
if resp["Content-Type"] != "text/yaml"
raise "Wrong content-type [#{resp['Content-Type']}]: \n#{data}"
end
expected = resp["Content-Length"] || ""
if data.nil? or data.size == 0
raise "Wrong size. Was #{data.size}, should be #{expected}"
elsif expected.to_i != data.size and resp["Transfer-Encoding"].nil?
raise "Wrong size. Was #{data.size}, should be #{expected}"
end
return data
end
end
class BasicServer
def initialize
@handlers = {}
@aboutHash = {
'name' => 'An !okay/rpc server.',
'uri' => nil,
'version' => VERSION,
'authors' => nil,
'about' => "Welcome to the !okay/rpc server."
}
add_introspection
end
def name( str )
@aboutHash['name']
end
def name=( str )
@aboutHash['name'] = str
end
def about
@aboutHash['about']
end
def about=( str )
@aboutHash['about'] = str.strip.gsub( /^ +/, '' ).gsub( /\n(\n*)/, ' \1' )
end
def uri( str )
@aboutHash['uri']
end
def uri=( str )
@aboutHash['uri'] = str
end
def add_author( name, email, url )
@aboutHash['authors'] ||= []
@aboutHash['authors'] << {
'name' => name,
'email' => email,
'url' => url
}
end
def add_handler( methodName, sig, doc, &block )
@handlers[ methodName ] = {
:signature => sig,
:help => doc,
:block => block
}
end
def get_handler( methodName, prop )
unless @handlers.has_key?( methodName )
Fault.new( 101, "No method ''#{methodName}'' available." )
else
@handlers[ methodName ][ prop ]
end
end
def dispatch( meth )
b = get_handler( meth.methodName, :block )
return b if b.is_a? Fault
b.call( meth )
end
def process( meth_yml )
s = YAML::Stream.new( :UseHeader => true )
YAML::load_documents( meth_yml ) { |doc|
s.add( dispatch( doc ) )
}
s.emit
end
private
def add_introspection
add_handler(
"system.about", %w(map),
"Provides a short description of this !okay/rpc server's intent."
) {
@aboutHash
}
add_handler(
"system.getCapabilities", %w(map),
"Describes this server's capabilities, including version of " +
"!okay/rpc available and YAML implementation."
) {
{
'okay/rpc' =>
{ 'version' => Okay::RPC::VERSION,
'id' => 'YAML.rb Okay::RPC',
'url' => 'http://wiki.yaml.org/yamlwiki/OkayRpcProtocol'
},
'yaml' =>
{ 'version' => YAML::VERSION,
'id' => 'YAML.rb',
'url' => 'http://yaml4r.sf.net/'
},
'sys' =>
{ 'version' => Kernel::RUBY_VERSION,
'id' => Kernel::RUBY_PLATFORM
}
}
}
add_handler(
"system.listMethods", %w(seq),
"Lists the available methods for this !okay/rpc server."
) {
@handlers.keys.sort
}
add_handler(
"system.methodSignature", %w(seq str),
"Returns a method signature."
) { |meth|
get_handler( meth.params[0], :signature )
}
add_handler(
"system.methodHelp", %w(str str),
"Returns help on using this method."
) { |meth|
get_handler( meth.params[0], :help )
}
add_handler(
"system.methodBlank", %w(str str),
"Returns a blank method."
) { |meth|
sig = get_handler( meth.params[0], :signature )
unless sig.is_a? Fault
"--- !okay/rpc/method\n#{meth.params[0]}:\n" +
sig[1..-1].collect { |type| " - !#{type}" }.join( "\n" )
else
sig
end
}
end
end
class ModRubyServer < BasicServer
def initialize(*a)
@ap = Apache::request
super(*a)
url ||= @ap.uri
end
def serve
catch(:exit_serve) {
header = {}
hdr_in_proc = proc {|key, value| header[key.capitalize] = value}
if @ap.respond_to? :headers_in
@ap.headers_in.each( &hdr_in_proc )
else
@ap.each_header( &hdr_in_proc )
end
length = header['Content-length'].to_i
http_error(405, "Method Not Allowed") unless @ap.request_method == "POST"
http_error(400, "Bad Request") unless header['Content-type'] == "text/yaml"
http_error(411, "Length Required") unless length > 0
# TODO: do we need a call to binmode?
@ap.binmode
data = @ap.read(length)
http_error(400, "Bad Request") if data.nil? or data.size != length
resp =
begin
process(data)
rescue Exception => e
Fault.new(101, e.message).to_yaml
end
http_write(resp, 200, "Content-type" => "text/yaml")
}
end
private
def http_error(status, message)
err = "#{status} #{message}"
msg = <<-"MSGEND"
#{err}
#{err}
Unexpected error occured while processing !okay/rpc request!
MSGEND
http_write(msg, status, "Status" => err, "Content-type" => "text/html")
throw :exit_serve # exit from the #serve method
end
def http_write(body, status, header)
h = {}
header.each {|key, value| h[key.to_s.capitalize] = value}
h['Status'] ||= "200 OK"
h['Content-length'] ||= body.size.to_s
h.each do |key, value|
if @ap.respond_to? :headers_out
@ap.headers_out[key] = value
else
@ap[key] = value
end
end
@ap.content_type = h["Content-type"]
@ap.status = status.to_i
@ap.send_http_header
@ap.print body
end
end
end
end
Okay.load_schema( <
XML-RPC for YAML.
examples: >
Testing
schema:
- map:
/*: [ seq ]
length: 1
EOY
yecht-0.0.2/ext/ruby/lib/yaml.rb 0000664 0000000 0000000 00000030341 11233025100 0016427 0 ustar 00root root 0000000 0000000 # -*- mode: ruby; ruby-indent-level: 4; tab-width: 4 -*- vim: sw=4 ts=4
# $Id$
#
# = yaml.rb: top-level module with methods for loading and parsing YAML documents
#
# Author:: why the lucky stiff
#
require 'stringio'
require 'yaml/compat'
require 'yaml/error'
require 'yaml/yecht'
require 'yaml/tag'
require 'yaml/stream'
require 'yaml/constants'
# == YAML
#
# YAML(tm) (rhymes with 'camel') is a
# straightforward machine parsable data serialization format designed for
# human readability and interaction with scripting languages such as Perl
# and Python. YAML is optimized for data serialization, formatted
# dumping, configuration files, log files, Internet messaging and
# filtering. This specification describes the YAML information model and
# serialization format. Together with the Unicode standard for characters, it
# provides all the information necessary to understand YAML Version 1.0
# and construct computer programs to process it.
#
# See http://yaml.org/ for more information. For a quick tutorial, please
# visit YAML In Five Minutes (http://yaml.kwiki.org/?YamlInFiveMinutes).
#
# == About This Library
#
# The YAML 1.0 specification outlines four stages of YAML loading and dumping.
# This library honors all four of those stages, although data is really only
# available to you in three stages.
#
# The four stages are: native, representation, serialization, and presentation.
#
# The native stage refers to data which has been loaded completely into Ruby's
# own types. (See +YAML::load+.)
#
# The representation stage means data which has been composed into
# +YAML::BaseNode+ objects. In this stage, the document is available as a
# tree of node objects. You can perform YPath queries and transformations
# at this level. (See +YAML::parse+.)
#
# The serialization stage happens inside the parser. The YAML parser used in
# Ruby is called Yecht. Serialized nodes are available in the extension as
# Node structs.
#
# The presentation stage is the YAML document itself. This is accessible
# to you as a string. (See +YAML::dump+.)
#
# For more information about the various information models, see Chapter
# 3 of the YAML 1.0 Specification (http://yaml.org/spec/#id2491269).
#
# The YAML module provides quick access to the most common loading (YAML::load)
# and dumping (YAML::dump) tasks. This module also provides an API for registering
# global types (YAML::add_domain_type).
#
# == Example
#
# A simple round-trip (load and dump) of an object.
#
# require "yaml"
#
# test_obj = ["dogs", "cats", "badgers"]
#
# yaml_obj = YAML::dump( test_obj )
# # -> ---
# - dogs
# - cats
# - badgers
# ruby_obj = YAML::load( yaml_obj )
# # => ["dogs", "cats", "badgers"]
# ruby_obj == test_obj
# # => true
#
# To register your custom types with the global resolver, use +add_domain_type+.
#
# YAML::add_domain_type( "your-site.com,2004", "widget" ) do |type, val|
# Widget.new( val )
# end
#
module YAML
Resolver = YAML::Yecht::Resolver
DefaultResolver = YAML::Yecht::DefaultResolver
DefaultResolver.use_types_at( @@tagged_classes )
GenericResolver = YAML::Yecht::GenericResolver
Parser = YAML::Yecht::Parser
Emitter = YAML::Yecht::Emitter
# Returns a new default parser
def YAML.parser; Parser.new.set_resolver( YAML.resolver ); end
# Returns a new generic parser
def YAML.generic_parser; Parser.new.set_resolver( GenericResolver ); end
# Returns the default resolver
def YAML.resolver; DefaultResolver; end
# Returns a new default emitter
def YAML.emitter; Emitter.new.set_resolver( YAML.resolver ); end
#
# Converts _obj_ to YAML and writes the YAML result to _io_.
#
# File.open( 'animals.yaml', 'w' ) do |out|
# YAML.dump( ['badger', 'elephant', 'tiger'], out )
# end
#
# If no _io_ is provided, a string containing the dumped YAML
# is returned.
#
# YAML.dump( :locked )
# #=> "--- :locked"
#
def YAML.dump( obj, io = nil )
obj.to_yaml( io || io2 = StringIO.new )
io || ( io2.rewind; io2.read )
end
#
# Load a document from the current _io_ stream.
#
# File.open( 'animals.yaml' ) { |yf| YAML::load( yf ) }
# #=> ['badger', 'elephant', 'tiger']
#
# Can also load from a string.
#
# YAML.load( "--- :locked" )
# #=> :locked
#
def YAML.load( io )
yp = parser.load( io )
end
#
# Load a document from the file located at _filepath_.
#
# YAML.load_file( 'animals.yaml' )
# #=> ['badger', 'elephant', 'tiger']
#
def YAML.load_file( filepath )
File.open( filepath ) do |f|
load( f )
end
end
#
# Parse the first document from the current _io_ stream
#
# File.open( 'animals.yaml' ) { |yf| YAML::load( yf ) }
# #=> #,
# #,
# #]>
#
# Can also load from a string.
#
# YAML.parse( "--- :locked" )
# #=> #
#
def YAML.parse( io )
yp = generic_parser.load( io )
end
#
# Parse a document from the file located at _filepath_.
#
# YAML.parse_file( 'animals.yaml' )
# #=> #,
# #,
# #]>
#
def YAML.parse_file( filepath )
File.open( filepath ) do |f|
parse( f )
end
end
#
# Calls _block_ with each consecutive document in the YAML
# stream contained in _io_.
#
# File.open( 'many-docs.yaml' ) do |yf|
# YAML.each_document( yf ) do |ydoc|
# ## ydoc contains the single object
# ## from the YAML document
# end
# end
#
def YAML.each_document( io, &block )
yp = parser.load_documents( io, &block )
end
#
# Calls _block_ with each consecutive document in the YAML
# stream contained in _io_.
#
# File.open( 'many-docs.yaml' ) do |yf|
# YAML.load_documents( yf ) do |ydoc|
# ## ydoc contains the single object
# ## from the YAML document
# end
# end
#
def YAML.load_documents( io, &doc_proc )
YAML.each_document( io, &doc_proc )
end
#
# Calls _block_ with a tree of +YAML::BaseNodes+, one tree for
# each consecutive document in the YAML stream contained in _io_.
#
# File.open( 'many-docs.yaml' ) do |yf|
# YAML.each_node( yf ) do |ydoc|
# ## ydoc contains a tree of nodes
# ## from the YAML document
# end
# end
#
def YAML.each_node( io, &doc_proc )
yp = generic_parser.load_documents( io, &doc_proc )
end
#
# Calls _block_ with a tree of +YAML::BaseNodes+, one tree for
# each consecutive document in the YAML stream contained in _io_.
#
# File.open( 'many-docs.yaml' ) do |yf|
# YAML.parse_documents( yf ) do |ydoc|
# ## ydoc contains a tree of nodes
# ## from the YAML document
# end
# end
#
def YAML.parse_documents( io, &doc_proc )
YAML.each_node( io, &doc_proc )
end
#
# Loads all documents from the current _io_ stream,
# returning a +YAML::Stream+ object containing all
# loaded documents.
#
def YAML.load_stream( io )
d = nil
parser.load_documents( io ) do |doc|
d = YAML::Stream.new if not d
d.add( doc )
end
return d
end
#
# Returns a YAML stream containing each of the items in +objs+,
# each having their own document.
#
# YAML.dump_stream( 0, [], {} )
# #=> --- 0
# --- []
# --- {}
#
def YAML.dump_stream( *objs )
d = YAML::Stream.new
objs.each do |doc|
d.add( doc )
end
d.emit
end
#
# Add a global handler for a YAML domain type.
#
def YAML.add_domain_type( domain, type_tag, &transfer_proc )
resolver.add_type( "tag:#{ domain }:#{ type_tag }", transfer_proc )
end
#
# Add a transfer method for a builtin type
#
def YAML.add_builtin_type( type_tag, &transfer_proc )
resolver.add_type( "tag:yaml.org,2002:#{ type_tag }", transfer_proc )
end
#
# Add a transfer method for a builtin type
#
def YAML.add_ruby_type( type_tag, &transfer_proc )
resolver.add_type( "tag:ruby.yaml.org,2002:#{ type_tag }", transfer_proc )
end
#
# Add a private document type
#
def YAML.add_private_type( type_re, &transfer_proc )
resolver.add_type( "x-private:" + type_re, transfer_proc )
end
#
# Detect typing of a string
#
def YAML.detect_implicit( val )
resolver.detect_implicit( val )
end
#
# Convert a type_id to a taguri
#
def YAML.tagurize( val )
resolver.tagurize( val )
end
#
# Apply a transfer method to a Ruby object
#
def YAML.transfer( type_id, obj )
resolver.transfer( YAML.tagurize( type_id ), obj )
end
#
# Apply any implicit a node may qualify for
#
def YAML.try_implicit( obj )
YAML.transfer( YAML.detect_implicit( obj ), obj )
end
#
# Method to extract colon-seperated type and class, returning
# the type and the constant of the class
#
def YAML.read_type_class( type, obj_class )
scheme, domain, type, tclass = type.split( ':', 4 )
tclass.split( "::" ).each { |c| obj_class = obj_class.const_get( c ) } if tclass
return [ type, obj_class ]
end
#
# Allocate blank object
#
def YAML.object_maker( obj_class, val )
if Hash === val
o = obj_class.allocate
val.each_pair { |k,v|
o.instance_variable_set("@#{k}", v)
}
o
else
raise YAML::Error, "Invalid object explicitly tagged !ruby/Object: " + val.inspect
end
end
#
# Allocate an Emitter if needed
#
def YAML.quick_emit( oid, opts = {}, &e )
out =
if opts.is_a? YAML::Emitter
opts
else
emitter.reset( opts )
end
out.emit( oid, &e )
end
end
require 'yaml/rubytypes'
require 'yaml/types'
module Kernel
#
# ryan:: You know how Kernel.p is a really convenient way to dump ruby
# structures? The only downside is that it's not as legible as
# YAML.
#
# _why:: (listening)
#
# ryan:: I know you don't want to urinate all over your users' namespaces.
# But, on the other hand, convenience of dumping for debugging is,
# IMO, a big YAML use case.
#
# _why:: Go nuts! Have a pony parade!
#
# ryan:: Either way, I certainly will have a pony parade.
#
# Prints any supplied _objects_ out in YAML. Intended as
# a variation on +Kernel::p+.
#
# S = Struct.new(:name, :state)
# s = S['dave', 'TX']
# y s
#
# _produces:_
#
# --- !ruby/struct:S
# name: dave
# state: TX
#
def y( object, *objects )
objects.unshift object
puts( if objects.length == 1
YAML::dump( *objects )
else
YAML::dump_stream( *objects )
end )
end
private :y
end
yecht-0.0.2/ext/ruby/lib/yaml/ 0000775 0000000 0000000 00000000000 11233025100 0016101 5 ustar 00root root 0000000 0000000 yecht-0.0.2/ext/ruby/lib/yaml/baseemitter.rb 0000664 0000000 0000000 00000013176 11233025100 0020742 0 ustar 00root root 0000000 0000000 #
# BaseEmitter
#
require 'yaml/constants'
require 'yaml/encoding'
require 'yaml/error'
module YAML
module BaseEmitter
def options( opt = nil )
if opt
@options[opt] || YAML::DEFAULTS[opt]
else
@options
end
end
def options=( opt )
@options = opt
end
#
# Emit binary data
#
def binary_base64( value )
self << "!binary "
self.node_text( [value].pack("m"), '|' )
end
#
# Emit plain, normal flowing text
#
def node_text( value, block = nil )
@seq_map = false
valx = value.dup
unless block
block =
if options(:UseBlock)
'|'
elsif not options(:UseFold) and valx =~ /\n[ \t]/ and not valx =~ /#{YAML::ESCAPE_CHAR}/
'|'
else
'>'
end
indt = $&.to_i if block =~ /\d+/
if valx =~ /(\A\n*[ \t#]|^---\s+)/
indt = options(:Indent) unless indt.to_i > 0
block += indt.to_s
end
block +=
if valx =~ /\n\Z\n/
"+"
elsif valx =~ /\Z\n/
""
else
"-"
end
end
block += "\n"
if block[0] == ?"
esc_skip = ( "\t\n" unless valx =~ /^[ \t]/ ) || ""
valx = fold( YAML::escape( valx, esc_skip ) + "\"" ).chomp
self << '"' + indent_text( valx, indt, false )
else
if block[0] == ?>
valx = fold( valx )
end
#p [block, indt]
self << block + indent_text( valx, indt )
end
end
#
# Emit a simple, unqouted string
#
def simple( value )
@seq_map = false
self << value.to_s
end
#
# Emit double-quoted string
#
def double( value )
"\"#{YAML.escape( value )}\""
end
#
# Emit single-quoted string
#
def single( value )
"'#{value}'"
end
#
# Write a text block with the current indent
#
def indent_text( text, mod, first_line = true )
return "" if text.to_s.empty?
spacing = indent( mod )
text = text.gsub( /\A([^\n])/, "#{ spacing }\\1" ) if first_line
return text.gsub( /\n^([^\n])/, "\n#{spacing}\\1" )
end
#
# Write a current indent
#
def indent( mod = nil )
#p [ self.id, level, mod, :INDENT ]
if level <= 0
mod ||= 0
else
mod ||= options(:Indent)
mod += ( level - 1 ) * options(:Indent)
end
return " " * mod
end
#
# Add indent to the buffer
#
def indent!
self << indent
end
#
# Folding paragraphs within a column
#
def fold( value )
value.gsub( /(^[ \t]+.*$)|(\S.{0,#{options(:BestWidth) - 1}})(?:[ \t]+|(\n+(?=[ \t]|\Z))|$)/ ) do |s|
$1 || $2 + ( $3 || "\n" )
end
end
#
# Quick mapping
#
def map( type, &e )
val = Mapping.new
e.call( val )
self << "#{type} " if type.length.nonzero?
#
# Empty hashes
#
if val.length.zero?
self << "{}"
@seq_map = false
else
# FIXME
# if @buffer.length == 1 and options(:UseHeader) == false and type.length.zero?
# @headless = 1
# end
defkey = @options.delete( :DefaultKey )
if defkey
seq_map_shortcut
self << "= : "
defkey.to_yaml( :Emitter => self )
end
#
# Emit the key and value
#
val.each { |v|
seq_map_shortcut
if v[0].is_complex_yaml?
self << "? "
end
v[0].to_yaml( :Emitter => self )
if v[0].is_complex_yaml?
self << "\n"
indent!
end
self << ": "
v[1].to_yaml( :Emitter => self )
}
end
end
def seq_map_shortcut
# FIXME: seq_map needs to work with the new anchoring system
# if @seq_map
# @anchor_extras[@buffer.length - 1] = "\n" + indent
# @seq_map = false
# else
self << "\n"
indent!
# end
end
#
# Quick sequence
#
def seq( type, &e )
@seq_map = false
val = Sequence.new
e.call( val )
self << "#{type} " if type.length.nonzero?
#
# Empty arrays
#
if val.length.zero?
self << "[]"
else
# FIXME
# if @buffer.length == 1 and options(:UseHeader) == false and type.length.zero?
# @headless = 1
# end
#
# Emit the key and value
#
val.each { |v|
self << "\n"
indent!
self << "- "
@seq_map = true if v.class == Hash
v.to_yaml( :Emitter => self )
}
end
end
end
#
# Emitter helper classes
#
class Mapping < Array
def add( k, v )
push [k, v]
end
end
class Sequence < Array
def add( v )
push v
end
end
end
yecht-0.0.2/ext/ruby/lib/yaml/basenode.rb 0000664 0000000 0000000 00000013761 11233025100 0020216 0 ustar 00root root 0000000 0000000 #
# YAML::BaseNode class
#
require 'yaml/ypath'
module YAML
#
# YAML Generic Model container
#
module BaseNode
#
# Search for YPath entry and return
# qualified nodes.
#
def select( ypath_str )
matches = match_path( ypath_str )
#
# Create a new generic view of the elements selected
#
if matches
result = []
matches.each { |m|
result.push m.last
}
YAML.transfer( 'seq', result )
end
end
#
# Search for YPath entry and return
# transformed nodes.
#
def select!( ypath_str )
matches = match_path( ypath_str )
#
# Create a new generic view of the elements selected
#
if matches
result = []
matches.each { |m|
result.push m.last.transform
}
result
end
end
#
# Search for YPath entry and return a list of
# qualified paths.
#
def search( ypath_str )
matches = match_path( ypath_str )
if matches
matches.collect { |m|
path = []
m.each_index { |i|
path.push m[i] if ( i % 2 ).zero?
}
"/" + path.compact.join( "/" )
}
end
end
def at( seg )
if Hash === @value
self[seg]
elsif Array === @value and seg =~ /\A\d+\Z/ and @value[seg.to_i]
@value[seg.to_i]
end
end
#
# YPath search returning a complete depth array
#
def match_path( ypath_str )
depth = 0
matches = []
YPath.each_path( ypath_str ) do |ypath|
seg = match_segment( ypath, 0 )
matches += seg if seg
end
matches.uniq
end
#
# Search a node for a single YPath segment
#
def match_segment( ypath, depth )
deep_nodes = []
seg = ypath.segments[ depth ]
if seg == "/"
unless String === @value
idx = -1
@value.collect { |v|
idx += 1
if Hash === @value
match_init = [v[0].transform, v[1]]
match_deep = v[1].match_segment( ypath, depth )
else
match_init = [idx, v]
match_deep = v.match_segment( ypath, depth )
end
if match_deep
match_deep.each { |m|
deep_nodes.push( match_init + m )
}
end
}
end
depth += 1
seg = ypath.segments[ depth ]
end
match_nodes =
case seg
when "."
[[nil, self]]
when ".."
[["..", nil]]
when "*"
if @value.is_a? Enumerable
idx = -1
@value.collect { |h|
idx += 1
if Hash === @value
[h[0].transform, h[1]]
else
[idx, h]
end
}
end
else
if seg =~ /^"(.*)"$/
seg = $1
elsif seg =~ /^'(.*)'$/
seg = $1
end
if ( v = at( seg ) )
[[ seg, v ]]
end
end
return deep_nodes unless match_nodes
pred = ypath.predicates[ depth ]
if pred
case pred
when /^\.=/
pred = $' # '
match_nodes.reject! { |n|
n.last.value != pred
}
else
match_nodes.reject! { |n|
n.last.at( pred ).nil?
}
end
end
return match_nodes + deep_nodes unless ypath.segments.length > depth + 1
#puts "DEPTH: #{depth + 1}"
deep_nodes = []
match_nodes.each { |n|
if n[1].is_a? BaseNode
match_deep = n[1].match_segment( ypath, depth + 1 )
if match_deep
match_deep.each { |m|
deep_nodes.push( n + m )
}
end
else
deep_nodes = []
end
}
deep_nodes = nil if deep_nodes.length == 0
deep_nodes
end
#
# We want the node to act like as Hash
# if it is.
#
def []( *key )
if Hash === @value
v = @value.detect { |k,v| k.transform == key.first }
v[1] if v
elsif Array === @value
@value.[]( *key )
end
end
def children
if Hash === @value
@value.values.collect { |c| c[1] }
elsif Array === @value
@value
end
end
def children_with_index
if Hash === @value
@value.keys.collect { |i| [self[i], i] }
elsif Array === @value
i = -1; @value.collect { |v| i += 1; [v, i] }
end
end
def emit
transform.to_yaml
end
end
end
yecht-0.0.2/ext/ruby/lib/yaml/compat.rb 0000664 0000000 0000000 00000001621 11233025100 0017711 0 ustar 00root root 0000000 0000000 #
# Ruby 1.6 -> 1.8 compatibility
# (an isolated incident)
#
class Object; alias_method :object_id, :id; end unless Object.respond_to? :object_id
class Object; def instance_variable_set(k, v); self.instance_eval "#{k} = v"; end; end \
unless Object.respond_to? :instance_variable_set
class Object; def instance_variable_get(k); self.instance_eval "#{k}"; end; end \
unless Object.respond_to? :instance_variable_get
unless Object.respond_to? :allocate
class Object
def allocate
name = self.class.name
if Marshal::const_defined? :MAJOR_VERSION
ostr = sprintf( "%c%co:%c%s\000", Marshal::MAJOR_VERSION, Marshal::MINOR_VERSION,
name.length + 5, name )
else
ostr = sprintf( "\004\006o:%c%s\000", name.length + 5, name )
end
::Marshal.load( ostr )
end
end
end
yecht-0.0.2/ext/ruby/lib/yaml/constants.rb 0000664 0000000 0000000 00000002242 11233025100 0020442 0 ustar 00root root 0000000 0000000 #
# Constants used throughout the library
#
module YAML
#
# Constants
#
VERSION = '0.60'
SUPPORTED_YAML_VERSIONS = ['1.0']
#
# Parser tokens
#
WORD_CHAR = 'A-Za-z0-9'
PRINTABLE_CHAR = '-_A-Za-z0-9!?/()$\'". '
NOT_PLAIN_CHAR = '\x7f\x0-\x1f\x80-\x9f'
ESCAPE_CHAR = '[\\x00-\\x09\\x0b-\\x1f]'
INDICATOR_CHAR = '*&!|\\\\^@%{}[]='
SPACE_INDICATORS = '-#:,?'
RESTRICTED_INDICATORS = '#:,}]'
DNS_COMP_RE = "\\w(?:[-\\w]*\\w)?"
DNS_NAME_RE = "(?:(?:#{DNS_COMP_RE}\\.)+#{DNS_COMP_RE}|#{DNS_COMP_RE})"
ESCAPES = %w{\x00 \x01 \x02 \x03 \x04 \x05 \x06 \a
\x08 \t \n \v \f \r \x0e \x0f
\x10 \x11 \x12 \x13 \x14 \x15 \x16 \x17
\x18 \x19 \x1a \e \x1c \x1d \x1e \x1f
}
UNESCAPES = {
'a' => "\x07", 'b' => "\x08", 't' => "\x09",
'n' => "\x0a", 'v' => "\x0b", 'f' => "\x0c",
'r' => "\x0d", 'e' => "\x1b", '\\' => '\\',
}
#
# Default settings
#
DEFAULTS = {
:Indent => 2, :UseHeader => false, :UseVersion => false, :Version => '1.0',
:SortKeys => false, :AnchorFormat => 'id%03d', :ExplicitTypes => false,
:WidthType => 'absolute', :BestWidth => 80,
:UseBlock => false, :UseFold => false, :Encoding => :None
}
end
yecht-0.0.2/ext/ruby/lib/yaml/dbm.rb 0000664 0000000 0000000 00000004372 11233025100 0017176 0 ustar 00root root 0000000 0000000 require 'yaml'
require 'dbm'
#
# YAML + DBM = YDBM
# - Same interface as DBM class
#
module YAML
class DBM < ::DBM
VERSION = "0.1"
def []( key )
fetch( key )
end
def []=( key, val )
store( key, val )
end
def fetch( keystr, ifnone = nil )
begin
val = super( keystr )
return YAML::load( val ) if String === val
rescue IndexError
end
if block_given?
yield keystr
else
ifnone
end
end
def index( keystr )
super( keystr.to_yaml )
end
def values_at( *keys )
keys.collect { |k| fetch( k ) }
end
def delete( key )
v = super( key )
if String === v
v = YAML::load( v )
end
v
end
def delete_if
del_keys = keys.dup
del_keys.delete_if { |k| yield( k, fetch( k ) ) == false }
del_keys.each { |k| delete( k ) }
self
end
def reject
hsh = self.to_hash
hsh.reject { |k,v| yield k, v }
end
def each_pair
keys.each { |k| yield k, fetch( k ) }
self
end
def each_value
super { |v| yield YAML::load( v ) }
self
end
def values
super.collect { |v| YAML::load( v ) }
end
def has_value?( val )
each_value { |v| return true if v == val }
return false
end
def invert
h = {}
keys.each { |k| h[ self.fetch( k ) ] = k }
h
end
def replace( hsh )
clear
update( hsh )
end
def shift
a = super
a[1] = YAML::load( a[1] ) if a
a
end
def select( *keys )
if block_given?
self.keys.collect { |k| v = self[k]; [k, v] if yield k, v }.compact
else
values_at( *keys )
end
end
def store( key, val )
super( key, val.to_yaml )
val
end
def update( hsh )
hsh.keys.each do |k|
self.store( k, hsh.fetch( k ) )
end
self
end
def to_a
a = []
keys.each { |k| a.push [ k, self.fetch( k ) ] }
a
end
def to_hash
h = {}
keys.each { |k| h[ k ] = self.fetch( k ) }
h
end
alias :each :each_pair
end
end
yecht-0.0.2/ext/ruby/lib/yaml/emitter.rb 0000664 0000000 0000000 00000004134 11233025100 0020101 0 ustar 00root root 0000000 0000000 #
# Output classes and methods
#
require 'yaml/baseemitter'
require 'yaml/encoding'
module YAML
#
# Emit a set of values
#
class Emitter
include BaseEmitter
attr_accessor :options
def initialize( opts )
opts = {} if opts.class != Hash
@options = YAML::DEFAULTS.dup.update( opts )
@headless = 0
@seq_map = false
@anchors = {}
@anchor_extras = {}
@active_anchors = []
@level = -1
self.clear
end
def clear
@buffer = []
end
def level
@level
end
#
# Version string
#
def version_s
" %YAML:#{@options[:Version]}" if @options[:UseVersion]
end
#
# Header
#
def header
if @headless.nonzero?
""
else
"---#{version_s} "
end
end
#
# Concatenate to the buffer
#
def <<( str )
#p [ self.id, @level, str ]
@buffer.last << str
end
#
# Monitor objects and allow references
#
def start_object( oid )
@level += 1
@buffer.push( "" )
#p [ self.id, @level, :OPEN ]
idx = nil
if oid
if @anchors.has_key?( oid )
idx = @active_anchors.index( oid )
unless idx
idx = @active_anchors.length
af_str = "{@options[:AnchorFormat]} " % [ idx + 1 ]
af_str += @anchor_extras[ @anchors[ oid ] ].to_s
@buffer[ @anchors[ oid ] ][0,0] = af_str
@headless = 0 if @anchors[ oid ].zero?
end
idx += 1
@active_anchors.push( oid )
else
@anchors[ oid ] = @buffer.length - 1
end
end
return idx
end
#
# Output method
#
def end_object
@level -= 1
@buffer.push( "" )
#p [ self.id, @level, :END ]
if @level < 0
header + @buffer.to_s[@headless..-1].to_s
end
end
end
end
yecht-0.0.2/ext/ruby/lib/yaml/encoding.rb 0000664 0000000 0000000 00000001144 11233025100 0020214 0 ustar 00root root 0000000 0000000 #
# Handle Unicode-to-Internal conversion
#
module YAML
#
# Escape the string, condensing common escapes
#
def YAML.escape( value, skip = "" )
value.gsub( /\\/, "\\\\\\" ).
gsub( /"/, "\\\"" ).
gsub( /([\x00-\x1f])/ ) do |x|
skip[x] || ESCAPES[ x.unpack("C")[0] ]
end
end
#
# Unescape the condenses escapes
#
def YAML.unescape( value )
value.gsub( /\\(?:([nevfbart\\])|0?x([0-9a-fA-F]{2})|u([0-9a-fA-F]{4}))/ ) { |x|
if $3
["#$3".hex ].pack('U*')
elsif $2
[$2].pack( "H2" )
else
UNESCAPES[$1]
end
}
end
end
yecht-0.0.2/ext/ruby/lib/yaml/error.rb 0000664 0000000 0000000 00000002055 11233025100 0017561 0 ustar 00root root 0000000 0000000 #
# Error messages and exception class
#
module YAML
#
# Error messages
#
ERROR_NO_HEADER_NODE = "With UseHeader=false, the node Array or Hash must have elements"
ERROR_NEED_HEADER = "With UseHeader=false, the node must be an Array or Hash"
ERROR_BAD_EXPLICIT = "Unsupported explicit transfer: '%s'"
ERROR_MANY_EXPLICIT = "More than one explicit transfer"
ERROR_MANY_IMPLICIT = "More than one implicit request"
ERROR_NO_ANCHOR = "No anchor for alias '%s'"
ERROR_BAD_ANCHOR = "Invalid anchor: %s"
ERROR_MANY_ANCHOR = "More than one anchor"
ERROR_ANCHOR_ALIAS = "Can't define both an anchor and an alias"
ERROR_BAD_ALIAS = "Invalid alias: %s"
ERROR_MANY_ALIAS = "More than one alias"
ERROR_ZERO_INDENT = "Can't use zero as an indentation width"
ERROR_UNSUPPORTED_VERSION = "This release of YAML.rb does not support YAML version %s"
ERROR_UNSUPPORTED_ENCODING = "Attempt to use unsupported encoding: %s"
#
# YAML Error classes
#
class Error < StandardError; end
class ParseError < Error; end
class TypeError < StandardError; end
end
yecht-0.0.2/ext/ruby/lib/yaml/rubytypes.rb 0000664 0000000 0000000 00000034314 11233025100 0020501 0 ustar 00root root 0000000 0000000 # -*- mode: ruby; ruby-indent-level: 4; tab-width: 4 -*- vim: sw=4 ts=4
require 'date'
require 'yaml/compat'
# For Compatibility with Syck 0.60
# class Module
# yaml_as "tag:ruby.yaml.org,2002:module"
# def Module.yaml_new( klass, tag, val )
# if String === val
# val.split(/::/).inject(Object) do |m, n|
# begin
# m.const_get(n)
# rescue NameError
# raise ArgumentError, "undefined class/module #{n} in #{val}"
# end
# end
# else
# raise YAML::TypeError, "Invalid Module: " + val.inspect
# end
# end
# def to_yaml( opts = {} )
# YAML::quick_emit( nil, opts ) { |out|
# out.scalar( "tag:ruby.yaml.org,2002:module", self.name, :plain )
# }
# end
# end
# class Class
# yaml_as "tag:ruby.yaml.org,2002:class"
# def Class.yaml_new( klass, tag, val )
# if String === val
# val.split(/::/).inject(Object) do |m, n|
# begin
# m.const_get(n)
# rescue NameError
# raise ArgumentError, "undefined class/module #{n} in #{val}"
# end
# end
# else
# raise YAML::TypeError, "Invalid Class: " + val.inspect
# end
# end
# def to_yaml( opts = {} )
# YAML::quick_emit( nil, opts ) { |out|
# out.scalar( "tag:ruby.yaml.org,2002:class", self.name, :plain )
# }
# end
# end
class Class
def to_yaml( opts = {} )
raise TypeError, "can't dump anonymous class %s" % self.class
end
end
class Object
yaml_as "tag:ruby.yaml.org,2002:object"
def to_yaml_style; end
def to_yaml_properties; instance_variables.sort; end
def to_yaml( opts = {} )
YAML::quick_emit( object_id, opts ) do |out|
out.map( taguri, to_yaml_style ) do |map|
to_yaml_properties.each do |m|
map.add( m[1..-1], instance_variable_get( m ) )
end
end
end
end
end
class Hash
yaml_as "tag:ruby.yaml.org,2002:hash"
yaml_as "tag:yaml.org,2002:map"
def yaml_initialize( tag, val )
if Array === val
update Hash.[]( *val ) # Convert the map to a sequence
elsif Hash === val
update val
else
raise YAML::TypeError, "Invalid map explicitly tagged #{ tag }: " + val.inspect
end
end
def to_yaml( opts = {} )
YAML::quick_emit( object_id, opts ) do |out|
out.map( taguri, to_yaml_style ) do |map|
each do |k, v|
map.add( k, v )
end
end
end
end
end
class Struct
yaml_as "tag:ruby.yaml.org,2002:struct"
def self.yaml_tag_class_name; self.name.gsub( "Struct::", "" ); end
def self.yaml_tag_read_class( name ); "Struct::#{ name }"; end
def self.yaml_new( klass, tag, val )
if Hash === val
struct_type = nil
#
# Use existing Struct if it exists
#
props = {}
val.delete_if { |k,v| props[k] = v if k =~ /^@/ }
begin
struct_name, struct_type = YAML.read_type_class( tag, Struct )
rescue NameError
end
if not struct_type
struct_def = [ tag.split( ':', 4 ).last ]
struct_type = Struct.new( *struct_def.concat( val.keys.collect { |k| k.intern } ) )
end
#
# Set the Struct properties
#
st = YAML::object_maker( struct_type, {} )
st.members.each do |m|
st.send( "#{m}=", val[m] )
end
props.each do |k,v|
st.instance_variable_set(k, v)
end
st
else
raise YAML::TypeError, "Invalid Ruby Struct: " + val.inspect
end
end
def to_yaml( opts = {} )
YAML::quick_emit( object_id, opts ) do |out|
#
# Basic struct is passed as a YAML map
#
out.map( taguri, to_yaml_style ) do |map|
self.members.each do |m|
map.add( m, self[m] )
end
self.to_yaml_properties.each do |m|
map.add( m, instance_variable_get( m ) )
end
end
end
end
end
class Array
yaml_as "tag:ruby.yaml.org,2002:array"
yaml_as "tag:yaml.org,2002:seq"
def yaml_initialize( tag, val ); concat( val.to_a ); end
def to_yaml( opts = {} )
YAML::quick_emit( object_id, opts ) do |out|
out.seq( taguri, to_yaml_style ) do |seq|
each do |x|
seq.add( x )
end
end
end
end
end
class Exception
yaml_as "tag:ruby.yaml.org,2002:exception"
def Exception.yaml_new( klass, tag, val )
o = YAML.object_maker( klass, { 'mesg' => val.delete( 'message' ) } )
val.each_pair do |k,v|
o.instance_variable_set("@#{k}", v)
end
o
end
def to_yaml( opts = {} )
YAML::quick_emit( object_id, opts ) do |out|
out.map( taguri, to_yaml_style ) do |map|
map.add( 'message', message )
to_yaml_properties.each do |m|
map.add( m[1..-1], instance_variable_get( m ) )
end
end
end
end
end
class String
yaml_as "tag:ruby.yaml.org,2002:string"
yaml_as "tag:yaml.org,2002:binary"
yaml_as "tag:yaml.org,2002:str"
def is_complex_yaml?
to_yaml_style or not to_yaml_properties.empty? or self =~ /\n.+/
end
def is_binary_data?
( self.count( "^ -~", "^\r\n" ) / self.size > 0.3 || self.count( "\x00" ) > 0 ) unless empty?
end
def String.yaml_new( klass, tag, val )
val = val.unpack("m")[0] if tag == "tag:yaml.org,2002:binary"
val = { 'str' => val } if String === val
if Hash === val
s = klass.allocate
# Thank you, NaHi
String.instance_method(:initialize).
bind(s).
call( val.delete( 'str' ) )
val.each { |k,v| s.instance_variable_set( k, v ) }
s
else
raise YAML::TypeError, "Invalid String: " + val.inspect
end
end
def to_yaml( opts = {} )
YAML::quick_emit( is_complex_yaml? ? object_id : nil, opts ) do |out|
if is_binary_data?
out.scalar( "tag:yaml.org,2002:binary", [self].pack("m"), :literal )
elsif to_yaml_properties.empty?
out.scalar( taguri, self, self =~ /^:/ ? :quote2 : to_yaml_style )
else
out.map( taguri, to_yaml_style ) do |map|
map.add( 'str', "#{self}" )
to_yaml_properties.each do |m|
map.add( m, instance_variable_get( m ) )
end
end
end
end
end
end
class Symbol
yaml_as "tag:ruby.yaml.org,2002:symbol"
yaml_as "tag:ruby.yaml.org,2002:sym"
def Symbol.yaml_new( klass, tag, val )
if String === val
val = YAML::load( val ) if val =~ /\A(["']).*\1\z/
val.intern
else
raise YAML::TypeError, "Invalid Symbol: " + val.inspect
end
end
def to_yaml( opts = {} )
YAML::quick_emit( nil, opts ) do |out|
out.scalar( "tag:yaml.org,2002:str", self.inspect, :plain )
end
end
end
class Range
yaml_as "tag:ruby.yaml.org,2002:range"
def Range.yaml_new( klass, tag, val )
inr = %r'(\w+|[+-]?\d+(?:\.\d+)?(?:e[+-]\d+)?|"(?:[^\\"]|\\.)*")'
opts = {}
if String === val and val =~ /^#{inr}(\.{2,3})#{inr}$/o
r1, rdots, r2 = $1, $2, $3
opts = {
'begin' => YAML.load( "--- #{r1}" ),
'end' => YAML.load( "--- #{r2}" ),
'excl' => rdots.length == 3
}
val = {}
elsif Hash === val
opts['begin'] = val.delete('begin')
opts['end'] = val.delete('end')
opts['excl'] = val.delete('excl')
end
if Hash === opts
r = YAML::object_maker( klass, {} )
# Thank you, NaHi
Range.instance_method(:initialize).
bind(r).
call( opts['begin'], opts['end'], opts['excl'] )
val.each { |k,v| r.instance_variable_set( k, v ) }
r
else
raise YAML::TypeError, "Invalid Range: " + val.inspect
end
end
def to_yaml( opts = {} )
YAML::quick_emit( object_id, opts ) do |out|
# if self.begin.is_complex_yaml? or self.begin.respond_to? :to_str or
# self.end.is_complex_yaml? or self.end.respond_to? :to_str or
# not to_yaml_properties.empty?
out.map( taguri, to_yaml_style ) do |map|
map.add( 'begin', self.begin )
map.add( 'end', self.end )
map.add( 'excl', self.exclude_end? )
to_yaml_properties.each do |m|
map.add( m, instance_variable_get( m ) )
end
end
# else
# out.scalar( taguri ) do |sc|
# sc.embed( self.begin )
# sc.concat( self.exclude_end? ? "..." : ".." )
# sc.embed( self.end )
# end
# end
end
end
end
class Regexp
yaml_as "tag:ruby.yaml.org,2002:regexp"
def Regexp.yaml_new( klass, tag, val )
if String === val and val =~ /^\/(.*)\/([mix]*)$/
val = { 'regexp' => $1, 'mods' => $2 }
end
if Hash === val
mods = nil
unless val['mods'].to_s.empty?
mods = 0x00
mods |= Regexp::EXTENDED if val['mods'].include?( 'x' )
mods |= Regexp::IGNORECASE if val['mods'].include?( 'i' )
mods |= Regexp::MULTILINE if val['mods'].include?( 'm' )
end
val.delete( 'mods' )
r = YAML::object_maker( klass, {} )
Regexp.instance_method(:initialize).
bind(r).
call( val.delete( 'regexp' ), mods )
val.each { |k,v| r.instance_variable_set( k, v ) }
r
else
raise YAML::TypeError, "Invalid Regular expression: " + val.inspect
end
end
def to_yaml( opts = {} )
YAML::quick_emit( nil, opts ) do |out|
if to_yaml_properties.empty?
out.scalar( taguri, self.inspect, :plain )
else
out.map( taguri, to_yaml_style ) do |map|
src = self.inspect
if src =~ /\A\/(.*)\/([a-z]*)\Z/
map.add( 'regexp', $1 )
map.add( 'mods', $2 )
else
raise YAML::TypeError, "Invalid Regular expression: " + src
end
to_yaml_properties.each do |m|
map.add( m, instance_variable_get( m ) )
end
end
end
end
end
end
class Time
yaml_as "tag:ruby.yaml.org,2002:time"
yaml_as "tag:yaml.org,2002:timestamp"
def Time.yaml_new( klass, tag, val )
if Hash === val
t = val.delete( 'at' )
val.each { |k,v| t.instance_variable_set( k, v ) }
t
else
raise YAML::TypeError, "Invalid Time: " + val.inspect
end
end
def to_yaml( opts = {} )
YAML::quick_emit( object_id, opts ) do |out|
tz = "Z"
# from the tidy Tobias Peters Thanks!
unless self.utc?
utc_same_instant = self.dup.utc
utc_same_writing = Time.utc(year,month,day,hour,min,sec,usec)
difference_to_utc = utc_same_writing - utc_same_instant
if (difference_to_utc < 0)
difference_sign = '-'
absolute_difference = -difference_to_utc
else
difference_sign = '+'
absolute_difference = difference_to_utc
end
difference_minutes = (absolute_difference/60).round
tz = "%s%02d:%02d" % [ difference_sign, difference_minutes / 60, difference_minutes % 60]
end
standard = self.strftime( "%Y-%m-%d %H:%M:%S" )
standard += ".%06d" % [usec] if usec.nonzero?
standard += " %s" % [tz]
if to_yaml_properties.empty?
out.scalar( taguri, standard, :plain )
else
out.map( taguri, to_yaml_style ) do |map|
map.add( 'at', standard )
to_yaml_properties.each do |m|
map.add( m, instance_variable_get( m ) )
end
end
end
end
end
end
class Date
yaml_as "tag:yaml.org,2002:timestamp#ymd"
def to_yaml( opts = {} )
YAML::quick_emit( object_id, opts ) do |out|
out.scalar( "tag:yaml.org,2002:timestamp", self.to_s, :plain )
end
end
end
class Integer
yaml_as "tag:yaml.org,2002:int"
def to_yaml( opts = {} )
YAML::quick_emit( nil, opts ) do |out|
out.scalar( "tag:yaml.org,2002:int", self.to_s, :plain )
end
end
end
class Float
yaml_as "tag:yaml.org,2002:float"
def to_yaml( opts = {} )
YAML::quick_emit( nil, opts ) do |out|
str = self.to_s
if str == "Infinity"
str = ".Inf"
elsif str == "-Infinity"
str = "-.Inf"
elsif str == "NaN"
str = ".NaN"
end
out.scalar( "tag:yaml.org,2002:float", str, :plain )
end
end
end
class TrueClass
yaml_as "tag:yaml.org,2002:bool#yes"
def to_yaml( opts = {} )
YAML::quick_emit( nil, opts ) do |out|
out.scalar( taguri, "true", :plain )
end
end
end
class FalseClass
yaml_as "tag:yaml.org,2002:bool#no"
def to_yaml( opts = {} )
YAML::quick_emit( nil, opts ) do |out|
out.scalar( taguri, "false", :plain )
end
end
end
class NilClass
yaml_as "tag:yaml.org,2002:null"
def to_yaml( opts = {} )
YAML::quick_emit( nil, opts ) do |out|
out.scalar( taguri, "", :plain )
end
end
end
yecht-0.0.2/ext/ruby/lib/yaml/store.rb 0000664 0000000 0000000 00000000625 11233025100 0017565 0 ustar 00root root 0000000 0000000 #
# YAML::Store
#
require 'yaml'
require 'pstore'
class YAML::Store < PStore
def initialize( *o )
@opt = YAML::DEFAULTS.dup
if String === o.first
super(o.shift)
end
if o.last.is_a? Hash
@opt.update(o.pop)
end
end
def dump(table)
@table.to_yaml(@opt)
end
def load(content)
YAML::load(content)
end
def load_file(file)
YAML::load(file)
end
end
yecht-0.0.2/ext/ruby/lib/yaml/stream.rb 0000664 0000000 0000000 00000001274 11233025100 0017725 0 ustar 00root root 0000000 0000000 module YAML
#
# YAML::Stream -- for emitting many documents
#
class Stream
attr_accessor :documents, :options
def initialize( opts = {} )
@options = opts
@documents = []
end
def []( i )
@documents[ i ]
end
def add( doc )
@documents << doc
end
def edit( doc_num, doc )
@documents[ doc_num ] = doc
end
def emit( io = nil )
# opts = @options.dup
# opts[:UseHeader] = true if @documents.length > 1
out = YAML.emitter
out.reset( io || io2 = StringIO.new )
@documents.each { |v|
v.to_yaml( out )
}
io || ( io2.rewind; io2.read )
end
end
end
yecht-0.0.2/ext/ruby/lib/yaml/stringio.rb 0000664 0000000 0000000 00000003661 11233025100 0020272 0 ustar 00root root 0000000 0000000 #
# Limited StringIO if no core lib is available
#
begin
require 'stringio'
rescue LoadError
# StringIO based on code by MoonWolf
class StringIO
def initialize(string="")
@string=string
@pos=0
@eof=(string.size==0)
end
def pos
@pos
end
def eof
@eof
end
alias eof? eof
def readline(rs=$/)
if @eof
raise EOFError
else
if p = @string[@pos..-1]=~rs
line = @string[@pos,p+1]
else
line = @string[@pos..-1]
end
@pos+=line.size
@eof =true if @pos==@string.size
$_ = line
end
end
def rewind
seek(0,0)
end
def seek(offset,whence)
case whence
when 0
@pos=offset
when 1
@pos+=offset
when 2
@pos=@string.size+offset
end
@eof=(@pos>=@string.size)
0
end
end
#
# Class method for creating streams
#
def YAML.make_stream( io )
if String === io
io = StringIO.new( io )
elsif not IO === io
raise YAML::Error, "YAML stream must be an IO or String object."
end
if YAML::unicode
def io.readline
YAML.utf_to_internal( readline( @ln_sep ), @utf_encoding )
end
def io.check_unicode
@utf_encoding = YAML.sniff_encoding( read( 4 ) )
@ln_sep = YAML.enc_separator( @utf_encoding )
seek( -4, IO::SEEK_CUR )
end
def io.utf_encoding
@utf_encoding
end
io.check_unicode
else
def io.utf_encoding
:None
end
end
io
end
end
yecht-0.0.2/ext/ruby/lib/yaml/tag.rb 0000664 0000000 0000000 00000006044 11233025100 0017205 0 ustar 00root root 0000000 0000000 # -*- mode: ruby; ruby-indent-level: 4; tab-width: 4 -*- vim: sw=4 ts=4
# $Id$
#
# = yaml/tag.rb: methods for associating a taguri to a class.
#
# Author:: why the lucky stiff
#
module YAML
# A dictionary of taguris which map to
# Ruby classes.
@@tagged_classes = {}
#
# Associates a taguri _tag_ with a Ruby class _cls_. The taguri is used to give types
# to classes when loading YAML. Taguris are of the form:
#
# tag:authorityName,date:specific
#
# The +authorityName+ is a domain name or email address. The +date+ is the date the type
# was issued in YYYY or YYYY-MM or YYYY-MM-DD format. The +specific+ is a name for
# the type being added.
#
# For example, built-in YAML types have 'yaml.org' as the +authorityName+ and '2002' as the
# +date+. The +specific+ is simply the name of the type:
#
# tag:yaml.org,2002:int
# tag:yaml.org,2002:float
# tag:yaml.org,2002:timestamp
#
# The domain must be owned by you on the +date+ declared. If you don't own any domains on the
# date you declare the type, you can simply use an e-mail address.
#
# tag:why@ruby-lang.org,2004:notes/personal
#
def YAML.tag_class( tag, cls )
if @@tagged_classes.has_key? tag
warn "class #{ @@tagged_classes[tag] } held ownership of the #{ tag } tag"
end
@@tagged_classes[tag] = cls
end
# Returns the complete dictionary of taguris, paired with classes. The key for
# the dictionary is the full taguri. The value for each key is the class constant
# associated to that taguri.
#
# YAML.tagged_classes["tag:yaml.org,2002:int"] => Integer
#
def YAML.tagged_classes
@@tagged_classes
end
end
class Module # :nodoc: all
# Adds a taguri _tag_ to a class, used when dumping or loading the class
# in YAML. See YAML::tag_class for detailed information on typing and
# taguris.
def yaml_as( tag, sc = true )
verbose, $VERBOSE = $VERBOSE, nil
class_eval <<-"end;", __FILE__, __LINE__+1
attr_writer :taguri
def taguri
if respond_to? :to_yaml_type
YAML::tagurize( to_yaml_type[1..-1] )
else
return @taguri if defined?(@taguri) and @taguri
tag = #{ tag.dump }
if self.class.yaml_tag_subclasses? and self.class != YAML::tagged_classes[tag]
tag = "\#{ tag }:\#{ self.class.yaml_tag_class_name }"
end
tag
end
end
def self.yaml_tag_subclasses?; #{ sc ? 'true' : 'false' }; end
end;
YAML::tag_class tag, self
ensure
$VERBOSE = verbose
end
# Transforms the subclass name into a name suitable for display
# in a subclassed tag.
def yaml_tag_class_name
self.name
end
# Transforms the subclass name found in the tag into a Ruby
# constant name.
def yaml_tag_read_class( name )
name
end
end
yecht-0.0.2/ext/ruby/lib/yaml/types.rb 0000664 0000000 0000000 00000012020 11233025100 0017565 0 ustar 00root root 0000000 0000000 # -*- mode: ruby; ruby-indent-level: 4 -*- vim: sw=4
#
# Classes required by the full core typeset
#
require 'yaml/compat'
module YAML
#
# Default private type
#
class PrivateType
def self.tag_subclasses?; false; end
attr_accessor :type_id, :value
verbose, $VERBOSE = $VERBOSE, nil
def initialize( type, val )
@type_id = type; @value = val
@value.taguri = "x-private:#{ @type_id }"
end
def to_yaml( opts = {} )
@value.to_yaml( opts )
end
ensure
$VERBOSE = verbose
end
#
# Default domain type
#
class DomainType
def self.tag_subclasses?; false; end
attr_accessor :domain, :type_id, :value
verbose, $VERBOSE = $VERBOSE, nil
def initialize( domain, type, val )
@domain = domain; @type_id = type; @value = val
@value.taguri = "tag:#{ @domain }:#{ @type_id }"
end
def to_yaml( opts = {} )
@value.to_yaml( opts )
end
ensure
$VERBOSE = verbose
end
#
# Unresolved objects
#
class Object
def self.tag_subclasses?; false; end
def to_yaml( opts = {} )
YAML::quick_emit( object_id, opts ) do |out|
out.map( "tag:ruby.yaml.org,2002:object:#{ @class }", to_yaml_style ) do |map|
@ivars.each do |k,v|
map.add( k, v )
end
end
end
end
end
#
# YAML Hash class to support comments and defaults
#
class SpecialHash < ::Hash
attr_accessor :default
def inspect
self.default.to_s
end
def to_s
self.default.to_s
end
def update( h )
if YAML::SpecialHash === h
@default = h.default if h.default
end
super( h )
end
def to_yaml( opts = {} )
opts[:DefaultKey] = self.default
super( opts )
end
end
#
# Builtin collection: !omap
#
class Omap < ::Array
yaml_as "tag:yaml.org,2002:omap"
def yaml_initialize( tag, val )
if Array === val
val.each do |v|
if Hash === v
concat( v.to_a ) # Convert the map to a sequence
else
raise YAML::Error, "Invalid !omap entry: " + val.inspect
end
end
else
raise YAML::Error, "Invalid !omap: " + val.inspect
end
self
end
def self.[]( *vals )
o = Omap.new
0.step( vals.length - 1, 2 ) do |i|
o[vals[i]] = vals[i+1]
end
o
end
def []( k )
self.assoc( k ).to_a[1]
end
def []=( k, *rest )
val, set = rest.reverse
if ( tmp = self.assoc( k ) ) and not set
tmp[1] = val
else
self << [ k, val ]
end
val
end
def has_key?( k )
self.assoc( k ) ? true : false
end
def is_complex_yaml?
true
end
def to_yaml( opts = {} )
YAML::quick_emit( self.object_id, opts ) do |out|
out.seq( taguri, to_yaml_style ) do |seq|
self.each do |v|
seq.add( Hash[ *v ] )
end
end
end
end
end
#
# Builtin collection: !pairs
#
class Pairs < ::Array
yaml_as "tag:yaml.org,2002:pairs"
def yaml_initialize( tag, val )
if Array === val
val.each do |v|
if Hash === v
concat( v.to_a ) # Convert the map to a sequence
else
raise YAML::Error, "Invalid !pairs entry: " + val.inspect
end
end
else
raise YAML::Error, "Invalid !pairs: " + val.inspect
end
self
end
def self.[]( *vals )
p = Pairs.new
0.step( vals.length - 1, 2 ) { |i|
p[vals[i]] = vals[i+1]
}
p
end
def []( k )
self.assoc( k ).to_a
end
def []=( k, val )
self << [ k, val ]
val
end
def has_key?( k )
self.assoc( k ) ? true : false
end
def is_complex_yaml?
true
end
def to_yaml( opts = {} )
YAML::quick_emit( self.object_id, opts ) do |out|
out.seq( taguri, to_yaml_style ) do |seq|
self.each do |v|
seq.add( Hash[ *v ] )
end
end
end
end
end
#
# Builtin collection: !set
#
class Set < ::Hash
yaml_as "tag:yaml.org,2002:set"
end
end
yecht-0.0.2/ext/ruby/lib/yaml/yamlnode.rb 0000664 0000000 0000000 00000002300 11233025100 0020231 0 ustar 00root root 0000000 0000000 #
# YAML::YamlNode class
#
require 'yaml/basenode'
module YAML
#
# YAML Generic Model container
#
class YamlNode
include BaseNode
attr_accessor :kind, :type_id, :value, :anchor
def initialize( t, v )
@type_id = t
if Hash === v
@kind = 'map'
@value = {}
v.each { |k,v|
@value[ k.transform ] = [ k, v ]
}
elsif Array === v
@kind = 'seq'
@value = v
elsif String === v
@kind = 'scalar'
@value = v
end
end
#
# Transform this node fully into a native type
#
def transform
t = nil
if @value.is_a? Hash
t = {}
@value.each { |k,v|
t[ k ] = v[1].transform
}
elsif @value.is_a? Array
t = []
@value.each { |v|
t.push v.transform
}
else
t = @value
end
YAML.transfer_method( @type_id, t )
end
end
end
yecht-0.0.2/ext/ruby/lib/yaml/yecht.rb 0000664 0000000 0000000 00000000423 11233025100 0017541 0 ustar 00root root 0000000 0000000 #
# YAML::Yecht module
# .. glues yecht and yaml.rb together ..
#
require 'yecht'
require 'yaml/basenode'
module YAML
module Yecht
#
# Mixin BaseNode functionality
#
class Node
include YAML::BaseNode
end
end
end
yecht-0.0.2/ext/ruby/lib/yaml/ypath.rb 0000664 0000000 0000000 00000002460 11233025100 0017555 0 ustar 00root root 0000000 0000000 #
# YAML::YPath
#
module YAML
class YPath
attr_accessor :segments, :predicates, :flags
def initialize( str )
@segments = []
@predicates = []
@flags = nil
while str =~ /^\/?(\/|[^\/\[]+)(?:\[([^\]]+)\])?/
@segments.push $1
@predicates.push $2
str = $'
end
unless str.to_s.empty?
@segments += str.split( "/" )
end
if @segments.length == 0
@segments.push "."
end
end
def YPath.each_path( str )
#
# Find choices
#
paths = []
str = "(#{ str })"
while str.sub!( /\(([^()]+)\)/, "\n#{ paths.length }\n" )
paths.push $1.split( '|' )
end
#
# Construct all possible paths
#
all = [ str ]
( paths.length - 1 ).downto( 0 ) do |i|
all = all.collect do |a|
paths[i].collect do |p|
a.gsub( /\n#{ i }\n/, p )
end
end.flatten.uniq
end
all.collect do |path|
yield YPath.new( path )
end
end
end
end
yecht-0.0.2/ext/ruby/src/ 0000775 0000000 0000000 00000000000 11233025100 0015160 5 ustar 00root root 0000000 0000000 yecht-0.0.2/ext/ruby/src/java/ 0000775 0000000 0000000 00000000000 11233025100 0016101 5 ustar 00root root 0000000 0000000 yecht-0.0.2/ext/ruby/src/java/YechtService.java 0000664 0000000 0000000 00000011217 11233025100 0021343 0 ustar 00root root 0000000 0000000
import java.io.IOException;
import org.jruby.Ruby;
import org.jruby.RubyClass;
import org.jruby.RubyModule;
import org.jruby.runtime.ThreadContext;
import org.jruby.runtime.builtin.IRubyObject;
import org.jruby.runtime.load.BasicLibraryService;
import org.yecht.YAML;
import org.yecht.ruby.*;
public class YechtService implements BasicLibraryService {
public boolean basicLoad(final Ruby runtime) throws IOException {
ThreadContext ctx = runtime.getCurrentContext();
RubyModule rb_yaml = runtime.getOrCreateModule("YAML");
RubyModule rb_yecht = rb_yaml.defineModuleUnder("Yecht");
rb_yecht.defineConstant("VERSION", runtime.newString(YAML.YECHT_VERSION));
rb_yecht.defineAnnotatedMethods(Module.class);
RubyClass cResolver = rb_yecht.defineClassUnder("Resolver", runtime.getObject(), runtime.getObject().getAllocator());
cResolver.defineAnnotatedMethods(Resolver.class);
cResolver.addReadWriteAttribute(ctx, "tags");
IRubyObject oDefaultResolver = cResolver.callMethod(ctx, "new");
oDefaultResolver.getSingletonClass().defineAnnotatedMethods(DefaultResolver.class);
rb_yecht.defineConstant("DefaultResolver", oDefaultResolver);
IRubyObject oGenericResolver = cResolver.callMethod(ctx, "new");
oGenericResolver.getSingletonClass().defineAnnotatedMethods(GenericResolver.class);
rb_yecht.defineConstant("GenericResolver", oGenericResolver);
RubyClass cParser = rb_yecht.defineClassUnder("Parser", runtime.getObject(), YParser.Allocator);
cParser.defineAnnotatedMethods(YParser.class);
cParser.addReadWriteAttribute(ctx, "options");
cParser.addReadWriteAttribute(ctx, "resolver");
cParser.addReadWriteAttribute(ctx, "input");
RubyClass cNode = rb_yecht.defineClassUnder("Node", runtime.getObject(), Node.Allocator);
cNode.defineAnnotatedMethods(Node.class);
cNode.addReadWriteAttribute(ctx, "emitter");
cNode.addReadWriteAttribute(ctx, "resolver");
cNode.addReadAttribute(ctx, "kind");
cNode.addReadAttribute(ctx, "type_id");
cNode.addReadAttribute(ctx, "kind");
cNode.addReadAttribute(ctx, "value");
RubyClass cScalar = rb_yecht.defineClassUnder("Scalar", cNode, Scalar.Allocator);
cScalar.defineAnnotatedMethods(Scalar.class);
cScalar.addReadAttribute(ctx, "value");
RubyClass cSeq = rb_yecht.defineClassUnder("Seq", cNode, Seq.Allocator);
cSeq.defineAnnotatedMethods(Seq.class);
RubyClass cMap = rb_yecht.defineClassUnder("Map", cNode, Map.Allocator);
cMap.defineAnnotatedMethods(Map.class);
RubyClass cPrivateType = rb_yecht.defineClassUnder("PrivateType", runtime.getObject(), runtime.getObject().getAllocator());
cPrivateType.defineAnnotatedMethods(PrivateType.class);
cPrivateType.addReadWriteAttribute(ctx, "type_id");
cPrivateType.addReadWriteAttribute(ctx, "value");
RubyClass cDomainType = rb_yecht.defineClassUnder("DomainType", runtime.getObject(), runtime.getObject().getAllocator());
cDomainType.defineAnnotatedMethods(DomainType.class);
cDomainType.addReadWriteAttribute(ctx, "domain");
cDomainType.addReadWriteAttribute(ctx, "type_id");
cDomainType.addReadWriteAttribute(ctx, "value");
RubyClass cYObject = rb_yaml.defineClassUnder("Object", runtime.getObject(), runtime.getObject().getAllocator());
cYObject.defineAnnotatedMethods(YObject.class);
cYObject.addReadWriteAttribute(ctx, "class");
cYObject.addReadWriteAttribute(ctx, "ivars");
RubyClass cBadAlias = rb_yecht.defineClassUnder("BadAlias", runtime.getObject(), BadAlias.Allocator);
cBadAlias.defineAnnotatedMethods(BadAlias.class);
cBadAlias.addReadWriteAttribute(ctx, "name");
cBadAlias.includeModule(runtime.getComparable());
rb_yecht.defineClassUnder("MergeKey", runtime.getObject(), runtime.getObject().getAllocator());
rb_yecht.defineClassUnder("DefaultKey", runtime.getObject(), runtime.getObject().getAllocator());
RubyClass cOut = rb_yecht.defineClassUnder("Out", runtime.getObject(), runtime.getObject().getAllocator());
cOut.defineAnnotatedMethods(Out.class);
cOut.addReadWriteAttribute(ctx, "emitter");
RubyClass cEmitter = rb_yecht.defineClassUnder("Emitter", runtime.getObject(), YEmitter.Allocator);
cEmitter.defineAnnotatedMethods(YEmitter.class);
cEmitter.addReadWriteAttribute(ctx, "level");
oGenericResolver.dataWrapStruct(new GenericResolver.Extra(runtime));
rb_yaml.dataWrapStruct(new YAMLExtra(runtime));
return true;
}
}
yecht-0.0.2/ext/ruby/src/java/org/ 0000775 0000000 0000000 00000000000 11233025100 0016670 5 ustar 00root root 0000000 0000000 yecht-0.0.2/ext/ruby/src/java/org/yecht/ 0000775 0000000 0000000 00000000000 11233025100 0020004 5 ustar 00root root 0000000 0000000 yecht-0.0.2/ext/ruby/src/java/org/yecht/ruby/ 0000775 0000000 0000000 00000000000 11233025100 0020765 5 ustar 00root root 0000000 0000000 yecht-0.0.2/ext/ruby/src/java/org/yecht/ruby/ArrayStorageLink.java 0000664 0000000 0000000 00000001065 11233025100 0025053 0 ustar 00root root 0000000 0000000 package org.yecht.ruby;
import org.jruby.RubyArray;
import org.jruby.runtime.builtin.IRubyObject;
class ArrayStorageLink extends StorageLink {
private final RubyArray array;
private final int index;
private final IRubyObject originalObject;
public ArrayStorageLink(IRubyObject arr, int index, IRubyObject originalObject) {
this.array = (RubyArray)arr;
this.index = index;
this.originalObject = originalObject;
}
public void replaceLinkWith(IRubyObject newObject) {
array.store(index, newObject);
}
}
yecht-0.0.2/ext/ruby/src/java/org/yecht/ruby/BadAlias.java 0000664 0000000 0000000 00000003155 11233025100 0023274 0 ustar 00root root 0000000 0000000 package org.yecht.ruby;
import java.util.List;
import java.util.LinkedList;
import org.jruby.Ruby;
import org.jruby.RubyClass;
import org.jruby.RubyObject;
import org.jruby.anno.JRubyMethod;
import org.jruby.runtime.ObjectAllocator;
import org.jruby.runtime.builtin.IRubyObject;
public class BadAlias extends RubyObject implements PossibleLinkNode {
public static final ObjectAllocator Allocator = new ObjectAllocator() {
public IRubyObject allocate(Ruby runtime, RubyClass klass) {
return new BadAlias(runtime, klass);
}
};
public BadAlias(Ruby runtime, RubyClass metaClass) {
super(runtime, metaClass);
}
private List links = new LinkedList();
public void addLink(StorageLink link) {
links.add(link);
}
public void replaceLinks(IRubyObject newObject) {
for(StorageLink sl : links) {
sl.replaceLinkWith(newObject);
}
links.clear();
}
// syck_badalias_initialize
@JRubyMethod
public static IRubyObject initialize(IRubyObject self, IRubyObject val) {
((RubyObject)self).fastSetInstanceVariable("@name", val);
return self;
}
// syck_badalias_cmp
@JRubyMethod(name = "<=>")
public static IRubyObject cmp(IRubyObject alias1, IRubyObject alias2) {
IRubyObject str1 = (IRubyObject)((RubyObject)alias1).fastGetInstanceVariable("@name");
IRubyObject str2 = (IRubyObject)((RubyObject)alias2).fastGetInstanceVariable("@name");
return str1.callMethod(alias1.getRuntime().getCurrentContext(), "<=>", str2);
}
}
yecht-0.0.2/ext/ruby/src/java/org/yecht/ruby/DefaultResolver.java 0000664 0000000 0000000 00000050531 11233025100 0024742 0 ustar 00root root 0000000 0000000 package org.yecht.ruby;
import java.util.List;
import java.util.LinkedList;
import java.util.Map;
import java.util.HashMap;
import org.yecht.BadAnchorHandler;
import org.yecht.BytecodeNodeHandler;
import org.yecht.Bytestring;
import org.yecht.Data;
import org.yecht.Emitter;
import org.yecht.EmitterHandler;
import org.yecht.ErrorHandler;
import org.yecht.IoStrRead;
import org.yecht.JechtIO;
import org.yecht.MapPart;
import org.yecht.NodeHandler;
import org.yecht.Parser;
import org.yecht.ParserInput;
import org.yecht.OutputHandler;
import org.yecht.Pointer;
import org.yecht.ImplicitScanner;
import org.yecht.ImplicitScanner2;
import org.yecht.MapStyle;
import org.yecht.SeqStyle;
import org.yecht.ScalarStyle;
import org.jruby.Ruby;
import org.jruby.RubyArray;
import org.jruby.RubyClass;
import org.jruby.RubyEnumerable;
import org.jruby.RubyHash;
import org.jruby.RubyKernel;
import org.jruby.RubyModule;
import org.jruby.RubyNumeric;
import org.jruby.RubyObject;
import org.jruby.RubyString;
import org.jruby.anno.JRubyMethod;
import org.jruby.runtime.Block;
import org.jruby.runtime.BlockCallback;
import org.jruby.runtime.ThreadContext;
import org.jruby.runtime.builtin.IRubyObject;
import org.jruby.runtime.ObjectAllocator;
import org.jruby.util.ByteList;
import org.jruby.util.TypeConverter;
public class DefaultResolver {
private static int extractInt(byte[] buff, int p, int pend) {
int len = 0;
while((p+len) < pend && Character.isDigit((char)buff[p+len])) {
len++;
}
try {
return Integer.parseInt(new String(buff, p, len, "ISO-8859-1"));
} catch(java.io.UnsupportedEncodingException e) {return -1;}
}
// rb_syck_mktime
public static IRubyObject makeTime(Ruby runtime, Pointer str, int len) {
// System.err.println("makeTime(" + new String(str.buffer, str.start, len) + ")");
int ptr = str.start;
int pend = ptr + len;
IRubyObject year = runtime.newFixnum(0);
IRubyObject mon = runtime.newFixnum(0);
IRubyObject day = runtime.newFixnum(0);
IRubyObject hour = runtime.newFixnum(0);
IRubyObject min = runtime.newFixnum(0);
IRubyObject sec = runtime.newFixnum(0);
long usec = 0;
if(str.buffer[ptr] != 0 && ptr < pend) {
year = runtime.newFixnum(extractInt(str.buffer, ptr, pend));
}
ptr += 4;
if(str.buffer[ptr] != 0 && ptr < pend) {
while(!Character.isDigit((char)str.buffer[ptr]) && ptr < pend) ptr++;
mon = runtime.newFixnum(extractInt(str.buffer, ptr, pend));
}
ptr += 2;
if(str.buffer[ptr] != 0 && ptr < pend) {
while(!Character.isDigit((char)str.buffer[ptr]) && ptr < pend) ptr++;
day = runtime.newFixnum(extractInt(str.buffer, ptr, pend));
}
ptr += 2;
if(str.buffer[ptr] != 0 && ptr < pend) {
while(!Character.isDigit((char)str.buffer[ptr]) && ptr < pend) ptr++;
hour = runtime.newFixnum(extractInt(str.buffer, ptr, pend));
}
ptr += 2;
if(str.buffer[ptr] != 0 && ptr < pend) {
while(!Character.isDigit((char)str.buffer[ptr]) && ptr < pend) ptr++;
min = runtime.newFixnum(extractInt(str.buffer, ptr, pend));
}
ptr += 2;
if(str.buffer[ptr] != 0 && ptr < pend) {
while(!Character.isDigit((char)str.buffer[ptr]) && ptr < pend) ptr++;
sec = runtime.newFixnum(extractInt(str.buffer, ptr, pend));
}
ptr += 2;
if(ptr < pend && str.buffer[ptr] == '.') {
int end = ptr + 1;
while(Character.isDigit((char)str.buffer[end]) && end < pend) end++;
byte[] padded = new byte[]{'0', '0', '0', '0', '0', '0'};
System.arraycopy(str.buffer, ptr+1, padded, 0, end - (ptr+1));
try {
usec = Long.parseLong(new String(padded, 0, 6, "ISO-8859-1"));
} catch(java.io.UnsupportedEncodingException e) {}
} else {
usec = 0;
}
while(ptr < pend && str.buffer[ptr] != 'Z' && str.buffer[ptr] != '+' && str.buffer[ptr] != '-' && str.buffer[ptr] != 0) {
ptr++;
}
if(ptr < pend && (str.buffer[ptr] == '-' || str.buffer[ptr] == '+')) {
int lenx = 1;
while(ptr+lenx < pend && Character.isDigit((char)str.buffer[ptr+lenx])) {
lenx++;
}
if(str.buffer[ptr] == '+') {
ptr++;
lenx--;
}
try {
long tz_offset = Long.parseLong(new String(str.buffer, ptr, lenx, "ISO-8859-1")) * 3600;
ptr+=lenx;
while(ptr < pend && str.buffer[ptr] != ':' && str.buffer[ptr] != 0 ) {
ptr++;
}
if(ptr < pend && str.buffer[ptr] == ':') {
ptr++;
if(tz_offset < 0) {
tz_offset -= extractInt(str.buffer, ptr, pend) * 60;
} else {
tz_offset += extractInt(str.buffer, ptr, pend) * 60;
}
}
IRubyObject time = runtime.getClass("Time").callMethod(runtime.getCurrentContext(), "utc", new IRubyObject[]{year,mon,day,hour,min,sec});
long tmp = RubyNumeric.num2long(time.callMethod(runtime.getCurrentContext(), "to_i")) - tz_offset;
return runtime.getClass("Time").callMethod(runtime.getCurrentContext(), "at", new IRubyObject[]{runtime.newFixnum(tmp), runtime.newFixnum(usec)});
} catch(java.io.UnsupportedEncodingException e) {}
} else {
// Make UTC time
return runtime.getClass("Time").callMethod(runtime.getCurrentContext(), "utc", new IRubyObject[]{year,mon,day,hour,min,sec,runtime.newFixnum(usec)});
}
System.err.println("oopsie, returning null");
return null;
}
private static interface ObjectCreator {
IRubyObject create(Ruby runtime, org.yecht.Node n, Data.Str ds) throws java.io.UnsupportedEncodingException;
}
private static Map scalarTypes = new HashMap();
static {
scalarTypes.put("null", new ObjectCreator() {
public IRubyObject create(Ruby runtime, org.yecht.Node n, Data.Str ds) {
return runtime.getNil();
}
});
scalarTypes.put("binary", new ObjectCreator() {
public IRubyObject create(Ruby runtime, org.yecht.Node n, Data.Str ds) {
ThreadContext ctx = runtime.getCurrentContext();
IRubyObject obj = RubyString.newStringShared(runtime, ds.ptr.buffer, ds.ptr.start, ds.len);
obj.callMethod(ctx, "tr!", new IRubyObject[]{runtime.newString("\n\t "), runtime.newString("")});
IRubyObject arr = obj.callMethod(ctx, "unpack", runtime.newString("m"));
return ((RubyArray)arr).shift(ctx);
}
});
scalarTypes.put("bool#yes", new ObjectCreator() {
public IRubyObject create(Ruby runtime, org.yecht.Node n, Data.Str ds) {
return runtime.getTrue();
}
});
scalarTypes.put("bool#no", new ObjectCreator() {
public IRubyObject create(Ruby runtime, org.yecht.Node n, Data.Str ds) {
return runtime.getFalse();
}
});
scalarTypes.put("int#hex", new ObjectCreator() {
public IRubyObject create(Ruby runtime, org.yecht.Node n, Data.Str ds) {
n.strBlowAwayCommas();
return RubyNumeric.str2inum(runtime, RubyString.newStringShared(runtime, ds.ptr.buffer, ds.ptr.start, ds.len), 16, true);
}
});
scalarTypes.put("int#oct", new ObjectCreator() {
public IRubyObject create(Ruby runtime, org.yecht.Node n, Data.Str ds) {
n.strBlowAwayCommas();
return RubyNumeric.str2inum(runtime, RubyString.newStringShared(runtime, ds.ptr.buffer, ds.ptr.start, ds.len), 8, true);
}
});
scalarTypes.put("int#base60", new ObjectCreator() {
public IRubyObject create(Ruby runtime, org.yecht.Node n, Data.Str ds) throws java.io.UnsupportedEncodingException {
long sixty = 1;
long total = 0;
n.strBlowAwayCommas();
int ptr = ds.ptr.start;
int end = ptr + ds.len;
while(end > ptr) {
long bnum = 0;
int colon = end - 1;
while(colon >= ptr && ds.ptr.buffer[colon] != ':' ) {
colon--;
}
bnum = Integer.parseInt(new String(ds.ptr.buffer, colon+1, end-(colon+1), "ISO-8859-1"));
total += bnum * sixty;
sixty *= 60;
end = colon;
}
return runtime.newFixnum(total);
}
});
scalarTypes.put("float#base60", new ObjectCreator() {
public IRubyObject create(Ruby runtime, org.yecht.Node n, Data.Str ds) throws java.io.UnsupportedEncodingException {
long sixty = 1;
double total = 0.0;
n.strBlowAwayCommas();
int ptr = ds.ptr.start;
int end = ptr + ds.len;
while(end > ptr) {
double bnum = 0;
int colon = end - 1;
while(colon >= ptr && ds.ptr.buffer[colon] != ':' ) {
colon--;
}
bnum = Double.parseDouble(new String(ds.ptr.buffer, colon+1, end-(colon+1), "ISO-8859-1"));
total += bnum * sixty;
sixty *= 60;
end = colon;
}
return runtime.newFloat(total);
}
});
scalarTypes.put("float#nan", new ObjectCreator() {
public IRubyObject create(Ruby runtime, org.yecht.Node n, Data.Str ds) {
return runtime.newFloat(Double.NaN);
}
});
scalarTypes.put("float#inf", new ObjectCreator() {
public IRubyObject create(Ruby runtime, org.yecht.Node n, Data.Str ds) {
return runtime.newFloat(Double.POSITIVE_INFINITY);
}
});
scalarTypes.put("float#neginf", new ObjectCreator() {
public IRubyObject create(Ruby runtime, org.yecht.Node n, Data.Str ds) {
return runtime.newFloat(Double.NEGATIVE_INFINITY);
}
});
scalarTypes.put("timestamp#iso8601", new ObjectCreator() {
public IRubyObject create(Ruby runtime, org.yecht.Node n, Data.Str ds) {
return makeTime(runtime, ds.ptr, ds.len);
}
});
scalarTypes.put("timestamp#spaced", new ObjectCreator() {
public IRubyObject create(Ruby runtime, org.yecht.Node n, Data.Str ds) {
return makeTime(runtime, ds.ptr, ds.len);
}
});
scalarTypes.put("timestamp#ymd", new ObjectCreator() {
public IRubyObject create(Ruby runtime, org.yecht.Node n, Data.Str ds) throws java.io.UnsupportedEncodingException {
IRubyObject year = runtime.newFixnum(Integer.parseInt(new String(ds.ptr.buffer, 0, 4, "ISO-8859-1")));
IRubyObject mon = runtime.newFixnum(Integer.parseInt(new String(ds.ptr.buffer, 5, 2, "ISO-8859-1")));
IRubyObject day = runtime.newFixnum(Integer.parseInt(new String(ds.ptr.buffer, 8, 2, "ISO-8859-1")));
RubyKernel.require(runtime.getTopSelf(), runtime.newString("date"), Block.NULL_BLOCK);
return runtime.getClass("Date").callMethod(runtime.getCurrentContext(), "new", new IRubyObject[] {year, mon, day});
}
});
scalarTypes.put("str", new ObjectCreator() {
public IRubyObject create(Ruby runtime, org.yecht.Node n, Data.Str ds) {
return RubyString.newStringShared(runtime, ds.ptr.buffer, ds.ptr.start, ds.len);
}
});
}
private static boolean handleScalar(Ruby runtime, org.yecht.Node n, String type_id, IRubyObject[] ref, YAMLExtra x) throws java.io.UnsupportedEncodingException {
Data.Str ds = (Data.Str)n.data;
ThreadContext ctx = runtime.getCurrentContext();
boolean transferred = true;
IRubyObject obj = null;
if(type_id == null) {
obj = RubyString.newStringShared(runtime, ds.ptr.buffer, ds.ptr.start, ds.len);
} else {
if(ds.style == ScalarStyle.Plain && ds.len > 1 && ds.ptr.buffer[ds.ptr.start] == ':') {
obj = x.DefaultResolver.callMethod(ctx, "transfer",
new IRubyObject[]{runtime.newString("tag:ruby.yaml.org,2002:sym"),
RubyString.newStringShared(runtime, ds.ptr.buffer, ds.ptr.start+1, ds.len-1)
});
} else {
ObjectCreator oc = scalarTypes.get(type_id);
if(oc != null) {
obj = oc.create(runtime, n, ds);
} else {
if(type_id.startsWith("int")) {
n.strBlowAwayCommas();
obj = RubyNumeric.str2inum(runtime, RubyString.newStringShared(runtime, ds.ptr.buffer, ds.ptr.start, ds.len), 10, true);
} else if(type_id.startsWith("float")) {
n.strBlowAwayCommas();
obj = RubyString.newStringShared(runtime, ds.ptr.buffer, ds.ptr.start, ds.len);
obj = obj.callMethod(ctx, "to_f");
} else if(type_id.startsWith("timestamp")) {
obj = makeTime(runtime, ds.ptr, ds.len);
} else if(type_id.startsWith("merge")) {
obj = x.MergeKey.callMethod(ctx, "new");
} else if(type_id.startsWith("default")) {
obj = x.DefaultKey.callMethod(ctx, "new");
} else {
transferred = false;
obj = RubyString.newStringShared(runtime, ds.ptr.buffer, ds.ptr.start, ds.len);
}
}
}
}
ref[0] = obj;
return transferred;
}
public static boolean handleSeq(Ruby runtime, org.yecht.Node n, String type_id, IRubyObject[] ref) {
boolean transferred = type_id == null || "seq".equals(type_id);
Data.Seq dl = (Data.Seq)n.data;
Object[] items = dl.items;
RubyArray obj = RubyArray.newArray(runtime, dl.idx);
for(int i = 0; i < dl.idx; i++) {
IRubyObject _obj = (IRubyObject)items[i];
if(_obj instanceof PossibleLinkNode) {
((PossibleLinkNode)_obj).addLink(new ArrayStorageLink(obj, i, _obj));
}
obj.store(i, _obj);
}
ref[0] = obj;
return transferred;
}
public static boolean handleMap(final Ruby runtime, org.yecht.Node n, String type_id, IRubyObject[] ref, YAMLExtra x) {
boolean transferred = type_id == null || "map".equals(type_id);
ThreadContext ctx = runtime.getCurrentContext();
Data.Map dm = (Data.Map)n.data;
Object[] keys = dm.keys;
Object[] vals = dm.values;
RubyHash obj = RubyHash.newHash(runtime);
RubyClass cMergeKey = x.MergeKey;
RubyClass cDefaultKey = x.DefaultKey;
for(int i = 0; i < dm.idx; i++) {
IRubyObject k = (IRubyObject)keys[i];
IRubyObject v = (IRubyObject)vals[i];
if(null == v) {
v = runtime.getNil();
}
boolean skip_aset = false;
if(cMergeKey.isInstance(k)) {
IRubyObject tmp = null;
if(!(tmp = TypeConverter.convertToTypeWithCheck(v, runtime.getHash(), "to_hash")).isNil()) {
RubyHash dup = (RubyHash)v.callMethod(ctx, "dup");
dup.callMethod(ctx, "update", obj);
obj = dup;
skip_aset = true;
} else if(!(tmp = v.checkArrayType()).isNil()) {
IRubyObject end = ((RubyArray)tmp).pop(ctx);
IRubyObject tmph = TypeConverter.convertToTypeWithCheck(end, runtime.getHash(), "to_hash");
if(!tmph.isNil()) {
final RubyHash dup = (RubyHash)tmph.callMethod(ctx, "dup");
tmp = ((RubyArray)tmp).reverse();
((RubyArray)tmp).append(obj);
RubyEnumerable.callEach(runtime, ctx, tmp, new BlockCallback() {
// syck_merge_i
public IRubyObject call(ThreadContext _ctx, IRubyObject[] largs, Block blk) {
IRubyObject entry = largs[0];
IRubyObject tmp = null;
if(!(tmp = TypeConverter.convertToTypeWithCheck(entry, runtime.getHash(), "to_hash")).isNil()) {
dup.callMethod(_ctx, "update", tmp);
}
return runtime.getNil();
}
});
obj = dup;
skip_aset = true;
}
}
} else if(cDefaultKey.isInstance(k)) {
obj.callMethod(ctx, "default=", v);
skip_aset = true;
}
if(!skip_aset) {
if(v instanceof PossibleLinkNode) {
((PossibleLinkNode)v).addLink(new HashStorageLink(obj, k, v));
}
obj.fastASet(k, v);
}
}
ref[0] = obj;
return transferred;
}
// yaml_org_handler
public static boolean orgHandler(IRubyObject self, org.yecht.Node n, IRubyObject[] ref, YAMLExtra x) {
final Ruby runtime = self.getRuntime();
String type_id = n.type_id;
boolean transferred = false;
if(type_id != null && type_id.startsWith("tag:yaml.org,2002:")) {
type_id = type_id.substring(18);
}
try {
switch(n.kind) {
case Str:
transferred = handleScalar(runtime, n, type_id, ref, x);
break;
case Seq:
transferred = handleSeq(runtime, n, type_id, ref);
break;
case Map:
transferred = handleMap(runtime, n, type_id, ref, x);
break;
}
} catch(java.io.UnsupportedEncodingException e) {}
return transferred;
}
// syck_defaultresolver_node_import
@JRubyMethod
public static IRubyObject node_import(IRubyObject self, IRubyObject node) {
// System.err.println("syck_defaultresolver_node_import()");
org.yecht.Node n = (org.yecht.Node)node.dataGetStructChecked();
IRubyObject[] _obj = new IRubyObject[]{null};
if(!orgHandler(self, n, _obj, ((Node)node).x)) {
_obj[0] = self.callMethod(self.getRuntime().getCurrentContext(), "transfer", new IRubyObject[]{self.getRuntime().newString(n.type_id), _obj[0]});
}
return _obj[0];
}
// syck_defaultresolver_detect_implicit
@JRubyMethod
public static IRubyObject detect_implicit(IRubyObject self, IRubyObject val) {
IRubyObject tmp = TypeConverter.convertToTypeWithCheck(val, self.getRuntime().getString(), "to_str");
if(!tmp.isNil()) {
ByteList bl = ((RubyString)tmp).getByteList();
String type_id = ImplicitScanner2.matchImplicit(Pointer.create(bl.bytes, bl.begin), bl.realSize);
return self.getRuntime().newString(type_id);
}
return RubyString.newEmptyString(self.getRuntime());
}
}
yecht-0.0.2/ext/ruby/src/java/org/yecht/ruby/DomainType.java 0000664 0000000 0000000 00000001074 11233025100 0023703 0 ustar 00root root 0000000 0000000 package org.yecht.ruby;
import org.jruby.RubyObject;
import org.jruby.anno.JRubyMethod;
import org.jruby.runtime.builtin.IRubyObject;
public class DomainType {
// syck_domaintype_initialize
@JRubyMethod
public static IRubyObject initialize(IRubyObject self, IRubyObject domain, IRubyObject type_id, IRubyObject val) {
((RubyObject)self).fastSetInstanceVariable("@domain", domain);
((RubyObject)self).fastSetInstanceVariable("@type_id", type_id);
((RubyObject)self).fastSetInstanceVariable("@value", val);
return self;
}
}
yecht-0.0.2/ext/ruby/src/java/org/yecht/ruby/GenericResolver.java 0000664 0000000 0000000 00000012273 11233025100 0024733 0 ustar 00root root 0000000 0000000 package org.yecht.ruby;
import org.yecht.Data;
import org.yecht.MapStyle;
import org.yecht.MapPart;
import org.yecht.SeqStyle;
import org.jruby.Ruby;
import org.jruby.RubyArray;
import org.jruby.RubyHash;
import org.jruby.RubyModule;
import org.jruby.RubyObject;
import org.jruby.RubyString;
import org.jruby.anno.JRubyMethod;
import org.jruby.runtime.builtin.IRubyObject;
import org.jruby.runtime.ThreadContext;
import org.jruby.runtime.CallSite;
import org.jruby.runtime.MethodIndex;
public class GenericResolver {
public static class Extra {
public IRubyObject quote1;
public IRubyObject quote2;
public IRubyObject fold;
public IRubyObject literal;
public IRubyObject plain;
public IRubyObject map;
public IRubyObject seq;
public IRubyObject inline;
public IRubyObject Scalar;
public IRubyObject Seq;
public IRubyObject Map;
public Ruby runtime;
private final CallSite newScalarAdapter = MethodIndex.getFunctionalCallSite("new");
private final CallSite newSeqAdapter = MethodIndex.getFunctionalCallSite("new");
private final CallSite newMapAdapter = MethodIndex.getFunctionalCallSite("new");
public Extra(Ruby runtime) {
quote1 = runtime.newSymbol("quote1");
quote2 = runtime.newSymbol("quote2");
fold = runtime.newSymbol("fold");
literal = runtime.newSymbol("literal");
plain = runtime.newSymbol("plain");
map = runtime.newSymbol("map");
seq = runtime.newSymbol("seq");
inline = runtime.newSymbol("inline");
Scalar = ((RubyModule)((RubyModule)runtime.getModule("YAML")).getConstant("Yecht")).getConstant("Scalar");
Seq = ((RubyModule)((RubyModule)runtime.getModule("YAML")).getConstant("Yecht")).getConstant("Seq");
Map = ((RubyModule)((RubyModule)runtime.getModule("YAML")).getConstant("Yecht")).getConstant("Map");
this.runtime = runtime;
}
public IRubyObject scalar(IRubyObject t, org.yecht.Node n, ThreadContext ctx) {
Data.Str dd = (Data.Str)n.data;
IRubyObject v = RubyString.newStringShared(runtime, dd.ptr.buffer, dd.ptr.start, dd.len);
IRubyObject style = runtime.getNil();
switch(dd.style) {
case OneQuote:
style = quote1;
break;
case TwoQuote:
style = quote2;
break;
case Fold:
style = fold;
break;
case Literal:
style = literal;
break;
case Plain:
style = plain;
break;
}
return newScalarAdapter.call(ctx, Scalar, Scalar, t, v, style);
}
public IRubyObject sequence(IRubyObject t, org.yecht.Node n, ThreadContext ctx) {
Data.Seq ds = (Data.Seq)n.data;
Object[] items = ds.items;
IRubyObject v = RubyArray.newArray(runtime, ds.idx);
for(int i = 0; i < ds.idx; i++) {
((RubyArray)v).store(i, (IRubyObject)items[i]);
}
IRubyObject style = runtime.getNil();
if(((Data.Seq)n.data).style == SeqStyle.Inline) {
style = inline;
}
IRubyObject obj = newSeqAdapter.call(ctx, Seq, Seq, t, v, style);
((RubyObject)obj).fastSetInstanceVariable("@kind", seq);
return obj;
}
public IRubyObject mapping(IRubyObject t, org.yecht.Node n, ThreadContext ctx) {
Data.Map dm = (Data.Map)n.data;
Object[] keys = dm.keys;
Object[] vals = dm.values;
IRubyObject v = RubyHash.newHash(runtime);
for(int i = 0; i < dm.idx; i++) {
IRubyObject k3 = (IRubyObject)keys[i];
IRubyObject v3 = (IRubyObject)vals[i];
if(null == v3) {
v3 = runtime.getNil();
}
((RubyHash)v).fastASet(k3, v3);
}
IRubyObject style = runtime.getNil();
if(((Data.Map)n.data).style == MapStyle.Inline) {
style = inline;
}
IRubyObject obj = newMapAdapter.call(ctx, Map, Map, t, v, style);
((RubyObject)obj).fastSetInstanceVariable("@kind", map);
return obj;
}
}
// syck_genericresolver_node_import
@JRubyMethod
public static IRubyObject node_import(IRubyObject self, IRubyObject node) {
// System.err.println("syck_genericresolver_node_import()");
Ruby runtime = self.getRuntime();
ThreadContext ctx = runtime.getCurrentContext();
org.yecht.Node n = (org.yecht.Node)node.dataGetStructChecked();
IRubyObject t = runtime.getNil();
Extra x = (Extra)self.dataGetStruct();
if(n.type_id != null) {
t = runtime.newString(n.type_id);
}
switch(n.kind) {
case Str:
return x.scalar(t, n, ctx);
case Seq:
return x.sequence(t, n, ctx);
case Map:
return x.mapping(t, n, ctx);
}
return runtime.getNil();
}
}
yecht-0.0.2/ext/ruby/src/java/org/yecht/ruby/HashStorageLink.java 0000664 0000000 0000000 00000001061 11233025100 0024654 0 ustar 00root root 0000000 0000000 package org.yecht.ruby;
import org.jruby.RubyHash;
import org.jruby.runtime.builtin.IRubyObject;
class HashStorageLink extends StorageLink {
private final RubyHash hash;
private final IRubyObject key;
private final IRubyObject originalObject;
public HashStorageLink(IRubyObject h, IRubyObject key, IRubyObject originalObject) {
this.hash = (RubyHash)h;
this.key = key;
this.originalObject = originalObject;
}
public void replaceLinkWith(IRubyObject newObject) {
hash.fastASet(key, newObject);
}
}
yecht-0.0.2/ext/ruby/src/java/org/yecht/ruby/Map.java 0000664 0000000 0000000 00000010553 11233025100 0022351 0 ustar 00root root 0000000 0000000 package org.yecht.ruby;
import org.yecht.Data;
import org.yecht.MapStyle;
import org.jruby.Ruby;
import org.jruby.RubyArray;
import org.jruby.RubyClass;
import org.jruby.RubyHash;
import org.jruby.RubyObject;
import org.jruby.anno.JRubyMethod;
import org.jruby.runtime.ObjectAllocator;
import org.jruby.runtime.ThreadContext;
import org.jruby.runtime.builtin.IRubyObject;
import org.jruby.util.TypeConverter;
public class Map {
public static final ObjectAllocator Allocator = new ObjectAllocator() {
// syck_map_alloc
public IRubyObject allocate(Ruby runtime, RubyClass klass) {
// System.err.println("ALLOCATING MAP");
org.yecht.Node node = org.yecht.Node.allocMap();
IRubyObject obj = new Node(runtime, klass, node, (YAMLExtra)runtime.getModule("YAML").dataGetStruct());
node.id = obj;
// System.err.println("syck_map_alloc() -> setting id");
return obj;
}
};
// syck_map_initialize
@JRubyMethod
public static IRubyObject initialize(IRubyObject self, IRubyObject type_id, IRubyObject val, IRubyObject style) {
org.yecht.Node node = (org.yecht.Node)self.dataGetStructChecked();
Ruby runtime = self.getRuntime();
ThreadContext ctx = runtime.getCurrentContext();
Data.Map ds = (Data.Map)node.data;
if(!val.isNil()) {
IRubyObject hsh = TypeConverter.convertToTypeWithCheck(val, runtime.getHash(), "to_hash");
if(hsh.isNil()) {
throw runtime.newTypeError("wrong argument type");
}
IRubyObject keys = hsh.callMethod(ctx, "keys");
for(int i = 0; i < ((RubyArray)keys).getLength(); i++) {
IRubyObject key = ((RubyArray)keys).entry(i);
node.mapAdd(key, ((RubyHash)hsh).op_aref(ctx, key));
}
}
((RubyObject)self).fastSetInstanceVariable("@kind", ((Node)self).x.seq); // NOT A TYPO - Syck does the same
self.callMethod(ctx, "type_id=", type_id);
self.callMethod(ctx, "value=", val);
self.callMethod(ctx, "style=", style);
return self;
}
// syck_map_value_set
@JRubyMethod(name = "value=")
public static IRubyObject value_set(IRubyObject self, IRubyObject val) {
org.yecht.Node node = (org.yecht.Node)self.dataGetStructChecked();
Ruby runtime = self.getRuntime();
ThreadContext ctx = runtime.getCurrentContext();
if(!val.isNil()) {
IRubyObject hsh = TypeConverter.convertToTypeWithCheck(val, runtime.getHash(), "to_hash");
if(hsh.isNil()) {
throw runtime.newTypeError("wrong argument type");
}
node.mapEmpty();
IRubyObject keys = hsh.callMethod(ctx, "keys");
for(int i = 0; i < ((RubyArray)keys).getLength(); i++) {
IRubyObject key = ((RubyArray)keys).entry(i);
node.mapAdd(key, ((RubyHash)hsh).op_aref(ctx, key));
}
}
((RubyObject)self).fastSetInstanceVariable("@value", val);
return val;
}
// syck_map_add_m
@JRubyMethod
public static IRubyObject add(IRubyObject self, IRubyObject key, IRubyObject val) {
IRubyObject emitter = (IRubyObject)((RubyObject)self).fastGetInstanceVariable("@emitter");
org.yecht.Node node = (org.yecht.Node)self.dataGetStructChecked();
if(emitter.respondsTo("node_export")) {
key = emitter.callMethod(self.getRuntime().getCurrentContext(), "node_export", key);
val = emitter.callMethod(self.getRuntime().getCurrentContext(), "node_export", val);
}
node.mapAdd(key, val);
((RubyHash)((RubyObject)self).fastGetInstanceVariable("@value")).fastASet(key, val);
return self;
}
// syck_map_style_set
@JRubyMethod(name = "style=")
public static IRubyObject style_set(IRubyObject self, IRubyObject style) {
org.yecht.Node node = (org.yecht.Node)self.dataGetStructChecked();
Ruby runtime = self.getRuntime();
Data.Map ds = (Data.Map)node.data;
if(style == ((Node)self).x.inline) {
ds.style = MapStyle.Inline;
} else {
ds.style = MapStyle.None;
}
((RubyObject)self).fastSetInstanceVariable("@style", style);
return self;
}
}
yecht-0.0.2/ext/ruby/src/java/org/yecht/ruby/Module.java 0000664 0000000 0000000 00000002164 11233025100 0023060 0 ustar 00root root 0000000 0000000 package org.yecht.ruby;
import org.yecht.Bytestring;
import org.yecht.BytecodeNodeHandler;
import org.yecht.Parser;
import org.jruby.RubyString;
import org.jruby.anno.JRubyMethod;
import org.jruby.runtime.builtin.IRubyObject;
import org.jruby.util.ByteList;
public class Module {
// rb_syck_compile
@JRubyMethod(name = "compile", required = 1, module = true)
public static IRubyObject compile(IRubyObject self, IRubyObject port) {
Parser parser = Parser.newParser();
boolean taint = YParser.assignIO(self.getRuntime(), parser, new IRubyObject[] {port});
parser.handler(new BytecodeNodeHandler());
parser.errorHandler(null);
parser.implicitTyping(false);
parser.taguriExpansion(false);
Bytestring sav = (Bytestring)parser.parse();
int len = Bytestring.strlen(sav.buffer);
ByteList bl = new ByteList(new byte[len+2], false);
bl.append(sav.buffer, 0, len);
bl.append('D');
bl.append('\n');
IRubyObject iro = RubyString.newStringLight(self.getRuntime(), bl);
if(taint) iro.setTaint(true);
return iro;
}
}
yecht-0.0.2/ext/ruby/src/java/org/yecht/ruby/Node.java 0000664 0000000 0000000 00000007775 11233025100 0022535 0 ustar 00root root 0000000 0000000 package org.yecht.ruby;
import org.yecht.MapPart;
import org.jruby.Ruby;
import org.jruby.RubyClass;
import org.jruby.RubyString;
import org.jruby.RubyObject;
import org.jruby.anno.JRubyMethod;
import org.jruby.runtime.ObjectAllocator;
import org.jruby.runtime.ThreadContext;
import org.jruby.runtime.builtin.IRubyObject;
public class Node extends RubyObject.Data {
public static final ObjectAllocator Allocator = new ObjectAllocator() {
public IRubyObject allocate(Ruby runtime, RubyClass klass) {
return new Node(runtime, klass, null, (YAMLExtra)runtime.getModule("YAML").dataGetStruct());
}
};
public YAMLExtra x;
public Node(Ruby runtime, RubyClass metaClass, Object data, YAMLExtra x) {
super(runtime, metaClass, data);
this.x = x;
}
public Node(RubyClass metaClass, Object data, YAMLExtra x) {
super(metaClass, data);
this.x = x;
}
// syck_node_init_copy
@JRubyMethod
public static IRubyObject initialize_copy(IRubyObject copy, IRubyObject orig) {
if(copy == orig) {
return copy;
}
if(orig.getClass() != RubyObject.class) {
throw copy.getRuntime().newTypeError("wrong argument type");
}
org.yecht.Node orig_n = (org.yecht.Node)orig.dataGetStructChecked();
org.yecht.Node copy_n = (org.yecht.Node)copy.dataGetStructChecked();
copy_n.id = orig_n.id;
copy_n.kind = orig_n.kind;
copy_n.type_id = orig_n.type_id;
copy_n.anchor = orig_n.anchor;
copy_n.data = orig_n.data.copy();
return copy;
}
// syck_node_type_id_set
@JRubyMethod(name = "type_id=")
public static IRubyObject set_type_id(IRubyObject self, IRubyObject type_id) {
org.yecht.Node node = (org.yecht.Node)self.dataGetStructChecked();
if(!type_id.isNil()) {
node.type_id = type_id.convertToString().toString();
}
((RubyObject)self).fastSetInstanceVariable("@type_id", type_id);
return type_id;
}
// syck_node_transform
@JRubyMethod
public static IRubyObject transform(IRubyObject self) {
// System.err.println("syck_node_transform()");
Ruby runtime = self.getRuntime();
ThreadContext ctx = runtime.getCurrentContext();
org.yecht.Node orig_n = (org.yecht.Node)self.dataGetStructChecked();
YAMLExtra x = ((Node)self).x;
IRubyObject t = new Node(runtime, self.getType(), null, x);
org.yecht.Node n = null;
switch(orig_n.kind) {
case Map:
n = org.yecht.Node.allocMap();
t.dataWrapStruct(n);
org.yecht.Data.Map dm = (org.yecht.Data.Map)orig_n.data;
for(int i=0; i < dm.idx; i++) {
IRubyObject k = ((IRubyObject)orig_n.mapRead(MapPart.Key, i)).callMethod(ctx, "transform");
IRubyObject v = ((IRubyObject)orig_n.mapRead(MapPart.Value, i)).callMethod(ctx, "transform");
n.mapAdd(k, v);
}
break;
case Seq:
n = org.yecht.Node.allocSeq();
t.dataWrapStruct(n);
org.yecht.Data.Seq ds = (org.yecht.Data.Seq)orig_n.data;
for(int i=0; i < ds.idx; i++) {
IRubyObject itm = ((IRubyObject)orig_n.seqRead(i)).callMethod(ctx, "transform");
n.seqAdd(itm);
}
break;
case Str:
org.yecht.Data.Str dss = (org.yecht.Data.Str)orig_n.data;
n = org.yecht.Node.newStr(dss.ptr, dss.len, dss.style);
t.dataWrapStruct(n);
break;
}
if(orig_n.type_id != null) {
n.type_id = orig_n.type_id;
}
if(orig_n.anchor != null) {
n.anchor = orig_n.anchor;
}
n.id = t;
// System.err.println("syck_node_transform(), setting id of object on: " + n);
IRubyObject result = x.DefaultResolver.callMethod(ctx, "node_import", t);
return result;
}
}
yecht-0.0.2/ext/ruby/src/java/org/yecht/ruby/Out.java 0000664 0000000 0000000 00000006256 11233025100 0022410 0 ustar 00root root 0000000 0000000 package org.yecht.ruby;
import org.yecht.Emitter;
import org.jruby.Ruby;
import org.jruby.RubyArray;
import org.jruby.RubyHash;
import org.jruby.RubyModule;
import org.jruby.RubyObject;
import org.jruby.anno.JRubyMethod;
import org.jruby.runtime.Block;
import org.jruby.runtime.BlockCallback;
import org.jruby.runtime.ThreadContext;
import org.jruby.runtime.builtin.IRubyObject;
public class Out {
// syck_out_mark
public static void outMark(IRubyObject emitter, IRubyObject node) {
Emitter emitterPtr = (Emitter)emitter.dataGetStructChecked();
YEmitter.Extra bonus = (YEmitter.Extra)emitterPtr.bonus;
((RubyObject)node).fastSetInstanceVariable("@emitter", emitter);
if(!bonus.oid.isNil()) {
((RubyHash)bonus.data).fastASet(bonus.oid, node);
}
}
// syck_out_initialize
@JRubyMethod
public static IRubyObject initialize(IRubyObject self, IRubyObject emitter) {
((RubyObject)self).fastSetInstanceVariable("@emitter", emitter);
return self;
}
// syck_out_map
@JRubyMethod(required = 1, optional = 1, frame = true)
public static IRubyObject map(IRubyObject self, IRubyObject[] args, Block block) {
Ruby runtime = self.getRuntime();
ThreadContext ctx = runtime.getCurrentContext();
IRubyObject type_id = args[0];
IRubyObject style = args.length == 1 ? runtime.getNil() : args[1];
IRubyObject map = ((RubyModule)((RubyModule)runtime.getModule("YAML")).getConstant("Yecht")).getConstant("Map").callMethod(ctx, "new", new IRubyObject[]{type_id, RubyHash.newHash(runtime), style});
outMark((IRubyObject)((RubyObject)self).fastGetInstanceVariable("@emitter"), map);
block.yield(ctx, map);
return map;
}
// syck_out_seq
@JRubyMethod(required = 1, optional = 1, frame = true)
public static IRubyObject seq(IRubyObject self, IRubyObject[] args, Block block) {
Ruby runtime = self.getRuntime();
ThreadContext ctx = runtime.getCurrentContext();
IRubyObject type_id = args[0];
IRubyObject style = args.length == 1 ? runtime.getNil() : args[1];
IRubyObject seq = ((RubyModule)((RubyModule)runtime.getModule("YAML")).getConstant("Yecht")).getConstant("Seq").callMethod(ctx, "new", new IRubyObject[]{type_id, RubyArray.newArray(runtime), style});
outMark((IRubyObject)((RubyObject)self).fastGetInstanceVariable("@emitter"), seq);
block.yield(ctx, seq);
return seq;
}
// syck_out_scalar
@JRubyMethod(required = 2, optional = 1, frame = true)
public static IRubyObject scalar(IRubyObject self, IRubyObject[] args, Block block) {
Ruby runtime = self.getRuntime();
ThreadContext ctx = runtime.getCurrentContext();
IRubyObject type_id = args[0];
IRubyObject str = args[1];
IRubyObject style = args.length == 2 ? runtime.getNil() : args[2];
IRubyObject scalar = ((RubyModule)((RubyModule)runtime.getModule("YAML")).getConstant("Yecht")).getConstant("Scalar").callMethod(ctx, "new", new IRubyObject[]{type_id, str, style});
outMark((IRubyObject)((RubyObject)self).fastGetInstanceVariable("@emitter"), scalar);
return scalar;
}
}
yecht-0.0.2/ext/ruby/src/java/org/yecht/ruby/PossibleLinkNode.java 0000664 0000000 0000000 00000000300 11233025100 0025025 0 ustar 00root root 0000000 0000000 package org.yecht.ruby;
import org.jruby.runtime.builtin.IRubyObject;
public interface PossibleLinkNode {
void addLink(StorageLink link);
void replaceLinks(IRubyObject newObject);
}
yecht-0.0.2/ext/ruby/src/java/org/yecht/ruby/PrivateType.java 0000664 0000000 0000000 00000000743 11233025100 0024110 0 ustar 00root root 0000000 0000000 package org.yecht.ruby;
import org.jruby.RubyObject;
import org.jruby.anno.JRubyMethod;
import org.jruby.runtime.builtin.IRubyObject;
public class PrivateType {
// syck_privatetype_initialize
@JRubyMethod
public static IRubyObject initialize(IRubyObject self, IRubyObject type_id, IRubyObject val) {
((RubyObject)self).fastSetInstanceVariable("@type_id", type_id);
((RubyObject)self).fastSetInstanceVariable("@value", val);
return self;
}
}
yecht-0.0.2/ext/ruby/src/java/org/yecht/ruby/Resolver.java 0000664 0000000 0000000 00000026620 11233025100 0023437 0 ustar 00root root 0000000 0000000 package org.yecht.ruby;
import org.yecht.Data;
import org.yecht.ImplicitScanner;
import org.yecht.MapPart;
import org.jruby.Ruby;
import org.jruby.RubyArray;
import org.jruby.RubyClass;
import org.jruby.RubyEnumerable;
import org.jruby.RubyHash;
import org.jruby.RubyModule;
import org.jruby.RubyNumeric;
import org.jruby.RubyObject;
import org.jruby.RubyString;
import org.jruby.anno.JRubyMethod;
import org.jruby.runtime.Block;
import org.jruby.runtime.BlockCallback;
import org.jruby.runtime.ThreadContext;
import org.jruby.runtime.builtin.IRubyObject;
import org.jruby.util.TypeConverter;
public class Resolver {
// syck_const_find
public static IRubyObject const_find(IRubyObject self, IRubyObject const_name) {
RubyModule tclass = self.getRuntime().getObject();
RubyArray tparts = ((RubyString)const_name).split(self.getRuntime().getCurrentContext(), self.getRuntime().newString("::"));
for(int i=0; i < tparts.getLength(); i++) {
String tpart = tparts.entry(i).toString();
try {
tclass = (RubyModule)tclass.getConstant(tpart);
} catch(Exception e) {
return self.getRuntime().getNil();
}
}
return tclass;
}
// syck_resolver_initialize
@JRubyMethod
public static IRubyObject initialize(IRubyObject self) {
((RubyObject)self).fastSetInstanceVariable("@tags", RubyHash.newHash(self.getRuntime()));
return self;
}
// syck_resolver_add_type
@JRubyMethod
public static IRubyObject add_type(IRubyObject self, IRubyObject taguri, IRubyObject cls) {
IRubyObject tags = self.callMethod(self.getRuntime().getCurrentContext(), "tags");
((RubyHash)tags).fastASet(taguri, cls);
return self.getRuntime().getNil();
}
// syck_resolver_use_types_at
@JRubyMethod
public static IRubyObject use_types_at(IRubyObject self, IRubyObject hsh) {
((RubyObject)self).fastSetInstanceVariable("@tags", hsh);
return self.getRuntime().getNil();
}
// syck_resolver_detect_implicit
@JRubyMethod
public static IRubyObject detect_implicit(IRubyObject self, IRubyObject val) {
return RubyString.newEmptyString(self.getRuntime());
}
// syck_resolver_transfer
@JRubyMethod
public static IRubyObject transfer(IRubyObject self, IRubyObject type, IRubyObject val) {
final Ruby runtime = self.getRuntime();
ThreadContext ctx = runtime.getCurrentContext();
if(type.isNil() || type.convertToString().getByteList().realSize == 0) {
type = self.callMethod(ctx, "detect_implicit", val);
}
if(!(type.isNil() || type.convertToString().getByteList().realSize == 0)) {
IRubyObject colon = runtime.newString(":");
IRubyObject tags = self.callMethod(ctx, "tags");
IRubyObject target_class = ((RubyHash)tags).op_aref(ctx, type);
IRubyObject subclass = target_class;
IRubyObject obj = runtime.getNil();
if(target_class.isNil()) {
RubyArray subclass_parts = runtime.newArray();
RubyArray parts = ((RubyString)type).split(ctx, colon);
while(parts.getLength() > 1) {
subclass_parts.unshift(parts.pop(ctx));
IRubyObject partial = parts.join(ctx, colon);
target_class = ((RubyHash)tags).op_aref(ctx, partial);
if(target_class.isNil()) {
((RubyString)partial).append(colon);
target_class = ((RubyHash)tags).op_aref(ctx, partial);
}
if(!target_class.isNil()) {
subclass = target_class;
if(subclass_parts.getLength() > 0 && target_class.respondsTo("yaml_tag_subclasses?") && target_class.callMethod(ctx, "yaml_tag_subclasses?").isTrue()) {
subclass = subclass_parts.join(ctx, colon);
subclass = target_class.callMethod(ctx, "yaml_tag_read_class", subclass);
IRubyObject subclass_v = const_find(self, subclass);
if(subclass_v != runtime.getNil()) {
subclass = subclass_v;
} else if(target_class == runtime.getObject() && subclass_v == runtime.getNil()) {
target_class = ((RubyModule)runtime.getModule("YAML")).getConstant("Object");
type = subclass;
subclass = target_class;
} else {
throw runtime.newTypeError("invalid subclass");
}
}
break;
}
}
}
if(target_class.respondsTo("call")) {
obj = target_class.callMethod(ctx, "call", new IRubyObject[]{type, val});
} else {
if(target_class.respondsTo("yaml_new")) {
obj = target_class.callMethod(ctx, "yaml_new", new IRubyObject[]{subclass, type, val});
} else if(!target_class.isNil()) {
if(subclass == runtime.getBignum()) {
obj = RubyNumeric.str2inum(runtime, val.convertToString(), 10);
} else {
obj = ((RubyClass)subclass).allocate();
}
if(obj.respondsTo("yaml_initialize")) {
obj.callMethod(ctx, "yaml_initialize", new IRubyObject[]{type, val});
} else if(!obj.isNil() && val instanceof RubyHash) {
final IRubyObject _obj = obj;
RubyEnumerable.callEach(runtime, ctx, val, new BlockCallback() {
public IRubyObject call(ThreadContext _ctx, IRubyObject[] largs, Block blk) {
IRubyObject ivname = ((RubyArray)largs[0]).entry(0);
String ivn = "@" + ivname.convertToString().toString();
_obj.getInstanceVariables().setInstanceVariable(ivn, ((RubyArray)largs[0]).entry(1));
return runtime.getNil();
}
});
}
} else {
RubyArray parts = ((RubyString)type).split(ctx, colon);
IRubyObject scheme = parts.shift(ctx);
if(scheme.convertToString().toString().equals("x-private")) {
IRubyObject name = parts.join(ctx, colon);
obj = ((RubyModule)((RubyModule)runtime.getModule("YAML")).getConstant("Yecht")).getConstant("PrivateType").callMethod(ctx, "new", new IRubyObject[]{name, val});
} else {
IRubyObject domain = parts.shift(ctx);
IRubyObject name = parts.join(ctx, colon);
obj = ((RubyModule)((RubyModule)runtime.getModule("YAML")).getConstant("Yecht")).getConstant("DomainType").callMethod(ctx, "new", new IRubyObject[]{domain, name, val});
}
}
}
val = obj;
}
return val;
}
// syck_resolver_node_import
@JRubyMethod
public static IRubyObject node_import(IRubyObject self, IRubyObject node) {
// System.err.println("syck_resolver_node_import()");
final Ruby runtime = self.getRuntime();
final ThreadContext ctx = runtime.getCurrentContext();
org.yecht.Node n = (org.yecht.Node)node.dataGetStructChecked();
YAMLExtra x = ((Node)node).x;
IRubyObject obj = null;
switch(n.kind) {
case Str:
Data.Str dd = (Data.Str)n.data;
obj = RubyString.newStringShared(runtime, dd.ptr.buffer, dd.ptr.start, dd.len);
break;
case Seq:
Data.Seq ds = (Data.Seq)n.data;
obj = RubyArray.newArray(runtime, ds.idx);
for(int i = 0; i < ds.idx; i++) {
IRubyObject obj2 = (IRubyObject)n.seqRead(i);
((RubyArray)obj).store(i, obj2);
}
break;
case Map:
Data.Map dm = (Data.Map)n.data;
obj = RubyHash.newHash(runtime);
RubyClass cMergeKey = x.MergeKey;
RubyClass cDefaultKey = x.DefaultKey;
RubyClass cHash = runtime.getHash();
RubyClass cArray = runtime.getArray();
for(int i = 0; i < dm.idx; i++) {
IRubyObject k = (IRubyObject)n.mapRead(MapPart.Key, i);
IRubyObject v = (IRubyObject)n.mapRead(MapPart.Value, i);
if(null == v) {
v = runtime.getNil();
}
boolean skip_aset = false;
if(cMergeKey.isInstance(k)) {
if(cHash.isInstance(v)) {
IRubyObject dup = v.callMethod(ctx, "dup");
dup.callMethod(ctx, "update", obj);
obj = dup;
skip_aset = true;
} else if(cArray.isInstance(v)) {
IRubyObject end = ((RubyArray)v).pop(ctx);
if(cHash.isInstance(end)) {
final IRubyObject dup = end.callMethod(ctx, "dup");
v = ((RubyArray)v).reverse();
((RubyArray)v).append(obj);
RubyEnumerable.callEach(runtime, ctx, v, new BlockCallback() {
// syck_merge_i
public IRubyObject call(ThreadContext _ctx, IRubyObject[] largs, Block blk) {
IRubyObject entry = largs[0];
IRubyObject tmp = null;
if(!(tmp = TypeConverter.convertToTypeWithCheck(entry, runtime.getHash(), "to_hash")).isNil()) {
dup.callMethod(_ctx, "update", tmp);
}
return runtime.getNil();
}
});
obj = dup;
skip_aset = true;
}
}
} else if(cDefaultKey.isInstance(k)) {
obj.callMethod(ctx, "default=", v);
skip_aset = true;
}
if(!skip_aset) {
((RubyHash)obj).fastASet(k, v);
}
}
break;
}
if(n.type_id != null) {
obj = self.callMethod(ctx, "transfer", new IRubyObject[]{runtime.newString(n.type_id), obj});
}
return obj;
}
// syck_resolver_tagurize
@JRubyMethod
public static IRubyObject tagurize(IRubyObject self, IRubyObject val) {
IRubyObject tmp = val.checkStringType();
if(!tmp.isNil()) {
String taguri = ImplicitScanner.typeIdToUri(tmp.toString());
val = self.getRuntime().newString(taguri);
}
return val;
}
}
yecht-0.0.2/ext/ruby/src/java/org/yecht/ruby/RubyBadAnchorHandler.java 0000664 0000000 0000000 00000001355 11233025100 0025615 0 ustar 00root root 0000000 0000000 package org.yecht.ruby;
import org.yecht.BadAnchorHandler;
import org.yecht.Parser;
import org.jruby.Ruby;
import org.jruby.anno.JRubyMethod;
import org.jruby.runtime.builtin.IRubyObject;
public class RubyBadAnchorHandler implements BadAnchorHandler {
private Ruby runtime;
public RubyBadAnchorHandler(Ruby runtime) {
this.runtime = runtime;
}
// rb_syck_bad_anchor_handler
public org.yecht.Node handle(Parser p, String a) {
IRubyObject anchor_name = runtime.newString(a);
IRubyObject nm = runtime.newString("name");
org.yecht.Node badanc = org.yecht.Node.newMap(nm, anchor_name);
badanc.type_id = "tag:ruby.yaml.org,2002:object:YAML::Yecht::BadAlias";
return badanc;
}
}
yecht-0.0.2/ext/ruby/src/java/org/yecht/ruby/RubyEmitterHandler.java 0000664 0000000 0000000 00000002511 11233025100 0025400 0 ustar 00root root 0000000 0000000 package org.yecht.ruby;
import org.yecht.Data;
import org.yecht.Emitter;
import org.yecht.EmitterHandler;
import org.yecht.MapPart;
import org.jruby.Ruby;
import org.jruby.anno.JRubyMethod;
import org.jruby.runtime.builtin.IRubyObject;
public class RubyEmitterHandler implements EmitterHandler {
private Ruby runtime;
public RubyEmitterHandler(Ruby runtime) {
this.runtime = runtime;
}
// rb_syck_emitter_handler
public void handle(Emitter e, Object data) {
org.yecht.Node n = (org.yecht.Node)((IRubyObject)data).dataGetStructChecked();
switch(n.kind) {
case Map:
Data.Map dm = (Data.Map)n.data;
e.emitMap(n.type_id, dm.style);
for(int i = 0; i < dm.idx; i++) {
e.emitItem(n.mapRead(MapPart.Key, i));
e.emitItem(n.mapRead(MapPart.Value, i));
}
e.emitEnd();
break;
case Seq:
Data.Seq ds = (Data.Seq)n.data;
e.emitSeq(n.type_id, ds.style);
for(int i = 0; i < ds.idx; i++) {
e.emitItem(n.seqRead(i));
}
e.emitEnd();
break;
case Str:
Data.Str dss = (Data.Str)n.data;
e.emitScalar(n.type_id, dss.style, 0, 0, 0, dss.ptr, dss.len);
break;
}
}
}
yecht-0.0.2/ext/ruby/src/java/org/yecht/ruby/RubyErrHandler.java 0000664 0000000 0000000 00000001735 11233025100 0024526 0 ustar 00root root 0000000 0000000 package org.yecht.ruby;
import org.yecht.Parser;
import org.yecht.ErrorHandler;
import org.jruby.Ruby;
import org.jruby.anno.JRubyMethod;
import org.jruby.runtime.builtin.IRubyObject;
public class RubyErrHandler implements ErrorHandler {
private Ruby runtime;
public RubyErrHandler(Ruby runtime) {
this.runtime = runtime;
}
// rb_syck_err_handler
public void handle(Parser p, String msg) {
int endl = p.cursor;
while(p.buffer.buffer[endl] != 0 && p.buffer.buffer[endl] != '\n') {
endl++;
}
try {
int lp = p.lineptr;
if(lp < 0) {
lp = 0;
}
String line = new String(p.buffer.buffer, lp, endl-lp, "ISO-8859-1");
String m1 = msg + " on line " + p.linect + ", col " + (p.cursor-lp) + ": `" + line + "'";
throw runtime.newArgumentError(m1);
} catch(java.io.UnsupportedEncodingException e) {
}
}
}
yecht-0.0.2/ext/ruby/src/java/org/yecht/ruby/RubyIoStrRead.java 0000664 0000000 0000000 00000002167 11233025100 0024334 0 ustar 00root root 0000000 0000000 package org.yecht.ruby;
import org.yecht.IoStrRead;
import org.yecht.JechtIO;
import org.yecht.Pointer;
import org.jruby.RubyNumeric;
import org.jruby.runtime.builtin.IRubyObject;
import org.jruby.util.ByteList;
public class RubyIoStrRead implements IoStrRead {
private IRubyObject port;
public RubyIoStrRead(IRubyObject port) {
this.port = port;
}
// rb_syck_io_str_read
public int read(Pointer buf, JechtIO.Str str, int max_size, int skip) {
int len = 0;
max_size -= skip;
if(max_size <= 0) {
max_size = 0;
} else {
IRubyObject src = port;
IRubyObject n = RubyNumeric.int2fix(port.getRuntime(), max_size);
IRubyObject str2 = src.callMethod(port.getRuntime().getCurrentContext(), "read", n);
if(!str2.isNil()) {
ByteList res = str2.convertToString().getByteList();
len = res.realSize;
System.arraycopy(res.bytes, res.begin, buf.buffer, buf.start+skip, len);
}
}
len += skip;
buf.buffer[buf.start+len] = 0;
return len;
}
}
yecht-0.0.2/ext/ruby/src/java/org/yecht/ruby/RubyLoadHandler.java 0000664 0000000 0000000 00000004221 11233025100 0024646 0 ustar 00root root 0000000 0000000 package org.yecht.ruby;
import org.yecht.NodeHandler;
import org.yecht.Parser;
import org.jruby.Ruby;
import org.jruby.RubyHash;
import org.jruby.runtime.builtin.IRubyObject;
import org.jruby.runtime.CallSite;
import org.jruby.runtime.MethodIndex;
public class RubyLoadHandler implements NodeHandler {
private Ruby runtime;
private YAMLExtra x;
private final CallSite node_importAdapter = MethodIndex.getFunctionalCallSite("node_import");
public RubyLoadHandler(Ruby runtime, YAMLExtra x) {
this.runtime = runtime;
this.x = x;
}
// rb_syck_load_handler
public Object handle(Parser p, org.yecht.Node n) {
// System.err.println("load_handler for node: " + n.type_id + " with anchor: " + n.anchor);
// System.err.println(" id: " + n.id);
// if(n.id != null) {
// System.err.println(" val: " + ((IRubyObject)n.id).inspect().toString());
// }
// System.err.println("rb_syck_load_handler(" + n + ")");
YParser.Extra bonus = (YParser.Extra)p.bonus;
IRubyObject resolver = bonus.resolver;
if(resolver.isNil()) {
resolver = x.DefaultResolver;
}
IRubyObject _n = new Node(runtime, x.Node, n, x);
IRubyObject obj = node_importAdapter.call(runtime.getCurrentContext(), resolver, resolver, _n);
// System.err.println(" node_import -> " + obj);
if(n.id != null && !obj.isNil()) {
if(n.id instanceof PossibleLinkNode) {
((PossibleLinkNode)n.id).replaceLinks(obj);
}
n.id = obj;
// System.err.println(" -- LoadHandler, setting id, yay!");
}
if(bonus.taint) {
obj.setTaint(true);
}
if(bonus.proc != null) {
bonus.proc.callMethod(runtime.getCurrentContext(), "call", obj);
}
((RubyHash)bonus.data).fastASet(((RubyHash)bonus.data).rb_size(), obj);
// System.err.println(" -> rb_syck_load_handler=" + n.id);
return obj;
}
}
yecht-0.0.2/ext/ruby/src/java/org/yecht/ruby/RubyOutputHandler.java 0000664 0000000 0000000 00000001554 11233025100 0025275 0 ustar 00root root 0000000 0000000 package org.yecht.ruby;
import org.yecht.Emitter;
import org.yecht.OutputHandler;
import org.jruby.Ruby;
import org.jruby.RubyString;
import org.jruby.anno.JRubyMethod;
import org.jruby.runtime.builtin.IRubyObject;
import org.jruby.util.ByteList;
public class RubyOutputHandler implements OutputHandler {
private Ruby runtime;
public RubyOutputHandler(Ruby runtime) {
this.runtime = runtime;
}
// rb_syck_output_handler
public void handle(Emitter emitter, byte[] str, int len) {
YEmitter.Extra bonus = (YEmitter.Extra)emitter.bonus;
IRubyObject dest = bonus.port;
if(dest instanceof RubyString) {
((RubyString)dest).cat(new ByteList(str, 0, len, false));
} else {
dest.callMethod(runtime.getCurrentContext(), "write", RubyString.newStringShared(runtime, str, 0, len));
}
}
}
yecht-0.0.2/ext/ruby/src/java/org/yecht/ruby/Scalar.java 0000664 0000000 0000000 00000006200 11233025100 0023033 0 ustar 00root root 0000000 0000000 package org.yecht.ruby;
import org.yecht.Data;
import org.yecht.Pointer;
import org.yecht.ScalarStyle;
import org.jruby.Ruby;
import org.jruby.RubyClass;
import org.jruby.RubyObject;
import org.jruby.RubyString;
import org.jruby.anno.JRubyMethod;
import org.jruby.runtime.ObjectAllocator;
import org.jruby.runtime.ThreadContext;
import org.jruby.runtime.builtin.IRubyObject;
import org.jruby.util.ByteList;
public class Scalar {
public static final ObjectAllocator Allocator = new ObjectAllocator() {
// syck_scalar_alloc
public IRubyObject allocate(Ruby runtime, RubyClass klass) {
// System.err.println("ALLOCATING SCALAR");
org.yecht.Node node = org.yecht.Node.allocStr();
IRubyObject obj = new Node(runtime, klass, node, (YAMLExtra)runtime.getModule("YAML").dataGetStruct());
node.id = obj;
// System.err.println("syck_scalar_alloc() -> setting id: " + node.id);
return obj;
}
};
// syck_scalar_initialize
@JRubyMethod
public static IRubyObject initialize(IRubyObject self, IRubyObject type_id, IRubyObject val, IRubyObject style) {
Ruby runtime = self.getRuntime();
ThreadContext ctx = runtime.getCurrentContext();
((RubyObject)self).fastSetInstanceVariable("@kind", ((Node)self).x.scalar);
self.callMethod(ctx, "type_id=", type_id);
self.callMethod(ctx, "value=", val);
self.callMethod(ctx, "style=", style);
return self;
}
// syck_scalar_style_set
@JRubyMethod(name = "style=")
public static IRubyObject style_set(IRubyObject self, IRubyObject style) {
YAMLExtra x = ((Node)self).x;
Ruby runtime = self.getRuntime();
Data.Str ds = (Data.Str)((org.yecht.Node)self.dataGetStructChecked()).data;
if(style.isNil()) {
ds.style = ScalarStyle.None;
} else if(style == x.quote1) {
ds.style = ScalarStyle.OneQuote;
} else if(style == x.quote2) {
ds.style = ScalarStyle.TwoQuote;
} else if(style == x.fold) {
ds.style = ScalarStyle.Fold;
} else if(style == x.literal) {
ds.style = ScalarStyle.Literal;
} else if(style == x.plain) {
ds.style = ScalarStyle.Plain;
}
((RubyObject)self).fastSetInstanceVariable("@style", style);
return self;
}
// syck_scalar_value_set
@JRubyMethod(name = "value=")
public static IRubyObject value_set(IRubyObject self, IRubyObject val) {
org.yecht.Node node = (org.yecht.Node)self.dataGetStructChecked();
Ruby runtime = self.getRuntime();
Data.Str ds = (Data.Str)node.data;
val = val.convertToString();
ByteList bl = ((RubyString)val).getByteList();
byte[] bss = new byte[bl.realSize];
System.arraycopy(bl.bytes, bl.begin, bss, 0, bss.length);
ds.ptr = Pointer.create(bss, 0);
ds.len = bss.length;
ds.style = ScalarStyle.None;
((RubyObject)self).fastSetInstanceVariable("@value", val);
return val;
}
}
yecht-0.0.2/ext/ruby/src/java/org/yecht/ruby/Seq.java 0000664 0000000 0000000 00000006335 11233025100 0022367 0 ustar 00root root 0000000 0000000 package org.yecht.ruby;
import org.yecht.Data;
import org.yecht.SeqStyle;
import org.jruby.Ruby;
import org.jruby.RubyArray;
import org.jruby.RubyClass;
import org.jruby.RubyHash;
import org.jruby.RubyObject;
import org.jruby.anno.JRubyMethod;
import org.jruby.runtime.ObjectAllocator;
import org.jruby.runtime.ThreadContext;
import org.jruby.runtime.builtin.IRubyObject;
public class Seq {
public static final ObjectAllocator Allocator = new ObjectAllocator() {
// syck_seq_alloc
public IRubyObject allocate(Ruby runtime, RubyClass klass) {
// System.err.println("ALLOCATING SEQ");
org.yecht.Node node = org.yecht.Node.allocSeq();
IRubyObject obj = new Node(runtime, klass, node, (YAMLExtra)runtime.getModule("YAML").dataGetStruct());
node.id = obj;
// System.err.println("syck_seq_alloc() -> setting id");
return obj;
}
};
// syck_seq_initialize
@JRubyMethod
public static IRubyObject initialize(IRubyObject self, IRubyObject type_id, IRubyObject val, IRubyObject style) {
Ruby runtime = self.getRuntime();
ThreadContext ctx = runtime.getCurrentContext();
((RubyObject)self).fastSetInstanceVariable("@kind", ((Node)self).x.seq);
self.callMethod(ctx, "type_id=", type_id);
self.callMethod(ctx, "value=", val);
self.callMethod(ctx, "style=", style);
return self;
}
// syck_seq_value_set
@JRubyMethod(name = "value=")
public static IRubyObject value_set(IRubyObject self, IRubyObject val) {
org.yecht.Node node = (org.yecht.Node)self.dataGetStructChecked();
Ruby runtime = self.getRuntime();
val = val.checkArrayType();
if(!val.isNil()) {
node.seqEmpty();
Data.Seq ds = (Data.Seq)node.data;
for(int i=0; i<((RubyArray)val).getLength(); i++) {
node.seqAdd(((RubyArray)val).entry(i));
}
}
((RubyObject)self).fastSetInstanceVariable("@value", val);
return val;
}
// syck_seq_style_set
@JRubyMethod(name = "style=")
public static IRubyObject style_set(IRubyObject self, IRubyObject style) {
org.yecht.Node node = (org.yecht.Node)self.dataGetStructChecked();
Ruby runtime = self.getRuntime();
Data.Seq ds = (Data.Seq)node.data;
if(style == runtime.newSymbol("inline")) {
ds.style = SeqStyle.Inline;
} else {
ds.style = SeqStyle.None;
}
((RubyObject)self).fastSetInstanceVariable("@style", style);
return self;
}
// syck_seq_add_m
@JRubyMethod
public static IRubyObject add(IRubyObject self, IRubyObject val) {
IRubyObject emitter = (IRubyObject)((RubyObject)self).fastGetInstanceVariable("@emitter");
org.yecht.Node node = (org.yecht.Node)self.dataGetStructChecked();
if(emitter.respondsTo("node_export")) {
val = emitter.callMethod(self.getRuntime().getCurrentContext(), "node_export", val);
}
node.seqAdd(val);
((RubyArray)((RubyObject)self).fastGetInstanceVariable("@value")).append(val);
return self;
}
}
yecht-0.0.2/ext/ruby/src/java/org/yecht/ruby/StorageLink.java 0000664 0000000 0000000 00000000245 11233025100 0024053 0 ustar 00root root 0000000 0000000 package org.yecht.ruby;
import org.jruby.runtime.builtin.IRubyObject;
abstract class StorageLink {
public abstract void replaceLinkWith(IRubyObject object);
}
yecht-0.0.2/ext/ruby/src/java/org/yecht/ruby/YAMLExtra.java 0000664 0000000 0000000 00000006157 11233025100 0023407 0 ustar 00root root 0000000 0000000 package org.yecht.ruby;
import org.jruby.Ruby;
import org.jruby.RubyClass;
import org.jruby.RubyModule;
import org.jruby.runtime.builtin.IRubyObject;
import org.jruby.runtime.CallSite;
import org.jruby.runtime.MethodIndex;
public class YAMLExtra {
public IRubyObject quote1;
public IRubyObject quote2;
public IRubyObject fold;
public IRubyObject literal;
public IRubyObject plain;
public IRubyObject map;
public IRubyObject seq;
public IRubyObject scalar;
public IRubyObject inline;
public RubyClass Scalar;
public RubyClass Seq;
public RubyClass Map;
public IRubyObject DefaultResolver;
public RubyClass Node;
public RubyClass MergeKey;
public RubyClass DefaultKey;
public final CallSite type_id_set_ScalarAdapter = MethodIndex.getFunctionalCallSite("type_id=");
public final CallSite value_set_ScalarAdapter = MethodIndex.getFunctionalCallSite("value=");
public final CallSite style_set_ScalarAdapter = MethodIndex.getFunctionalCallSite("style=");
public final CallSite type_id_set_MapAdapter = MethodIndex.getFunctionalCallSite("type_id=");
public final CallSite value_set_MapAdapter = MethodIndex.getFunctionalCallSite("value=");
public final CallSite style_set_MapAdapter = MethodIndex.getFunctionalCallSite("style=");
public final CallSite type_id_set_SeqAdapter = MethodIndex.getFunctionalCallSite("type_id=");
public final CallSite value_set_SeqAdapter = MethodIndex.getFunctionalCallSite("value=");
public final CallSite style_set_SeqAdapter = MethodIndex.getFunctionalCallSite("style=");
public final CallSite node_export_EmitterAdapter = MethodIndex.getFunctionalCallSite("node_export");
public final CallSite keys_HashAdapter = MethodIndex.getFunctionalCallSite("keys");
public Ruby runtime;
public YAMLExtra(Ruby runtime) {
quote1 = runtime.newSymbol("quote1");
quote2 = runtime.newSymbol("quote2");
fold = runtime.newSymbol("fold");
literal = runtime.newSymbol("literal");
plain = runtime.newSymbol("plain");
map = runtime.newSymbol("map");
seq = runtime.newSymbol("seq");
scalar = runtime.newSymbol("scalar");
inline = runtime.newSymbol("inline");
Scalar = (RubyClass)((RubyModule)((RubyModule)runtime.getModule("YAML")).getConstant("Yecht")).getConstant("Scalar");
Seq = (RubyClass)((RubyModule)((RubyModule)runtime.getModule("YAML")).getConstant("Yecht")).getConstant("Seq");
Map = (RubyClass)((RubyModule)((RubyModule)runtime.getModule("YAML")).getConstant("Yecht")).getConstant("Map");
DefaultResolver = ((RubyModule)((RubyModule)runtime.getModule("YAML")).getConstant("Yecht")).getConstant("DefaultResolver");
Node = (RubyClass)((RubyModule)((RubyModule)runtime.getModule("YAML")).getConstant("Yecht")).getConstant("Node");
MergeKey = (RubyClass)((RubyModule)((RubyModule)runtime.getModule("YAML")).getConstant("Yecht")).getConstant("MergeKey");
DefaultKey = (RubyClass)((RubyModule)((RubyModule)runtime.getModule("YAML")).getConstant("Yecht")).getConstant("DefaultKey");
this.runtime = runtime;
}
}
yecht-0.0.2/ext/ruby/src/java/org/yecht/ruby/YEmitter.java 0000664 0000000 0000000 00000011111 11233025100 0023365 0 ustar 00root root 0000000 0000000 package org.yecht.ruby;
import org.yecht.Emitter;
import org.jruby.Ruby;
import org.jruby.RubyClass;
import org.jruby.RubyHash;
import org.jruby.RubyModule;
import org.jruby.RubyNumeric;
import org.jruby.RubyObject;
import org.jruby.anno.JRubyMethod;
import org.jruby.runtime.Block;
import org.jruby.runtime.BlockCallback;
import org.jruby.runtime.ObjectAllocator;
import org.jruby.runtime.ThreadContext;
import org.jruby.runtime.builtin.IRubyObject;
import org.jruby.util.TypeConverter;
public class YEmitter {
public static class Extra {
public IRubyObject oid;
public IRubyObject data;
public IRubyObject port;
}
public static final ObjectAllocator Allocator = new ObjectAllocator() {
// syck_emitter_s_alloc
public IRubyObject allocate(Ruby runtime, RubyClass klass) {
// System.err.println("ALLOCATING EMITTER");
Emitter emitter = new Emitter();
emitter.bonus = new Extra();
IRubyObject pobj = runtime.newData(klass, emitter);
emitter.handler(new RubyEmitterHandler(runtime));
emitter.outputHandler(new RubyOutputHandler(runtime));
((RubyObject)pobj).fastSetInstanceVariable("@out", ((RubyModule)((RubyModule)runtime.getModule("YAML")).getConstant("Yecht")).getConstant("Out").callMethod(runtime.getCurrentContext(), "new", pobj));
return pobj;
}
};
// syck_emitter_set_resolver
@JRubyMethod
public static IRubyObject set_resolver(IRubyObject self, IRubyObject resolver) {
((RubyObject)self).fastSetInstanceVariable("@resolver", resolver);
return self;
}
// syck_emitter_node_export
@JRubyMethod
public static IRubyObject node_export(IRubyObject self, IRubyObject node) {
return node.callMethod(self.getRuntime().getCurrentContext(), "to_yaml", self);
}
// syck_emitter_reset
@JRubyMethod(name = {"initialize", "reset"}, optional = 1)
public static IRubyObject reset(IRubyObject self, IRubyObject[] args) {
Ruby runtime = self.getRuntime();
ThreadContext ctx = runtime.getCurrentContext();
Emitter emitter = (Emitter)self.dataGetStructChecked();
Extra bonus = (Extra)emitter.bonus;
bonus.oid = runtime.getNil();
bonus.port = runtime.newString("");
bonus.data = RubyHash.newHash(runtime);
IRubyObject options = null;
IRubyObject tmp;
if(args.length == 1) {
options = args[0];
if(!(tmp = options.checkStringType()).isNil()) {
bonus.port = tmp;
} else if(options.respondsTo("write")) {
bonus.port = options;
} else {
options = TypeConverter.convertToTypeWithCheck(options, runtime.getHash(), "to_hash");
((RubyObject)self).fastSetInstanceVariable("@options", options);
}
} else {
options = RubyHash.newHash(runtime);
((RubyObject)self).fastSetInstanceVariable("@options", options);
}
emitter.headless = false;
((RubyObject)self).fastSetInstanceVariable("@level", runtime.newFixnum(0));
((RubyObject)self).fastSetInstanceVariable("@resolver", runtime.getNil());
return self;
}
// syck_emitter_emit
@JRubyMethod(optional = 1, frame = true)
public static IRubyObject emit(IRubyObject self, IRubyObject[] _oid, Block proc) {
Ruby runtime = self.getRuntime();
int level = RubyNumeric.fix2int((IRubyObject)((RubyObject)self).fastGetInstanceVariable("@level")) + 1;
((RubyObject)self).fastSetInstanceVariable("@level", runtime.newFixnum(level));
ThreadContext ctx = runtime.getCurrentContext();
Emitter emitter = (Emitter)self.dataGetStructChecked();
Extra bonus = (Extra)emitter.bonus;
IRubyObject oid = _oid.length == 0 ? runtime.getNil() : _oid[0];
bonus.oid = oid;
IRubyObject symple;
if(!oid.isNil() && bonus.data.callMethod(ctx, "has_key?", oid).isTrue()) {
symple = ((RubyHash)bonus.data).op_aref(ctx, oid);
} else {
symple = proc.yield(ctx, (IRubyObject)((RubyObject)self).fastGetInstanceVariable("@out"));
}
emitter.markNode(symple);
level--;
((RubyObject)self).fastSetInstanceVariable("@level", runtime.newFixnum(level));
if(level == 0) {
emitter.emit(symple);
emitter.flush(0);
return bonus.port;
}
return symple;
}
}
yecht-0.0.2/ext/ruby/src/java/org/yecht/ruby/YObject.java 0000664 0000000 0000000 00000001427 11233025100 0023173 0 ustar 00root root 0000000 0000000 package org.yecht.ruby;
import org.jruby.RubyObject;
import org.jruby.anno.JRubyMethod;
import org.jruby.runtime.builtin.IRubyObject;
public class YObject {
// syck_yobject_initialize
@JRubyMethod
public static IRubyObject initialize(IRubyObject self, IRubyObject klass, IRubyObject ivars) {
((RubyObject)self).fastSetInstanceVariable("@class", klass);
((RubyObject)self).fastSetInstanceVariable("@ivars", ivars);
return self;
}
// syck_yobject_initialize
@JRubyMethod
public static IRubyObject yaml_initialize(IRubyObject self, IRubyObject klass, IRubyObject ivars) {
((RubyObject)self).fastSetInstanceVariable("@class", klass);
((RubyObject)self).fastSetInstanceVariable("@ivars", ivars);
return self;
}
}
yecht-0.0.2/ext/ruby/src/java/org/yecht/ruby/YParser.java 0000664 0000000 0000000 00000016053 11233025100 0023222 0 ustar 00root root 0000000 0000000 package org.yecht.ruby;
import org.yecht.Parser;
import org.yecht.ParserInput;
import org.yecht.Pointer;
import org.jruby.Ruby;
import org.jruby.RubyClass;
import org.jruby.RubyHash;
import org.jruby.RubyModule;
import org.jruby.RubyNumeric;
import org.jruby.RubyObject;
import org.jruby.RubyString;
import org.jruby.anno.JRubyMethod;
import org.jruby.runtime.Block;
import org.jruby.runtime.BlockCallback;
import org.jruby.runtime.ObjectAllocator;
import org.jruby.runtime.ThreadContext;
import org.jruby.runtime.builtin.IRubyObject;
import org.jruby.util.ByteList;
public class YParser {
public static class Extra {
public IRubyObject data;
public IRubyObject proc;
public IRubyObject resolver;
public boolean taint;
}
public static final ObjectAllocator Allocator = new ObjectAllocator() {
// syck_parser_s_alloc
public IRubyObject allocate(Ruby runtime, RubyClass klass) {
// System.err.println("ALLOCATING PARSER");
Parser parser = Parser.newParser();
parser.bonus = new Extra();
IRubyObject pobj = runtime.newData(klass, parser);
parser.setRootOnError(runtime.getNil());
return pobj;
}
};
// syck_parser_assign_io
public static boolean assignIO(Ruby runtime, Parser parser, IRubyObject[] pport) {
boolean taint = true;
IRubyObject tmp, port = pport[0];
if(!(tmp = port.checkStringType()).isNil()) {
taint = port.isTaint();
port = tmp;
ByteList bl = ((RubyString)port).getByteList();
parser.str(Pointer.create(bl.bytes, bl.begin), bl.realSize, null);
} else if(port.respondsTo("read")) {
if(port.respondsTo("binmode")) {
port.callMethod(runtime.getCurrentContext(), "binmode");
}
parser.str(Pointer.empty(), 0, new RubyIoStrRead(port));
} else {
throw runtime.newTypeError("instance of IO needed");
}
pport[0] = port;
return taint;
}
// syck_set_model
public static void setModel(IRubyObject p, IRubyObject input, IRubyObject model) {
Ruby runtime = p.getRuntime();
Parser parser = (Parser)p.dataGetStructChecked();
parser.handler(new RubyLoadHandler(runtime, ((YAMLExtra)runtime.getModule("YAML").dataGetStruct())));
if(model == runtime.newSymbol("Generic")) {
p.callMethod(runtime.getCurrentContext(), "set_resolver", ((RubyModule)((RubyModule)runtime.getModule("YAML")).getConstant("Yecht")).getConstant("GenericResolver"));
}
parser.implicitTyping(true);
parser.taguriExpansion(true);
if(input.isNil()) {
input = (IRubyObject)((RubyObject)p).fastGetInstanceVariable("@input");
}
if(input == runtime.newSymbol("bytecode")) {
parser.setInputType(ParserInput.Bytecode_UTF8);
} else {
parser.setInputType(ParserInput.YAML_UTF8);
}
parser.errorHandler(new RubyErrHandler(runtime));
parser.badAnchorHandler(new RubyBadAnchorHandler(runtime));
}
@JRubyMethod(optional = 1)
public static IRubyObject initialize(IRubyObject self, IRubyObject[] args) {
IRubyObject options = null;
if(args.length == 0) {
options = RubyHash.newHash(self.getRuntime());
} else {
options = args[0].convertToHash();
}
((RubyObject)self).fastSetInstanceVariable("@options", options);
((RubyObject)self).fastSetInstanceVariable("@input", self.getRuntime().getNil());
((RubyObject)self).fastSetInstanceVariable("@resolver", self.getRuntime().getNil());
return self;
}
// syck_parser_bufsize_set
@JRubyMethod(name="bufsize=")
public static IRubyObject bufsize_set(IRubyObject self, IRubyObject size) {
if(size.respondsTo("to_i")) {
int n = RubyNumeric.fix2int(size.callMethod(self.getRuntime().getCurrentContext(), "to_i"));
Parser p = (Parser)self.dataGetStructChecked();
p.bufsize = n;
}
return self;
}
// syck_parser_bufsize_get
@JRubyMethod
public static IRubyObject bufsize(IRubyObject self) {
Parser p = (Parser)self.dataGetStructChecked();
return self.getRuntime().newFixnum(p.bufsize);
}
// syck_parser_load
@JRubyMethod(required = 1, optional = 1)
public static IRubyObject load(IRubyObject self, IRubyObject[] args) {
Ruby runtime = self.getRuntime();
ThreadContext ctx = runtime.getCurrentContext();
IRubyObject port = args[0];
IRubyObject proc = null;
if(args.length > 1) {
proc = args[1];
} else {
proc = runtime.getNil();
}
IRubyObject input = ((RubyHash)self.callMethod(ctx, "options")).op_aref(ctx, runtime.newSymbol("input"));
IRubyObject model = ((RubyHash)self.callMethod(ctx, "options")).op_aref(ctx, runtime.newSymbol("Model"));
Parser parser = (Parser)self.dataGetStructChecked();
setModel(self, input, model);
Extra bonus = (Extra)parser.bonus;
bonus.taint = assignIO(runtime, parser, new IRubyObject[]{port});
parser.setRootOnError(runtime.getNil());
bonus.data = RubyHash.newHash(runtime);
bonus.resolver = self.callMethod(ctx, "resolver");
// System.err.println("Parser resolver is : " + bonus.resolver);
if(proc.isNil()) {
bonus.proc = null;
} else {
bonus.proc = proc;
}
IRubyObject id = (IRubyObject)parser.parse();
IRubyObject result = id;
return result;
}
// syck_parser_load_documents
@JRubyMethod(frame=true)
public static IRubyObject load_documents(IRubyObject self, IRubyObject port, Block proc) {
Ruby runtime = self.getRuntime();
ThreadContext ctx = runtime.getCurrentContext();
IRubyObject input = ((RubyHash)self.callMethod(ctx, "options")).op_aref(ctx, runtime.newSymbol("input"));
IRubyObject model = ((RubyHash)self.callMethod(ctx, "options")).op_aref(ctx, runtime.newSymbol("Model"));
Parser parser = (Parser)self.dataGetStructChecked();
setModel(self, input, model);
Extra bonus = (Extra)parser.bonus;
bonus.taint = assignIO(runtime, parser, new IRubyObject[]{port});
parser.setRootOnError(runtime.getNil());
bonus.resolver = self.callMethod(ctx, "resolver");
bonus.proc = null;
while(true) {
bonus.data = RubyHash.newHash(runtime);
IRubyObject v = (IRubyObject)parser.parse();
if(parser.eof) {
return runtime.getNil();
}
proc.yield(ctx, v);
}
}
// syck_parser_set_resolver
@JRubyMethod
public static IRubyObject set_resolver(IRubyObject self, IRubyObject resolver) {
((RubyObject)self).fastSetInstanceVariable("@resolver", resolver);
return self;
}
}
yecht-0.0.2/ext/ruby/tests/ 0000775 0000000 0000000 00000000000 11233025100 0015533 5 ustar 00root root 0000000 0000000 yecht-0.0.2/ext/ruby/tests/basic.rb 0000664 0000000 0000000 00000136711 11233025100 0017152 0 ustar 00root root 0000000 0000000 # vim:sw=4:ts=4
# $Id$
#
require 'runit/testcase'
require 'runit/cui/testrunner'
require 'yaml'
# [ruby-core:01946]
module YAML_Tests
StructTest = Struct::new( :c )
end
class YAML_Unit_Tests < RUNIT::TestCase
#
# Convert between YAML and the object to verify correct parsing and
# emitting
#
def assert_to_yaml( obj, yaml )
assert_equal( obj, YAML::load( yaml ) )
assert_equal( obj, YAML::parse( yaml ).transform )
assert_equal( obj, YAML::load( obj.to_yaml ) )
assert_equal( obj, YAML::parse( obj.to_yaml ).transform )
assert_equal( obj, YAML::load(
obj.to_yaml( :UseVersion => true, :UseHeader => true, :SortKeys => true )
) )
# yb = YAML::Parser.new
# yb.resolver = YAML.resolver
# yb.input = :bytecode
# assert_equal( obj, yb.load( YAML::Yecht::compile( yaml ) ) )
end
#
# Test bytecode parser
#
def assert_bytecode( obj, yaml )
yp = YAML::Parser.new
yp.input = :bytecode
assert_equal( obj, yp.load( yaml ) )
end
#
# Test parser only
#
def assert_parse_only( obj, yaml )
assert_equal( obj, YAML::load( yaml ) )
assert_equal( obj, YAML::parse( yaml ).transform )
yp = YAML::Parser.new
yp.input = :bytecode
assert_equal( obj, yp.load( YAML::Yecht::compile( yaml ) ) )
end
def assert_path_segments( path, segments )
YAML::YPath.each_path( path ) { |choice|
assert_equal( choice.segments, segments.shift )
}
assert_equal( segments.length, 0, "Some segments leftover: #{ segments.inspect }" )
end
#
# Make a time with the time zone
#
def mktime( year, mon, day, hour, min, sec, usec, zone = "Z" )
usec = usec.to_s.to_f * 1000000
val = Time::utc( year.to_i, mon.to_i, day.to_i, hour.to_i, min.to_i, sec.to_i, usec )
if zone != "Z"
hour = zone[0,3].to_i * 3600
min = zone[3,2].to_i * 60
ofs = (hour + min)
val = Time.at( val.to_f - ofs )
end
return val
end
#
# Tests modified from 00basic.t in YAML.pm
#
def test_basic_map
# Simple map
map = { 'one' => 'foo', 'three' => 'baz', 'two' => 'bar' }
assert_to_yaml(
map, < 'simple string', 2 => 42, 3 => '1 Single Quoted String',
4 => 'YAML\'s Double "Quoted" String', 5 => "A block\n with several\n lines.\n",
6 => "A \"chomped\" block", 7 => "A folded\n string\n" }
assert_to_yaml(
basic, <
A
folded
string
EOY
)
assert_bytecode( basic,
"D\nM\nS1\nSsimple string\nS2\nS42\nS3\nS1 Single Quoted String\nS4\nSYAML's Double \"Quoted\" String\n" +
"S5\nSA block\nN\nC with several\nN\nC lines.\nN\nS6\nSA \"chomped\" block\nS7\nSA folded\nN\nC string\nN\nE\n" )
end
#
# Test the specification examples
# - Many examples have been changes because of whitespace problems that
# caused the two to be inequivalent, or keys to be sorted wrong
#
def test_spec_simple_implicit_sequence
# Simple implicit sequence
seq = [ 'Mark McGwire', 'Sammy Sosa', 'Ken Griffey' ]
assert_to_yaml(
seq, < 65, 'avg' => 0.278, 'rbi' => 147 }
assert_to_yaml(
map, <
[ 'Boston Red Sox', 'Detroit Tigers', 'New York Yankees' ],
'national' =>
[ 'New York Mets', 'Chicago Cubs', 'Atlanta Braves' ] }
assert_to_yaml(
nest, < 'Mark McGwire', 'hr' => 65, 'avg' => 0.278},
{'name' => 'Sammy Sosa', 'hr' => 63, 'avg' => 0.288}
]
assert_to_yaml(
nest, <
{ 'hr' => 65, 'avg' => 0.278 },
'Sammy Sosa' =>
{ 'hr' => 63, 'avg' => 0.288 }
}
assert_to_yaml(
map, < [ 'Mark McGwire', 'Sammy Sosa' ],
'rbi' => [ 'Sammy Sosa', 'Ken Griffey' ] }
assert_to_yaml(
nest, <
[ 'Mark McGwire', 'Sammy Sosa' ],
'rbi' =>
[ 'Sammy Sosa', 'Ken Griffey' ] }
assert_to_yaml( anc1, <"EDI", "departure"=>"LAX", "fareref"=>"DOGMA", "currency"=>"GBP"}, {"arrival"=>"MEL", "departure"=>"SYD", "fareref"=>"MADF", "currency"=>"AUD"}, {"arrival"=>"MCO", "departure"=>"JFK", "fareref"=>"DFSF", "currency"=>"USD"}]
assert_to_yaml(
anc2, <["fareref", "currency", "departure", "arrival"], "FARES"=>[{"arrival"=>"EDI", "departure"=>"LAX", "fareref"=>"DOGMA", "currency"=>"GBP"}, {"arrival"=>"MEL", "departure"=>"SYD", "fareref"=>"MADF", "currency"=>"AUD"}, {"arrival"=>"MCO", "departure"=>"JFK", "fareref"=>"DFSF", "currency"=>"USD"}]}
assert_to_yaml(
anc3, < [ Date.new( 2001, 7, 23 ) ],
[ 'New York Yankees', 'Atlanta Braves' ] => [ Date.new( 2001, 7, 2 ), Date.new( 2001, 8, 12 ), Date.new( 2001, 8, 14 ) ] }
assert_to_yaml(
complex, <
[ Date.new( 2001, 7, 2 ), Date.new( 2001, 8, 12 ),
Date.new( 2001, 8, 14 ) ],
[ 'Detroit Tigers', 'Chicago Cubs' ] =>
[ Date.new( 2001, 7, 23 ) ]
}, < 34843, 'date' => Date.new( 2001, 1, 23 ),
'bill-to' => 'Chris Dumars', 'product' =>
[ { 'item' => 'Super Hoop', 'quantity' => 1 },
{ 'item' => 'Basketball', 'quantity' => 4 },
{ 'item' => 'Big Shoes', 'quantity' => 1 } ] }
assert_to_yaml(
seq, < nil },
[ { 'five' => [ 'six' ] } ],
[ 'seven' ]
],
[ 'eight', 'nine' ]
]
assert_to_yaml( seq, <
Mark McGwire's
year was crippled
by a knee injury.
EOY
# Force a few elaborate folded blocks
assert_to_yaml( [ <
ruby -ropen-uri -e 'eval(open("http://go.hobix.com/").read)'
STR1
Ok, so the idea here is that one whole weblahhg is contained
in a single directory. What is stored in the directory?
hobix.yaml <- configuration
entries/ <- edit and organize
your news items,
articles and so on.
skel/ <- contains your
templates
htdocs/ <- html is created here,
store all your images here,
this is your viewable
websyht
lib/ <- extra hobix libraries
(plugins) go here
One weblahhg can be shared with many authors. In the @hobix.yaml@
file, you can store information about each author, as well as
information about others who contribute to your websyht.
You also have a file of your own, a configuration file called
@.hobixrc@, which contains a list of the weblahhgs you belong
to.
h2. Pull One From the Sky
If you would like to create your own weblahhg from scratch:
hobix create blahhg
You will be prompted for a full path where the new weblahhg can
be created. Don't worry if the directory doesn't yet exist,
Hobix will take care of clearing a path for it.
Once you give it the path, Hobix will create all the necessary
directories, as well as the @hobix.yaml@. You should also have
a set of sample templates to get you started.
In fact, if you want to generate the default site:
hobix regen blahhg
h2. Joining Hands With Others
To join an existing weblahhg:
hobix add other-blahhg /path/to/other-blahhg/hobix.yaml
You don't need to be on a weblahhg's author list to join the weblahhg.
You just need permissions to edit the file.
h2. Leaving in a Cloud of Keystrokes
To remove a weblahhg from your configuration:
hobix del other-blahhg
Please don't be afraid to edit your configuration file yourself,
should the commandline not suit your style.
See, here's my @.hobixrc@:
---
weblogs:
hobix: /usr/local/www/hobix.com/www/hobix.yaml
why: /usr/local/www/whytheluckystiff.net/www/hobix.yaml
username: why
use editor: true
That's a YAML file. Very simple to edit. You can manually edit
your information, safely add or edit your weblogs, and save back
to your @.hobixrc@.
Enough then. Time to trick out your new Hoblahhg.
You will be guided through an automatic installation (or upgrade) of
Hobix.
STR2
NOW BUNKING together: the ruby and yaml scripts up at http://go.hobix.com/. Hey ,, the life and unity we feel is tree-mending-US!!
Try:
ruby -ropen-uri -e'eval open("http://go.hobix.com/").read'
No longer are curtains dropping ON the actors' arms !! No longer are swift currents ON the actors' legs !! The actors have a bottomless cereal container, witness.
STR3
---
- |+
Here's what you're going to need:
* Ruby 1.8.0 or higher.
** Linux/FreeBSD: "Get the latest, please.":http://ruby-lang.org/en/20020102.html
** Windows: "Installer for Windows.":http://rubyinstaller.sourceforge.net/
** Mac: "OSX disk image.":http://homepage.mac.com/discord/Ruby/
* Once Ruby is installed, open a command prompt and type:
ruby -ropen-uri -e 'eval(open("http://go.hobix.com/").read)'
- |
Ok, so the idea here is that one whole weblahhg is contained
in a single directory. What is stored in the directory?
hobix.yaml <- configuration
entries/ <- edit and organize
your news items,
articles and so on.
skel/ <- contains your
templates
htdocs/ <- html is created here,
store all your images here,
this is your viewable
websyht
lib/ <- extra hobix libraries
(plugins) go here
One weblahhg can be shared with many authors. In the @hobix.yaml@
file, you can store information about each author, as well as
information about others who contribute to your websyht.
You also have a file of your own, a configuration file called
@.hobixrc@, which contains a list of the weblahhgs you belong
to.
h2. Pull One From the Sky
If you would like to create your own weblahhg from scratch:
hobix create blahhg
You will be prompted for a full path where the new weblahhg can
be created. Don't worry if the directory doesn't yet exist,
Hobix will take care of clearing a path for it.
Once you give it the path, Hobix will create all the necessary
directories, as well as the @hobix.yaml@. You should also have
a set of sample templates to get you started.
In fact, if you want to generate the default site:
hobix regen blahhg
h2. Joining Hands With Others
To join an existing weblahhg:
hobix add other-blahhg /path/to/other-blahhg/hobix.yaml
You don't need to be on a weblahhg's author list to join the weblahhg.
You just need permissions to edit the file.
h2. Leaving in a Cloud of Keystrokes
To remove a weblahhg from your configuration:
hobix del other-blahhg
Please don't be afraid to edit your configuration file yourself,
should the commandline not suit your style.
See, here's my @.hobixrc@:
---
weblogs:
hobix: /usr/local/www/hobix.com/www/hobix.yaml
why: /usr/local/www/whytheluckystiff.net/www/hobix.yaml
username: why
use editor: true
That's a YAML file. Very simple to edit. You can manually edit
your information, safely add or edit your weblogs, and save back
to your @.hobixrc@.
Enough then. Time to trick out your new Hoblahhg.
You will be guided through an automatic installation (or upgrade) of
Hobix.
- |
NOW BUNKING together: the ruby and yaml scripts up at http://go.hobix.com/. Hey ,, the life and unity we feel is tree-mending-US!!
Try:
ruby -ropen-uri -e'eval open("http://go.hobix.com/").read'
No longer are curtains dropping ON the actors' arms !! No longer are swift currents ON the actors' legs !! The actors have a bottomless cereal container, witness.
EOY
assert_bytecode( fold, "D\nQ\nSMark McGwire's year was crippled by a knee injury.\nN\nE\n" )
end
def test_spec_preserve_indent
# Preserve indented spaces
fold = "Sammy Sosa completed another fine season with great stats.\n\n 63 Home Runs\n 0.288 Batting Average\n\nWhat a year!\n"
assert_to_yaml( fold, <
Sammy Sosa completed another
fine season with great stats.
63 Home Runs
0.288 Batting Average
What a year!
EOY
assert_bytecode( fold, "D\nSSammy Sosa completed another fine season with great stats.\nN\nN\nC 63 Home Runs\nN\nC 0.288 Batting Average\nN\nN\nCWhat a year!\nN\n" )
end
def test_spec_indentation_determines_scope
map = { 'name' => 'Mark McGwire', 'accomplishment' => "Mark set a major league home run record in 1998.\n",
'stats' => "65 Home Runs\n0.278 Batting Average\n" }
assert_to_yaml( map, <
Mark set a major league
home run record in 1998.
stats: |
65 Home Runs
0.278 Batting Average
EOY
assert_bytecode( map, "D\nM\nSname\nSMark McGwire\nSaccomplishment\nSMark set a major league home run record in 1998.\nN\nSstats\nS65 Home Runs\nN\nC0.278 Batting Average\nN\nE\n" )
end
# def test_spec_quoted_scalars
# assert_to_yaml(
# {"tie-fighter"=>"|\\-*-/|", "control"=>"\0101998\t1999\t2000\n", "unicode"=>"Sosa did fine." + ["263A".hex].pack('U*'), "quoted"=>" # not a 'comment'.", "single"=>"\"Howdy!\" he cried.", "hexesc"=>"\r\n is \r\n"}, < 'This unquoted scalar spans many lines.',
'quoted' => "So does this quoted scalar.\n" }
assert_to_yaml( map, < 12345, 'decimal' => 12345, 'octal' => '014'.oct, 'hexadecimal' => '0xC'.hex }
assert_to_yaml( map, < 685230, 'decimal' => 685230, 'octal' => '02472256'.oct, 'hexadecimal' => '0x0A74AE'.hex, 'sexagesimal' => 685230 }
assert_to_yaml( map, < 1230.15, 'exponential' => 1230.15, 'fixed' => 1230.15,
'sexagecimal' => 1230.15, 'negative infinity' => -1.0/0.0 }
assert_to_yaml( map, < nil, true => true, false => false, 'string' => '12345' }
assert_to_yaml( map, < 'Chris', 'family' => 'Dumars', 'address' =>
{ 'lines' => "458 Walkman Dr.\nSuite #292\n", 'city' => 'Royal Oak',
'state' => 'MI', 'postal' => 48046 } }
invoice = { 'invoice' => 34843, 'date' => Date.new( 2001, 1, 23 ),
'bill-to' => id001, 'ship-to' => id001, 'product' =>
[ { 'sku' => 'BL394D', 'quantity' => 4,
'description' => 'Basketball', 'price' => 450.00 },
{ 'sku' => 'BL4438H', 'quantity' => 1,
'description' => 'Super Hoop', 'price' => 2392.00 } ],
'tax' => 251.42, 'total' => 4443.52,
'comments' => "Late afternoon is best. Backup contact is Nancy Billsmer @ 338-4338.\n" }
assert_to_yaml( invoice, <
Late afternoon is best.
Backup contact is Nancy
Billsmer @ 338-4338.
EOY
assert_bytecode( invoice, "D\nM\nSinvoice\nS34843\nSdate\nS2001-01-23\nSbill-to\nAid001\n" +
"M\nSgiven\nSChris\nSfamily\nT!str\nSDumars\nSaddress\n" +
"M\nSlines\nS458 Walkman Dr.\nN\nCSuite #292\nN\nScity\nSRoyal Oak\nSstate\nSMI\nSpostal\nS48046\nE\nE\n" +
"Sship-to\nRid001\nSproduct\nQ\n" +
"T!map\nM\nSsku\nSBL394D\nSquantity\nS4\nSdescription\nSBasketball\nSprice\nS450.00\nE\n" +
"M\nSsku\nSBL4438H\nSquantity\nS1\nSdescription\nSSuper Hoop\nSprice\nS2392.00\nE\nE\n" +
"Stax\nS251.42\nStotal\nS4443.52\nScomments\n" +
"SLate afternoon is best. Backup contact is Nancy Billsmer @ 338-4338.\nN\n" +
"E\n" )
end
def test_spec_log_file
doc_ct = 0
doc1 = { 'Time' => mktime( 2001, 11, 23, 15, 01, 42, 00, "-05:00" ),
'User' => 'ed', 'Warning' => "This is an error message for the log file\n" }
doc2 = { 'Time' => mktime( 2001, 11, 23, 15, 02, 31, 00, "-05:00" ),
'User' => 'ed', 'Warning' => "A slightly different error message.\n" }
doc3 = { 'Date' => mktime( 2001, 11, 23, 15, 03, 17, 00, "-05:00" ),
'User' => 'ed', 'Fatal' => "Unknown variable \"bar\"\n",
'Stack' => [
{ 'file' => 'TopClass.py', 'line' => 23, 'code' => "x = MoreObject(\"345\\n\")\n" },
{ 'file' => 'MoreClass.py', 'line' => 58, 'code' => "foo = bar" } ] }
YAML::load_documents( <
This is an error message
for the log file
---
Time: 2001-11-23 15:02:31 -05:00
User: ed
Warning: >
A slightly different error
message.
---
Date: 2001-11-23 15:03:17 -05:00
User: ed
Fatal: >
Unknown variable "bar"
Stack:
- file: TopClass.py
line: 23
code: |
x = MoreObject("345\\n")
- file: MoreClass.py
line: 58
code: |-
foo = bar
EOY
) { |doc|
case doc_ct
when 0
assert_equals( doc, doc1 )
when 1
assert_equals( doc, doc2 )
when 2
assert_equals( doc, doc3 )
end
doc_ct += 1
}
assert_equals( doc_ct, 3 )
doc_ct = 0
yp = YAML::Parser.new
yp.input = :bytecode
yp.load_documents(
"D\nM\nSTime\nS2001-11-23 15:01:42 -05:00\nSUser\nSed\nSWarning\nSThis is an error message for the log file\nN\nE\n" +
"D\nM\nSTime\nS2001-11-23 15:02:31 -05:00\nSUser\nSed\nSWarning\nSA slightly different error message.\nN\nE\n" +
"D\nM\nSDate\nS2001-11-23 15:03:17 -05:00\nSUser\nSed\nSFatal\nSUnknown variable \"bar\"\nN\nSStack\n" +
"Q\nM\nSfile\nSTopClass.py\nSline\nS23\nScode\nSx = MoreObject(\"345\\n\")\nN\nE\n" +
"M\nSfile\nSMoreClass.py\nSline\nS58\nScode\nSfoo = bar\nE\nE\nE\n"
) { |doc|
case doc_ct
when 0
assert_equals( doc, doc1 )
when 1
assert_equals( doc, doc2 )
when 2
assert_equals( doc, doc3 )
end
doc_ct += 1
}
assert_equals( doc_ct, 3 )
end
def test_spec_root_fold
y = YAML::load( <
This YAML stream contains a single text value.
The next stream is a log file - a sequence of
log entries. Adding an entry to the log is a
simple matter of appending it at the end.
EOY
)
assert_equals( y, "This YAML stream contains a single text value. The next stream is a log file - a sequence of log entries. Adding an entry to the log is a simple matter of appending it at the end.\n" )
end
def test_spec_root_mapping
y = YAML::load( < 34843, 'date' => Date.new( 2001, 1, 23 ), 'total' => 4443.52 } )
end
# def test_spec_oneline_docs
# doc_ct = 0
# YAML::load_documents( < { "customers"=> [ { "given"=>"Chris", "type"=>"domain customer", "family"=>"Dumars" } ], "type"=>"domain invoice" } }
assert_to_yaml( map, <"contains three lines of text.\nThe third one starts with a\n# character. This isn't a comment.\n"}
assert_to_yaml( map, < 12, 'also int' => 12, 'string' => '12' }
assert_to_yaml( map, < 8, 'color' => 'black' } )
# when 1
# assert_equals( doc['bearing'].type_id, 'x-private:ball' )
# assert_equals( doc['bearing'].transform.value, { 'material' => 'steel' } )
# end
# doc_ct += 1
# }
# assert_equals( doc_ct, 2 )
#
# doc_ct = 0
# YAML::Yecht::Parser.new( :Input => :Bytecode, :Model => :Generic )::load_documents(
# "D\nc Private types are per-document.\nM\nSpool\nT!!ball\n" +
# "M\nSnumber\nS8\nScolor\nSblack\nE\nE\n" +
# "D\nM\nSbearing\nT!!ball\nM\nSmaterial\nSsteel\nE\nE\n"
# ) { |doc|
# case doc_ct
# when 0
# assert_equals( doc['pool'].type_id, 'x-private:ball' )
# assert_equals( doc['pool'].transform.value, { 'number' => 8, 'color' => 'black' } )
# when 1
# assert_equals( doc['bearing'].type_id, 'x-private:ball' )
# assert_equals( doc['bearing'].transform.value, { 'material' => 'steel' } )
# end
# doc_ct += 1
# }
# assert_equals( doc_ct, 2 )
# end
def test_spec_url_escaping
YAML.add_domain_type( "domain.tld,2002", "type0" ) { |type, val|
"ONE: #{val}"
}
YAML.add_domain_type( "domain.tld,2002", "type%30" ) { |type, val|
"TWO: #{val}"
}
map = { 'same' => [ 'ONE: value', 'ONE: value' ], 'different' => [ 'TWO: value' ] }
assert_to_yaml( map, < 'This scalar has an anchor.', 'override' => a001, 'alias' => a001 }
assert_to_yaml( anc, <
The alias node below is a
repeated use of this value.
alias : *A001
EOY
assert_bytecode( anc, "D\nM\nSanchor\nAA001\nSThis scalar has an anchor.\nSoverride\nAA001\n" +
"SThe alias node below is a repeated use of this value.\nN\nSalias\nRA001\nE\n" )
end
def test_spec_explicit_families
YAML.add_domain_type( "somewhere.com,2002", 'type' ) { |type, val|
"SOMEWHERE: #{val}"
}
map = { 'not-date' => '2002-04-28', 'picture' => "GIF89a\f\000\f\000\204\000\000\377\377\367\365\365\356\351\351\345fff\000\000\000\347\347\347^^^\363\363\355\216\216\216\340\340\340\237\237\237\223\223\223\247\247\247\236\236\236i^\020' \202\n\001\000;", 'hmm' => "SOMEWHERE: family above is short for\nhttp://somewhere.com/type\n" }
assert_to_yaml( map, <7, "center"=>{"x"=>73, "y"=>129}, "TYPE"=>"Shape: graph/circle"}, {"finish"=>{"x"=>89, "y"=>102}, "TYPE"=>"Shape: graph/line", "start"=>{"x"=>73, "y"=>129}}, {"TYPE"=>"Shape: graph/text", "value"=>"Pretty vector drawing.", "start"=>{"x"=>73, "y"=>129}, "color"=>16772795}, "Shape Container"]]
assert_to_yaml( seq, < [], 'in-line' => [ 'one', 'two', 'three', 'four', 'five' ],
'nested' => [ 'First item in top sequence', [ 'Subordinate sequence entry' ],
"A multi-line sequence entry\n", 'Sixth item in top sequence' ] }, <
A multi-line
sequence entry
- Sixth item in top sequence
EOY
)
end
def test_spec_builtin_map
# Assortment of mappings
assert_to_yaml(
{ 'empty' => {}, 'in-line' => { 'one' => 1, 'two' => 2 },
'spanning' => { 'one' => 1, 'two' => 2 },
'nested' => { 'first' => 'First entry', 'second' =>
{ 'key' => 'Subordinate mapping' }, 'third' =>
[ 'Subordinate sequence', {}, 'Previous mapping is empty.',
{ 'A key' => 'value pair in a sequence.', 'A second' => 'key:value pair.' },
'The previous entry is equal to the following one.',
{ 'A key' => 'value pair in a sequence.', 'A second' => 'key:value pair.' } ],
12.0 => 'This key is a float.', "?\n" => 'This key had to be protected.',
"\a" => 'This key had to be escaped.',
"This is a multi-line folded key\n" => "Whose value is also multi-line.\n",
[ 'This key', 'is a sequence' ] => [ 'With a sequence value.' ] } }, <
?
: This key had to be protected.
"\\a" : This key had to be escaped.
? >
This is a
multi-line
folded key
: >
Whose value is
also multi-line.
?
- This key
- is a sequence
:
- With a sequence value.
# The following parses correctly,
# but Ruby 1.6.* fails the comparison!
# ?
# This: key
# is a: mapping
# :
# with a: mapping value.
EOY
)
end
def test_spec_builtin_literal_blocks
# Assortment of literal scalar blocks
assert_to_yaml(
{"both are equal to"=>" This has no newline.", "is equal to"=>"The \\ ' \" characters may be\nfreely used. Leading white\n space is significant.\n\nLine breaks are significant.\nThus this value contains one\nempty line and ends with a\nsingle line break, but does\nnot start with one.\n", "also written as"=>" This has no newline.", "indented and chomped"=>" This has no newline.", "empty"=>"", "literal"=>"The \\ ' \" characters may be\nfreely used. Leading white\n space is significant.\n\nLine breaks are significant.\nThus this value contains one\nempty line and ends with a\nsingle line break, but does\nnot start with one.\n"}, < str1, 'same as "clipped" above' => str1,
'stripped' => str2, 'same as "stripped" above' => str2,
'kept' => str3, 'same as "kept" above' => str3 }, <"a single quote ' must be escaped.", "second"=>"! : \\ etc. can be used freely.", "is same as"=>"this contains six spaces\nand one line break", "empty"=>"", "span"=>"this contains six spaces\nand one line break"}, <"this contains four spaces", "third"=>"a \" or a \\ must be escaped.", "second"=>"! : etc. can be used freely.", "empty"=>"", "fourth"=>"this value ends with an LF.\n", "span"=>"this contains four spaces"}, < mktime( 2001, 12, 14, 21, 59, 43, ".10", "-05:00" ),
"canonical" => mktime( 2001, 12, 15, 2, 59, 43, ".10" ),
"date (noon UTC)" => Date.new( 2002, 12, 14),
"valid iso8601" => mktime( 2001, 12, 14, 21, 59, 43, ".10", "-05:00" ) }, < arrow_gif, 'base64' => arrow_gif,
'description' => "The binary value above is a tiny arrow encoded as a gif image.\n" }, < /George McFly/i }, < 2, :UseVersion => 0 )
y.add(
{ 'hi' => 'hello', 'map' =>
{ 'good' => 'two' },
'time' => Time.now,
'try' => /^po(.*)$/,
'bye' => 'goodbye'
}
)
y.add( { 'po' => 'nil', 'oper' => 90 } )
y.add( { 'hi' => 'wow!', 'bye' => 'wow!' } )
y.add( { [ 'Red Socks', 'Boston' ] => [ 'One', 'Two', 'Three' ] } )
y.add( [ true, false, false ] )
end
#
# Test YPath choices parsing
#
def test_ypath_parsing
assert_path_segments( "/*/((one|three)/name|place)|//place",
[ ["*", "one", "name"],
["*", "three", "name"],
["*", "place"],
["/", "place"] ]
)
end
#
# Test of Ranges
#
def test_ranges
# Simple numeric
assert_to_yaml( 1..3, <"A,","B"=>"B"}, <2, "2"=>3}, <"b"}] * 2, <"b", "c"=>"d"} }
# YAML::load( a.to_yaml )
end
#
# Test Time.now cycle
#
def test_time_now_cycle
#
# From Minero Aoki [ruby-core:2305]
#
require 'yaml'
t = Time.now
5.times do
assert_equals( t, YAML.load( YAML.dump( t ) ) )
end
end
# #
# # Circular references
# #
# def test_circular_references
# a = []; a[0] = a; a[1] = a
# inspect_str = "[[...], [...]]"
# assert_equals( inspect_str, YAML::load( a.to_yaml ).inspect )
# end
end
RUNIT::CUI::TestRunner.run( YAML_Unit_Tests.suite )
yecht-0.0.2/ext/ruby/yts/ 0000775 0000000 0000000 00000000000 11233025100 0015210 5 ustar 00root root 0000000 0000000 yecht-0.0.2/ext/ruby/yts/YtsAnchorAlias.yml 0000664 0000000 0000000 00000002266 11233025100 0020625 0 ustar 00root root 0000000 0000000 --- %YAML:1.0
test: Simple Alias Example
brief: >
If you need to refer to the same item of data twice,
you can give that item an alias. The alias is a plain
string, starting with an ampersand. The item may then
be referred to by the alias throughout your document
by using an asterisk before the name of the alias.
This is called an anchor.
yaml: |
- &showell Steve
- Clark
- Brian
- Oren
- *showell
python: |
[
[ 'Steve', 'Clark', 'Brian', 'Oren', 'Steve']
]
ruby-setup: |
showell = 'Steve'
ruby: |
[ showell, 'Clark', 'Brian', 'Oren', showell ]
---
test: Alias of a Mapping
brief: >
An alias can be used on any item of data, including
sequences, mappings, and other complex data types.
yaml: |
- &hello
Meat: pork
Starch: potato
- banana
- *hello
python: |
[
[
{'Meat': 'pork', 'Starch': 'potato'},
'banana',
{'Meat': 'pork', 'Starch': 'potato'},
]
]
ruby-setup: |
hello = { 'Meat' => 'pork', 'Starch' => 'potato' }
ruby: |
[
hello,
'banana',
hello
]
yecht-0.0.2/ext/ruby/yts/YtsBasicTests.yml 0000664 0000000 0000000 00000013450 11233025100 0020502 0 ustar 00root root 0000000 0000000 --- %YAML:1.0
test: Simple Sequence
brief: |
You can specify a list in YAML by placing each
member of the list on a new line with an opening
dash. These lists are called sequences.
yaml: |
- apple
- banana
- carrot
perl: |
['apple', 'banana', 'carrot']
python: |
[
['apple', 'banana', 'carrot']
]
ruby: |
['apple', 'banana', 'carrot']
---
test: Nested Sequences
brief: |
You can include a sequence within another
sequence by giving the sequence an empty
dash, followed by an indented list.
yaml: |
-
- foo
- bar
- baz
perl: |
[['foo', 'bar', 'baz']]
python: |
[
[['foo', 'bar', 'baz']]
]
ruby: |
[['foo', 'bar', 'baz']]
---
test: Mixed Sequences
brief: |
Sequences can contain any YAML data,
including strings and other sequences.
yaml: |
- apple
-
- foo
- bar
- x123
- banana
- carrot
perl: |
['apple', ['foo', 'bar', 'x123'], 'banana', 'carrot']
python: |
[
['apple', ['foo', 'bar', 'x123'], 'banana', 'carrot']
]
ruby: |
['apple', ['foo', 'bar', 'x123'], 'banana', 'carrot']
---
test: Deeply Nested Sequences
brief: |
Sequences can be nested even deeper, with each
level of indentation representing a level of
depth.
yaml: |
-
-
- uno
- dos
perl: |
[[['uno', 'dos']]]
python: |
[
[[['uno', 'dos']]]
]
ruby: |
[[['uno', 'dos']]]
---
test: Simple Mapping
brief: |
You can add a keyed list (also known as a dictionary or
hash) to your document by placing each member of the
list on a new line, with a colon seperating the key
from its value. In YAML, this type of list is called
a mapping.
yaml: |
foo: whatever
bar: stuff
perl: |
{ foo => 'whatever', bar => 'stuff' }
python: |
[
{'foo': 'whatever', 'bar': 'stuff'}
]
ruby: |
{ 'foo' => 'whatever', 'bar' => 'stuff' }
---
test: Sequence in a Mapping
brief: |
A value in a mapping can be a sequence.
yaml: |
foo: whatever
bar:
- uno
- dos
perl: |
{ foo => 'whatever', bar => [ 'uno', 'dos' ] }
python: |
[
{'foo': 'whatever', 'bar': ['uno', 'dos']}
]
ruby: |
{ 'foo' => 'whatever', 'bar' => [ 'uno', 'dos' ] }
---
test: Nested Mappings
brief: |
A value in a mapping can be another mapping.
yaml: |
foo: whatever
bar:
fruit: apple
name: steve
sport: baseball
perl: |
{ foo => 'whatever',
bar => {
fruit => 'apple',
name => 'steve',
sport => 'baseball'
}
}
python: |
[
{'foo': 'whatever',
'bar': {
'fruit': 'apple',
'name': 'steve',
'sport': 'baseball'
}
}
]
ruby: |
{ 'foo' => 'whatever',
'bar' => {
'fruit' => 'apple',
'name' => 'steve',
'sport' => 'baseball'
}
}
---
test: Mixed Mapping
brief: |
A mapping can contain any assortment
of mappings and sequences as values.
yaml: |
foo: whatever
bar:
-
fruit: apple
name: steve
sport: baseball
- more
-
python: rocks
perl: papers
ruby: scissorses
perl: |
{ foo => 'whatever',
bar => [
{
fruit => 'apple',
name => 'steve',
sport => 'baseball'
},
'more',
{
python => 'rocks',
perl => 'papers',
ruby => 'scissorses'
}
]
}
python: |
[
{'foo': 'whatever',
'bar': [
{
'fruit': 'apple',
'name': 'steve',
'sport': 'baseball'
},
'more',
{
'python': 'rocks',
'perl': 'papers',
'ruby': 'scissorses'
}
]
}
]
ruby: |
{ 'foo' => 'whatever',
'bar' => [
{
'fruit' => 'apple',
'name' => 'steve',
'sport' => 'baseball'
},
'more',
{
'python' => 'rocks',
'perl' => 'papers',
'ruby' => 'scissorses'
}
]
}
---
test: Mapping-in-Sequence Shortcut
brief: |
If you are adding a mapping to a sequence, you
can place the mapping on the same line as the
dash as a shortcut.
yaml: |
- work on YAML.py:
- work on Store
perl: |
[ { 'work on YAML.py' => ['work on Store'] } ]
python: |
[
[ {'work on YAML.py': ['work on Store']} ]
]
ruby: |
[ { 'work on YAML.py' => ['work on Store'] } ]
---
test: Sequence-in-Mapping Shortcut
brief: |
The dash in a sequence counts as indentation, so
you can add a sequence inside of a mapping without
needing spaces as indentation.
yaml: |
allow:
- 'localhost'
- '%.sourceforge.net'
- '%.freepan.org'
perl: |
{ 'allow' => [ 'localhost', '%.sourceforge.net', '%.freepan.org' ] }
python: |
[
{ 'allow': [ 'localhost', '%.sourceforge.net', '%.freepan.org' ] }
]
ruby: |
{ 'allow' => [ 'localhost', '%.sourceforge.net', '%.freepan.org' ] }
---
test: Merge key
brief: |
A merge key ('<<') can be used in a mapping to insert other mappings. If
the value associated with the merge key is a mapping, each of its key/value
pairs is inserted into the current mapping.
yaml: |
mapping:
name: Joe
job: Accountant
<<:
age: 38
ruby: |
{ 'mapping' =>
{ 'name' => 'Joe',
'job' => 'Accountant',
'age' => 38
}
}
yecht-0.0.2/ext/ruby/yts/YtsBlockMapping.yml 0000664 0000000 0000000 00000002433 11233025100 0021003 0 ustar 00root root 0000000 0000000 ---
test: One Element Mapping
brief: |
A mapping with one key/value pair
yaml: |
---
foo: bar
perl: |
{foo => 'bar'}
ruby: |
{ 'foo' => 'bar' }
---
test: Multi Element Mapping
brief: |
More than one key/value pair
yaml: |
---
red: baron
white: walls
blue: berries
perl: |
{
red => 'baron',
white => 'walls',
blue => 'berries',
}
ruby: |
{
'red' => 'baron',
'white' => 'walls',
'blue' => 'berries',
}
---
test: Values aligned
brief: |
Often times human editors of documents will align the values even
though YAML emitters generally don't.
yaml: |
---
red: baron
white: walls
blue: berries
perl: |
{
red => 'baron',
white => 'walls',
blue => 'berries',
}
ruby: |
{
'red' => 'baron',
'white' => 'walls',
'blue' => 'berries',
}
---
test: Colons aligned
brief: |
Spaces can come before the ': ' key/value separator.
yaml: |
---
red : baron
white : walls
blue : berries
perl: |
{
red => 'baron',
white => 'walls',
blue => 'berries',
}
ruby: |
{
'red' => 'baron',
'white' => 'walls',
'blue' => 'berries',
}
yecht-0.0.2/ext/ruby/yts/YtsBlockSequence.yml 0000664 0000000 0000000 00000000000 11233025100 0021144 0 ustar 00root root 0000000 0000000 yecht-0.0.2/ext/ruby/yts/YtsDocumentSeparator.yml 0000664 0000000 0000000 00000003531 11233025100 0022074 0 ustar 00root root 0000000 0000000 --- %YAML:1.0
test: Trailing Document Separator
brief: >
You can separate YAML documents
with a string of three dashes.
yaml: |
- foo: 1
bar: 2
---
more: stuff
python: |
[
[ { 'foo': 1, 'bar': 2 } ],
{ 'more': 'stuff' }
]
ruby: |
[ { 'foo' => 1, 'bar' => 2 } ]
---
test: Leading Document Separator
brief: >
You can explicity give an opening
document separator to your YAML stream.
yaml: |
---
- foo: 1
bar: 2
---
more: stuff
python: |
[
[ {'foo': 1, 'bar': 2}],
{'more': 'stuff'}
]
ruby: |
[ { 'foo' => 1, 'bar' => 2 } ]
---
test: YAML Header
brief: >
The opening separator can contain directives
to the YAML parser, such as the version
number.
yaml: |
--- %YAML:1.0
foo: 1
bar: 2
python: |
[
{ 'foo': 1, 'bar': 2 }
]
ruby: |
y = YAML::Stream.new
y.add( { 'foo' => 1, 'bar' => 2 } )
documents: 1
---
test: Red Herring Document Separator
brief: >
Separators included in blocks or strings
are treated as blocks or strings, as the
document separator should have no indentation
preceding it.
yaml: |
foo: |
---
python: |
[
{ 'foo': "---\n" }
]
ruby: |
{ 'foo' => "---\n" }
---
test: Multiple Document Separators in Block
brief: >
This technique allows you to embed other YAML
documents within literal blocks.
yaml: |
foo: |
---
foo: bar
---
yo: baz
bar: |
fooness
python: |
[
{ 'foo': flushLeft("""
---
foo: bar
---
yo: baz
"""),
'bar': "fooness\n"
}
]
ruby: |
{
'foo' => "---\nfoo: bar\n---\nyo: baz\n",
'bar' => "fooness\n"
}
yecht-0.0.2/ext/ruby/yts/YtsErrorTests.yml 0000664 0000000 0000000 00000001140 11233025100 0020543 0 ustar 00root root 0000000 0000000 ---
test: Missing value for hash item
brief: |
Third item in this hash doesn't have a value
yaml: |
okay: value
also okay: ~
causes error because no value specified
last key: value okay here too
python-error: causes error because no value specified
---
test: Not indenting enough
brief: |
There was a bug in PyYaml where it was off by one
in the indentation check. It was allowing the YAML
below.
# This is actually valid YAML now. Someone should tell showell.
yaml: |
foo:
firstline: 1
secondline: 2
python-error: Inadequate indentation
yecht-0.0.2/ext/ruby/yts/YtsFlowCollections.yml 0000664 0000000 0000000 00000003470 11233025100 0021545 0 ustar 00root root 0000000 0000000 ---
test: Simple Inline Array
brief: >
Sequences can be contained on a
single line, using the inline syntax.
Separate each entry with commas and
enclose in square brackets.
yaml: |
---
seq: [ a, b, c ]
python: |
[
{ 'seq': [ 'a', 'b', 'c' ] }
]
ruby: |
{ 'seq' => [ 'a', 'b', 'c' ] }
---
test: Simple Inline Hash
brief: >
Mapping can also be contained on
a single line, using the inline
syntax. Each key-value pair is
separated by a colon, with a comma
between each entry in the mapping.
Enclose with curly braces.
yaml: |
---
hash: { name: Steve, foo: bar }
python: |
[
{ 'hash': {'name': 'Steve', 'foo': 'bar'} }
]
ruby: |
{ 'hash' => { 'name' => 'Steve', 'foo' => 'bar' } }
---
test: Multi-line Inline Collections
brief: >
Both inline sequences and inline mappings
can span multiple lines, provided that you
indent the additional lines.
yaml: |
languages: [ Ruby,
Perl,
Python ]
websites: { YAML: yaml.org,
Ruby: ruby-lang.org,
Python: python.org,
Perl: use.perl.org }
ruby: |
{ 'languages' => [ 'Ruby', 'Perl', 'Python' ],
'websites' => {
'YAML' => 'yaml.org',
'Ruby' => 'ruby-lang.org',
'Python' => 'python.org',
'Perl' => 'use.perl.org'
}
}
---
test: Commas in Values
brief: >
List items in collections are delimited by commas, but
there must be a space after each comma. This allows you
to add numbers without quoting.
yaml: |
attendances: [ 45,123, 70,000, 17,222 ]
python: |
[
{'attendances': [ 45123, 70000, 17222 ]}
]
ruby: |
{ 'attendances' => [ 45123, 70000, 17222 ] }
yecht-0.0.2/ext/ruby/yts/YtsFoldedScalars.yml 0000664 0000000 0000000 00000012165 11233025100 0021146 0 ustar 00root root 0000000 0000000 --- %YAML:1.0
test: Single ending newline
brief: >
A pipe character, followed by an indented
block of text is treated as a literal
block, in which newlines are preserved
throughout the block, including the final
newline.
yaml: |
---
this: |
Foo
Bar
ruby: |
{ 'this' => "Foo\nBar\n" }
python: |
[
{ 'this': "Foo\nBar\n" }
]
---
test: The '+' indicator
brief: >
The '+' indicator says to keep newlines at the end of text
blocks.
yaml: |
normal: |
extra new lines not kept
preserving: |+
extra new lines are kept
dummy: value
ruby: |
{
'normal' => "extra new lines not kept\n",
'preserving' => "extra new lines are kept\n\n\n",
'dummy' => 'value'
}
python: |
[ {
'normal': "extra new lines not kept\n",
'preserving': "extra new lines are kept\n\n\n",
'dummy': 'value'
} ]
---
test: Three trailing newlines in literals
brief: >
To give you more control over how space
is preserved in text blocks, YAML has
the keep '+' and chomp '-' indicators.
The keep indicator will preserve all
ending newlines, while the chomp indicator
will strip all ending newlines.
yaml: |
clipped: |
This has one newline.
same as "clipped" above: "This has one newline.\n"
stripped: |-
This has no newline.
same as "stripped" above: "This has no newline."
kept: |+
This has four newlines.
same as "kept" above: "This has four newlines.\n\n\n\n"
ruby: |
{
'clipped' => "This has one newline.\n",
'same as "clipped" above' => "This has one newline.\n",
'stripped' => 'This has no newline.',
'same as "stripped" above' => 'This has no newline.',
'kept' => "This has four newlines.\n\n\n\n",
'same as "kept" above' => "This has four newlines.\n\n\n\n"
}
not_yet_in_python: |
[
{
'clipped': "This has one newline.\n",
'same as "clipped" above': "This has one newline.\n",
'stripped': 'This has no newline.',
'same as "stripped" above': 'This has no newline.',
'kept': "This has four newlines.\n\n\n\n",
'same as "kept" above': "This has four newlines.\n\n\n\n"
}
]
---
test: Extra trailing newlines with spaces
brief: >
Normally, only a single newline is kept
from the end of a literal block, unless the
keep '+' character is used in combination
with the pipe. The following example
will preserve all ending whitespace
since the last line of both literal blocks
contains spaces which extend past the indentation
level.
yaml: |
---
this: |
Foo
kept: |+
Foo
ruby: |
{ 'this' => "Foo\n\n \n",
'kept' => "Foo\n\n \n" }
---
test: Folded Block in a Sequence
brief: >
A greater-then character, followed by an indented
block of text is treated as a folded block, in
which lines of text separated by a single newline
are concatenated as a single line.
yaml: |
---
- apple
- banana
- >
can't you see
the beauty of yaml?
hmm
- dog
python: |
[
[
'apple',
'banana',
"can't you see the beauty of yaml? hmm\n",
'dog'
]
]
ruby: |
[
'apple',
'banana',
"can't you see the beauty of yaml? hmm\n",
'dog'
]
---
test: Folded Block as a Mapping Value
brief: >
Both literal and folded blocks can be
used in collections, as values in a
sequence or a mapping.
yaml: |
---
quote: >
Mark McGwire's
year was crippled
by a knee injury.
source: espn
python: |
[
{
'quote': "Mark McGwire's year was crippled by a knee injury.\n",
'source': 'espn'
}
]
ruby: |
{
'quote' => "Mark McGwire's year was crippled by a knee injury.\n",
'source' => 'espn'
}
---
test: Three trailing newlines in folded blocks
brief: >
The keep and chomp indicators can also
be applied to folded blocks.
yaml: |
clipped: >
This has one newline.
same as "clipped" above: "This has one newline.\n"
stripped: >-
This has no newline.
same as "stripped" above: "This has no newline."
kept: >+
This has four newlines.
same as "kept" above: "This has four newlines.\n\n\n\n"
ruby: |
{
'clipped' => "This has one newline.\n",
'same as "clipped" above' => "This has one newline.\n",
'stripped' => 'This has no newline.',
'same as "stripped" above' => 'This has no newline.',
'kept' => "This has four newlines.\n\n\n\n",
'same as "kept" above' => "This has four newlines.\n\n\n\n"
}
---
test: Trailing tab in plains
yaml: |
a: b
ruby: |
{ 'a' => 'b' }
syck: |
struct test_node map[] = {
{ T_STR, 0, "a" },
{ T_STR, 0, "b" },
end_node
};
struct test_node stream[] = {
{ T_MAP, 0, 0, map },
end_node
};
yecht-0.0.2/ext/ruby/yts/YtsMapInSeq.yml 0000664 0000000 0000000 00000000000 11233025100 0020076 0 ustar 00root root 0000000 0000000 yecht-0.0.2/ext/ruby/yts/YtsNullsAndEmpties.yml 0000664 0000000 0000000 00000003651 11233025100 0021507 0 ustar 00root root 0000000 0000000 --- %YAML:1.0
test: Empty Sequence
brief: >
You can represent the empty sequence
with an empty inline sequence.
yaml: |
empty: []
python: |
[
{ 'empty': [] }
]
ruby: |
{ 'empty' => [] }
syck: |
struct test_node seq[] = {
end_node
};
struct test_node map[] = {
{ T_STR, 0, "empty" },
{ T_SEQ, 0, 0, seq },
end_node
};
struct test_node stream[] = {
{ T_MAP, 0, 0, map },
end_node
};
---
test: Empty Mapping
brief: >
You can represent the empty mapping
with an empty inline mapping.
yaml: |
empty: {}
python: |
[
{ 'empty': {} }
]
ruby: |
{ 'empty' => {} }
syck: |
struct test_node map2[] = {
end_node
};
struct test_node map1[] = {
{ T_STR, 0, "empty" },
{ T_MAP, 0, 0, map2 },
end_node
};
struct test_node stream[] = {
{ T_MAP, 0, 0, map1 },
end_node
};
---
test: Empty Sequence as Entire Document
yaml: |
--- []
python: |
[ [] ]
ruby: |
[]
syck: |
struct test_node seq[] = {
end_node
};
struct test_node stream[] = {
{ T_SEQ, 0, 0, seq },
end_node
};
---
test: Empty Mapping as Entire Document
yaml: |
--- {}
python: |
[ {} ]
ruby: |
{}
syck: |
struct test_node map[] = {
end_node
};
struct test_node stream[] = {
{ T_MAP, 0, 0, map },
end_node
};
---
test: Null as Document
yaml: |
--- ~
python: |
[ None ]
ruby: |
nil
syck: |
struct test_node stream[] = {
{ T_STR, 0, "~" },
end_node
};
---
test: Empty String
brief: >
You can represent an empty string
with a pair of quotes.
yaml: |
--- ''
python: |
[ '' ]
ruby: |
''
syck: |
struct test_node stream[] = {
{ T_STR, 0, "" },
end_node
};
yecht-0.0.2/ext/ruby/yts/YtsRubyTests.yml 0000664 0000000 0000000 00000011634 11233025100 0020404 0 ustar 00root root 0000000 0000000 --- %YAML:1.0
test: Symbols
brief: >
Ruby Symbols can be simply serialized using
the !ruby/symbol transfer method, or the
abbreviated !ruby/sym.
yaml: |
simple symbol: !ruby/symbol Simple
shortcut syntax: !ruby/sym Simple
symbols in seqs:
- !ruby/symbol ValOne
- !ruby/symbol ValTwo
- !ruby/symbol ValThree
symbols in maps:
- !ruby/symbol MapKey: !ruby/symbol MapValue
ruby: |
{ 'simple symbol' => :Simple,
'shortcut syntax' => :Simple,
'symbols in seqs' => [ :ValOne, :ValTwo, :ValThree ],
'symbols in maps' => [ { :MapKey => :MapValue } ]
}
---
test: Ranges
brief: >
Ranges are serialized with the !ruby/range
type family.
yaml: |
normal range: !ruby/range 10..20
exclusive range: !ruby/range 11...20
negative range: !ruby/range -1..-5
? !ruby/range 0..40
: range as a map key
ruby: |
{ 'normal range' => (10..20),
'exclusive range' => (11...20),
'negative range' => (-1..-5),
(0..40) => 'range as a map key'
}
---
test: Regexps
brief: >
Regexps may be serialized to YAML, both its
syntax and any modifiers.
yaml: |
case-insensitive: !ruby/regexp "/George McFly/i"
complex: !ruby/regexp "/\\A\"((?:[^\"]|\\\")+)\"/"
simple: !ruby/regexp '/a.b/'
ruby: |
{ 'simple' => /a.b/, 'complex' => /\A"((?:[^"]|\")+)"/,
'case-insensitive' => /George McFly/i }
---
test: Struct class
brief: >
The Ruby Struct class is registered as a YAML
builtin type through Ruby, so it can safely
be serialized. To use it, first make sure you
define your Struct with Struct::new. Then,
you are able to serialize with Struct#to_yaml
and unserialize from a YAML stream.
yaml: |
--- !ruby/struct:BookStruct
author: Yukihiro Matsumoto
title: Ruby in a Nutshell
year: 2002
isbn: 0-596-00214-9
ruby-setup: |
book_struct = Struct::new( "BookStruct", :author, :title, :year, :isbn )
ruby: |
book_struct.new( "Yukihiro Matsumoto", "Ruby in a Nutshell", 2002, "0-596-00214-9" )
---
test: Nested Structs
brief: >
As with other YAML builtins, you may nest the
Struct inside of other Structs or other data
types.
yaml: |
- !ruby/struct:FoodStruct
name: Nachos
ingredients:
- Mission Chips
- !ruby/struct:FoodStruct
name: Tostitos Nacho Cheese
ingredients:
- Milk and Enzymes
- Jack Cheese
- Some Volatile Chemicals
taste: Angelic
- Sour Cream
taste: Zesty
- !ruby/struct:FoodStruct
name: Banana Cream Pie
ingredients:
- Bananas
- Creamy Stuff
- And Such
taste: Puffy
ruby-setup: |
food_struct = Struct::new( "FoodStruct", :name, :ingredients, :taste )
ruby: |
[
food_struct.new( 'Nachos', [ 'Mission Chips',
food_struct.new( 'Tostitos Nacho Cheese', [ 'Milk and Enzymes', 'Jack Cheese', 'Some Volatile Chemicals' ], 'Angelic' ),
'Sour Cream' ], 'Zesty' ),
food_struct.new( 'Banana Cream Pie', [ 'Bananas', 'Creamy Stuff', 'And Such' ], 'Puffy' )
]
---
test: Objects
brief: >
YAML has generic support for serializing objects
from any class available in Ruby. If using the
generic object serialization, no extra code is
needed.
yaml: |
--- !ruby/object:Zoolander
name: Derek
look: Blue Steel
ruby-setup: |
class Zoolander
attr_accessor :name, :look
def initialize( look )
@name = "Derek"
@look = look
end
def ==( z )
self.name == z.name and self.look == z.look
end
end
ruby: |
Zoolander.new( "Blue Steel" )
---
test: Extending Kernel::Array
brief: >
When extending the Array class, your instances
of such a class will dump as YAML sequences,
tagged with a class name.
yaml: |
--- !ruby/array:MyArray
- jacket
- sweater
- windbreaker
ruby-setup: |
class MyArray < ::Array; end
ruby: |
outerwear = MyArray.new
outerwear << 'jacket'
outerwear << 'sweater'
outerwear << 'windbreaker'
outerwear
---
test: Extending Kernel::Hash
brief: >
When extending the Hash class, your instances
of such a class will dump as YAML maps, tagged
with a class name.
yaml: |
--- !ruby/hash:MyHash
Black Francis: Frank Black
Kim Deal: Breeders
Joey Santiago: Martinis
ruby-setup: |
# Note that the @me attribute isn't dumped
# because the default to_yaml is trained
# to dump as a regular Hash.
class MyHash < ::Hash
attr_accessor :me
def initialize
@me = "Why"
end
end
ruby: |
pixies = MyHash.new
pixies['Black Francis'] = 'Frank Black'
pixies['Kim Deal'] = 'Breeders'
pixies['Joey Santiago'] = 'Martinis'
pixies
yecht-0.0.2/ext/ruby/yts/YtsSpecificationExamples.yml 0000664 0000000 0000000 00000206760 11233025100 0022725 0 ustar 00root root 0000000 0000000 --- %YAML:1.0
test: Sequence of scalars
spec: 2.1
yaml: |
- Mark McGwire
- Sammy Sosa
- Ken Griffey
perl: |
[ 'Mark McGwire', 'Sammy Sosa', 'Ken Griffey' ]
python: |
[ ['Mark McGwire', 'Sammy Sosa', 'Ken Griffey'] ]
ruby: |
[ 'Mark McGwire', 'Sammy Sosa', 'Ken Griffey' ]
syck: |
struct test_node seq[] = {
{ T_STR, 0, "Mark McGwire" },
{ T_STR, 0, "Sammy Sosa" },
{ T_STR, 0, "Ken Griffey" },
end_node
};
struct test_node stream[] = {
{ T_SEQ, 0, 0, seq },
end_node
};
---
test: Mapping of scalars to scalars
spec: 2.2
yaml: |
hr: 65
avg: 0.278
rbi: 147
perl: |
{ hr => 65, avg => 0.278, rbi => 147 }
python: |
[ {'hr': 65, 'avg': .278, 'rbi': 147} ]
ruby: |
{ 'hr' => 65, 'avg' => 0.278, 'rbi' => 147 }
syck: |
struct test_node map[] = {
{ T_STR, 0, "hr" },
{ T_STR, 0, "65" },
{ T_STR, 0, "avg" },
{ T_STR, 0, "0.278" },
{ T_STR, 0, "rbi" },
{ T_STR, 0, "147" },
end_node
};
struct test_node stream[] = {
{ T_MAP, 0, 0, map },
end_node
};
---
test: Mapping of scalars to sequences
spec: 2.3
yaml: |
american:
- Boston Red Sox
- Detroit Tigers
- New York Yankees
national:
- New York Mets
- Chicago Cubs
- Atlanta Braves
perl: |
{ american =>
[ 'Boston Red Sox', 'Detroit Tigers',
'New York Yankees' ],
national =>
[ 'New York Mets', 'Chicago Cubs',
'Atlanta Braves' ]
}
python: |
[
{
'american':
['Boston Red Sox', 'Detroit Tigers',
'New York Yankees'],
'national':
['New York Mets', 'Chicago Cubs',
'Atlanta Braves']
}
]
ruby: |
{ 'american' =>
[ 'Boston Red Sox', 'Detroit Tigers',
'New York Yankees' ],
'national' =>
[ 'New York Mets', 'Chicago Cubs',
'Atlanta Braves' ]
}
syck: |
struct test_node seq1[] = {
{ T_STR, 0, "Boston Red Sox" },
{ T_STR, 0, "Detroit Tigers" },
{ T_STR, 0, "New York Yankees" },
end_node
};
struct test_node seq2[] = {
{ T_STR, 0, "New York Mets" },
{ T_STR, 0, "Chicago Cubs" },
{ T_STR, 0, "Atlanta Braves" },
end_node
};
struct test_node map[] = {
{ T_STR, 0, "american" },
{ T_SEQ, 0, 0, seq1 },
{ T_STR, 0, "national" },
{ T_SEQ, 0, 0, seq2 },
end_node
};
struct test_node stream[] = {
{ T_MAP, 0, 0, map },
end_node
};
---
test: Sequence of mappings
spec: 2.4
yaml: |
-
name: Mark McGwire
hr: 65
avg: 0.278
-
name: Sammy Sosa
hr: 63
avg: 0.288
perl: |
[
{name => 'Mark McGwire', hr => 65, avg => 0.278},
{name => 'Sammy Sosa', hr => 63, avg => 0.288}
]
python: |
[[
{
'name': 'Mark McGwire',
'hr': 65,
'avg': 0.278
},
{
'name': 'Sammy Sosa',
'hr': 63,
'avg': 0.288
}
]]
ruby: |
[
{'name' => 'Mark McGwire', 'hr' => 65, 'avg' => 0.278},
{'name' => 'Sammy Sosa', 'hr' => 63, 'avg' => 0.288}
]
syck: |
struct test_node map1[] = {
{ T_STR, 0, "name" },
{ T_STR, 0, "Mark McGwire" },
{ T_STR, 0, "hr" },
{ T_STR, 0, "65" },
{ T_STR, 0, "avg" },
{ T_STR, 0, "0.278" },
end_node
};
struct test_node map2[] = {
{ T_STR, 0, "name" },
{ T_STR, 0, "Sammy Sosa" },
{ T_STR, 0, "hr" },
{ T_STR, 0, "63" },
{ T_STR, 0, "avg" },
{ T_STR, 0, "0.288" },
end_node
};
struct test_node seq[] = {
{ T_MAP, 0, 0, map1 },
{ T_MAP, 0, 0, map2 },
end_node
};
struct test_node stream[] = {
{ T_SEQ, 0, 0, seq },
end_node
};
---
test: Legacy A5
spec: legacy_A5
yaml: |
?
- New York Yankees
- Atlanta Braves
:
- 2001-07-02
- 2001-08-12
- 2001-08-14
?
- Detroit Tigers
- Chicago Cubs
:
- 2001-07-23
perl-busted: >
YAML.pm will be able to emulate this behavior soon. In this regard
it may be somewhat more correct than Python's native behaviour which
can only use tuples as mapping keys. PyYAML will also need to figure
out some clever way to roundtrip structured keys.
python: |
[
{
('New York Yankees', 'Atlanta Braves'):
[yaml.timestamp('2001-07-02'),
yaml.timestamp('2001-08-12'),
yaml.timestamp('2001-08-14')],
('Detroit Tigers', 'Chicago Cubs'):
[yaml.timestamp('2001-07-23')]
}
]
ruby: |
{
[ 'New York Yankees', 'Atlanta Braves' ] =>
[ Date.new( 2001, 7, 2 ), Date.new( 2001, 8, 12 ), Date.new( 2001, 8, 14 ) ],
[ 'Detroit Tigers', 'Chicago Cubs' ] =>
[ Date.new( 2001, 7, 23 ) ]
}
syck: |
struct test_node seq1[] = {
{ T_STR, 0, "New York Yankees" },
{ T_STR, 0, "Atlanta Braves" },
end_node
};
struct test_node seq2[] = {
{ T_STR, 0, "2001-07-02" },
{ T_STR, 0, "2001-08-12" },
{ T_STR, 0, "2001-08-14" },
end_node
};
struct test_node seq3[] = {
{ T_STR, 0, "Detroit Tigers" },
{ T_STR, 0, "Chicago Cubs" },
end_node
};
struct test_node seq4[] = {
{ T_STR, 0, "2001-07-23" },
end_node
};
struct test_node map[] = {
{ T_SEQ, 0, 0, seq1 },
{ T_SEQ, 0, 0, seq2 },
{ T_SEQ, 0, 0, seq3 },
{ T_SEQ, 0, 0, seq4 },
end_node
};
struct test_node stream[] = {
{ T_MAP, 0, 0, map },
end_node
};
---
test: Sequence of sequences
spec: 2.5
yaml: |
- [ name , hr , avg ]
- [ Mark McGwire , 65 , 0.278 ]
- [ Sammy Sosa , 63 , 0.288 ]
perl: |
[
[ 'name', 'hr', 'avg' ],
[ 'Mark McGwire', 65, 0.278 ],
[ 'Sammy Sosa', 63, 0.288 ],
]
python: |
[[
[ 'name', 'hr', 'avg' ],
[ 'Mark McGwire', 65, 0.278 ],
[ 'Sammy Sosa', 63, 0.288 ]
]]
ruby: |
[
[ 'name', 'hr', 'avg' ],
[ 'Mark McGwire', 65, 0.278 ],
[ 'Sammy Sosa', 63, 0.288 ]
]
syck: |
struct test_node seq1[] = {
{ T_STR, 0, "name" },
{ T_STR, 0, "hr" },
{ T_STR, 0, "avg" },
end_node
};
struct test_node seq2[] = {
{ T_STR, 0, "Mark McGwire" },
{ T_STR, 0, "65" },
{ T_STR, 0, "0.278" },
end_node
};
struct test_node seq3[] = {
{ T_STR, 0, "Sammy Sosa" },
{ T_STR, 0, "63" },
{ T_STR, 0, "0.288" },
end_node
};
struct test_node seq[] = {
{ T_SEQ, 0, 0, seq1 },
{ T_SEQ, 0, 0, seq2 },
{ T_SEQ, 0, 0, seq3 },
end_node
};
struct test_node stream[] = {
{ T_SEQ, 0, 0, seq },
end_node
};
---
test: Mapping of mappings
spec: 2.6
yaml: |
Mark McGwire: {hr: 65, avg: 0.278}
Sammy Sosa: {
hr: 63,
avg: 0.288
}
perl-xxx: |
{
'Mark McGwire' => { 'hr' => 65, 'avg' => 0.278 },
'Sammy Sosa' => { 'hr' => 63, 'avg' => 0.288 },
}
not_yet_in_python: |
[{
'Mark McGwire':
{ 'hr': 65, 'avg': 0.278 },
'Sammy Sosa':
{ 'hr': 63, 'avg': 0.288 }
}]
ruby: |
{
'Mark McGwire' =>
{ 'hr' => 65, 'avg' => 0.278 },
'Sammy Sosa' =>
{ 'hr' => 63, 'avg' => 0.288 }
}
syck: |
struct test_node map1[] = {
{ T_STR, 0, "hr" },
{ T_STR, 0, "65" },
{ T_STR, 0, "avg" },
{ T_STR, 0, "0.278" },
end_node
};
struct test_node map2[] = {
{ T_STR, 0, "hr" },
{ T_STR, 0, "63" },
{ T_STR, 0, "avg" },
{ T_STR, 0, "0.288" },
end_node
};
struct test_node map[] = {
{ T_STR, 0, "Mark McGwire" },
{ T_MAP, 0, 0, map1 },
{ T_STR, 0, "Sammy Sosa" },
{ T_MAP, 0, 0, map2 },
end_node
};
struct test_node stream[] = {
{ T_MAP, 0, 0, map },
end_node
};
---
test: Two documents in a stream each with a
leading comment
spec: 2.7
yaml: |
# Ranking of 1998 home runs
---
- Mark McGwire
- Sammy Sosa
- Ken Griffey
# Team ranking
---
- Chicago Cubs
- St Louis Cardinals
perl: |
{ name => 'Mark McGwire', 'hr' => 65, 'avg' => 0.278 },
{ name => 'Sammy Sosa', 'hr' => 63, 'avg' => 0.288 }
python: |
[
{ 'name': 'Mark McGwire', 'hr': 65, 'avg': 0.278 },
{ 'name': 'Sammy Sosa', 'hr': 63, 'avg': 0.288 }
]
ruby: |
y = YAML::Stream.new
y.add( [ 'Mark McGwire', 'Sammy Sosa', 'Ken Griffey' ] )
y.add( [ 'Chicago Cubs', 'St Louis Cardinals' ] )
syck: |
struct test_node seq1[] = {
{ T_STR, 0, "Mark McGwire" },
{ T_STR, 0, "Sammy Sosa" },
{ T_STR, 0, "Ken Griffey" },
end_node
};
struct test_node seq2[] = {
{ T_STR, 0, "Chicago Cubs" },
{ T_STR, 0, "St Louis Cardinals" },
end_node
};
struct test_node stream[] = {
{ T_SEQ, 0, 0, seq1 },
{ T_SEQ, 0, 0, seq2 },
end_node
};
documents: 2
---
test: Play by play feed from a game
spec: 2.8
yaml: |
---
time: 20:03:20
player: Sammy Sosa
action: strike (miss)
...
---
time: 20:03:47
player: Sammy Sosa
action: grand slam
...
perl: |
[ 'Mark McGwire', 'Sammy Sosa', 'Ken Griffey' ]
python: |
[[ 'Mark McGwire', 'Sammy Sosa', 'Ken Griffey' ]]
ruby: |
y = YAML::Stream.new
y.add( {"player"=>"Sammy Sosa", "time"=>72200, "action"=>"strike (miss)"} )
y.add( {"player"=>"Sammy Sosa", "time"=>72227, "action"=>"grand slam"} )
syck: |
struct test_node map1[] = {
{ T_STR, 0, "time" },
{ T_STR, 0, "20:03:20" },
{ T_STR, 0, "player" },
{ T_STR, 0, "Sammy Sosa" },
{ T_STR, 0, "action" },
{ T_STR, 0, "strike (miss)" },
end_node
};
struct test_node map2[] = {
{ T_STR, 0, "time" },
{ T_STR, 0, "20:03:47" },
{ T_STR, 0, "player" },
{ T_STR, 0, "Sammy Sosa" },
{ T_STR, 0, "action" },
{ T_STR, 0, "grand slam" },
end_node
};
struct test_node stream[] = {
{ T_MAP, 0, 0, map1 },
{ T_MAP, 0, 0, map2 },
end_node
};
documents: 2
---
test: Single document with two comments
spec: 2.9
yaml: |
hr: # 1998 hr ranking
- Mark McGwire
- Sammy Sosa
rbi:
# 1998 rbi ranking
- Sammy Sosa
- Ken Griffey
perl-xxx: |
{
'hr' => [ 'Mark McGwire', 'Sammy Sosa' ],
'rbi' => [ 'Sammy Sosa', 'Ken Griffey' ]
}
python: |
[{
'hr': [ 'Mark McGwire', 'Sammy Sosa' ],
'rbi': [ 'Sammy Sosa', 'Ken Griffey' ]
}]
ruby: |
{
'hr' => [ 'Mark McGwire', 'Sammy Sosa' ],
'rbi' => [ 'Sammy Sosa', 'Ken Griffey' ]
}
syck: |
struct test_node seq1[] = {
{ T_STR, 0, "Mark McGwire" },
{ T_STR, 0, "Sammy Sosa" },
end_node
};
struct test_node seq2[] = {
{ T_STR, 0, "Sammy Sosa" },
{ T_STR, 0, "Ken Griffey" },
end_node
};
struct test_node map[] = {
{ T_STR, 0, "hr" },
{ T_SEQ, 0, 0, seq1 },
{ T_STR, 0, "rbi" },
{ T_SEQ, 0, 0, seq2 },
end_node
};
struct test_node stream[] = {
{ T_MAP, 0, 0, map },
end_node
};
---
test: Node for Sammy Sosa appears twice in this document
spec: 2.10
yaml: |
---
hr:
- Mark McGwire
# Following node labeled SS
- &SS Sammy Sosa
rbi:
- *SS # Subsequent occurance
- Ken Griffey
perl: |
{
'hr' => [ 'Mark McGwire', 'Sammy Sosa' ],
'rbi' => [ 'Sammy Sosa', 'Ken Griffey' ]
}
python: |
[{
'hr': [ 'Mark McGwire', 'Sammy Sosa' ],
'rbi': [ 'Sammy Sosa', 'Ken Griffey' ]
}]
ruby: |
{
'hr' =>
[ 'Mark McGwire', 'Sammy Sosa' ],
'rbi' =>
[ 'Sammy Sosa', 'Ken Griffey' ]
}
syck: |
struct test_node seq1[] = {
{ T_STR, 0, "Mark McGwire" },
{ T_STR, 0, "Sammy Sosa" },
end_node
};
struct test_node seq2[] = {
{ T_STR, 0, "Sammy Sosa" },
{ T_STR, 0, "Ken Griffey" },
end_node
};
struct test_node map[] = {
{ T_STR, 0, "hr" },
{ T_SEQ, 0, 0, seq1 },
{ T_STR, 0, "rbi" },
{ T_SEQ, 0, 0, seq2 },
end_node
};
struct test_node stream[] = {
{ T_MAP, 0, 0, map },
end_node
};
---
test: Mapping between sequences
spec: 2.11
yaml: |
? # PLAY SCHEDULE
- Detroit Tigers
- Chicago Cubs
:
- 2001-07-23
? [ New York Yankees,
Atlanta Braves ]
: [ 2001-07-02, 2001-08-12,
2001-08-14 ]
ruby: |
{
[ 'Detroit Tigers', 'Chicago Cubs' ] => [ Date.new( 2001, 7, 23 ) ],
[ 'New York Yankees', 'Atlanta Braves' ] => [ Date.new( 2001, 7, 2 ), Date.new( 2001, 8, 12 ), Date.new( 2001, 8, 14 ) ]
}
syck: |
struct test_node seq1[] = {
{ T_STR, 0, "New York Yankees" },
{ T_STR, 0, "Atlanta Braves" },
end_node
};
struct test_node seq2[] = {
{ T_STR, 0, "2001-07-02" },
{ T_STR, 0, "2001-08-12" },
{ T_STR, 0, "2001-08-14" },
end_node
};
struct test_node seq3[] = {
{ T_STR, 0, "Detroit Tigers" },
{ T_STR, 0, "Chicago Cubs" },
end_node
};
struct test_node seq4[] = {
{ T_STR, 0, "2001-07-23" },
end_node
};
struct test_node map[] = {
{ T_SEQ, 0, 0, seq3 },
{ T_SEQ, 0, 0, seq4 },
{ T_SEQ, 0, 0, seq1 },
{ T_SEQ, 0, 0, seq2 },
end_node
};
struct test_node stream[] = {
{ T_MAP, 0, 0, map },
end_node
};
---
test: Sequence key shortcut
spec: 2.12
yaml: |
---
# products purchased
- item : Super Hoop
quantity: 1
- item : Basketball
quantity: 4
- item : Big Shoes
quantity: 1
perl: |
[
{ item => 'Super Hoop', quantity => 1 },
{ item => 'Basketball', quantity => 4 },
{ item => 'Big Shoes', quantity => 1 }
]
ruby: |
[
{ 'item' => 'Super Hoop', 'quantity' => 1 },
{ 'item' => 'Basketball', 'quantity' => 4 },
{ 'item' => 'Big Shoes', 'quantity' => 1 }
]
python: |
[
{ 'item': 'Super Hoop', 'quantity': 1 },
{ 'item': 'Basketball', 'quantity': 4 },
{ 'item': 'Big Shoes', 'quantity': 1 }
]
syck: |
struct test_node map1[] = {
{ T_STR, 0, "item" },
{ T_STR, 0, "Super Hoop" },
{ T_STR, 0, "quantity" },
{ T_STR, 0, "1" },
end_node
};
struct test_node map2[] = {
{ T_STR, 0, "item" },
{ T_STR, 0, "Basketball" },
{ T_STR, 0, "quantity" },
{ T_STR, 0, "4" },
end_node
};
struct test_node map3[] = {
{ T_STR, 0, "item" },
{ T_STR, 0, "Big Shoes" },
{ T_STR, 0, "quantity" },
{ T_STR, 0, "1" },
end_node
};
struct test_node seq[] = {
{ T_MAP, 0, 0, map1 },
{ T_MAP, 0, 0, map2 },
{ T_MAP, 0, 0, map3 },
end_node
};
struct test_node stream[] = {
{ T_SEQ, 0, 0, seq },
end_node
};
---
test: Literal perserves newlines
spec: 2.13
yaml: |
# ASCII Art
--- |
\//||\/||
// || ||_
perl: |
"\\//||\\/||\n// || ||_\n"
ruby: |
"\\//||\\/||\n// || ||_\n"
python: |
[
flushLeft(
"""
\//||\/||
// || ||_
"""
)
]
syck: |
struct test_node stream[] = {
{ T_STR, 0, "\\//||\\/||\n// || ||_\n" },
end_node
};
---
test: Folded treats newlines as a space
spec: 2.14
yaml: |
---
Mark McGwire's
year was crippled
by a knee injury.
perl: |
"Mark McGwire's year was crippled by a knee injury."
ruby: |
"Mark McGwire's year was crippled by a knee injury."
python: |
[ "Mark McGwire's year was crippled by a knee injury." ]
syck: |
struct test_node stream[] = {
{ T_STR, 0, "Mark McGwire's year was crippled by a knee injury." },
end_node
};
---
test: Newlines preserved for indented and blank lines
spec: 2.15
yaml: |
--- >
Sammy Sosa completed another
fine season with great stats.
63 Home Runs
0.288 Batting Average
What a year!
perl: |
"Sammy Sosa completed another fine season with great stats.\n\n 63 Home Runs\n 0.288 Batting Average\n\nWhat a year!\n"
ruby: |
"Sammy Sosa completed another fine season with great stats.\n\n 63 Home Runs\n 0.288 Batting Average\n\nWhat a year!\n"
python: |
[
flushLeft(
"""
Sammy Sosa completed another fine season with great stats.
63 Home Runs
0.288 Batting Average
What a year!
"""
)
]
syck: |
struct test_node stream[] = {
{ T_STR, 0, "Sammy Sosa completed another fine season with great stats.\n\n 63 Home Runs\n 0.288 Batting Average\n\nWhat a year!\n" },
end_node
};
---
test: Indentation determines scope
spec: 2.16
yaml: |
name: Mark McGwire
accomplishment: >
Mark set a major league
home run record in 1998.
stats: |
65 Home Runs
0.278 Batting Average
perl: |
{
name => 'Mark McGwire',
accomplishment => "Mark set a major league home run record in 1998.\n",
stats => "65 Home Runs\n0.278 Batting Average\n"
}
ruby: |
{
'name' => 'Mark McGwire', 'accomplishment' => "Mark set a major league home run record in 1998.\n",
'stats' => "65 Home Runs\n0.278 Batting Average\n"
}
python: |
[
{
'name': 'Mark McGwire',
'accomplishment':
'Mark set a major league home run record in 1998.\n',
'stats': "65 Home Runs\n0.278 Batting Average\n"
}
]
syck: |
struct test_node map[] = {
{ T_STR, 0, "name" },
{ T_STR, 0, "Mark McGwire" },
{ T_STR, 0, "accomplishment" },
{ T_STR, 0, "Mark set a major league home run record in 1998.\n" },
{ T_STR, 0, "stats" },
{ T_STR, 0, "65 Home Runs\n0.278 Batting Average\n" },
end_node
};
struct test_node stream[] = {
{ T_MAP, 0, 0, map },
end_node
};
---
test: Quoted scalars
spec: 2.17
yaml: |
unicode: "Sosa did fine.\u263A"
control: "\b1998\t1999\t2000\n"
hexesc: "\x0D\x0A is \r\n"
single: '"Howdy!" he cried.'
quoted: ' # not a ''comment''.'
tie-fighter: '|\-*-/|'
perl-not-working: |
{
unicode => "Sosa did fine.\x{263A}",
control => "\x081998\t1999\t2000\n",
hexesc => "\r\n is \r\n",
single => '"Howdy!" he cried.',
quoted => " # not a 'comment'.",
"tie-fighter" => '|\\-*-/|',
}
ruby: |
{
"tie-fighter" => "|\\-*-/|",
"control"=>"\0101998\t1999\t2000\n",
"unicode"=>"Sosa did fine." + ["263A".hex ].pack('U*'),
"quoted"=>" # not a 'comment'.",
"single"=>"\"Howdy!\" he cried.",
"hexesc"=>"\r\n is \r\n"
}
python: |
[ {
'unicode': u"Sosa did fine.\u263A",
'control': "\b1998\t1999\t2000\n",
'hexesc': "\x0D\x0A is \r\n",
'single': '"Howdy!" he cried.',
'quoted': ' # not a \'comment\'.',
'tie-fighter': '|\-*-/|',
} ]
---
test: Multiline flow scalars
spec: 2.18
yaml: |
plain:
This unquoted scalar
spans many lines.
quoted: "So does this
quoted scalar.\n"
perl-not-working: |
{
plain => 'This unquoted scalar spans many lines.',
quoted => "So does this quoted scalar.\n"
}
ruby: |
{
'plain' => 'This unquoted scalar spans many lines.',
'quoted' => "So does this quoted scalar.\n"
}
python: |
[ {
'plain': 'This unquoted scalar spans many lines.',
'quoted': 'So does this quoted scalar.\n'
}
]
syck: |
struct test_node map[] = {
{ T_STR, 0, "plain" },
{ T_STR, 0, "This unquoted scalar spans many lines." },
{ T_STR, 0, "quoted" },
{ T_STR, 0, "So does this quoted scalar.\n" },
end_node
};
struct test_node stream[] = {
{ T_MAP, 0, 0, map },
end_node
};
---
test: Integers
spec: 2.19
yaml: |
canonical: 12345
decimal: +12,345
sexagecimal: 3:25:45
octal: 014
hexadecimal: 0xC
perl: |
{
canonical => 12345,
decimal => 12345,
octal => oct("014"),
hexadecimal => hex("0xC"),
}
ruby: |
{
'canonical' => 12345,
'decimal' => 12345,
'sexagecimal' => 12345,
'octal' => '014'.oct,
'hexadecimal' => '0xC'.hex
}
python: |
[ {
'canonical': 12345,
'decimal': 12345,
'octal': 014,
'hexadecimal': 0xC
} ]
syck: |
struct test_node map[] = {
{ T_STR, 0, "canonical" },
{ T_STR, 0, "12345" },
{ T_STR, 0, "decimal" },
{ T_STR, 0, "+12,345" },
{ T_STR, 0, "sexagecimal" },
{ T_STR, 0, "3:25:45" },
{ T_STR, 0, "octal" },
{ T_STR, 0, "014" },
{ T_STR, 0, "hexadecimal" },
{ T_STR, 0, "0xC" },
end_node
};
struct test_node stream[] = {
{ T_MAP, 0, 0, map },
end_node
};
---
# FIX: spec shows parens around -inf and NaN
test: Floating point
spec: 2.20
yaml: |
canonical: 1.23015e+3
exponential: 12.3015e+02
sexagecimal: 20:30.15
fixed: 1,230.15
negative infinity: -.inf
not a number: .NaN
perl: |
{
'canonical' => 1230.15,
'exponential' => 1230.15,
'fixed' => 1230.15,
'negative infinity' => "-.inf",
'not a number' => ".NaN",
}
ruby: |
{
'canonical' => 1230.15,
'exponential' => 1230.15,
'sexagecimal' => 1230.15,
'fixed' => 1230.15,
'negative infinity' => -1.0/0.0,
'not a number' => 0.0/0.0
}
if obj_y['not a number'].nan? # NaN comparison doesn't work right against 0.0/0.0
obj_r['not a number'] = obj_y['not a number']
end
python: |
[ {
'canonical': 1.23015e+3,
'exponential': 1.23015e+3,
'fixed': 1230.15,
'negative infinity': '-.inf',
'not a number': '.NaN',
} ]
syck: |
struct test_node map[] = {
{ T_STR, 0, "canonical" },
{ T_STR, 0, "1.23015e+3" },
{ T_STR, 0, "exponential" },
{ T_STR, 0, "12.3015e+02" },
{ T_STR, 0, "sexagecimal" },
{ T_STR, 0, "20:30.15" },
{ T_STR, 0, "fixed" },
{ T_STR, 0, "1,230.15" },
{ T_STR, 0, "negative infinity" },
{ T_STR, 0, "-.inf" },
{ T_STR, 0, "not a number" },
{ T_STR, 0, ".NaN" },
end_node
};
struct test_node stream[] = {
{ T_MAP, 0, 0, map },
end_node
};
---
test: Miscellaneous
spec: 2.21
yaml: |
null: ~
true: y
false: n
string: '12345'
perl: |
{
null => undef,
true => 1,
false => 0,
string => "12345"
}
ruby: |
{
nil => nil,
true => true,
false => false,
'string' => '12345'
}
python: |
[ {
'null': None,
'true': 1,
'false': 0,
'string': '12345',
} ]
syck: |
struct test_node map[] = {
{ T_STR, 0, "null" },
{ T_STR, 0, "~" },
{ T_STR, 0, "true" },
{ T_STR, 0, "y" },
{ T_STR, 0, "false" },
{ T_STR, 0, "n" },
{ T_STR, 0, "string" },
{ T_STR, 0, "12345" },
end_node
};
struct test_node stream[] = {
{ T_MAP, 0, 0, map },
end_node
};
---
test: Timestamps
spec: 2.22
yaml: |
canonical: 2001-12-15T02:59:43.1Z
iso8601: 2001-12-14t21:59:43.10-05:00
spaced: 2001-12-14 21:59:43.10 -05:00
date: 2002-12-14 # Time is noon UTC
perl: |
{
canonical => "2001-12-15T02:59:43.1Z",
iso8601 => "2001-12-14t21:59:43.10-05:00",
spaced => "2001-12-14 21:59:43.10 -05:00",
date => "2002-12-14",
}
ruby: |
{
'canonical' => YAML::mktime( 2001, 12, 15, 2, 59, 43, 0.10 ),
'iso8601' => YAML::mktime( 2001, 12, 14, 21, 59, 43, 0.10, "-05:00" ),
'spaced' => YAML::mktime( 2001, 12, 14, 21, 59, 43, 0.10, "-05:00" ),
'date' => Date.new( 2002, 12, 14 )
}
syck: |
struct test_node map[] = {
{ T_STR, 0, "canonical" },
{ T_STR, 0, "2001-12-15T02:59:43.1Z" },
{ T_STR, 0, "iso8601" },
{ T_STR, 0, "2001-12-14t21:59:43.10-05:00" },
{ T_STR, 0, "spaced" },
{ T_STR, 0, "2001-12-14 21:59:43.10 -05:00" },
{ T_STR, 0, "date" },
{ T_STR, 0, "2002-12-14" },
end_node
};
struct test_node stream[] = {
{ T_MAP, 0, 0, map },
end_node
};
---
test: legacy Timestamps test
spec: legacy D4
yaml: |
canonical: 2001-12-15T02:59:43.00Z
iso8601: 2001-02-28t21:59:43.00-05:00
spaced: 2001-12-14 21:59:43.00 -05:00
date: 2002-12-14
python: |
[ {
'canonical': yaml.timestamp('2001-12-15T02:59:43.00Z'),
'iso8601': yaml.timestamp('2001-03-01T02:59:43.00Z'),
'spaced': yaml.timestamp('2001-12-15T02:59:43.00Z'),
'date': yaml.timestamp('2002-12-14T00:00:00.00Z')
} ]
ruby: |
{
'canonical' => Time::utc( 2001, 12, 15, 2, 59, 43, 0 ),
'iso8601' => YAML::mktime( 2001, 2, 28, 21, 59, 43, 0, "-05:00" ),
'spaced' => YAML::mktime( 2001, 12, 14, 21, 59, 43, 0, "-05:00" ),
'date' => Date.new( 2002, 12, 14 )
}
syck: |
struct test_node map[] = {
{ T_STR, 0, "canonical" },
{ T_STR, 0, "2001-12-15T02:59:43.00Z" },
{ T_STR, 0, "iso8601" },
{ T_STR, 0, "2001-02-28t21:59:43.00-05:00" },
{ T_STR, 0, "spaced" },
{ T_STR, 0, "2001-12-14 21:59:43.00 -05:00" },
{ T_STR, 0, "date" },
{ T_STR, 0, "2002-12-14" },
end_node
};
struct test_node stream[] = {
{ T_MAP, 0, 0, map },
end_node
};
---
test: Various explicit families
spec: 2.23
yaml: |
not-date: !str 2002-04-28
picture: !binary |
R0lGODlhDAAMAIQAAP//9/X
17unp5WZmZgAAAOfn515eXv
Pz7Y6OjuDg4J+fn5OTk6enp
56enmleECcgggoBADs=
application specific tag: !!something |
The semantics of the tag
above may be different for
different documents.
ruby-setup: |
YAML.add_private_type( "something" ) do |type, val|
"SOMETHING: #{val}"
end
ruby: |
{
'not-date' => '2002-04-28',
'picture' => "GIF89a\f\000\f\000\204\000\000\377\377\367\365\365\356\351\351\345fff\000\000\000\347\347\347^^^\363\363\355\216\216\216\340\340\340\237\237\237\223\223\223\247\247\247\236\236\236i^\020' \202\n\001\000;",
'application specific tag' => "SOMETHING: The semantics of the tag\nabove may be different for\ndifferent documents.\n"
}
syck: |
struct test_node map[] = {
{ T_STR, 0, "not-date" },
{ T_STR, "tag:yaml.org,2002:str", "2002-04-28" },
{ T_STR, 0, "picture" },
{ T_STR, "tag:yaml.org,2002:binary", "R0lGODlhDAAMAIQAAP//9/X\n17unp5WZmZgAAAOfn515eXv\nPz7Y6OjuDg4J+fn5OTk6enp\n56enmleECcgggoBADs=\n" },
{ T_STR, 0, "application specific tag" },
{ T_STR, "x-private:something", "The semantics of the tag\nabove may be different for\ndifferent documents.\n" },
end_node
};
struct test_node stream[] = {
{ T_MAP, 0, 0, map },
end_node
};
---
test: Application specific family
spec: 2.24
yaml: |
# Establish a tag prefix
--- !clarkevans.com,2002/graph/^shape
# Use the prefix: shorthand for
# !clarkevans.com,2002/graph/circle
- !^circle
center: &ORIGIN {x: 73, 'y': 129}
radius: 7
- !^line # !clarkevans.com,2002/graph/line
start: *ORIGIN
finish: { x: 89, 'y': 102 }
- !^label
start: *ORIGIN
color: 0xFFEEBB
value: Pretty vector drawing.
ruby-setup: |
YAML.add_domain_type( "clarkevans.com,2002", 'graph/shape' ) { |type, val|
if Array === val
val << "Shape Container"
val
else
raise YAML::Error, "Invalid graph of class #{ val.class }: " + val.inspect
end
}
one_shape_proc = Proc.new { |type, val|
scheme, domain, type = type.split( /:/, 3 )
if val.is_a? ::Hash
val['TYPE'] = "Shape: #{type}"
val
else
raise YAML::Error, "Invalid graph of class #{ val.class }: " + val.inspect
end
}
YAML.add_domain_type( "clarkevans.com,2002", 'graph/circle', &one_shape_proc )
YAML.add_domain_type( "clarkevans.com,2002", 'graph/line', &one_shape_proc )
YAML.add_domain_type( "clarkevans.com,2002", 'graph/label', &one_shape_proc )
ruby: |
[
{
"radius" => 7,
"center"=>
{
"x" => 73,
"y" => 129
},
"TYPE" => "Shape: graph/circle"
}, {
"finish" =>
{
"x" => 89,
"y" => 102
},
"TYPE" => "Shape: graph/line",
"start" =>
{
"x" => 73,
"y" => 129
}
}, {
"TYPE" => "Shape: graph/label",
"value" => "Pretty vector drawing.",
"start" =>
{
"x" => 73,
"y" => 129
},
"color" => 16772795
},
"Shape Container"
]
syck: |
struct test_node point1[] = {
{ T_STR, 0, "x" },
{ T_STR, 0, "73" },
{ T_STR, 0, "y" },
{ T_STR, 0, "129" },
end_node
};
struct test_node point2[] = {
{ T_STR, 0, "x" },
{ T_STR, 0, "89" },
{ T_STR, 0, "y" },
{ T_STR, 0, "102" },
end_node
};
struct test_node map1[] = {
{ T_STR, 0, "center" },
{ T_MAP, 0, 0, point1 },
{ T_STR, 0, "radius" },
{ T_STR, 0, "7" },
end_node
};
struct test_node map2[] = {
{ T_STR, 0, "start" },
{ T_MAP, 0, 0, point1 },
{ T_STR, 0, "finish" },
{ T_MAP, 0, 0, point2 },
end_node
};
struct test_node map3[] = {
{ T_STR, 0, "start" },
{ T_MAP, 0, 0, point1 },
{ T_STR, 0, "color" },
{ T_STR, 0, "0xFFEEBB" },
{ T_STR, 0, "value" },
{ T_STR, 0, "Pretty vector drawing." },
end_node
};
struct test_node seq[] = {
{ T_MAP, "tag:clarkevans.com,2002:graph/circle", 0, map1 },
{ T_MAP, "tag:clarkevans.com,2002:graph/line", 0, map2 },
{ T_MAP, "tag:clarkevans.com,2002:graph/label", 0, map3 },
end_node
};
struct test_node stream[] = {
{ T_SEQ, "tag:clarkevans.com,2002:graph/shape", 0, seq },
end_node
};
# ---
# test: Unordered set
# spec: 2.25
# yaml: |
# # sets are represented as a
# # mapping where each key is
# # associated with the empty string
# --- !set
# ? Mark McGwire
# ? Sammy Sosa
# ? Ken Griff
---
test: Ordered mappings
spec: 2.26
yaml: |
# ordered maps are represented as
# a sequence of mappings, with
# each mapping having one key
--- !omap
- Mark McGwire: 65
- Sammy Sosa: 63
- Ken Griffy: 58
ruby: |
YAML::Omap[
'Mark McGwire', 65,
'Sammy Sosa', 63,
'Ken Griffy', 58
]
syck: |
struct test_node map1[] = {
{ T_STR, 0, "Mark McGwire" },
{ T_STR, 0, "65" },
end_node
};
struct test_node map2[] = {
{ T_STR, 0, "Sammy Sosa" },
{ T_STR, 0, "63" },
end_node
};
struct test_node map3[] = {
{ T_STR, 0, "Ken Griffy" },
{ T_STR, 0, "58" },
end_node
};
struct test_node seq[] = {
{ T_MAP, 0, 0, map1 },
{ T_MAP, 0, 0, map2 },
{ T_MAP, 0, 0, map3 },
end_node
};
struct test_node stream[] = {
{ T_SEQ, "tag:yaml.org,2002:omap", 0, seq },
end_node
};
---
test: Invoice
spec: 2.27
yaml: |
--- !clarkevans.com,2002/^invoice
invoice: 34843
date : 2001-01-23
bill-to: &id001
given : Chris
family : Dumars
address:
lines: |
458 Walkman Dr.
Suite #292
city : Royal Oak
state : MI
postal : 48046
ship-to: *id001
product:
- sku : BL394D
quantity : 4
description : Basketball
price : 450.00
- sku : BL4438H
quantity : 1
description : Super Hoop
price : 2392.00
tax : 251.42
total: 4443.52
comments: >
Late afternoon is best.
Backup contact is Nancy
Billsmer @ 338-4338.
ruby-setup: |
YAML.add_domain_type( "clarkevans.com,2002", "invoice" ) { |type, val| val }
id001 = { 'given' => 'Chris', 'family' => 'Dumars', 'address' =>
{ 'lines' => "458 Walkman Dr.\nSuite #292\n", 'city' => 'Royal Oak',
'state' => 'MI', 'postal' => 48046 } }
ruby: |
{
'invoice' => 34843, 'date' => Date.new( 2001, 1, 23 ),
'bill-to' => id001, 'ship-to' => id001, 'product' =>
[ { 'sku' => 'BL394D', 'quantity' => 4,
'description' => 'Basketball', 'price' => 450.00 },
{ 'sku' => 'BL4438H', 'quantity' => 1,
'description' => 'Super Hoop', 'price' => 2392.00 } ],
'tax' => 251.42, 'total' => 4443.52,
'comments' => "Late afternoon is best. Backup contact is Nancy Billsmer @ 338-4338.\n" }
syck: |
struct test_node prod1[] = {
{ T_STR, 0, "sku" },
{ T_STR, 0, "BL394D" },
{ T_STR, 0, "quantity" },
{ T_STR, 0, "4" },
{ T_STR, 0, "description" },
{ T_STR, 0, "Basketball" },
{ T_STR, 0, "price" },
{ T_STR, 0, "450.00" },
end_node
};
struct test_node prod2[] = {
{ T_STR, 0, "sku" },
{ T_STR, 0, "BL4438H" },
{ T_STR, 0, "quantity" },
{ T_STR, 0, "1" },
{ T_STR, 0, "description" },
{ T_STR, 0, "Super Hoop" },
{ T_STR, 0, "price" },
{ T_STR, 0, "2392.00" },
end_node
};
struct test_node products[] = {
{ T_MAP, 0, 0, prod1 },
{ T_MAP, 0, 0, prod2 },
end_node
};
struct test_node address[] = {
{ T_STR, 0, "lines" },
{ T_STR, 0, "458 Walkman Dr.\nSuite #292\n" },
{ T_STR, 0, "city" },
{ T_STR, 0, "Royal Oak" },
{ T_STR, 0, "state" },
{ T_STR, 0, "MI" },
{ T_STR, 0, "postal" },
{ T_STR, 0, "48046" },
end_node
};
struct test_node id001[] = {
{ T_STR, 0, "given" },
{ T_STR, 0, "Chris" },
{ T_STR, 0, "family" },
{ T_STR, 0, "Dumars" },
{ T_STR, 0, "address" },
{ T_MAP, 0, 0, address },
end_node
};
struct test_node map[] = {
{ T_STR, 0, "invoice" },
{ T_STR, 0, "34843" },
{ T_STR, 0, "date" },
{ T_STR, 0, "2001-01-23" },
{ T_STR, 0, "bill-to" },
{ T_MAP, 0, 0, id001 },
{ T_STR, 0, "ship-to" },
{ T_MAP, 0, 0, id001 },
{ T_STR, 0, "product" },
{ T_SEQ, 0, 0, products },
{ T_STR, 0, "tax" },
{ T_STR, 0, "251.42" },
{ T_STR, 0, "total" },
{ T_STR, 0, "4443.52" },
{ T_STR, 0, "comments" },
{ T_STR, 0, "Late afternoon is best. Backup contact is Nancy Billsmer @ 338-4338.\n" },
end_node
};
struct test_node stream[] = {
{ T_MAP, "tag:clarkevans.com,2002:invoice", 0, map },
end_node
};
---
test: Log file
spec: 2.28
yaml: |
---
Time: 2001-11-23 15:01:42 -05:00
User: ed
Warning: >
This is an error message
for the log file
---
Time: 2001-11-23 15:02:31 -05:00
User: ed
Warning: >
A slightly different error
message.
---
Date: 2001-11-23 15:03:17 -05:00
User: ed
Fatal: >
Unknown variable "bar"
Stack:
- file: TopClass.py
line: 23
code: |
x = MoreObject("345\n")
- file: MoreClass.py
line: 58
code: |-
foo = bar
ruby: |
y = YAML::Stream.new
y.add( { 'Time' => YAML::mktime( 2001, 11, 23, 15, 01, 42, 00, "-05:00" ),
'User' => 'ed', 'Warning' => "This is an error message for the log file\n" } )
y.add( { 'Time' => YAML::mktime( 2001, 11, 23, 15, 02, 31, 00, "-05:00" ),
'User' => 'ed', 'Warning' => "A slightly different error message.\n" } )
y.add( { 'Date' => YAML::mktime( 2001, 11, 23, 15, 03, 17, 00, "-05:00" ),
'User' => 'ed', 'Fatal' => "Unknown variable \"bar\"\n",
'Stack' => [
{ 'file' => 'TopClass.py', 'line' => 23, 'code' => "x = MoreObject(\"345\\n\")\n" },
{ 'file' => 'MoreClass.py', 'line' => 58, 'code' => "foo = bar" } ] } )
syck: |
struct test_node map1[] = {
{ T_STR, 0, "Time" },
{ T_STR, 0, "2001-11-23 15:01:42 -05:00" },
{ T_STR, 0, "User" },
{ T_STR, 0, "ed" },
{ T_STR, 0, "Warning" },
{ T_STR, 0, "This is an error message for the log file\n" },
end_node
};
struct test_node map2[] = {
{ T_STR, 0, "Time" },
{ T_STR, 0, "2001-11-23 15:02:31 -05:00" },
{ T_STR, 0, "User" },
{ T_STR, 0, "ed" },
{ T_STR, 0, "Warning" },
{ T_STR, 0, "A slightly different error message.\n" },
end_node
};
struct test_node file1[] = {
{ T_STR, 0, "file" },
{ T_STR, 0, "TopClass.py" },
{ T_STR, 0, "line" },
{ T_STR, 0, "23" },
{ T_STR, 0, "code" },
{ T_STR, 0, "x = MoreObject(\"345\\n\")\n" },
end_node
};
struct test_node file2[] = {
{ T_STR, 0, "file" },
{ T_STR, 0, "MoreClass.py" },
{ T_STR, 0, "line" },
{ T_STR, 0, "58" },
{ T_STR, 0, "code" },
{ T_STR, 0, "foo = bar" },
end_node
};
struct test_node stack[] = {
{ T_MAP, 0, 0, file1 },
{ T_MAP, 0, 0, file2 },
end_node
};
struct test_node map3[] = {
{ T_STR, 0, "Date" },
{ T_STR, 0, "2001-11-23 15:03:17 -05:00" },
{ T_STR, 0, "User" },
{ T_STR, 0, "ed" },
{ T_STR, 0, "Fatal" },
{ T_STR, 0, "Unknown variable \"bar\"\n" },
{ T_STR, 0, "Stack" },
{ T_SEQ, 0, 0, stack },
end_node
};
struct test_node stream[] = {
{ T_MAP, 0, 0, map1 },
{ T_MAP, 0, 0, map2 },
{ T_MAP, 0, 0, map3 },
end_node
};
documents: 3
---
test: Throwaway comments
yaml: |
### These are four throwaway comment ###
### lines (the second line is empty). ###
this: | # Comments may trail lines.
contains three lines of text.
The third one starts with a
# character. This isn't a comment.
# These are three throwaway comment
# lines (the first line is empty).
ruby: |
{
'this' => "contains three lines of text.\nThe third one starts with a\n# character. This isn't a comment.\n"
}
syck: |
struct test_node map[] = {
{ T_STR, 0, "this" },
{ T_STR, 0, "contains three lines of text.\nThe third one starts with a\n# character. This isn't a comment.\n" },
end_node
};
struct test_node stream[] = {
{ T_MAP, 0, 0, map },
end_node
};
---
test: Document with a single value
yaml: |
--- >
This YAML stream contains a single text value.
The next stream is a log file - a sequence of
log entries. Adding an entry to the log is a
simple matter of appending it at the end.
ruby: |
"This YAML stream contains a single text value. The next stream is a log file - a sequence of log entries. Adding an entry to the log is a simple matter of appending it at the end.\n"
syck: |
struct test_node stream[] = {
{ T_STR, 0, "This YAML stream contains a single text value. The next stream is a log file - a sequence of log entries. Adding an entry to the log is a simple matter of appending it at the end.\n" },
end_node
};
---
test: Document stream
yaml: |
---
at: 2001-08-12 09:25:00.00 Z
type: GET
HTTP: '1.0'
url: '/index.html'
---
at: 2001-08-12 09:25:10.00 Z
type: GET
HTTP: '1.0'
url: '/toc.html'
ruby: |
y = YAML::Stream.new
y.add( {
'at' => Time::utc( 2001, 8, 12, 9, 25, 00 ),
'type' => 'GET',
'HTTP' => '1.0',
'url' => '/index.html'
} )
y.add( {
'at' => Time::utc( 2001, 8, 12, 9, 25, 10 ),
'type' => 'GET',
'HTTP' => '1.0',
'url' => '/toc.html'
} )
syck: |
struct test_node map1[] = {
{ T_STR, 0, "at" },
{ T_STR, 0, "2001-08-12 09:25:00.00 Z" },
{ T_STR, 0, "type" },
{ T_STR, 0, "GET" },
{ T_STR, 0, "HTTP" },
{ T_STR, 0, "1.0" },
{ T_STR, 0, "url" },
{ T_STR, 0, "/index.html" },
end_node
};
struct test_node map2[] = {
{ T_STR, 0, "at" },
{ T_STR, 0, "2001-08-12 09:25:10.00 Z" },
{ T_STR, 0, "type" },
{ T_STR, 0, "GET" },
{ T_STR, 0, "HTTP" },
{ T_STR, 0, "1.0" },
{ T_STR, 0, "url" },
{ T_STR, 0, "/toc.html" },
end_node
};
struct test_node stream[] = {
{ T_MAP, 0, 0, map1 },
{ T_MAP, 0, 0, map2 },
end_node
};
documents: 2
---
test: Top level mapping
yaml: |
# This stream is an example of a top-level mapping.
invoice : 34843
date : 2001-01-23
total : 4443.52
ruby: |
{
'invoice' => 34843,
'date' => Date.new( 2001, 1, 23 ),
'total' => 4443.52
}
syck: |
struct test_node map[] = {
{ T_STR, 0, "invoice" },
{ T_STR, 0, "34843" },
{ T_STR, 0, "date" },
{ T_STR, 0, "2001-01-23" },
{ T_STR, 0, "total" },
{ T_STR, 0, "4443.52" },
end_node
};
struct test_node stream[] = {
{ T_MAP, 0, 0, map },
end_node
};
---
test: Single-line documents
yaml: |
# The following is a sequence of three documents.
# The first contains an empty mapping, the second
# an empty sequence, and the last an empty string.
--- {}
--- [ ]
--- ''
ruby: |
y = YAML::Stream.new
y.add( {} )
y.add( [] )
y.add( '' )
syck: |
struct test_node map[] = {
end_node
};
struct test_node seq[] = {
end_node
};
struct test_node stream[] = {
{ T_MAP, 0, 0, map },
{ T_SEQ, 0, 0, seq },
{ T_STR, 0, "" },
end_node
};
documents: 3
---
test: Document with pause
yaml: |
# A communication channel based on a YAML stream.
---
sent at: 2002-06-06 11:46:25.10 Z
payload: Whatever
# Receiver can process this as soon as the following is sent:
...
# Even if the next message is sent long after:
---
sent at: 2002-06-06 12:05:53.47 Z
payload: Whatever
...
ruby: |
y = YAML::Stream.new
y.add(
{ 'sent at' => YAML::mktime( 2002, 6, 6, 11, 46, 25, 0.10 ),
'payload' => 'Whatever' }
)
y.add(
{ "payload" => "Whatever", "sent at" => YAML::mktime( 2002, 6, 6, 12, 5, 53, 0.47 ) }
)
syck: |
struct test_node map1[] = {
{ T_STR, 0, "sent at" },
{ T_STR, 0, "2002-06-06 11:46:25.10 Z" },
{ T_STR, 0, "payload" },
{ T_STR, 0, "Whatever" },
end_node
};
struct test_node map2[] = {
{ T_STR, 0, "sent at" },
{ T_STR, 0, "2002-06-06 12:05:53.47 Z" },
{ T_STR, 0, "payload" },
{ T_STR, 0, "Whatever" },
end_node
};
struct test_node stream[] = {
{ T_MAP, 0, 0, map1 },
{ T_MAP, 0, 0, map2 },
end_node
};
documents: 2
---
test: Explicit typing
yaml: |
integer: 12
also int: ! "12"
string: !str 12
ruby: |
{ 'integer' => 12, 'also int' => 12, 'string' => '12' }
syck: |
struct test_node map[] = {
{ T_STR, 0, "integer" },
{ T_STR, "tag:yaml.org,2002:int", "12" },
{ T_STR, 0, "also int" },
{ T_STR, "tag:yaml.org,2002:int", "12" },
{ T_STR, 0, "string" },
{ T_STR, "tag:yaml.org,2002:str", "12" },
end_node
};
struct test_node stream[] = {
{ T_MAP, 0, 0, map },
end_node
};
---
test: Private types
yaml: |
# Both examples below make use of the 'x-private:ball'
# type family URI, but with different semantics.
---
pool: !!ball
number: 8
color: black
---
bearing: !!ball
material: steel
ruby: |
y = YAML::Stream.new
y.add( { 'pool' =>
YAML::PrivateType.new( 'ball',
{ 'number' => 8, 'color' => 'black' } ) }
)
y.add( { 'bearing' =>
YAML::PrivateType.new( 'ball',
{ 'material' => 'steel' } ) }
)
syck: |
struct test_node pool[] = {
{ T_STR, 0, "number" },
{ T_STR, 0, "8" },
{ T_STR, 0, "color" },
{ T_STR, 0, "black" },
end_node
};
struct test_node map1[] = {
{ T_STR, 0, "pool" },
{ T_MAP, "x-private:ball", 0, pool },
end_node
};
struct test_node bearing[] = {
{ T_STR, 0, "material" },
{ T_STR, 0, "steel" },
end_node
};
struct test_node map2[] = {
{ T_STR, 0, "bearing" },
{ T_MAP, "x-private:ball", 0, bearing },
end_node
};
struct test_node stream[] = {
{ T_MAP, 0, 0, map1 },
{ T_MAP, 0, 0, map2 },
end_node
};
documents: 2
---
test: Type family under yaml.org
yaml: |
# The URI is 'tag:yaml.org,2002:str'
- !str a Unicode string
python: |
[ [ 'a Unicode string' ] ]
ruby: |
[ 'a Unicode string' ]
syck: |
struct test_node seq[] = {
{ T_STR, "tag:yaml.org,2002:str", "a Unicode string" },
end_node
};
struct test_node stream[] = {
{ T_SEQ, 0, 0, seq },
end_node
};
---
test: Type family under perl.yaml.org
yaml: |
# The URI is 'tag:perl.yaml.org,2002:Text::Tabs'
- !perl/Text::Tabs {}
ruby: |
[ YAML::DomainType.new( 'perl.yaml.org,2002', 'Text::Tabs', {} ) ]
syck: |
struct test_node map[] = {
end_node
};
struct test_node seq[] = {
{ T_MAP, "tag:perl.yaml.org,2002:Text::Tabs", 0, map },
end_node
};
struct test_node stream[] = {
{ T_SEQ, 0, 0, seq },
end_node
};
---
test: Type family under clarkevans.com
yaml: |
# The URI is 'tag:clarkevans.com,2003-02:timesheet'
- !clarkevans.com,2003-02/timesheet {}
ruby: |
[ YAML::DomainType.new( 'clarkevans.com,2003-02', 'timesheet', {} ) ]
syck: |
struct test_node map[] = {
end_node
};
struct test_node seq[] = {
{ T_MAP, "tag:clarkevans.com,2003-02:timesheet", 0, map },
end_node
};
struct test_node stream[] = {
{ T_SEQ, 0, 0, seq },
end_node
};
---
test: URI Escaping
yaml: |
same:
- !domain.tld,2002/type\x30 value
- !domain.tld,2002/type0 value
different: # As far as the YAML parser is concerned
- !domain.tld,2002/type%30 value
- !domain.tld,2002/type0 value
ruby-setup: |
YAML.add_domain_type( "domain.tld,2002", "type0" ) { |type, val|
"ONE: #{val}"
}
YAML.add_domain_type( "domain.tld,2002", "type%30" ) { |type, val|
"TWO: #{val}"
}
ruby: |
{ 'same' => [ 'ONE: value', 'ONE: value' ], 'different' => [ 'TWO: value', 'ONE: value' ] }
syck: |
struct test_node same[] = {
{ T_STR, "tag:domain.tld,2002:type0", "value" },
{ T_STR, "tag:domain.tld,2002:type0", "value" },
end_node
};
struct test_node diff[] = {
{ T_STR, "tag:domain.tld,2002:type%30", "value" },
{ T_STR, "tag:domain.tld,2002:type0", "value" },
end_node
};
struct test_node map[] = {
{ T_STR, 0, "same" },
{ T_SEQ, 0, 0, same },
{ T_STR, 0, "different" },
{ T_SEQ, 0, 0, diff },
end_node
};
struct test_node stream[] = {
{ T_MAP, 0, 0, map },
end_node
};
---
test: URI Prefixing
yaml: |
# 'tag:domain.tld,2002:invoice' is some type family.
invoice: !domain.tld,2002/^invoice
# 'seq' is shorthand for 'tag:yaml.org,2002:seq'.
# This does not effect '^customer' below
# because it is does not specify a prefix.
customers: !seq
# '^customer' is shorthand for the full
# notation 'tag:domain.tld,2002:customer'.
- !^customer
given : Chris
family : Dumars
ruby-setup: |
YAML.add_domain_type( "domain.tld,2002", /(invoice|customer)/ ) { |type, val|
if val.is_a? ::Hash
scheme, domain, type = type.split( /:/, 3 )
val['type'] = "domain #{type}"
val
else
raise YAML::Error, "Not a Hash in domain.tld/invoice: " + val.inspect
end
}
ruby: |
{ "invoice"=> { "customers"=> [ { "given"=>"Chris", "type"=>"domain customer", "family"=>"Dumars" } ], "type"=>"domain invoice" } }
---
test: Overriding anchors
yaml: |
anchor : &A001 This scalar has an anchor.
override : &A001 >
The alias node below is a
repeated use of this value.
alias : *A001
ruby: |
{ 'anchor' => 'This scalar has an anchor.',
'override' => "The alias node below is a repeated use of this value.\n",
'alias' => "The alias node below is a repeated use of this value.\n" }
syck: |
struct test_node map[] = {
{ T_STR, 0, "anchor" },
{ T_STR, 0, "This scalar has an anchor." },
{ T_STR, 0, "override" },
{ T_STR, 0, "The alias node below is a repeated use of this value.\n" },
{ T_STR, 0, "alias" },
{ T_STR, 0, "The alias node below is a repeated use of this value.\n" },
end_node
};
struct test_node stream[] = {
{ T_MAP, 0, 0, map },
end_node
};
---
test: Flow and block formatting
yaml: |
empty: []
flow: [ one, two, three # May span lines,
, four, # indentation is
five ] # mostly ignored.
block:
- First item in top sequence
-
- Subordinate sequence entry
- >
A folded sequence entry
- Sixth item in top sequence
ruby: |
{ 'empty' => [], 'flow' => [ 'one', 'two', 'three', 'four', 'five' ],
'block' => [ 'First item in top sequence', [ 'Subordinate sequence entry' ],
"A folded sequence entry\n", 'Sixth item in top sequence' ] }
syck: |
struct test_node empty[] = {
end_node
};
struct test_node flow[] = {
{ T_STR, 0, "one" },
{ T_STR, 0, "two" },
{ T_STR, 0, "three" },
{ T_STR, 0, "four" },
{ T_STR, 0, "five" },
end_node
};
struct test_node inblock[] = {
{ T_STR, 0, "Subordinate sequence entry" },
end_node
};
struct test_node block[] = {
{ T_STR, 0, "First item in top sequence" },
{ T_SEQ, 0, 0, inblock },
{ T_STR, 0, "A folded sequence entry\n" },
{ T_STR, 0, "Sixth item in top sequence" },
end_node
};
struct test_node map[] = {
{ T_STR, 0, "empty" },
{ T_SEQ, 0, 0, empty },
{ T_STR, 0, "flow" },
{ T_SEQ, 0, 0, flow },
{ T_STR, 0, "block" },
{ T_SEQ, 0, 0, block },
end_node
};
struct test_node stream[] = {
{ T_MAP, 0, 0, map },
end_node
};
---
test: Complete mapping test
yaml: |
empty: {}
flow: { one: 1, two: 2 }
spanning: { one: 1,
two: 2 }
block:
first : First entry
second:
key: Subordinate mapping
third:
- Subordinate sequence
- { }
- Previous mapping is empty.
- A key: value pair in a sequence.
A second: key:value pair.
- The previous entry is equal to the following one.
-
A key: value pair in a sequence.
A second: key:value pair.
!float 12 : This key is a float.
? >
?
: This key had to be protected.
"\a" : This key had to be escaped.
? >
This is a
multi-line
folded key
: Whose value is
also multi-line.
? this also works as a key
: with a value at the next line.
?
- This key
- is a sequence
:
- With a sequence value.
?
This: key
is a: mapping
:
with a: mapping value.
ruby: |
{ 'empty' => {}, 'flow' => { 'one' => 1, 'two' => 2 },
'spanning' => { 'one' => 1, 'two' => 2 },
'block' => { 'first' => 'First entry', 'second' =>
{ 'key' => 'Subordinate mapping' }, 'third' =>
[ 'Subordinate sequence', {}, 'Previous mapping is empty.',
{ 'A key' => 'value pair in a sequence.', 'A second' => 'key:value pair.' },
'The previous entry is equal to the following one.',
{ 'A key' => 'value pair in a sequence.', 'A second' => 'key:value pair.' } ],
12.0 => 'This key is a float.', "?\n" => 'This key had to be protected.',
"\a" => 'This key had to be escaped.',
"This is a multi-line folded key\n" => "Whose value is also multi-line.",
'this also works as a key' => 'with a value at the next line.',
[ 'This key', 'is a sequence' ] => [ 'With a sequence value.' ] } }
# Couldn't recreate map exactly, so we'll do a detailed check to be sure it's entact
obj_y['block'].keys.each { |k|
if Hash === k
v = obj_y['block'][k]
if k['This'] == 'key' and k['is a'] == 'mapping' and v['with a'] == 'mapping value.'
obj_r['block'][k] = v
end
end
}
---
test: Literal explicit indentation
yaml: |
# Explicit indentation must
# be given in all the three
# following cases.
leading spaces: |2
This value starts with four spaces.
leading line break: |2
This value starts with a line break.
leading comment indicator: |2
# first line starts with a
# character.
# Explicit indentation may
# also be given when it is
# not required.
redundant: |2
This value is indented 2 spaces.
ruby: |
{
'leading spaces' => " This value starts with four spaces.\n",
'leading line break' => "\nThis value starts with a line break.\n",
'leading comment indicator' => "# first line starts with a\n# character.\n",
'redundant' => "This value is indented 2 spaces.\n"
}
---
test: Chomping and keep modifiers
yaml: |
clipped: |
This has one newline.
same as "clipped" above: "This has one newline.\n"
stripped: |-
This has no newline.
same as "stripped" above: "This has no newline."
kept: |+
This has two newlines.
same as "kept" above: "This has two newlines.\n\n"
ruby: |
{
'clipped' => "This has one newline.\n",
'same as "clipped" above' => "This has one newline.\n",
'stripped' => 'This has no newline.',
'same as "stripped" above' => 'This has no newline.',
'kept' => "This has two newlines.\n\n",
'same as "kept" above' => "This has two newlines.\n\n"
}
---
test: Literal combinations
yaml: |
empty: |
literal: |
The \ ' " characters may be
freely used. Leading white
space is significant.
Line breaks are significant.
Thus this value contains one
empty line and ends with a
single line break, but does
not start with one.
is equal to: "The \\ ' \" characters may \
be\nfreely used. Leading white\n space \
is significant.\n\nLine breaks are \
significant.\nThus this value contains \
one\nempty line and ends with a\nsingle \
line break, but does\nnot start with one.\n"
# Comments may follow a block
# scalar value. They must be
# less indented.
# Modifiers may be combined in any order.
indented and chomped: |2-
This has no newline.
also written as: |-2
This has no newline.
both are equal to: " This has no newline."
ruby: |
{
'empty' => '',
'literal' => "The \\ ' \" characters may be\nfreely used. Leading white\n space " +
"is significant.\n\nLine breaks are significant.\nThus this value contains one\n" +
"empty line and ends with a\nsingle line break, but does\nnot start with one.\n",
'is equal to' => "The \\ ' \" characters may be\nfreely used. Leading white\n space " +
"is significant.\n\nLine breaks are significant.\nThus this value contains one\n" +
"empty line and ends with a\nsingle line break, but does\nnot start with one.\n",
'indented and chomped' => ' This has no newline.',
'also written as' => ' This has no newline.',
'both are equal to' => ' This has no newline.'
}
syck: |
struct test_node map[] = {
{ T_STR, 0, "empty" },
{ T_STR, 0, "" },
{ T_STR, 0, "literal" },
{ T_STR, 0, "The \\ ' \" characters may be\nfreely used. Leading white\n space "
"is significant.\n\nLine breaks are significant.\nThus this value contains one\n"
"empty line and ends with a\nsingle line break, but does\nnot start with one.\n" },
{ T_STR, 0, "is equal to" },
{ T_STR, 0, "The \\ ' \" characters may be\nfreely used. Leading white\n space "
"is significant.\n\nLine breaks are significant.\nThus this value contains one\n"
"empty line and ends with a\nsingle line break, but does\nnot start with one.\n" },
{ T_STR, 0, "indented and chomped" },
{ T_STR, 0, " This has no newline." },
{ T_STR, 0, "also written as" },
{ T_STR, 0, " This has no newline." },
{ T_STR, 0, "both are equal to" },
{ T_STR, 0, " This has no newline." },
end_node
};
struct test_node stream[] = {
{ T_MAP, 0, 0, map },
end_node
};
---
test: Folded combinations
yaml: |
empty: >
one paragraph: >
Line feeds are converted
to spaces, so this value
contains no line breaks
except for the final one.
multiple paragraphs: >2
An empty line, either
at the start or in
the value:
Is interpreted as a
line break. Thus this
value contains three
line breaks.
indented text: >
This is a folded
paragraph followed
by a list:
* first entry
* second entry
Followed by another
folded paragraph,
another list:
* first entry
* second entry
And a final folded
paragraph.
above is equal to: |
This is a folded paragraph followed by a list:
* first entry
* second entry
Followed by another folded paragraph, another list:
* first entry
* second entry
And a final folded paragraph.
# Explicit comments may follow
# but must be less indented.
ruby: |
{
'empty' => '',
'one paragraph' => 'Line feeds are converted to spaces, so this value' +
" contains no line breaks except for the final one.\n",
'multiple paragraphs' => "\nAn empty line, either at the start or in the value:\n" +
"Is interpreted as a line break. Thus this value contains three line breaks.\n",
'indented text' => "This is a folded paragraph followed by a list:\n" +
" * first entry\n * second entry\nFollowed by another folded paragraph, " +
"another list:\n\n * first entry\n\n * second entry\n\nAnd a final folded paragraph.\n",
'above is equal to' => "This is a folded paragraph followed by a list:\n" +
" * first entry\n * second entry\nFollowed by another folded paragraph, " +
"another list:\n\n * first entry\n\n * second entry\n\nAnd a final folded paragraph.\n"
}
---
test: Single quotes
yaml: |
empty: ''
second: '! : \ etc. can be used freely.'
third: 'a single quote '' must be escaped.'
span: 'this contains
six spaces
and one
line break'
is same as: "this contains six spaces\nand one line break"
ruby: |
{
'empty' => '',
'second' => '! : \\ etc. can be used freely.',
'third' => "a single quote ' must be escaped.",
'span' => "this contains six spaces\nand one line break",
'is same as' => "this contains six spaces\nand one line break"
}
---
test: Double quotes
yaml: |
empty: ""
second: "! : etc. can be used freely."
third: "a \" or a \\ must be escaped."
fourth: "this value ends with an LF.\n"
span: "this contains
four \
spaces"
is equal to: "this contains four spaces"
ruby: |
{
'empty' => '',
'second' => '! : etc. can be used freely.',
'third' => 'a " or a \\ must be escaped.',
'fourth' => "this value ends with an LF.\n",
'span' => "this contains four spaces",
'is equal to' => "this contains four spaces"
}
---
test: Unquoted strings
yaml: |
first: There is no unquoted empty string.
second: 12 ## This is an integer.
third: !str 12 ## This is a string.
span: this contains
six spaces
and one
line break
indicators: this has no comments.
#:foo and bar# are
both text.
flow: [ can span
lines, # comment
like
this ]
note: { one-line keys: but multi-line values }
ruby: |
{
'first' => 'There is no unquoted empty string.',
'second' => 12,
'third' => '12',
'span' => "this contains six spaces\nand one line break",
'indicators' => "this has no comments. #:foo and bar# are both text.",
'flow' => [ 'can span lines', 'like this' ],
'note' => { 'one-line keys' => 'but multi-line values' }
}
---
test: Spanning sequences
yaml: |
# The following are equal seqs
# with different identities.
flow: [ one, two ]
spanning: [ one,
two ]
block:
- one
- two
ruby: |
{
'flow' => [ 'one', 'two' ],
'spanning' => [ 'one', 'two' ],
'block' => [ 'one', 'two' ]
}
---
test: Flow mappings
yaml: |
# The following are equal maps
# with different identities.
flow: { one: 1, two: 2 }
block:
one: 1
two: 2
ruby: |
{
'flow' => { 'one' => 1, 'two' => 2 },
'block' => { 'one' => 1, 'two' => 2 }
}
---
test: Representations of 12
yaml: |
- 12 # An integer
# The following scalars
# are loaded to the
# string value '1' '2'.
- !str 12
- '12'
- "12"
- "\
1\
2\
"
# Strings containing paths and regexps can be unquoted:
- /foo/bar
- d:/foo/bar
- foo/bar
- /a.*b/
ruby: |
[ 12, '12', '12', '12', '12', '/foo/bar', 'd:/foo/bar', 'foo/bar', '/a.*b/' ]
---
test: "Null"
yaml: |
canonical: ~
english: null
# This sequence has five
# entries, two with values.
sparse:
- ~
- 2nd entry
- Null
- 4th entry
-
four: This mapping has five keys,
only two with values.
ruby: |
{
'canonical' => nil,
'english' => nil,
'sparse' => [ nil, '2nd entry', nil, '4th entry', nil ],
'four' => 'This mapping has five keys, only two with values.'
}
---
test: Omap
yaml: |
# Explicitly typed dictionary.
Bestiary: !omap
- aardvark: African pig-like ant eater. Ugly.
- anteater: South-American ant eater. Two species.
- anaconda: South-American constrictor snake. Scary.
# Etc.
ruby: |
{
'Bestiary' => YAML::Omap[
'aardvark', 'African pig-like ant eater. Ugly.',
'anteater', 'South-American ant eater. Two species.',
'anaconda', 'South-American constrictor snake. Scary.'
]
}
---
test: Pairs
yaml: |
# Explicitly typed pairs.
tasks: !pairs
- meeting: with team.
- meeting: with boss.
- break: lunch.
- meeting: with client.
ruby: |
{
'tasks' => YAML::Pairs[
'meeting', 'with team.',
'meeting', 'with boss.',
'break', 'lunch.',
'meeting', 'with client.'
]
}
---
test: Set
yaml: |
# Explicitly typed set.
baseball players: !set
Mark McGwire:
Sammy Sosa:
Ken Griffey:
ruby: |
{
'baseball players' => YAML::Set[
'Mark McGwire', nil,
'Sammy Sosa', nil,
'Ken Griffey', nil
]
}
---
test: Boolean
yaml: |
false: used as key
logical: true
answer: no
ruby: |
{
false => 'used as key',
'logical' => true,
'answer' => false
}
---
test: Integer
yaml: |
canonical: 12345
decimal: +12,345
octal: 014
hexadecimal: 0xC
ruby: |
{
'canonical' => 12345,
'decimal' => 12345,
'octal' => 12,
'hexadecimal' => 12
}
---
test: Float
yaml: |
canonical: 1.23015e+3
exponential: 12.3015e+02
fixed: 1,230.15
negative infinity: -.inf
not a number: .NaN
ruby: |
{
'canonical' => 1230.15,
'exponential' => 1230.15,
'fixed' => 1230.15,
'negative infinity' => -1.0/0.0,
'not a number' => 0.0/0.0
}
if obj_y['not a number'].nan? # NaN comparison doesn't work right against 0.0/0.0
obj_r['not a number'] = obj_y['not a number']
end
---
test: Timestamp
yaml: |
canonical: 2001-12-15T02:59:43.1Z
valid iso8601: 2001-12-14t21:59:43.10-05:00
space separated: 2001-12-14 21:59:43.10 -05:00
date (noon UTC): 2002-12-14
ruby: |
{
'canonical' => YAML::mktime( 2001, 12, 15, 2, 59, 43, 0.10 ),
'valid iso8601' => YAML::mktime( 2001, 12, 14, 21, 59, 43, 0.10, "-05:00" ),
'space separated' => YAML::mktime( 2001, 12, 14, 21, 59, 43, 0.10, "-05:00" ),
'date (noon UTC)' => Date.new( 2002, 12, 14 )
}
syck: |
struct test_node map[] = {
{ T_STR, 0, "canonical" },
{ T_STR, 0, "2001-12-15T02:59:43.1Z" },
{ T_STR, 0, "valid iso8601" },
{ T_STR, 0, "2001-12-14t21:59:43.10-05:00" },
{ T_STR, 0, "space separated" },
{ T_STR, 0, "2001-12-14 21:59:43.10 -05:00" },
{ T_STR, 0, "date (noon UTC)" },
{ T_STR, 0, "2002-12-14" },
end_node
};
struct test_node stream[] = {
{ T_MAP, 0, 0, map },
end_node
};
---
test: Binary
yaml: |
canonical: !binary "\
R0lGODlhDAAMAIQAAP//9/X17unp5WZmZgAAAOfn515eXvPz7Y6OjuDg4J+fn5\
OTk6enp56enmlpaWNjY6Ojo4SEhP/++f/++f/++f/++f/++f/++f/++f/++f/+\
+f/++f/++f/++f/++f/++SH+Dk1hZGUgd2l0aCBHSU1QACwAAAAADAAMAAAFLC\
AgjoEwnuNAFOhpEMTRiggcz4BNJHrv/zCFcLiwMWYNG84BwwEeECcgggoBADs="
base64: !binary |
R0lGODlhDAAMAIQAAP//9/X17unp5WZmZgAAAOfn515eXvPz7Y6OjuDg4J+fn5
OTk6enp56enmlpaWNjY6Ojo4SEhP/++f/++f/++f/++f/++f/++f/++f/++f/+
+f/++f/++f/++f/++f/++SH+Dk1hZGUgd2l0aCBHSU1QACwAAAAADAAMAAAFLC
AgjoEwnuNAFOhpEMTRiggcz4BNJHrv/zCFcLiwMWYNG84BwwEeECcgggoBADs=
description: >
The binary value above is a tiny arrow
encoded as a gif image.
ruby-setup: |
arrow_gif = "GIF89a\f\000\f\000\204\000\000\377\377\367\365\365\356\351\351\345fff\000\000\000\347\347\347^^^\363\363\355\216\216\216\340\340\340\237\237\237\223\223\223\247\247\247\236\236\236iiiccc\243\243\243\204\204\204\377\376\371\377\376\371\377\376\371\377\376\371\377\376\371\377\376\371\377\376\371\377\376\371\377\376\371\377\376\371\377\376\371\377\376\371\377\376\371\377\376\371!\376\016Made with GIMP\000,\000\000\000\000\f\000\f\000\000\005, \216\2010\236\343@\024\350i\020\304\321\212\010\034\317\200M$z\357\3770\205p\270\2601f\r\e\316\001\303\001\036\020' \202\n\001\000;"
ruby: |
{
'canonical' => arrow_gif,
'base64' => arrow_gif,
'description' => "The binary value above is a tiny arrow encoded as a gif image.\n"
}
---
test: Merge key
yaml: |
---
- &CENTER { x: 1, y: 2 }
- &LEFT { x: 0, y: 2 }
- &BIG { r: 10 }
- &SMALL { r: 1 }
# All the following maps are equal:
- # Explicit keys
x: 1
y: 2
r: 10
label: center/big
- # Merge one map
<< : *CENTER
r: 10
label: center/big
- # Merge multiple maps
<< : [ *CENTER, *BIG ]
label: center/big
- # Override
<< : [ *BIG, *LEFT, *SMALL ]
x: 1
label: center/big
ruby-setup: |
center = { 'x' => 1, 'y' => 2 }
left = { 'x' => 0, 'y' => 2 }
big = { 'r' => 10 }
small = { 'r' => 1 }
node1 = { 'x' => 1, 'y' => 2, 'r' => 10, 'label' => 'center/big' }
node2 = center.dup
node2.update( { 'r' => 10, 'label' => 'center/big' } )
node3 = big.dup
node3.update( center )
node3.update( { 'label' => 'center/big' } )
node4 = small.dup
node4.update( left )
node4.update( big )
node4.update( { 'x' => 1, 'label' => 'center/big' } )
ruby: |
[
center, left, big, small, node1, node2, node3, node4
]
---
test: Default key
yaml: |
--- # Old schema
link with:
- library1.dll
- library2.dll
--- # New schema
link with:
- = : library1.dll
version: 1.2
- = : library2.dll
version: 2.3
ruby: |
y = YAML::Stream.new
y.add( { 'link with' => [ 'library1.dll', 'library2.dll' ] } )
obj_h = Hash[ 'version' => 1.2 ]
obj_h.default = 'library1.dll'
obj_h2 = Hash[ 'version' => 2.3 ]
obj_h2.default = 'library2.dll'
y.add( { 'link with' => [ obj_h, obj_h2 ] } )
documents: 2
---
test: Special keys
yaml: |
"!": These three keys
"&": had to be quoted
"=": and are normal strings.
# NOTE: the following node should NOT be serialized this way.
encoded node :
!special '!' : '!type'
!special|canonical '&' : 12
= : value
# The proper way to serialize the above node is as follows:
node : !!type &12 value
ruby: |
{ '!' => 'These three keys', '&' => 'had to be quoted',
'=' => 'and are normal strings.',
'encoded node' => YAML::PrivateType.new( 'type', 'value' ),
'node' => YAML::PrivateType.new( 'type', 'value' ) }
yecht-0.0.2/ext/ruby/yts/YtsTypeTransfers.yml 0000664 0000000 0000000 00000016127 11233025100 0021253 0 ustar 00root root 0000000 0000000 --- %YAML:1.0
test: Strings
brief: >
Any group of characters beginning with an
alphabetic or numeric character is a string,
unless it belongs to one of the groups below
(such as an Integer or Time).
yaml: |
--- String
ruby: |
'String'
---
test: String characters
brief: >
A string can contain any alphabetic or
numeric character, along with many
punctuation characters, including the
period, dash, space, quotes, exclamation, and
question mark.
yaml: |
- What's Yaml?
- It's for writing data structures in plain text.
- And?
- And what? That's not good enough for you?
- No, I mean, "And what about Yaml?"
- Oh, oh yeah. Uh.. Yaml for Ruby.
ruby: |
[
"What's Yaml?",
"It's for writing data structures in plain text.",
"And?",
"And what? That's not good enough for you?",
"No, I mean, \"And what about Yaml?\"",
"Oh, oh yeah. Uh.. Yaml for Ruby."
]
---
test: Indicators in Strings
brief: >
Be careful using indicators in strings. In particular,
the comma, colon, and pound sign must be used carefully.
yaml: |
the colon followed by space is an indicator: but is a string:right here
same for the pound sign: here we have it#in a string
the comma can, honestly, be used in most cases: [ but not in, inline collections ]
ruby: |
{
'the colon followed by space is an indicator' => 'but is a string:right here',
'same for the pound sign' => 'here we have it#in a string',
'the comma can, honestly, be used in most cases' => [ 'but not in', 'inline collections' ]
}
---
test: Forcing Strings
brief: >
Any YAML type can be forced into a string using the
explicit !str method.
yaml: |
date string: !str 2001-08-01
number string: !str 192
ruby: |
{
'date string' => '2001-08-01',
'number string' => '192'
}
---
test: Single-quoted Strings
brief: >
You can also enclose your strings within single quotes,
which allows use of slashes, colons, and other indicators
freely. Inside single quotes, you can represent a single
quote in your string by using two single quotes next to
each other.
yaml: |
all my favorite symbols: '#:!/%.)'
a few i hate: '&(*'
why do i hate them?: 'it''s very hard to explain'
ruby: |
{
'all my favorite symbols' => '#:!/%.)',
'a few i hate' => '&(*',
'why do i hate them?' => 'it\'s very hard to explain'
}
---
test: Double-quoted Strings
brief: >
Enclosing strings in double quotes allows you
to use escapings to represent ASCII and
Unicode characters.
yaml: |
i know where i want my line breaks: "one here\nand another here\n"
ruby: |
{
'i know where i want my line breaks' => "one here\nand another here\n"
}
---
test: Multi-line Quoted Strings
brief: >
Both single- and double-quoted strings may be
carried on to new lines in your YAML document.
They must be indented a step and indentation
is interpreted as a single space.
yaml: |
i want a long string: "so i'm going to
let it go on and on to other lines
until i end it with a quote."
ruby: |
{ 'i want a long string' => "so i'm going to " +
"let it go on and on to other lines " +
"until i end it with a quote."
}
---
test: Plain scalars
brief: >
Unquoted strings may also span multiple lines, if they
are free of YAML space indicators and indented.
yaml: |
- My little toe is broken in two places;
- I'm crazy to have skied this way;
- I'm not the craziest he's seen, since there was always the German guy
who skied for 3 hours on a broken shin bone (just below the kneecap);
- Nevertheless, second place is respectable, and he doesn't
recommend going for the record;
- He's going to put my foot in plaster for a month;
- This would impair my skiing ability somewhat for the
duration, as can be imagined.
ruby: |
[
"My little toe is broken in two places;",
"I'm crazy to have skied this way;",
"I'm not the craziest he's seen, since there was always " +
"the German guy who skied for 3 hours on a broken shin " +
"bone (just below the kneecap);",
"Nevertheless, second place is respectable, and he doesn't " +
"recommend going for the record;",
"He's going to put my foot in plaster for a month;",
"This would impair my skiing ability somewhat for the duration, " +
"as can be imagined."
]
---
test: 'Null'
brief: >
You can use the tilde '~' character for a null value.
yaml: |
name: Mr. Show
hosted by: Bob and David
date of next season: ~
ruby: |
{
'name' => 'Mr. Show',
'hosted by' => 'Bob and David',
'date of next season' => nil
}
---
test: Boolean
brief: >
You can use 'true' and 'false' for boolean values.
yaml: |
Is Gus a Liar?: true
Do I rely on Gus for Sustenance?: false
ruby: |
{
'Is Gus a Liar?' => true,
'Do I rely on Gus for Sustenance?' => false
}
---
test: Integers
brief: >
An integer is a series of numbers, optionally
starting with a positive or negative sign. Integers
may also contain commas for readability.
yaml: |
zero: 0
simple: 12
one-thousand: 1,000
negative one-thousand: -1,000
ruby: |
{
'zero' => 0,
'simple' => 12,
'one-thousand' => 1000,
'negative one-thousand' => -1000
}
python: |
[
{
'zero': 0,
'simple': 12,
'one-thousand': 1000,
'negative one-thousand': -1000,
}
]
---
test: Integers as Map Keys
brief: >
An integer can be used a dictionary key.
yaml: |
1: one
2: two
3: three
python: |
[
{
1: 'one',
2: 'two',
3: 'three',
}
]
ruby: |
{
1 => 'one',
2 => 'two',
3 => 'three'
}
---
test: Floats
brief: >
Floats are represented by numbers with decimals,
allowing for scientific notation, as well as
positive and negative infinity and "not a number."
yaml: |
a simple float: 2.00
larger float: 1,000.09
scientific notation: 1.00009e+3
ruby: |
{
'a simple float' => 2.0,
'larger float' => 1000.09,
'scientific notation' => 1000.09
}
---
test: Time
brief: >
You can represent timestamps by using
ISO8601 format, or a variation which
allows spaces between the date, time and
time zone.
yaml: |
iso8601: 2001-12-14t21:59:43.10-05:00
space seperated: 2001-12-14 21:59:43.10 -05:00
ruby: |
{
'iso8601' => YAML::mktime( 2001, 12, 14, 21, 59, 43, 0.10, "-05:00" ),
'space seperated' => YAML::mktime( 2001, 12, 14, 21, 59, 43, 0.10, "-05:00" )
}
---
test: Date
brief: >
A date can be represented by its year,
month and day in ISO8601 order.
yaml: |
--- 1976-07-31
ruby: |
Date.new( 1976, 7, 31 )
yecht-0.0.2/ext/ruby/yts/YtsYpath.yml 0000664 0000000 0000000 00000005630 11233025100 0017524 0 ustar 00root root 0000000 0000000 data:
apple: red
ypath: /
expected:
- /
---
data:
apple: red
ypath: .
expected:
- /
---
data:
apple: red
ypath: /*
expected:
- /apple
---
data:
apple: red
lemon: yellow
ypath: /*
expected:
- /apple
- /lemon
unordered: 1
---
data:
fruit:
banana: yellow
vegetable:
carrot: orange
ypath: //.
expected:
- /
- /fruit
- /fruit/banana
- /vegetable
- /vegetable/carrot
unordered: 1
---
data:
one:
two: xxx
ypath: //two/..
expected:
- /one
---
data:
apple: red
ypath: /apple
expected:
- /apple
---
data:
apple: red
lemon: yellow
ypath: /"lemon"
expected:
- /lemon
---
data:
apple: red
lemon: yellow
ypath: /'lemon'
expected:
- /lemon
---
data:
apple: red
lemon: yellow
ypath: /lemon
expected:
- /lemon
---
data:
- apple
- lemon
ypath: /0
expected:
- /0
---
data:
apple: red
lemon: yellow
ypath: /orange
expected: []
---
data:
apple: red
ypath: ./.
expected:
- /
---
data:
fruit:
banana: yellow
vegetable:
carrot: orange
ypath: /fruit/banana
expected:
- /fruit/banana
---
data:
fruit:
banana: yellow
vegetable:
carrot: orange
ypath: fruit/banana
expected:
- /fruit/banana
---
data:
names:
- Steve Howell
- Clark Evans
ypath: /names/0
expected:
- /names/0
---
data:
names:
- first: Clark
last: Evans
- first: Steve
last: Howell
ypath: /names/1/first
expected:
- /names/1/first
---
data:
names:
- first: Clark
last: Evans
- first: Steve
last: Howell
ypath: /names/*/first
expected:
- /names/0/first
- /names/1/first
---
data:
names:
python-heads:
- first: Clark
last: Evans
- first: Steve
last: Howell
perl-heads:
- first: Brian
last: Ingerson
ypath: names//first
expected:
- /names/python-heads/0/first
- /names/python-heads/1/first
- /names/perl-heads/0/first
---
data:
task:
- name: wake
foo: bar
- name: eat
task:
- name: veggies
- name: meats
- name: sleep
ypath: //task
expected:
- /task
- /task/1/task
---
data:
- one:
name: xxx
- two:
name: yyy
- three:
name: zzz
ypath: /*/one/name|//three/name
expected:
- /0/one/name
- /2/three/name
---
data:
apple: red
ypath: .|/apple|apple|/|.
expected:
- /
- /apple
---
data:
- one:
name: xxx
- two:
name: yyy
- three:
name: zzz
ypath: /*/(one|three)/name
expected:
- /0/one/name
- /2/three/name
---
data:
- one: xxx
- two: yyy
- one: zzz
ypath: /*[one]
expected:
- /0
- /2
---
data:
- food: Hamburger
calories: 900
- food: Fries
calories: 650
- food: Soft Drink
calories: 350
ypath: //food[.=Fries]
expected:
- /1/food
yecht-0.0.2/ext/ruby/yts/cookbook.rb 0000664 0000000 0000000 00000006557 11233025100 0017360 0 ustar 00root root 0000000 0000000 # vim:sw=4:ts=4
# $Id$
#
# Cookbook Generator for YamlTestingSuite
#
require 'erb/erbl'
require 'yaml'
ytsFiles = [
[ 'YtsBasicTests.yml', {
'name' => 'Collections',
'doc' => []
} ],
[ 'YtsFlowCollections.yml', {
'name' => 'Inline Collections',
'doc' => []
} ],
[ 'YtsTypeTransfers.yml', {
'name' => 'Basic Types',
'doc' => []
} ],
[ 'YtsFoldedScalars.yml', {
'name' => 'Blocks',
'doc' => []
} ],
[ 'YtsAnchorAlias.yml', {
'name' => 'Aliases and Anchors',
'doc' => []
} ],
[ 'YtsDocumentSeparator.yml', {
'name' => 'Documents',
'doc' => []
} ],
[ 'YtsRubyTests.yml', {
'name' => 'YAML For Ruby',
'doc' => []
} ]
# [ 'YtsSpecificationExamples.yml', {
# 'name' => 'Examples from the Specification',
# 'doc' => []
# } ]
]
ytsFiles.each do |yt|
yt[1]['doc'] = YAML::load_stream( File.open( yt[0] ) )
yt[1]['href'] = yt[1]['name'].downcase.gsub( /\s+/, '_' )
end
erb = ERbLight.new( <
<% ytsFiles.each do |yt| %>
- <%= yt[1]['name'] %>
<% if yt[1]['doc'].documents.length > 0 %>
<%
yt[1]['doc'].documents.each do |ydoc|
ydoc['href'] = ydoc['test'].downcase.gsub( /\s+/, '_' ) if ydoc['test']
%>
- <%= ydoc['test'] %>
<%
end
%>
<% end %>
<% end %>
<% ytsFiles.each do |yt| %>
<% if yt[1]['doc'].documents.length > 0
yt[1]['doc'].documents.each do |ydoc|
%>
Brief
<%= ydoc['brief'] %>
Yaml
Ruby
|
<% if ydoc.has_key?( 'ruby-setup' ) %>
<%= ydoc['ruby-setup'] %>
<% end %>
<%= ydoc['ruby'] %>
|
|
|
<% end
end %>
<% end %>
TMPL
)
puts erb.result
yecht-0.0.2/ext/ruby/yts/index.yml 0000664 0000000 0000000 00000000304 11233025100 0017037 0 ustar 00root root 0000000 0000000 - YtsBasicTests
- YtsBlockMapping
- YtsFlowCollections
- YtsTypeTransfers
- YtsFoldedScalars
- YtsAnchorAlias
- YtsDocumentSeparator
- YtsNullsAndEmpties
- YtsRubyTests
- YtsSpecificationExamples
yecht-0.0.2/ext/ruby/yts/yts.rb 0000664 0000000 0000000 00000010761 11233025100 0016361 0 ustar 00root root 0000000 0000000 # vim:sw=4:ts=4
# $Id$
#
require 'yaml'
module YAML
#
# Make a time with the time zone
#
def YAML::mktime( year, mon, day, hour, min, sec, usec, zone = "Z" )
usec = usec.to_s.to_f * 1000000
val = Time::utc( year.to_i, mon.to_i, day.to_i, hour.to_i, min.to_i, sec.to_i, usec )
if zone != "Z"
hour = zone[0,3].to_i * 3600
min = zone[3,2].to_i * 60
ofs = (hour + min)
val = Time.at( val.to_f - ofs )
end
return val
end
class Stream
def ==( doc )
self.documents == doc.documents
end
end
class PrivateType
def ==( pt )
self.type_id == pt.type_id and self.value == pt.value
end
end
class DomainType
def ==( dt )
self.domain == dt.domain and self.type_id == dt.type_id and self.value == dt.value
end
end
class SpecialHash
def ==( h )
if h.is_a? SpecialHash
self.default == h.default and not self.keys.detect { |k| self[k] != h[k] }
else
false
end
end
def inspect
"{SpecialHash: @default=#{@default} @hash=#{super}}"
end
end
end
header = " %YAML:1.0"
YAML::load( File.read( "index.yml" ) ).each do |yst|
YAML.load_documents( File.read( yst + ".yml" ) ) do |ydoc|
#
# Test the document
#
reason = nil
success = 'no'
round_trip = 'no'
round_out = nil
interval = nil
if ydoc.has_key?( 'ruby' )
obj_r = nil
obj_y = nil
begin
eval( ydoc['ruby-setup'] ) if ydoc.has_key?( 'ruby-setup' )
time = Time.now
ydoc['yaml'].gsub!( / +$/, '' )
if ydoc.has_key?( 'documents' )
obj_y = YAML::load_stream( ydoc['yaml'] )
else
obj_y = YAML::load( ydoc['yaml'] )
end
interval = Time.now - time
eval( "obj_r = #{ydoc['ruby']}" )
if obj_r == obj_y
success = 'yes'
# Attempt round trip
unless ydoc['no-round-trip'].is_a?( Array ) and ydoc['no-round-trip'].include?( 'ruby' )
obj_y2 = nil
begin
if obj_y.is_a? YAML::Stream
round_out = obj_y.emit
obj_y2 = YAML::load_stream( round_out )
else
round_out = obj_y.to_yaml
obj_y2 = YAML::load( round_out )
end
rescue YAML::Error => e
reason = e.to_s
end
obj_y = obj_y2
eval( "obj_r = #{ydoc['ruby']}" )
if obj_r == obj_y
round_trip = 'yes'
else
reason = 'Expected <' + obj_r.inspect + '>, but was <' +
obj_y2.inspect + '>'
end
else
end
else
reason = 'Expected <' + obj_r.inspect + '>, but was <' +
obj_y.inspect + '>'
end
rescue Exception => e
reason = e.to_s
end
else
reason = 'No Ruby parse information available in the test document.'
end
#
# Print out YAML result
#
puts <, but was <' +
paths.inspect + '>'
end
rescue YAML::Error => e
reason = e.to_s
end
puts <