<commit_before>﻿// Copyright (c) 2012, 2013 <NAME> <<EMAIL>>
// All rights reserved.
//
// The contents of this file are made available under the terms of the
// Eclipse Public License v1.0 (the "License") which accompanies this
// distribution, and is available at the following URL:
// http://www.opensource.org/licenses/eclipse-1.0.php
//
// Software distributed under the License is distributed on an "AS IS" basis,
// WITHOUT WARRANTY OF ANY KIND, either expressed or implied. See the License for
// the specific language governing rights and limitations under the License.
//
// By using this software in any fashion, you are agreeing to be bound by the
// terms of the License.

namespace Brahma.FSharp.OpenCL.Translator

open System.Reflection
open Microsoft.FSharp.Quotations
open Brahma.FSharp.OpenCL.AST
open Microsoft.FSharp.Collections
open FSharpx.Collections
open Brahma.FSharp.OpenCL.Translator.QuotationTransformers
open FSharp.Quotations.Evaluator
open Brahma.FSharp

// Translations restricts the generic parameter of the AST nodes to the type Lang
#nowarn "64"

[<AutoOpen>]
module private BodyPatterns =
    let (|VarName|_|) (str: string) (var': Var) =
        match var'.Name with
        | tName when tName = str -> Some VarName
        | _ -> None

    let (|Lower|_|) (expected: string) (str: string) =
        match str with
        | _ when expected.ToLowerInvariant() = str.ToLowerInvariant() -> Some Lower
        | _ -> None

    let (|ForLoopWithStep|_|) = function
        | Patterns.Let
            (
                VarName "inputSequence",
                DerivedPatterns.SpecificCall <@ (.. ..) @> (
                    _,
                    _,
                    [start; step; finish]
                ),
                Patterns.Let (
                    VarName "enumerator",
                    _,
                    Patterns.TryFinally (
                        Patterns.WhileLoop (
                            _,
                            Patterns.Let (
                                loopVar,
                                _,
                                loopBody
                            )
                        ),
                        _
                    )
                )
            ) -> Some (loopVar, (start, step, finish), loopBody)
        | _ -> None

    let (|ForLoop|_|) = function
        | Patterns.Let
            (
                VarName "inputSequence",
                DerivedPatterns.SpecificCall <@ (..) @> (
                    _,
                    _,
                    [start; finish]
                ),
                Patterns.Let (
                    VarName "enumerator",
                    _,
                    Patterns.TryFinally (
                        Patterns.WhileLoop (
                            _,
                            Patterns.Let (
                                loopVar,
                                _,
                                loopBody
                            )
                        ),
                        _
                    )
                )
            ) -> Some (loopVar, (start, finish), loopBody)
        | _ -> None

module rec Body =
    // new var scope
    let private clearContext (targetContext: TranslationContext<'a, 'b>) =
        { targetContext with VarDecls = ResizeArray() }

    let toStb (s: Node<_>) = translation {
        match s with
        | :? StatementBlock<_> as s ->
            return s
        | x -> return StatementBlock <| ResizeArray [x :?> Statement<_>]
    }

    let private itemHelper exprs hostVar = translation {
        let! idx = translation {
            match exprs with
            | hd :: _ -> return! translateAsExpr hd
            | [] -> return raise <| InvalidKernelException("Array index missed!")
        }

        return idx, hostVar
    }

    let private translateBinding (var: Var) newName (expr: Expr) = translation {
        let! body = translateCond (*TranslateAsExpr*) expr
        let! varType = translation {
            match (body: Expression<_>) with
            | :? Const<_> as c ->
                return c.Type
            | :? ArrayInitializer<_> as ai ->
                return! Type.translate var.Type |> State.using (fun ctx -> { ctx with ArrayKind = CArrayDecl ai.Length })
            | _ -> return! Type.translate var.Type
        }

        let varDecl = VarDecl(varType, newName, Some body)
        if newName.Contains "Ref" then
            varDecl.SpaceModifier <- Some AddressSpaceQualifier.Private

        return varDecl
    }

    let private translateListOfArgs (args: Expr list) =
        args
        |> List.fold
            (fun state arg ->
                translation {
                    let! state = state
                    let! translated = translateCond arg
                    return translated :: state
                }
            ) (State.return' [])
        |> State.map List.rev

    let private translateCall exprOpt (mInfo: System.Reflection.MethodInfo) args = translation {
        let! args = translateListOfArgs args<commit_msg>Fix ref type detection<commit_after>﻿// Copyright (c) 2012, 2013 <NAME> <<EMAIL>>
// All rights reserved.
//
// The contents of this file are made available under the terms of the
// Eclipse Public License v1.0 (the "License") which accompanies this
// distribution, and is available at the following URL:
// http://www.opensource.org/licenses/eclipse-1.0.php
//
// Software distributed under the License is distributed on an "AS IS" basis,
// WITHOUT WARRANTY OF ANY KIND, either expressed or implied. See the License for
// the specific language governing rights and limitations under the License.
//
// By using this software in any fashion, you are agreeing to be bound by the
// terms of the License.

namespace Brahma.FSharp.OpenCL.Translator

open System.Reflection
open Microsoft.FSharp.Quotations
open Brahma.FSharp.OpenCL.AST
open Microsoft.FSharp.Collections
open FSharpx.Collections
open Brahma.FSharp.OpenCL.Translator.QuotationTransformers
open FSharp.Quotations.Evaluator
open Brahma.FSharp

// Translations restricts the generic parameter of the AST nodes to the type Lang
#nowarn "64"

[<AutoOpen>]
module private BodyPatterns =
    let (|VarName|_|) (str: string) (var': Var) =
        match var'.Name with
        | tName when tName = str -> Some VarName
        | _ -> None

    let (|Lower|_|) (expected: string) (str: string) =
        match str with
        | _ when expected.ToLowerInvariant() = str.ToLowerInvariant() -> Some Lower
        | _ -> None

    let (|ForLoopWithStep|_|) = function
        | Patterns.Let
            (
                VarName "inputSequence",
                DerivedPatterns.SpecificCall <@ (.. ..) @> (
                    _,
                    _,
                    [start; step; finish]
                ),
                Patterns.Let (
                    VarName "enumerator",
                    _,
                    Patterns.TryFinally (
                        Patterns.WhileLoop (
                            _,
                            Patterns.Let (
                                loopVar,
                                _,
                                loopBody
                            )
                        ),
                        _
                    )
                )
            ) -> Some (loopVar, (start, step, finish), loopBody)
        | _ -> None

    let (|ForLoop|_|) = function
        | Patterns.Let
            (
                VarName "inputSequence",
                DerivedPatterns.SpecificCall <@ (..) @> (
                    _,
                    _,
                    [start; finish]
                ),
                Patterns.Let (
                    VarName "enumerator",
                    _,
                    Patterns.TryFinally (
                        Patterns.WhileLoop (
                            _,
                            Patterns.Let (
                                loopVar,
                                _,
                                loopBody
                            )
                        ),
                        _
                    )
                )
            ) -> Some (loopVar, (start, finish), loopBody)
        | _ -> None

module rec Body =
    // new var scope
    let private clearContext (targetContext: TranslationContext<'a, 'b>) =
        { targetContext with VarDecls = ResizeArray() }

    let toStb (s: Node<_>) = translation {
        match s with
        | :? StatementBlock<_> as s ->
            return s
        | x -> return StatementBlock <| ResizeArray [x :?> Statement<_>]
    }

    let private itemHelper exprs hostVar = translation {
        let! idx = translation {
            match exprs with
            | hd :: _ -> return! translateAsExpr hd
            | [] -> return raise <| InvalidKernelException("Array index missed!")
        }

        return idx, hostVar
    }

    let private translateBinding (var: Var) newName (expr: Expr) = translation {
        let! body = translateCond (*TranslateAsExpr*) expr
        let! varType = translation {
            match (body: Expression<_>) with
            | :? Const<_> as c ->
                return c.Type
            | :? ArrayInitializer<_> as ai ->
                return! Type.translate var.Type |> State.using (fun ctx -> { ctx with ArrayKind = CArrayDecl ai.Length })
            | _ -> return! Type.translate var.Type
        }

        let varDecl = VarDecl(varType, newName, Some body)
        if varType :? RefType<Lang> then
            varDecl.SpaceModifier <- Some AddressSpaceQualifier.Private

        return varDecl
    }

    let private translateListOfArgs (args: Expr list) =
        args
        |> List.fold
            (fun state arg ->
                translation {
                    let! state = state
                    let! translated = translateCond arg
                    return translated :: state
                }
            ) (State.return' [])
        |> State.map List.rev

    let private translateCall exprOpt (mInfo: System.Reflection.MethodInfo) args = translation {
        let! args = translateListOfArgs args
{'fraction_non_alphanumeric': 0.08837665522314861, 'fraction_numerical': 0.0027464443354585583, 'mean_word_length': 1.344986200551978, 'pattern_counts': {'":': 0, '<': 36, '<?xml version=': 0, '>': 72, 'https://': 0, 'lorem ipsum': 0, 'www.': 2, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '5618541', 'n_tokens_mistral': 2650, 'n_tokens_neox': 2457, 'n_words': 732}