[!tip] Programming Language
A notation system that represents computations in a form that can be performed by computers and read by humans.0.1 Language Spectrum
![[Language Spectrum.canvas|Language Spectrum]]
![[Screenshot 2023-10-08 at 12.41.05 AM.png]]
![[Screenshot 2023-10-08 at 12.54.16 AM.png]]
![[Screenshot 2023-10-08 at 1.03.57 AM.png]]
![[Screenshot 2023-10-09 at 11.35.49 PM.png|500]]
[!Definition]
- Syntax: Syntax refers to the set of rules that dictate how valid sentences or statements are structured in a programming language
- Tokens: Tokens are the smallest units of a programming language's syntax.
- Terminal: ~Symbols~ that appear in the source code and have no further productions or rules associated with them.
- . Nonterminal: ~Symbols~ in a formal grammar that can be replaced by a sequence of terminals and/or other nonterminals through production rules.
- CFG (Context-Free Grammar): a formal notation used to describe the syntax of a programming language or any formal language. It consists of a set of production rules that define how nonterminals can be replaced by other nonterminals and terminals.
- Rule: A rule in CFG specifies how a nonterminal can be replaced by a sequence of symbols (terminals and/or other nonterminals). A rule consists of a left-hand side (the nonterminal to be replaced) and a right-hand side (the sequence of symbols that replace it).
Nonterminal + Terminal + MetaSymbols
[!meta Symbols]
1. : := : (define)
2. | : (or)
3. <> : (nonterminal)
<if문> ::= if <논리식> then <문장> | if<논리식> then <문장> else <문장>
<식별자> ::= <letter> | <식별자><digit> | <식별자><letter>
<letter> ::= A|B|C|D|...|Z||a|b|...|y||z|
<digit> ::= 0|1|2|3|4|5|6|7|8|9
[!Meta Symbols][] :(optional)
{} :(zero or more)
() :(or)
'' : (use meta symbols)
<if문> ::= if <논리식> then <문장> [else <문장>]
<identifier> ::= <letter>{<letter>|<digit>}
<unsigned integer> ::= <digit>{<digit>}
<expression> ::= <expression>(+|-|*|/|%)<expression>
[!Units]
1. Square = Nonterminal
2. Circle = Terminal
3. Arrow = Rule
![[Screenshot 2023-11-17 at 9.17.25 PM.png]]
[ ]
![[Screenshot 2023-11-17 at 9.17.40 PM.png]]
( | | | )
![[Screenshot 2023-11-17 at 9.17.46 PM.png]]
{ }
![[Screenshot 2023-11-17 at 9.18.33 PM.png]]
{ | }
자연어로 시작하긴했지만 형식 의미론이 개발됨
비단말기호마다의 타입 속성이 있다고 가정하여 규칙 설명
<선언> ::= <T><id><L>; <T>:: = int|char <L>::= <id><L> | Ɛ
id.t = T.t
T.t = 정수 | 문자
L.t =T .t
기계의 상태의 변화를 표현
<수행할 명령어, 메모리상태>
< z=x; x=y ; y=z , [x->5,y->7,z->0] > => < x=y; y=z;, [x->5,y->7,z->5] > => < y=z; [x->7,y->7,z->5] > => < , [x->7,y->5,z->5] >x 와 y 값 교환
표기적 의미론
각 구문요소를 수학적 표기에 대응(의미함수)
<Binary> ::= 0 | 1 | <Binary>0 | <Binary>1
Bin[[0]]=0
Bin[[1]]=1
Bin[[B0]]=2*Bin[[B]]
Bin[[B1]]= 2*Bin[[B]] + 1
의미함수 Bin
3.2.4 Axiomatic Semantics
공리적 의미론
{P}S{Q}4. Syntax Analysis
Token 을 찾아내자
유도가 가능한 프로그램 = 구문 규칙이 에러가없음
<exp>::= <exp> |<exp> (+|-|*|/) <exp> | <digit>
<exp>
<exp>+<exp>
<exp>+<exp>*<exp>
<digit>+<digit>*<digit>
1+5*2
유도 ⇒ 문법 오류 x
4.2.1 Parse Tree
![[Screenshot 2023-11-18 at 3.46.43 AM.png]]
![[Screenshot 2023-11-18 at 3.47.34 AM.png]]
1+5*은 문법오류다
![[Screenshot 2023-11-18 at 3.49.05 AM.png]]
구문적으론 부합하지만 의미론적으로 다름
<exp> ::= <exp>( + | - )<exp> | <term>
<term> ::= <term>( * | / )<term> | <factor>
<factor> :: = (<exp>) | <digit>
![[Screenshot 2023-11-18 at 3.54.08 AM.png]]
<exp> ::= <exp>( + | - )<term> | <term>
<term> ::=<term>( * | / )<factor> | <factor>
<factor> ::= (<exp>) | <digit>
왼쪽부터 계산 좌결합 연산자
5 . Variable
Type + Identifier + Address + Value
![[Screenshot 2023-11-18 at 4.04.33 AM.png]]
배런의 표기법
변수명 → 타입 → 주소 → 값 순
바인딩 = 언어 구성요소의 속성이 결정됨
![[Screenshot 2023-11-18 at 4.07.36 AM.png]]
로드시점까지는 정적 바인딩
프로그램 수행시점은 동적 바인딩
[!tip]
대부분 정적바인딩으로하나
파이썬같은 경우 동적바인딩됨 k=123; k='abc' → 프로그램 수행전에 타입 바인딩 불가능
주소 바인딩 = 할당(allocation)
[!tip]
변수의 수명은 변수가 메모리를 할당 받고있는기간
자동할당 : 명시적선언 + 묵시적선언 ⇒ Stack or Data
수동할당 : 지정한 크기의 동적할당 ⇒ [[Memory Structure|Heap]]
정적바인딩 ⇒ 로드시점에 전역/정적변수 저장하여 프로그램이 끝날때까지 유지
동적바인딩 ⇒ 실행 시점에 동적세그먼트(스택,힙) 의 주소를 바인딩
x=3;
수명의시작
1. 동적바인딩
2. 정적바인딩
scope = 실제로 사용할 수 있는 범위 수명 != 영역
변수의 참조 위치를 결정하는 법 (언어마다 다름)
블록들의 정적 내포 관계이용
![[Screenshot 2023-11-19 at 1.55.41 AM.png]]
Static Ancestor, Static Parent(가장가까운 정적조상)
![[Screenshot 2023-11-19 at 2.14.48 AM.png]]
#### Dynamic Scope Rule
서브프로그램의 호출 관계로 내포관계 정함
![[Screenshot 2023-11-19 at 2.15.24 AM.png]]
Sub2를 호출한 Main의 A를 참조하게됨
Name Space
int i=0;
int main(){
int i=5; // 영역 구멍 생성
::i++; //1 영역연산자 -> 전역변수
i++; //6 지역변수
}
데이터 집합 + 연산 집합
![[Screenshot 2023-11-19 at 2.26.40 AM.png]]
- / %
char
![[Screenshot 2023-11-19 at 2.28.41 AM.png]]
enum color {red, green, blue};
color c = red;
cout << blue << endl;//2
cout << c << endl ; //0
#include <map>
map<string, int> walk {{"monday", 1}, {"tuesday", 2},{"wednesday", 3}};
cout << walk["monday"] << endl;
struct person {
char name[20];
int birth;
double height;
double weight;
};
union uni{
int i;
char a;
double f;
}
![[Screenshot 2023-11-19 at 3.01.58 AM.png]]
int *ptr;
int &a= b;
![[Screenshot 2023-11-19 at 3.01.52 AM.png]]
연산자(함수) + 피연산자
f(피연산자) = 값
1. Expression : 하나의 값을 나타냄`
int f(){
return 100;
}
-5.3 // No Operator
i+3 // 두개의 Operand + Operator
"good" + "morning"
f()//No Operand - 100
![[Pasted image 20231120023256.png]]
1. 묵시적 타입변환
1. 데이터 집합이 더 커지는 확대변환만 가능
7.5*4 // 7.5 * 4.0 = 확대변환 30.0
(int)7.5*4 // 7 * 4 = 28
7.5*(double)4 // 7.5*4.0 = 30.0
![[Screenshot 2023-11-20 at 2.31.48 AM.png]]
![[Screenshot 2023-11-20 at 2.32.09 AM.png]]
2>1
![[Screenshot 2023-11-20 at 2.43.59 AM.png]]
true && false
![[Screenshot 2023-11-20 at 2.47.24 AM.png]]
![[Screenshot 2023-11-20 at 2.56.59 AM.png]]
처리를 나타냄
문장은 ; 로 끝냄
1. 선언문 : 변수명 타입 바인딩
2. 실행문 : 데이터를 처리함
1. 대입문
2. 제어문
1. 조건문
2. 반복문y = add(3,4);6.2.1 Declaration
int y; int add(int,int); //프로토콜
A = B = C =5;
if y>3:
y=10
print(y)
else:
y=0
print(y)
for (i=0;i<100;i++){
y+=i;
}
입력 + 출력을 갖춘 프로그램조각
- 하나의 입구 (Entry Point) → f( Entry )
- 1개이상의 출구 (Exit Point) → {Return}
- return이없으면 블록의 끝이 출구
SORTS
1. Function
1. 인수 o 반환 o
2. Procedure (void 함수)
1. 반환 x
3. SubRoutine
1. 인수 x 반환 x
//Declaration
int hi (int); // Protocol (Prototype)
//Definition
int hi (int i){ // header
//body
}
hi(); // call
Declartion = Protocol = int hi (Profile);
Definition = Body + Header
거의 구분 x
Formal Parameter :
Actual Parameter :
Positional Correspondence
Keyword Correspondence
int sum(int ...ns){ // Variadic Arguments
int s =0;
for (int n :ns){
}
}
인수 전달 모델들
물리적으로 실인수값을 복사하여 전달
Call-By-Reference
실인수를 참조할 참조 경로를 전달
7.3.3 Implementation Model
int elem(Matrix m,int row, int col);
int elem(const Matrix* mp,int row,int col); //메모리아낌
void sub(int &x,int &y){ // 흉내내는 것일뿐 실제로 지원안함
x=2;
y=3;
}
sub(a,b); //a,b에 대입
int Hypotenuse(int &a, int &b){
a*=a
b*=b
return a+b; //a^2 + b^2
}
a=2
sqSum(a,a); // 32 aliasing problem
글자 그대로 치환
procedure dobule(x);
interger x;
begin
x := x * 2
end;
i :=2;
double(i);
i:=2;
i:=i*2;
void swap(int a, int b){
int temp = a;
a = b;
b = temp;
}
int main(){
int list[3]={1,2,3};
int i =0;
swap(i,list[i]);
return;
}
이 예제에서 swap 이 참조 전달(실인수 주소값이 이미 정해짐)인경우
스왑이 일어나나 이름 전달일경우 이상한 결과가 나온다.
범용 서브프로그램 : 여러타입을 다룰 수있는(polymorphism) 서브프로그램
C++ : Template , JAVA : Generic
Polymorphic Data Structure
#define MAX(a,b) (a>b?a:b)
int MAX(void* a, void* b){
return *(float*)a > *(int*)b ? *(float*)a : *(int*)b;
}
int main(){
float a = 13.0;
int a = 14;
MAX(a,b);
return 0;
}
c언어 다형 서브프로그램
less<int>();C++ 다형서브프로그램 : 템플릿
int printf(const char *s,...);
int main(){
printf("hello");
return 0;
}
<stdio.h>없이도 아무문제없이 컴파일가능