text:
using Newtonsoft.Json;
using Newtonsoft.Json.Serialization;
using Telegram.Bot.Types.Enums;

// ReSharper disable once CheckNamespace
namespace Telegram.Bot.Types
{
    /// <summary>
    /// Represents a video to be sent
    /// </summary>
    [JsonObject(MemberSerialization.OptIn, NamingStrategyType = typeof(SnakeCaseNamingStrategy))]
    public class InputMediaVideo : InputMediaBase,
                                   IInputMediaThumb,
                                   IAlbumInputMedia
    {
        /// <inheritdoc />
        [JsonProperty(Required = Required.Always)]
        public override InputMediaType Type => InputMediaType.Video;

        /// <inheritdoc />
        [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)]
        public InputMedia? Thumb { get; set; }

        /// <summary>
        /// Optional. Video width
        /// </summary>
        [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)]
        public int? Width { get; set; }

        /// <summary>
        /// Optional. Video height
        /// </summary>
        [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)]
        public int? Height { get; set; }

        /// <summary>
        /// Optional. Video duration
        /// </summary>
        [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)]
        public int? Duration { get; set; }

        /// <summary>
        /// Optional. Pass True, if the uploaded video is suitable for streaming
        /// </summary>
        [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)]
        public bool? SupportsStreaming { get; set; }

        /// <summary>
        /// Initializes a new video media to send with an <see cref="InputMedia"/>
        /// </summary>
        /// <param name="media">File to send</param>
        public InputMediaVideo(InputMedia media)
            : base(media)
        { }
    }
}


text:
.class public final Lcom/google/gson/internal/bind/SqlDateTypeAdapter;
.super Lcom/google/gson/TypeAdapter;
.source "SqlDateTypeAdapter.java"

# annotations
.annotation system Ldalvik/annotation/Signature;
    value = {
        "Lcom/google/gson/TypeAdapter",
        "<",
        "Ljava/sql/Date;",
        ">;"
    }
.end annotation

# static fields
.field public static final FACTORY:Lcom/google/gson/TypeAdapterFactory;

# instance fields
.field private final format:Ljava/text/DateFormat;

# direct methods
.method static constructor <clinit>()V
    .locals 1

    new-instance v0, Lcom/google/gson/internal/bind/SqlDateTypeAdapter$1;

    invoke-direct {v0}, Lcom/google/gson/internal/bind/SqlDateTypeAdapter$1;-><init>()V

    sput-object v0, Lcom/google/gson/internal/bind/SqlDateTypeAdapter;->FACTORY:Lcom/google/gson/TypeAdapterFactory;

    return-void
.end method

.method public constructor <init>()V
    .locals 2

    invoke-direct {p0}, Lcom/google/gson/TypeAdapter;-><init>()V

    new-instance v0, Ljava/text/SimpleDateFormat;

    const-string/jumbo v1, "MMM d, yyyy"

    invoke-direct {v0, v1}, Ljava/text/SimpleDateFormat;-><init>(Ljava/lang/String;)V

    iput-object v0, p0, Lcom/google/gson/internal/bind/SqlDateTypeAdapter;->format:Ljava/text/DateFormat;

    return-void
.end method

# virtual methods
.method public bridge synthetic read(Lcom/google/gson/stream/JsonReader;)Ljava/lang/Object;
    .locals 1
    .annotation system Ldalvik/annotation/Throws;
        value = {
            Ljava/io/IOException;
        }
    .end annotation

    invoke-virtual {p0, p1}, Lcom/google/gson/internal/bind/SqlDateTypeAdapter;->read(Lcom/google/gson/stream/JsonReader;)Ljava/sql/Date;

    move-result-object v0

    return-object v0
.end method

.method public declared-synchronized read(Lcom/google/gson/stream/JsonReader;)Ljava/sql/Date;
    .locals 5
    .annotation system Ldalvik/annotation/Throws;
        value = {
            Ljava/io/IOException;
        }
    .end annotation

    monitor-enter p0

    :try_start_0
    invoke-virtual {p1}, Lcom/google/gson/stream/JsonReader;->peek()Lcom/google/gson/stream/JsonToken;

    move-result-object v1

    sget-object v4, Lcom/google/gson/stream/JsonToken;->NULL:Lcom/google/gson/stream/JsonToken;
    :try_end_0
    .catchall {:try_start_0 .. :try_end_0} :catchall_0

    if-eq v1, v4, :cond_0

    :try_start_1
    iget-object v1, p0, Lcom/google/gson/internal/bind/SqlDateTypeAdapter;->format:Ljava/text/DateFormat;

    invoke-virtual {p1}, Lcom/google/gson/stream/JsonReader;->nextString()Ljava/lang/String;

    move-result-object v4

    invoke-virtual {v1, v4}, Ljava/text/DateFormat;->parse(Ljava/lang/String;)Ljava/util/Date;

    move-result-object v1

    invoke-virtual {v1}, Ljava/util/Date;->getTime()J

    move-result-wide v2

    new-instance v1, Ljava/sql/Date;

    invoke-direct {v1, v2, v3}, Ljava/sql/Date;-><init>(J)V
    :try_end_1
    .catch Ljava/text/ParseException; {:try_start_1 .. :try_end_1} :catch_0
    .catchall {:try_start_1 .. :try_end_1} :catchall_0

    monitor-exit p0

    return-object v1

    :cond_0
    :try_start_2
    invoke-virtual {p1}, Lcom/google/gson/stream/JsonReader;->nextNull()V
    :try_end_2
    .catchall {:try_start_2 .. :try_end_2} :catchall_0

    const/4 v1, 0x0

    monitor-exit p0

    return-object v1

    :catch_0
    move-exception v0

    :try_start_3
    new-instance v1, Lcom/google/gson/JsonSyntaxException;

    invoke-direct {v1, v0}, Lcom/google/gson/JsonSyntaxException;-><init>(Ljava/lang/Throwable;)V

    throw v1
    :try_end_3
    .catchall {:try_start_3 .. :try_end_3} :catchall_0

    :catchall_0
    move-exception v1

    monitor-exit p0

    throw v1
.end method

.method public bridge synthetic write(Lcom/google/gson/stream/JsonWriter;Ljava/lang/Object;)V
    .locals 0
    .annotation system Ldalvik/annotation/Throws;
        value = {
            Ljava/io/IOException;
        }
    .end annotation

    check-cast p2, Ljava/sql/Date;

    invoke-virtual {p0, p1, p2}, Lcom/google/gson/internal/bind/SqlDateTypeAdapter;->write(Lcom/google/gson/stream/JsonWriter;Ljava/sql/Date;)V

    return-void
.end method

.method public declared-synchronized write(Lcom/google/gson/stream/JsonWriter;Ljava/sql/Date;)V
    .locals 1
    .annotation system Ldalvik/annotation/Throws;
        value = {
            Ljava/io/IOException;
        }
    .end annotation

    const/4 v0, 0x0

    monitor-enter p0

    if-eqz p2, :cond_0

    :try_start_0
    iget-object v0, p0, Lcom/google/gson/internal/bind/SqlDateTypeAdapter;->format:Ljava/text/DateFormat;

    invoke-virtual {v0, p2}, Ljava/text/DateFormat;->format(Ljava/util/Date;)Ljava/lang/String;

    move-result-object v0

    :cond_0
    invoke-virtual {p1, v0}, Lcom/google/gson/stream/JsonWriter;->value(Ljava/lang/String;)Lcom/google/gson/stream/JsonWriter;
    :try_end_0
    .catchall {:try_start_0 .. :try_end_0} :catchall_0

    monitor-exit p0

    return-void

    :catchall_0
    move-exception v0

    monitor-exit p0

    throw v0
.end method

redpajama_set_name: RedPajamaGithub


text:
package com.smartdevicelink.test.rpc.datatypes;

import com.smartdevicelink.marshal.JsonRPCMarshaller;
import com.smartdevicelink.proxy.rpc.DateTime;
import com.smartdevicelink.proxy.rpc.Image;
import com.smartdevicelink.proxy.rpc.LocationDetails;
import com.smartdevicelink.proxy.rpc.NavigationInstruction;
import com.smartdevicelink.proxy.rpc.enums.Direction;
import com.smartdevicelink.proxy.rpc.enums.NavigationAction;
import com.smartdevicelink.proxy.rpc.enums.NavigationJunction;
import com.smartdevicelink.test.JsonUtils;
import com.smartdevicelink.test.TestValues;
import com.smartdevicelink.test.Validator;

import junit.framework.TestCase;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.Hashtable;
import java.util.Iterator;

/**
 * This is a unit test class for the SmartDeviceLink library project class :
 * {@link com.smartdevicelink.proxy.rpc.NavigationInstruction}
 */
public class NavigationInstructionTests extends TestCase {

    private NavigationInstruction msg;

    @Override
    public void setUp() {
        msg = new NavigationInstruction();

        msg.setLocationDetails(TestValues.GENERAL_LOCATIONDETAILS);
        msg.setAction(TestValues.GENERAL_NAVIGATIONACTION);
        msg.setEta(TestValues.GENERAL_DATETIME);
        msg.setBearing(TestValues.GENERAL_INTEGER);
        msg.setJunctionType(TestValues.GENERAL_NAVIGATION_JUNCTION);
        msg.setDrivingSide(TestValues.GENERAL_DIRECTION);
        msg.setDetails(TestValues.GENERAL_STRING);
        msg.setImage(TestValues.GENERAL_IMAGE);
    }

    /**
     * Tests the expected values of the RPC message.
     */
    public void testRpcValues() {
        // Test Values
        LocationDetails locationDetails = msg.getLocationDetails();
        NavigationAction action = msg.getAction();
        DateTime eta = msg.getEta();
        Integer bearing = msg.getBearing();
        NavigationJunction junctionType = msg.getJunctionType();
        Direction drivingSide = msg.getDrivingSide();
        String details = msg.getDetails();
        Image image = msg.getImage();

        // Valid Tests
        assertEquals(TestValues.GENERAL_LOCATIONDETAILS, locationDetails);
        assertEquals(TestValues.GENERAL_NAVIGATIONACTION, action);
        assertEquals(TestValues.GENERAL_DATETIME, eta);
        assertEquals(TestValues.GENERAL_INTEGER, bearing);
        assertEquals(TestValues.GENERAL_NAVIGATION_JUNCTION, junctionType);
        assertEquals(TestValues.GENERAL_DIRECTION, drivingSide);
        assertEquals(TestValues.GENERAL_STRING, details);
        assertEquals(TestValues.GENERAL_IMAGE, image);

        // Invalid/Null Tests
        NavigationInstruction msg = new NavigationInstruction();
        assertNotNull(TestValues.NOT_NULL, msg);

        assertNull(TestValues.NULL, msg.getLocationDetails());
        assertNull(TestValues.NULL, msg.getAction());
        assertNull(TestValues.NULL, msg.getEta());
        assertNull(TestValues.NULL, msg.getBearing());
        assertNull(TestValues.NULL, msg.getJunctionType());
        assertNull(TestValues.NULL, msg.getDrivingSide());
        assertNull(TestValues.NULL, msg.getDetails());
        assertNull(TestValues.NULL, msg.getImage());
    }

    public void testRequiredConstructor() {
        NavigationInstruction msg = new NavigationInstruction(TestValues.GENERAL_LOCATIONDETAILS, TestValues.GENERAL_NAVIGATIONACTION);
        assertNotNull(TestValues.NOT_NULL, msg);

        LocationDetails locationDetails = msg.getLocationDetails();
        NavigationAction action = msg.getAction();

        assertEquals(TestValues.GENERAL_LOCATIONDETAILS, locationDetails);
        assertEquals(TestValues.GENERAL_NAVIGATIONACTION, action);
    }

    public void testJson() {
        JSONObject reference = new JSONObject();

        try {
            reference.put(NavigationInstruction.KEY_LOCATION_DETAILS, TestValues.GENERAL_LOCATIONDETAILS);
            reference.put(NavigationInstruction.KEY_ACTION, TestValues.GENERAL_NAVIGATIONACTION);
            reference.put(NavigationInstruction.KEY_ETA, TestValues.GENERAL_DATETIME);
            reference.put(NavigationInstruction.KEY_BEARING, TestValues.GENERAL_INTEGER);
            reference.put(NavigationInstruction.KEY_JUNCTION_TYPE, TestValues.GENERAL_NAVIGATION_JUNCTION);
            reference.put(NavigationInstruction.KEY_DRIVING_SIDE, TestValues.GENERAL_DIRECTION);
            reference.put(NavigationInstruction.KEY_DETAILS, TestValues.GENERAL_STRING);
            reference.put(NavigationInstruction.KEY_IMAGE, TestValues.GENERAL_IMAGE);

            JSONObject underTest = msg.serializeJSON();
            assertEquals(TestValues.MATCH, reference.length(), underTest.length());

            Iterator<?> iterator = reference.keys();
            while (iterator.hasNext()) {
                String key = (String) iterator.next();

                if (key.equals(NavigationInstruction.KEY_IMAGE)) {
                    JSONObject testEquals = (JSONObject) JsonUtils.readObjectFromJsonObject(underTest, key);
                    Image refIcon1 = new Image(JsonRPCMarshaller.deserializeJSONObject(testEquals));
                    assertTrue(TestValues.TRUE, Validator.validateImage(refIcon1, msg.getImage()));
                } else if (key.equals(NavigationInstruction.KEY_LOCATION_DETAILS)) {
                    JSONObject testEquals = (JSONObject) JsonUtils.readObjectFromJsonObject(underTest, key);
                    Hashtable<String, Object> hashTest = JsonRPCMarshaller.deserializeJSONObject(testEquals);
                    assertTrue(TestValues.TRUE, Validator.validateLocationDetails(TestValues.GENERAL_LOCATIONDETAILS, new LocationDetails(hashTest)));
                } else if (key.equals(NavigationInstruction.KEY_ETA)) {
                    JSONObject testEquals = (JSONObject) JsonUtils.readObjectFromJsonObject(underTest, key);
                    Hashtable<String, Object> hashTest = JsonRPCMarshaller.deserializeJSONObject(testEquals);
                    assertTrue(TestValues.TRUE, Validator.validateDateTime(TestValues.GENERAL_DATETIME, new DateTime(hashTest)));
                } else {
                    assertEquals(TestValues.MATCH, JsonUtils.readObjectFromJsonObject(reference, key), JsonUtils.readObjectFromJsonObject(underTest, key));
                }
            }
        } catch (JSONException e) {
            fail(TestValues.JSON_FAIL);
        }
    }
}


text:
//===--- SILModule.cpp - SILModule implementation -------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//

#define DEBUG_TYPE "sil-module"
#include "swift/Serialization/SerializedSILLoader.h"
#include "swift/AST/GenericEnvironment.h"
#include "swift/AST/ProtocolConformance.h"
#include "swift/AST/Substitution.h"
#include "swift/SIL/FormalLinkage.h"
#include "swift/SIL/SILDebugScope.h"
#include "swift/SIL/SILModule.h"
#include "Linker.h"
#include "swift/SIL/SILVisitor.h"
#include "swift/SIL/SILValue.h"
#include "llvm/ADT/FoldingSet.h"
#include "llvm/ADT/SmallString.h"
#include "llvm/ADT/StringSwitch.h"
#include "llvm/ADT/Statistic.h"
#include "llvm/Support/Debug.h"
#include <functional>
using namespace swift;
using namespace Lowering;

class SILModule::SerializationCallback : public SerializedSILLoader::Callback {
  void didDeserialize(ModuleDecl *M, SILFunction *fn) override {
    updateLinkage(fn);
  }

  void didDeserialize(ModuleDecl *M, SILGlobalVariable *var) override {
    updateLinkage(var);

    // For globals we currently do not support available_externally.
    // In the interpreter it would result in two instances for a single global:
    // one in the imported module and one in the main module.
    var->setDeclaration(true);
  }

  void didDeserialize(ModuleDecl *M, SILVTable *vtable) override {
    // TODO: should vtables get linkage?
    //updateLinkage(vtable);
  }

  void didDeserialize(ModuleDecl *M, SILWitnessTable *wt) override {
    updateLinkage(wt);
  }

  template <class T> void updateLinkage(T *decl) {
    switch (decl->getLinkage()) {
    case SILLinkage::Public:
      decl->setLinkage(SILLinkage::PublicExternal);
      return;
    case SILLinkage::Hidden:
      decl->setLinkage(SILLinkage::HiddenExternal);
      return;
    case SILLinkage::Shared:
      decl->setLinkage(SILLinkage::SharedExternal);
      return;
    case SILLinkage::Private:
        decl->setLinkage(SILLinkage::PrivateExternal);
        return;
    case SILLinkage::PublicExternal:
    case SILLinkage::HiddenExternal:
    case SILLinkage::SharedExternal:
    case SILLinkage::PrivateExternal:
      return;
    }
  }

  void didDeserializeFunctionBody(ModuleDecl *M, SILFunction *fn) override {
    // Callbacks are currently applied in the order they are registered.
    for (auto callBack : fn->getModule().getDeserializationCallbacks())
      callBack(M, fn);
  }
};

SILModule::SILModule(ModuleDecl *SwiftModule, SILOptions &Options,
                     const DeclContext *associatedDC, bool wholeModule)
    : TheSwiftModule(SwiftModule), AssociatedDeclContext(associatedDC),
      Stage(SILStage::Raw), Callback(new SILModule::SerializationCallback()),
      wholeModule(wholeModule), Options(Options), Types(*this) {}

SILModule::~SILModule() {
  // Decrement ref count for each SILGlobalVariable with static initializers.
  for (SILGlobalVariable &v : silGlobals)
    if (v.getInitializer())
      v.getInitializer()->decrementRefCount();

  // Drop everything functions in this module reference.
  //
  // This is necessary since the functions may reference each other.  We don't
  // need to worry about sil_witness_tables since witness tables reference each
  // other via protocol conformances and sil_vtables don't reference each other
  // at all.
  for (SILFunction &F : *this)
    F.dropAllReferences();
}

void *SILModule::allocate(unsigned Size, unsigned Align) const {
  if (getASTContext().LangOpts.UseMalloc)
    return AlignedAlloc(Size, Align);

  return BPA.Allocate(Size, Align);
}

void *SILModule::allocateInst(unsigned Size, unsigned Align) const {
  return AlignedAlloc(Size, Align);
}

void SILModule::deallocateInst(SILInstruction *I) {
  AlignedFree(I);
}

SILWitnessTable *
SILModule::createWitnessTableDeclaration(ProtocolConformance *C,
                                         SILLinkage linkage) {
  // If we are passed in a null conformance (a valid value), just return nullptr
  // since we cannot map a witness table to it.
  if (!C)
    return nullptr;

  // Extract the base NormalProtocolConformance.
  NormalProtocolConformance *NormalC = C->getRootNormalConformance();

  return SILWitnessTable::create(*this, linkage, NormalC);
}

SILWitnessTable *
SILModule::lookUpWitnessTable(ProtocolConformanceRef C,
                              bool deserializeLazily) {
  // If we have an abstract conformance passed in (a legal value), just return
  // nullptr.
  if (!C.isConcrete())
    return nullptr;

  return lookUpWitnessTable(C.getConcrete());
}

SILWitnessTable *
SILModule::lookUpWitnessTable(const ProtocolConformance *C,
                              bool deserializeLazily) {
  assert(C && "null conformance passed to lookUpWitnessTable");

  const NormalProtocolConformance *NormalC = C->getRootNormalConformance();
  // Attempt to lookup the witness table from the table.
  auto found = WitnessTableMap.find(NormalC);
  if (found == WitnessTableMap.end()) {
#ifndef NDEBUG
    // Make sure that all witness tables are in the witness table lookup
    // cache.
    //
    // This code should not be hit normally since we add witness tables to the
    // lookup cache when we create them. We don't just assert here since there
    // is the potential for a conformance without a witness table to be passed
    // to this function.
    for (SILWitnessTable &WT : witnessTables)
      assert(WT.getConformance() != NormalC &&
             "Found witness table that is not"
             " in the witness table lookup cache.");
#endif
    return nullptr;
  }

  SILWitnessTable *wtable = found->second;
  assert(wtable != nullptr && "Should never map a conformance to a null witness"
                          " table.");

  // If we have a definition, return it.
  if (wtable->isDefinition())
    return wtable;

  // Otherwise try to deserialize it. If we succeed return the deserialized
  // function.
  //
  // *NOTE* In practice, wtable will be deserializedTable, but I do not want to rely
  // on that behavior for now.
  if (deserializeLazily)
    if (auto deserialized = getSILLoader()->lookupWitnessTable(wtable))
      return deserialized;

  // If we fail, just return the declaration.
  return wtable;
}

SILDefaultWitnessTable *
SILModule::lookUpDefaultWitnessTable(const ProtocolDecl *Protocol,
                                     bool deserializeLazily) {
  // Note: we only ever look up default witness tables in the translation unit
  // that is currently being compiled, since they SILGen generates them when it
  // visits the protocol declaration, and IRGen emits them when emitting the
  // protocol descriptor metadata for the protocol.

  auto found = DefaultWitnessTableMap.find(Protocol);
  if (found == DefaultWitnessTableMap.end()) {
    if (deserializeLazily) {
      SILLinkage linkage =
        getSILLinkage(getDeclLinkage(Protocol), ForDefinition);
      SILDefaultWitnessTable *wtable =
        SILDefaultWitnessTable::create(*this, linkage, Protocol);
      wtable = getSILLoader()->lookupDefaultWitnessTable(wtable);
      if (wtable)
        DefaultWitnessTableMap[Protocol] = wtable;
      return wtable;
    }

    return nullptr;
  }

  return found->second;
}

SILDefaultWitnessTable *
SILModule::createDefaultWitnessTableDeclaration(const ProtocolDecl *Protocol,
                                                SILLinkage Linkage) {
  return SILDefaultWitnessTable::create(*this, Linkage, Protocol);
}

void SILModule::deleteWitnessTable(SILWitnessTable *Wt) {
  NormalProtocolConformance *Conf = Wt->getConformance();
  assert(lookUpWitnessTable(Conf, false) == Wt);
  WitnessTableMap.erase(Conf);
  witnessTables.erase(Wt);
}

SILFunction *SILModule::getOrCreateFunction(SILLocation loc,
                                            StringRef name,
                                            SILLinkage linkage,
                                            CanSILFunctionType type,
                                            IsBare_t isBareSILFunction,
                                            IsTransparent_t isTransparent,
                                            IsSerialized_t isSerialized,
                                            IsThunk_t isThunk,
                                            SubclassScope subclassScope) {
  if (auto fn = lookUpFunction(name)) {
    assert(fn->getLoweredFunctionType() == type);
    assert(fn->getLinkage() == linkage ||
           stripExternalFromLinkage(fn->getLinkage()) == linkage);
    return fn;
  }

  auto fn = SILFunction::create(*this, linkage, name, type, nullptr,
                                loc, isBareSILFunction, isTransparent,
                                isSerialized, isThunk, subclassScope);
  fn->setDebugScope(new (*this) SILDebugScope(loc, fn));
  return fn;
}

static bool verifySILSelfParameterType(SILDeclRef DeclRef,
                                       SILFunction *F, CanSILFunctionType FTy) {
  SILModule &M = F->getModule();
  SILParameterInfo PInfo = FTy->getSelfParameter();
  CanType CTy = PInfo.getType();
  SILType Ty = SILType::getPrimitiveObjectType(CTy);

  // We do not care about trivial parameters (for now). There seem to be
  // cases where we lower them as unowned.
  //
  // *NOTE* We do not run this check when we have a generic type since
  // *generic types do not have type lowering and are always treated as
  // *non-trivial since we do not know the type.
  if (CTy->hasArchetype() || CTy->hasTypeParameter() ||
      M.getTypeLowering(Ty).isTrivial())
    return true;

  // If this function is a constructor or destructor, bail. These have @owned
  // parameters.
  if (DeclRef.isConstructor() || DeclRef.isDestructor())
    return true;

  // Otherwise, if this function type has a guaranteed self parameter type,
  // make sure that we have a +0 self param.
  return !FTy->getExtInfo().hasGuaranteedSelfParam() ||
          PInfo.isGuaranteed() || PInfo.isIndirectMutating();
}

SILFunction *SILModule::getOrCreateFunction(SILLocation loc,
                                            SILDeclRef constant,
                                            ForDefinition_t forDefinition) {

  auto name = constant.mangle();
  auto constantType = Types.getConstantType(constant).castTo<SILFunctionType>();
  SILLinkage linkage = constant.getLinkage(forDefinition);

  if (auto fn = lookUpFunction(name)) {
    assert(fn->getLoweredFunctionType() == constantType);
    assert(fn->getLinkage() == linkage ||
           (forDefinition == ForDefinition_t::NotForDefinition &&
            fn->getLinkage() ==
                constant.getLinkage(ForDefinition_t::ForDefinition)));
    if (forDefinition) {
      // In all the cases where getConstantLinkage returns something
      // different for ForDefinition, it returns an available-externally
      // linkage.
      if (isAvailableExternally(fn->getLinkage())) {
        fn->setLinkage(constant.getLinkage(ForDefinition));
      }
    }
    return fn;
  }

  IsTransparent_t IsTrans = constant.isTransparent()
                            ? IsTransparent
                            : IsNotTransparent;
  IsSerialized_t IsSer = constant.isSerialized();

  EffectsKind EK = constant.hasEffectsAttribute()
                   ? constant.getEffectsAttribute()
                   : EffectsKind::Unspecified;

  Inline_t inlineStrategy = InlineDefault;
  if (constant.isNoinline())
    inlineStrategy = NoInline;
  else if (constant.isAlwaysInline())
    inlineStrategy = AlwaysInline;

  auto *F = SILFunction::create(*this, linkage, name,
                                constantType, nullptr,
                                None, IsNotBare, IsTrans, IsSer, IsNotThunk,
                                constant.getSubclassScope(),
                                inlineStrategy, EK);
  F->setDebugScope(new (*this) SILDebugScope(loc, F));

  F->setGlobalInit(constant.isGlobal());
  if (constant.hasDecl()) {
    auto decl = constant.getDecl();

    if (constant.isForeign && decl->hasClangNode())
      F->setClangNodeOwner(decl);

    auto Attrs = decl->getAttrs();
    for (auto *A : Attrs.getAttributes<SemanticsAttr>())
      F->addSemanticsAttr(cast<SemanticsAttr>(A)->Value);

    for (auto *A : Attrs.getAttributes<SpecializeAttr>()) {
      auto *SA = cast<SpecializeAttr>(A);
      auto kind = SA->getSpecializationKind() ==
                          SpecializeAttr::SpecializationKind::Full
                      ? SILSpecializeAttr::SpecializationKind::Full
                      : SILSpecializeAttr::SpecializationKind::Partial;
      F->addSpecializeAttr(SILSpecializeAttr::create(
          *this, SA->getRequirements(), SA->isExported(), kind));
    }
  }

  // If this function has a self parameter, make sure that it has a +0 calling
  // convention. This cannot be done for general function types, since
  // function_ref's SILFunctionTypes do not have archetypes associated with
  // it.
  CanSILFunctionType FTy = F->getLoweredFunctionType();
  if (FTy->hasSelfParam()) {
    (void)&verifySILSelfParameterType;
    assert(verifySILSelfParameterType(constant, F, FTy) &&
           "Invalid signature for SIL Self parameter type");
  }

  return F;
}

SILFunction *SILModule::getOrCreateSharedFunction(SILLocation loc,
                                                  StringRef name,
                                                  CanSILFunctionType type,
                                                  IsBare_t isBareSILFunction,
                                                  IsTransparent_t isTransparent,
                                                  IsSerialized_t isSerialized,
                                                  IsThunk_t isThunk) {
  return getOrCreateFunction(loc, name, SILLinkage::Shared,
                             type, isBareSILFunction, isTransparent, isSerialized,
                             isThunk, SubclassScope::NotApplicable);
}

SILFunction *SILModule::createFunction(
    SILLinkage linkage, StringRef name, CanSILFunctionType loweredType,
    GenericEnvironment *genericEnv, Optional<SILLocation> loc,
    IsBare_t isBareSILFunction, IsTransparent_t isTrans,
    IsSerialized_t isSerialized, IsThunk_t isThunk, SubclassScope subclassScope,
    Inline_t inlineStrategy, EffectsKind EK, SILFunction *InsertBefore,
    const SILDebugScope *DebugScope) {
  return SILFunction::create(*this, linkage, name, loweredType, genericEnv, loc,
                             isBareSILFunction, isTrans, isSerialized, isThunk,
                             subclassScope, inlineStrategy, EK, InsertBefore,
                             DebugScope);
}

const IntrinsicInfo &SILModule::getIntrinsicInfo(Identifier ID) {
  unsigned OldSize = IntrinsicIDCache.size();
  IntrinsicInfo &Info = IntrinsicIDCache[ID];

  // If the element was is in the cache, return it.
  if (OldSize == IntrinsicIDCache.size())
    return Info;

  // Otherwise, lookup the ID and Type and store them in the map.
  StringRef NameRef = getBuiltinBaseName(getASTContext(), ID.str(), Info.Types);
  Info.ID = (llvm::Intrinsic::ID)getLLVMIntrinsicID(NameRef);

  return Info;
}

const BuiltinInfo &SILModule::getBuiltinInfo(Identifier ID) {
  unsigned OldSize = BuiltinIDCache.size();
  BuiltinInfo &Info = BuiltinIDCache[ID];

  // If the element was is in the cache, return it.
  if (OldSize == BuiltinIDCache.size())
    return Info;

  // Otherwise, lookup the ID and Type and store them in the map.
  // Find the matching ID.
  StringRef OperationName =
    getBuiltinBaseName(getASTContext(), ID.str(), Info.Types);

  // Several operation names have suffixes and don't match the name from
  // Builtins.def, so handle those first.
  if (OperationName.startswith("fence_"))
    Info.ID = BuiltinValueKind::Fence;
  else if (OperationName.startswith("cmpxchg_"))
    Info.ID = BuiltinValueKind::CmpXChg;
  else if (OperationName.startswith("atomicrmw_"))
    Info.ID = BuiltinValueKind::AtomicRMW;
  else if (OperationName.startswith("atomicload_"))
    Info.ID = BuiltinValueKind::AtomicLoad;
  else if (OperationName.startswith("atomicstore_"))
    Info.ID = BuiltinValueKind::AtomicStore;
  else if (OperationName.startswith("allocWithTailElems_"))
    Info.ID = BuiltinValueKind::AllocWithTailElems;
  else {
    // Switch through the rest of builtins.
    Info.ID = llvm::StringSwitch<BuiltinValueKind>(OperationName)
#define BUILTIN(ID, Name, Attrs) \
      .Case(Name, BuiltinValueKind::ID)
#include "swift/AST/Builtins.def"
      .Default(BuiltinValueKind::None);
  }

  return Info;
}

SILFunction *SILModule::lookUpFunction(SILDeclRef fnRef) {
  auto name = fnRef.mangle();
  return lookUpFunction(name);
}

bool SILModule::linkFunction(SILFunction *Fun, SILModule::LinkingMode Mode) {
  return SILLinkerVisitor(*this, getSILLoader(), Mode).processFunction(Fun);
}

bool SILModule::linkFunction(StringRef Name, SILModule::LinkingMode Mode) {
  return SILLinkerVisitor(*this, getSILLoader(), Mode).processFunction(Name);
}

SILFunction *SILModule::findFunction(StringRef Name, SILLinkage Linkage) {
  assert((Linkage == SILLinkage::Public ||
          Linkage == SILLinkage::PublicExternal) &&
         "Only a lookup of public functions is supported currently");

  SILFunction *F = nullptr;

  // First, check if there is a function with a required name in the
  // current module.
  SILFunction *CurF = lookUpFunction(Name);

  // Nothing to do if the current module has a required function
  // with a proper linkage already.
  if (CurF && CurF->getLinkage() == Linkage) {
    F = CurF;
  } else {
    assert((!CurF || CurF->getLinkage() != Linkage) &&
           "hasFunction should be only called for functions that are not "
           "contained in the SILModule yet or do not have a required linkage");
  }

  if (!F) {
    SILLinkerVisitor Visitor(*this, getSILLoader(),
                             SILModule::LinkingMode::LinkNormal);
    if (CurF) {
      // Perform this lookup only if a function with a given
      // name is present in the current module.
      // This is done to reduce the amount of IO from the
      // swift module file.
      if (!Visitor.hasFunction(Name, Linkage))
        return nullptr;
      // The function in the current module will be changed.
      F = CurF;
    }

    // If function with a given name wasn't seen anywhere yet
    // or if it is known to exist, perform a lookup.
    if (!F) {
      // Try to load the function from other modules.
      F = Visitor.lookupFunction(Name, Linkage);
      // Bail if nothing was found and we are not sure if
      // this function exists elsewhere.
      if (!F)
        return nullptr;
      assert(F && "SILFunction should be present in one of the modules");
      assert(F->getLinkage() == Linkage && "SILFunction has a wrong linkage");
    }
  }

  // If a function exists already and it is a non-optimizing
  // compilation, simply convert it into an external declaration,
  // so that a compiled version from the shared library is used.
  if (F->isDefinition() &&
      F->getModule().getOptions().Optimization <
          SILOptions::SILOptMode::Optimize) {
    F->convertToDeclaration();
  }
  if (F->isExternalDeclaration())
    F->setSerialized(IsSerialized_t::IsNotSerialized);
  F->setLinkage(Linkage);
  return F;
}

bool SILModule::hasFunction(StringRef Name) {
  if (lookUpFunction(Name))
    return true;
  SILLinkerVisitor Visitor(*this, getSILLoader(),
                           SILModule::LinkingMode::LinkNormal);
  return Visitor.hasFunction(Name);
}

void SILModule::linkAllFromCurrentModule() {
  getSILLoader()->getAllForModule(getSwiftModule()->getName(),
                                  /*PrimaryFile=*/nullptr);
}

void SILModule::linkAllWitnessTables() {
  getSILLoader()->getAllWitnessTables();
}

void SILModule::linkAllVTables() {
  getSILLoader()->getAllVTables();
}

void SILModule::invalidateSILLoaderCaches() {
  getSILLoader()->invalidateCaches();
}

void SILModule::removeFromZombieList(StringRef Name) {
  if (auto *Zombie = ZombieFunctionTable.lookup(Name)) {
    ZombieFunctionTable.erase(Name);
    zombieFunctions.remove(Zombie);
  }
}

/// Erase a function from the module.
void SILModule::eraseFunction(SILFunction *F) {
  assert(! F->isZombie() && "zombie function is in list of alive functions");
  // The owner of the function's Name is the FunctionTable key. As we remove
  // the function from the table we have to store the name string elsewhere:
  // in zombieFunctionNames.
  StringRef copiedName = F->getName().copy(zombieFunctionNames);
  FunctionTable.erase(F->getName());
  F->Name = copiedName;

  // The function is dead, but we need it later (at IRGen) for debug info
  // or vtable stub generation. So we move it into the zombie list.
  getFunctionList().remove(F);
  zombieFunctions.push_back(F);
  ZombieFunctionTable[copiedName] = F;
  F->setZombie();

  // This opens dead-function-removal opportunities for called functions.
  // (References are not needed anymore.)
  F->dropAllReferences();
}

void SILModule::invalidateFunctionInSILCache(SILFunction *F) {
  getSILLoader()->invalidateFunction(F);
}

/// Erase a global SIL variable from the module.
void SILModule::eraseGlobalVariable(SILGlobalVariable *G) {
  GlobalVariableMap.erase(G->getName());
  getSILGlobalList().erase(G);
}

SILVTable *SILModule::lookUpVTable(const ClassDecl *C) {
  if (!C)
    return nullptr;

  // First try to look up R from the lookup table.
  auto R = VTableMap.find(C);
  if (R != VTableMap.end())
    return R->second;

  // If that fails, try to deserialize it. If that fails, return nullptr.
  SILVTable *Vtbl =
      SILLinkerVisitor(*this, getSILLoader(), SILModule::LinkingMode::LinkAll)
          .processClassDecl(C);
  if (!Vtbl)
    return nullptr;

  // If we succeeded, map C -> VTbl in the table and return VTbl.
  VTableMap[C] = Vtbl;
  return Vtbl;
}

SerializedSILLoader *SILModule::getSILLoader() {
  // If the SILLoader is null, create it.
  if (!SILLoader)
    SILLoader = SerializedSILLoader::create(getASTContext(), this,
                                            Callback.get());
  // Return the SerializedSILLoader.
  return SILLoader.get();
}

/// \brief Given a conformance \p C and a protocol requirement \p Requirement,
/// search the witness table for the conformance and return the witness thunk
/// for the requirement.
std::pair<SILFunction *, SILWitnessTable *>
SILModule::lookUpFunctionInWitnessTable(ProtocolConformanceRef C,
                                        SILDeclRef Requirement) {
  // Look up the witness table associated with our protocol conformance from the
  // SILModule.
  auto Ret = lookUpWitnessTable(C);

  // If no witness table was found, bail.
  if (!Ret) {
    DEBUG(llvm::dbgs() << "        Failed speculative lookup of witness for: ";
          C.dump(); Requirement.dump());
    return std::make_pair(nullptr, nullptr);
  }

  // Okay, we found the correct witness table. Now look for the method.
  for (auto &Entry : Ret->getEntries()) {
    // Look at method entries only.
    if (Entry.getKind() != SILWitnessTable::WitnessKind::Method)
      continue;

    SILWitnessTable::MethodWitness MethodEntry = Entry.getMethodWitness();
    // Check if this is the member we were looking for.
    if (MethodEntry.Requirement != Requirement)
      continue;

    return std::make_pair(MethodEntry.Witness, Ret);
  }

  return std::make_pair(nullptr, nullptr);
}

/// \brief Given a protocol \p Protocol and a requirement \p Requirement,
/// search the protocol's default witness table and return the default
/// witness thunk for the requirement.
std::pair<SILFunction *, SILDefaultWitnessTable *>
SILModule::lookUpFunctionInDefaultWitnessTable(const ProtocolDecl *Protocol,
                                               SILDeclRef Requirement,
                                               bool deserializeLazily) {
  // Look up the default witness table associated with our protocol from the
  // SILModule.
  auto Ret = lookUpDefaultWitnessTable(Protocol, deserializeLazily);

  // If no default witness table was found, bail.
  //
  // FIXME: Could be an assert if we fix non-single-frontend mode to link
  // together serialized SIL emitted by each translation unit.
  if (!Ret) {
    DEBUG(llvm::dbgs() << "        Failed speculative lookup of default "
          "witness for " << Protocol->getName() << " ";
          Requirement.dump());
    return std::make_pair(nullptr, nullptr);
  }

  // Okay, we found the correct default witness table. Now look for the method.
  for (auto &Entry : Ret->getEntries()) {
    // Ignore dummy entries semitted for non-method requirements, as well as
    // requirements without default implementations.
    if (!Entry.isValid())
      continue;

    // Check if this is the member we were looking for.
    if (Entry.getRequirement() != Requirement)
      continue;

    return std::make_pair(Entry.getWitness(), Ret);
  }

  // This requirement doesn't have a default implementation.
  return std::make_pair(nullptr, nullptr);
}

static ClassDecl *getClassDeclSuperClass(ClassDecl *Class) {
  Type T = Class->getSuperclass();
  if (!T)
    return nullptr;
  return T->getCanonicalType()->getClassOrBoundGenericClass();
}

SILFunction *
SILModule::
lookUpFunctionInVTable(ClassDecl *Class, SILDeclRef Member) {
  // Until we reach the top of the class hierarchy...
  while (Class) {
    // Try to lookup a VTable for Class from the module...
    auto *Vtbl = lookUpVTable(Class);

    // Bail, if the lookup of VTable fails.
    if (!Vtbl) {
      return nullptr;
    }

    // Ok, we have a VTable. Try to lookup the SILFunction implementation from
    // the VTable.
    if (SILFunction *F = Vtbl->getImplementation(*this, Member))
      return F;

    // If we fail to lookup the SILFunction, again skip Class and attempt to
    // resolve the method in the VTable of the super class of Class if such a
    // super class exists.
    Class = getClassDeclSuperClass(Class);
  }

  return nullptr;
}

void SILModule::registerDeserializationCallback(
    SILFunctionBodyCallback callBack) {
  if (std::find(DeserializationCallbacks.begin(),
                DeserializationCallbacks.end(), callBack)
      == DeserializationCallbacks.end())
    DeserializationCallbacks.push_back(callBack);
}

ArrayRef<SILModule::SILFunctionBodyCallback>
SILModule::getDeserializationCallbacks() {
  return DeserializationCallbacks;
}

void SILModule::
registerDeleteNotificationHandler(DeleteNotificationHandler* Handler) {
  // Ask the handler (that can be an analysis, a pass, or some other data
  // structure) if it wants to receive delete notifications.
  if (Handler->needsNotifications()) {
    NotificationHandlers.insert(Handler);
  }
}

void SILModule::
removeDeleteNotificationHandler(DeleteNotificationHandler* Handler) {
  NotificationHandlers.remove(Handler);
}

void SILModule::notifyDeleteHandlers(ValueBase *V) {
  for (auto *Handler : NotificationHandlers) {
    Handler->handleDeleteNotification(V);
  }
}

// TODO: We should have an "isNoReturn" bit on Swift's BuiltinInfo, but for
// now, let's recognize noreturn intrinsics and builtins specially here.
bool SILModule::isNoReturnBuiltinOrIntrinsic(Identifier Name) {
  const auto &IntrinsicInfo = getIntrinsicInfo(Name);
  if (IntrinsicInfo.ID != llvm::Intrinsic::not_intrinsic) {
    return IntrinsicInfo.hasAttribute(llvm::Attribute::NoReturn);
  }
  const auto &BuiltinInfo = getBuiltinInfo(Name);
  switch (BuiltinInfo.ID) {
  default:
    return false;
  case BuiltinValueKind::Unreachable:
  case BuiltinValueKind::CondUnreachable:
  case BuiltinValueKind::UnexpectedError:
  case BuiltinValueKind::ErrorInMain:
    return true;
  }
}


text:
import os
from unittest.mock import patch

import pytest

from elizabeth.core.providers import Path
from elizabeth.intd import (
    PROGRAMMING_LANGS,
    FOLDERS,
    PROJECT_NAMES
)

@pytest.fixture
def path():
    return Path()

def test_root(path):
    platform_patcher = patch('sys.platform', 'win32')
    platform_patcher.start()
    assert 'С:\\' == path.root
    platform_patcher.stop()

    platform_patcher = patch('sys.platform', 'linux2')
    platform_patcher.start()
    assert '/' == path.root
    platform_patcher.stop()

def test_home(path):
    platform_patcher = patch('sys.platform', 'win32')
    platform_patcher.start()
    assert 'С:\\Users\\' == path.home
    platform_patcher.stop()

    platform_patcher = patch('sys.platform', 'linux2')
    platform_patcher.start()
    assert '/home/' == path.home
    platform_patcher.stop()

def test_user(path):
    user = path.user(gender='female')
    result = user.split(os.sep)
    assert len(result) == 3

def test_users_folder(path):
    folder = path.users_folder(user_gender='female')
    folder = folder.split(os.sep)
    assert len(folder) == 4
    assert folder[3] in FOLDERS

def test_dev_dir(path):
    dev_dir = path.dev_dir(user_gender='female')
    # /home/yajaira/Development/Lua
    dev_dir = dev_dir.split(os.sep)
    assert len(dev_dir) == 5
    assert dev_dir[4] in PROGRAMMING_LANGS

def test_project_dir(path):
    project_path = path.project_dir(user_gender='female')
    project_path = project_path.split(os.sep)
    assert len(project_path) == 6
    # /home/sherika/Development/Falcon/mercenary
    assert project_path[5] in PROJECT_NAMES


text:
<!DOCTYPE html>

	<meta charset="utf-8">

	<title>CGMCPCalibrationStatusOption Constants Reference</title>

	<link rel="stylesheet" href="../css/style.css">
	<meta name="viewport" content="initial-scale=1, maximum-scale=1.4">
	<meta name="generator" content="appledoc 2.2.1 (build 1333)">

				UHNCGMController

				Centre for Global eHealth Innovation

Index

Hierarchy

							On This Page

							<select id="jump-to">
	<option value="top">Jump To…</option>

</select>

CGMCPCalibrationStatusOption Constants Reference

	Declared in
	UHNCGMConstants.h

CGMCPCalibrationStatusOption

All possible CGMCP Calibration Status options

If none of the options are true, then the calibration data record was valid and accepted

Definition

                        typedef NS_ENUM(uint8_t, CGMCPCalibrationStatusOption ) {

                               CGMCPCalibrationStatusDataRejected = 0,

                               CGMCPCalibrationStatusDataOutOfRange,

                               CGMCPCalibrationStatusProcessPending,

                            };

Constants

CGMCPCalibrationStatusDataRejected

Calibration status indicating that the calibration data was rejected

		Declared In UHNCGMConstants.h.

CGMCPCalibrationStatusDataOutOfRange

Calibration status indicating that the calibration data was out-of-range

		Declared In UHNCGMConstants.h.

CGMCPCalibrationStatusProcessPending

Calibration status indicating that the calibration process is still pending

		Declared In UHNCGMConstants.h.

Declared In

UHNCGMConstants.h

Copyright © 2015 Centre for Global eHealth Innovation. All rights reserved. Updated: 2015-06-17

Generated by appledoc 2.2.1 (build 1333).


text:
use crate::runtime::program::{Program, RuntimeError};
use std::collections::{HashMap, LinkedList};
use crate::runtime::object::{Object, ModelInstance, Reference, make_reference, NativeModel, NativeFunction, NativeModelInstance};
use crate::intermediate::Position;
use crate::runtime::opcode::{Instruction, OpCode};
use std::ops::Deref;
use crate::runtime::object_property::{instance_get_array, instance_get_integer, instance_get_float, instance_get_string};

#[derive(Debug, Clone)]
pub struct Frame {
    pub locals: Vec<Object>,
    pub program_counter: usize,
    pub function_index: usize,
    pub stack_size: usize
}

impl Frame {
    pub fn new(local_count: usize, function_index: usize, stack_size: usize) -> Frame {
        let mut locals = Vec::new();
        for _ in 0..local_count {
            locals.push(Object::Null);
        };

        Frame {
            locals,
            program_counter: 0,
            function_index,
            stack_size
        }
    }
}

pub struct State {
    globals: HashMap<String, Object>,
    locals: Vec<Object>,
    native_models: Vec<Reference<dyn NativeModel>>,
    stack: LinkedList<Object>,
    frames: LinkedList<Frame>,
    program: Program
}

impl From<Program> for State {
    fn from(program: Program) -> Self {
        let mut locals = Vec::new();

        for i in 0..program.local_count {
            locals.push(if let Some(constant_index) = program.local_values.get(&i) {
                program.constants.get(*constant_index).unwrap().clone()
            } else {
                Object::Null
            });
        };

        State {
            globals: HashMap::new(),
            locals,
            native_models: Vec::new(),
            stack: LinkedList::new(),
            frames: LinkedList::new(),
            program
        }
    }
}

impl State {
    pub fn get_program(&self) -> &Program {
        &self.program
    }

    pub fn call_function_by_index(&mut self, function_index: usize, parameters: &[ Object ]) -> Result<(), RuntimeError> {
        let function = self.program.functions.get(function_index).unwrap();

        // function index is checked outside, no need to check here
        if parameters.len() > function.parameter_count {
            return Err(RuntimeError::new("too many parameters", Position::none()));
        }

        let mut frame = Frame::new(function.local_count, function_index, self.stack.len());

        for (i, object) in parameters.iter().enumerate() {
            frame.locals[i] = object.clone();
        }

        self.push_frame(frame);

        Ok(())
    }

    pub fn current_frame_as_mut(&mut self) -> &mut Frame {
        self.frames.back_mut().unwrap()
    }

    pub fn current_frame(&self) -> &Frame {
        self.frames.back().unwrap()
    }

    pub fn pop(&mut self) -> Option<Object> {
        self.stack.pop_back()
    }

    pub fn push(&mut self, object: Object) {
        self.stack.push_back(object)
    }

    pub fn top(&self) -> Object {
        self.stack.back().unwrap().clone()
    }

    pub fn last_position(&self) -> Position {
        let program_counter = self.current_frame().program_counter;
        if let Some(debug_info) = &self.program.debug_info {
            if program_counter > 0 {
                let function_index = self.current_frame().function_index;

                return debug_info.functions[function_index][program_counter - 1];
            };
        };

        Position::none()
    }

    pub fn execute_by_function_index(&mut self, function_index: usize, parameters: &[ Object ]) -> Result<Object, RuntimeError> {
        if self.program.functions.len() <= function_index {
            return Err(RuntimeError::new("can not found function", Position::none()));
        };

        let function = self.program.functions.get(function_index).unwrap();

        if parameters.len() > function.parameter_count {
            return Err(RuntimeError::new("too many parameters", Position::none()));
        };

        self.call_function_by_index(function_index, parameters)?;

        while !self.frames.is_empty() {
            self.step()?;
        };

        if let Some(object) = self.pop() {
            Ok(object)
        } else {
            Err(RuntimeError::new("there is no result", Position::none()))
        }
    }

    pub fn execute(&mut self) -> Result<Object, RuntimeError> {
        for &global_index in self.program.global_dependencies.iter() {
            if let Some(Object::String(global_name)) = self.program.constants.get(global_index) {
                if !self.globals.contains_key(global_name.borrow().deref()) {
                    return Err(RuntimeError::new(&format!("this program need a global variable [{}] which is not found in this state", global_name.borrow().deref()), Position::none()));
                }
            }
        }

        self.execute_by_function_index(self.program.entry_point, &[])
    }

    pub fn add_native_function(&mut self, name: &str, function: NativeFunction)  {
        self.globals.insert(name.to_string(), Object::NativeFunction(function));
    }

    pub fn add_native_model(&mut self, name: &str, native_model: Reference<dyn NativeModel>) -> usize {
        let index = self.native_models.len();
        self.native_models.push(native_model);

        self.globals.insert(name.to_string(), Object::NativeModel(index));

        index
    }

    pub fn step(&mut self) -> Result<(), RuntimeError> {
        if let Err(mut error) = self.internal_step() {

            let mut call_stack = LinkedList::new();

            while self.frames.len() > 0 {
                let rescue_position = self.program.functions.get(self.current_frame().function_index).unwrap().rescue_position;

                if rescue_position > 0 {
                    self.current_frame_as_mut().program_counter = rescue_position;
                    return Ok(());
                } else {
                    let frame = self.frames.pop_back().unwrap();
                    while self.stack.len() > frame.stack_size {
                        self.stack.pop_back();
                    };
                    call_stack.push_front(frame);
                }
            }

            error.stack = call_stack;

            Err(error)
        } else {
            Ok(())
        }
    }
}

impl State {
    fn call_model_by_index(&mut self, model_index: usize, parameters: &[ Object ]) -> Result<(), RuntimeError> {
        let model = self.program.models.get(model_index).unwrap();
        if parameters.len() > model.property_indices.len() {
            return Err(RuntimeError::new("too many parameters", Position::none()));
        };

        let mut properties = parameters.iter().cloned().collect::<Vec<Object>>();

        for _ in properties.len()..model.property_indices.len() {
            properties.push(Object::Null);
        };

        self.push(Object::Instance(make_reference(ModelInstance {
            model_index,
            properties
        })));

        Ok(())
    }

    fn call_native_function(&mut self, function: NativeFunction, parameters: &[ Object ]) -> Result<(), RuntimeError> {
            let result = function(self, parameters)?;
            self.push(result);
            Ok(())
    }

    fn call_instance_native_function(&mut self, instance: Reference<dyn NativeModelInstance>, function_name: &str, parameters: &[ Object ]) -> Result<(), RuntimeError> {
        let result = instance.borrow_mut().call(self, function_name, parameters)?;

        self.push(State::process_native_instance_result(instance, result));

        Ok(())
    }

    fn process_native_instance_result(instance: Reference<dyn NativeModelInstance>, result: Object) -> Object {
        match &result {
            Object::EmptyInstanceNativeFunction(function_name) => Object::InstanceNativeFunction(instance, function_name.clone()),
            _ => result
        }
    }

    fn call_object(&mut self, object: Object, parameters: &[ Object ]) -> Result<(), RuntimeError> {
        match object {
            Object::Function(function_index) => self.call_function_by_index(function_index, parameters),
            Object::InstanceFunction(model, function_index) => self.call_function_by_index(function_index,&make_instance_call_parameters(model.deref().clone(), parameters)),
            Object::NativeFunction(function) => self.call_native_function(function, parameters),
            Object::InstanceNativeFunction(instance, function_name) => self.call_instance_native_function(instance, &function_name, parameters),
            Object::Model(model_index) => self.call_model_by_index(model_index, parameters),
            _ => Err(RuntimeError::new(&format!("can not call {:?}", object), self.last_position()))
        }
    }

    fn execute_call_opcode(&mut self, parameter_count: usize) -> Result<(), RuntimeError> {
        let mut parameters = vec![Object::Null; parameter_count];

        for i in (0..parameter_count).rev() {
            parameters[i] = self.stack.pop_back().unwrap();
        };

        let function_object = self.stack.pop_back().unwrap();

        self.call_object(function_object, &parameters)
    }

    fn current_instruction(&self) -> Instruction {
        let (function_index, program_counter) = {
            let frame = self.frames.back().unwrap();
            (frame.function_index, frame.program_counter)
        };

        let function = self.program.functions.get(function_index).unwrap();

        function.instructions[program_counter]
    }

    fn push_frame(&mut self, frame: Frame) {
        self.frames.push_back(frame);
    }

    fn pop_frame(&mut self) {
        let frame = self.frames.pop_back().unwrap();

        if self.stack.len() > frame.stack_size + 1 {
            return;
        };

        let return_value = self.pop().unwrap();

        // clean up stack
        while self.stack.len() > frame.stack_size {
            self.pop();
        };

        self.push(return_value);
    }

    fn instance_get_native_model(&mut self, model_index: usize, key: &str) -> Result<(), RuntimeError> {
        let model = self.native_models.get(model_index).unwrap();
        let result = model.borrow().model_get(key)?;
        self.push(result);

        Ok(())
    }

    fn instance_get_native_instance(&mut self, instance: Reference<dyn NativeModelInstance>, key: &str) -> Result<(), RuntimeError> {
        let result = instance.borrow().instance_get(key)?;

        self.push(State::process_native_instance_result(instance, result));

        Ok(())
    }

    fn instance_get(&mut self) -> Result<(), RuntimeError> {
        let index = self.pop().unwrap();
        let instance = self.pop().unwrap();

        match instance {

            Object::Model(model_index) => self.index_get_model(model_index, &index)?,
            Object::Instance(model_instance) => self.index_get_model_instance(model_instance, &index)?,
            Object::NativeModel(model_index) => self.instance_get_native_model(model_index, index.as_reference_string().borrow().deref())?,
            Object::NativeInstance(instance) => self.instance_get_native_instance(instance, index.as_reference_string().borrow().deref())?,

            Object::Integer(value) => instance_get_integer(self, value, index.as_reference_string().borrow().deref())?,
            Object::Float(value) => instance_get_float(self, value, index.as_reference_string().borrow().deref())?,
            Object::String(value) => instance_get_string(self, value, index.as_reference_string().borrow().deref())?,

            Object::Array(array) => instance_get_array(self, array, index.as_reference_string().borrow().deref())?,
            _ => {
                return Err(RuntimeError::new("this object's instance get did not implemented yet", self.last_position()));
            }
        };

        Ok(())
    }

    // index get for model
    fn index_get_model(&mut self, model_index: usize, index: &Object) -> Result<(), RuntimeError> {
        if let Object::String(key) = &index {
            let model = self.program.models.get(model_index).unwrap();

            if let Some(&function_index) = model.functions.get(key.borrow().deref()) {
                self.push(Object::Function(function_index));
                return Ok(());
            };
        }

        self.push(Object::Null);
        Ok(())
    }

    fn index_get_model_instance(&mut self, model_instance: Reference<ModelInstance>, index: &Object) -> Result<(), RuntimeError> {
        if let Object::String(key) = &index {
            let model = self.program.models.get(model_instance.borrow().deref().model_index).unwrap();

            // have property?
            if let Some(&property_index) = model.property_indices.get(key.borrow().deref()) {
                self.push(model_instance.borrow().deref().properties[property_index].clone());
                return Ok(());
            };

            // have function?
            if let Some(&function_index) = model.functions.get(key.borrow().deref()) {
                if self.program.functions[function_index].is_instance {
                    self.push(Object::InstanceFunction(Box::new(Object::Instance(model_instance.clone())), function_index));
                } else {
                    self.push(Object::Function(function_index));
                };

                return Ok(());
            };

        } else if let Object::Integer(i) = &index {
            if let Some(object) = model_instance.borrow().deref().properties.get(*i as usize) {
                self.push(object.clone());
                return Ok(());
            }
        }
        self.push(Object::Null);

        Ok(())
    }

    fn index_get_array(&mut self, array: Reference<Vec<Object>>, index: &Object) -> Result<(), RuntimeError> {
        match index {
            Object::Integer(i) => {
                let array_index = *i;
                if array_index < 0 || array_index >= array.borrow().deref().len() as i64 {
                    return Err(RuntimeError::new("index out of range", self.last_position()));
                };

                self.push(array.borrow().deref().get(array_index as usize).unwrap().clone());
            },
            _ => {
                return Err(RuntimeError::new("can not get array with object index", self.last_position()));
            }
        };

        Ok(())
    }

    fn index_get(&mut self) -> Result<(), RuntimeError> {
        let index = self.pop().unwrap();
        let instance = self.pop().unwrap();

        match instance {
            Object::Model(model_index) => self.index_get_model(model_index, &index)?,
            Object::Instance(model_instance) => self.index_get_model_instance(model_instance, &index)?,
            Object::Array(array) => self.index_get_array(array, &index)?,
            _ => {
                return Err(RuntimeError::new("this object's instance get did not implemented yet", self.last_position()));
            }
        };

        Ok(())
    }

    fn instance_set(&mut self) -> Result<(), RuntimeError> {
        let index = self.pop().unwrap();
        let instance = self.pop().unwrap();

        match instance {
            Object::Instance(model_instance) => self.index_set_model_instance(model_instance, &index)?,
            Object::NativeInstance(instance) => instance.borrow_mut().instance_set(index.as_reference_string().borrow().deref(), self.top())?,
            _ => {
                return Err(RuntimeError::new("this object's instance set did not implemented yet", self.last_position()));
            }
        };

        Ok(())
    }

    fn index_set_model_instance_by_index(&mut self, model_instance: Reference<ModelInstance>, index: usize) -> Result<(), RuntimeError> {
        if let Some(object) = model_instance.borrow_mut().properties.get_mut(index as usize) {
            *object = self.top();
            Ok(())
        } else {
            Err(RuntimeError::new("index does not exists", self.last_position()))
        }
    }

    fn index_set_model_instance(&mut self, model_instance: Reference<ModelInstance>, index: &Object) -> Result<(), RuntimeError> {
        if let Object::String(key) = &index {
            let model = self.program.models.get(model_instance.borrow().deref().model_index).unwrap();

            // have property?
            if let Some(&property_index) = model.property_indices.get(key.borrow().deref()) {
                self.index_set_model_instance_by_index(model_instance, property_index)?;
            };

        } else if let Object::Integer(i) = &index {
            self.index_set_model_instance_by_index(model_instance, *i as usize)?;
        }

        Ok(())
    }

    fn index_set_array(&mut self, array: Reference<Vec<Object>>, index: &Object) -> Result<(), RuntimeError> {
        match index {
            Object::Integer(i) => {
                if *i < 0 || *i >= array.borrow().deref().len() as i64 {
                    return Err(RuntimeError::new("index out of range", self.last_position()));
                };

                array.borrow_mut()[*i as usize] = self.top();
            },
            _ => {
                return Err(RuntimeError::new("can not get array with object index", self.last_position()));
            }
        };

        Ok(())
    }

    fn index_set(&mut self) -> Result<(), RuntimeError> {
        let index = self.pop().unwrap();
        let instance = self.pop().unwrap();

        match instance {
            Object::Instance(model_instance) => self.index_set_model_instance(model_instance, &index)?,
            Object::NativeInstance(instance) => instance.borrow_mut().index_set(&index, self.top())?,
            Object::Array(array) => self.index_set_array(array, &index)?,
            _ => {
                return Err(RuntimeError::new("this object's instance set did not implemented yet", self.last_position()));
            }
        };

        Ok(())
    }

    fn push_array(&mut self, value_count: usize) -> Result<(), RuntimeError> {
        let mut array = Vec::<Object>::new();

        for _ in 0..value_count {
            array.push(self.pop().unwrap());
        }

        array.reverse();

        self.push(Object::Array(make_reference(array)));

        Ok(())
    }

    fn binary_operation(&mut self, operand: usize) -> Result<(), RuntimeError> {
        let right = self.pop().unwrap();
        let left = self.pop().unwrap();

        self.binary_operation_with_parameters(&left, &right, operand)?;

        Ok(())
    }

    fn internal_step(&mut self) -> Result<(), RuntimeError> {
        let instruction = self.current_instruction();
        let opcode = instruction.opcode();

        self.current_frame_as_mut().program_counter += 1;

        match opcode {
            OpCode::Pop => { self.stack.pop_back(); },
            OpCode::PushConstant => {
                let constant = self.program.constants[instruction.operand() as usize].clone();
                self.push(constant);
            },
            OpCode::Return => { self.pop_frame(); },

            OpCode::LocalGet => self.push(self.current_frame().locals.get(instruction.operand() as usize).unwrap().clone()),
            OpCode::LocalSet => { self.current_frame_as_mut().locals[instruction.operand() as usize] = self.top(); },
            OpCode::LocalInit => { self.current_frame_as_mut().locals[instruction.operand() as usize] = self.pop().unwrap(); },

            OpCode::ContextGet => self.push(self.locals.get(instruction.operand() as usize).unwrap().clone()),
            OpCode::ContextSet => { self.locals[instruction.operand() as usize] = self.top(); },

            OpCode::GlobalGet => {
                let global_object_option = if let Some(Object::String(global_name)) = self.program.constants.get(instruction.operand() as usize) {
                    if let Some(object) = self.globals.get(global_name.borrow().deref()) {
                       Some(object.clone())
                    } else {
                        return Err(RuntimeError::new("global not found", self.last_position()));
                    }
                } else {
                    None
                };

                if let Some(global_object) = global_object_option {
                    self.push(global_object);
                };

            },
            OpCode::GlobalSet => {
                if let Some(Object::String(global_name)) = self.program.constants.get(instruction.operand() as usize) {
                    if let Some(object) = self.globals.get_mut(global_name.borrow().deref()) {
                        *object = self.stack.back().unwrap().clone();
                    } else {
                        return Err(RuntimeError::new("global not found", self.last_position()));
                    }
                }
            },
            OpCode::InstanceGet => self.instance_get()?,
            OpCode::InstanceSet => self.instance_set()?,
            OpCode::IndexGet => self.index_get()?,
            OpCode::IndexSet => self.index_set()?,
            OpCode::Call => self.execute_call_opcode(instruction.operand() as usize)?,
            OpCode::Array => self.push_array(instruction.operand() as usize)?,
            OpCode::Operation => self.binary_operation(instruction.operand() as usize)?,
            OpCode::Not => {
                let value = Object::Boolean(!self.pop().unwrap().to_bool());
                self.push(value);
            },
            OpCode::Negative => {
                let target = self.pop().unwrap();
                self.push(self.negative_operation(&target)?)
            },
            OpCode::Jump => { self.current_frame_as_mut().program_counter = instruction.operand() as usize; },
            OpCode::JumpIf => {
                let object = self.pop().unwrap();
                if object.to_bool() {
                    self.current_frame_as_mut().program_counter = instruction.operand() as usize;
                };
            },
            OpCode::ForNext => { self.for_next(instruction.operand() as usize)?; },
            OpCode::Iterate => { self.iterate(instruction.operand() as usize); },
            _ => {
                // not implemented
            }
        }

        Ok(())
    }
}

// helpers
fn make_instance_call_parameters(object: Object, parameters: &[ Object ]) -> Vec<Object> {
    let mut new_parameters = vec![ object ];
    new_parameters.extend_from_slice(parameters);
    new_parameters
}