- README

- Top Level Namespace
- Adler32
- ArgumentError
- Array
- Atomic
- Base64
  - Error
- Benchmark
  - BM
    - Job
    - Tms
  - IPS
    - Entry
    - Job
- BigFloat
- BigInt
- BigRational
- BitArray
- Bool
- Box
- Bytes
- Channel
  - Buffered
  - ClosedError
  - ReceiveAction
  - SelectAction
  - SendAction
  - Unbuffered
- Char
  - Reader
- Class
- Colorize
  - Object
  - ObjectExtensions
- Comparable
- Complex
- Concurrent
  - CanceledError
- CRC32
- Crypto
  - Bcrypt
    - Error
    - Password
  - Blowfish
  - Subtle
- Crystal
  - Macros
    - And
    - Arg
    - ArrayLiteral
    - Assign
    - ASTNode
    - BinaryOp
    - Block
    - BoolLiteral
    - Call
    - Case
    - Cast
    - CharLiteral
    - ClassDef
    - ClassVar
    - Def
    - Expressions
    - Generic
    - Global
    - HashLiteral
    - If
    - ImplicitObj
    - InstanceSizeOf
    - InstanceVar
    - IsA
    - Macro
    - MacroId
    - MetaVar
    - MultiAssign
    - NamedArgument
    - NamedTupleLiteral
    - NilableCast
    - NilLiteral
    - Nop
    - Not
    - NumberLiteral
    - Or
    - Out
    - Path
    - PointerOf
    - RangeLiteral
    - ReadInstanceVar
    - RegexLiteral
    - Require
    - RespondsTo
    - SizeOf
    - Splat
    - StringInterpolation
    - StringLiteral
    - SymbolLiteral
    - TupleLiteral
    - TypeDeclaration
    - TypeNode
    - UnaryExpression
    - UninitializedVar
    - Union
    - Var
    - VisibilityModifier
    - When
    - While
  - System
- CSV
  - Builder
    - Row
  - Error
  - Lexer
  - MalformedCSVError
  - Parser
  - Row
  - Token
    - Kind
- Debug
  - DWARF
    - Abbrev
      - Attribute
    - AT
    - FORM
    - Info
      - Value
    - LineNumbers
      - Register
      - Row
      - Sequence
    - LNE
    - LNS
    - Strings
    - TAG
  - ELF
    - Endianness
    - Error
    - Ident
    - Klass
    - Machine
    - OSABI
    - SectionHeader
      - Flags
      - Type
    - Type
- Deque
- Digest
  - Base
  - MD5
  - SHA1
- Dir
- DivisionByZero
- DL
- ECR
- Enum
- Enumerable
  - EmptyError
- ENV
- Errno
- Exception
- Fiber
- File
  - Stat
- FileUtils
- Flate
  - Error
  - Reader
  - Strategy
  - Writer
- Float
  - Primitive
  - Printer
    - CachedPowers
      - Power
    - DiyFP
    - Grisu3
    - IEEE
- Float32
- Float64
- GC
  - Stats
- Gzip
  - Error
  - Header
  - Reader
  - Writer
- Hash
- HTML
- HTTP
  - Client
    - BodyType
    - Response
  - CompressHandler
  - ComputedContentTypeHeader
  - Cookie
  - Cookies
  - ErrorHandler
  - FormData
    - Builder
    - Error
    - FileMetadata
    - Parser
    - Part
  - Handler
    - Proc
  - Headers
  - LogHandler
  - Multipart
    - Builder
    - Error
    - Parser
  - Params
    - Builder
  - Request
  - Server
    - Context
    - RequestProcessor
    - Response
  - StaticFileHandler
    - DirectoryListing
  - WebSocket
  - WebSocketHandler
- Indexable
- IndexError
- INI
- Int
  - Primitive
  - Signed
  - Unsigned
- Int16
- Int32
- Int64
- Int8
- InvalidByteSequenceError
- IO
  - Buffered
  - ByteFormat
    - BigEndian
    - LittleEndian
    - NetworkEndian
    - SystemEndian
  - Delimited
  - EncodingOptions
  - EOFError
  - Error
  - FileDescriptor
  - Hexdump
  - Memory
  - MultiWriter
  - Seek
  - Sized
  - Timeout
- IPSocket
- Iterable
- Iterator
  - IteratorWrapper
  - Stop
- JSON
  - Any
  - Builder
    - ArrayState
    - DocumentEndState
    - DocumentStartState
    - ObjectState
    - StartState
    - State
  - Error
  - Lexer
  - ParseException
  - Parser
  - PullParser
  - Token
  - Type
- KeyError
- Levenshtein
  - Finder
- LLVM
  - ABI
    - AArch64
    - ArgKind
    - ArgType
    - ARM
    - FunctionType
    - X86
    - X86_64
      - RegClass
  - AtomicOrdering
  - AtomicRMWBinOp
  - Attribute
  - AttributeIndex
  - BasicBlock
  - BasicBlockCollection
  - Builder
  - CallConvention
  - CodeGenFileType
  - CodeGenOptLevel
  - CodeModel
  - Context
  - DIBuilder
  - DIFlags
  - DwarfTag
  - DwarfTypeEncoding
  - Function
  - FunctionCollection
  - FunctionPassManager
    - Runner
  - GenericValue
  - GlobalCollection
  - InstructionCollection
  - IntPredicate
  - JITCompiler
  - Linkage
  - MemoryBuffer
  - Module
  - ModuleFlag
  - ModulePassManager
  - OperandBundleDef
  - ParameterCollection
  - PassManagerBuilder
  - PassRegistry
  - PhiTable
  - RealPredicate
  - RelocMode
  - Target
  - TargetData
  - TargetMachine
  - Type
    - Kind
  - Value
    - Kind
  - ValueMethods
  - VerifierFailureAction
- Logger
  - Formatter
  - Severity
- Markdown
  - HTMLRenderer
  - Parser
    - PrefixHeader
    - UnorderedList
  - Renderer
- Math
- Mutex
- NamedTuple
- Nil
- Number
  - Primitive
- OAuth
  - AccessToken
  - Consumer
  - Error
  - RequestToken
- OAuth2
  - AccessToken
    - Bearer
    - Mac
  - Client
  - Error
  - Session
- Object
- OpenSSL
  - Digest
    - Error
    - UnsupportedError
  - DigestBase
  - DigestIO
    - DigestMode
  - Error
  - HMAC
  - MD5
  - SHA1
  - SSL
    - Context
      - Client
      - Server
    - Error
    - ErrorType
    - Modes
    - Options
    - Socket
      - Client
      - Server
    - VerifyMode
    - X509VerifyFlags
- OptionParser
  - Exception
  - InvalidOption
  - MissingOption
- PartialComparable
- Pointer
  - Appender
- PrettyPrint
- Proc
- Process
  - Env
  - Status
  - Stdio
  - Tms
- Random
  - ISAAC
  - MT19937
  - PCG32
  - System
- Range
- Readline
  - CompletionProc
  - KeyBindingProc
- Reference
- Reflect
- Regex
  - MatchData
  - Options
- SecureRandom
- Set
- Signal
- Slice
- Socket
  - Address
  - Addrinfo
  - Error
  - Family
  - IPAddress
  - Protocol
  - Server
  - Type
  - UNIXAddress
- Spec
  - Expectations
  - Methods
  - ObjectExtensions
- StaticArray
- String
  - Builder
  - RawConverter
- StringPool
- StringScanner
- Struct
- Symbol
- System
- TCPServer
- TCPSocket
- Tempfile
- Termios
  - AttributeSelection
  - BaudRate
  - ControlMode
  - InputMode
  - LineControl
  - LocalMode
  - OutputMode
- Time
  - DayOfWeek
  - EpochConverter
  - EpochMillisConverter
  - Format
    - Error
  - Kind
  - MonthSpan
  - Span
- Tuple
- TypeCastError
- UDPSocket
- UInt16
- UInt32
- UInt64
- UInt8
- Unicode
  - CaseOptions
- Union
- UNIXServer
- UNIXSocket
- URI
  - Error
- Value
- WeakRef
- XML
  - Attributes
  - AttributeType
  - Builder
  - Error
  - HTMLParserOptions
  - Namespace
  - Node
  - NodeSet
  - ParserOptions
  - Reader
  - SaveOptions
  - Type
  - XPathContext
- YAML
  - Any
  - Builder
  - Error
  - EventKind
  - ParseException
  - Parser
  - PullParser
  - Type
- Zip
  - CompressionMethod
  - Error
  - File
    - Entry
  - FileInfo
  - Reader
    - Entry
  - Writer
    - Entry
- Zlib
  - Error
  - Reader
  - Writer

# abstract class Object

## Overview

`Object` is the base type of all Crystal objects.

## Included Modules

- Colorize::ObjectExtensions
- Spec::ObjectExtensions

## Direct Known Subclasses

- Reference
- Value

## Defined in:

## Constructors

- .from_json(string_or_io, root : String) : self

  Deserializes the given JSON in string_or_io into an instance of `self`, assuming the JSON consists of an JSON object with key root, and whose value is the value to deserialize.

- .from_json(string_or_io) : self

  Deserializes the given JSON in string_or_io into an instance of `self`.

- .from_yaml(string_or_io) : self

## Instance Method Summary

- #!=(other)

  Returns `true` if this object is not equal to other.

- #!~(other)

  Shortcut to `!(self =~ other)`.

- #==(other)

  Returns `true` if this object is equal to other.

- #===(other : JSON::Any)
- #===(other : YAML::Any)
- #===(other)

  Case equality.

- #=~(other)

  Pattern match.

- #class

  Returns the runtime `Class` of an object.

- #dup

  Returns a shallow copy of this object.

- #hash

  Generates an `Int` hash value for this object.

- #inspect(io : IO)

  Appends a string representation of this object to the given `IO` object.

- #inspect

  Returns a `String` representation of this object.

- #itself

  Return `self`.

- #not_nil!

  Returns `self`.

- #pretty_inspect(width = 79, newline = "\n", indent = 0) : String

  Returns a pretty printed version of `self`.

- #pretty_print(pp : PrettyPrint) : Nil

  Pretty prints `self` into the given printer.

- #tap(&block)

  Yields `self` to the block, and then returns `self`.

- #to_json(io : IO)
- #to_json
- #to_pretty_json(indent : String = " ")
- #to_pretty_json(io : IO, indent : String = " ")
- #to_s

  Returns a string representation of this object.

- #to_s(io : IO)

  Appends a `String` representation of this object to the given `IO` object.

- #to_yaml(io : IO)
- #to_yaml
- #try(&block)

  Yields `self`.

- #unsafe_as(type : T.class) forall T

  Unsafely reinterprets the bytes of an object as being of another `type`.

## Macro Summary

- class_getter(*names)

  Defines getter methods for each of the given arguments.

- class_getter!(*names)

  Defines raise-on-nil and nilable getter methods for each of the given arguments.

- class_getter?(*names)

  Defines query getter methods for each of the given arguments.

- class_property(*names)

  Defines property methods for each of the given arguments.

- class_property!(*names)

  Defines raise-on-nil property methods for each of the given arguments.

- class_property?(*names)

  Defines query property methods for each of the given arguments.

- class_setter(*names)

  Defines setter methods for each of the given arguments.

- def_clone

  Defines a `clone` method that returns a copy of this object with all instance variables cloned (`clone` is in turn invoked on them).

- def_equals(*fields)

  Defines an `#==` method by comparing the given fields.

- def_equals_and_hash(*fields)

  Defines `#hash` and `#==` method from the given fields.

- def_hash(*fields)

  Defines a `#hash` method computed from the given fields.

- delegate(*methods, to object)

  Delegate methods to to.

- forward_missing_to(delegate)

  Forwards missing methods to delegate.

- getter(*names)

  Defines getter methods for each of the given arguments.

- getter!(*names)

  Defines raise-on-nil and nilable getter methods for each of the given arguments.

- getter?(*names)

  Defines query getter methods for each of the given arguments.

- property(*names)

  Defines property methods for each of the given arguments.

- property!(*names)

  Defines raise-on-nil property methods for each of the given arguments.

- property?(*names)

  Defines query property methods for each of the given arguments.

- setter(*names)

  Defines setter methods for each of the given arguments.

### Instance methods inherited from module `Spec::ObjectExtensions`

should(expectation, file = __FILE__, line = __LINE__) should, should_not(expectation, file = __FILE__, line = __LINE__) should_not

### Instance methods inherited from module `Colorize::ObjectExtensions`

colorize(fore)
colorize colorize

## Constructor Detail

def self.from_json(string_or_io, root : String) : self #

Deserializes the given JSON in string_or_io into an instance of `self`, assuming the JSON consists of an JSON object with key root, and whose value is the value to deserialize.

    Int32.from_json(%({"main": 1}), root: "main") # => 1

def self.from_json(string_or_io) : self #

Deserializes the given JSON in string_or_io into an instance of `self`. This simply creates a `parser = JSON::PullParser` and invokes `new(parser)`: classes that want to provide JSON deserialization must provide an `def initialize(parser : JSON::PullParser)` method.

    Int32.from_json("1")                # => 1
    Array(Int32).from_json("[1, 2, 3]") # => [1, 2, 3]

def self.from_yaml(string_or_io) : self #

## Instance Method Detail

def !=(other) #

Returns `true` if this object is not equal to other.

By default this method is implemented as `!(self == other)` so there's no need to override this unless there's a more efficient way to do it.

def !~(other) #

Shortcut to `!(self =~ other)`.

abstract def ==(other) #

Returns `true` if this object is equal to other.

Subclasses override this method to provide class-specific meaning.

def ===(other : JSON::Any) #
def ===(other : YAML::Any) #
def ===(other) #

Case equality.

The `#===` method is used in a `case ... when ... end` expression.

For example, this code:

    case value
    when x
      # something when x
    when y
      # something when y
    end

Is equivalent to this code:

    if x === value
      # something when x
    elsif y === value
      # something when y
    end

Object simply implements `#===` by invoking `#==`, but subclasses (notably `Regex`) can override it to provide meaningful case-equality semantics.

def =~(other) #

Pattern match.

Overridden by descendants (notably `Regex` and `String`) to provide meaningful pattern-match semantics.

def class #

Returns the runtime `Class` of an object.

    1.class       # => Int32
    "hello".class # => String

Compare it with `typeof`, which returns the compile-time type of an object:

    random_value = rand # => 0.627423
    value = random_value < 0.5 ? 1 : "hello"
    value         # => "hello"
    value.class   # => String
    typeof(value) # => Int32 | String

abstract def dup #

Returns a shallow copy of this object.

As a convention, `clone` is the method used to create a deep copy of an object, but this logic isn't defined generically for every type because cycles could be involved, and the clone logic might not need to clone everything.

Many types in the standard library, like `Array`, `Hash`, `Set` and `Deque`, and all primitive types, define `#dup` and `clone`.

abstract def hash #

Generates an `Int` hash value for this object.

This method must have the property that `a == b` implies `a.hash == b.hash`.

The hash value is used along with `#==` by the `Hash` class to determine if two objects reference the same hash key.

def inspect(io : IO) #

Appends a string representation of this object to the given `IO` object.

Similar to `#to_s(io)`, but usually appends more information about this object.

def inspect #

Returns a `String` representation of this object.

Similar to `#to_s`, but usually returns more information about this object.

Classes must usually not override this method. Instead, they must override `#inspect(io)`, which must append to the given `IO` object.

def itself #

Return `self`.

    str = "hello"
    str.itself.object_id == str.object_id # => true

def not_nil! #

Returns `self`. `Nil` overrides this method and raises an exception.

def pretty_inspect(width = 79, newline = "\n", indent = 0) : String #

Returns a pretty printed version of `self`.

def pretty_print(pp : PrettyPrint) : Nil #

Pretty prints `self` into the given printer.

By default appends a text that is the result of invoking `#inspect` on `self`. Subclasses should override for custom pretty printing.

def tap(&block) #

Yields `self` to the block, and then returns `self`.

The primary purpose of this method is to "tap into" a method chain, in order to perform operations on intermediate results within the chain.

    (1..10).tap { |x| puts "original: #{x.inspect}" }
           .to_a.tap { |x| puts "array: #{x.inspect}" }
                .select { |x| x % 2 == 0 }.tap { |x| puts "evens: #{x.inspect}" }
                                          .map { |x| x*x }.tap { |x| puts "squares: #{x.inspect}" }

def to_json(io : IO) #
def to_json #
def to_pretty_json(indent : String = " ") #
def to_pretty_json(io : IO, indent : String = " ") #
def to_s #

Returns a string representation of this object.

Descendants must usually not override this method. Instead, they must override `#to_s(io)`, which must append to the given IO object.

abstract def to_s(io : IO) #

Appends a `String` representation of this object to the given `IO` object.

An object must never append itself to the io argument, as this will in turn call `#to_s(io)` on it.

def to_yaml(io : IO) #
def to_yaml #
def try(&block) #

Yields `self`. `Nil` overrides this method and doesn't yield.

This method is useful for dealing with nilable types, to safely perform operations only when the value is not `nil`.

    # First program argument in downcase, or nil
    ARGV[0]?.try &.downcase

def unsafe_as(type : T.class) forall T #

Unsafely reinterprets the bytes of an object as being of another `type`.

This method is useful to treat a type that is represented as a chunk of bytes as another type where those bytes convey useful information. As an example, you can check the individual bytes of an `Int32`:

    0x01020304.unsafe_as(StaticArray(UInt8, 4)) # => StaticArray[4, 3, 2, 1]

Or treat the bytes of a `Float64` as an `Int64`:

    1.234_f64.unsafe_as(Int64) # => 4608236261112822104

This method is unsafe because it behaves unpredictably when the given `type` doesn't have the same bytesize as the receiver, or when the given `type` representation doesn't semantically match the underlying bytes.

Also note that because `#unsafe_as` is a regular method, unlike the pseudo-method `as`, you can't specify some types in the type grammar using a short notation, so specifying a static array must always be done as `StaticArray(T, N)`, a tuple as `Tuple(...)` and so on, never as `UInt8[4]` or `{Int32, Int32}`.

## Macro Detail

macro class_getter(*names) #

Defines getter methods for each of the given arguments.

Writing:

    class Person
      class_getter name
    end

Is the same as writing:

    class Person
      def self.name
        @@name
      end
    end

The arguments can be string literals, symbol literals or plain names:

    class Person
      class_getter :name, "age"
    end

If a type declaration is given, a variable with that name is declared with that type.

    class Person
      class_getter name : String
    end

Is the same as writing:

    class Person
      @@name : String

      def self.name : String
        @@name
      end
    end

The type declaration can also include an initial value:

    class Person
      class_getter name : String = "John Doe"
    end

Is the same as writing:

    class Person
      @@name : String = "John Doe"

      def self.name : String
        @@name
      end
    end

An assignment can be passed too, but in this case the type of the variable must be easily inferrable from the initial value:

    class Person
      class_getter name = "John Doe"
    end

Is the same as writing:

    class Person
      @@name = "John Doe"

      def self.name : String
        @@name
      end
    end

If a block is given to the macro, a getter is generated with a variable that is lazily initialized with the block's contents:

    class Person
      class_getter(birth_date) { Time.now }
    end

Is the same as writing:

    class Person
      def self.birth_date
        @@birth_date ||= Time.now
      end
    end

macro class_getter!(*names) #

Defines raise-on-nil and nilable getter methods for each of the given arguments.

Writing:

    class Person
      class_getter! name
    end

Is the same as writing:

    class Person
      def self.name?
        @@name
      end

      def self.name
        @@name.not_nil!
      end
    end

The arguments can be string literals, symbol literals or plain names:

    class Person
      class_getter! :name, "age"
    end

If a type declaration is given, a variable with that name is declared with that type, as nilable.

    class Person
      class_getter! name : String
    end

is the same as writing:

    class Person
      @@name : String?

      def self.name?
        @@name
      end

      def self.name
        @@name.not_nil!
      end
    end

macro class_getter?(*names) #

Defines query getter methods for each of the given arguments.

Writing:

    class Person
      class_getter? happy
    end

Is the same as writing:

    class Person
      def self.happy?
        @@happy
      end
    end

The arguments can be string literals, symbol literals or plain names:

    class Person
      class_getter? :happy, "famous"
    end

If a type declaration is given, a variable with that name is declared with that type.

    class Person
      class_getter? happy : Bool
    end

is the same as writing:

    class Person
      @@happy : Bool

      def self.happy? : Bool
        @@happy
      end
    end

The type declaration can also include an initial value:

    class Person
      class_getter? happy : Bool = true
    end

Is the same as writing:

    class Person
      @@happy : Bool = true

      def self.happy? : Bool
        @@happy
      end
    end

An assignment can be passed too, but in this case the type of the variable must be easily inferrable from the initial value:

    class Person
      class_getter? happy = true
    end

Is the same as writing:

    class Person
      @@happy = true

      def self.happy?
        @@happy
      end
    end

macro class_property(*names) #

Defines property methods for each of the given arguments.

Writing:

    class Person
      class_property name
    end

Is the same as writing:

    class Person
      def self.name=(@@name)
      end

      def self.name
        @@name
      end
    end

The arguments can be string literals, symbol literals or plain names:

    class Person
      class_property :name, "age"
    end

If a type declaration is given, a variable with that name is declared with that type.

    class Person
      class_property name : String
    end

Is the same as writing:

    class Person
      @@name : String

      def self.name=(@@name)
      end

      def self.name
        @@name
      end
    end

The type declaration can also include an initial value:

    class Person
      class_property name : String = "John Doe"
    end

Is the same as writing:

    class Person
      @@name : String = "John Doe"

      def self.name=(@@name : String)
      end

      def self.name
        @@name
      end
    end

An assignment can be passed too, but in this case the type of the variable must be easily inferrable from the initial value:

    class Person
      class_property name = "John Doe"
    end

Is the same as writing:

    class Person
      @@name = "John Doe"

      def self.name=(@@name : String)
      end

      def self.name
        @@name
      end
    end

If a block is given to the macro, a property is generated with a variable that is lazily initialized with the block's contents:

    class Person
      class_property(birth_date) { Time.now }
    end

Is the same as writing:

    class Person
      def self.birth_date
        @@birth_date ||= Time.now
      end

      def self.birth_date=(@@birth_date)
      end
    end

macro class_property!(*names) #

Defines raise-on-nil property methods for each of the given arguments.

Writing:

    class Person
      class_property! name
    end

Is the same as writing:

    class Person
      def self.name=(@@name)
      end

      def self.name?
        @@name
      end

      def self.name
        @@name.not_nil!
      end
    end

The arguments can be string literals, symbol literals or plain names:

    class Person
      class_property! :name, "age"
    end

If a type declaration is given, a variable with that name is declared with that type, as nilable.

    class Person
      class_property! name : String
    end

Is the same as writing:

    class Person
      @@name : String?

      def self.name=(@@name)
      end

      def self.name?
        @@name
      end

      def self.name
        @@name.not_nil!
      end
    end

macro class_property?(*names) #

Defines query property methods for each of the given arguments.

Writing:

    class Person
      class_property? happy
    end

Is the same as writing:

    class Person
      def self.happy=(@@happy)
      end

      def self.happy?
        @@happy
      end
    end

The arguments can be string literals, symbol literals or plain names:

    class Person
      class_property? :happy, "famous"
    end

If a type declaration is given, a variable with that name is declared with that type.

    class Person
      class_property? happy : Bool
    end

Is the same as writing:

    class Person
      @@happy : Bool

      def self.happy=(@@happy)
      end

      def self.happy?
        @@happy
      end

      def self.happy
        @@happy.not_nil!
      end
    end

The type declaration can also include an initial value:

    class Person
      class_property? happy : Bool = true
    end

Is the same as writing:

    class Person
      @@happy : Bool = true

      def self.happy=(@@happy : Bool)
      end

      def self.happy? : Bool
        @@happy
      end
    end

An assignment can be passed too, but in this case the type of the variable must be easily inferrable from the initial value:

    class Person
      class_property? happy = true
    end

Is the same as writing:

    class Person
      @@happy = true

      def self.happy=(@@happy)
      end

      def self.happy?
        @@happy
      end
    end

macro class_setter(*names) #

Defines setter methods for each of the given arguments.

Writing:

    class Person
      class_setter name
    end

Is the same as writing:

    class Person
      def self.name=(@@name)
      end
    end

The arguments can be string literals, symbol literals or plain names:

    class Person
      class_setter :name, "age"
    end

If a type declaration is given, a variable with that name is declared with that type.

    class Person
      class_setter name : String
    end

is the same as writing:

    class Person
      @@name : String

      def self.name=(@@name : String)
      end
    end

The type declaration can also include an initial value:

    class Person
      class_setter name : String = "John Doe"
    end

Is the same as writing:

    class Person
      @@name : String = "John Doe"

      def self.name=(@@name : String)
      end
    end

An assignment can be passed too, but in this case the type of the variable must be easily inferrable from the initial value:

    class Person
      class_setter name = "John Doe"
    end

Is the same as writing:

    class Person
      @@name = "John Doe"

      def self.name=(@@name)
      end
    end

macro def_clone #

Defines a `clone` method that returns a copy of this object with all instance variables cloned (`clone` is in turn invoked on them).

macro def_equals(*fields) #

Defines an `#==` method by comparing the given fields.

The generated `#==` method has a `self` restriction.

    class Person
      def initialize(@name, @age)
      end

      # Define a `==` method that compares @name and @age
      def_equals @name, @age
    end

macro def_equals_and_hash(*fields) #

Defines `#hash` and `#==` method from the given fields.

The generated `#==` method has a `self` restriction.

    class Person
      def initialize(@name, @age)
      end

      # Define a hash method based on @name and @age
      # Define a `==` method that compares @name and @age
      def_equals_and_hash @name, @age
    end

macro def_hash(*fields) #

Defines a `#hash` method computed from the given fields.

    class Person
      def initialize(@name, @age)
      end

      # Define a hash method based on @name and @age
      def_hash @name, @age
    end

macro delegate(*methods, to object) #

Delegate methods to to.

Note that due to current language limitations this is only useful when no captured blocks are involved.

    class StringWrapper
      def initialize(@string : String)
      end

      delegate downcase, to: @string
      delegate gsub, to: @string
      delegate empty?, capitalize, to: @string
    end

    wrapper = StringWrapper.new "HELLO"
    wrapper.downcase       # => "hello"
    wrapper.gsub(/E/, "A") # => "HALLO"
    wrapper.empty?         # => false
    wrapper.capitalize     # => "Hello"

macro forward_missing_to(delegate) #

Forwards missing methods to delegate.

    class StringWrapper
      def initialize(@string : String)
      end

      forward_missing_to @string
    end

    wrapper = StringWrapper.new "HELLO"
    wrapper.downcase       # => "hello"
    wrapper.gsub(/E/, "A") # => "HALLO"

macro getter(*names) #

Defines getter methods for each of the given arguments.

Writing:

    class Person
      getter name
    end

Is the same as writing:

    class Person
      def name
        @name
      end
    end

The arguments can be string literals, symbol literals or plain names:

    class Person
      getter :name, "age"
    end

If a type declaration is given, a variable with that name is declared with that type.

    class Person
      getter name : String
    end

Is the same as writing:

    class Person
      @name : String

      def name : String
        @name
      end
    end

The type declaration can also include an initial value:

    class Person
      getter name : String = "John Doe"
    end

Is the same as writing:

    class Person
      @name : String = "John Doe"

      def name : String
        @name
      end
    end

An assignment can be passed too, but in this case the type of the variable must be easily inferrable from the initial value:

    class Person
      getter name = "John Doe"
    end

Is the same as writing:

    class Person
      @name = "John Doe"

      def name : String
        @name
      end
    end

If a block is given to the macro, a getter is generated with a variable that is lazily initialized with the block's contents:

    class Person
      getter(birth_date) { Time.now }
    end

Is the same as writing:

    class Person
      def birth_date
        @birth_date ||= Time.now
      end
    end

macro getter!(*names) #

Defines raise-on-nil and nilable getter methods for each of the given arguments.

Writing:

    class Person
      getter! name
    end

Is the same as writing:

    class Person
      def name?
        @name
      end

      def name
        @name.not_nil!
      end
    end

The arguments can be string literals, symbol literals or plain names:

    class Person
      getter! :name, "age"
    end

If a type declaration is given, a variable with that name is declared with that type, as nilable.

    class Person
      getter! name : String
    end

is the same as writing:

    class Person
      @name : String?

      def name?
        @name
      end

      def name
        @name.not_nil!
      end
    end

macro getter?(*names) #

Defines query getter methods for each of the given arguments.

Writing:

    class Person
      getter? happy
    end

Is the same as writing:

    class Person
      def happy?
        @happy
      end
    end

The arguments can be string literals, symbol literals or plain names:

    class Person
      getter? :happy, "famous"
    end

If a type declaration is given, a variable with that name is declared with that type.

    class Person
      getter? happy : Bool
    end

is the same as writing:

    class Person
      @happy : Bool

      def happy? : Bool
        @happy
      end
    end

The type declaration can also include an initial value:

    class Person
      getter? happy : Bool = true
    end

Is the same as writing:

    class Person
      @happy : Bool = true

      def happy? : Bool
        @happy
      end
    end

An assignment can be passed too, but in this case the type of the variable must be easily inferrable from the initial value:

    class Person
      getter? happy = true
    end

Is the same as writing:

    class Person
      @happy = true

      def happy?
        @happy
      end
    end

macro property(*names) #

Defines property methods for each of the given arguments.

Writing:

    class Person
      property name
    end

Is the same as writing:

    class Person
      def name=(@name)
      end

      def name
        @name
      end
    end

The arguments can be string literals, symbol literals or plain names:

    class Person
      property :name, "age"
    end

If a type declaration is given, a variable with that name is declared with that type.

    class Person
      property name : String
    end

Is the same as writing:

    class Person
      @name : String

      def name=(@name)
      end

      def name
        @name
      end
    end

The type declaration can also include an initial value:

    class Person
      property name : String = "John Doe"
    end

Is the same as writing:

    class Person
      @name : String = "John Doe"

      def name=(@name : String)
      end

      def name
        @name
      end
    end

An assignment can be passed too, but in this case the type of the variable must be easily inferrable from the initial value:

    class Person
      property name = "John Doe"
    end

Is the same as writing:

    class Person
      @name = "John Doe"

      def name=(@name : String)
      end

      def name
        @name
      end
    end

If a block is given to the macro, a property is generated with a variable that is lazily initialized with the block's contents:

    class Person
      property(birth_date) { Time.now }
    end

Is the same as writing:

    class Person
      def birth_date
        @birth_date ||= Time.now
      end

      def birth_date=(@birth_date)
      end
    end

macro property!(*names) #

Defines raise-on-nil property methods for each of the given arguments.

Writing:

    class Person
      property! name
    end

Is the same as writing:

    class Person
      def name=(@name)
      end

      def name?
        @name
      end

      def name
        @name.not_nil!
      end
    end

The arguments can be string literals, symbol literals or plain names:

    class Person
      property! :name, "age"
    end

If a type declaration is given, a variable with that name is declared with that type, as nilable.

    class Person
      property! name : String
    end

Is the same as writing:

    class Person
      @name : String?

      def name=(@name)
      end

      def name?
        @name
      end

      def name
        @name.not_nil!
      end
    end

macro property?(*names) #

Defines query property methods for each of the given arguments.

Writing:

    class Person
      property? happy
    end

Is the same as writing:

    class Person
      def happy=(@happy)
      end

      def happy?
        @happy
      end
    end

The arguments can be string literals, symbol literals or plain names:

    class Person
      property? :happy, "famous"
    end

If a type declaration is given, a variable with that name is declared with that type.

    class Person
      property? happy : Bool
    end

Is the same as writing:

    class Person
      @happy : Bool

      def happy=(@happy)
      end

      def happy?
        @happy
      end

      def happy
        @happy.not_nil!
      end
    end

The type declaration can also include an initial value:

    class Person
      property? happy : Bool = true
    end

Is the same as writing:

    class Person
      @happy : Bool = true

      def happy=(@happy : Bool)
      end

      def happy? : Bool
        @happy
      end
    end

An assignment can be passed too, but in this case the type of the variable must be easily inferrable from the initial value:

    class Person
      property? happy = true
    end

Is the same as writing:

    class Person
      @happy = true

      def happy=(@happy)
      end

      def happy?
        @happy
      end
    end

macro setter(*names) #

Defines setter methods for each of the given arguments.

Writing:

    class Person
      setter name
    end

Is the same as writing:

    class Person
      def name=(@name)
      end
    end

The arguments can be string literals, symbol literals or plain names:

    class Person
      setter :name, "age"
    end

If a type declaration is given, a variable with that name is declared with that type.

    class Person
      setter name : String
    end

is the same as writing:

    class Person
      @name : String

      def name=(@name : String)
      end
    end

The type declaration can also include an initial value:

    class Person
      setter name : String = "John Doe"
    end

Is the same as writing:

    class Person
      @name : String = "John Doe"

      def name=(@name : String)
      end
    end

An assignment can be passed too, but in this case the type of the variable must be easily inferrable from the initial value:

    class Person
      setter name = "John Doe"
    end

Is the same as writing:

    class Person
      @name = "John Doe"

      def name=(@name)
      end
    end