# Copyright Vladimir Prus 2004.
# Copyright Noel Belcourt 2007.
# Distributed under the Boost Software License, Version 1.0.
# (See accompanying file LICENSE_1_0.txt
# or copy at http://www.boost.org/LICENSE_1_0.txt)

import clang ;
import feature : feature ;
import os ;
import toolset ;
import toolset : flags ;
import gcc ;
import common ;
import errors ;
import generators ;

feature.extend-subfeature toolset clang : platform : darwin ;

## The MacOSX version to compile for, which maps to the SDK to use (sysroot).
#feature macosx-version : : propagated link-incompatible symmetric optional ;

## The minimal MacOSX version to target.
#feature macosx-version-min : : propagated optional ;

toolset.inherit-generators clang-darwin 
  <toolset>clang <toolset-clang:platform>darwin 
  : gcc 
  # Don't inherit PCH generators. They were not tested, and probably
  # don't work for this compiler.
  : gcc.mingw.link gcc.mingw.link.dll gcc.compile.c.pch gcc.compile.c++.pch
  ;

generators.override clang-darwin.prebuilt : builtin.lib-generator ;
generators.override clang-darwin.prebuilt : builtin.prebuilt ;
generators.override clang-darwin.searched-lib-generator : searched-lib-generator ;

toolset.inherit-rules clang-darwin : gcc ;
toolset.inherit-flags clang-darwin : gcc 
        : <inlining>off <inlining>on <inlining>full <optimization>space 
          <warnings>off <warnings>all <warnings>on
  	  <architecture>arm/<address-model>32
     	  <architecture>arm/<address-model>64
          <architecture>x86/<address-model>32
          <architecture>x86/<address-model>64
        ;
        
if [ MATCH (--debug-configuration) : [ modules.peek : ARGV ] ]
{
    .debug-configuration = true ;
}
                       
# vectorization diagnostics
feature vectorize : off on full ;

# Initializes the clang-darwin toolset
#   version in optional
#   name (default clang++) is used to invoke the specified clang complier
#   compile and link options allow you to specify addition command line options for each version
rule init ( version ? :  command * : options * : requirement * )
{
    # First time around, figure what is host OSX version
    if ! $(.host-osx-version)  
    {
        .host-osx-version = [ MATCH "^([0-9.]+)"
          : [ SHELL "/usr/bin/sw_vers -productVersion" ] ] ;
        if $(.debug-configuration)
        {
            ECHO notice: OSX version on this machine is $(.host-osx-version) ;
        }
    }

    # - The root directory of the tool install.
    local root = [ feature.get-values <root> : $(options) ] ;
    
    # - The bin directory where to find the commands to execute.
    local bin ;

    # The version as reported by the compiler
    local real-version ;

    command = [ common.get-invocation-command clang-darwin : clang++ 
        : $(command) ] ;

    # Determine the version
    local command-string = $(command:J=" ") ;
    if $(command)
    {    
        version ?= [ MATCH "^([0-9.]+)"
            : [ SHELL "$(command-string) -dumpversion" ] ] ;
    }
    
    # - Autodetect the root and bin dir if not given.
    if $(command)
    {
        bin ?= [ common.get-absolute-tool-path $(command[1]) ] ;
        if $(bin) = "/usr/bin"
        {
            root ?= /Developer ;
        }
        else
        {
            local r = $(bin:D) ;
            r = $(r:D) ;
            root ?= $(r) ;
        }
    }
    
    .real-version.$(version) = $(real-version) ;

    local condition = [ common.check-init-parameters clang-darwin $(requirement)
        : version $(version) ] ;    

    common.handle-options clang-darwin : $(condition) : $(command) : $(options) ;

    gcc.init-link-flags clang-darwin darwin $(condition) ;

    # - Initialize the SDKs available in the root for this tool.
    local sdks = [ init-available-sdk-versions $(condition) : $(root) ] ;

}

# Add and set options for a discovered SDK version.
local rule init-sdk ( condition * : root ? : version + : version-feature ? )
{
    local rule version-to-feature ( version + )
    {
        switch $(version[1])
        {
            case iphone* :
            {
                return $(version[1])-$(version[2-]:J=.) ;
            }
            case mac* :
            {
                return $(version[2-]:J=.) ;
            }
            case * :
            {
                return $(version:J=.) ;
            }
        }
    }
    
    if $(version-feature)
    {
        if $(.debug-configuration)
        {
            ECHO notice: available sdk for $(condition)/<macosx-version>$(version-feature) at $(sdk) ;
        }
        
        # Add the version to the features for specifying them.
        if ! $(version-feature) in [ feature.values macosx-version ]
        {
            feature.extend macosx-version : $(version-feature) ;
        }
        if ! $(version-feature) in [ feature.values macosx-version-min ]
        {
            feature.extend macosx-version-min : $(version-feature) ;
        }
        
        # Set the flags the version needs to compile with, first
        # generic options.
        flags clang-darwin.compile OPTIONS $(condition)/<macosx-version>$(version-feature)
            : -isysroot $(sdk) ;
        flags clang-darwin.link OPTIONS $(condition)/<macosx-version>$(version-feature)
            : -isysroot $(sdk) ;
        
        # Then device variation options.
        switch $(version[1])
        {
            case iphone* :
            {
                flags clang-darwin.compile OPTIONS <macosx-version-min>$(version-feature)
                    : -miphoneos-version-min=$(version[2-]:J=.) ;
                flags clang-darwin.link OPTIONS <macosx-version-min>$(version-feature)
                    : -miphoneos-version-min=$(version[2-]:J=.) ;
            }
            
            case mac* :
            {
                flags clang-darwin.compile OPTIONS <macosx-version-min>$(version-feature)
                    : -mmacosx-version-min=$(version[2-]:J=.) ;
                flags clang-darwin.link OPTIONS <macosx-version-min>$(version-feature)
                    : -mmacosx-version-min=$(version[2-]:J=.) ;
            }
        }
        
        return $(version-feature) ;
    }
    else if $(version[4])
    {
        # We have a patch version of an SDK. We want to set up
        # both the specific patch version, and the minor version.
        # So we recurse to set up the minor version. Plus the minor version.
        return
            [ init-sdk $(condition) : $(root)
                : $(version[1-3]) : [ version-to-feature $(version[1-3]) ] ]
            [ init-sdk $(condition) : $(root)
                : $(version) : [ version-to-feature $(version) ] ] ;
    }
    else
    {
        # Yes, this is intentionally recursive.
        return
            [ init-sdk $(condition) : $(root)
                : $(version) : [ version-to-feature $(version) ] ] ;
    }
}

# Determine the MacOSX SDK versions installed and their locations.
local rule init-available-sdk-versions ( condition * : root ? )
{
    root ?= /Developer ;
    local sdks-root = $(root)/SDKs ;
    local sdks = [ GLOB $(sdks-root) : MacOSX*.sdk iPhoneOS*.sdk iPhoneSimulator*.sdk ] ;
    local result ;
    for local sdk in $(sdks)
    {
        local sdk-match = [ MATCH ([^0-9]+)([0-9]+)[.]([0-9x]+)[.]?([0-9x]+)? : $(sdk:D=) ] ;
        local sdk-platform = $(sdk-match[1]:L) ;
        local sdk-version = $(sdk-match[2-]) ;
        if $(sdk-version)
        {
            switch $(sdk-platform)
            {
                case macosx :
                {
                    sdk-version = mac $(sdk-version) ;
                }
                case iphoneos :
                {
                    sdk-version = iphone $(sdk-version) ;
                }
                case iphonesimulator :
                {
                    sdk-version = iphonesim $(sdk-version) ;
                }
                case * :
                {
                    sdk-version = $(sdk-version:J=-) ;
                }
            }
            result += [ init-sdk $(condition) : $(sdk) : $(sdk-version) ] ;
        }
    }
    return $(result) ;
}

rule setup-address-model ( targets * : sources * : properties * )
{
    local ps = [ property-set.create $(properties) ] ;
    local arch = [ $(ps).get <architecture> ] ;
    local address-model = [ $(ps).get <address-model> ] ;
    local osx-version = [ $(ps).get <macosx-version> ] ;
    local options ;
    
    osx-version ?= $(.host-osx-version) ;

    switch $(arch)
    {
        case combined : 
        {
            if $(address-model) = 32_64 {
	        # Build 3-way binary
                options = -arch i386 -arch ppc -arch x86_64 ;
            } else if $(address-model) = 64 {
                errors.user-error "64-bit PPC compilation is not supported when targeting OSX 10.6 or later" ;
            } else {
                options = -arch i386 -arch ppc ;
            }
        }
        
        case x86 : 
        {
            if $(address-model) = 32_64 {
                options = -arch i386 -arch x86_64 ;
            } else if $(address-model) = 64 {
                options = -arch x86_64 ;
            } else {
                options = -arch i386 ;
            }
        }        
                
        case arm :
        {
            options = -arch armv6 ;
        }        
    }
    
    if $(options)
    {
        OPTIONS on $(targets) += $(options) ;
    }            
}


SPACE = " " ;

flags clang-darwin.compile OPTIONS <cflags> ;
flags clang-darwin.compile OPTIONS <cxxflags> ;
# flags clang-darwin.compile INCLUDES <include> ;

# Declare flags and action for compilation.
toolset.flags clang-darwin.compile OPTIONS <optimization>off   : -O0 ;
toolset.flags clang-darwin.compile OPTIONS <optimization>speed : -O3 ;
toolset.flags clang-darwin.compile OPTIONS <optimization>space : -Os ;

toolset.flags clang-darwin.compile OPTIONS <inlining>off  : -fno-inline ;
toolset.flags clang-darwin.compile OPTIONS <inlining>on   : -Wno-inline ;
toolset.flags clang-darwin.compile OPTIONS <inlining>full : -finline-functions -Wno-inline ;

toolset.flags clang-darwin.compile OPTIONS <warnings>off : -w ;
toolset.flags clang-darwin.compile OPTIONS <warnings>on  : -Wall ;
toolset.flags clang-darwin.compile OPTIONS <warnings>all : -Wall -pedantic ;
toolset.flags clang-darwin.compile OPTIONS <warnings-as-errors>on : -Werror ;

toolset.flags clang-darwin.compile OPTIONS <debug-symbols>on : -g ;
toolset.flags clang-darwin.compile OPTIONS <profiling>on : -pg ;
toolset.flags clang-darwin.compile OPTIONS <rtti>off : -fno-rtti ;

actions compile.c
{
    "$(CONFIG_COMMAND)" -x c $(OPTIONS) -D$(DEFINES) -I"$(INCLUDES)" -c -o "$(<)" "$(>)"
}

actions compile.c++
{
    "$(CONFIG_COMMAND)" -x c++ $(OPTIONS) -D$(DEFINES) -I"$(INCLUDES)" -c -o "$(<)" "$(>)"
}

flags clang-darwin ARFLAGS <archiveflags> ;

# Default value. Mostly for the sake of clang-linux
# that inherits from gcc, but does not has the same
# logic to set the .AR variable. We can put the same
# logic in clang-linux, but that's hardly worth the trouble
# as on Linux, 'ar' is always available.
.AR = ar ;

rule archive ( targets * : sources * : properties * )
{
  # Always remove archive and start again. Here's rationale from
  # Andre Hentz:
  #
  # I had a file, say a1.c, that was included into liba.a. 
  # I moved a1.c to a2.c, updated my Jamfiles and rebuilt. 
  # My program was crashing with absurd errors. 
  # After some debugging I traced it back to the fact that a1.o was *still* 
  # in liba.a 
  #
  # Rene Rivera:
  #
  # Originally removing the archive was done by splicing an RM
  # onto the archive action. That makes archives fail to build on NT
  # when they have many files because it will no longer execute the
  # action directly and blow the line length limit. Instead we
  # remove the file in a different action, just before the building
  # of the archive.
  #
  local clean.a = $(targets[1])(clean) ;
  TEMPORARY $(clean.a) ;
  NOCARE $(clean.a) ;
  LOCATE on $(clean.a) = [ on $(targets[1]) return $(LOCATE) ] ;
  DEPENDS $(clean.a) : $(sources) ;
  DEPENDS $(targets) : $(clean.a) ;
  common.RmTemps $(clean.a) : $(targets) ;
}

actions piecemeal archive
{
  "$(.AR)" $(AROPTIONS) rc "$(<)" "$(>)"
  "ranlib" -cs "$(<)"
}

flags clang-darwin.link USER_OPTIONS <linkflags> ;

# Declare actions for linking
rule link ( targets * : sources * : properties * )
{
  SPACE on $(targets) = " " ;
  # Serialize execution of the 'link' action, since
  # running N links in parallel is just slower.
  JAM_SEMAPHORE on $(targets) = <s>clang-darwin-link-semaphore ;
}

actions link bind LIBRARIES
{
    "$(CONFIG_COMMAND)" $(USER_OPTIONS) -L"$(LINKPATH)" -o "$(<)" "$(>)" "$(LIBRARIES)" -l$(FINDLIBS-SA) -l$(FINDLIBS-ST) $(OPTIONS)
}

actions link.dll bind LIBRARIES
{
    "$(CONFIG_COMMAND)" $(USER_OPTIONS) -L"$(LINKPATH)" -o "$(<)" -single_module -dynamiclib -install_name "$(<[1]:D=)" "$(>)"  "$(LIBRARIES)" -l$(FINDLIBS-SA) -l$(FINDLIBS-ST) $(OPTIONS)
}
