Transcript
Page 1: 2011-11-14 Chapter 5 Data Types - Sangji Universitycompiler.sangji.ac.kr/lecture/plt/2014/Type_add.pdf · 2011-11-14 1 Chapter 5 Data Types SANGJI University KO Kwangman (kkman@sangji.ac.kr)

2011-11-14

1

Chapter 5

Data Types

SANGJI University

KO Kwangman([email protected])

[email protected] 2

1. Introductiono Type supports abstraction

RealWorld

NaturalNumbers

RealNumbers

ProgrammingLanguage

intdata

doubledata

ProgrammingLanguage

Implementation

binary digitsin sizeof(int)

bytes

binary digitsin sizeof(int)

bytes

유한성(finite)추상화(abstraction)

concreterepresentation

2'scomplement

IEEE754

Chap. 5 : Data Type

[email protected]

o 타입(type)~ 값의 집합과 그 값들에 대한 연산의 집합.

~ 정수 타입

§ 값 : ..., -2, -1, 0, 1, 2, ...

§ 연산 : +, -, *, /, <, ...로 구성

~ 불 타입

§ 값 : true, false

§ 연산 : Ù, Ú, Ø

Chap. 5 : Data Type 3

Page 2: 2011-11-14 Chapter 5 Data Types - Sangji Universitycompiler.sangji.ac.kr/lecture/plt/2014/Type_add.pdf · 2011-11-14 1 Chapter 5 Data Types SANGJI University KO Kwangman (kkman@sangji.ac.kr)

2011-11-14

2

[email protected]

5.1 자료형 오류o 컴퓨터에 저장된 데이터~ 자료형 정보를 가지고 있지 않다.

~ 기본적으로 비트들의 열(sequence)을 저장

§ 예 : 0100 0000 0101 1000 0000 0000 0000 0000

o 비트열의 가능한 해석~ 부동 소수점 수 3.375

• 32비트 정수 1,079,508,992.

• 두 개의 16비트 정수 16472와 0

• 네 개의 ASCII 문자열 @ X NUL NUL

Chap. 5 : Data Type 4

[email protected]

o 타입 오류(type error) ~ 어떤 연산을 해당하지 않는 타입의 값에 적용함으로써 발생

하는 오류

~ 어셈블리 프로그램 작성 시에 자주 발생

~ 고급 언어의 경우에는 컴파일러와 실행시간 시스템이 타입오류를 검사 및 추출

~ 타입 체계(type system)는 타입 오류를 검출하기 위한 기반을 제공

Chap. 5 : Data Type 5

[email protected]

5.2 정적 및 동적 타입 결정o 타입 체계~ 덧셈에 사용되는 값은 숫자여야 한다는 것과 같은 제약을 보

~ EBNF를 사용하여 문법적으로 표현할 수 없음.

o 자료형 검사~ 컴파일 시간에 타입 검사 수행

§ C 언어

~ 실행 시간에 타입 검사 수행

§ Perl 언어

~ 두 가지 방법을 다 사용하기도 한다.

§ Java 언어

Chap. 5 : Data Type 6

Page 3: 2011-11-14 Chapter 5 Data Types - Sangji Universitycompiler.sangji.ac.kr/lecture/plt/2014/Type_add.pdf · 2011-11-14 1 Chapter 5 Data Types SANGJI University KO Kwangman (kkman@sangji.ac.kr)

2011-11-14

3

[email protected]

o statically typed~ 변수의 타입이 컴파일 시간에 선언에 의하여 고정

~ 정적으로 타입이 결정(statically typed)되는 언어

o dynamically typed~ 변수의 타입이 저장되는 값에 따라 실행 중에 볂하

~ 동적으로 타입이 결정(dynamically typed )되는 언어

Chap. 5 : Data Type 7

[email protected]

o strongly typed 언어~ 타입 체계가 컴파일 중이나 실행 중에 모든 타입 오류를 찾

아낼 수 있을 언어

~ 동적 타입 결정 또는 정적 타입 결정.

~ 유니온(union) 타입

§ 많은 언어들에서 타입 체계의 허점의 원인

~ 동적으로 타입이 결정되는 언어는 각각의 값에 타입을 함께저장

Chap. 5 : Data Type 8

[email protected]

5.3 기본 타입o 현재 32-bit 컴퓨터에서 사용되는 용어~ Nibble: 4 bits

~ Byte: 8 bits

~ Half-word: 16 bits

~ Word: 32 bits

~ Double word: 64 bits

~ Quad word: 128 bits

o 대부분의 언어에서 숫자 타입은 유한한 크기~ a + b, Overflow 가능성

~ 수학과의 차이점 존재:

§ a + (b + c) ¹ (a + b) + c

Page 4: 2011-11-14 Chapter 5 Data Types - Sangji Universitycompiler.sangji.ac.kr/lecture/plt/2014/Type_add.pdf · 2011-11-14 1 Chapter 5 Data Types SANGJI University KO Kwangman (kkman@sangji.ac.kr)

2011-11-14

4

[email protected]

o 중복(overloaded)~ 함수나 연산자가 인수의 타입에 따라 그 의미가 달라지는

~ a + b in Java

§ 정수 덧셈

§ 부동소수점수 덧셈

§ 문자열 접합 (concatenation)

~ 혼합모드

§ 하나는 정수이고 다른 인수는 부동소수점수인 경우

[email protected]

o 자료형 변환~ narrowing 변환

§ 원래 값보다 더 적은 수의 비트열을 결과로 생성하는 타입 변환

~ widening

~ 묵시적 변환이 허용되지 않는 이유?

Chap. 5 : Data Type 11

[email protected]

5.4 사용자 정의 자료형o 열거형(Enumeration) :

enum day {Mon, Tue, Wed, Thu, Fri, Sat, Sun};

enum day myDay = Wednesday;

~ C/C++ 에서 위 타입들의 값은 0, ..., 6이 사용된다.

~ Java는 더 강력한 구조가 사용

for (day d : day.values())

Sytem.out.println(d);

Chap. 5 : Data Type 12

Page 5: 2011-11-14 Chapter 5 Data Types - Sangji Universitycompiler.sangji.ac.kr/lecture/plt/2014/Type_add.pdf · 2011-11-14 1 Chapter 5 Data Types SANGJI University KO Kwangman (kkman@sangji.ac.kr)

2011-11-14

5

[email protected]

Pointero 포인터(pointer)~ 다른 변수의 주소를 가지고 있는 변수

~ 포인터가 가리키는 내용의 변경: * 연산자 사용

Chap. 5 : Data Type 13

char a='A';char *p;p = &a;

26

‘A’

변수 a

주소

26

포인터 p

*p= 'B';

[email protected]

o 포인터 연산자~ & 연산자

§ 변수의 주소를 추출

~ * 연산자

§ 포인터가 가리키는 곳의 내용을 추출

Chap. 5 : Data Type 14

26

‘A’

변수 a

주소

26

포인터 p

&a*p

[email protected]

o 포인터의 사용

struct Node {

int key;

struct Node* next;

};

struct Node* head;

Chap. 5 : Data Type 15

Page 6: 2011-11-14 Chapter 5 Data Types - Sangji Universitycompiler.sangji.ac.kr/lecture/plt/2014/Type_add.pdf · 2011-11-14 1 Chapter 5 Data Types SANGJI University KO Kwangman (kkman@sangji.ac.kr)

2011-11-14

6

[email protected]

o 포인터 사용에서 발생될 수 있는 문제~ 신뢰성 있는 소프트웨어의 개발을 방해.

~ 오류가 생기기 쉽다

~ 버퍼 넘침(Buffer overflow), 메모리 누출(memory leaks)

~ 특히 C 에서 문제가 많이 발생함

Chap. 5 : Data Type 16

[email protected]

Array, List

o 배열(array)

~ 동일 자료형(same type)의 자료들이 순서(linear) 있게구성된 집합

~ 연속된 기억 공간 차지

~ 유한한 개수의 자료가 저장됨

~ 직접접근 (direct access)

§ 기준위치에 대한 상대적 위치를 나타내는 인덱스(index)를 사용하여 가능

Chap. 5 : Data Type 17

… …A[0] A[1] A[9]

시작주소(base)

배열이름 : 기억장소의 시작위치(주소)

인덱스(첨자)

[email protected]

o Java에서의 배열~ 선언(declaration)

§ 생성될 배열 시작 위치 저장

int dsInt [] ;

~ 생성(creation)

§ 힙 메모리에서 배열 크기만큼의

기억 공간을 할당한 후 시작 주소를 배정

dsInt = new int[3] ;

Chap. 5 : Data Type 18

1) int dsint []

2) dsInt = new int[3]

dsInt[0]dsInt[1]dsInt[2]

3) 생성된 배열의시작주소 전달

Page 7: 2011-11-14 Chapter 5 Data Types - Sangji Universitycompiler.sangji.ac.kr/lecture/plt/2014/Type_add.pdf · 2011-11-14 1 Chapter 5 Data Types SANGJI University KO Kwangman (kkman@sangji.ac.kr)

2011-11-14

7

[email protected]

o Homeworks~ 연결 리스트

~ 구조체

~ 유니온

~ 문자열

~ 부분 범위형

Chap. 5 : Data Type 19

[email protected] 20

명시적 자료형(Explicit Typing)

o 정적 자료형 검사(static type checking)~ static type checking is still controversial.

~ 유연성(flexibility)

§ 자료형 결정 및 검사를 느슨 또는 반대

~ 신뢰성(reliability) 또는 보안(security)

§ 최대한 제약성(restrictiveness)

§ 엄격한 번역 시간 자료형 검사

Flexibility

type-lesslanguage

Reliability(security)

strongly typedlanguage

stillcontroversial

Chap. 5 : Data Type

[email protected] 21

정적 자료형 검사의 이유

1. 수행 효율성(execution efficiency)~ no need to run-time type checking

~ 효율적인 메모리 할당

~ 효율적인 목적기계 코드 생성

2.번역 효율성(Translation Efficiency)~ 분리 컴파일(separate compilation) 가능

~ 재컴파일시 컴파일되는 코드의 양을 줄일 수 있음

3. 작성 용이성(writability, Coding Efficiency)~ 번역시에 타입 에러를 조기에 발견

Chap. 5 : Data Type

Page 8: 2011-11-14 Chapter 5 Data Types - Sangji Universitycompiler.sangji.ac.kr/lecture/plt/2014/Type_add.pdf · 2011-11-14 1 Chapter 5 Data Types SANGJI University KO Kwangman (kkman@sangji.ac.kr)

2011-11-14

8

[email protected] 22

4. 보안과 신뢰성(security & reliability)~ 실행시 발생 될 수 있는 에러를 사전 차단

5.판독성(readability)~ 명시적 자료형 선언은 자료형 설계를 문서화

~ good for documentation

6. 모호성 제거(remove ambiguity)~ 다중 적재된 명칭(overloaded names)에 대한 모호성 해

결(resolving)

7. …

Chap. 5 : Data Type

[email protected] 23

자료형 정의

o 정의_1~ a set of values~ ex) the data type int in Java

~ Vint = { x | x ∈ Z,

~ -2,147,483,648 ≤ x ≤ 2,147,483,647 }

o 정의_2

~ a set of values with a set of operations

~ ex) the data type int in Java

Vint = { x | x ∈ Z,

-2,147,483,648 ≤ x ≤ 2,147,483,647 }

with the following set of operations

Fint = { +, -, *, … }

Chap. 5 : Data Type

[email protected] 24

자료형 검사, 자료형 추론

o 자료형 검사(type checking)~ 번역기가 프로그램내에 자료형 정보에 문제가 없는지 검사

한 과정

~ 연산자(서브 프로그램)과 피연산자(매개변수) 사이에 자료형의 일관성(type consistency)을 검사한 과정

o 자료형 추론(type inference)~ 수식에 자료형 부착(attaching)시키는 동작

~ z=x/y에서 z의 자료형을 결정하기 위해서 ?

§ x, y의 의 자료형이 결정되어야 함.

o 상호의존족~ 자료형 검사와 자료형 추론은 상호의존적

Chap. 5 : Data Type

Page 9: 2011-11-14 Chapter 5 Data Types - Sangji Universitycompiler.sangji.ac.kr/lecture/plt/2014/Type_add.pdf · 2011-11-14 1 Chapter 5 Data Types SANGJI University KO Kwangman (kkman@sangji.ac.kr)

2011-11-14

9

[email protected] 25

Constructing Types

o 자료형 구성자(type constructors)~ 기본 자료형으로 부터 새로운 자료형을 구성

~ Derived types are parameterized type constructors.

Basic Types(primitive types)int, double,

Derived Typesarray, structures,

…type constructors

type constructors

사용자-정의 자료형(user-defined data type)

Chap. 5 : Data Type

[email protected] 26

o 자료형 선언(type declaration)~ 새로운 자료형에 이름 부여

(In C example)

typedef int int10[10];

Chap. 5 : Data Type

[email protected] 27

자료형 시스템(type system)

o 자료형 동등성(type equivalence) 알고리즘~ 두 개의 자료형이 일치하는지 여부를 결정하는 알고리즘

~ 방법 ?

o 자료형 시스템(type system)~ 자료형 구성 방법

~ 자료형 동등성 알고리즘

~ 자료형 검사, 자료형 추론

~ …

Chap. 5 : Data Type

Page 10: 2011-11-14 Chapter 5 Data Types - Sangji Universitycompiler.sangji.ac.kr/lecture/plt/2014/Type_add.pdf · 2011-11-14 1 Chapter 5 Data Types SANGJI University KO Kwangman (kkman@sangji.ac.kr)

2011-11-14

10

[email protected] 28

Typingo 엄격한 자료형(strongly-typed) 언어~ 모든 자료형 에러가 번역 시간에 발견

~ 가능한 가장 이른 시점에 프로그램내의 모든 에러 발견

~ 예외(exception) 검사

§ 실행 도중에만 검사할 수 있는 오류s.~ 불안전한 프로그램은 대부분 번역 시간에 거부

~ 너무 엄격해서 적법한 프로그램까지 거부

~ 적적한 자료형 정보를 프로그래머가 명시적으로 제공

~ Ada, Haskell, Pascal, …

Chap. 5 : Data Type

[email protected] 29

o 느스한 자료형(weakly-typed) 언어~ the languages which detect type errors during

translation time but allow a few loopholes

o 타입 결여(untyped) 언어~ 정적 자료형 시스템을 지원하지 않는 언어

~ 데이터 안전성에 관한 검사가 실행시간에 이루어짐.

~ Scheme, LISP, Smalltalk, Perl, …

Chap. 5 : Data Type

[email protected] 30

Safe Programs

o Every well-typed programs are safe but not vice versa.

Executable Programs

Legal Programs(Safe Programs)

Well-Typed ProgramsUnsafe Programs

contain data-corrupting

errors

Chap. 5 : Data Type

Page 11: 2011-11-14 Chapter 5 Data Types - Sangji Universitycompiler.sangji.ac.kr/lecture/plt/2014/Type_add.pdf · 2011-11-14 1 Chapter 5 Data Types SANGJI University KO Kwangman (kkman@sangji.ac.kr)

2011-11-14

11

[email protected] 31

단순 타입(Simple Types)

o 단순 타입~ atomic types

~ the types which contain no other type substructures

o 단순 타입의 분류

SimpleTypes

Predefined Simple Types

User-Defined Ordinal Types

Enumeration Types

Subrange TypesDefined Operators: • successor• predecessor• comparison

Chap. 5 : Data Type

[email protected] 32

Ordinal Type Exampleo Enumerated Type in C

enum Color { Red, Green, Blue };

o Enumerated Type in Adatype Color_Type is (Red, Green, Blue);

o Enumerated Type in MLdatatype Color_Type = Red | Green | Blue;

o Java does not have enumerated types.

o Subrange Type in Adatype Digit_Type is range 0..9;

Chap. 5 : Data Type

[email protected]

Some Notes on Simple Typeso 순서 타입(ordinal type)~ 비교 연산자를 항상 지원하지 않음

~ ex) Subrange of floating-point numbers in Ada.

type Unit_Interval is range 0.0..1.0;

o 부분범위타입(subrange type)

type Digit_Type is range 0 .. 9;

~ 효과 ?

o 단순 자료형은 하드웨어상에서 직접 구현~ 하드웨어 효율성 중시

Chap. 5 : Data Type

Page 12: 2011-11-14 Chapter 5 Data Types - Sangji Universitycompiler.sangji.ac.kr/lecture/plt/2014/Type_add.pdf · 2011-11-14 1 Chapter 5 Data Types SANGJI University KO Kwangman (kkman@sangji.ac.kr)

2011-11-14

12

[email protected] 34

Type Constructorso 타입~ 집합(set)

~ 집합 연산이 기존의 타입에서 새로운 타입을 구성하는데 사용

o 타입 구성자(type constructor)~ 집합 연산이 타입에 적용

~ 데카르트 곱, 합집합, 멱집합, 함수집합, 부분집합.

Chap. 5 : Data Type

[email protected] 35

데카르트 곱(cartesian product)

o Cartesian product~ a set of pairs

~ 두 집합 U, V에 대한 모든 원소들의 순서쌍(ordered pair)

U ⅹ V = { (u, v) | u∈ U and v ∈ V }

with projection functions p1 and p2:

p1: U ⅹ V → U p1 ((u, v)) = u

p2: U ⅹ V → V p2 ((u, v)) = v

o corresponding to the Cartesian products~ record (structure) constructors

Chap. 5 : Data Type

[email protected] 36

Example: Structure Types in Cstruct IntReal // IntReal = int ⅹ double{

int i;double r;

};struct IntReal x = {1, 2.5};

// x = (1, 2.5) ∈ IntReal

x.i // p1(x)x.r // p2(x) component selector operation

(structure member operation)

Chap. 5 : Data Type

Page 13: 2011-11-14 Chapter 5 Data Types - Sangji Universitycompiler.sangji.ac.kr/lecture/plt/2014/Type_add.pdf · 2011-11-14 1 Chapter 5 Data Types SANGJI University KO Kwangman (kkman@sangji.ac.kr)

2011-11-14

13

[email protected] 37

합집합(union)

o 합집합 종류~ 비구별 합집합(undiscriminated union)

§ normal set union

~ 구별 합집합(discriminated union)

§ 원소를 구별하기 위한 태그(tag)가 첨부

Chap. 5 : Data Type

[email protected] 38

o Example: Union in C~ undiscriminated union: a union itself

~ discriminated union: a union embedded in a structure

union IntOrReal{ int i;

double r;};

enum Disc {IsInt,IsReal};struct IntOrReal{ enum Disc which;

union{ int i;

double r;} val;

};

Chap. 5 : Data Type

[email protected] 39

More Safe Union

o Variant Records in Ada~ the discriminant and

the value should be assigned at once

o Datatype in ML~ enumerators may

include data fields

~ pattern matching using case expressions

type Disc is (IsInt, IsReal);type IntOrReal (which: Disc)isrecord

case which iswhen IsInt => i:integer;when IsReal => r:float;

end case;end record;...x: IntOrReal := (IsReal,2.3);

datatype IntOrReal =IsInt of int |IsReal of real;

...fun printIntOrReal x =

case x ofIsInt(i) => printInt i |IsReal(r) =>printReal r ;

Page 14: 2011-11-14 Chapter 5 Data Types - Sangji Universitycompiler.sangji.ac.kr/lecture/plt/2014/Type_add.pdf · 2011-11-14 1 Chapter 5 Data Types SANGJI University KO Kwangman (kkman@sangji.ac.kr)

2011-11-14

14

[email protected] 40

부분집합(subset)

o 부분집합~ supported by subtypes(부분자료형).

o In Ada~ subtypes and subrange types are different:

~ subtypesubtype IntDigit_Type is integer range 0..9;

~ new type (that is a subrange of an existing type)type Digit_Type is range 0..9;

~ fixing the variant part of a variant record typesubtype IRInt is IntOrReal(IsInt);subtype IRReal is IntOrReal(IsReal);

Chap. 5 : Data Type

[email protected] 41

Arrays and Functions

o Consider a function

f: U → V

If U is an ordinal type, f corresponds to an array:

U: index type, V: component type

f(i) ∈ V which i ∈ U

o Array Size Problem~ the size of an array may be or may not be the part

of an array

Chap. 5 : Data Type

[email protected] 42

Array Example: C/C++

o The size of an array is not part of the array.~ When passing array parameters, the sizes of the arrays

may have to be passed as separate parameters.int array_max (int a[], int size);

~ In a formal parameter, the array notation = pointer.

o Difference between C and C++.~ 교재가 틀렸다.

const int Size = 5;int x[Size]; /* illegal C, ok in C++ */int x[Size*Size]; /* illegal C, ok in C++ */

Chap. 5 : Data Type

Page 15: 2011-11-14 Chapter 5 Data Types - Sangji Universitycompiler.sangji.ac.kr/lecture/plt/2014/Type_add.pdf · 2011-11-14 1 Chapter 5 Data Types SANGJI University KO Kwangman (kkman@sangji.ac.kr)

2011-11-14

15

[email protected] 43

Array Example: Java, Ada

o In Java,~ the size of an array is

the part of the array

~ array can be dynamically allocated

o Unconstrained Array in Ada~ dynamically sized

array

~ 배열 선언시 크기 결정

// a part of Figure 6.3...int [] x = new int[u] ;

// Dynamic array allocationfor (int i = 0; i < x.length;

i++)x[i] = i;

...

type IntToInt isarray (INTEGER range <>)

of INTEGER;...declare

x: IntToInt(1..size);begin

for i in x'range loopx(i) := i;

[email protected]

Multidimensional Array

o Supporting Multidimensional Array~ Multidimensional array may be simulated by

arrays of arrays (C, C++, Java)

o 기억 장소 할당(memory allocation)~ Row-Major : natural way for arrays of arrays

~ Column-Major : FORTRAN

~ 특정 원소 접근 공식 ?

1 2 3

4 5 6

Row-Major: 1 3 5

2 4 6

Column-Major:

Chap. 5 : Data Type

[email protected]

Passing Multidimensional Array

o 배열을 매개변수로 전달~ 배열의 크기가 배열의 일부로 간주

§ there is no problem of array parameters.

~ 배열의 크기가 배열의 일부로 간주되지 않는 경우

§ 매개변수 전달시 배열의 크기를 전달

o passing 2-dimensional array in C/C++.~ When the both dimensions are known

~ When the 1st dimension should be passed

~ When the both dimensions should be passed

Chap. 5 : Data Type

Page 16: 2011-11-14 Chapter 5 Data Types - Sangji Universitycompiler.sangji.ac.kr/lecture/plt/2014/Type_add.pdf · 2011-11-14 1 Chapter 5 Data Types SANGJI University KO Kwangman (kkman@sangji.ac.kr)

2011-11-14

16

[email protected]

Passing no Dimensions#include <iostream>using namespace std;const int R = 3, C = 3;int sum(int a[R][C]){

int sum = 0;for (int i = 0; i < R; ++i)

for (int j = 0; j < C; ++j)sum += a[i][j];

return sum;}main(){

int a[R][C] = { 1, 2, 3, 4, 5, 6, 7, 8, 9 };cout << "1+2+..+9 = " << sum(a) << endl;

}

Chap. 5 : Data Type

[email protected]

Passing the 1st Dimension#include <iostream>using namespace std;const int R = 3, C = 3;int sum(int a[][C], int row){

int sum = 0;for (int i = 0; i < row; ++i)

for (int j = 0; j < C; ++j)sum += a[i][j];

return sum;}main(){

int a[R][C] = { 1, 2, 3, 4, 5, 6, 7, 8, 9 };cout << "1+2+..+9 = " << sum(a, R) << endl;

}

Chap. 5 : Data Type

[email protected]

Passing the Both Dimensions#include <iostream>using namespace std;int sum(int a[], int row, int col){

int sum = 0;for (int i = 0; i < row; ++i)

for (int j = 0; j < col; ++j)sum += a[i*col+j];

return sum;}const int R = 3, C = 3;main(){

int a[R][C] = { 1, 2, 3, 4, 5, 6, 7, 8, 9 };cout << "1+2+..+9 = " << sum(&(a[0][0]), R, C) << endl;

}

Chap. 5 : Data Type

Page 17: 2011-11-14 Chapter 5 Data Types - Sangji Universitycompiler.sangji.ac.kr/lecture/plt/2014/Type_add.pdf · 2011-11-14 1 Chapter 5 Data Types SANGJI University KO Kwangman (kkman@sangji.ac.kr)

2011-11-14

17

[email protected]

Some Notes on 2-Dimensional Arrayo Equivalences and Differences~ for a constant N

int a[N] ≡ int a[] ≡ int *a~ for constants M and N

int a[M][N] ≡ int a[][N] ≡ int (*a)[N]~ beware that

int a[][N] ≠ int **a

o Declarations of C/C++~ declarations implies the usages

int *a[N];int (*a)[N];

Chap. 5 : Data Type

[email protected]

Pointer(Reference) Types

o Pointer(Reference) Type~ 집합 연산에 대응되지 않는 타입 구성자

~ 지정된 자료형을 지칭(참조)하는 모든 주소들의 집합

~ 자동 쓰레기 수집에 허용되는 언어에서 포인턴 묵시적

§ Java, ML, Scheme

o 참조 vs. 포인터~ 참조 : 시스템 제어하에 있는 객체의 주소

§ 값으로 사용 및 연산이 가해질 수 없음.

~ 포인터

§ 값으로 사용 및 연산이 가해질 수 있음.

double r = 2.3, &s = r;

Chap. 5 : Data Type

[email protected]

o In C and C++, arrays are constant pointers

int a[] = {1,2,3,4,5};

int* p = a;printf(“%d \n”, *p);printf(“%d \n”, *(p+2) );printf(“%d \n”, *(a+2) );printf(“%d \n”, 2[a]);

a[2] ≡ *(a + 2) ≡ 2[a] // Wow!

Chap. 5 : Data Type

Page 18: 2011-11-14 Chapter 5 Data Types - Sangji Universitycompiler.sangji.ac.kr/lecture/plt/2014/Type_add.pdf · 2011-11-14 1 Chapter 5 Data Types SANGJI University KO Kwangman (kkman@sangji.ac.kr)

2011-11-14

18

[email protected]

Recursive Types

o 순환 타입(recursive types)~ a type that uses itself in its declaration

~ pointers are useful for recursive types

o The Size Problem of Recursive Types~ require that the maximum size of a data type

should be determined at translation time.

Chap. 5 : Data Type

[email protected]

struct CharList{ char data;

struct CharList next;}; /* illegal! */union CharList{ enum { nothing } empty;

struct{ char data;union CharList next;

} charListNode;}; /* still, illegal! */

struct CharListNode{ char data;

struct CharListNode* next;};

typedef struct CharListNode*CharList;

/* Now, legal */

[email protected] 54

Data Types and the Environment

Fully Dynamic

Environment

Recursive TypesGeneral Function Types

Functional Languages

Traditional Environment(stack & heap)

Recursive types and function types are implemented by

pointers

Algol-style Languages

Page 19: 2011-11-14 Chapter 5 Data Types - Sangji Universitycompiler.sangji.ac.kr/lecture/plt/2014/Type_add.pdf · 2011-11-14 1 Chapter 5 Data Types SANGJI University KO Kwangman (kkman@sangji.ac.kr)

2011-11-14

19

[email protected]

The Type Structure of C

Chap. 5 : Data Type

[email protected]

The Type Structure of Java

Chap. 5 : Data Type

[email protected]

Simplified Type Structure of Ada

Chap. 5 : Data Type

Page 20: 2011-11-14 Chapter 5 Data Types - Sangji Universitycompiler.sangji.ac.kr/lecture/plt/2014/Type_add.pdf · 2011-11-14 1 Chapter 5 Data Types SANGJI University KO Kwangman (kkman@sangji.ac.kr)

2011-11-14

20

[email protected]

타입 동등성(Type Equivalence)

o 타입 동등성이란 ?~ 두개의 타입이 어느때 같은(=일치=동등)한가 !

~ 종류

§ 구조적 동치(structural equivalence)

§ 이름 동치(name equivalence)

§ 선언 동치(declaration equivalence)

o 구조적 동치~ 두개의 타입이 동일한 구조(same structure)

~ 동일한 구조

§ the same type constructor and the same component types.

~ 교재 PP.258

Chap. 5 : Data Type

[email protected]

o 이름 동치~ 두 개의 타입은 공일한 이름을 가질 때에만 동등

o Declaration Equivalence~ Two types are equivalent if they are derived from

the same name.

Chap. 5 : Data Type

[email protected]

Complicating Factors

o Array Size~ 배열의 크기를 배열의 한 부분으로 간주 ?

o Field Names of Record Types~ The following RecA and RecB should be structurally

equivalent (char ⅹ int) but not in practice because of the field names.

struct RecA{ char x;

int y;};

struct RecB{ char a;

int b;};

Chap. 5 : Data Type

Page 21: 2011-11-14 Chapter 5 Data Types - Sangji Universitycompiler.sangji.ac.kr/lecture/plt/2014/Type_add.pdf · 2011-11-14 1 Chapter 5 Data Types SANGJI University KO Kwangman (kkman@sangji.ac.kr)

2011-11-14

21

[email protected]

Language Example: Adao Ada~ pure name equivalence

§ the variables a and b ina, b: array (1..10) of integer;

are not type equivalent because the above declaration is considered as a shorthand fora: array (1..10) of integer;b: array (1..10) of integer;

~ the new types and the subtypes are different each other

§ new typetype Age is new integer;

§ subtype: compatible to the original typesubtype Age is integer;

Chap. 5 : Data Type

[email protected]

Language Examples: Others

o Pascal~ every type constructors introduce a new type

~ new type names for existing type names are equivalent

o Java~ no ‘typedef’ constructs

~ class and interface declarations introduce a new type name

~ inheritance hierarchy (subtype)

~ structural equivalence for arrays

Chap. 5 : Data Type

[email protected]

타입 검사(Type Checking)o 타입 검사 종류(categories)~ Dynamic Type Checking

§ 타입 정보를 실행시간에 유지하고 검사

~ Static Type Checking

§ 느슨한(weakly) 자료형 검사 언어

§ Strongly-Typed Languages

o Unspecified whether dynamic or static typing is to be used

Chap. 5 : Data Type

Page 22: 2011-11-14 Chapter 5 Data Types - Sangji Universitycompiler.sangji.ac.kr/lecture/plt/2014/Type_add.pdf · 2011-11-14 1 Chapter 5 Data Types SANGJI University KO Kwangman (kkman@sangji.ac.kr)

2011-11-14

22

[email protected]

Type Checking Examples

o C/C++~ static type checking

~ no a strongly typed language: type conversion

o Scheme~ dynamic type checking but rigorous~ predefined type test functions: number?, symbol?, …

o Ada~ a strongly typed language

~ array bound checks are performed during run-time: exceptions

Chap. 5 : Data Type

[email protected]

Type Checking and Type Inference

o 타입 추론(inference)~ the process to infer the type of an expression

from the types of its subexpressions

o Type Checking and Type Inference~ Type checking rules and type inference rules are

intermingled

e1 + e2

~ Type checking rules are type inference rules are closely related with the type equivalence algorithm

~ Explicit declarations are helpful for type checking but not mandatory

Chap. 5 : Data Type

[email protected]

Type Compatibility

o Relaxing the type correctness

For assignment compatibility, information preservation is an important requirement.

o Language Examples~ Ada: subrange types of a base type are

compatible

~ C, Java: numeric types are compatible

Type Equivalence Type Compatibilitye1 + e2

e1 and e2 should be of equivalent types.

e1 and e2 should be of compatible types.

Chap. 5 : Data Type

Page 23: 2011-11-14 Chapter 5 Data Types - Sangji Universitycompiler.sangji.ac.kr/lecture/plt/2014/Type_add.pdf · 2011-11-14 1 Chapter 5 Data Types SANGJI University KO Kwangman (kkman@sangji.ac.kr)

2011-11-14

23

[email protected]

Implicit Types

o Implicit Types~ The types of entities are not explicitly declared

but inferred implicitly

o Examples~ C: the types of variables and functions are

implicitly intx; /* implicitly int */f(int x) { return x + 1; } /* returns int */

~ Pascal: constants are implicitly typed from the literalsconst PI = 3.14159; (* implicitly real *)

Chap. 5 : Data Type

[email protected] 68

Type Conversion

o Classifying Type Conversions~ According to the

notation

§ Implicit Conversions (coercion)

§ Explicit Conversions (casting)

~ According to the sizes of the types involved

§ Widening Conversions

§ Narrowing Conversions: may involve a loss of data

o C Exampleint x = 3;x = 2.3 + x / 2;

int

double

promotion(widening)

int

doubleassignmentconversion(narrowing)

[email protected]

Notes on Type Conversions

o Advantages of Explicit Conversions~ Type conversions are documented precisely.

~ Make it easier for the translator to resolve overloading.double max(int, double); // max #1double max(double, int); // max #2...max(2, 3); // calls what?max(2, (double)3); // calls max #1

o Structure Casting~ The sizes of the structure types should be

identical.

~ The translation merely reinterprets the memory

Chap. 5 : Data Type

Page 24: 2011-11-14 Chapter 5 Data Types - Sangji Universitycompiler.sangji.ac.kr/lecture/plt/2014/Type_add.pdf · 2011-11-14 1 Chapter 5 Data Types SANGJI University KO Kwangman (kkman@sangji.ac.kr)

2011-11-14

24

[email protected]

포괄(generic) Pointers

o Generic pointers may point anything.~ anonymous pointers (void* in C)

~ C allows the both conversion to be implicit.

~ In C++, the conversion 1 is implicit

but the conversion 2 should be explicit.

char *int *...

conversion 1

conversion 2void *

Chap. 5 : Data Type

[email protected]

Library Functions for Conversions

o Ada Example~ attribute functions of the character type

character'pos('a') -- returns 97character'val(97) -- returns 'a'

o Java Example~ conversion functions of the Integer class

String s = Integer.toString(12345);int i = Integer.parseInt("54321");

Chap. 5 : Data Type


Top Related